1/* 2 * apply.c 3 * 4 * Copyright (C) Linus Torvalds, 2005 5 * 6 * This applies patches on top of some (arbitrary) version of the SCM. 7 * 8 */ 9#include"cache.h" 10#include"cache-tree.h" 11#include"quote.h" 12#include"blob.h" 13#include"delta.h" 14#include"builtin.h" 15#include"string-list.h" 16#include"dir.h" 17 18/* 19 * --check turns on checking that the working tree matches the 20 * files that are being modified, but doesn't apply the patch 21 * --stat does just a diffstat, and doesn't actually apply 22 * --numstat does numeric diffstat, and doesn't actually apply 23 * --index-info shows the old and new index info for paths if available. 24 * --index updates the cache as well. 25 * --cached updates only the cache without ever touching the working tree. 26 */ 27static const char*prefix; 28static int prefix_length = -1; 29static int newfd = -1; 30 31static int unidiff_zero; 32static int p_value =1; 33static int p_value_known; 34static int check_index; 35static int update_index; 36static int cached; 37static int diffstat; 38static int numstat; 39static int summary; 40static int check; 41static int apply =1; 42static int apply_in_reverse; 43static int apply_with_reject; 44static int apply_verbosely; 45static int no_add; 46static const char*fake_ancestor; 47static int line_termination ='\n'; 48static unsigned long p_context = ULONG_MAX; 49static const char apply_usage[] = 50"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>..."; 51 52static enum ws_error_action { 53 nowarn_ws_error, 54 warn_on_ws_error, 55 die_on_ws_error, 56 correct_ws_error, 57} ws_error_action = warn_on_ws_error; 58static int whitespace_error; 59static int squelch_whitespace_errors =5; 60static int applied_after_fixing_ws; 61static const char*patch_input_file; 62static const char*root; 63static int root_len; 64 65static voidparse_whitespace_option(const char*option) 66{ 67if(!option) { 68 ws_error_action = warn_on_ws_error; 69return; 70} 71if(!strcmp(option,"warn")) { 72 ws_error_action = warn_on_ws_error; 73return; 74} 75if(!strcmp(option,"nowarn")) { 76 ws_error_action = nowarn_ws_error; 77return; 78} 79if(!strcmp(option,"error")) { 80 ws_error_action = die_on_ws_error; 81return; 82} 83if(!strcmp(option,"error-all")) { 84 ws_error_action = die_on_ws_error; 85 squelch_whitespace_errors =0; 86return; 87} 88if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 89 ws_error_action = correct_ws_error; 90return; 91} 92die("unrecognized whitespace option '%s'", option); 93} 94 95static voidset_default_whitespace_mode(const char*whitespace_option) 96{ 97if(!whitespace_option && !apply_default_whitespace) 98 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 99} 100 101/* 102 * For "diff-stat" like behaviour, we keep track of the biggest change 103 * we've seen, and the longest filename. That allows us to do simple 104 * scaling. 105 */ 106static int max_change, max_len; 107 108/* 109 * Various "current state", notably line numbers and what 110 * file (and how) we're patching right now.. The "is_xxxx" 111 * things are flags, where -1 means "don't know yet". 112 */ 113static int linenr =1; 114 115/* 116 * This represents one "hunk" from a patch, starting with 117 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 118 * patch text is pointed at by patch, and its byte length 119 * is stored in size. leading and trailing are the number 120 * of context lines. 121 */ 122struct fragment { 123unsigned long leading, trailing; 124unsigned long oldpos, oldlines; 125unsigned long newpos, newlines; 126const char*patch; 127int size; 128int rejected; 129struct fragment *next; 130}; 131 132/* 133 * When dealing with a binary patch, we reuse "leading" field 134 * to store the type of the binary hunk, either deflated "delta" 135 * or deflated "literal". 136 */ 137#define binary_patch_method leading 138#define BINARY_DELTA_DEFLATED 1 139#define BINARY_LITERAL_DEFLATED 2 140 141/* 142 * This represents a "patch" to a file, both metainfo changes 143 * such as creation/deletion, filemode and content changes represented 144 * as a series of fragments. 145 */ 146struct patch { 147char*new_name, *old_name, *def_name; 148unsigned int old_mode, new_mode; 149int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 150int rejected; 151unsigned ws_rule; 152unsigned long deflate_origlen; 153int lines_added, lines_deleted; 154int score; 155unsigned int is_toplevel_relative:1; 156unsigned int inaccurate_eof:1; 157unsigned int is_binary:1; 158unsigned int is_copy:1; 159unsigned int is_rename:1; 160unsigned int recount:1; 161struct fragment *fragments; 162char*result; 163size_t resultsize; 164char old_sha1_prefix[41]; 165char new_sha1_prefix[41]; 166struct patch *next; 167}; 168 169/* 170 * A line in a file, len-bytes long (includes the terminating LF, 171 * except for an incomplete line at the end if the file ends with 172 * one), and its contents hashes to 'hash'. 173 */ 174struct line { 175size_t len; 176unsigned hash :24; 177unsigned flag :8; 178#define LINE_COMMON 1 179}; 180 181/* 182 * This represents a "file", which is an array of "lines". 183 */ 184struct image { 185char*buf; 186size_t len; 187size_t nr; 188size_t alloc; 189struct line *line_allocated; 190struct line *line; 191}; 192 193/* 194 * Records filenames that have been touched, in order to handle 195 * the case where more than one patches touch the same file. 196 */ 197 198static struct string_list fn_table; 199 200static uint32_thash_line(const char*cp,size_t len) 201{ 202size_t i; 203uint32_t h; 204for(i =0, h =0; i < len; i++) { 205if(!isspace(cp[i])) { 206 h = h *3+ (cp[i] &0xff); 207} 208} 209return h; 210} 211 212static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 213{ 214ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 215 img->line_allocated[img->nr].len = len; 216 img->line_allocated[img->nr].hash =hash_line(bol, len); 217 img->line_allocated[img->nr].flag = flag; 218 img->nr++; 219} 220 221static voidprepare_image(struct image *image,char*buf,size_t len, 222int prepare_linetable) 223{ 224const char*cp, *ep; 225 226memset(image,0,sizeof(*image)); 227 image->buf = buf; 228 image->len = len; 229 230if(!prepare_linetable) 231return; 232 233 ep = image->buf + image->len; 234 cp = image->buf; 235while(cp < ep) { 236const char*next; 237for(next = cp; next < ep && *next !='\n'; next++) 238; 239if(next < ep) 240 next++; 241add_line_info(image, cp, next - cp,0); 242 cp = next; 243} 244 image->line = image->line_allocated; 245} 246 247static voidclear_image(struct image *image) 248{ 249free(image->buf); 250 image->buf = NULL; 251 image->len =0; 252} 253 254static voidsay_patch_name(FILE*output,const char*pre, 255struct patch *patch,const char*post) 256{ 257fputs(pre, output); 258if(patch->old_name && patch->new_name && 259strcmp(patch->old_name, patch->new_name)) { 260quote_c_style(patch->old_name, NULL, output,0); 261fputs(" => ", output); 262quote_c_style(patch->new_name, NULL, output,0); 263}else{ 264const char*n = patch->new_name; 265if(!n) 266 n = patch->old_name; 267quote_c_style(n, NULL, output,0); 268} 269fputs(post, output); 270} 271 272#define CHUNKSIZE (8192) 273#define SLOP (16) 274 275static voidread_patch_file(struct strbuf *sb,int fd) 276{ 277if(strbuf_read(sb, fd,0) <0) 278die("git apply: read returned%s",strerror(errno)); 279 280/* 281 * Make sure that we have some slop in the buffer 282 * so that we can do speculative "memcmp" etc, and 283 * see to it that it is NUL-filled. 284 */ 285strbuf_grow(sb, SLOP); 286memset(sb->buf + sb->len,0, SLOP); 287} 288 289static unsigned longlinelen(const char*buffer,unsigned long size) 290{ 291unsigned long len =0; 292while(size--) { 293 len++; 294if(*buffer++ =='\n') 295break; 296} 297return len; 298} 299 300static intis_dev_null(const char*str) 301{ 302return!memcmp("/dev/null", str,9) &&isspace(str[9]); 303} 304 305#define TERM_SPACE 1 306#define TERM_TAB 2 307 308static intname_terminate(const char*name,int namelen,int c,int terminate) 309{ 310if(c ==' '&& !(terminate & TERM_SPACE)) 311return0; 312if(c =='\t'&& !(terminate & TERM_TAB)) 313return0; 314 315return1; 316} 317 318static char*find_name(const char*line,char*def,int p_value,int terminate) 319{ 320int len; 321const char*start = line; 322 323if(*line =='"') { 324struct strbuf name; 325 326/* 327 * Proposed "new-style" GNU patch/diff format; see 328 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2 329 */ 330strbuf_init(&name,0); 331if(!unquote_c_style(&name, line, NULL)) { 332char*cp; 333 334for(cp = name.buf; p_value; p_value--) { 335 cp =strchr(cp,'/'); 336if(!cp) 337break; 338 cp++; 339} 340if(cp) { 341/* name can later be freed, so we need 342 * to memmove, not just return cp 343 */ 344strbuf_remove(&name,0, cp - name.buf); 345free(def); 346if(root) 347strbuf_insert(&name,0, root, root_len); 348returnstrbuf_detach(&name, NULL); 349} 350} 351strbuf_release(&name); 352} 353 354for(;;) { 355char c = *line; 356 357if(isspace(c)) { 358if(c =='\n') 359break; 360if(name_terminate(start, line-start, c, terminate)) 361break; 362} 363 line++; 364if(c =='/'&& !--p_value) 365 start = line; 366} 367if(!start) 368return def; 369 len = line - start; 370if(!len) 371return def; 372 373/* 374 * Generally we prefer the shorter name, especially 375 * if the other one is just a variation of that with 376 * something else tacked on to the end (ie "file.orig" 377 * or "file~"). 378 */ 379if(def) { 380int deflen =strlen(def); 381if(deflen < len && !strncmp(start, def, deflen)) 382return def; 383free(def); 384} 385 386if(root) { 387char*ret =xmalloc(root_len + len +1); 388strcpy(ret, root); 389memcpy(ret + root_len, start, len); 390 ret[root_len + len] ='\0'; 391return ret; 392} 393 394returnxmemdupz(start, len); 395} 396 397static intcount_slashes(const char*cp) 398{ 399int cnt =0; 400char ch; 401 402while((ch = *cp++)) 403if(ch =='/') 404 cnt++; 405return cnt; 406} 407 408/* 409 * Given the string after "--- " or "+++ ", guess the appropriate 410 * p_value for the given patch. 411 */ 412static intguess_p_value(const char*nameline) 413{ 414char*name, *cp; 415int val = -1; 416 417if(is_dev_null(nameline)) 418return-1; 419 name =find_name(nameline, NULL,0, TERM_SPACE | TERM_TAB); 420if(!name) 421return-1; 422 cp =strchr(name,'/'); 423if(!cp) 424 val =0; 425else if(prefix) { 426/* 427 * Does it begin with "a/$our-prefix" and such? Then this is 428 * very likely to apply to our directory. 429 */ 430if(!strncmp(name, prefix, prefix_length)) 431 val =count_slashes(prefix); 432else{ 433 cp++; 434if(!strncmp(cp, prefix, prefix_length)) 435 val =count_slashes(prefix) +1; 436} 437} 438free(name); 439return val; 440} 441 442/* 443 * Get the name etc info from the ---/+++ lines of a traditional patch header 444 * 445 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 446 * files, we can happily check the index for a match, but for creating a 447 * new file we should try to match whatever "patch" does. I have no idea. 448 */ 449static voidparse_traditional_patch(const char*first,const char*second,struct patch *patch) 450{ 451char*name; 452 453 first +=4;/* skip "--- " */ 454 second +=4;/* skip "+++ " */ 455if(!p_value_known) { 456int p, q; 457 p =guess_p_value(first); 458 q =guess_p_value(second); 459if(p <0) p = q; 460if(0<= p && p == q) { 461 p_value = p; 462 p_value_known =1; 463} 464} 465if(is_dev_null(first)) { 466 patch->is_new =1; 467 patch->is_delete =0; 468 name =find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB); 469 patch->new_name = name; 470}else if(is_dev_null(second)) { 471 patch->is_new =0; 472 patch->is_delete =1; 473 name =find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB); 474 patch->old_name = name; 475}else{ 476 name =find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB); 477 name =find_name(second, name, p_value, TERM_SPACE | TERM_TAB); 478 patch->old_name = patch->new_name = name; 479} 480if(!name) 481die("unable to find filename in patch at line%d", linenr); 482} 483 484static intgitdiff_hdrend(const char*line,struct patch *patch) 485{ 486return-1; 487} 488 489/* 490 * We're anal about diff header consistency, to make 491 * sure that we don't end up having strange ambiguous 492 * patches floating around. 493 * 494 * As a result, gitdiff_{old|new}name() will check 495 * their names against any previous information, just 496 * to make sure.. 497 */ 498static char*gitdiff_verify_name(const char*line,int isnull,char*orig_name,const char*oldnew) 499{ 500if(!orig_name && !isnull) 501returnfind_name(line, NULL, p_value, TERM_TAB); 502 503if(orig_name) { 504int len; 505const char*name; 506char*another; 507 name = orig_name; 508 len =strlen(name); 509if(isnull) 510die("git apply: bad git-diff - expected /dev/null, got%son line%d", name, linenr); 511 another =find_name(line, NULL, p_value, TERM_TAB); 512if(!another ||memcmp(another, name, len)) 513die("git apply: bad git-diff - inconsistent%sfilename on line%d", oldnew, linenr); 514free(another); 515return orig_name; 516} 517else{ 518/* expect "/dev/null" */ 519if(memcmp("/dev/null", line,9) || line[9] !='\n') 520die("git apply: bad git-diff - expected /dev/null on line%d", linenr); 521return NULL; 522} 523} 524 525static intgitdiff_oldname(const char*line,struct patch *patch) 526{ 527 patch->old_name =gitdiff_verify_name(line, patch->is_new, patch->old_name,"old"); 528return0; 529} 530 531static intgitdiff_newname(const char*line,struct patch *patch) 532{ 533 patch->new_name =gitdiff_verify_name(line, patch->is_delete, patch->new_name,"new"); 534return0; 535} 536 537static intgitdiff_oldmode(const char*line,struct patch *patch) 538{ 539 patch->old_mode =strtoul(line, NULL,8); 540return0; 541} 542 543static intgitdiff_newmode(const char*line,struct patch *patch) 544{ 545 patch->new_mode =strtoul(line, NULL,8); 546return0; 547} 548 549static intgitdiff_delete(const char*line,struct patch *patch) 550{ 551 patch->is_delete =1; 552 patch->old_name = patch->def_name; 553returngitdiff_oldmode(line, patch); 554} 555 556static intgitdiff_newfile(const char*line,struct patch *patch) 557{ 558 patch->is_new =1; 559 patch->new_name = patch->def_name; 560returngitdiff_newmode(line, patch); 561} 562 563static intgitdiff_copysrc(const char*line,struct patch *patch) 564{ 565 patch->is_copy =1; 566 patch->old_name =find_name(line, NULL,0,0); 567return0; 568} 569 570static intgitdiff_copydst(const char*line,struct patch *patch) 571{ 572 patch->is_copy =1; 573 patch->new_name =find_name(line, NULL,0,0); 574return0; 575} 576 577static intgitdiff_renamesrc(const char*line,struct patch *patch) 578{ 579 patch->is_rename =1; 580 patch->old_name =find_name(line, NULL,0,0); 581return0; 582} 583 584static intgitdiff_renamedst(const char*line,struct patch *patch) 585{ 586 patch->is_rename =1; 587 patch->new_name =find_name(line, NULL,0,0); 588return0; 589} 590 591static intgitdiff_similarity(const char*line,struct patch *patch) 592{ 593if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 594 patch->score =0; 595return0; 596} 597 598static intgitdiff_dissimilarity(const char*line,struct patch *patch) 599{ 600if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 601 patch->score =0; 602return0; 603} 604 605static intgitdiff_index(const char*line,struct patch *patch) 606{ 607/* 608 * index line is N hexadecimal, "..", N hexadecimal, 609 * and optional space with octal mode. 610 */ 611const char*ptr, *eol; 612int len; 613 614 ptr =strchr(line,'.'); 615if(!ptr || ptr[1] !='.'||40< ptr - line) 616return0; 617 len = ptr - line; 618memcpy(patch->old_sha1_prefix, line, len); 619 patch->old_sha1_prefix[len] =0; 620 621 line = ptr +2; 622 ptr =strchr(line,' '); 623 eol =strchr(line,'\n'); 624 625if(!ptr || eol < ptr) 626 ptr = eol; 627 len = ptr - line; 628 629if(40< len) 630return0; 631memcpy(patch->new_sha1_prefix, line, len); 632 patch->new_sha1_prefix[len] =0; 633if(*ptr ==' ') 634 patch->new_mode = patch->old_mode =strtoul(ptr+1, NULL,8); 635return0; 636} 637 638/* 639 * This is normal for a diff that doesn't change anything: we'll fall through 640 * into the next diff. Tell the parser to break out. 641 */ 642static intgitdiff_unrecognized(const char*line,struct patch *patch) 643{ 644return-1; 645} 646 647static const char*stop_at_slash(const char*line,int llen) 648{ 649int i; 650 651for(i =0; i < llen; i++) { 652int ch = line[i]; 653if(ch =='/') 654return line + i; 655} 656return NULL; 657} 658 659/* 660 * This is to extract the same name that appears on "diff --git" 661 * line. We do not find and return anything if it is a rename 662 * patch, and it is OK because we will find the name elsewhere. 663 * We need to reliably find name only when it is mode-change only, 664 * creation or deletion of an empty file. In any of these cases, 665 * both sides are the same name under a/ and b/ respectively. 666 */ 667static char*git_header_name(char*line,int llen) 668{ 669const char*name; 670const char*second = NULL; 671size_t len; 672 673 line +=strlen("diff --git "); 674 llen -=strlen("diff --git "); 675 676if(*line =='"') { 677const char*cp; 678struct strbuf first; 679struct strbuf sp; 680 681strbuf_init(&first,0); 682strbuf_init(&sp,0); 683 684if(unquote_c_style(&first, line, &second)) 685goto free_and_fail1; 686 687/* advance to the first slash */ 688 cp =stop_at_slash(first.buf, first.len); 689/* we do not accept absolute paths */ 690if(!cp || cp == first.buf) 691goto free_and_fail1; 692strbuf_remove(&first,0, cp +1- first.buf); 693 694/* 695 * second points at one past closing dq of name. 696 * find the second name. 697 */ 698while((second < line + llen) &&isspace(*second)) 699 second++; 700 701if(line + llen <= second) 702goto free_and_fail1; 703if(*second =='"') { 704if(unquote_c_style(&sp, second, NULL)) 705goto free_and_fail1; 706 cp =stop_at_slash(sp.buf, sp.len); 707if(!cp || cp == sp.buf) 708goto free_and_fail1; 709/* They must match, otherwise ignore */ 710if(strcmp(cp +1, first.buf)) 711goto free_and_fail1; 712strbuf_release(&sp); 713returnstrbuf_detach(&first, NULL); 714} 715 716/* unquoted second */ 717 cp =stop_at_slash(second, line + llen - second); 718if(!cp || cp == second) 719goto free_and_fail1; 720 cp++; 721if(line + llen - cp != first.len +1|| 722memcmp(first.buf, cp, first.len)) 723goto free_and_fail1; 724returnstrbuf_detach(&first, NULL); 725 726 free_and_fail1: 727strbuf_release(&first); 728strbuf_release(&sp); 729return NULL; 730} 731 732/* unquoted first name */ 733 name =stop_at_slash(line, llen); 734if(!name || name == line) 735return NULL; 736 name++; 737 738/* 739 * since the first name is unquoted, a dq if exists must be 740 * the beginning of the second name. 741 */ 742for(second = name; second < line + llen; second++) { 743if(*second =='"') { 744struct strbuf sp; 745const char*np; 746 747strbuf_init(&sp,0); 748if(unquote_c_style(&sp, second, NULL)) 749goto free_and_fail2; 750 751 np =stop_at_slash(sp.buf, sp.len); 752if(!np || np == sp.buf) 753goto free_and_fail2; 754 np++; 755 756 len = sp.buf + sp.len - np; 757if(len < second - name && 758!strncmp(np, name, len) && 759isspace(name[len])) { 760/* Good */ 761strbuf_remove(&sp,0, np - sp.buf); 762returnstrbuf_detach(&sp, NULL); 763} 764 765 free_and_fail2: 766strbuf_release(&sp); 767return NULL; 768} 769} 770 771/* 772 * Accept a name only if it shows up twice, exactly the same 773 * form. 774 */ 775for(len =0; ; len++) { 776switch(name[len]) { 777default: 778continue; 779case'\n': 780return NULL; 781case'\t':case' ': 782 second = name+len; 783for(;;) { 784char c = *second++; 785if(c =='\n') 786return NULL; 787if(c =='/') 788break; 789} 790if(second[len] =='\n'&& !memcmp(name, second, len)) { 791returnxmemdupz(name, len); 792} 793} 794} 795} 796 797/* Verify that we recognize the lines following a git header */ 798static intparse_git_header(char*line,int len,unsigned int size,struct patch *patch) 799{ 800unsigned long offset; 801 802/* A git diff has explicit new/delete information, so we don't guess */ 803 patch->is_new =0; 804 patch->is_delete =0; 805 806/* 807 * Some things may not have the old name in the 808 * rest of the headers anywhere (pure mode changes, 809 * or removing or adding empty files), so we get 810 * the default name from the header. 811 */ 812 patch->def_name =git_header_name(line, len); 813 814 line += len; 815 size -= len; 816 linenr++; 817for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) { 818static const struct opentry { 819const char*str; 820int(*fn)(const char*,struct patch *); 821} optable[] = { 822{"@@ -", gitdiff_hdrend }, 823{"--- ", gitdiff_oldname }, 824{"+++ ", gitdiff_newname }, 825{"old mode ", gitdiff_oldmode }, 826{"new mode ", gitdiff_newmode }, 827{"deleted file mode ", gitdiff_delete }, 828{"new file mode ", gitdiff_newfile }, 829{"copy from ", gitdiff_copysrc }, 830{"copy to ", gitdiff_copydst }, 831{"rename old ", gitdiff_renamesrc }, 832{"rename new ", gitdiff_renamedst }, 833{"rename from ", gitdiff_renamesrc }, 834{"rename to ", gitdiff_renamedst }, 835{"similarity index ", gitdiff_similarity }, 836{"dissimilarity index ", gitdiff_dissimilarity }, 837{"index ", gitdiff_index }, 838{"", gitdiff_unrecognized }, 839}; 840int i; 841 842 len =linelen(line, size); 843if(!len || line[len-1] !='\n') 844break; 845for(i =0; i <ARRAY_SIZE(optable); i++) { 846const struct opentry *p = optable + i; 847int oplen =strlen(p->str); 848if(len < oplen ||memcmp(p->str, line, oplen)) 849continue; 850if(p->fn(line + oplen, patch) <0) 851return offset; 852break; 853} 854} 855 856return offset; 857} 858 859static intparse_num(const char*line,unsigned long*p) 860{ 861char*ptr; 862 863if(!isdigit(*line)) 864return0; 865*p =strtoul(line, &ptr,10); 866return ptr - line; 867} 868 869static intparse_range(const char*line,int len,int offset,const char*expect, 870unsigned long*p1,unsigned long*p2) 871{ 872int digits, ex; 873 874if(offset <0|| offset >= len) 875return-1; 876 line += offset; 877 len -= offset; 878 879 digits =parse_num(line, p1); 880if(!digits) 881return-1; 882 883 offset += digits; 884 line += digits; 885 len -= digits; 886 887*p2 =1; 888if(*line ==',') { 889 digits =parse_num(line+1, p2); 890if(!digits) 891return-1; 892 893 offset += digits+1; 894 line += digits+1; 895 len -= digits+1; 896} 897 898 ex =strlen(expect); 899if(ex > len) 900return-1; 901if(memcmp(line, expect, ex)) 902return-1; 903 904return offset + ex; 905} 906 907static voidrecount_diff(char*line,int size,struct fragment *fragment) 908{ 909int oldlines =0, newlines =0, ret =0; 910 911if(size <1) { 912warning("recount: ignore empty hunk"); 913return; 914} 915 916for(;;) { 917int len =linelen(line, size); 918 size -= len; 919 line += len; 920 921if(size <1) 922break; 923 924switch(*line) { 925case' ':case'\n': 926 newlines++; 927/* fall through */ 928case'-': 929 oldlines++; 930continue; 931case'+': 932 newlines++; 933continue; 934case'\\': 935continue; 936case'@': 937 ret = size <3||prefixcmp(line,"@@ "); 938break; 939case'd': 940 ret = size <5||prefixcmp(line,"diff "); 941break; 942default: 943 ret = -1; 944break; 945} 946if(ret) { 947warning("recount: unexpected line: %.*s", 948(int)linelen(line, size), line); 949return; 950} 951break; 952} 953 fragment->oldlines = oldlines; 954 fragment->newlines = newlines; 955} 956 957/* 958 * Parse a unified diff fragment header of the 959 * form "@@ -a,b +c,d @@" 960 */ 961static intparse_fragment_header(char*line,int len,struct fragment *fragment) 962{ 963int offset; 964 965if(!len || line[len-1] !='\n') 966return-1; 967 968/* Figure out the number of lines in a fragment */ 969 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines); 970 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines); 971 972return offset; 973} 974 975static intfind_header(char*line,unsigned long size,int*hdrsize,struct patch *patch) 976{ 977unsigned long offset, len; 978 979 patch->is_toplevel_relative =0; 980 patch->is_rename = patch->is_copy =0; 981 patch->is_new = patch->is_delete = -1; 982 patch->old_mode = patch->new_mode =0; 983 patch->old_name = patch->new_name = NULL; 984for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) { 985unsigned long nextlen; 986 987 len =linelen(line, size); 988if(!len) 989break; 990 991/* Testing this early allows us to take a few shortcuts.. */ 992if(len <6) 993continue; 994 995/* 996 * Make sure we don't find any unconnected patch fragments. 997 * That's a sign that we didn't find a header, and that a 998 * patch has become corrupted/broken up. 999 */1000if(!memcmp("@@ -", line,4)) {1001struct fragment dummy;1002if(parse_fragment_header(line, len, &dummy) <0)1003continue;1004die("patch fragment without header at line%d: %.*s",1005 linenr, (int)len-1, line);1006}10071008if(size < len +6)1009break;10101011/*1012 * Git patch? It might not have a real patch, just a rename1013 * or mode change, so we handle that specially1014 */1015if(!memcmp("diff --git ", line,11)) {1016int git_hdr_len =parse_git_header(line, len, size, patch);1017if(git_hdr_len <= len)1018continue;1019if(!patch->old_name && !patch->new_name) {1020if(!patch->def_name)1021die("git diff header lacks filename information (line%d)", linenr);1022 patch->old_name = patch->new_name = patch->def_name;1023}1024 patch->is_toplevel_relative =1;1025*hdrsize = git_hdr_len;1026return offset;1027}10281029/* --- followed by +++ ? */1030if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1031continue;10321033/*1034 * We only accept unified patches, so we want it to1035 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1036 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1037 */1038 nextlen =linelen(line + len, size - len);1039if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1040continue;10411042/* Ok, we'll consider it a patch */1043parse_traditional_patch(line, line+len, patch);1044*hdrsize = len + nextlen;1045 linenr +=2;1046return offset;1047}1048return-1;1049}10501051static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1052{1053char*err;1054unsigned result =ws_check(line +1, len -1, ws_rule);1055if(!result)1056return;10571058 whitespace_error++;1059if(squelch_whitespace_errors &&1060 squelch_whitespace_errors < whitespace_error)1061;1062else{1063 err =whitespace_error_string(result);1064fprintf(stderr,"%s:%d:%s.\n%.*s\n",1065 patch_input_file, linenr, err, len -2, line +1);1066free(err);1067}1068}10691070/*1071 * Parse a unified diff. Note that this really needs to parse each1072 * fragment separately, since the only way to know the difference1073 * between a "---" that is part of a patch, and a "---" that starts1074 * the next patch is to look at the line counts..1075 */1076static intparse_fragment(char*line,unsigned long size,1077struct patch *patch,struct fragment *fragment)1078{1079int added, deleted;1080int len =linelen(line, size), offset;1081unsigned long oldlines, newlines;1082unsigned long leading, trailing;10831084 offset =parse_fragment_header(line, len, fragment);1085if(offset <0)1086return-1;1087if(offset >0&& patch->recount)1088recount_diff(line + offset, size - offset, fragment);1089 oldlines = fragment->oldlines;1090 newlines = fragment->newlines;1091 leading =0;1092 trailing =0;10931094/* Parse the thing.. */1095 line += len;1096 size -= len;1097 linenr++;1098 added = deleted =0;1099for(offset = len;11000< size;1101 offset += len, size -= len, line += len, linenr++) {1102if(!oldlines && !newlines)1103break;1104 len =linelen(line, size);1105if(!len || line[len-1] !='\n')1106return-1;1107switch(*line) {1108default:1109return-1;1110case'\n':/* newer GNU diff, an empty context line */1111case' ':1112 oldlines--;1113 newlines--;1114if(!deleted && !added)1115 leading++;1116 trailing++;1117break;1118case'-':1119if(apply_in_reverse &&1120 ws_error_action != nowarn_ws_error)1121check_whitespace(line, len, patch->ws_rule);1122 deleted++;1123 oldlines--;1124 trailing =0;1125break;1126case'+':1127if(!apply_in_reverse &&1128 ws_error_action != nowarn_ws_error)1129check_whitespace(line, len, patch->ws_rule);1130 added++;1131 newlines--;1132 trailing =0;1133break;11341135/*1136 * We allow "\ No newline at end of file". Depending1137 * on locale settings when the patch was produced we1138 * don't know what this line looks like. The only1139 * thing we do know is that it begins with "\ ".1140 * Checking for 12 is just for sanity check -- any1141 * l10n of "\ No newline..." is at least that long.1142 */1143case'\\':1144if(len <12||memcmp(line,"\\",2))1145return-1;1146break;1147}1148}1149if(oldlines || newlines)1150return-1;1151 fragment->leading = leading;1152 fragment->trailing = trailing;11531154/*1155 * If a fragment ends with an incomplete line, we failed to include1156 * it in the above loop because we hit oldlines == newlines == 01157 * before seeing it.1158 */1159if(12< size && !memcmp(line,"\\",2))1160 offset +=linelen(line, size);11611162 patch->lines_added += added;1163 patch->lines_deleted += deleted;11641165if(0< patch->is_new && oldlines)1166returnerror("new file depends on old contents");1167if(0< patch->is_delete && newlines)1168returnerror("deleted file still has contents");1169return offset;1170}11711172static intparse_single_patch(char*line,unsigned long size,struct patch *patch)1173{1174unsigned long offset =0;1175unsigned long oldlines =0, newlines =0, context =0;1176struct fragment **fragp = &patch->fragments;11771178while(size >4&& !memcmp(line,"@@ -",4)) {1179struct fragment *fragment;1180int len;11811182 fragment =xcalloc(1,sizeof(*fragment));1183 len =parse_fragment(line, size, patch, fragment);1184if(len <=0)1185die("corrupt patch at line%d", linenr);1186 fragment->patch = line;1187 fragment->size = len;1188 oldlines += fragment->oldlines;1189 newlines += fragment->newlines;1190 context += fragment->leading + fragment->trailing;11911192*fragp = fragment;1193 fragp = &fragment->next;11941195 offset += len;1196 line += len;1197 size -= len;1198}11991200/*1201 * If something was removed (i.e. we have old-lines) it cannot1202 * be creation, and if something was added it cannot be1203 * deletion. However, the reverse is not true; --unified=01204 * patches that only add are not necessarily creation even1205 * though they do not have any old lines, and ones that only1206 * delete are not necessarily deletion.1207 *1208 * Unfortunately, a real creation/deletion patch do _not_ have1209 * any context line by definition, so we cannot safely tell it1210 * apart with --unified=0 insanity. At least if the patch has1211 * more than one hunk it is not creation or deletion.1212 */1213if(patch->is_new <0&&1214(oldlines || (patch->fragments && patch->fragments->next)))1215 patch->is_new =0;1216if(patch->is_delete <0&&1217(newlines || (patch->fragments && patch->fragments->next)))1218 patch->is_delete =0;12191220if(0< patch->is_new && oldlines)1221die("new file%sdepends on old contents", patch->new_name);1222if(0< patch->is_delete && newlines)1223die("deleted file%sstill has contents", patch->old_name);1224if(!patch->is_delete && !newlines && context)1225fprintf(stderr,"** warning: file%sbecomes empty but "1226"is not deleted\n", patch->new_name);12271228return offset;1229}12301231staticinlineintmetadata_changes(struct patch *patch)1232{1233return patch->is_rename >0||1234 patch->is_copy >0||1235 patch->is_new >0||1236 patch->is_delete ||1237(patch->old_mode && patch->new_mode &&1238 patch->old_mode != patch->new_mode);1239}12401241static char*inflate_it(const void*data,unsigned long size,1242unsigned long inflated_size)1243{1244 z_stream stream;1245void*out;1246int st;12471248memset(&stream,0,sizeof(stream));12491250 stream.next_in = (unsigned char*)data;1251 stream.avail_in = size;1252 stream.next_out = out =xmalloc(inflated_size);1253 stream.avail_out = inflated_size;1254inflateInit(&stream);1255 st =inflate(&stream, Z_FINISH);1256if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1257free(out);1258return NULL;1259}1260return out;1261}12621263static struct fragment *parse_binary_hunk(char**buf_p,1264unsigned long*sz_p,1265int*status_p,1266int*used_p)1267{1268/*1269 * Expect a line that begins with binary patch method ("literal"1270 * or "delta"), followed by the length of data before deflating.1271 * a sequence of 'length-byte' followed by base-85 encoded data1272 * should follow, terminated by a newline.1273 *1274 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1275 * and we would limit the patch line to 66 characters,1276 * so one line can fit up to 13 groups that would decode1277 * to 52 bytes max. The length byte 'A'-'Z' corresponds1278 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1279 */1280int llen, used;1281unsigned long size = *sz_p;1282char*buffer = *buf_p;1283int patch_method;1284unsigned long origlen;1285char*data = NULL;1286int hunk_size =0;1287struct fragment *frag;12881289 llen =linelen(buffer, size);1290 used = llen;12911292*status_p =0;12931294if(!prefixcmp(buffer,"delta ")) {1295 patch_method = BINARY_DELTA_DEFLATED;1296 origlen =strtoul(buffer +6, NULL,10);1297}1298else if(!prefixcmp(buffer,"literal ")) {1299 patch_method = BINARY_LITERAL_DEFLATED;1300 origlen =strtoul(buffer +8, NULL,10);1301}1302else1303return NULL;13041305 linenr++;1306 buffer += llen;1307while(1) {1308int byte_length, max_byte_length, newsize;1309 llen =linelen(buffer, size);1310 used += llen;1311 linenr++;1312if(llen ==1) {1313/* consume the blank line */1314 buffer++;1315 size--;1316break;1317}1318/*1319 * Minimum line is "A00000\n" which is 7-byte long,1320 * and the line length must be multiple of 5 plus 2.1321 */1322if((llen <7) || (llen-2) %5)1323goto corrupt;1324 max_byte_length = (llen -2) /5*4;1325 byte_length = *buffer;1326if('A'<= byte_length && byte_length <='Z')1327 byte_length = byte_length -'A'+1;1328else if('a'<= byte_length && byte_length <='z')1329 byte_length = byte_length -'a'+27;1330else1331goto corrupt;1332/* if the input length was not multiple of 4, we would1333 * have filler at the end but the filler should never1334 * exceed 3 bytes1335 */1336if(max_byte_length < byte_length ||1337 byte_length <= max_byte_length -4)1338goto corrupt;1339 newsize = hunk_size + byte_length;1340 data =xrealloc(data, newsize);1341if(decode_85(data + hunk_size, buffer +1, byte_length))1342goto corrupt;1343 hunk_size = newsize;1344 buffer += llen;1345 size -= llen;1346}13471348 frag =xcalloc(1,sizeof(*frag));1349 frag->patch =inflate_it(data, hunk_size, origlen);1350if(!frag->patch)1351goto corrupt;1352free(data);1353 frag->size = origlen;1354*buf_p = buffer;1355*sz_p = size;1356*used_p = used;1357 frag->binary_patch_method = patch_method;1358return frag;13591360 corrupt:1361free(data);1362*status_p = -1;1363error("corrupt binary patch at line%d: %.*s",1364 linenr-1, llen-1, buffer);1365return NULL;1366}13671368static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1369{1370/*1371 * We have read "GIT binary patch\n"; what follows is a line1372 * that says the patch method (currently, either "literal" or1373 * "delta") and the length of data before deflating; a1374 * sequence of 'length-byte' followed by base-85 encoded data1375 * follows.1376 *1377 * When a binary patch is reversible, there is another binary1378 * hunk in the same format, starting with patch method (either1379 * "literal" or "delta") with the length of data, and a sequence1380 * of length-byte + base-85 encoded data, terminated with another1381 * empty line. This data, when applied to the postimage, produces1382 * the preimage.1383 */1384struct fragment *forward;1385struct fragment *reverse;1386int status;1387int used, used_1;13881389 forward =parse_binary_hunk(&buffer, &size, &status, &used);1390if(!forward && !status)1391/* there has to be one hunk (forward hunk) */1392returnerror("unrecognized binary patch at line%d", linenr-1);1393if(status)1394/* otherwise we already gave an error message */1395return status;13961397 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1398if(reverse)1399 used += used_1;1400else if(status) {1401/*1402 * Not having reverse hunk is not an error, but having1403 * a corrupt reverse hunk is.1404 */1405free((void*) forward->patch);1406free(forward);1407return status;1408}1409 forward->next = reverse;1410 patch->fragments = forward;1411 patch->is_binary =1;1412return used;1413}14141415static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1416{1417int hdrsize, patchsize;1418int offset =find_header(buffer, size, &hdrsize, patch);14191420if(offset <0)1421return offset;14221423 patch->ws_rule =whitespace_rule(patch->new_name1424? patch->new_name1425: patch->old_name);14261427 patchsize =parse_single_patch(buffer + offset + hdrsize,1428 size - offset - hdrsize, patch);14291430if(!patchsize) {1431static const char*binhdr[] = {1432"Binary files ",1433"Files ",1434 NULL,1435};1436static const char git_binary[] ="GIT binary patch\n";1437int i;1438int hd = hdrsize + offset;1439unsigned long llen =linelen(buffer + hd, size - hd);14401441if(llen ==sizeof(git_binary) -1&&1442!memcmp(git_binary, buffer + hd, llen)) {1443int used;1444 linenr++;1445 used =parse_binary(buffer + hd + llen,1446 size - hd - llen, patch);1447if(used)1448 patchsize = used + llen;1449else1450 patchsize =0;1451}1452else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1453for(i =0; binhdr[i]; i++) {1454int len =strlen(binhdr[i]);1455if(len < size - hd &&1456!memcmp(binhdr[i], buffer + hd, len)) {1457 linenr++;1458 patch->is_binary =1;1459 patchsize = llen;1460break;1461}1462}1463}14641465/* Empty patch cannot be applied if it is a text patch1466 * without metadata change. A binary patch appears1467 * empty to us here.1468 */1469if((apply || check) &&1470(!patch->is_binary && !metadata_changes(patch)))1471die("patch with only garbage at line%d", linenr);1472}14731474return offset + hdrsize + patchsize;1475}14761477#define swap(a,b) myswap((a),(b),sizeof(a))14781479#define myswap(a, b, size) do { \1480 unsigned char mytmp[size]; \1481 memcpy(mytmp, &a, size); \1482 memcpy(&a, &b, size); \1483 memcpy(&b, mytmp, size); \1484} while (0)14851486static voidreverse_patches(struct patch *p)1487{1488for(; p; p = p->next) {1489struct fragment *frag = p->fragments;14901491swap(p->new_name, p->old_name);1492swap(p->new_mode, p->old_mode);1493swap(p->is_new, p->is_delete);1494swap(p->lines_added, p->lines_deleted);1495swap(p->old_sha1_prefix, p->new_sha1_prefix);14961497for(; frag; frag = frag->next) {1498swap(frag->newpos, frag->oldpos);1499swap(frag->newlines, frag->oldlines);1500}1501}1502}15031504static const char pluses[] =1505"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";1506static const char minuses[]=1507"----------------------------------------------------------------------";15081509static voidshow_stats(struct patch *patch)1510{1511struct strbuf qname;1512char*cp = patch->new_name ? patch->new_name : patch->old_name;1513int max, add, del;15141515strbuf_init(&qname,0);1516quote_c_style(cp, &qname, NULL,0);15171518/*1519 * "scale" the filename1520 */1521 max = max_len;1522if(max >50)1523 max =50;15241525if(qname.len > max) {1526 cp =strchr(qname.buf + qname.len +3- max,'/');1527if(!cp)1528 cp = qname.buf + qname.len +3- max;1529strbuf_splice(&qname,0, cp - qname.buf,"...",3);1530}15311532if(patch->is_binary) {1533printf(" %-*s | Bin\n", max, qname.buf);1534strbuf_release(&qname);1535return;1536}15371538printf(" %-*s |", max, qname.buf);1539strbuf_release(&qname);15401541/*1542 * scale the add/delete1543 */1544 max = max + max_change >70?70- max : max_change;1545 add = patch->lines_added;1546 del = patch->lines_deleted;15471548if(max_change >0) {1549int total = ((add + del) * max + max_change /2) / max_change;1550 add = (add * max + max_change /2) / max_change;1551 del = total - add;1552}1553printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,1554 add, pluses, del, minuses);1555}15561557static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)1558{1559switch(st->st_mode & S_IFMT) {1560case S_IFLNK:1561strbuf_grow(buf, st->st_size);1562if(readlink(path, buf->buf, st->st_size) != st->st_size)1563return-1;1564strbuf_setlen(buf, st->st_size);1565return0;1566case S_IFREG:1567if(strbuf_read_file(buf, path, st->st_size) != st->st_size)1568returnerror("unable to open or read%s", path);1569convert_to_git(path, buf->buf, buf->len, buf,0);1570return0;1571default:1572return-1;1573}1574}15751576static voidupdate_pre_post_images(struct image *preimage,1577struct image *postimage,1578char*buf,1579size_t len)1580{1581int i, ctx;1582char*new, *old, *fixed;1583struct image fixed_preimage;15841585/*1586 * Update the preimage with whitespace fixes. Note that we1587 * are not losing preimage->buf -- apply_one_fragment() will1588 * free "oldlines".1589 */1590prepare_image(&fixed_preimage, buf, len,1);1591assert(fixed_preimage.nr == preimage->nr);1592for(i =0; i < preimage->nr; i++)1593 fixed_preimage.line[i].flag = preimage->line[i].flag;1594free(preimage->line_allocated);1595*preimage = fixed_preimage;15961597/*1598 * Adjust the common context lines in postimage, in place.1599 * This is possible because whitespace fixing does not make1600 * the string grow.1601 */1602new= old = postimage->buf;1603 fixed = preimage->buf;1604for(i = ctx =0; i < postimage->nr; i++) {1605size_t len = postimage->line[i].len;1606if(!(postimage->line[i].flag & LINE_COMMON)) {1607/* an added line -- no counterparts in preimage */1608memmove(new, old, len);1609 old += len;1610new+= len;1611continue;1612}16131614/* a common context -- skip it in the original postimage */1615 old += len;16161617/* and find the corresponding one in the fixed preimage */1618while(ctx < preimage->nr &&1619!(preimage->line[ctx].flag & LINE_COMMON)) {1620 fixed += preimage->line[ctx].len;1621 ctx++;1622}1623if(preimage->nr <= ctx)1624die("oops");16251626/* and copy it in, while fixing the line length */1627 len = preimage->line[ctx].len;1628memcpy(new, fixed, len);1629new+= len;1630 fixed += len;1631 postimage->line[i].len = len;1632 ctx++;1633}16341635/* Fix the length of the whole thing */1636 postimage->len =new- postimage->buf;1637}16381639static intmatch_fragment(struct image *img,1640struct image *preimage,1641struct image *postimage,1642unsigned longtry,1643int try_lno,1644unsigned ws_rule,1645int match_beginning,int match_end)1646{1647int i;1648char*fixed_buf, *buf, *orig, *target;16491650if(preimage->nr + try_lno > img->nr)1651return0;16521653if(match_beginning && try_lno)1654return0;16551656if(match_end && preimage->nr + try_lno != img->nr)1657return0;16581659/* Quick hash check */1660for(i =0; i < preimage->nr; i++)1661if(preimage->line[i].hash != img->line[try_lno + i].hash)1662return0;16631664/*1665 * Do we have an exact match? If we were told to match1666 * at the end, size must be exactly at try+fragsize,1667 * otherwise try+fragsize must be still within the preimage,1668 * and either case, the old piece should match the preimage1669 * exactly.1670 */1671if((match_end1672? (try+ preimage->len == img->len)1673: (try+ preimage->len <= img->len)) &&1674!memcmp(img->buf +try, preimage->buf, preimage->len))1675return1;16761677if(ws_error_action != correct_ws_error)1678return0;16791680/*1681 * The hunk does not apply byte-by-byte, but the hash says1682 * it might with whitespace fuzz.1683 */1684 fixed_buf =xmalloc(preimage->len +1);1685 buf = fixed_buf;1686 orig = preimage->buf;1687 target = img->buf +try;1688for(i =0; i < preimage->nr; i++) {1689size_t fixlen;/* length after fixing the preimage */1690size_t oldlen = preimage->line[i].len;1691size_t tgtlen = img->line[try_lno + i].len;1692size_t tgtfixlen;/* length after fixing the target line */1693char tgtfixbuf[1024], *tgtfix;1694int match;16951696/* Try fixing the line in the preimage */1697 fixlen =ws_fix_copy(buf, orig, oldlen, ws_rule, NULL);16981699/* Try fixing the line in the target */1700if(sizeof(tgtfixbuf) < tgtlen)1701 tgtfix = tgtfixbuf;1702else1703 tgtfix =xmalloc(tgtlen);1704 tgtfixlen =ws_fix_copy(tgtfix, target, tgtlen, ws_rule, NULL);17051706/*1707 * If they match, either the preimage was based on1708 * a version before our tree fixed whitespace breakage,1709 * or we are lacking a whitespace-fix patch the tree1710 * the preimage was based on already had (i.e. target1711 * has whitespace breakage, the preimage doesn't).1712 * In either case, we are fixing the whitespace breakages1713 * so we might as well take the fix together with their1714 * real change.1715 */1716 match = (tgtfixlen == fixlen && !memcmp(tgtfix, buf, fixlen));17171718if(tgtfix != tgtfixbuf)1719free(tgtfix);1720if(!match)1721goto unmatch_exit;17221723 orig += oldlen;1724 buf += fixlen;1725 target += tgtlen;1726}17271728/*1729 * Yes, the preimage is based on an older version that still1730 * has whitespace breakages unfixed, and fixing them makes the1731 * hunk match. Update the context lines in the postimage.1732 */1733update_pre_post_images(preimage, postimage,1734 fixed_buf, buf - fixed_buf);1735return1;17361737 unmatch_exit:1738free(fixed_buf);1739return0;1740}17411742static intfind_pos(struct image *img,1743struct image *preimage,1744struct image *postimage,1745int line,1746unsigned ws_rule,1747int match_beginning,int match_end)1748{1749int i;1750unsigned long backwards, forwards,try;1751int backwards_lno, forwards_lno, try_lno;17521753if(preimage->nr > img->nr)1754return-1;17551756/*1757 * If match_begining or match_end is specified, there is no1758 * point starting from a wrong line that will never match and1759 * wander around and wait for a match at the specified end.1760 */1761if(match_beginning)1762 line =0;1763else if(match_end)1764 line = img->nr - preimage->nr;17651766if(line > img->nr)1767 line = img->nr;17681769try=0;1770for(i =0; i < line; i++)1771try+= img->line[i].len;17721773/*1774 * There's probably some smart way to do this, but I'll leave1775 * that to the smart and beautiful people. I'm simple and stupid.1776 */1777 backwards =try;1778 backwards_lno = line;1779 forwards =try;1780 forwards_lno = line;1781 try_lno = line;17821783for(i =0; ; i++) {1784if(match_fragment(img, preimage, postimage,1785try, try_lno, ws_rule,1786 match_beginning, match_end))1787return try_lno;17881789 again:1790if(backwards_lno ==0&& forwards_lno == img->nr)1791break;17921793if(i &1) {1794if(backwards_lno ==0) {1795 i++;1796goto again;1797}1798 backwards_lno--;1799 backwards -= img->line[backwards_lno].len;1800try= backwards;1801 try_lno = backwards_lno;1802}else{1803if(forwards_lno == img->nr) {1804 i++;1805goto again;1806}1807 forwards += img->line[forwards_lno].len;1808 forwards_lno++;1809try= forwards;1810 try_lno = forwards_lno;1811}18121813}1814return-1;1815}18161817static voidremove_first_line(struct image *img)1818{1819 img->buf += img->line[0].len;1820 img->len -= img->line[0].len;1821 img->line++;1822 img->nr--;1823}18241825static voidremove_last_line(struct image *img)1826{1827 img->len -= img->line[--img->nr].len;1828}18291830static voidupdate_image(struct image *img,1831int applied_pos,1832struct image *preimage,1833struct image *postimage)1834{1835/*1836 * remove the copy of preimage at offset in img1837 * and replace it with postimage1838 */1839int i, nr;1840size_t remove_count, insert_count, applied_at =0;1841char*result;18421843for(i =0; i < applied_pos; i++)1844 applied_at += img->line[i].len;18451846 remove_count =0;1847for(i =0; i < preimage->nr; i++)1848 remove_count += img->line[applied_pos + i].len;1849 insert_count = postimage->len;18501851/* Adjust the contents */1852 result =xmalloc(img->len + insert_count - remove_count +1);1853memcpy(result, img->buf, applied_at);1854memcpy(result + applied_at, postimage->buf, postimage->len);1855memcpy(result + applied_at + postimage->len,1856 img->buf + (applied_at + remove_count),1857 img->len - (applied_at + remove_count));1858free(img->buf);1859 img->buf = result;1860 img->len += insert_count - remove_count;1861 result[img->len] ='\0';18621863/* Adjust the line table */1864 nr = img->nr + postimage->nr - preimage->nr;1865if(preimage->nr < postimage->nr) {1866/*1867 * NOTE: this knows that we never call remove_first_line()1868 * on anything other than pre/post image.1869 */1870 img->line =xrealloc(img->line, nr *sizeof(*img->line));1871 img->line_allocated = img->line;1872}1873if(preimage->nr != postimage->nr)1874memmove(img->line + applied_pos + postimage->nr,1875 img->line + applied_pos + preimage->nr,1876(img->nr - (applied_pos + preimage->nr)) *1877sizeof(*img->line));1878memcpy(img->line + applied_pos,1879 postimage->line,1880 postimage->nr *sizeof(*img->line));1881 img->nr = nr;1882}18831884static intapply_one_fragment(struct image *img,struct fragment *frag,1885int inaccurate_eof,unsigned ws_rule)1886{1887int match_beginning, match_end;1888const char*patch = frag->patch;1889int size = frag->size;1890char*old, *new, *oldlines, *newlines;1891int new_blank_lines_at_end =0;1892unsigned long leading, trailing;1893int pos, applied_pos;1894struct image preimage;1895struct image postimage;18961897memset(&preimage,0,sizeof(preimage));1898memset(&postimage,0,sizeof(postimage));1899 oldlines =xmalloc(size);1900 newlines =xmalloc(size);19011902 old = oldlines;1903new= newlines;1904while(size >0) {1905char first;1906int len =linelen(patch, size);1907int plen, added;1908int added_blank_line =0;19091910if(!len)1911break;19121913/*1914 * "plen" is how much of the line we should use for1915 * the actual patch data. Normally we just remove the1916 * first character on the line, but if the line is1917 * followed by "\ No newline", then we also remove the1918 * last one (which is the newline, of course).1919 */1920 plen = len -1;1921if(len < size && patch[len] =='\\')1922 plen--;1923 first = *patch;1924if(apply_in_reverse) {1925if(first =='-')1926 first ='+';1927else if(first =='+')1928 first ='-';1929}19301931switch(first) {1932case'\n':1933/* Newer GNU diff, empty context line */1934if(plen <0)1935/* ... followed by '\No newline'; nothing */1936break;1937*old++ ='\n';1938*new++ ='\n';1939add_line_info(&preimage,"\n",1, LINE_COMMON);1940add_line_info(&postimage,"\n",1, LINE_COMMON);1941break;1942case' ':1943case'-':1944memcpy(old, patch +1, plen);1945add_line_info(&preimage, old, plen,1946(first ==' '? LINE_COMMON :0));1947 old += plen;1948if(first =='-')1949break;1950/* Fall-through for ' ' */1951case'+':1952/* --no-add does not add new lines */1953if(first =='+'&& no_add)1954break;19551956if(first !='+'||1957!whitespace_error ||1958 ws_error_action != correct_ws_error) {1959memcpy(new, patch +1, plen);1960 added = plen;1961}1962else{1963 added =ws_fix_copy(new, patch +1, plen, ws_rule, &applied_after_fixing_ws);1964}1965add_line_info(&postimage,new, added,1966(first =='+'?0: LINE_COMMON));1967new+= added;1968if(first =='+'&&1969 added ==1&&new[-1] =='\n')1970 added_blank_line =1;1971break;1972case'@':case'\\':1973/* Ignore it, we already handled it */1974break;1975default:1976if(apply_verbosely)1977error("invalid start of line: '%c'", first);1978return-1;1979}1980if(added_blank_line)1981 new_blank_lines_at_end++;1982else1983 new_blank_lines_at_end =0;1984 patch += len;1985 size -= len;1986}1987if(inaccurate_eof &&1988 old > oldlines && old[-1] =='\n'&&1989new> newlines &&new[-1] =='\n') {1990 old--;1991new--;1992}19931994 leading = frag->leading;1995 trailing = frag->trailing;19961997/*1998 * A hunk to change lines at the beginning would begin with1999 * @@ -1,L +N,M @@2000 * but we need to be careful. -U0 that inserts before the second2001 * line also has this pattern.2002 *2003 * And a hunk to add to an empty file would begin with2004 * @@ -0,0 +N,M @@2005 *2006 * In other words, a hunk that is (frag->oldpos <= 1) with or2007 * without leading context must match at the beginning.2008 */2009 match_beginning = (!frag->oldpos ||2010(frag->oldpos ==1&& !unidiff_zero));20112012/*2013 * A hunk without trailing lines must match at the end.2014 * However, we simply cannot tell if a hunk must match end2015 * from the lack of trailing lines if the patch was generated2016 * with unidiff without any context.2017 */2018 match_end = !unidiff_zero && !trailing;20192020 pos = frag->newpos ? (frag->newpos -1) :0;2021 preimage.buf = oldlines;2022 preimage.len = old - oldlines;2023 postimage.buf = newlines;2024 postimage.len =new- newlines;2025 preimage.line = preimage.line_allocated;2026 postimage.line = postimage.line_allocated;20272028for(;;) {20292030 applied_pos =find_pos(img, &preimage, &postimage, pos,2031 ws_rule, match_beginning, match_end);20322033if(applied_pos >=0)2034break;20352036/* Am I at my context limits? */2037if((leading <= p_context) && (trailing <= p_context))2038break;2039if(match_beginning || match_end) {2040 match_beginning = match_end =0;2041continue;2042}20432044/*2045 * Reduce the number of context lines; reduce both2046 * leading and trailing if they are equal otherwise2047 * just reduce the larger context.2048 */2049if(leading >= trailing) {2050remove_first_line(&preimage);2051remove_first_line(&postimage);2052 pos--;2053 leading--;2054}2055if(trailing > leading) {2056remove_last_line(&preimage);2057remove_last_line(&postimage);2058 trailing--;2059}2060}20612062if(applied_pos >=0) {2063if(ws_error_action == correct_ws_error &&2064 new_blank_lines_at_end &&2065 postimage.nr + applied_pos == img->nr) {2066/*2067 * If the patch application adds blank lines2068 * at the end, and if the patch applies at the2069 * end of the image, remove those added blank2070 * lines.2071 */2072while(new_blank_lines_at_end--)2073remove_last_line(&postimage);2074}20752076/*2077 * Warn if it was necessary to reduce the number2078 * of context lines.2079 */2080if((leading != frag->leading) ||2081(trailing != frag->trailing))2082fprintf(stderr,"Context reduced to (%ld/%ld)"2083" to apply fragment at%d\n",2084 leading, trailing, applied_pos+1);2085update_image(img, applied_pos, &preimage, &postimage);2086}else{2087if(apply_verbosely)2088error("while searching for:\n%.*s",2089(int)(old - oldlines), oldlines);2090}20912092free(oldlines);2093free(newlines);2094free(preimage.line_allocated);2095free(postimage.line_allocated);20962097return(applied_pos <0);2098}20992100static intapply_binary_fragment(struct image *img,struct patch *patch)2101{2102struct fragment *fragment = patch->fragments;2103unsigned long len;2104void*dst;21052106/* Binary patch is irreversible without the optional second hunk */2107if(apply_in_reverse) {2108if(!fragment->next)2109returnerror("cannot reverse-apply a binary patch "2110"without the reverse hunk to '%s'",2111 patch->new_name2112? patch->new_name : patch->old_name);2113 fragment = fragment->next;2114}2115switch(fragment->binary_patch_method) {2116case BINARY_DELTA_DEFLATED:2117 dst =patch_delta(img->buf, img->len, fragment->patch,2118 fragment->size, &len);2119if(!dst)2120return-1;2121clear_image(img);2122 img->buf = dst;2123 img->len = len;2124return0;2125case BINARY_LITERAL_DEFLATED:2126clear_image(img);2127 img->len = fragment->size;2128 img->buf =xmalloc(img->len+1);2129memcpy(img->buf, fragment->patch, img->len);2130 img->buf[img->len] ='\0';2131return0;2132}2133return-1;2134}21352136static intapply_binary(struct image *img,struct patch *patch)2137{2138const char*name = patch->old_name ? patch->old_name : patch->new_name;2139unsigned char sha1[20];21402141/*2142 * For safety, we require patch index line to contain2143 * full 40-byte textual SHA1 for old and new, at least for now.2144 */2145if(strlen(patch->old_sha1_prefix) !=40||2146strlen(patch->new_sha1_prefix) !=40||2147get_sha1_hex(patch->old_sha1_prefix, sha1) ||2148get_sha1_hex(patch->new_sha1_prefix, sha1))2149returnerror("cannot apply binary patch to '%s' "2150"without full index line", name);21512152if(patch->old_name) {2153/*2154 * See if the old one matches what the patch2155 * applies to.2156 */2157hash_sha1_file(img->buf, img->len, blob_type, sha1);2158if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2159returnerror("the patch applies to '%s' (%s), "2160"which does not match the "2161"current contents.",2162 name,sha1_to_hex(sha1));2163}2164else{2165/* Otherwise, the old one must be empty. */2166if(img->len)2167returnerror("the patch applies to an empty "2168"'%s' but it is not empty", name);2169}21702171get_sha1_hex(patch->new_sha1_prefix, sha1);2172if(is_null_sha1(sha1)) {2173clear_image(img);2174return0;/* deletion patch */2175}21762177if(has_sha1_file(sha1)) {2178/* We already have the postimage */2179enum object_type type;2180unsigned long size;2181char*result;21822183 result =read_sha1_file(sha1, &type, &size);2184if(!result)2185returnerror("the necessary postimage%sfor "2186"'%s' cannot be read",2187 patch->new_sha1_prefix, name);2188clear_image(img);2189 img->buf = result;2190 img->len = size;2191}else{2192/*2193 * We have verified buf matches the preimage;2194 * apply the patch data to it, which is stored2195 * in the patch->fragments->{patch,size}.2196 */2197if(apply_binary_fragment(img, patch))2198returnerror("binary patch does not apply to '%s'",2199 name);22002201/* verify that the result matches */2202hash_sha1_file(img->buf, img->len, blob_type, sha1);2203if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2204returnerror("binary patch to '%s' creates incorrect result (expecting%s, got%s)",2205 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2206}22072208return0;2209}22102211static intapply_fragments(struct image *img,struct patch *patch)2212{2213struct fragment *frag = patch->fragments;2214const char*name = patch->old_name ? patch->old_name : patch->new_name;2215unsigned ws_rule = patch->ws_rule;2216unsigned inaccurate_eof = patch->inaccurate_eof;22172218if(patch->is_binary)2219returnapply_binary(img, patch);22202221while(frag) {2222if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule)) {2223error("patch failed:%s:%ld", name, frag->oldpos);2224if(!apply_with_reject)2225return-1;2226 frag->rejected =1;2227}2228 frag = frag->next;2229}2230return0;2231}22322233static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2234{2235if(!ce)2236return0;22372238if(S_ISGITLINK(ce->ce_mode)) {2239strbuf_grow(buf,100);2240strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2241}else{2242enum object_type type;2243unsigned long sz;2244char*result;22452246 result =read_sha1_file(ce->sha1, &type, &sz);2247if(!result)2248return-1;2249/* XXX read_sha1_file NUL-terminates */2250strbuf_attach(buf, result, sz, sz +1);2251}2252return0;2253}22542255static struct patch *in_fn_table(const char*name)2256{2257struct string_list_item *item;22582259if(name == NULL)2260return NULL;22612262 item =string_list_lookup(name, &fn_table);2263if(item != NULL)2264return(struct patch *)item->util;22652266return NULL;2267}22682269static voidadd_to_fn_table(struct patch *patch)2270{2271struct string_list_item *item;22722273/*2274 * Always add new_name unless patch is a deletion2275 * This should cover the cases for normal diffs,2276 * file creations and copies2277 */2278if(patch->new_name != NULL) {2279 item =string_list_insert(patch->new_name, &fn_table);2280 item->util = patch;2281}22822283/*2284 * store a failure on rename/deletion cases because2285 * later chunks shouldn't patch old names2286 */2287if((patch->new_name == NULL) || (patch->is_rename)) {2288 item =string_list_insert(patch->old_name, &fn_table);2289 item->util = (struct patch *) -1;2290}2291}22922293static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)2294{2295struct strbuf buf;2296struct image image;2297size_t len;2298char*img;2299struct patch *tpatch;23002301strbuf_init(&buf,0);23022303if(!(patch->is_copy || patch->is_rename) &&2304((tpatch =in_fn_table(patch->old_name)) != NULL)) {2305if(tpatch == (struct patch *) -1) {2306returnerror("patch%shas been renamed/deleted",2307 patch->old_name);2308}2309/* We have a patched copy in memory use that */2310strbuf_add(&buf, tpatch->result, tpatch->resultsize);2311}else if(cached) {2312if(read_file_or_gitlink(ce, &buf))2313returnerror("read of%sfailed", patch->old_name);2314}else if(patch->old_name) {2315if(S_ISGITLINK(patch->old_mode)) {2316if(ce) {2317read_file_or_gitlink(ce, &buf);2318}else{2319/*2320 * There is no way to apply subproject2321 * patch without looking at the index.2322 */2323 patch->fragments = NULL;2324}2325}else{2326if(read_old_data(st, patch->old_name, &buf))2327returnerror("read of%sfailed", patch->old_name);2328}2329}23302331 img =strbuf_detach(&buf, &len);2332prepare_image(&image, img, len, !patch->is_binary);23332334if(apply_fragments(&image, patch) <0)2335return-1;/* note with --reject this succeeds. */2336 patch->result = image.buf;2337 patch->resultsize = image.len;2338add_to_fn_table(patch);2339free(image.line_allocated);23402341if(0< patch->is_delete && patch->resultsize)2342returnerror("removal patch leaves file contents");23432344return0;2345}23462347static intcheck_to_create_blob(const char*new_name,int ok_if_exists)2348{2349struct stat nst;2350if(!lstat(new_name, &nst)) {2351if(S_ISDIR(nst.st_mode) || ok_if_exists)2352return0;2353/*2354 * A leading component of new_name might be a symlink2355 * that is going to be removed with this patch, but2356 * still pointing at somewhere that has the path.2357 * In such a case, path "new_name" does not exist as2358 * far as git is concerned.2359 */2360if(has_symlink_leading_path(strlen(new_name), new_name))2361return0;23622363returnerror("%s: already exists in working directory", new_name);2364}2365else if((errno != ENOENT) && (errno != ENOTDIR))2366returnerror("%s:%s", new_name,strerror(errno));2367return0;2368}23692370static intverify_index_match(struct cache_entry *ce,struct stat *st)2371{2372if(S_ISGITLINK(ce->ce_mode)) {2373if(!S_ISDIR(st->st_mode))2374return-1;2375return0;2376}2377returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID);2378}23792380static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)2381{2382const char*old_name = patch->old_name;2383struct patch *tpatch = NULL;2384int stat_ret =0;2385unsigned st_mode =0;23862387/*2388 * Make sure that we do not have local modifications from the2389 * index when we are looking at the index. Also make sure2390 * we have the preimage file to be patched in the work tree,2391 * unless --cached, which tells git to apply only in the index.2392 */2393if(!old_name)2394return0;23952396assert(patch->is_new <=0);23972398if(!(patch->is_copy || patch->is_rename) &&2399(tpatch =in_fn_table(old_name)) != NULL) {2400if(tpatch == (struct patch *) -1) {2401returnerror("%s: has been deleted/renamed", old_name);2402}2403 st_mode = tpatch->new_mode;2404}else if(!cached) {2405 stat_ret =lstat(old_name, st);2406if(stat_ret && errno != ENOENT)2407returnerror("%s:%s", old_name,strerror(errno));2408}24092410if(check_index && !tpatch) {2411int pos =cache_name_pos(old_name,strlen(old_name));2412if(pos <0) {2413if(patch->is_new <0)2414goto is_new;2415returnerror("%s: does not exist in index", old_name);2416}2417*ce = active_cache[pos];2418if(stat_ret <0) {2419struct checkout costate;2420/* checkout */2421 costate.base_dir ="";2422 costate.base_dir_len =0;2423 costate.force =0;2424 costate.quiet =0;2425 costate.not_new =0;2426 costate.refresh_cache =1;2427if(checkout_entry(*ce, &costate, NULL) ||2428lstat(old_name, st))2429return-1;2430}2431if(!cached &&verify_index_match(*ce, st))2432returnerror("%s: does not match index", old_name);2433if(cached)2434 st_mode = (*ce)->ce_mode;2435}else if(stat_ret <0) {2436if(patch->is_new <0)2437goto is_new;2438returnerror("%s:%s", old_name,strerror(errno));2439}24402441if(!cached)2442 st_mode =ce_mode_from_stat(*ce, st->st_mode);24432444if(patch->is_new <0)2445 patch->is_new =0;2446if(!patch->old_mode)2447 patch->old_mode = st_mode;2448if((st_mode ^ patch->old_mode) & S_IFMT)2449returnerror("%s: wrong type", old_name);2450if(st_mode != patch->old_mode)2451fprintf(stderr,"warning:%shas type%o, expected%o\n",2452 old_name, st_mode, patch->old_mode);2453return0;24542455 is_new:2456 patch->is_new =1;2457 patch->is_delete =0;2458 patch->old_name = NULL;2459return0;2460}24612462static intcheck_patch(struct patch *patch)2463{2464struct stat st;2465const char*old_name = patch->old_name;2466const char*new_name = patch->new_name;2467const char*name = old_name ? old_name : new_name;2468struct cache_entry *ce = NULL;2469int ok_if_exists;2470int status;24712472 patch->rejected =1;/* we will drop this after we succeed */24732474 status =check_preimage(patch, &ce, &st);2475if(status)2476return status;2477 old_name = patch->old_name;24782479if(in_fn_table(new_name) == (struct patch *) -1)2480/*2481 * A type-change diff is always split into a patch to2482 * delete old, immediately followed by a patch to2483 * create new (see diff.c::run_diff()); in such a case2484 * it is Ok that the entry to be deleted by the2485 * previous patch is still in the working tree and in2486 * the index.2487 */2488 ok_if_exists =1;2489else2490 ok_if_exists =0;24912492if(new_name &&2493((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {2494if(check_index &&2495cache_name_pos(new_name,strlen(new_name)) >=0&&2496!ok_if_exists)2497returnerror("%s: already exists in index", new_name);2498if(!cached) {2499int err =check_to_create_blob(new_name, ok_if_exists);2500if(err)2501return err;2502}2503if(!patch->new_mode) {2504if(0< patch->is_new)2505 patch->new_mode = S_IFREG |0644;2506else2507 patch->new_mode = patch->old_mode;2508}2509}25102511if(new_name && old_name) {2512int same = !strcmp(old_name, new_name);2513if(!patch->new_mode)2514 patch->new_mode = patch->old_mode;2515if((patch->old_mode ^ patch->new_mode) & S_IFMT)2516returnerror("new mode (%o) of%sdoes not match old mode (%o)%s%s",2517 patch->new_mode, new_name, patch->old_mode,2518 same ?"":" of ", same ?"": old_name);2519}25202521if(apply_data(patch, &st, ce) <0)2522returnerror("%s: patch does not apply", name);2523 patch->rejected =0;2524return0;2525}25262527static intcheck_patch_list(struct patch *patch)2528{2529int err =0;25302531while(patch) {2532if(apply_verbosely)2533say_patch_name(stderr,2534"Checking patch ", patch,"...\n");2535 err |=check_patch(patch);2536 patch = patch->next;2537}2538return err;2539}25402541/* This function tries to read the sha1 from the current index */2542static intget_current_sha1(const char*path,unsigned char*sha1)2543{2544int pos;25452546if(read_cache() <0)2547return-1;2548 pos =cache_name_pos(path,strlen(path));2549if(pos <0)2550return-1;2551hashcpy(sha1, active_cache[pos]->sha1);2552return0;2553}25542555/* Build an index that contains the just the files needed for a 3way merge */2556static voidbuild_fake_ancestor(struct patch *list,const char*filename)2557{2558struct patch *patch;2559struct index_state result = {0};2560int fd;25612562/* Once we start supporting the reverse patch, it may be2563 * worth showing the new sha1 prefix, but until then...2564 */2565for(patch = list; patch; patch = patch->next) {2566const unsigned char*sha1_ptr;2567unsigned char sha1[20];2568struct cache_entry *ce;2569const char*name;25702571 name = patch->old_name ? patch->old_name : patch->new_name;2572if(0< patch->is_new)2573continue;2574else if(get_sha1(patch->old_sha1_prefix, sha1))2575/* git diff has no index line for mode/type changes */2576if(!patch->lines_added && !patch->lines_deleted) {2577if(get_current_sha1(patch->new_name, sha1) ||2578get_current_sha1(patch->old_name, sha1))2579die("mode change for%s, which is not "2580"in current HEAD", name);2581 sha1_ptr = sha1;2582}else2583die("sha1 information is lacking or useless "2584"(%s).", name);2585else2586 sha1_ptr = sha1;25872588 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);2589if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))2590die("Could not add%sto temporary index", name);2591}25922593 fd =open(filename, O_WRONLY | O_CREAT,0666);2594if(fd <0||write_index(&result, fd) ||close(fd))2595die("Could not write temporary index to%s", filename);25962597discard_index(&result);2598}25992600static voidstat_patch_list(struct patch *patch)2601{2602int files, adds, dels;26032604for(files = adds = dels =0; patch ; patch = patch->next) {2605 files++;2606 adds += patch->lines_added;2607 dels += patch->lines_deleted;2608show_stats(patch);2609}26102611printf("%dfiles changed,%dinsertions(+),%ddeletions(-)\n", files, adds, dels);2612}26132614static voidnumstat_patch_list(struct patch *patch)2615{2616for( ; patch; patch = patch->next) {2617const char*name;2618 name = patch->new_name ? patch->new_name : patch->old_name;2619if(patch->is_binary)2620printf("-\t-\t");2621else2622printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);2623write_name_quoted(name, stdout, line_termination);2624}2625}26262627static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)2628{2629if(mode)2630printf("%smode%06o%s\n", newdelete, mode, name);2631else2632printf("%s %s\n", newdelete, name);2633}26342635static voidshow_mode_change(struct patch *p,int show_name)2636{2637if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {2638if(show_name)2639printf(" mode change%06o =>%06o%s\n",2640 p->old_mode, p->new_mode, p->new_name);2641else2642printf(" mode change%06o =>%06o\n",2643 p->old_mode, p->new_mode);2644}2645}26462647static voidshow_rename_copy(struct patch *p)2648{2649const char*renamecopy = p->is_rename ?"rename":"copy";2650const char*old, *new;26512652/* Find common prefix */2653 old = p->old_name;2654new= p->new_name;2655while(1) {2656const char*slash_old, *slash_new;2657 slash_old =strchr(old,'/');2658 slash_new =strchr(new,'/');2659if(!slash_old ||2660!slash_new ||2661 slash_old - old != slash_new -new||2662memcmp(old,new, slash_new -new))2663break;2664 old = slash_old +1;2665new= slash_new +1;2666}2667/* p->old_name thru old is the common prefix, and old and new2668 * through the end of names are renames2669 */2670if(old != p->old_name)2671printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,2672(int)(old - p->old_name), p->old_name,2673 old,new, p->score);2674else2675printf("%s %s=>%s(%d%%)\n", renamecopy,2676 p->old_name, p->new_name, p->score);2677show_mode_change(p,0);2678}26792680static voidsummary_patch_list(struct patch *patch)2681{2682struct patch *p;26832684for(p = patch; p; p = p->next) {2685if(p->is_new)2686show_file_mode_name("create", p->new_mode, p->new_name);2687else if(p->is_delete)2688show_file_mode_name("delete", p->old_mode, p->old_name);2689else{2690if(p->is_rename || p->is_copy)2691show_rename_copy(p);2692else{2693if(p->score) {2694printf(" rewrite%s(%d%%)\n",2695 p->new_name, p->score);2696show_mode_change(p,0);2697}2698else2699show_mode_change(p,1);2700}2701}2702}2703}27042705static voidpatch_stats(struct patch *patch)2706{2707int lines = patch->lines_added + patch->lines_deleted;27082709if(lines > max_change)2710 max_change = lines;2711if(patch->old_name) {2712int len =quote_c_style(patch->old_name, NULL, NULL,0);2713if(!len)2714 len =strlen(patch->old_name);2715if(len > max_len)2716 max_len = len;2717}2718if(patch->new_name) {2719int len =quote_c_style(patch->new_name, NULL, NULL,0);2720if(!len)2721 len =strlen(patch->new_name);2722if(len > max_len)2723 max_len = len;2724}2725}27262727static voidremove_file(struct patch *patch,int rmdir_empty)2728{2729if(update_index) {2730if(remove_file_from_cache(patch->old_name) <0)2731die("unable to remove%sfrom index", patch->old_name);2732}2733if(!cached) {2734if(S_ISGITLINK(patch->old_mode)) {2735if(rmdir(patch->old_name))2736warning("unable to remove submodule%s",2737 patch->old_name);2738}else if(!unlink(patch->old_name) && rmdir_empty) {2739remove_path(patch->old_name);2740}2741}2742}27432744static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)2745{2746struct stat st;2747struct cache_entry *ce;2748int namelen =strlen(path);2749unsigned ce_size =cache_entry_size(namelen);27502751if(!update_index)2752return;27532754 ce =xcalloc(1, ce_size);2755memcpy(ce->name, path, namelen);2756 ce->ce_mode =create_ce_mode(mode);2757 ce->ce_flags = namelen;2758if(S_ISGITLINK(mode)) {2759const char*s = buf;27602761if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))2762die("corrupt patch for subproject%s", path);2763}else{2764if(!cached) {2765if(lstat(path, &st) <0)2766die("unable to stat newly created file%s",2767 path);2768fill_stat_cache_info(ce, &st);2769}2770if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)2771die("unable to create backing store for newly created file%s", path);2772}2773if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)2774die("unable to add cache entry for%s", path);2775}27762777static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)2778{2779int fd;2780struct strbuf nbuf;27812782if(S_ISGITLINK(mode)) {2783struct stat st;2784if(!lstat(path, &st) &&S_ISDIR(st.st_mode))2785return0;2786returnmkdir(path,0777);2787}27882789if(has_symlinks &&S_ISLNK(mode))2790/* Although buf:size is counted string, it also is NUL2791 * terminated.2792 */2793returnsymlink(buf, path);27942795 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);2796if(fd <0)2797return-1;27982799strbuf_init(&nbuf,0);2800if(convert_to_working_tree(path, buf, size, &nbuf)) {2801 size = nbuf.len;2802 buf = nbuf.buf;2803}2804write_or_die(fd, buf, size);2805strbuf_release(&nbuf);28062807if(close(fd) <0)2808die("closing file%s:%s", path,strerror(errno));2809return0;2810}28112812/*2813 * We optimistically assume that the directories exist,2814 * which is true 99% of the time anyway. If they don't,2815 * we create them and try again.2816 */2817static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)2818{2819if(cached)2820return;2821if(!try_create_file(path, mode, buf, size))2822return;28232824if(errno == ENOENT) {2825if(safe_create_leading_directories(path))2826return;2827if(!try_create_file(path, mode, buf, size))2828return;2829}28302831if(errno == EEXIST || errno == EACCES) {2832/* We may be trying to create a file where a directory2833 * used to be.2834 */2835struct stat st;2836if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))2837 errno = EEXIST;2838}28392840if(errno == EEXIST) {2841unsigned int nr =getpid();28422843for(;;) {2844const char*newpath;2845 newpath =mkpath("%s~%u", path, nr);2846if(!try_create_file(newpath, mode, buf, size)) {2847if(!rename(newpath, path))2848return;2849unlink(newpath);2850break;2851}2852if(errno != EEXIST)2853break;2854++nr;2855}2856}2857die("unable to write file%smode%o", path, mode);2858}28592860static voidcreate_file(struct patch *patch)2861{2862char*path = patch->new_name;2863unsigned mode = patch->new_mode;2864unsigned long size = patch->resultsize;2865char*buf = patch->result;28662867if(!mode)2868 mode = S_IFREG |0644;2869create_one_file(path, mode, buf, size);2870add_index_file(path, mode, buf, size);2871}28722873/* phase zero is to remove, phase one is to create */2874static voidwrite_out_one_result(struct patch *patch,int phase)2875{2876if(patch->is_delete >0) {2877if(phase ==0)2878remove_file(patch,1);2879return;2880}2881if(patch->is_new >0|| patch->is_copy) {2882if(phase ==1)2883create_file(patch);2884return;2885}2886/*2887 * Rename or modification boils down to the same2888 * thing: remove the old, write the new2889 */2890if(phase ==0)2891remove_file(patch, patch->is_rename);2892if(phase ==1)2893create_file(patch);2894}28952896static intwrite_out_one_reject(struct patch *patch)2897{2898FILE*rej;2899char namebuf[PATH_MAX];2900struct fragment *frag;2901int cnt =0;29022903for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {2904if(!frag->rejected)2905continue;2906 cnt++;2907}29082909if(!cnt) {2910if(apply_verbosely)2911say_patch_name(stderr,2912"Applied patch ", patch," cleanly.\n");2913return0;2914}29152916/* This should not happen, because a removal patch that leaves2917 * contents are marked "rejected" at the patch level.2918 */2919if(!patch->new_name)2920die("internal error");29212922/* Say this even without --verbose */2923say_patch_name(stderr,"Applying patch ", patch," with");2924fprintf(stderr,"%drejects...\n", cnt);29252926 cnt =strlen(patch->new_name);2927if(ARRAY_SIZE(namebuf) <= cnt +5) {2928 cnt =ARRAY_SIZE(namebuf) -5;2929fprintf(stderr,2930"warning: truncating .rej filename to %.*s.rej",2931 cnt -1, patch->new_name);2932}2933memcpy(namebuf, patch->new_name, cnt);2934memcpy(namebuf + cnt,".rej",5);29352936 rej =fopen(namebuf,"w");2937if(!rej)2938returnerror("cannot open%s:%s", namebuf,strerror(errno));29392940/* Normal git tools never deal with .rej, so do not pretend2941 * this is a git patch by saying --git nor give extended2942 * headers. While at it, maybe please "kompare" that wants2943 * the trailing TAB and some garbage at the end of line ;-).2944 */2945fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",2946 patch->new_name, patch->new_name);2947for(cnt =1, frag = patch->fragments;2948 frag;2949 cnt++, frag = frag->next) {2950if(!frag->rejected) {2951fprintf(stderr,"Hunk #%dapplied cleanly.\n", cnt);2952continue;2953}2954fprintf(stderr,"Rejected hunk #%d.\n", cnt);2955fprintf(rej,"%.*s", frag->size, frag->patch);2956if(frag->patch[frag->size-1] !='\n')2957fputc('\n', rej);2958}2959fclose(rej);2960return-1;2961}29622963static intwrite_out_results(struct patch *list,int skipped_patch)2964{2965int phase;2966int errs =0;2967struct patch *l;29682969if(!list && !skipped_patch)2970returnerror("No changes");29712972for(phase =0; phase <2; phase++) {2973 l = list;2974while(l) {2975if(l->rejected)2976 errs =1;2977else{2978write_out_one_result(l, phase);2979if(phase ==1&&write_out_one_reject(l))2980 errs =1;2981}2982 l = l->next;2983}2984}2985return errs;2986}29872988static struct lock_file lock_file;29892990static struct excludes {2991struct excludes *next;2992const char*path;2993} *excludes;29942995static intuse_patch(struct patch *p)2996{2997const char*pathname = p->new_name ? p->new_name : p->old_name;2998struct excludes *x = excludes;2999while(x) {3000if(fnmatch(x->path, pathname,0) ==0)3001return0;3002 x = x->next;3003}3004if(0< prefix_length) {3005int pathlen =strlen(pathname);3006if(pathlen <= prefix_length ||3007memcmp(prefix, pathname, prefix_length))3008return0;3009}3010return1;3011}30123013static voidprefix_one(char**name)3014{3015char*old_name = *name;3016if(!old_name)3017return;3018*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3019free(old_name);3020}30213022static voidprefix_patches(struct patch *p)3023{3024if(!prefix || p->is_toplevel_relative)3025return;3026for( ; p; p = p->next) {3027if(p->new_name == p->old_name) {3028char*prefixed = p->new_name;3029prefix_one(&prefixed);3030 p->new_name = p->old_name = prefixed;3031}3032else{3033prefix_one(&p->new_name);3034prefix_one(&p->old_name);3035}3036}3037}30383039#define INACCURATE_EOF (1<<0)3040#define RECOUNT (1<<1)30413042static intapply_patch(int fd,const char*filename,int options)3043{3044size_t offset;3045struct strbuf buf;3046struct patch *list = NULL, **listp = &list;3047int skipped_patch =0;30483049/* FIXME - memory leak when using multiple patch files as inputs */3050memset(&fn_table,0,sizeof(struct string_list));3051strbuf_init(&buf,0);3052 patch_input_file = filename;3053read_patch_file(&buf, fd);3054 offset =0;3055while(offset < buf.len) {3056struct patch *patch;3057int nr;30583059 patch =xcalloc(1,sizeof(*patch));3060 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3061 patch->recount = !!(options & RECOUNT);3062 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3063if(nr <0)3064break;3065if(apply_in_reverse)3066reverse_patches(patch);3067if(prefix)3068prefix_patches(patch);3069if(use_patch(patch)) {3070patch_stats(patch);3071*listp = patch;3072 listp = &patch->next;3073}3074else{3075/* perhaps free it a bit better? */3076free(patch);3077 skipped_patch++;3078}3079 offset += nr;3080}30813082if(whitespace_error && (ws_error_action == die_on_ws_error))3083 apply =0;30843085 update_index = check_index && apply;3086if(update_index && newfd <0)3087 newfd =hold_locked_index(&lock_file,1);30883089if(check_index) {3090if(read_cache() <0)3091die("unable to read index file");3092}30933094if((check || apply) &&3095check_patch_list(list) <0&&3096!apply_with_reject)3097exit(1);30983099if(apply &&write_out_results(list, skipped_patch))3100exit(1);31013102if(fake_ancestor)3103build_fake_ancestor(list, fake_ancestor);31043105if(diffstat)3106stat_patch_list(list);31073108if(numstat)3109numstat_patch_list(list);31103111if(summary)3112summary_patch_list(list);31133114strbuf_release(&buf);3115return0;3116}31173118static intgit_apply_config(const char*var,const char*value,void*cb)3119{3120if(!strcmp(var,"apply.whitespace"))3121returngit_config_string(&apply_default_whitespace, var, value);3122returngit_default_config(var, value, cb);3123}312431253126intcmd_apply(int argc,const char**argv,const char*unused_prefix)3127{3128int i;3129int read_stdin =1;3130int options =0;3131int errs =0;3132int is_not_gitdir;31333134const char*whitespace_option = NULL;31353136 prefix =setup_git_directory_gently(&is_not_gitdir);3137 prefix_length = prefix ?strlen(prefix) :0;3138git_config(git_apply_config, NULL);3139if(apply_default_whitespace)3140parse_whitespace_option(apply_default_whitespace);31413142for(i =1; i < argc; i++) {3143const char*arg = argv[i];3144char*end;3145int fd;31463147if(!strcmp(arg,"-")) {3148 errs |=apply_patch(0,"<stdin>", options);3149 read_stdin =0;3150continue;3151}3152if(!prefixcmp(arg,"--exclude=")) {3153struct excludes *x =xmalloc(sizeof(*x));3154 x->path = arg +10;3155 x->next = excludes;3156 excludes = x;3157continue;3158}3159if(!prefixcmp(arg,"-p")) {3160 p_value =atoi(arg +2);3161 p_value_known =1;3162continue;3163}3164if(!strcmp(arg,"--no-add")) {3165 no_add =1;3166continue;3167}3168if(!strcmp(arg,"--stat")) {3169 apply =0;3170 diffstat =1;3171continue;3172}3173if(!strcmp(arg,"--allow-binary-replacement") ||3174!strcmp(arg,"--binary")) {3175continue;/* now no-op */3176}3177if(!strcmp(arg,"--numstat")) {3178 apply =0;3179 numstat =1;3180continue;3181}3182if(!strcmp(arg,"--summary")) {3183 apply =0;3184 summary =1;3185continue;3186}3187if(!strcmp(arg,"--check")) {3188 apply =0;3189 check =1;3190continue;3191}3192if(!strcmp(arg,"--index")) {3193if(is_not_gitdir)3194die("--index outside a repository");3195 check_index =1;3196continue;3197}3198if(!strcmp(arg,"--cached")) {3199if(is_not_gitdir)3200die("--cached outside a repository");3201 check_index =1;3202 cached =1;3203continue;3204}3205if(!strcmp(arg,"--apply")) {3206 apply =1;3207continue;3208}3209if(!strcmp(arg,"--build-fake-ancestor")) {3210 apply =0;3211if(++i >= argc)3212die("need a filename");3213 fake_ancestor = argv[i];3214continue;3215}3216if(!strcmp(arg,"-z")) {3217 line_termination =0;3218continue;3219}3220if(!prefixcmp(arg,"-C")) {3221 p_context =strtoul(arg +2, &end,0);3222if(*end !='\0')3223die("unrecognized context count '%s'", arg +2);3224continue;3225}3226if(!prefixcmp(arg,"--whitespace=")) {3227 whitespace_option = arg +13;3228parse_whitespace_option(arg +13);3229continue;3230}3231if(!strcmp(arg,"-R") || !strcmp(arg,"--reverse")) {3232 apply_in_reverse =1;3233continue;3234}3235if(!strcmp(arg,"--unidiff-zero")) {3236 unidiff_zero =1;3237continue;3238}3239if(!strcmp(arg,"--reject")) {3240 apply = apply_with_reject = apply_verbosely =1;3241continue;3242}3243if(!strcmp(arg,"-v") || !strcmp(arg,"--verbose")) {3244 apply_verbosely =1;3245continue;3246}3247if(!strcmp(arg,"--inaccurate-eof")) {3248 options |= INACCURATE_EOF;3249continue;3250}3251if(!strcmp(arg,"--recount")) {3252 options |= RECOUNT;3253continue;3254}3255if(!prefixcmp(arg,"--directory=")) {3256 arg +=strlen("--directory=");3257 root_len =strlen(arg);3258if(root_len && arg[root_len -1] !='/') {3259char*new_root;3260 root = new_root =xmalloc(root_len +2);3261strcpy(new_root, arg);3262strcpy(new_root + root_len++,"/");3263}else3264 root = arg;3265continue;3266}3267if(0< prefix_length)3268 arg =prefix_filename(prefix, prefix_length, arg);32693270 fd =open(arg, O_RDONLY);3271if(fd <0)3272die("can't open patch '%s':%s", arg,strerror(errno));3273 read_stdin =0;3274set_default_whitespace_mode(whitespace_option);3275 errs |=apply_patch(fd, arg, options);3276close(fd);3277}3278set_default_whitespace_mode(whitespace_option);3279if(read_stdin)3280 errs |=apply_patch(0,"<stdin>", options);3281if(whitespace_error) {3282if(squelch_whitespace_errors &&3283 squelch_whitespace_errors < whitespace_error) {3284int squelched =3285 whitespace_error - squelch_whitespace_errors;3286fprintf(stderr,"warning: squelched%d"3287"whitespace error%s\n",3288 squelched,3289 squelched ==1?"":"s");3290}3291if(ws_error_action == die_on_ws_error)3292die("%dline%sadd%swhitespace errors.",3293 whitespace_error,3294 whitespace_error ==1?"":"s",3295 whitespace_error ==1?"s":"");3296if(applied_after_fixing_ws && apply)3297fprintf(stderr,"warning:%dline%sapplied after"3298" fixing whitespace errors.\n",3299 applied_after_fixing_ws,3300 applied_after_fixing_ws ==1?"":"s");3301else if(whitespace_error)3302fprintf(stderr,"warning:%dline%sadd%swhitespace errors.\n",3303 whitespace_error,3304 whitespace_error ==1?"":"s",3305 whitespace_error ==1?"s":"");3306}33073308if(update_index) {3309if(write_cache(newfd, active_cache, active_nr) ||3310commit_locked_index(&lock_file))3311die("Unable to write new index file");3312}33133314return!!errs;3315}