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); 813if(patch->def_name && root) { 814char*s =xmalloc(root_len +strlen(patch->def_name) +1); 815strcpy(s, root); 816strcpy(s + root_len, patch->def_name); 817free(patch->def_name); 818 patch->def_name = s; 819} 820 821 line += len; 822 size -= len; 823 linenr++; 824for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) { 825static const struct opentry { 826const char*str; 827int(*fn)(const char*,struct patch *); 828} optable[] = { 829{"@@ -", gitdiff_hdrend }, 830{"--- ", gitdiff_oldname }, 831{"+++ ", gitdiff_newname }, 832{"old mode ", gitdiff_oldmode }, 833{"new mode ", gitdiff_newmode }, 834{"deleted file mode ", gitdiff_delete }, 835{"new file mode ", gitdiff_newfile }, 836{"copy from ", gitdiff_copysrc }, 837{"copy to ", gitdiff_copydst }, 838{"rename old ", gitdiff_renamesrc }, 839{"rename new ", gitdiff_renamedst }, 840{"rename from ", gitdiff_renamesrc }, 841{"rename to ", gitdiff_renamedst }, 842{"similarity index ", gitdiff_similarity }, 843{"dissimilarity index ", gitdiff_dissimilarity }, 844{"index ", gitdiff_index }, 845{"", gitdiff_unrecognized }, 846}; 847int i; 848 849 len =linelen(line, size); 850if(!len || line[len-1] !='\n') 851break; 852for(i =0; i <ARRAY_SIZE(optable); i++) { 853const struct opentry *p = optable + i; 854int oplen =strlen(p->str); 855if(len < oplen ||memcmp(p->str, line, oplen)) 856continue; 857if(p->fn(line + oplen, patch) <0) 858return offset; 859break; 860} 861} 862 863return offset; 864} 865 866static intparse_num(const char*line,unsigned long*p) 867{ 868char*ptr; 869 870if(!isdigit(*line)) 871return0; 872*p =strtoul(line, &ptr,10); 873return ptr - line; 874} 875 876static intparse_range(const char*line,int len,int offset,const char*expect, 877unsigned long*p1,unsigned long*p2) 878{ 879int digits, ex; 880 881if(offset <0|| offset >= len) 882return-1; 883 line += offset; 884 len -= offset; 885 886 digits =parse_num(line, p1); 887if(!digits) 888return-1; 889 890 offset += digits; 891 line += digits; 892 len -= digits; 893 894*p2 =1; 895if(*line ==',') { 896 digits =parse_num(line+1, p2); 897if(!digits) 898return-1; 899 900 offset += digits+1; 901 line += digits+1; 902 len -= digits+1; 903} 904 905 ex =strlen(expect); 906if(ex > len) 907return-1; 908if(memcmp(line, expect, ex)) 909return-1; 910 911return offset + ex; 912} 913 914static voidrecount_diff(char*line,int size,struct fragment *fragment) 915{ 916int oldlines =0, newlines =0, ret =0; 917 918if(size <1) { 919warning("recount: ignore empty hunk"); 920return; 921} 922 923for(;;) { 924int len =linelen(line, size); 925 size -= len; 926 line += len; 927 928if(size <1) 929break; 930 931switch(*line) { 932case' ':case'\n': 933 newlines++; 934/* fall through */ 935case'-': 936 oldlines++; 937continue; 938case'+': 939 newlines++; 940continue; 941case'\\': 942continue; 943case'@': 944 ret = size <3||prefixcmp(line,"@@ "); 945break; 946case'd': 947 ret = size <5||prefixcmp(line,"diff "); 948break; 949default: 950 ret = -1; 951break; 952} 953if(ret) { 954warning("recount: unexpected line: %.*s", 955(int)linelen(line, size), line); 956return; 957} 958break; 959} 960 fragment->oldlines = oldlines; 961 fragment->newlines = newlines; 962} 963 964/* 965 * Parse a unified diff fragment header of the 966 * form "@@ -a,b +c,d @@" 967 */ 968static intparse_fragment_header(char*line,int len,struct fragment *fragment) 969{ 970int offset; 971 972if(!len || line[len-1] !='\n') 973return-1; 974 975/* Figure out the number of lines in a fragment */ 976 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines); 977 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines); 978 979return offset; 980} 981 982static intfind_header(char*line,unsigned long size,int*hdrsize,struct patch *patch) 983{ 984unsigned long offset, len; 985 986 patch->is_toplevel_relative =0; 987 patch->is_rename = patch->is_copy =0; 988 patch->is_new = patch->is_delete = -1; 989 patch->old_mode = patch->new_mode =0; 990 patch->old_name = patch->new_name = NULL; 991for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) { 992unsigned long nextlen; 993 994 len =linelen(line, size); 995if(!len) 996break; 997 998/* Testing this early allows us to take a few shortcuts.. */ 999if(len <6)1000continue;10011002/*1003 * Make sure we don't find any unconnected patch fragments.1004 * That's a sign that we didn't find a header, and that a1005 * patch has become corrupted/broken up.1006 */1007if(!memcmp("@@ -", line,4)) {1008struct fragment dummy;1009if(parse_fragment_header(line, len, &dummy) <0)1010continue;1011die("patch fragment without header at line%d: %.*s",1012 linenr, (int)len-1, line);1013}10141015if(size < len +6)1016break;10171018/*1019 * Git patch? It might not have a real patch, just a rename1020 * or mode change, so we handle that specially1021 */1022if(!memcmp("diff --git ", line,11)) {1023int git_hdr_len =parse_git_header(line, len, size, patch);1024if(git_hdr_len <= len)1025continue;1026if(!patch->old_name && !patch->new_name) {1027if(!patch->def_name)1028die("git diff header lacks filename information (line%d)", linenr);1029 patch->old_name = patch->new_name = patch->def_name;1030}1031 patch->is_toplevel_relative =1;1032*hdrsize = git_hdr_len;1033return offset;1034}10351036/* --- followed by +++ ? */1037if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1038continue;10391040/*1041 * We only accept unified patches, so we want it to1042 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1043 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1044 */1045 nextlen =linelen(line + len, size - len);1046if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1047continue;10481049/* Ok, we'll consider it a patch */1050parse_traditional_patch(line, line+len, patch);1051*hdrsize = len + nextlen;1052 linenr +=2;1053return offset;1054}1055return-1;1056}10571058static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1059{1060char*err;1061unsigned result =ws_check(line +1, len -1, ws_rule);1062if(!result)1063return;10641065 whitespace_error++;1066if(squelch_whitespace_errors &&1067 squelch_whitespace_errors < whitespace_error)1068;1069else{1070 err =whitespace_error_string(result);1071fprintf(stderr,"%s:%d:%s.\n%.*s\n",1072 patch_input_file, linenr, err, len -2, line +1);1073free(err);1074}1075}10761077/*1078 * Parse a unified diff. Note that this really needs to parse each1079 * fragment separately, since the only way to know the difference1080 * between a "---" that is part of a patch, and a "---" that starts1081 * the next patch is to look at the line counts..1082 */1083static intparse_fragment(char*line,unsigned long size,1084struct patch *patch,struct fragment *fragment)1085{1086int added, deleted;1087int len =linelen(line, size), offset;1088unsigned long oldlines, newlines;1089unsigned long leading, trailing;10901091 offset =parse_fragment_header(line, len, fragment);1092if(offset <0)1093return-1;1094if(offset >0&& patch->recount)1095recount_diff(line + offset, size - offset, fragment);1096 oldlines = fragment->oldlines;1097 newlines = fragment->newlines;1098 leading =0;1099 trailing =0;11001101/* Parse the thing.. */1102 line += len;1103 size -= len;1104 linenr++;1105 added = deleted =0;1106for(offset = len;11070< size;1108 offset += len, size -= len, line += len, linenr++) {1109if(!oldlines && !newlines)1110break;1111 len =linelen(line, size);1112if(!len || line[len-1] !='\n')1113return-1;1114switch(*line) {1115default:1116return-1;1117case'\n':/* newer GNU diff, an empty context line */1118case' ':1119 oldlines--;1120 newlines--;1121if(!deleted && !added)1122 leading++;1123 trailing++;1124break;1125case'-':1126if(apply_in_reverse &&1127 ws_error_action != nowarn_ws_error)1128check_whitespace(line, len, patch->ws_rule);1129 deleted++;1130 oldlines--;1131 trailing =0;1132break;1133case'+':1134if(!apply_in_reverse &&1135 ws_error_action != nowarn_ws_error)1136check_whitespace(line, len, patch->ws_rule);1137 added++;1138 newlines--;1139 trailing =0;1140break;11411142/*1143 * We allow "\ No newline at end of file". Depending1144 * on locale settings when the patch was produced we1145 * don't know what this line looks like. The only1146 * thing we do know is that it begins with "\ ".1147 * Checking for 12 is just for sanity check -- any1148 * l10n of "\ No newline..." is at least that long.1149 */1150case'\\':1151if(len <12||memcmp(line,"\\",2))1152return-1;1153break;1154}1155}1156if(oldlines || newlines)1157return-1;1158 fragment->leading = leading;1159 fragment->trailing = trailing;11601161/*1162 * If a fragment ends with an incomplete line, we failed to include1163 * it in the above loop because we hit oldlines == newlines == 01164 * before seeing it.1165 */1166if(12< size && !memcmp(line,"\\",2))1167 offset +=linelen(line, size);11681169 patch->lines_added += added;1170 patch->lines_deleted += deleted;11711172if(0< patch->is_new && oldlines)1173returnerror("new file depends on old contents");1174if(0< patch->is_delete && newlines)1175returnerror("deleted file still has contents");1176return offset;1177}11781179static intparse_single_patch(char*line,unsigned long size,struct patch *patch)1180{1181unsigned long offset =0;1182unsigned long oldlines =0, newlines =0, context =0;1183struct fragment **fragp = &patch->fragments;11841185while(size >4&& !memcmp(line,"@@ -",4)) {1186struct fragment *fragment;1187int len;11881189 fragment =xcalloc(1,sizeof(*fragment));1190 len =parse_fragment(line, size, patch, fragment);1191if(len <=0)1192die("corrupt patch at line%d", linenr);1193 fragment->patch = line;1194 fragment->size = len;1195 oldlines += fragment->oldlines;1196 newlines += fragment->newlines;1197 context += fragment->leading + fragment->trailing;11981199*fragp = fragment;1200 fragp = &fragment->next;12011202 offset += len;1203 line += len;1204 size -= len;1205}12061207/*1208 * If something was removed (i.e. we have old-lines) it cannot1209 * be creation, and if something was added it cannot be1210 * deletion. However, the reverse is not true; --unified=01211 * patches that only add are not necessarily creation even1212 * though they do not have any old lines, and ones that only1213 * delete are not necessarily deletion.1214 *1215 * Unfortunately, a real creation/deletion patch do _not_ have1216 * any context line by definition, so we cannot safely tell it1217 * apart with --unified=0 insanity. At least if the patch has1218 * more than one hunk it is not creation or deletion.1219 */1220if(patch->is_new <0&&1221(oldlines || (patch->fragments && patch->fragments->next)))1222 patch->is_new =0;1223if(patch->is_delete <0&&1224(newlines || (patch->fragments && patch->fragments->next)))1225 patch->is_delete =0;12261227if(0< patch->is_new && oldlines)1228die("new file%sdepends on old contents", patch->new_name);1229if(0< patch->is_delete && newlines)1230die("deleted file%sstill has contents", patch->old_name);1231if(!patch->is_delete && !newlines && context)1232fprintf(stderr,"** warning: file%sbecomes empty but "1233"is not deleted\n", patch->new_name);12341235return offset;1236}12371238staticinlineintmetadata_changes(struct patch *patch)1239{1240return patch->is_rename >0||1241 patch->is_copy >0||1242 patch->is_new >0||1243 patch->is_delete ||1244(patch->old_mode && patch->new_mode &&1245 patch->old_mode != patch->new_mode);1246}12471248static char*inflate_it(const void*data,unsigned long size,1249unsigned long inflated_size)1250{1251 z_stream stream;1252void*out;1253int st;12541255memset(&stream,0,sizeof(stream));12561257 stream.next_in = (unsigned char*)data;1258 stream.avail_in = size;1259 stream.next_out = out =xmalloc(inflated_size);1260 stream.avail_out = inflated_size;1261inflateInit(&stream);1262 st =inflate(&stream, Z_FINISH);1263if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1264free(out);1265return NULL;1266}1267return out;1268}12691270static struct fragment *parse_binary_hunk(char**buf_p,1271unsigned long*sz_p,1272int*status_p,1273int*used_p)1274{1275/*1276 * Expect a line that begins with binary patch method ("literal"1277 * or "delta"), followed by the length of data before deflating.1278 * a sequence of 'length-byte' followed by base-85 encoded data1279 * should follow, terminated by a newline.1280 *1281 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1282 * and we would limit the patch line to 66 characters,1283 * so one line can fit up to 13 groups that would decode1284 * to 52 bytes max. The length byte 'A'-'Z' corresponds1285 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1286 */1287int llen, used;1288unsigned long size = *sz_p;1289char*buffer = *buf_p;1290int patch_method;1291unsigned long origlen;1292char*data = NULL;1293int hunk_size =0;1294struct fragment *frag;12951296 llen =linelen(buffer, size);1297 used = llen;12981299*status_p =0;13001301if(!prefixcmp(buffer,"delta ")) {1302 patch_method = BINARY_DELTA_DEFLATED;1303 origlen =strtoul(buffer +6, NULL,10);1304}1305else if(!prefixcmp(buffer,"literal ")) {1306 patch_method = BINARY_LITERAL_DEFLATED;1307 origlen =strtoul(buffer +8, NULL,10);1308}1309else1310return NULL;13111312 linenr++;1313 buffer += llen;1314while(1) {1315int byte_length, max_byte_length, newsize;1316 llen =linelen(buffer, size);1317 used += llen;1318 linenr++;1319if(llen ==1) {1320/* consume the blank line */1321 buffer++;1322 size--;1323break;1324}1325/*1326 * Minimum line is "A00000\n" which is 7-byte long,1327 * and the line length must be multiple of 5 plus 2.1328 */1329if((llen <7) || (llen-2) %5)1330goto corrupt;1331 max_byte_length = (llen -2) /5*4;1332 byte_length = *buffer;1333if('A'<= byte_length && byte_length <='Z')1334 byte_length = byte_length -'A'+1;1335else if('a'<= byte_length && byte_length <='z')1336 byte_length = byte_length -'a'+27;1337else1338goto corrupt;1339/* if the input length was not multiple of 4, we would1340 * have filler at the end but the filler should never1341 * exceed 3 bytes1342 */1343if(max_byte_length < byte_length ||1344 byte_length <= max_byte_length -4)1345goto corrupt;1346 newsize = hunk_size + byte_length;1347 data =xrealloc(data, newsize);1348if(decode_85(data + hunk_size, buffer +1, byte_length))1349goto corrupt;1350 hunk_size = newsize;1351 buffer += llen;1352 size -= llen;1353}13541355 frag =xcalloc(1,sizeof(*frag));1356 frag->patch =inflate_it(data, hunk_size, origlen);1357if(!frag->patch)1358goto corrupt;1359free(data);1360 frag->size = origlen;1361*buf_p = buffer;1362*sz_p = size;1363*used_p = used;1364 frag->binary_patch_method = patch_method;1365return frag;13661367 corrupt:1368free(data);1369*status_p = -1;1370error("corrupt binary patch at line%d: %.*s",1371 linenr-1, llen-1, buffer);1372return NULL;1373}13741375static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1376{1377/*1378 * We have read "GIT binary patch\n"; what follows is a line1379 * that says the patch method (currently, either "literal" or1380 * "delta") and the length of data before deflating; a1381 * sequence of 'length-byte' followed by base-85 encoded data1382 * follows.1383 *1384 * When a binary patch is reversible, there is another binary1385 * hunk in the same format, starting with patch method (either1386 * "literal" or "delta") with the length of data, and a sequence1387 * of length-byte + base-85 encoded data, terminated with another1388 * empty line. This data, when applied to the postimage, produces1389 * the preimage.1390 */1391struct fragment *forward;1392struct fragment *reverse;1393int status;1394int used, used_1;13951396 forward =parse_binary_hunk(&buffer, &size, &status, &used);1397if(!forward && !status)1398/* there has to be one hunk (forward hunk) */1399returnerror("unrecognized binary patch at line%d", linenr-1);1400if(status)1401/* otherwise we already gave an error message */1402return status;14031404 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1405if(reverse)1406 used += used_1;1407else if(status) {1408/*1409 * Not having reverse hunk is not an error, but having1410 * a corrupt reverse hunk is.1411 */1412free((void*) forward->patch);1413free(forward);1414return status;1415}1416 forward->next = reverse;1417 patch->fragments = forward;1418 patch->is_binary =1;1419return used;1420}14211422static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1423{1424int hdrsize, patchsize;1425int offset =find_header(buffer, size, &hdrsize, patch);14261427if(offset <0)1428return offset;14291430 patch->ws_rule =whitespace_rule(patch->new_name1431? patch->new_name1432: patch->old_name);14331434 patchsize =parse_single_patch(buffer + offset + hdrsize,1435 size - offset - hdrsize, patch);14361437if(!patchsize) {1438static const char*binhdr[] = {1439"Binary files ",1440"Files ",1441 NULL,1442};1443static const char git_binary[] ="GIT binary patch\n";1444int i;1445int hd = hdrsize + offset;1446unsigned long llen =linelen(buffer + hd, size - hd);14471448if(llen ==sizeof(git_binary) -1&&1449!memcmp(git_binary, buffer + hd, llen)) {1450int used;1451 linenr++;1452 used =parse_binary(buffer + hd + llen,1453 size - hd - llen, patch);1454if(used)1455 patchsize = used + llen;1456else1457 patchsize =0;1458}1459else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1460for(i =0; binhdr[i]; i++) {1461int len =strlen(binhdr[i]);1462if(len < size - hd &&1463!memcmp(binhdr[i], buffer + hd, len)) {1464 linenr++;1465 patch->is_binary =1;1466 patchsize = llen;1467break;1468}1469}1470}14711472/* Empty patch cannot be applied if it is a text patch1473 * without metadata change. A binary patch appears1474 * empty to us here.1475 */1476if((apply || check) &&1477(!patch->is_binary && !metadata_changes(patch)))1478die("patch with only garbage at line%d", linenr);1479}14801481return offset + hdrsize + patchsize;1482}14831484#define swap(a,b) myswap((a),(b),sizeof(a))14851486#define myswap(a, b, size) do { \1487 unsigned char mytmp[size]; \1488 memcpy(mytmp, &a, size); \1489 memcpy(&a, &b, size); \1490 memcpy(&b, mytmp, size); \1491} while (0)14921493static voidreverse_patches(struct patch *p)1494{1495for(; p; p = p->next) {1496struct fragment *frag = p->fragments;14971498swap(p->new_name, p->old_name);1499swap(p->new_mode, p->old_mode);1500swap(p->is_new, p->is_delete);1501swap(p->lines_added, p->lines_deleted);1502swap(p->old_sha1_prefix, p->new_sha1_prefix);15031504for(; frag; frag = frag->next) {1505swap(frag->newpos, frag->oldpos);1506swap(frag->newlines, frag->oldlines);1507}1508}1509}15101511static const char pluses[] =1512"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";1513static const char minuses[]=1514"----------------------------------------------------------------------";15151516static voidshow_stats(struct patch *patch)1517{1518struct strbuf qname;1519char*cp = patch->new_name ? patch->new_name : patch->old_name;1520int max, add, del;15211522strbuf_init(&qname,0);1523quote_c_style(cp, &qname, NULL,0);15241525/*1526 * "scale" the filename1527 */1528 max = max_len;1529if(max >50)1530 max =50;15311532if(qname.len > max) {1533 cp =strchr(qname.buf + qname.len +3- max,'/');1534if(!cp)1535 cp = qname.buf + qname.len +3- max;1536strbuf_splice(&qname,0, cp - qname.buf,"...",3);1537}15381539if(patch->is_binary) {1540printf(" %-*s | Bin\n", max, qname.buf);1541strbuf_release(&qname);1542return;1543}15441545printf(" %-*s |", max, qname.buf);1546strbuf_release(&qname);15471548/*1549 * scale the add/delete1550 */1551 max = max + max_change >70?70- max : max_change;1552 add = patch->lines_added;1553 del = patch->lines_deleted;15541555if(max_change >0) {1556int total = ((add + del) * max + max_change /2) / max_change;1557 add = (add * max + max_change /2) / max_change;1558 del = total - add;1559}1560printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,1561 add, pluses, del, minuses);1562}15631564static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)1565{1566switch(st->st_mode & S_IFMT) {1567case S_IFLNK:1568strbuf_grow(buf, st->st_size);1569if(readlink(path, buf->buf, st->st_size) != st->st_size)1570return-1;1571strbuf_setlen(buf, st->st_size);1572return0;1573case S_IFREG:1574if(strbuf_read_file(buf, path, st->st_size) != st->st_size)1575returnerror("unable to open or read%s", path);1576convert_to_git(path, buf->buf, buf->len, buf,0);1577return0;1578default:1579return-1;1580}1581}15821583static voidupdate_pre_post_images(struct image *preimage,1584struct image *postimage,1585char*buf,1586size_t len)1587{1588int i, ctx;1589char*new, *old, *fixed;1590struct image fixed_preimage;15911592/*1593 * Update the preimage with whitespace fixes. Note that we1594 * are not losing preimage->buf -- apply_one_fragment() will1595 * free "oldlines".1596 */1597prepare_image(&fixed_preimage, buf, len,1);1598assert(fixed_preimage.nr == preimage->nr);1599for(i =0; i < preimage->nr; i++)1600 fixed_preimage.line[i].flag = preimage->line[i].flag;1601free(preimage->line_allocated);1602*preimage = fixed_preimage;16031604/*1605 * Adjust the common context lines in postimage, in place.1606 * This is possible because whitespace fixing does not make1607 * the string grow.1608 */1609new= old = postimage->buf;1610 fixed = preimage->buf;1611for(i = ctx =0; i < postimage->nr; i++) {1612size_t len = postimage->line[i].len;1613if(!(postimage->line[i].flag & LINE_COMMON)) {1614/* an added line -- no counterparts in preimage */1615memmove(new, old, len);1616 old += len;1617new+= len;1618continue;1619}16201621/* a common context -- skip it in the original postimage */1622 old += len;16231624/* and find the corresponding one in the fixed preimage */1625while(ctx < preimage->nr &&1626!(preimage->line[ctx].flag & LINE_COMMON)) {1627 fixed += preimage->line[ctx].len;1628 ctx++;1629}1630if(preimage->nr <= ctx)1631die("oops");16321633/* and copy it in, while fixing the line length */1634 len = preimage->line[ctx].len;1635memcpy(new, fixed, len);1636new+= len;1637 fixed += len;1638 postimage->line[i].len = len;1639 ctx++;1640}16411642/* Fix the length of the whole thing */1643 postimage->len =new- postimage->buf;1644}16451646static intmatch_fragment(struct image *img,1647struct image *preimage,1648struct image *postimage,1649unsigned longtry,1650int try_lno,1651unsigned ws_rule,1652int match_beginning,int match_end)1653{1654int i;1655char*fixed_buf, *buf, *orig, *target;16561657if(preimage->nr + try_lno > img->nr)1658return0;16591660if(match_beginning && try_lno)1661return0;16621663if(match_end && preimage->nr + try_lno != img->nr)1664return0;16651666/* Quick hash check */1667for(i =0; i < preimage->nr; i++)1668if(preimage->line[i].hash != img->line[try_lno + i].hash)1669return0;16701671/*1672 * Do we have an exact match? If we were told to match1673 * at the end, size must be exactly at try+fragsize,1674 * otherwise try+fragsize must be still within the preimage,1675 * and either case, the old piece should match the preimage1676 * exactly.1677 */1678if((match_end1679? (try+ preimage->len == img->len)1680: (try+ preimage->len <= img->len)) &&1681!memcmp(img->buf +try, preimage->buf, preimage->len))1682return1;16831684if(ws_error_action != correct_ws_error)1685return0;16861687/*1688 * The hunk does not apply byte-by-byte, but the hash says1689 * it might with whitespace fuzz.1690 */1691 fixed_buf =xmalloc(preimage->len +1);1692 buf = fixed_buf;1693 orig = preimage->buf;1694 target = img->buf +try;1695for(i =0; i < preimage->nr; i++) {1696size_t fixlen;/* length after fixing the preimage */1697size_t oldlen = preimage->line[i].len;1698size_t tgtlen = img->line[try_lno + i].len;1699size_t tgtfixlen;/* length after fixing the target line */1700char tgtfixbuf[1024], *tgtfix;1701int match;17021703/* Try fixing the line in the preimage */1704 fixlen =ws_fix_copy(buf, orig, oldlen, ws_rule, NULL);17051706/* Try fixing the line in the target */1707if(sizeof(tgtfixbuf) > tgtlen)1708 tgtfix = tgtfixbuf;1709else1710 tgtfix =xmalloc(tgtlen);1711 tgtfixlen =ws_fix_copy(tgtfix, target, tgtlen, ws_rule, NULL);17121713/*1714 * If they match, either the preimage was based on1715 * a version before our tree fixed whitespace breakage,1716 * or we are lacking a whitespace-fix patch the tree1717 * the preimage was based on already had (i.e. target1718 * has whitespace breakage, the preimage doesn't).1719 * In either case, we are fixing the whitespace breakages1720 * so we might as well take the fix together with their1721 * real change.1722 */1723 match = (tgtfixlen == fixlen && !memcmp(tgtfix, buf, fixlen));17241725if(tgtfix != tgtfixbuf)1726free(tgtfix);1727if(!match)1728goto unmatch_exit;17291730 orig += oldlen;1731 buf += fixlen;1732 target += tgtlen;1733}17341735/*1736 * Yes, the preimage is based on an older version that still1737 * has whitespace breakages unfixed, and fixing them makes the1738 * hunk match. Update the context lines in the postimage.1739 */1740update_pre_post_images(preimage, postimage,1741 fixed_buf, buf - fixed_buf);1742return1;17431744 unmatch_exit:1745free(fixed_buf);1746return0;1747}17481749static intfind_pos(struct image *img,1750struct image *preimage,1751struct image *postimage,1752int line,1753unsigned ws_rule,1754int match_beginning,int match_end)1755{1756int i;1757unsigned long backwards, forwards,try;1758int backwards_lno, forwards_lno, try_lno;17591760if(preimage->nr > img->nr)1761return-1;17621763/*1764 * If match_begining or match_end is specified, there is no1765 * point starting from a wrong line that will never match and1766 * wander around and wait for a match at the specified end.1767 */1768if(match_beginning)1769 line =0;1770else if(match_end)1771 line = img->nr - preimage->nr;17721773if(line > img->nr)1774 line = img->nr;17751776try=0;1777for(i =0; i < line; i++)1778try+= img->line[i].len;17791780/*1781 * There's probably some smart way to do this, but I'll leave1782 * that to the smart and beautiful people. I'm simple and stupid.1783 */1784 backwards =try;1785 backwards_lno = line;1786 forwards =try;1787 forwards_lno = line;1788 try_lno = line;17891790for(i =0; ; i++) {1791if(match_fragment(img, preimage, postimage,1792try, try_lno, ws_rule,1793 match_beginning, match_end))1794return try_lno;17951796 again:1797if(backwards_lno ==0&& forwards_lno == img->nr)1798break;17991800if(i &1) {1801if(backwards_lno ==0) {1802 i++;1803goto again;1804}1805 backwards_lno--;1806 backwards -= img->line[backwards_lno].len;1807try= backwards;1808 try_lno = backwards_lno;1809}else{1810if(forwards_lno == img->nr) {1811 i++;1812goto again;1813}1814 forwards += img->line[forwards_lno].len;1815 forwards_lno++;1816try= forwards;1817 try_lno = forwards_lno;1818}18191820}1821return-1;1822}18231824static voidremove_first_line(struct image *img)1825{1826 img->buf += img->line[0].len;1827 img->len -= img->line[0].len;1828 img->line++;1829 img->nr--;1830}18311832static voidremove_last_line(struct image *img)1833{1834 img->len -= img->line[--img->nr].len;1835}18361837static voidupdate_image(struct image *img,1838int applied_pos,1839struct image *preimage,1840struct image *postimage)1841{1842/*1843 * remove the copy of preimage at offset in img1844 * and replace it with postimage1845 */1846int i, nr;1847size_t remove_count, insert_count, applied_at =0;1848char*result;18491850for(i =0; i < applied_pos; i++)1851 applied_at += img->line[i].len;18521853 remove_count =0;1854for(i =0; i < preimage->nr; i++)1855 remove_count += img->line[applied_pos + i].len;1856 insert_count = postimage->len;18571858/* Adjust the contents */1859 result =xmalloc(img->len + insert_count - remove_count +1);1860memcpy(result, img->buf, applied_at);1861memcpy(result + applied_at, postimage->buf, postimage->len);1862memcpy(result + applied_at + postimage->len,1863 img->buf + (applied_at + remove_count),1864 img->len - (applied_at + remove_count));1865free(img->buf);1866 img->buf = result;1867 img->len += insert_count - remove_count;1868 result[img->len] ='\0';18691870/* Adjust the line table */1871 nr = img->nr + postimage->nr - preimage->nr;1872if(preimage->nr < postimage->nr) {1873/*1874 * NOTE: this knows that we never call remove_first_line()1875 * on anything other than pre/post image.1876 */1877 img->line =xrealloc(img->line, nr *sizeof(*img->line));1878 img->line_allocated = img->line;1879}1880if(preimage->nr != postimage->nr)1881memmove(img->line + applied_pos + postimage->nr,1882 img->line + applied_pos + preimage->nr,1883(img->nr - (applied_pos + preimage->nr)) *1884sizeof(*img->line));1885memcpy(img->line + applied_pos,1886 postimage->line,1887 postimage->nr *sizeof(*img->line));1888 img->nr = nr;1889}18901891static intapply_one_fragment(struct image *img,struct fragment *frag,1892int inaccurate_eof,unsigned ws_rule)1893{1894int match_beginning, match_end;1895const char*patch = frag->patch;1896int size = frag->size;1897char*old, *new, *oldlines, *newlines;1898int new_blank_lines_at_end =0;1899unsigned long leading, trailing;1900int pos, applied_pos;1901struct image preimage;1902struct image postimage;19031904memset(&preimage,0,sizeof(preimage));1905memset(&postimage,0,sizeof(postimage));1906 oldlines =xmalloc(size);1907 newlines =xmalloc(size);19081909 old = oldlines;1910new= newlines;1911while(size >0) {1912char first;1913int len =linelen(patch, size);1914int plen, added;1915int added_blank_line =0;19161917if(!len)1918break;19191920/*1921 * "plen" is how much of the line we should use for1922 * the actual patch data. Normally we just remove the1923 * first character on the line, but if the line is1924 * followed by "\ No newline", then we also remove the1925 * last one (which is the newline, of course).1926 */1927 plen = len -1;1928if(len < size && patch[len] =='\\')1929 plen--;1930 first = *patch;1931if(apply_in_reverse) {1932if(first =='-')1933 first ='+';1934else if(first =='+')1935 first ='-';1936}19371938switch(first) {1939case'\n':1940/* Newer GNU diff, empty context line */1941if(plen <0)1942/* ... followed by '\No newline'; nothing */1943break;1944*old++ ='\n';1945*new++ ='\n';1946add_line_info(&preimage,"\n",1, LINE_COMMON);1947add_line_info(&postimage,"\n",1, LINE_COMMON);1948break;1949case' ':1950case'-':1951memcpy(old, patch +1, plen);1952add_line_info(&preimage, old, plen,1953(first ==' '? LINE_COMMON :0));1954 old += plen;1955if(first =='-')1956break;1957/* Fall-through for ' ' */1958case'+':1959/* --no-add does not add new lines */1960if(first =='+'&& no_add)1961break;19621963if(first !='+'||1964!whitespace_error ||1965 ws_error_action != correct_ws_error) {1966memcpy(new, patch +1, plen);1967 added = plen;1968}1969else{1970 added =ws_fix_copy(new, patch +1, plen, ws_rule, &applied_after_fixing_ws);1971}1972add_line_info(&postimage,new, added,1973(first =='+'?0: LINE_COMMON));1974new+= added;1975if(first =='+'&&1976 added ==1&&new[-1] =='\n')1977 added_blank_line =1;1978break;1979case'@':case'\\':1980/* Ignore it, we already handled it */1981break;1982default:1983if(apply_verbosely)1984error("invalid start of line: '%c'", first);1985return-1;1986}1987if(added_blank_line)1988 new_blank_lines_at_end++;1989else1990 new_blank_lines_at_end =0;1991 patch += len;1992 size -= len;1993}1994if(inaccurate_eof &&1995 old > oldlines && old[-1] =='\n'&&1996new> newlines &&new[-1] =='\n') {1997 old--;1998new--;1999}20002001 leading = frag->leading;2002 trailing = frag->trailing;20032004/*2005 * A hunk to change lines at the beginning would begin with2006 * @@ -1,L +N,M @@2007 * but we need to be careful. -U0 that inserts before the second2008 * line also has this pattern.2009 *2010 * And a hunk to add to an empty file would begin with2011 * @@ -0,0 +N,M @@2012 *2013 * In other words, a hunk that is (frag->oldpos <= 1) with or2014 * without leading context must match at the beginning.2015 */2016 match_beginning = (!frag->oldpos ||2017(frag->oldpos ==1&& !unidiff_zero));20182019/*2020 * A hunk without trailing lines must match at the end.2021 * However, we simply cannot tell if a hunk must match end2022 * from the lack of trailing lines if the patch was generated2023 * with unidiff without any context.2024 */2025 match_end = !unidiff_zero && !trailing;20262027 pos = frag->newpos ? (frag->newpos -1) :0;2028 preimage.buf = oldlines;2029 preimage.len = old - oldlines;2030 postimage.buf = newlines;2031 postimage.len =new- newlines;2032 preimage.line = preimage.line_allocated;2033 postimage.line = postimage.line_allocated;20342035for(;;) {20362037 applied_pos =find_pos(img, &preimage, &postimage, pos,2038 ws_rule, match_beginning, match_end);20392040if(applied_pos >=0)2041break;20422043/* Am I at my context limits? */2044if((leading <= p_context) && (trailing <= p_context))2045break;2046if(match_beginning || match_end) {2047 match_beginning = match_end =0;2048continue;2049}20502051/*2052 * Reduce the number of context lines; reduce both2053 * leading and trailing if they are equal otherwise2054 * just reduce the larger context.2055 */2056if(leading >= trailing) {2057remove_first_line(&preimage);2058remove_first_line(&postimage);2059 pos--;2060 leading--;2061}2062if(trailing > leading) {2063remove_last_line(&preimage);2064remove_last_line(&postimage);2065 trailing--;2066}2067}20682069if(applied_pos >=0) {2070if(ws_error_action == correct_ws_error &&2071 new_blank_lines_at_end &&2072 postimage.nr + applied_pos == img->nr) {2073/*2074 * If the patch application adds blank lines2075 * at the end, and if the patch applies at the2076 * end of the image, remove those added blank2077 * lines.2078 */2079while(new_blank_lines_at_end--)2080remove_last_line(&postimage);2081}20822083/*2084 * Warn if it was necessary to reduce the number2085 * of context lines.2086 */2087if((leading != frag->leading) ||2088(trailing != frag->trailing))2089fprintf(stderr,"Context reduced to (%ld/%ld)"2090" to apply fragment at%d\n",2091 leading, trailing, applied_pos+1);2092update_image(img, applied_pos, &preimage, &postimage);2093}else{2094if(apply_verbosely)2095error("while searching for:\n%.*s",2096(int)(old - oldlines), oldlines);2097}20982099free(oldlines);2100free(newlines);2101free(preimage.line_allocated);2102free(postimage.line_allocated);21032104return(applied_pos <0);2105}21062107static intapply_binary_fragment(struct image *img,struct patch *patch)2108{2109struct fragment *fragment = patch->fragments;2110unsigned long len;2111void*dst;21122113/* Binary patch is irreversible without the optional second hunk */2114if(apply_in_reverse) {2115if(!fragment->next)2116returnerror("cannot reverse-apply a binary patch "2117"without the reverse hunk to '%s'",2118 patch->new_name2119? patch->new_name : patch->old_name);2120 fragment = fragment->next;2121}2122switch(fragment->binary_patch_method) {2123case BINARY_DELTA_DEFLATED:2124 dst =patch_delta(img->buf, img->len, fragment->patch,2125 fragment->size, &len);2126if(!dst)2127return-1;2128clear_image(img);2129 img->buf = dst;2130 img->len = len;2131return0;2132case BINARY_LITERAL_DEFLATED:2133clear_image(img);2134 img->len = fragment->size;2135 img->buf =xmalloc(img->len+1);2136memcpy(img->buf, fragment->patch, img->len);2137 img->buf[img->len] ='\0';2138return0;2139}2140return-1;2141}21422143static intapply_binary(struct image *img,struct patch *patch)2144{2145const char*name = patch->old_name ? patch->old_name : patch->new_name;2146unsigned char sha1[20];21472148/*2149 * For safety, we require patch index line to contain2150 * full 40-byte textual SHA1 for old and new, at least for now.2151 */2152if(strlen(patch->old_sha1_prefix) !=40||2153strlen(patch->new_sha1_prefix) !=40||2154get_sha1_hex(patch->old_sha1_prefix, sha1) ||2155get_sha1_hex(patch->new_sha1_prefix, sha1))2156returnerror("cannot apply binary patch to '%s' "2157"without full index line", name);21582159if(patch->old_name) {2160/*2161 * See if the old one matches what the patch2162 * applies to.2163 */2164hash_sha1_file(img->buf, img->len, blob_type, sha1);2165if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2166returnerror("the patch applies to '%s' (%s), "2167"which does not match the "2168"current contents.",2169 name,sha1_to_hex(sha1));2170}2171else{2172/* Otherwise, the old one must be empty. */2173if(img->len)2174returnerror("the patch applies to an empty "2175"'%s' but it is not empty", name);2176}21772178get_sha1_hex(patch->new_sha1_prefix, sha1);2179if(is_null_sha1(sha1)) {2180clear_image(img);2181return0;/* deletion patch */2182}21832184if(has_sha1_file(sha1)) {2185/* We already have the postimage */2186enum object_type type;2187unsigned long size;2188char*result;21892190 result =read_sha1_file(sha1, &type, &size);2191if(!result)2192returnerror("the necessary postimage%sfor "2193"'%s' cannot be read",2194 patch->new_sha1_prefix, name);2195clear_image(img);2196 img->buf = result;2197 img->len = size;2198}else{2199/*2200 * We have verified buf matches the preimage;2201 * apply the patch data to it, which is stored2202 * in the patch->fragments->{patch,size}.2203 */2204if(apply_binary_fragment(img, patch))2205returnerror("binary patch does not apply to '%s'",2206 name);22072208/* verify that the result matches */2209hash_sha1_file(img->buf, img->len, blob_type, sha1);2210if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2211returnerror("binary patch to '%s' creates incorrect result (expecting%s, got%s)",2212 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2213}22142215return0;2216}22172218static intapply_fragments(struct image *img,struct patch *patch)2219{2220struct fragment *frag = patch->fragments;2221const char*name = patch->old_name ? patch->old_name : patch->new_name;2222unsigned ws_rule = patch->ws_rule;2223unsigned inaccurate_eof = patch->inaccurate_eof;22242225if(patch->is_binary)2226returnapply_binary(img, patch);22272228while(frag) {2229if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule)) {2230error("patch failed:%s:%ld", name, frag->oldpos);2231if(!apply_with_reject)2232return-1;2233 frag->rejected =1;2234}2235 frag = frag->next;2236}2237return0;2238}22392240static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2241{2242if(!ce)2243return0;22442245if(S_ISGITLINK(ce->ce_mode)) {2246strbuf_grow(buf,100);2247strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2248}else{2249enum object_type type;2250unsigned long sz;2251char*result;22522253 result =read_sha1_file(ce->sha1, &type, &sz);2254if(!result)2255return-1;2256/* XXX read_sha1_file NUL-terminates */2257strbuf_attach(buf, result, sz, sz +1);2258}2259return0;2260}22612262static struct patch *in_fn_table(const char*name)2263{2264struct string_list_item *item;22652266if(name == NULL)2267return NULL;22682269 item =string_list_lookup(name, &fn_table);2270if(item != NULL)2271return(struct patch *)item->util;22722273return NULL;2274}22752276static voidadd_to_fn_table(struct patch *patch)2277{2278struct string_list_item *item;22792280/*2281 * Always add new_name unless patch is a deletion2282 * This should cover the cases for normal diffs,2283 * file creations and copies2284 */2285if(patch->new_name != NULL) {2286 item =string_list_insert(patch->new_name, &fn_table);2287 item->util = patch;2288}22892290/*2291 * store a failure on rename/deletion cases because2292 * later chunks shouldn't patch old names2293 */2294if((patch->new_name == NULL) || (patch->is_rename)) {2295 item =string_list_insert(patch->old_name, &fn_table);2296 item->util = (struct patch *) -1;2297}2298}22992300static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)2301{2302struct strbuf buf;2303struct image image;2304size_t len;2305char*img;2306struct patch *tpatch;23072308strbuf_init(&buf,0);23092310if(!(patch->is_copy || patch->is_rename) &&2311((tpatch =in_fn_table(patch->old_name)) != NULL)) {2312if(tpatch == (struct patch *) -1) {2313returnerror("patch%shas been renamed/deleted",2314 patch->old_name);2315}2316/* We have a patched copy in memory use that */2317strbuf_add(&buf, tpatch->result, tpatch->resultsize);2318}else if(cached) {2319if(read_file_or_gitlink(ce, &buf))2320returnerror("read of%sfailed", patch->old_name);2321}else if(patch->old_name) {2322if(S_ISGITLINK(patch->old_mode)) {2323if(ce) {2324read_file_or_gitlink(ce, &buf);2325}else{2326/*2327 * There is no way to apply subproject2328 * patch without looking at the index.2329 */2330 patch->fragments = NULL;2331}2332}else{2333if(read_old_data(st, patch->old_name, &buf))2334returnerror("read of%sfailed", patch->old_name);2335}2336}23372338 img =strbuf_detach(&buf, &len);2339prepare_image(&image, img, len, !patch->is_binary);23402341if(apply_fragments(&image, patch) <0)2342return-1;/* note with --reject this succeeds. */2343 patch->result = image.buf;2344 patch->resultsize = image.len;2345add_to_fn_table(patch);2346free(image.line_allocated);23472348if(0< patch->is_delete && patch->resultsize)2349returnerror("removal patch leaves file contents");23502351return0;2352}23532354static intcheck_to_create_blob(const char*new_name,int ok_if_exists)2355{2356struct stat nst;2357if(!lstat(new_name, &nst)) {2358if(S_ISDIR(nst.st_mode) || ok_if_exists)2359return0;2360/*2361 * A leading component of new_name might be a symlink2362 * that is going to be removed with this patch, but2363 * still pointing at somewhere that has the path.2364 * In such a case, path "new_name" does not exist as2365 * far as git is concerned.2366 */2367if(has_symlink_leading_path(strlen(new_name), new_name))2368return0;23692370returnerror("%s: already exists in working directory", new_name);2371}2372else if((errno != ENOENT) && (errno != ENOTDIR))2373returnerror("%s:%s", new_name,strerror(errno));2374return0;2375}23762377static intverify_index_match(struct cache_entry *ce,struct stat *st)2378{2379if(S_ISGITLINK(ce->ce_mode)) {2380if(!S_ISDIR(st->st_mode))2381return-1;2382return0;2383}2384returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID);2385}23862387static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)2388{2389const char*old_name = patch->old_name;2390struct patch *tpatch = NULL;2391int stat_ret =0;2392unsigned st_mode =0;23932394/*2395 * Make sure that we do not have local modifications from the2396 * index when we are looking at the index. Also make sure2397 * we have the preimage file to be patched in the work tree,2398 * unless --cached, which tells git to apply only in the index.2399 */2400if(!old_name)2401return0;24022403assert(patch->is_new <=0);24042405if(!(patch->is_copy || patch->is_rename) &&2406(tpatch =in_fn_table(old_name)) != NULL) {2407if(tpatch == (struct patch *) -1) {2408returnerror("%s: has been deleted/renamed", old_name);2409}2410 st_mode = tpatch->new_mode;2411}else if(!cached) {2412 stat_ret =lstat(old_name, st);2413if(stat_ret && errno != ENOENT)2414returnerror("%s:%s", old_name,strerror(errno));2415}24162417if(check_index && !tpatch) {2418int pos =cache_name_pos(old_name,strlen(old_name));2419if(pos <0) {2420if(patch->is_new <0)2421goto is_new;2422returnerror("%s: does not exist in index", old_name);2423}2424*ce = active_cache[pos];2425if(stat_ret <0) {2426struct checkout costate;2427/* checkout */2428 costate.base_dir ="";2429 costate.base_dir_len =0;2430 costate.force =0;2431 costate.quiet =0;2432 costate.not_new =0;2433 costate.refresh_cache =1;2434if(checkout_entry(*ce, &costate, NULL) ||2435lstat(old_name, st))2436return-1;2437}2438if(!cached &&verify_index_match(*ce, st))2439returnerror("%s: does not match index", old_name);2440if(cached)2441 st_mode = (*ce)->ce_mode;2442}else if(stat_ret <0) {2443if(patch->is_new <0)2444goto is_new;2445returnerror("%s:%s", old_name,strerror(errno));2446}24472448if(!cached)2449 st_mode =ce_mode_from_stat(*ce, st->st_mode);24502451if(patch->is_new <0)2452 patch->is_new =0;2453if(!patch->old_mode)2454 patch->old_mode = st_mode;2455if((st_mode ^ patch->old_mode) & S_IFMT)2456returnerror("%s: wrong type", old_name);2457if(st_mode != patch->old_mode)2458fprintf(stderr,"warning:%shas type%o, expected%o\n",2459 old_name, st_mode, patch->old_mode);2460return0;24612462 is_new:2463 patch->is_new =1;2464 patch->is_delete =0;2465 patch->old_name = NULL;2466return0;2467}24682469static intcheck_patch(struct patch *patch)2470{2471struct stat st;2472const char*old_name = patch->old_name;2473const char*new_name = patch->new_name;2474const char*name = old_name ? old_name : new_name;2475struct cache_entry *ce = NULL;2476int ok_if_exists;2477int status;24782479 patch->rejected =1;/* we will drop this after we succeed */24802481 status =check_preimage(patch, &ce, &st);2482if(status)2483return status;2484 old_name = patch->old_name;24852486if(in_fn_table(new_name) == (struct patch *) -1)2487/*2488 * A type-change diff is always split into a patch to2489 * delete old, immediately followed by a patch to2490 * create new (see diff.c::run_diff()); in such a case2491 * it is Ok that the entry to be deleted by the2492 * previous patch is still in the working tree and in2493 * the index.2494 */2495 ok_if_exists =1;2496else2497 ok_if_exists =0;24982499if(new_name &&2500((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {2501if(check_index &&2502cache_name_pos(new_name,strlen(new_name)) >=0&&2503!ok_if_exists)2504returnerror("%s: already exists in index", new_name);2505if(!cached) {2506int err =check_to_create_blob(new_name, ok_if_exists);2507if(err)2508return err;2509}2510if(!patch->new_mode) {2511if(0< patch->is_new)2512 patch->new_mode = S_IFREG |0644;2513else2514 patch->new_mode = patch->old_mode;2515}2516}25172518if(new_name && old_name) {2519int same = !strcmp(old_name, new_name);2520if(!patch->new_mode)2521 patch->new_mode = patch->old_mode;2522if((patch->old_mode ^ patch->new_mode) & S_IFMT)2523returnerror("new mode (%o) of%sdoes not match old mode (%o)%s%s",2524 patch->new_mode, new_name, patch->old_mode,2525 same ?"":" of ", same ?"": old_name);2526}25272528if(apply_data(patch, &st, ce) <0)2529returnerror("%s: patch does not apply", name);2530 patch->rejected =0;2531return0;2532}25332534static intcheck_patch_list(struct patch *patch)2535{2536int err =0;25372538while(patch) {2539if(apply_verbosely)2540say_patch_name(stderr,2541"Checking patch ", patch,"...\n");2542 err |=check_patch(patch);2543 patch = patch->next;2544}2545return err;2546}25472548/* This function tries to read the sha1 from the current index */2549static intget_current_sha1(const char*path,unsigned char*sha1)2550{2551int pos;25522553if(read_cache() <0)2554return-1;2555 pos =cache_name_pos(path,strlen(path));2556if(pos <0)2557return-1;2558hashcpy(sha1, active_cache[pos]->sha1);2559return0;2560}25612562/* Build an index that contains the just the files needed for a 3way merge */2563static voidbuild_fake_ancestor(struct patch *list,const char*filename)2564{2565struct patch *patch;2566struct index_state result = {0};2567int fd;25682569/* Once we start supporting the reverse patch, it may be2570 * worth showing the new sha1 prefix, but until then...2571 */2572for(patch = list; patch; patch = patch->next) {2573const unsigned char*sha1_ptr;2574unsigned char sha1[20];2575struct cache_entry *ce;2576const char*name;25772578 name = patch->old_name ? patch->old_name : patch->new_name;2579if(0< patch->is_new)2580continue;2581else if(get_sha1(patch->old_sha1_prefix, sha1))2582/* git diff has no index line for mode/type changes */2583if(!patch->lines_added && !patch->lines_deleted) {2584if(get_current_sha1(patch->new_name, sha1) ||2585get_current_sha1(patch->old_name, sha1))2586die("mode change for%s, which is not "2587"in current HEAD", name);2588 sha1_ptr = sha1;2589}else2590die("sha1 information is lacking or useless "2591"(%s).", name);2592else2593 sha1_ptr = sha1;25942595 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);2596if(!ce)2597die("make_cache_entry failed for path '%s'", name);2598if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))2599die("Could not add%sto temporary index", name);2600}26012602 fd =open(filename, O_WRONLY | O_CREAT,0666);2603if(fd <0||write_index(&result, fd) ||close(fd))2604die("Could not write temporary index to%s", filename);26052606discard_index(&result);2607}26082609static voidstat_patch_list(struct patch *patch)2610{2611int files, adds, dels;26122613for(files = adds = dels =0; patch ; patch = patch->next) {2614 files++;2615 adds += patch->lines_added;2616 dels += patch->lines_deleted;2617show_stats(patch);2618}26192620printf("%dfiles changed,%dinsertions(+),%ddeletions(-)\n", files, adds, dels);2621}26222623static voidnumstat_patch_list(struct patch *patch)2624{2625for( ; patch; patch = patch->next) {2626const char*name;2627 name = patch->new_name ? patch->new_name : patch->old_name;2628if(patch->is_binary)2629printf("-\t-\t");2630else2631printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);2632write_name_quoted(name, stdout, line_termination);2633}2634}26352636static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)2637{2638if(mode)2639printf("%smode%06o%s\n", newdelete, mode, name);2640else2641printf("%s %s\n", newdelete, name);2642}26432644static voidshow_mode_change(struct patch *p,int show_name)2645{2646if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {2647if(show_name)2648printf(" mode change%06o =>%06o%s\n",2649 p->old_mode, p->new_mode, p->new_name);2650else2651printf(" mode change%06o =>%06o\n",2652 p->old_mode, p->new_mode);2653}2654}26552656static voidshow_rename_copy(struct patch *p)2657{2658const char*renamecopy = p->is_rename ?"rename":"copy";2659const char*old, *new;26602661/* Find common prefix */2662 old = p->old_name;2663new= p->new_name;2664while(1) {2665const char*slash_old, *slash_new;2666 slash_old =strchr(old,'/');2667 slash_new =strchr(new,'/');2668if(!slash_old ||2669!slash_new ||2670 slash_old - old != slash_new -new||2671memcmp(old,new, slash_new -new))2672break;2673 old = slash_old +1;2674new= slash_new +1;2675}2676/* p->old_name thru old is the common prefix, and old and new2677 * through the end of names are renames2678 */2679if(old != p->old_name)2680printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,2681(int)(old - p->old_name), p->old_name,2682 old,new, p->score);2683else2684printf("%s %s=>%s(%d%%)\n", renamecopy,2685 p->old_name, p->new_name, p->score);2686show_mode_change(p,0);2687}26882689static voidsummary_patch_list(struct patch *patch)2690{2691struct patch *p;26922693for(p = patch; p; p = p->next) {2694if(p->is_new)2695show_file_mode_name("create", p->new_mode, p->new_name);2696else if(p->is_delete)2697show_file_mode_name("delete", p->old_mode, p->old_name);2698else{2699if(p->is_rename || p->is_copy)2700show_rename_copy(p);2701else{2702if(p->score) {2703printf(" rewrite%s(%d%%)\n",2704 p->new_name, p->score);2705show_mode_change(p,0);2706}2707else2708show_mode_change(p,1);2709}2710}2711}2712}27132714static voidpatch_stats(struct patch *patch)2715{2716int lines = patch->lines_added + patch->lines_deleted;27172718if(lines > max_change)2719 max_change = lines;2720if(patch->old_name) {2721int len =quote_c_style(patch->old_name, NULL, NULL,0);2722if(!len)2723 len =strlen(patch->old_name);2724if(len > max_len)2725 max_len = len;2726}2727if(patch->new_name) {2728int len =quote_c_style(patch->new_name, NULL, NULL,0);2729if(!len)2730 len =strlen(patch->new_name);2731if(len > max_len)2732 max_len = len;2733}2734}27352736static voidremove_file(struct patch *patch,int rmdir_empty)2737{2738if(update_index) {2739if(remove_file_from_cache(patch->old_name) <0)2740die("unable to remove%sfrom index", patch->old_name);2741}2742if(!cached) {2743if(S_ISGITLINK(patch->old_mode)) {2744if(rmdir(patch->old_name))2745warning("unable to remove submodule%s",2746 patch->old_name);2747}else if(!unlink(patch->old_name) && rmdir_empty) {2748remove_path(patch->old_name);2749}2750}2751}27522753static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)2754{2755struct stat st;2756struct cache_entry *ce;2757int namelen =strlen(path);2758unsigned ce_size =cache_entry_size(namelen);27592760if(!update_index)2761return;27622763 ce =xcalloc(1, ce_size);2764memcpy(ce->name, path, namelen);2765 ce->ce_mode =create_ce_mode(mode);2766 ce->ce_flags = namelen;2767if(S_ISGITLINK(mode)) {2768const char*s = buf;27692770if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))2771die("corrupt patch for subproject%s", path);2772}else{2773if(!cached) {2774if(lstat(path, &st) <0)2775die("unable to stat newly created file%s",2776 path);2777fill_stat_cache_info(ce, &st);2778}2779if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)2780die("unable to create backing store for newly created file%s", path);2781}2782if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)2783die("unable to add cache entry for%s", path);2784}27852786static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)2787{2788int fd;2789struct strbuf nbuf;27902791if(S_ISGITLINK(mode)) {2792struct stat st;2793if(!lstat(path, &st) &&S_ISDIR(st.st_mode))2794return0;2795returnmkdir(path,0777);2796}27972798if(has_symlinks &&S_ISLNK(mode))2799/* Although buf:size is counted string, it also is NUL2800 * terminated.2801 */2802returnsymlink(buf, path);28032804 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);2805if(fd <0)2806return-1;28072808strbuf_init(&nbuf,0);2809if(convert_to_working_tree(path, buf, size, &nbuf)) {2810 size = nbuf.len;2811 buf = nbuf.buf;2812}2813write_or_die(fd, buf, size);2814strbuf_release(&nbuf);28152816if(close(fd) <0)2817die("closing file%s:%s", path,strerror(errno));2818return0;2819}28202821/*2822 * We optimistically assume that the directories exist,2823 * which is true 99% of the time anyway. If they don't,2824 * we create them and try again.2825 */2826static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)2827{2828if(cached)2829return;2830if(!try_create_file(path, mode, buf, size))2831return;28322833if(errno == ENOENT) {2834if(safe_create_leading_directories(path))2835return;2836if(!try_create_file(path, mode, buf, size))2837return;2838}28392840if(errno == EEXIST || errno == EACCES) {2841/* We may be trying to create a file where a directory2842 * used to be.2843 */2844struct stat st;2845if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))2846 errno = EEXIST;2847}28482849if(errno == EEXIST) {2850unsigned int nr =getpid();28512852for(;;) {2853char newpath[PATH_MAX];2854mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);2855if(!try_create_file(newpath, mode, buf, size)) {2856if(!rename(newpath, path))2857return;2858unlink(newpath);2859break;2860}2861if(errno != EEXIST)2862break;2863++nr;2864}2865}2866die("unable to write file%smode%o", path, mode);2867}28682869static voidcreate_file(struct patch *patch)2870{2871char*path = patch->new_name;2872unsigned mode = patch->new_mode;2873unsigned long size = patch->resultsize;2874char*buf = patch->result;28752876if(!mode)2877 mode = S_IFREG |0644;2878create_one_file(path, mode, buf, size);2879add_index_file(path, mode, buf, size);2880}28812882/* phase zero is to remove, phase one is to create */2883static voidwrite_out_one_result(struct patch *patch,int phase)2884{2885if(patch->is_delete >0) {2886if(phase ==0)2887remove_file(patch,1);2888return;2889}2890if(patch->is_new >0|| patch->is_copy) {2891if(phase ==1)2892create_file(patch);2893return;2894}2895/*2896 * Rename or modification boils down to the same2897 * thing: remove the old, write the new2898 */2899if(phase ==0)2900remove_file(patch, patch->is_rename);2901if(phase ==1)2902create_file(patch);2903}29042905static intwrite_out_one_reject(struct patch *patch)2906{2907FILE*rej;2908char namebuf[PATH_MAX];2909struct fragment *frag;2910int cnt =0;29112912for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {2913if(!frag->rejected)2914continue;2915 cnt++;2916}29172918if(!cnt) {2919if(apply_verbosely)2920say_patch_name(stderr,2921"Applied patch ", patch," cleanly.\n");2922return0;2923}29242925/* This should not happen, because a removal patch that leaves2926 * contents are marked "rejected" at the patch level.2927 */2928if(!patch->new_name)2929die("internal error");29302931/* Say this even without --verbose */2932say_patch_name(stderr,"Applying patch ", patch," with");2933fprintf(stderr,"%drejects...\n", cnt);29342935 cnt =strlen(patch->new_name);2936if(ARRAY_SIZE(namebuf) <= cnt +5) {2937 cnt =ARRAY_SIZE(namebuf) -5;2938fprintf(stderr,2939"warning: truncating .rej filename to %.*s.rej",2940 cnt -1, patch->new_name);2941}2942memcpy(namebuf, patch->new_name, cnt);2943memcpy(namebuf + cnt,".rej",5);29442945 rej =fopen(namebuf,"w");2946if(!rej)2947returnerror("cannot open%s:%s", namebuf,strerror(errno));29482949/* Normal git tools never deal with .rej, so do not pretend2950 * this is a git patch by saying --git nor give extended2951 * headers. While at it, maybe please "kompare" that wants2952 * the trailing TAB and some garbage at the end of line ;-).2953 */2954fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",2955 patch->new_name, patch->new_name);2956for(cnt =1, frag = patch->fragments;2957 frag;2958 cnt++, frag = frag->next) {2959if(!frag->rejected) {2960fprintf(stderr,"Hunk #%dapplied cleanly.\n", cnt);2961continue;2962}2963fprintf(stderr,"Rejected hunk #%d.\n", cnt);2964fprintf(rej,"%.*s", frag->size, frag->patch);2965if(frag->patch[frag->size-1] !='\n')2966fputc('\n', rej);2967}2968fclose(rej);2969return-1;2970}29712972static intwrite_out_results(struct patch *list,int skipped_patch)2973{2974int phase;2975int errs =0;2976struct patch *l;29772978if(!list && !skipped_patch)2979returnerror("No changes");29802981for(phase =0; phase <2; phase++) {2982 l = list;2983while(l) {2984if(l->rejected)2985 errs =1;2986else{2987write_out_one_result(l, phase);2988if(phase ==1&&write_out_one_reject(l))2989 errs =1;2990}2991 l = l->next;2992}2993}2994return errs;2995}29962997static struct lock_file lock_file;29982999static struct excludes {3000struct excludes *next;3001const char*path;3002} *excludes;30033004static intuse_patch(struct patch *p)3005{3006const char*pathname = p->new_name ? p->new_name : p->old_name;3007struct excludes *x = excludes;3008while(x) {3009if(fnmatch(x->path, pathname,0) ==0)3010return0;3011 x = x->next;3012}3013if(0< prefix_length) {3014int pathlen =strlen(pathname);3015if(pathlen <= prefix_length ||3016memcmp(prefix, pathname, prefix_length))3017return0;3018}3019return1;3020}30213022static voidprefix_one(char**name)3023{3024char*old_name = *name;3025if(!old_name)3026return;3027*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3028free(old_name);3029}30303031static voidprefix_patches(struct patch *p)3032{3033if(!prefix || p->is_toplevel_relative)3034return;3035for( ; p; p = p->next) {3036if(p->new_name == p->old_name) {3037char*prefixed = p->new_name;3038prefix_one(&prefixed);3039 p->new_name = p->old_name = prefixed;3040}3041else{3042prefix_one(&p->new_name);3043prefix_one(&p->old_name);3044}3045}3046}30473048#define INACCURATE_EOF (1<<0)3049#define RECOUNT (1<<1)30503051static intapply_patch(int fd,const char*filename,int options)3052{3053size_t offset;3054struct strbuf buf;3055struct patch *list = NULL, **listp = &list;3056int skipped_patch =0;30573058/* FIXME - memory leak when using multiple patch files as inputs */3059memset(&fn_table,0,sizeof(struct string_list));3060strbuf_init(&buf,0);3061 patch_input_file = filename;3062read_patch_file(&buf, fd);3063 offset =0;3064while(offset < buf.len) {3065struct patch *patch;3066int nr;30673068 patch =xcalloc(1,sizeof(*patch));3069 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3070 patch->recount = !!(options & RECOUNT);3071 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3072if(nr <0)3073break;3074if(apply_in_reverse)3075reverse_patches(patch);3076if(prefix)3077prefix_patches(patch);3078if(use_patch(patch)) {3079patch_stats(patch);3080*listp = patch;3081 listp = &patch->next;3082}3083else{3084/* perhaps free it a bit better? */3085free(patch);3086 skipped_patch++;3087}3088 offset += nr;3089}30903091if(whitespace_error && (ws_error_action == die_on_ws_error))3092 apply =0;30933094 update_index = check_index && apply;3095if(update_index && newfd <0)3096 newfd =hold_locked_index(&lock_file,1);30973098if(check_index) {3099if(read_cache() <0)3100die("unable to read index file");3101}31023103if((check || apply) &&3104check_patch_list(list) <0&&3105!apply_with_reject)3106exit(1);31073108if(apply &&write_out_results(list, skipped_patch))3109exit(1);31103111if(fake_ancestor)3112build_fake_ancestor(list, fake_ancestor);31133114if(diffstat)3115stat_patch_list(list);31163117if(numstat)3118numstat_patch_list(list);31193120if(summary)3121summary_patch_list(list);31223123strbuf_release(&buf);3124return0;3125}31263127static intgit_apply_config(const char*var,const char*value,void*cb)3128{3129if(!strcmp(var,"apply.whitespace"))3130returngit_config_string(&apply_default_whitespace, var, value);3131returngit_default_config(var, value, cb);3132}313331343135intcmd_apply(int argc,const char**argv,const char*unused_prefix)3136{3137int i;3138int read_stdin =1;3139int options =0;3140int errs =0;3141int is_not_gitdir;31423143const char*whitespace_option = NULL;31443145 prefix =setup_git_directory_gently(&is_not_gitdir);3146 prefix_length = prefix ?strlen(prefix) :0;3147git_config(git_apply_config, NULL);3148if(apply_default_whitespace)3149parse_whitespace_option(apply_default_whitespace);31503151for(i =1; i < argc; i++) {3152const char*arg = argv[i];3153char*end;3154int fd;31553156if(!strcmp(arg,"-")) {3157 errs |=apply_patch(0,"<stdin>", options);3158 read_stdin =0;3159continue;3160}3161if(!prefixcmp(arg,"--exclude=")) {3162struct excludes *x =xmalloc(sizeof(*x));3163 x->path = arg +10;3164 x->next = excludes;3165 excludes = x;3166continue;3167}3168if(!prefixcmp(arg,"-p")) {3169 p_value =atoi(arg +2);3170 p_value_known =1;3171continue;3172}3173if(!strcmp(arg,"--no-add")) {3174 no_add =1;3175continue;3176}3177if(!strcmp(arg,"--stat")) {3178 apply =0;3179 diffstat =1;3180continue;3181}3182if(!strcmp(arg,"--allow-binary-replacement") ||3183!strcmp(arg,"--binary")) {3184continue;/* now no-op */3185}3186if(!strcmp(arg,"--numstat")) {3187 apply =0;3188 numstat =1;3189continue;3190}3191if(!strcmp(arg,"--summary")) {3192 apply =0;3193 summary =1;3194continue;3195}3196if(!strcmp(arg,"--check")) {3197 apply =0;3198 check =1;3199continue;3200}3201if(!strcmp(arg,"--index")) {3202if(is_not_gitdir)3203die("--index outside a repository");3204 check_index =1;3205continue;3206}3207if(!strcmp(arg,"--cached")) {3208if(is_not_gitdir)3209die("--cached outside a repository");3210 check_index =1;3211 cached =1;3212continue;3213}3214if(!strcmp(arg,"--apply")) {3215 apply =1;3216continue;3217}3218if(!strcmp(arg,"--build-fake-ancestor")) {3219 apply =0;3220if(++i >= argc)3221die("need a filename");3222 fake_ancestor = argv[i];3223continue;3224}3225if(!strcmp(arg,"-z")) {3226 line_termination =0;3227continue;3228}3229if(!prefixcmp(arg,"-C")) {3230 p_context =strtoul(arg +2, &end,0);3231if(*end !='\0')3232die("unrecognized context count '%s'", arg +2);3233continue;3234}3235if(!prefixcmp(arg,"--whitespace=")) {3236 whitespace_option = arg +13;3237parse_whitespace_option(arg +13);3238continue;3239}3240if(!strcmp(arg,"-R") || !strcmp(arg,"--reverse")) {3241 apply_in_reverse =1;3242continue;3243}3244if(!strcmp(arg,"--unidiff-zero")) {3245 unidiff_zero =1;3246continue;3247}3248if(!strcmp(arg,"--reject")) {3249 apply = apply_with_reject = apply_verbosely =1;3250continue;3251}3252if(!strcmp(arg,"-v") || !strcmp(arg,"--verbose")) {3253 apply_verbosely =1;3254continue;3255}3256if(!strcmp(arg,"--inaccurate-eof")) {3257 options |= INACCURATE_EOF;3258continue;3259}3260if(!strcmp(arg,"--recount")) {3261 options |= RECOUNT;3262continue;3263}3264if(!prefixcmp(arg,"--directory=")) {3265 arg +=strlen("--directory=");3266 root_len =strlen(arg);3267if(root_len && arg[root_len -1] !='/') {3268char*new_root;3269 root = new_root =xmalloc(root_len +2);3270strcpy(new_root, arg);3271strcpy(new_root + root_len++,"/");3272}else3273 root = arg;3274continue;3275}3276if(0< prefix_length)3277 arg =prefix_filename(prefix, prefix_length, arg);32783279 fd =open(arg, O_RDONLY);3280if(fd <0)3281die("can't open patch '%s':%s", arg,strerror(errno));3282 read_stdin =0;3283set_default_whitespace_mode(whitespace_option);3284 errs |=apply_patch(fd, arg, options);3285close(fd);3286}3287set_default_whitespace_mode(whitespace_option);3288if(read_stdin)3289 errs |=apply_patch(0,"<stdin>", options);3290if(whitespace_error) {3291if(squelch_whitespace_errors &&3292 squelch_whitespace_errors < whitespace_error) {3293int squelched =3294 whitespace_error - squelch_whitespace_errors;3295fprintf(stderr,"warning: squelched%d"3296"whitespace error%s\n",3297 squelched,3298 squelched ==1?"":"s");3299}3300if(ws_error_action == die_on_ws_error)3301die("%dline%sadd%swhitespace errors.",3302 whitespace_error,3303 whitespace_error ==1?"":"s",3304 whitespace_error ==1?"s":"");3305if(applied_after_fixing_ws && apply)3306fprintf(stderr,"warning:%dline%sapplied after"3307" fixing whitespace errors.\n",3308 applied_after_fixing_ws,3309 applied_after_fixing_ws ==1?"":"s");3310else if(whitespace_error)3311fprintf(stderr,"warning:%dline%sadd%swhitespace errors.\n",3312 whitespace_error,3313 whitespace_error ==1?"":"s",3314 whitespace_error ==1?"s":"");3315}33163317if(update_index) {3318if(write_cache(newfd, active_cache, active_nr) ||3319commit_locked_index(&lock_file))3320die("Unable to write new index file");3321}33223323return!!errs;3324}