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#include"parse-options.h" 18 19/* 20 * --check turns on checking that the working tree matches the 21 * files that are being modified, but doesn't apply the patch 22 * --stat does just a diffstat, and doesn't actually apply 23 * --numstat does numeric diffstat, and doesn't actually apply 24 * --index-info shows the old and new index info for paths if available. 25 * --index updates the cache as well. 26 * --cached updates only the cache without ever touching the working tree. 27 */ 28static const char*prefix; 29static int prefix_length = -1; 30static int newfd = -1; 31 32static int unidiff_zero; 33static int p_value =1; 34static int p_value_known; 35static int check_index; 36static int update_index; 37static int cached; 38static int diffstat; 39static int numstat; 40static int summary; 41static int check; 42static int apply =1; 43static int apply_in_reverse; 44static int apply_with_reject; 45static int apply_verbosely; 46static int no_add; 47static const char*fake_ancestor; 48static int line_termination ='\n'; 49static unsigned int p_context = UINT_MAX; 50static const char*const apply_usage[] = { 51"git apply [options] [<patch>...]", 52 NULL 53}; 54 55static enum ws_error_action { 56 nowarn_ws_error, 57 warn_on_ws_error, 58 die_on_ws_error, 59 correct_ws_error, 60} ws_error_action = warn_on_ws_error; 61static int whitespace_error; 62static int squelch_whitespace_errors =5; 63static int applied_after_fixing_ws; 64static const char*patch_input_file; 65static const char*root; 66static int root_len; 67static int read_stdin =1; 68static int options; 69 70static voidparse_whitespace_option(const char*option) 71{ 72if(!option) { 73 ws_error_action = warn_on_ws_error; 74return; 75} 76if(!strcmp(option,"warn")) { 77 ws_error_action = warn_on_ws_error; 78return; 79} 80if(!strcmp(option,"nowarn")) { 81 ws_error_action = nowarn_ws_error; 82return; 83} 84if(!strcmp(option,"error")) { 85 ws_error_action = die_on_ws_error; 86return; 87} 88if(!strcmp(option,"error-all")) { 89 ws_error_action = die_on_ws_error; 90 squelch_whitespace_errors =0; 91return; 92} 93if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 94 ws_error_action = correct_ws_error; 95return; 96} 97die("unrecognized whitespace option '%s'", option); 98} 99 100static voidset_default_whitespace_mode(const char*whitespace_option) 101{ 102if(!whitespace_option && !apply_default_whitespace) 103 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 104} 105 106/* 107 * For "diff-stat" like behaviour, we keep track of the biggest change 108 * we've seen, and the longest filename. That allows us to do simple 109 * scaling. 110 */ 111static int max_change, max_len; 112 113/* 114 * Various "current state", notably line numbers and what 115 * file (and how) we're patching right now.. The "is_xxxx" 116 * things are flags, where -1 means "don't know yet". 117 */ 118static int linenr =1; 119 120/* 121 * This represents one "hunk" from a patch, starting with 122 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 123 * patch text is pointed at by patch, and its byte length 124 * is stored in size. leading and trailing are the number 125 * of context lines. 126 */ 127struct fragment { 128unsigned long leading, trailing; 129unsigned long oldpos, oldlines; 130unsigned long newpos, newlines; 131const char*patch; 132int size; 133int rejected; 134struct fragment *next; 135}; 136 137/* 138 * When dealing with a binary patch, we reuse "leading" field 139 * to store the type of the binary hunk, either deflated "delta" 140 * or deflated "literal". 141 */ 142#define binary_patch_method leading 143#define BINARY_DELTA_DEFLATED 1 144#define BINARY_LITERAL_DEFLATED 2 145 146/* 147 * This represents a "patch" to a file, both metainfo changes 148 * such as creation/deletion, filemode and content changes represented 149 * as a series of fragments. 150 */ 151struct patch { 152char*new_name, *old_name, *def_name; 153unsigned int old_mode, new_mode; 154int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 155int rejected; 156unsigned ws_rule; 157unsigned long deflate_origlen; 158int lines_added, lines_deleted; 159int score; 160unsigned int is_toplevel_relative:1; 161unsigned int inaccurate_eof:1; 162unsigned int is_binary:1; 163unsigned int is_copy:1; 164unsigned int is_rename:1; 165unsigned int recount:1; 166struct fragment *fragments; 167char*result; 168size_t resultsize; 169char old_sha1_prefix[41]; 170char new_sha1_prefix[41]; 171struct patch *next; 172}; 173 174/* 175 * A line in a file, len-bytes long (includes the terminating LF, 176 * except for an incomplete line at the end if the file ends with 177 * one), and its contents hashes to 'hash'. 178 */ 179struct line { 180size_t len; 181unsigned hash :24; 182unsigned flag :8; 183#define LINE_COMMON 1 184}; 185 186/* 187 * This represents a "file", which is an array of "lines". 188 */ 189struct image { 190char*buf; 191size_t len; 192size_t nr; 193size_t alloc; 194struct line *line_allocated; 195struct line *line; 196}; 197 198/* 199 * Records filenames that have been touched, in order to handle 200 * the case where more than one patches touch the same file. 201 */ 202 203static struct string_list fn_table; 204 205static uint32_thash_line(const char*cp,size_t len) 206{ 207size_t i; 208uint32_t h; 209for(i =0, h =0; i < len; i++) { 210if(!isspace(cp[i])) { 211 h = h *3+ (cp[i] &0xff); 212} 213} 214return h; 215} 216 217static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 218{ 219ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 220 img->line_allocated[img->nr].len = len; 221 img->line_allocated[img->nr].hash =hash_line(bol, len); 222 img->line_allocated[img->nr].flag = flag; 223 img->nr++; 224} 225 226static voidprepare_image(struct image *image,char*buf,size_t len, 227int prepare_linetable) 228{ 229const char*cp, *ep; 230 231memset(image,0,sizeof(*image)); 232 image->buf = buf; 233 image->len = len; 234 235if(!prepare_linetable) 236return; 237 238 ep = image->buf + image->len; 239 cp = image->buf; 240while(cp < ep) { 241const char*next; 242for(next = cp; next < ep && *next !='\n'; next++) 243; 244if(next < ep) 245 next++; 246add_line_info(image, cp, next - cp,0); 247 cp = next; 248} 249 image->line = image->line_allocated; 250} 251 252static voidclear_image(struct image *image) 253{ 254free(image->buf); 255 image->buf = NULL; 256 image->len =0; 257} 258 259static voidsay_patch_name(FILE*output,const char*pre, 260struct patch *patch,const char*post) 261{ 262fputs(pre, output); 263if(patch->old_name && patch->new_name && 264strcmp(patch->old_name, patch->new_name)) { 265quote_c_style(patch->old_name, NULL, output,0); 266fputs(" => ", output); 267quote_c_style(patch->new_name, NULL, output,0); 268}else{ 269const char*n = patch->new_name; 270if(!n) 271 n = patch->old_name; 272quote_c_style(n, NULL, output,0); 273} 274fputs(post, output); 275} 276 277#define CHUNKSIZE (8192) 278#define SLOP (16) 279 280static voidread_patch_file(struct strbuf *sb,int fd) 281{ 282if(strbuf_read(sb, fd,0) <0) 283die_errno("git apply: failed to read"); 284 285/* 286 * Make sure that we have some slop in the buffer 287 * so that we can do speculative "memcmp" etc, and 288 * see to it that it is NUL-filled. 289 */ 290strbuf_grow(sb, SLOP); 291memset(sb->buf + sb->len,0, SLOP); 292} 293 294static unsigned longlinelen(const char*buffer,unsigned long size) 295{ 296unsigned long len =0; 297while(size--) { 298 len++; 299if(*buffer++ =='\n') 300break; 301} 302return len; 303} 304 305static intis_dev_null(const char*str) 306{ 307return!memcmp("/dev/null", str,9) &&isspace(str[9]); 308} 309 310#define TERM_SPACE 1 311#define TERM_TAB 2 312 313static intname_terminate(const char*name,int namelen,int c,int terminate) 314{ 315if(c ==' '&& !(terminate & TERM_SPACE)) 316return0; 317if(c =='\t'&& !(terminate & TERM_TAB)) 318return0; 319 320return1; 321} 322 323/* remove double slashes to make --index work with such filenames */ 324static char*squash_slash(char*name) 325{ 326int i =0, j =0; 327 328while(name[i]) { 329if((name[j++] = name[i++]) =='/') 330while(name[i] =='/') 331 i++; 332} 333 name[j] ='\0'; 334return name; 335} 336 337static char*find_name(const char*line,char*def,int p_value,int terminate) 338{ 339int len; 340const char*start = line; 341 342if(*line =='"') { 343struct strbuf name = STRBUF_INIT; 344 345/* 346 * Proposed "new-style" GNU patch/diff format; see 347 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2 348 */ 349if(!unquote_c_style(&name, line, NULL)) { 350char*cp; 351 352for(cp = name.buf; p_value; p_value--) { 353 cp =strchr(cp,'/'); 354if(!cp) 355break; 356 cp++; 357} 358if(cp) { 359/* name can later be freed, so we need 360 * to memmove, not just return cp 361 */ 362strbuf_remove(&name,0, cp - name.buf); 363free(def); 364if(root) 365strbuf_insert(&name,0, root, root_len); 366returnsquash_slash(strbuf_detach(&name, NULL)); 367} 368} 369strbuf_release(&name); 370} 371 372for(;;) { 373char c = *line; 374 375if(isspace(c)) { 376if(c =='\n') 377break; 378if(name_terminate(start, line-start, c, terminate)) 379break; 380} 381 line++; 382if(c =='/'&& !--p_value) 383 start = line; 384} 385if(!start) 386returnsquash_slash(def); 387 len = line - start; 388if(!len) 389returnsquash_slash(def); 390 391/* 392 * Generally we prefer the shorter name, especially 393 * if the other one is just a variation of that with 394 * something else tacked on to the end (ie "file.orig" 395 * or "file~"). 396 */ 397if(def) { 398int deflen =strlen(def); 399if(deflen < len && !strncmp(start, def, deflen)) 400returnsquash_slash(def); 401free(def); 402} 403 404if(root) { 405char*ret =xmalloc(root_len + len +1); 406strcpy(ret, root); 407memcpy(ret + root_len, start, len); 408 ret[root_len + len] ='\0'; 409returnsquash_slash(ret); 410} 411 412returnsquash_slash(xmemdupz(start, len)); 413} 414 415static intcount_slashes(const char*cp) 416{ 417int cnt =0; 418char ch; 419 420while((ch = *cp++)) 421if(ch =='/') 422 cnt++; 423return cnt; 424} 425 426/* 427 * Given the string after "--- " or "+++ ", guess the appropriate 428 * p_value for the given patch. 429 */ 430static intguess_p_value(const char*nameline) 431{ 432char*name, *cp; 433int val = -1; 434 435if(is_dev_null(nameline)) 436return-1; 437 name =find_name(nameline, NULL,0, TERM_SPACE | TERM_TAB); 438if(!name) 439return-1; 440 cp =strchr(name,'/'); 441if(!cp) 442 val =0; 443else if(prefix) { 444/* 445 * Does it begin with "a/$our-prefix" and such? Then this is 446 * very likely to apply to our directory. 447 */ 448if(!strncmp(name, prefix, prefix_length)) 449 val =count_slashes(prefix); 450else{ 451 cp++; 452if(!strncmp(cp, prefix, prefix_length)) 453 val =count_slashes(prefix) +1; 454} 455} 456free(name); 457return val; 458} 459 460/* 461 * Get the name etc info from the ---/+++ lines of a traditional patch header 462 * 463 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 464 * files, we can happily check the index for a match, but for creating a 465 * new file we should try to match whatever "patch" does. I have no idea. 466 */ 467static voidparse_traditional_patch(const char*first,const char*second,struct patch *patch) 468{ 469char*name; 470 471 first +=4;/* skip "--- " */ 472 second +=4;/* skip "+++ " */ 473if(!p_value_known) { 474int p, q; 475 p =guess_p_value(first); 476 q =guess_p_value(second); 477if(p <0) p = q; 478if(0<= p && p == q) { 479 p_value = p; 480 p_value_known =1; 481} 482} 483if(is_dev_null(first)) { 484 patch->is_new =1; 485 patch->is_delete =0; 486 name =find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB); 487 patch->new_name = name; 488}else if(is_dev_null(second)) { 489 patch->is_new =0; 490 patch->is_delete =1; 491 name =find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB); 492 patch->old_name = name; 493}else{ 494 name =find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB); 495 name =find_name(second, name, p_value, TERM_SPACE | TERM_TAB); 496 patch->old_name = patch->new_name = name; 497} 498if(!name) 499die("unable to find filename in patch at line%d", linenr); 500} 501 502static intgitdiff_hdrend(const char*line,struct patch *patch) 503{ 504return-1; 505} 506 507/* 508 * We're anal about diff header consistency, to make 509 * sure that we don't end up having strange ambiguous 510 * patches floating around. 511 * 512 * As a result, gitdiff_{old|new}name() will check 513 * their names against any previous information, just 514 * to make sure.. 515 */ 516static char*gitdiff_verify_name(const char*line,int isnull,char*orig_name,const char*oldnew) 517{ 518if(!orig_name && !isnull) 519returnfind_name(line, NULL, p_value, TERM_TAB); 520 521if(orig_name) { 522int len; 523const char*name; 524char*another; 525 name = orig_name; 526 len =strlen(name); 527if(isnull) 528die("git apply: bad git-diff - expected /dev/null, got%son line%d", name, linenr); 529 another =find_name(line, NULL, p_value, TERM_TAB); 530if(!another ||memcmp(another, name, len)) 531die("git apply: bad git-diff - inconsistent%sfilename on line%d", oldnew, linenr); 532free(another); 533return orig_name; 534} 535else{ 536/* expect "/dev/null" */ 537if(memcmp("/dev/null", line,9) || line[9] !='\n') 538die("git apply: bad git-diff - expected /dev/null on line%d", linenr); 539return NULL; 540} 541} 542 543static intgitdiff_oldname(const char*line,struct patch *patch) 544{ 545 patch->old_name =gitdiff_verify_name(line, patch->is_new, patch->old_name,"old"); 546return0; 547} 548 549static intgitdiff_newname(const char*line,struct patch *patch) 550{ 551 patch->new_name =gitdiff_verify_name(line, patch->is_delete, patch->new_name,"new"); 552return0; 553} 554 555static intgitdiff_oldmode(const char*line,struct patch *patch) 556{ 557 patch->old_mode =strtoul(line, NULL,8); 558return0; 559} 560 561static intgitdiff_newmode(const char*line,struct patch *patch) 562{ 563 patch->new_mode =strtoul(line, NULL,8); 564return0; 565} 566 567static intgitdiff_delete(const char*line,struct patch *patch) 568{ 569 patch->is_delete =1; 570 patch->old_name = patch->def_name; 571returngitdiff_oldmode(line, patch); 572} 573 574static intgitdiff_newfile(const char*line,struct patch *patch) 575{ 576 patch->is_new =1; 577 patch->new_name = patch->def_name; 578returngitdiff_newmode(line, patch); 579} 580 581static intgitdiff_copysrc(const char*line,struct patch *patch) 582{ 583 patch->is_copy =1; 584 patch->old_name =find_name(line, NULL,0,0); 585return0; 586} 587 588static intgitdiff_copydst(const char*line,struct patch *patch) 589{ 590 patch->is_copy =1; 591 patch->new_name =find_name(line, NULL,0,0); 592return0; 593} 594 595static intgitdiff_renamesrc(const char*line,struct patch *patch) 596{ 597 patch->is_rename =1; 598 patch->old_name =find_name(line, NULL,0,0); 599return0; 600} 601 602static intgitdiff_renamedst(const char*line,struct patch *patch) 603{ 604 patch->is_rename =1; 605 patch->new_name =find_name(line, NULL,0,0); 606return0; 607} 608 609static intgitdiff_similarity(const char*line,struct patch *patch) 610{ 611if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 612 patch->score =0; 613return0; 614} 615 616static intgitdiff_dissimilarity(const char*line,struct patch *patch) 617{ 618if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 619 patch->score =0; 620return0; 621} 622 623static intgitdiff_index(const char*line,struct patch *patch) 624{ 625/* 626 * index line is N hexadecimal, "..", N hexadecimal, 627 * and optional space with octal mode. 628 */ 629const char*ptr, *eol; 630int len; 631 632 ptr =strchr(line,'.'); 633if(!ptr || ptr[1] !='.'||40< ptr - line) 634return0; 635 len = ptr - line; 636memcpy(patch->old_sha1_prefix, line, len); 637 patch->old_sha1_prefix[len] =0; 638 639 line = ptr +2; 640 ptr =strchr(line,' '); 641 eol =strchr(line,'\n'); 642 643if(!ptr || eol < ptr) 644 ptr = eol; 645 len = ptr - line; 646 647if(40< len) 648return0; 649memcpy(patch->new_sha1_prefix, line, len); 650 patch->new_sha1_prefix[len] =0; 651if(*ptr ==' ') 652 patch->old_mode =strtoul(ptr+1, NULL,8); 653return0; 654} 655 656/* 657 * This is normal for a diff that doesn't change anything: we'll fall through 658 * into the next diff. Tell the parser to break out. 659 */ 660static intgitdiff_unrecognized(const char*line,struct patch *patch) 661{ 662return-1; 663} 664 665static const char*stop_at_slash(const char*line,int llen) 666{ 667int i; 668 669for(i =0; i < llen; i++) { 670int ch = line[i]; 671if(ch =='/') 672return line + i; 673} 674return NULL; 675} 676 677/* 678 * This is to extract the same name that appears on "diff --git" 679 * line. We do not find and return anything if it is a rename 680 * patch, and it is OK because we will find the name elsewhere. 681 * We need to reliably find name only when it is mode-change only, 682 * creation or deletion of an empty file. In any of these cases, 683 * both sides are the same name under a/ and b/ respectively. 684 */ 685static char*git_header_name(char*line,int llen) 686{ 687const char*name; 688const char*second = NULL; 689size_t len; 690 691 line +=strlen("diff --git "); 692 llen -=strlen("diff --git "); 693 694if(*line =='"') { 695const char*cp; 696struct strbuf first = STRBUF_INIT; 697struct strbuf sp = STRBUF_INIT; 698 699if(unquote_c_style(&first, line, &second)) 700goto free_and_fail1; 701 702/* advance to the first slash */ 703 cp =stop_at_slash(first.buf, first.len); 704/* we do not accept absolute paths */ 705if(!cp || cp == first.buf) 706goto free_and_fail1; 707strbuf_remove(&first,0, cp +1- first.buf); 708 709/* 710 * second points at one past closing dq of name. 711 * find the second name. 712 */ 713while((second < line + llen) &&isspace(*second)) 714 second++; 715 716if(line + llen <= second) 717goto free_and_fail1; 718if(*second =='"') { 719if(unquote_c_style(&sp, second, NULL)) 720goto free_and_fail1; 721 cp =stop_at_slash(sp.buf, sp.len); 722if(!cp || cp == sp.buf) 723goto free_and_fail1; 724/* They must match, otherwise ignore */ 725if(strcmp(cp +1, first.buf)) 726goto free_and_fail1; 727strbuf_release(&sp); 728returnstrbuf_detach(&first, NULL); 729} 730 731/* unquoted second */ 732 cp =stop_at_slash(second, line + llen - second); 733if(!cp || cp == second) 734goto free_and_fail1; 735 cp++; 736if(line + llen - cp != first.len +1|| 737memcmp(first.buf, cp, first.len)) 738goto free_and_fail1; 739returnstrbuf_detach(&first, NULL); 740 741 free_and_fail1: 742strbuf_release(&first); 743strbuf_release(&sp); 744return NULL; 745} 746 747/* unquoted first name */ 748 name =stop_at_slash(line, llen); 749if(!name || name == line) 750return NULL; 751 name++; 752 753/* 754 * since the first name is unquoted, a dq if exists must be 755 * the beginning of the second name. 756 */ 757for(second = name; second < line + llen; second++) { 758if(*second =='"') { 759struct strbuf sp = STRBUF_INIT; 760const char*np; 761 762if(unquote_c_style(&sp, second, NULL)) 763goto free_and_fail2; 764 765 np =stop_at_slash(sp.buf, sp.len); 766if(!np || np == sp.buf) 767goto free_and_fail2; 768 np++; 769 770 len = sp.buf + sp.len - np; 771if(len < second - name && 772!strncmp(np, name, len) && 773isspace(name[len])) { 774/* Good */ 775strbuf_remove(&sp,0, np - sp.buf); 776returnstrbuf_detach(&sp, NULL); 777} 778 779 free_and_fail2: 780strbuf_release(&sp); 781return NULL; 782} 783} 784 785/* 786 * Accept a name only if it shows up twice, exactly the same 787 * form. 788 */ 789for(len =0; ; len++) { 790switch(name[len]) { 791default: 792continue; 793case'\n': 794return NULL; 795case'\t':case' ': 796 second = name+len; 797for(;;) { 798char c = *second++; 799if(c =='\n') 800return NULL; 801if(c =='/') 802break; 803} 804if(second[len] =='\n'&& !memcmp(name, second, len)) { 805returnxmemdupz(name, len); 806} 807} 808} 809} 810 811/* Verify that we recognize the lines following a git header */ 812static intparse_git_header(char*line,int len,unsigned int size,struct patch *patch) 813{ 814unsigned long offset; 815 816/* A git diff has explicit new/delete information, so we don't guess */ 817 patch->is_new =0; 818 patch->is_delete =0; 819 820/* 821 * Some things may not have the old name in the 822 * rest of the headers anywhere (pure mode changes, 823 * or removing or adding empty files), so we get 824 * the default name from the header. 825 */ 826 patch->def_name =git_header_name(line, len); 827if(patch->def_name && root) { 828char*s =xmalloc(root_len +strlen(patch->def_name) +1); 829strcpy(s, root); 830strcpy(s + root_len, patch->def_name); 831free(patch->def_name); 832 patch->def_name = s; 833} 834 835 line += len; 836 size -= len; 837 linenr++; 838for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) { 839static const struct opentry { 840const char*str; 841int(*fn)(const char*,struct patch *); 842} optable[] = { 843{"@@ -", gitdiff_hdrend }, 844{"--- ", gitdiff_oldname }, 845{"+++ ", gitdiff_newname }, 846{"old mode ", gitdiff_oldmode }, 847{"new mode ", gitdiff_newmode }, 848{"deleted file mode ", gitdiff_delete }, 849{"new file mode ", gitdiff_newfile }, 850{"copy from ", gitdiff_copysrc }, 851{"copy to ", gitdiff_copydst }, 852{"rename old ", gitdiff_renamesrc }, 853{"rename new ", gitdiff_renamedst }, 854{"rename from ", gitdiff_renamesrc }, 855{"rename to ", gitdiff_renamedst }, 856{"similarity index ", gitdiff_similarity }, 857{"dissimilarity index ", gitdiff_dissimilarity }, 858{"index ", gitdiff_index }, 859{"", gitdiff_unrecognized }, 860}; 861int i; 862 863 len =linelen(line, size); 864if(!len || line[len-1] !='\n') 865break; 866for(i =0; i <ARRAY_SIZE(optable); i++) { 867const struct opentry *p = optable + i; 868int oplen =strlen(p->str); 869if(len < oplen ||memcmp(p->str, line, oplen)) 870continue; 871if(p->fn(line + oplen, patch) <0) 872return offset; 873break; 874} 875} 876 877return offset; 878} 879 880static intparse_num(const char*line,unsigned long*p) 881{ 882char*ptr; 883 884if(!isdigit(*line)) 885return0; 886*p =strtoul(line, &ptr,10); 887return ptr - line; 888} 889 890static intparse_range(const char*line,int len,int offset,const char*expect, 891unsigned long*p1,unsigned long*p2) 892{ 893int digits, ex; 894 895if(offset <0|| offset >= len) 896return-1; 897 line += offset; 898 len -= offset; 899 900 digits =parse_num(line, p1); 901if(!digits) 902return-1; 903 904 offset += digits; 905 line += digits; 906 len -= digits; 907 908*p2 =1; 909if(*line ==',') { 910 digits =parse_num(line+1, p2); 911if(!digits) 912return-1; 913 914 offset += digits+1; 915 line += digits+1; 916 len -= digits+1; 917} 918 919 ex =strlen(expect); 920if(ex > len) 921return-1; 922if(memcmp(line, expect, ex)) 923return-1; 924 925return offset + ex; 926} 927 928static voidrecount_diff(char*line,int size,struct fragment *fragment) 929{ 930int oldlines =0, newlines =0, ret =0; 931 932if(size <1) { 933warning("recount: ignore empty hunk"); 934return; 935} 936 937for(;;) { 938int len =linelen(line, size); 939 size -= len; 940 line += len; 941 942if(size <1) 943break; 944 945switch(*line) { 946case' ':case'\n': 947 newlines++; 948/* fall through */ 949case'-': 950 oldlines++; 951continue; 952case'+': 953 newlines++; 954continue; 955case'\\': 956continue; 957case'@': 958 ret = size <3||prefixcmp(line,"@@ "); 959break; 960case'd': 961 ret = size <5||prefixcmp(line,"diff "); 962break; 963default: 964 ret = -1; 965break; 966} 967if(ret) { 968warning("recount: unexpected line: %.*s", 969(int)linelen(line, size), line); 970return; 971} 972break; 973} 974 fragment->oldlines = oldlines; 975 fragment->newlines = newlines; 976} 977 978/* 979 * Parse a unified diff fragment header of the 980 * form "@@ -a,b +c,d @@" 981 */ 982static intparse_fragment_header(char*line,int len,struct fragment *fragment) 983{ 984int offset; 985 986if(!len || line[len-1] !='\n') 987return-1; 988 989/* Figure out the number of lines in a fragment */ 990 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines); 991 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines); 992 993return offset; 994} 995 996static intfind_header(char*line,unsigned long size,int*hdrsize,struct patch *patch) 997{ 998unsigned long offset, len; 9991000 patch->is_toplevel_relative =0;1001 patch->is_rename = patch->is_copy =0;1002 patch->is_new = patch->is_delete = -1;1003 patch->old_mode = patch->new_mode =0;1004 patch->old_name = patch->new_name = NULL;1005for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) {1006unsigned long nextlen;10071008 len =linelen(line, size);1009if(!len)1010break;10111012/* Testing this early allows us to take a few shortcuts.. */1013if(len <6)1014continue;10151016/*1017 * Make sure we don't find any unconnected patch fragments.1018 * That's a sign that we didn't find a header, and that a1019 * patch has become corrupted/broken up.1020 */1021if(!memcmp("@@ -", line,4)) {1022struct fragment dummy;1023if(parse_fragment_header(line, len, &dummy) <0)1024continue;1025die("patch fragment without header at line%d: %.*s",1026 linenr, (int)len-1, line);1027}10281029if(size < len +6)1030break;10311032/*1033 * Git patch? It might not have a real patch, just a rename1034 * or mode change, so we handle that specially1035 */1036if(!memcmp("diff --git ", line,11)) {1037int git_hdr_len =parse_git_header(line, len, size, patch);1038if(git_hdr_len <= len)1039continue;1040if(!patch->old_name && !patch->new_name) {1041if(!patch->def_name)1042die("git diff header lacks filename information (line%d)", linenr);1043 patch->old_name = patch->new_name = patch->def_name;1044}1045 patch->is_toplevel_relative =1;1046*hdrsize = git_hdr_len;1047return offset;1048}10491050/* --- followed by +++ ? */1051if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1052continue;10531054/*1055 * We only accept unified patches, so we want it to1056 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1057 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1058 */1059 nextlen =linelen(line + len, size - len);1060if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1061continue;10621063/* Ok, we'll consider it a patch */1064parse_traditional_patch(line, line+len, patch);1065*hdrsize = len + nextlen;1066 linenr +=2;1067return offset;1068}1069return-1;1070}10711072static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1073{1074char*err;1075unsigned result =ws_check(line +1, len -1, ws_rule);1076if(!result)1077return;10781079 whitespace_error++;1080if(squelch_whitespace_errors &&1081 squelch_whitespace_errors < whitespace_error)1082;1083else{1084 err =whitespace_error_string(result);1085fprintf(stderr,"%s:%d:%s.\n%.*s\n",1086 patch_input_file, linenr, err, len -2, line +1);1087free(err);1088}1089}10901091/*1092 * Parse a unified diff. Note that this really needs to parse each1093 * fragment separately, since the only way to know the difference1094 * between a "---" that is part of a patch, and a "---" that starts1095 * the next patch is to look at the line counts..1096 */1097static intparse_fragment(char*line,unsigned long size,1098struct patch *patch,struct fragment *fragment)1099{1100int added, deleted;1101int len =linelen(line, size), offset;1102unsigned long oldlines, newlines;1103unsigned long leading, trailing;11041105 offset =parse_fragment_header(line, len, fragment);1106if(offset <0)1107return-1;1108if(offset >0&& patch->recount)1109recount_diff(line + offset, size - offset, fragment);1110 oldlines = fragment->oldlines;1111 newlines = fragment->newlines;1112 leading =0;1113 trailing =0;11141115/* Parse the thing.. */1116 line += len;1117 size -= len;1118 linenr++;1119 added = deleted =0;1120for(offset = len;11210< size;1122 offset += len, size -= len, line += len, linenr++) {1123if(!oldlines && !newlines)1124break;1125 len =linelen(line, size);1126if(!len || line[len-1] !='\n')1127return-1;1128switch(*line) {1129default:1130return-1;1131case'\n':/* newer GNU diff, an empty context line */1132case' ':1133 oldlines--;1134 newlines--;1135if(!deleted && !added)1136 leading++;1137 trailing++;1138break;1139case'-':1140if(apply_in_reverse &&1141 ws_error_action != nowarn_ws_error)1142check_whitespace(line, len, patch->ws_rule);1143 deleted++;1144 oldlines--;1145 trailing =0;1146break;1147case'+':1148if(!apply_in_reverse &&1149 ws_error_action != nowarn_ws_error)1150check_whitespace(line, len, patch->ws_rule);1151 added++;1152 newlines--;1153 trailing =0;1154break;11551156/*1157 * We allow "\ No newline at end of file". Depending1158 * on locale settings when the patch was produced we1159 * don't know what this line looks like. The only1160 * thing we do know is that it begins with "\ ".1161 * Checking for 12 is just for sanity check -- any1162 * l10n of "\ No newline..." is at least that long.1163 */1164case'\\':1165if(len <12||memcmp(line,"\\",2))1166return-1;1167break;1168}1169}1170if(oldlines || newlines)1171return-1;1172 fragment->leading = leading;1173 fragment->trailing = trailing;11741175/*1176 * If a fragment ends with an incomplete line, we failed to include1177 * it in the above loop because we hit oldlines == newlines == 01178 * before seeing it.1179 */1180if(12< size && !memcmp(line,"\\",2))1181 offset +=linelen(line, size);11821183 patch->lines_added += added;1184 patch->lines_deleted += deleted;11851186if(0< patch->is_new && oldlines)1187returnerror("new file depends on old contents");1188if(0< patch->is_delete && newlines)1189returnerror("deleted file still has contents");1190return offset;1191}11921193static intparse_single_patch(char*line,unsigned long size,struct patch *patch)1194{1195unsigned long offset =0;1196unsigned long oldlines =0, newlines =0, context =0;1197struct fragment **fragp = &patch->fragments;11981199while(size >4&& !memcmp(line,"@@ -",4)) {1200struct fragment *fragment;1201int len;12021203 fragment =xcalloc(1,sizeof(*fragment));1204 len =parse_fragment(line, size, patch, fragment);1205if(len <=0)1206die("corrupt patch at line%d", linenr);1207 fragment->patch = line;1208 fragment->size = len;1209 oldlines += fragment->oldlines;1210 newlines += fragment->newlines;1211 context += fragment->leading + fragment->trailing;12121213*fragp = fragment;1214 fragp = &fragment->next;12151216 offset += len;1217 line += len;1218 size -= len;1219}12201221/*1222 * If something was removed (i.e. we have old-lines) it cannot1223 * be creation, and if something was added it cannot be1224 * deletion. However, the reverse is not true; --unified=01225 * patches that only add are not necessarily creation even1226 * though they do not have any old lines, and ones that only1227 * delete are not necessarily deletion.1228 *1229 * Unfortunately, a real creation/deletion patch do _not_ have1230 * any context line by definition, so we cannot safely tell it1231 * apart with --unified=0 insanity. At least if the patch has1232 * more than one hunk it is not creation or deletion.1233 */1234if(patch->is_new <0&&1235(oldlines || (patch->fragments && patch->fragments->next)))1236 patch->is_new =0;1237if(patch->is_delete <0&&1238(newlines || (patch->fragments && patch->fragments->next)))1239 patch->is_delete =0;12401241if(0< patch->is_new && oldlines)1242die("new file%sdepends on old contents", patch->new_name);1243if(0< patch->is_delete && newlines)1244die("deleted file%sstill has contents", patch->old_name);1245if(!patch->is_delete && !newlines && context)1246fprintf(stderr,"** warning: file%sbecomes empty but "1247"is not deleted\n", patch->new_name);12481249return offset;1250}12511252staticinlineintmetadata_changes(struct patch *patch)1253{1254return patch->is_rename >0||1255 patch->is_copy >0||1256 patch->is_new >0||1257 patch->is_delete ||1258(patch->old_mode && patch->new_mode &&1259 patch->old_mode != patch->new_mode);1260}12611262static char*inflate_it(const void*data,unsigned long size,1263unsigned long inflated_size)1264{1265 z_stream stream;1266void*out;1267int st;12681269memset(&stream,0,sizeof(stream));12701271 stream.next_in = (unsigned char*)data;1272 stream.avail_in = size;1273 stream.next_out = out =xmalloc(inflated_size);1274 stream.avail_out = inflated_size;1275git_inflate_init(&stream);1276 st =git_inflate(&stream, Z_FINISH);1277git_inflate_end(&stream);1278if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1279free(out);1280return NULL;1281}1282return out;1283}12841285static struct fragment *parse_binary_hunk(char**buf_p,1286unsigned long*sz_p,1287int*status_p,1288int*used_p)1289{1290/*1291 * Expect a line that begins with binary patch method ("literal"1292 * or "delta"), followed by the length of data before deflating.1293 * a sequence of 'length-byte' followed by base-85 encoded data1294 * should follow, terminated by a newline.1295 *1296 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1297 * and we would limit the patch line to 66 characters,1298 * so one line can fit up to 13 groups that would decode1299 * to 52 bytes max. The length byte 'A'-'Z' corresponds1300 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1301 */1302int llen, used;1303unsigned long size = *sz_p;1304char*buffer = *buf_p;1305int patch_method;1306unsigned long origlen;1307char*data = NULL;1308int hunk_size =0;1309struct fragment *frag;13101311 llen =linelen(buffer, size);1312 used = llen;13131314*status_p =0;13151316if(!prefixcmp(buffer,"delta ")) {1317 patch_method = BINARY_DELTA_DEFLATED;1318 origlen =strtoul(buffer +6, NULL,10);1319}1320else if(!prefixcmp(buffer,"literal ")) {1321 patch_method = BINARY_LITERAL_DEFLATED;1322 origlen =strtoul(buffer +8, NULL,10);1323}1324else1325return NULL;13261327 linenr++;1328 buffer += llen;1329while(1) {1330int byte_length, max_byte_length, newsize;1331 llen =linelen(buffer, size);1332 used += llen;1333 linenr++;1334if(llen ==1) {1335/* consume the blank line */1336 buffer++;1337 size--;1338break;1339}1340/*1341 * Minimum line is "A00000\n" which is 7-byte long,1342 * and the line length must be multiple of 5 plus 2.1343 */1344if((llen <7) || (llen-2) %5)1345goto corrupt;1346 max_byte_length = (llen -2) /5*4;1347 byte_length = *buffer;1348if('A'<= byte_length && byte_length <='Z')1349 byte_length = byte_length -'A'+1;1350else if('a'<= byte_length && byte_length <='z')1351 byte_length = byte_length -'a'+27;1352else1353goto corrupt;1354/* if the input length was not multiple of 4, we would1355 * have filler at the end but the filler should never1356 * exceed 3 bytes1357 */1358if(max_byte_length < byte_length ||1359 byte_length <= max_byte_length -4)1360goto corrupt;1361 newsize = hunk_size + byte_length;1362 data =xrealloc(data, newsize);1363if(decode_85(data + hunk_size, buffer +1, byte_length))1364goto corrupt;1365 hunk_size = newsize;1366 buffer += llen;1367 size -= llen;1368}13691370 frag =xcalloc(1,sizeof(*frag));1371 frag->patch =inflate_it(data, hunk_size, origlen);1372if(!frag->patch)1373goto corrupt;1374free(data);1375 frag->size = origlen;1376*buf_p = buffer;1377*sz_p = size;1378*used_p = used;1379 frag->binary_patch_method = patch_method;1380return frag;13811382 corrupt:1383free(data);1384*status_p = -1;1385error("corrupt binary patch at line%d: %.*s",1386 linenr-1, llen-1, buffer);1387return NULL;1388}13891390static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1391{1392/*1393 * We have read "GIT binary patch\n"; what follows is a line1394 * that says the patch method (currently, either "literal" or1395 * "delta") and the length of data before deflating; a1396 * sequence of 'length-byte' followed by base-85 encoded data1397 * follows.1398 *1399 * When a binary patch is reversible, there is another binary1400 * hunk in the same format, starting with patch method (either1401 * "literal" or "delta") with the length of data, and a sequence1402 * of length-byte + base-85 encoded data, terminated with another1403 * empty line. This data, when applied to the postimage, produces1404 * the preimage.1405 */1406struct fragment *forward;1407struct fragment *reverse;1408int status;1409int used, used_1;14101411 forward =parse_binary_hunk(&buffer, &size, &status, &used);1412if(!forward && !status)1413/* there has to be one hunk (forward hunk) */1414returnerror("unrecognized binary patch at line%d", linenr-1);1415if(status)1416/* otherwise we already gave an error message */1417return status;14181419 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1420if(reverse)1421 used += used_1;1422else if(status) {1423/*1424 * Not having reverse hunk is not an error, but having1425 * a corrupt reverse hunk is.1426 */1427free((void*) forward->patch);1428free(forward);1429return status;1430}1431 forward->next = reverse;1432 patch->fragments = forward;1433 patch->is_binary =1;1434return used;1435}14361437static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1438{1439int hdrsize, patchsize;1440int offset =find_header(buffer, size, &hdrsize, patch);14411442if(offset <0)1443return offset;14441445 patch->ws_rule =whitespace_rule(patch->new_name1446? patch->new_name1447: patch->old_name);14481449 patchsize =parse_single_patch(buffer + offset + hdrsize,1450 size - offset - hdrsize, patch);14511452if(!patchsize) {1453static const char*binhdr[] = {1454"Binary files ",1455"Files ",1456 NULL,1457};1458static const char git_binary[] ="GIT binary patch\n";1459int i;1460int hd = hdrsize + offset;1461unsigned long llen =linelen(buffer + hd, size - hd);14621463if(llen ==sizeof(git_binary) -1&&1464!memcmp(git_binary, buffer + hd, llen)) {1465int used;1466 linenr++;1467 used =parse_binary(buffer + hd + llen,1468 size - hd - llen, patch);1469if(used)1470 patchsize = used + llen;1471else1472 patchsize =0;1473}1474else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1475for(i =0; binhdr[i]; i++) {1476int len =strlen(binhdr[i]);1477if(len < size - hd &&1478!memcmp(binhdr[i], buffer + hd, len)) {1479 linenr++;1480 patch->is_binary =1;1481 patchsize = llen;1482break;1483}1484}1485}14861487/* Empty patch cannot be applied if it is a text patch1488 * without metadata change. A binary patch appears1489 * empty to us here.1490 */1491if((apply || check) &&1492(!patch->is_binary && !metadata_changes(patch)))1493die("patch with only garbage at line%d", linenr);1494}14951496return offset + hdrsize + patchsize;1497}14981499#define swap(a,b) myswap((a),(b),sizeof(a))15001501#define myswap(a, b, size) do { \1502 unsigned char mytmp[size]; \1503 memcpy(mytmp, &a, size); \1504 memcpy(&a, &b, size); \1505 memcpy(&b, mytmp, size); \1506} while (0)15071508static voidreverse_patches(struct patch *p)1509{1510for(; p; p = p->next) {1511struct fragment *frag = p->fragments;15121513swap(p->new_name, p->old_name);1514swap(p->new_mode, p->old_mode);1515swap(p->is_new, p->is_delete);1516swap(p->lines_added, p->lines_deleted);1517swap(p->old_sha1_prefix, p->new_sha1_prefix);15181519for(; frag; frag = frag->next) {1520swap(frag->newpos, frag->oldpos);1521swap(frag->newlines, frag->oldlines);1522}1523}1524}15251526static const char pluses[] =1527"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";1528static const char minuses[]=1529"----------------------------------------------------------------------";15301531static voidshow_stats(struct patch *patch)1532{1533struct strbuf qname = STRBUF_INIT;1534char*cp = patch->new_name ? patch->new_name : patch->old_name;1535int max, add, del;15361537quote_c_style(cp, &qname, NULL,0);15381539/*1540 * "scale" the filename1541 */1542 max = max_len;1543if(max >50)1544 max =50;15451546if(qname.len > max) {1547 cp =strchr(qname.buf + qname.len +3- max,'/');1548if(!cp)1549 cp = qname.buf + qname.len +3- max;1550strbuf_splice(&qname,0, cp - qname.buf,"...",3);1551}15521553if(patch->is_binary) {1554printf(" %-*s | Bin\n", max, qname.buf);1555strbuf_release(&qname);1556return;1557}15581559printf(" %-*s |", max, qname.buf);1560strbuf_release(&qname);15611562/*1563 * scale the add/delete1564 */1565 max = max + max_change >70?70- max : max_change;1566 add = patch->lines_added;1567 del = patch->lines_deleted;15681569if(max_change >0) {1570int total = ((add + del) * max + max_change /2) / max_change;1571 add = (add * max + max_change /2) / max_change;1572 del = total - add;1573}1574printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,1575 add, pluses, del, minuses);1576}15771578static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)1579{1580switch(st->st_mode & S_IFMT) {1581case S_IFLNK:1582if(strbuf_readlink(buf, path, st->st_size) <0)1583returnerror("unable to read symlink%s", path);1584return0;1585case S_IFREG:1586if(strbuf_read_file(buf, path, st->st_size) != st->st_size)1587returnerror("unable to open or read%s", path);1588convert_to_git(path, buf->buf, buf->len, buf,0);1589return0;1590default:1591return-1;1592}1593}15941595static voidupdate_pre_post_images(struct image *preimage,1596struct image *postimage,1597char*buf,1598size_t len)1599{1600int i, ctx;1601char*new, *old, *fixed;1602struct image fixed_preimage;16031604/*1605 * Update the preimage with whitespace fixes. Note that we1606 * are not losing preimage->buf -- apply_one_fragment() will1607 * free "oldlines".1608 */1609prepare_image(&fixed_preimage, buf, len,1);1610assert(fixed_preimage.nr == preimage->nr);1611for(i =0; i < preimage->nr; i++)1612 fixed_preimage.line[i].flag = preimage->line[i].flag;1613free(preimage->line_allocated);1614*preimage = fixed_preimage;16151616/*1617 * Adjust the common context lines in postimage, in place.1618 * This is possible because whitespace fixing does not make1619 * the string grow.1620 */1621new= old = postimage->buf;1622 fixed = preimage->buf;1623for(i = ctx =0; i < postimage->nr; i++) {1624size_t len = postimage->line[i].len;1625if(!(postimage->line[i].flag & LINE_COMMON)) {1626/* an added line -- no counterparts in preimage */1627memmove(new, old, len);1628 old += len;1629new+= len;1630continue;1631}16321633/* a common context -- skip it in the original postimage */1634 old += len;16351636/* and find the corresponding one in the fixed preimage */1637while(ctx < preimage->nr &&1638!(preimage->line[ctx].flag & LINE_COMMON)) {1639 fixed += preimage->line[ctx].len;1640 ctx++;1641}1642if(preimage->nr <= ctx)1643die("oops");16441645/* and copy it in, while fixing the line length */1646 len = preimage->line[ctx].len;1647memcpy(new, fixed, len);1648new+= len;1649 fixed += len;1650 postimage->line[i].len = len;1651 ctx++;1652}16531654/* Fix the length of the whole thing */1655 postimage->len =new- postimage->buf;1656}16571658static intmatch_fragment(struct image *img,1659struct image *preimage,1660struct image *postimage,1661unsigned longtry,1662int try_lno,1663unsigned ws_rule,1664int match_beginning,int match_end)1665{1666int i;1667char*fixed_buf, *buf, *orig, *target;16681669if(preimage->nr + try_lno > img->nr)1670return0;16711672if(match_beginning && try_lno)1673return0;16741675if(match_end && preimage->nr + try_lno != img->nr)1676return0;16771678/* Quick hash check */1679for(i =0; i < preimage->nr; i++)1680if(preimage->line[i].hash != img->line[try_lno + i].hash)1681return0;16821683/*1684 * Do we have an exact match? If we were told to match1685 * at the end, size must be exactly at try+fragsize,1686 * otherwise try+fragsize must be still within the preimage,1687 * and either case, the old piece should match the preimage1688 * exactly.1689 */1690if((match_end1691? (try+ preimage->len == img->len)1692: (try+ preimage->len <= img->len)) &&1693!memcmp(img->buf +try, preimage->buf, preimage->len))1694return1;16951696if(ws_error_action != correct_ws_error)1697return0;16981699/*1700 * The hunk does not apply byte-by-byte, but the hash says1701 * it might with whitespace fuzz.1702 */1703 fixed_buf =xmalloc(preimage->len +1);1704 buf = fixed_buf;1705 orig = preimage->buf;1706 target = img->buf +try;1707for(i =0; i < preimage->nr; i++) {1708size_t fixlen;/* length after fixing the preimage */1709size_t oldlen = preimage->line[i].len;1710size_t tgtlen = img->line[try_lno + i].len;1711size_t tgtfixlen;/* length after fixing the target line */1712char tgtfixbuf[1024], *tgtfix;1713int match;17141715/* Try fixing the line in the preimage */1716 fixlen =ws_fix_copy(buf, orig, oldlen, ws_rule, NULL);17171718/* Try fixing the line in the target */1719if(sizeof(tgtfixbuf) > tgtlen)1720 tgtfix = tgtfixbuf;1721else1722 tgtfix =xmalloc(tgtlen);1723 tgtfixlen =ws_fix_copy(tgtfix, target, tgtlen, ws_rule, NULL);17241725/*1726 * If they match, either the preimage was based on1727 * a version before our tree fixed whitespace breakage,1728 * or we are lacking a whitespace-fix patch the tree1729 * the preimage was based on already had (i.e. target1730 * has whitespace breakage, the preimage doesn't).1731 * In either case, we are fixing the whitespace breakages1732 * so we might as well take the fix together with their1733 * real change.1734 */1735 match = (tgtfixlen == fixlen && !memcmp(tgtfix, buf, fixlen));17361737if(tgtfix != tgtfixbuf)1738free(tgtfix);1739if(!match)1740goto unmatch_exit;17411742 orig += oldlen;1743 buf += fixlen;1744 target += tgtlen;1745}17461747/*1748 * Yes, the preimage is based on an older version that still1749 * has whitespace breakages unfixed, and fixing them makes the1750 * hunk match. Update the context lines in the postimage.1751 */1752update_pre_post_images(preimage, postimage,1753 fixed_buf, buf - fixed_buf);1754return1;17551756 unmatch_exit:1757free(fixed_buf);1758return0;1759}17601761static intfind_pos(struct image *img,1762struct image *preimage,1763struct image *postimage,1764int line,1765unsigned ws_rule,1766int match_beginning,int match_end)1767{1768int i;1769unsigned long backwards, forwards,try;1770int backwards_lno, forwards_lno, try_lno;17711772if(preimage->nr > img->nr)1773return-1;17741775/*1776 * If match_begining or match_end is specified, there is no1777 * point starting from a wrong line that will never match and1778 * wander around and wait for a match at the specified end.1779 */1780if(match_beginning)1781 line =0;1782else if(match_end)1783 line = img->nr - preimage->nr;17841785if(line > img->nr)1786 line = img->nr;17871788try=0;1789for(i =0; i < line; i++)1790try+= img->line[i].len;17911792/*1793 * There's probably some smart way to do this, but I'll leave1794 * that to the smart and beautiful people. I'm simple and stupid.1795 */1796 backwards =try;1797 backwards_lno = line;1798 forwards =try;1799 forwards_lno = line;1800 try_lno = line;18011802for(i =0; ; i++) {1803if(match_fragment(img, preimage, postimage,1804try, try_lno, ws_rule,1805 match_beginning, match_end))1806return try_lno;18071808 again:1809if(backwards_lno ==0&& forwards_lno == img->nr)1810break;18111812if(i &1) {1813if(backwards_lno ==0) {1814 i++;1815goto again;1816}1817 backwards_lno--;1818 backwards -= img->line[backwards_lno].len;1819try= backwards;1820 try_lno = backwards_lno;1821}else{1822if(forwards_lno == img->nr) {1823 i++;1824goto again;1825}1826 forwards += img->line[forwards_lno].len;1827 forwards_lno++;1828try= forwards;1829 try_lno = forwards_lno;1830}18311832}1833return-1;1834}18351836static voidremove_first_line(struct image *img)1837{1838 img->buf += img->line[0].len;1839 img->len -= img->line[0].len;1840 img->line++;1841 img->nr--;1842}18431844static voidremove_last_line(struct image *img)1845{1846 img->len -= img->line[--img->nr].len;1847}18481849static voidupdate_image(struct image *img,1850int applied_pos,1851struct image *preimage,1852struct image *postimage)1853{1854/*1855 * remove the copy of preimage at offset in img1856 * and replace it with postimage1857 */1858int i, nr;1859size_t remove_count, insert_count, applied_at =0;1860char*result;18611862for(i =0; i < applied_pos; i++)1863 applied_at += img->line[i].len;18641865 remove_count =0;1866for(i =0; i < preimage->nr; i++)1867 remove_count += img->line[applied_pos + i].len;1868 insert_count = postimage->len;18691870/* Adjust the contents */1871 result =xmalloc(img->len + insert_count - remove_count +1);1872memcpy(result, img->buf, applied_at);1873memcpy(result + applied_at, postimage->buf, postimage->len);1874memcpy(result + applied_at + postimage->len,1875 img->buf + (applied_at + remove_count),1876 img->len - (applied_at + remove_count));1877free(img->buf);1878 img->buf = result;1879 img->len += insert_count - remove_count;1880 result[img->len] ='\0';18811882/* Adjust the line table */1883 nr = img->nr + postimage->nr - preimage->nr;1884if(preimage->nr < postimage->nr) {1885/*1886 * NOTE: this knows that we never call remove_first_line()1887 * on anything other than pre/post image.1888 */1889 img->line =xrealloc(img->line, nr *sizeof(*img->line));1890 img->line_allocated = img->line;1891}1892if(preimage->nr != postimage->nr)1893memmove(img->line + applied_pos + postimage->nr,1894 img->line + applied_pos + preimage->nr,1895(img->nr - (applied_pos + preimage->nr)) *1896sizeof(*img->line));1897memcpy(img->line + applied_pos,1898 postimage->line,1899 postimage->nr *sizeof(*img->line));1900 img->nr = nr;1901}19021903static intapply_one_fragment(struct image *img,struct fragment *frag,1904int inaccurate_eof,unsigned ws_rule)1905{1906int match_beginning, match_end;1907const char*patch = frag->patch;1908int size = frag->size;1909char*old, *new, *oldlines, *newlines;1910int new_blank_lines_at_end =0;1911unsigned long leading, trailing;1912int pos, applied_pos;1913struct image preimage;1914struct image postimage;19151916memset(&preimage,0,sizeof(preimage));1917memset(&postimage,0,sizeof(postimage));1918 oldlines =xmalloc(size);1919 newlines =xmalloc(size);19201921 old = oldlines;1922new= newlines;1923while(size >0) {1924char first;1925int len =linelen(patch, size);1926int plen, added;1927int added_blank_line =0;19281929if(!len)1930break;19311932/*1933 * "plen" is how much of the line we should use for1934 * the actual patch data. Normally we just remove the1935 * first character on the line, but if the line is1936 * followed by "\ No newline", then we also remove the1937 * last one (which is the newline, of course).1938 */1939 plen = len -1;1940if(len < size && patch[len] =='\\')1941 plen--;1942 first = *patch;1943if(apply_in_reverse) {1944if(first =='-')1945 first ='+';1946else if(first =='+')1947 first ='-';1948}19491950switch(first) {1951case'\n':1952/* Newer GNU diff, empty context line */1953if(plen <0)1954/* ... followed by '\No newline'; nothing */1955break;1956*old++ ='\n';1957*new++ ='\n';1958add_line_info(&preimage,"\n",1, LINE_COMMON);1959add_line_info(&postimage,"\n",1, LINE_COMMON);1960break;1961case' ':1962case'-':1963memcpy(old, patch +1, plen);1964add_line_info(&preimage, old, plen,1965(first ==' '? LINE_COMMON :0));1966 old += plen;1967if(first =='-')1968break;1969/* Fall-through for ' ' */1970case'+':1971/* --no-add does not add new lines */1972if(first =='+'&& no_add)1973break;19741975if(first !='+'||1976!whitespace_error ||1977 ws_error_action != correct_ws_error) {1978memcpy(new, patch +1, plen);1979 added = plen;1980}1981else{1982 added =ws_fix_copy(new, patch +1, plen, ws_rule, &applied_after_fixing_ws);1983}1984add_line_info(&postimage,new, added,1985(first =='+'?0: LINE_COMMON));1986new+= added;1987if(first =='+'&&1988 added ==1&&new[-1] =='\n')1989 added_blank_line =1;1990break;1991case'@':case'\\':1992/* Ignore it, we already handled it */1993break;1994default:1995if(apply_verbosely)1996error("invalid start of line: '%c'", first);1997return-1;1998}1999if(added_blank_line)2000 new_blank_lines_at_end++;2001else2002 new_blank_lines_at_end =0;2003 patch += len;2004 size -= len;2005}2006if(inaccurate_eof &&2007 old > oldlines && old[-1] =='\n'&&2008new> newlines &&new[-1] =='\n') {2009 old--;2010new--;2011}20122013 leading = frag->leading;2014 trailing = frag->trailing;20152016/*2017 * A hunk to change lines at the beginning would begin with2018 * @@ -1,L +N,M @@2019 * but we need to be careful. -U0 that inserts before the second2020 * line also has this pattern.2021 *2022 * And a hunk to add to an empty file would begin with2023 * @@ -0,0 +N,M @@2024 *2025 * In other words, a hunk that is (frag->oldpos <= 1) with or2026 * without leading context must match at the beginning.2027 */2028 match_beginning = (!frag->oldpos ||2029(frag->oldpos ==1&& !unidiff_zero));20302031/*2032 * A hunk without trailing lines must match at the end.2033 * However, we simply cannot tell if a hunk must match end2034 * from the lack of trailing lines if the patch was generated2035 * with unidiff without any context.2036 */2037 match_end = !unidiff_zero && !trailing;20382039 pos = frag->newpos ? (frag->newpos -1) :0;2040 preimage.buf = oldlines;2041 preimage.len = old - oldlines;2042 postimage.buf = newlines;2043 postimage.len =new- newlines;2044 preimage.line = preimage.line_allocated;2045 postimage.line = postimage.line_allocated;20462047for(;;) {20482049 applied_pos =find_pos(img, &preimage, &postimage, pos,2050 ws_rule, match_beginning, match_end);20512052if(applied_pos >=0)2053break;20542055/* Am I at my context limits? */2056if((leading <= p_context) && (trailing <= p_context))2057break;2058if(match_beginning || match_end) {2059 match_beginning = match_end =0;2060continue;2061}20622063/*2064 * Reduce the number of context lines; reduce both2065 * leading and trailing if they are equal otherwise2066 * just reduce the larger context.2067 */2068if(leading >= trailing) {2069remove_first_line(&preimage);2070remove_first_line(&postimage);2071 pos--;2072 leading--;2073}2074if(trailing > leading) {2075remove_last_line(&preimage);2076remove_last_line(&postimage);2077 trailing--;2078}2079}20802081if(applied_pos >=0) {2082if(ws_error_action == correct_ws_error &&2083 new_blank_lines_at_end &&2084 postimage.nr + applied_pos == img->nr) {2085/*2086 * If the patch application adds blank lines2087 * at the end, and if the patch applies at the2088 * end of the image, remove those added blank2089 * lines.2090 */2091while(new_blank_lines_at_end--)2092remove_last_line(&postimage);2093}20942095/*2096 * Warn if it was necessary to reduce the number2097 * of context lines.2098 */2099if((leading != frag->leading) ||2100(trailing != frag->trailing))2101fprintf(stderr,"Context reduced to (%ld/%ld)"2102" to apply fragment at%d\n",2103 leading, trailing, applied_pos+1);2104update_image(img, applied_pos, &preimage, &postimage);2105}else{2106if(apply_verbosely)2107error("while searching for:\n%.*s",2108(int)(old - oldlines), oldlines);2109}21102111free(oldlines);2112free(newlines);2113free(preimage.line_allocated);2114free(postimage.line_allocated);21152116return(applied_pos <0);2117}21182119static intapply_binary_fragment(struct image *img,struct patch *patch)2120{2121struct fragment *fragment = patch->fragments;2122unsigned long len;2123void*dst;21242125/* Binary patch is irreversible without the optional second hunk */2126if(apply_in_reverse) {2127if(!fragment->next)2128returnerror("cannot reverse-apply a binary patch "2129"without the reverse hunk to '%s'",2130 patch->new_name2131? patch->new_name : patch->old_name);2132 fragment = fragment->next;2133}2134switch(fragment->binary_patch_method) {2135case BINARY_DELTA_DEFLATED:2136 dst =patch_delta(img->buf, img->len, fragment->patch,2137 fragment->size, &len);2138if(!dst)2139return-1;2140clear_image(img);2141 img->buf = dst;2142 img->len = len;2143return0;2144case BINARY_LITERAL_DEFLATED:2145clear_image(img);2146 img->len = fragment->size;2147 img->buf =xmalloc(img->len+1);2148memcpy(img->buf, fragment->patch, img->len);2149 img->buf[img->len] ='\0';2150return0;2151}2152return-1;2153}21542155static intapply_binary(struct image *img,struct patch *patch)2156{2157const char*name = patch->old_name ? patch->old_name : patch->new_name;2158unsigned char sha1[20];21592160/*2161 * For safety, we require patch index line to contain2162 * full 40-byte textual SHA1 for old and new, at least for now.2163 */2164if(strlen(patch->old_sha1_prefix) !=40||2165strlen(patch->new_sha1_prefix) !=40||2166get_sha1_hex(patch->old_sha1_prefix, sha1) ||2167get_sha1_hex(patch->new_sha1_prefix, sha1))2168returnerror("cannot apply binary patch to '%s' "2169"without full index line", name);21702171if(patch->old_name) {2172/*2173 * See if the old one matches what the patch2174 * applies to.2175 */2176hash_sha1_file(img->buf, img->len, blob_type, sha1);2177if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2178returnerror("the patch applies to '%s' (%s), "2179"which does not match the "2180"current contents.",2181 name,sha1_to_hex(sha1));2182}2183else{2184/* Otherwise, the old one must be empty. */2185if(img->len)2186returnerror("the patch applies to an empty "2187"'%s' but it is not empty", name);2188}21892190get_sha1_hex(patch->new_sha1_prefix, sha1);2191if(is_null_sha1(sha1)) {2192clear_image(img);2193return0;/* deletion patch */2194}21952196if(has_sha1_file(sha1)) {2197/* We already have the postimage */2198enum object_type type;2199unsigned long size;2200char*result;22012202 result =read_sha1_file(sha1, &type, &size);2203if(!result)2204returnerror("the necessary postimage%sfor "2205"'%s' cannot be read",2206 patch->new_sha1_prefix, name);2207clear_image(img);2208 img->buf = result;2209 img->len = size;2210}else{2211/*2212 * We have verified buf matches the preimage;2213 * apply the patch data to it, which is stored2214 * in the patch->fragments->{patch,size}.2215 */2216if(apply_binary_fragment(img, patch))2217returnerror("binary patch does not apply to '%s'",2218 name);22192220/* verify that the result matches */2221hash_sha1_file(img->buf, img->len, blob_type, sha1);2222if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2223returnerror("binary patch to '%s' creates incorrect result (expecting%s, got%s)",2224 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2225}22262227return0;2228}22292230static intapply_fragments(struct image *img,struct patch *patch)2231{2232struct fragment *frag = patch->fragments;2233const char*name = patch->old_name ? patch->old_name : patch->new_name;2234unsigned ws_rule = patch->ws_rule;2235unsigned inaccurate_eof = patch->inaccurate_eof;22362237if(patch->is_binary)2238returnapply_binary(img, patch);22392240while(frag) {2241if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule)) {2242error("patch failed:%s:%ld", name, frag->oldpos);2243if(!apply_with_reject)2244return-1;2245 frag->rejected =1;2246}2247 frag = frag->next;2248}2249return0;2250}22512252static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2253{2254if(!ce)2255return0;22562257if(S_ISGITLINK(ce->ce_mode)) {2258strbuf_grow(buf,100);2259strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2260}else{2261enum object_type type;2262unsigned long sz;2263char*result;22642265 result =read_sha1_file(ce->sha1, &type, &sz);2266if(!result)2267return-1;2268/* XXX read_sha1_file NUL-terminates */2269strbuf_attach(buf, result, sz, sz +1);2270}2271return0;2272}22732274static struct patch *in_fn_table(const char*name)2275{2276struct string_list_item *item;22772278if(name == NULL)2279return NULL;22802281 item =string_list_lookup(name, &fn_table);2282if(item != NULL)2283return(struct patch *)item->util;22842285return NULL;2286}22872288/*2289 * item->util in the filename table records the status of the path.2290 * Usually it points at a patch (whose result records the contents2291 * of it after applying it), but it could be PATH_WAS_DELETED for a2292 * path that a previously applied patch has already removed.2293 */2294#define PATH_TO_BE_DELETED ((struct patch *) -2)2295#define PATH_WAS_DELETED ((struct patch *) -1)22962297static intto_be_deleted(struct patch *patch)2298{2299return patch == PATH_TO_BE_DELETED;2300}23012302static intwas_deleted(struct patch *patch)2303{2304return patch == PATH_WAS_DELETED;2305}23062307static voidadd_to_fn_table(struct patch *patch)2308{2309struct string_list_item *item;23102311/*2312 * Always add new_name unless patch is a deletion2313 * This should cover the cases for normal diffs,2314 * file creations and copies2315 */2316if(patch->new_name != NULL) {2317 item =string_list_insert(patch->new_name, &fn_table);2318 item->util = patch;2319}23202321/*2322 * store a failure on rename/deletion cases because2323 * later chunks shouldn't patch old names2324 */2325if((patch->new_name == NULL) || (patch->is_rename)) {2326 item =string_list_insert(patch->old_name, &fn_table);2327 item->util = PATH_WAS_DELETED;2328}2329}23302331static voidprepare_fn_table(struct patch *patch)2332{2333/*2334 * store information about incoming file deletion2335 */2336while(patch) {2337if((patch->new_name == NULL) || (patch->is_rename)) {2338struct string_list_item *item;2339 item =string_list_insert(patch->old_name, &fn_table);2340 item->util = PATH_TO_BE_DELETED;2341}2342 patch = patch->next;2343}2344}23452346static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)2347{2348struct strbuf buf = STRBUF_INIT;2349struct image image;2350size_t len;2351char*img;2352struct patch *tpatch;23532354if(!(patch->is_copy || patch->is_rename) &&2355(tpatch =in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {2356if(was_deleted(tpatch)) {2357returnerror("patch%shas been renamed/deleted",2358 patch->old_name);2359}2360/* We have a patched copy in memory use that */2361strbuf_add(&buf, tpatch->result, tpatch->resultsize);2362}else if(cached) {2363if(read_file_or_gitlink(ce, &buf))2364returnerror("read of%sfailed", patch->old_name);2365}else if(patch->old_name) {2366if(S_ISGITLINK(patch->old_mode)) {2367if(ce) {2368read_file_or_gitlink(ce, &buf);2369}else{2370/*2371 * There is no way to apply subproject2372 * patch without looking at the index.2373 */2374 patch->fragments = NULL;2375}2376}else{2377if(read_old_data(st, patch->old_name, &buf))2378returnerror("read of%sfailed", patch->old_name);2379}2380}23812382 img =strbuf_detach(&buf, &len);2383prepare_image(&image, img, len, !patch->is_binary);23842385if(apply_fragments(&image, patch) <0)2386return-1;/* note with --reject this succeeds. */2387 patch->result = image.buf;2388 patch->resultsize = image.len;2389add_to_fn_table(patch);2390free(image.line_allocated);23912392if(0< patch->is_delete && patch->resultsize)2393returnerror("removal patch leaves file contents");23942395return0;2396}23972398static intcheck_to_create_blob(const char*new_name,int ok_if_exists)2399{2400struct stat nst;2401if(!lstat(new_name, &nst)) {2402if(S_ISDIR(nst.st_mode) || ok_if_exists)2403return0;2404/*2405 * A leading component of new_name might be a symlink2406 * that is going to be removed with this patch, but2407 * still pointing at somewhere that has the path.2408 * In such a case, path "new_name" does not exist as2409 * far as git is concerned.2410 */2411if(has_symlink_leading_path(new_name,strlen(new_name)))2412return0;24132414returnerror("%s: already exists in working directory", new_name);2415}2416else if((errno != ENOENT) && (errno != ENOTDIR))2417returnerror("%s:%s", new_name,strerror(errno));2418return0;2419}24202421static intverify_index_match(struct cache_entry *ce,struct stat *st)2422{2423if(S_ISGITLINK(ce->ce_mode)) {2424if(!S_ISDIR(st->st_mode))2425return-1;2426return0;2427}2428returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID);2429}24302431static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)2432{2433const char*old_name = patch->old_name;2434struct patch *tpatch = NULL;2435int stat_ret =0;2436unsigned st_mode =0;24372438/*2439 * Make sure that we do not have local modifications from the2440 * index when we are looking at the index. Also make sure2441 * we have the preimage file to be patched in the work tree,2442 * unless --cached, which tells git to apply only in the index.2443 */2444if(!old_name)2445return0;24462447assert(patch->is_new <=0);24482449if(!(patch->is_copy || patch->is_rename) &&2450(tpatch =in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {2451if(was_deleted(tpatch))2452returnerror("%s: has been deleted/renamed", old_name);2453 st_mode = tpatch->new_mode;2454}else if(!cached) {2455 stat_ret =lstat(old_name, st);2456if(stat_ret && errno != ENOENT)2457returnerror("%s:%s", old_name,strerror(errno));2458}24592460if(to_be_deleted(tpatch))2461 tpatch = NULL;24622463if(check_index && !tpatch) {2464int pos =cache_name_pos(old_name,strlen(old_name));2465if(pos <0) {2466if(patch->is_new <0)2467goto is_new;2468returnerror("%s: does not exist in index", old_name);2469}2470*ce = active_cache[pos];2471if(stat_ret <0) {2472struct checkout costate;2473/* checkout */2474 costate.base_dir ="";2475 costate.base_dir_len =0;2476 costate.force =0;2477 costate.quiet =0;2478 costate.not_new =0;2479 costate.refresh_cache =1;2480if(checkout_entry(*ce, &costate, NULL) ||2481lstat(old_name, st))2482return-1;2483}2484if(!cached &&verify_index_match(*ce, st))2485returnerror("%s: does not match index", old_name);2486if(cached)2487 st_mode = (*ce)->ce_mode;2488}else if(stat_ret <0) {2489if(patch->is_new <0)2490goto is_new;2491returnerror("%s:%s", old_name,strerror(errno));2492}24932494if(!cached && !tpatch)2495 st_mode =ce_mode_from_stat(*ce, st->st_mode);24962497if(patch->is_new <0)2498 patch->is_new =0;2499if(!patch->old_mode)2500 patch->old_mode = st_mode;2501if((st_mode ^ patch->old_mode) & S_IFMT)2502returnerror("%s: wrong type", old_name);2503if(st_mode != patch->old_mode)2504warning("%shas type%o, expected%o",2505 old_name, st_mode, patch->old_mode);2506if(!patch->new_mode && !patch->is_delete)2507 patch->new_mode = st_mode;2508return0;25092510 is_new:2511 patch->is_new =1;2512 patch->is_delete =0;2513 patch->old_name = NULL;2514return0;2515}25162517static intcheck_patch(struct patch *patch)2518{2519struct stat st;2520const char*old_name = patch->old_name;2521const char*new_name = patch->new_name;2522const char*name = old_name ? old_name : new_name;2523struct cache_entry *ce = NULL;2524struct patch *tpatch;2525int ok_if_exists;2526int status;25272528 patch->rejected =1;/* we will drop this after we succeed */25292530 status =check_preimage(patch, &ce, &st);2531if(status)2532return status;2533 old_name = patch->old_name;25342535if((tpatch =in_fn_table(new_name)) &&2536(was_deleted(tpatch) ||to_be_deleted(tpatch)))2537/*2538 * A type-change diff is always split into a patch to2539 * delete old, immediately followed by a patch to2540 * create new (see diff.c::run_diff()); in such a case2541 * it is Ok that the entry to be deleted by the2542 * previous patch is still in the working tree and in2543 * the index.2544 */2545 ok_if_exists =1;2546else2547 ok_if_exists =0;25482549if(new_name &&2550((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {2551if(check_index &&2552cache_name_pos(new_name,strlen(new_name)) >=0&&2553!ok_if_exists)2554returnerror("%s: already exists in index", new_name);2555if(!cached) {2556int err =check_to_create_blob(new_name, ok_if_exists);2557if(err)2558return err;2559}2560if(!patch->new_mode) {2561if(0< patch->is_new)2562 patch->new_mode = S_IFREG |0644;2563else2564 patch->new_mode = patch->old_mode;2565}2566}25672568if(new_name && old_name) {2569int same = !strcmp(old_name, new_name);2570if(!patch->new_mode)2571 patch->new_mode = patch->old_mode;2572if((patch->old_mode ^ patch->new_mode) & S_IFMT)2573returnerror("new mode (%o) of%sdoes not match old mode (%o)%s%s",2574 patch->new_mode, new_name, patch->old_mode,2575 same ?"":" of ", same ?"": old_name);2576}25772578if(apply_data(patch, &st, ce) <0)2579returnerror("%s: patch does not apply", name);2580 patch->rejected =0;2581return0;2582}25832584static intcheck_patch_list(struct patch *patch)2585{2586int err =0;25872588prepare_fn_table(patch);2589while(patch) {2590if(apply_verbosely)2591say_patch_name(stderr,2592"Checking patch ", patch,"...\n");2593 err |=check_patch(patch);2594 patch = patch->next;2595}2596return err;2597}25982599/* This function tries to read the sha1 from the current index */2600static intget_current_sha1(const char*path,unsigned char*sha1)2601{2602int pos;26032604if(read_cache() <0)2605return-1;2606 pos =cache_name_pos(path,strlen(path));2607if(pos <0)2608return-1;2609hashcpy(sha1, active_cache[pos]->sha1);2610return0;2611}26122613/* Build an index that contains the just the files needed for a 3way merge */2614static voidbuild_fake_ancestor(struct patch *list,const char*filename)2615{2616struct patch *patch;2617struct index_state result = { NULL };2618int fd;26192620/* Once we start supporting the reverse patch, it may be2621 * worth showing the new sha1 prefix, but until then...2622 */2623for(patch = list; patch; patch = patch->next) {2624const unsigned char*sha1_ptr;2625unsigned char sha1[20];2626struct cache_entry *ce;2627const char*name;26282629 name = patch->old_name ? patch->old_name : patch->new_name;2630if(0< patch->is_new)2631continue;2632else if(get_sha1(patch->old_sha1_prefix, sha1))2633/* git diff has no index line for mode/type changes */2634if(!patch->lines_added && !patch->lines_deleted) {2635if(get_current_sha1(patch->new_name, sha1) ||2636get_current_sha1(patch->old_name, sha1))2637die("mode change for%s, which is not "2638"in current HEAD", name);2639 sha1_ptr = sha1;2640}else2641die("sha1 information is lacking or useless "2642"(%s).", name);2643else2644 sha1_ptr = sha1;26452646 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);2647if(!ce)2648die("make_cache_entry failed for path '%s'", name);2649if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))2650die("Could not add%sto temporary index", name);2651}26522653 fd =open(filename, O_WRONLY | O_CREAT,0666);2654if(fd <0||write_index(&result, fd) ||close(fd))2655die("Could not write temporary index to%s", filename);26562657discard_index(&result);2658}26592660static voidstat_patch_list(struct patch *patch)2661{2662int files, adds, dels;26632664for(files = adds = dels =0; patch ; patch = patch->next) {2665 files++;2666 adds += patch->lines_added;2667 dels += patch->lines_deleted;2668show_stats(patch);2669}26702671printf("%dfiles changed,%dinsertions(+),%ddeletions(-)\n", files, adds, dels);2672}26732674static voidnumstat_patch_list(struct patch *patch)2675{2676for( ; patch; patch = patch->next) {2677const char*name;2678 name = patch->new_name ? patch->new_name : patch->old_name;2679if(patch->is_binary)2680printf("-\t-\t");2681else2682printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);2683write_name_quoted(name, stdout, line_termination);2684}2685}26862687static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)2688{2689if(mode)2690printf("%smode%06o%s\n", newdelete, mode, name);2691else2692printf("%s %s\n", newdelete, name);2693}26942695static voidshow_mode_change(struct patch *p,int show_name)2696{2697if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {2698if(show_name)2699printf(" mode change%06o =>%06o%s\n",2700 p->old_mode, p->new_mode, p->new_name);2701else2702printf(" mode change%06o =>%06o\n",2703 p->old_mode, p->new_mode);2704}2705}27062707static voidshow_rename_copy(struct patch *p)2708{2709const char*renamecopy = p->is_rename ?"rename":"copy";2710const char*old, *new;27112712/* Find common prefix */2713 old = p->old_name;2714new= p->new_name;2715while(1) {2716const char*slash_old, *slash_new;2717 slash_old =strchr(old,'/');2718 slash_new =strchr(new,'/');2719if(!slash_old ||2720!slash_new ||2721 slash_old - old != slash_new -new||2722memcmp(old,new, slash_new -new))2723break;2724 old = slash_old +1;2725new= slash_new +1;2726}2727/* p->old_name thru old is the common prefix, and old and new2728 * through the end of names are renames2729 */2730if(old != p->old_name)2731printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,2732(int)(old - p->old_name), p->old_name,2733 old,new, p->score);2734else2735printf("%s %s=>%s(%d%%)\n", renamecopy,2736 p->old_name, p->new_name, p->score);2737show_mode_change(p,0);2738}27392740static voidsummary_patch_list(struct patch *patch)2741{2742struct patch *p;27432744for(p = patch; p; p = p->next) {2745if(p->is_new)2746show_file_mode_name("create", p->new_mode, p->new_name);2747else if(p->is_delete)2748show_file_mode_name("delete", p->old_mode, p->old_name);2749else{2750if(p->is_rename || p->is_copy)2751show_rename_copy(p);2752else{2753if(p->score) {2754printf(" rewrite%s(%d%%)\n",2755 p->new_name, p->score);2756show_mode_change(p,0);2757}2758else2759show_mode_change(p,1);2760}2761}2762}2763}27642765static voidpatch_stats(struct patch *patch)2766{2767int lines = patch->lines_added + patch->lines_deleted;27682769if(lines > max_change)2770 max_change = lines;2771if(patch->old_name) {2772int len =quote_c_style(patch->old_name, NULL, NULL,0);2773if(!len)2774 len =strlen(patch->old_name);2775if(len > max_len)2776 max_len = len;2777}2778if(patch->new_name) {2779int len =quote_c_style(patch->new_name, NULL, NULL,0);2780if(!len)2781 len =strlen(patch->new_name);2782if(len > max_len)2783 max_len = len;2784}2785}27862787static voidremove_file(struct patch *patch,int rmdir_empty)2788{2789if(update_index) {2790if(remove_file_from_cache(patch->old_name) <0)2791die("unable to remove%sfrom index", patch->old_name);2792}2793if(!cached) {2794if(S_ISGITLINK(patch->old_mode)) {2795if(rmdir(patch->old_name))2796warning("unable to remove submodule%s",2797 patch->old_name);2798}else if(!unlink_or_warn(patch->old_name) && rmdir_empty) {2799remove_path(patch->old_name);2800}2801}2802}28032804static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)2805{2806struct stat st;2807struct cache_entry *ce;2808int namelen =strlen(path);2809unsigned ce_size =cache_entry_size(namelen);28102811if(!update_index)2812return;28132814 ce =xcalloc(1, ce_size);2815memcpy(ce->name, path, namelen);2816 ce->ce_mode =create_ce_mode(mode);2817 ce->ce_flags = namelen;2818if(S_ISGITLINK(mode)) {2819const char*s = buf;28202821if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))2822die("corrupt patch for subproject%s", path);2823}else{2824if(!cached) {2825if(lstat(path, &st) <0)2826die_errno("unable to stat newly created file '%s'",2827 path);2828fill_stat_cache_info(ce, &st);2829}2830if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)2831die("unable to create backing store for newly created file%s", path);2832}2833if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)2834die("unable to add cache entry for%s", path);2835}28362837static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)2838{2839int fd;2840struct strbuf nbuf = STRBUF_INIT;28412842if(S_ISGITLINK(mode)) {2843struct stat st;2844if(!lstat(path, &st) &&S_ISDIR(st.st_mode))2845return0;2846returnmkdir(path,0777);2847}28482849if(has_symlinks &&S_ISLNK(mode))2850/* Although buf:size is counted string, it also is NUL2851 * terminated.2852 */2853returnsymlink(buf, path);28542855 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);2856if(fd <0)2857return-1;28582859if(convert_to_working_tree(path, buf, size, &nbuf)) {2860 size = nbuf.len;2861 buf = nbuf.buf;2862}2863write_or_die(fd, buf, size);2864strbuf_release(&nbuf);28652866if(close(fd) <0)2867die_errno("closing file '%s'", path);2868return0;2869}28702871/*2872 * We optimistically assume that the directories exist,2873 * which is true 99% of the time anyway. If they don't,2874 * we create them and try again.2875 */2876static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)2877{2878if(cached)2879return;2880if(!try_create_file(path, mode, buf, size))2881return;28822883if(errno == ENOENT) {2884if(safe_create_leading_directories(path))2885return;2886if(!try_create_file(path, mode, buf, size))2887return;2888}28892890if(errno == EEXIST || errno == EACCES) {2891/* We may be trying to create a file where a directory2892 * used to be.2893 */2894struct stat st;2895if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))2896 errno = EEXIST;2897}28982899if(errno == EEXIST) {2900unsigned int nr =getpid();29012902for(;;) {2903char newpath[PATH_MAX];2904mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);2905if(!try_create_file(newpath, mode, buf, size)) {2906if(!rename(newpath, path))2907return;2908unlink_or_warn(newpath);2909break;2910}2911if(errno != EEXIST)2912break;2913++nr;2914}2915}2916die_errno("unable to write file '%s' mode%o", path, mode);2917}29182919static voidcreate_file(struct patch *patch)2920{2921char*path = patch->new_name;2922unsigned mode = patch->new_mode;2923unsigned long size = patch->resultsize;2924char*buf = patch->result;29252926if(!mode)2927 mode = S_IFREG |0644;2928create_one_file(path, mode, buf, size);2929add_index_file(path, mode, buf, size);2930}29312932/* phase zero is to remove, phase one is to create */2933static voidwrite_out_one_result(struct patch *patch,int phase)2934{2935if(patch->is_delete >0) {2936if(phase ==0)2937remove_file(patch,1);2938return;2939}2940if(patch->is_new >0|| patch->is_copy) {2941if(phase ==1)2942create_file(patch);2943return;2944}2945/*2946 * Rename or modification boils down to the same2947 * thing: remove the old, write the new2948 */2949if(phase ==0)2950remove_file(patch, patch->is_rename);2951if(phase ==1)2952create_file(patch);2953}29542955static intwrite_out_one_reject(struct patch *patch)2956{2957FILE*rej;2958char namebuf[PATH_MAX];2959struct fragment *frag;2960int cnt =0;29612962for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {2963if(!frag->rejected)2964continue;2965 cnt++;2966}29672968if(!cnt) {2969if(apply_verbosely)2970say_patch_name(stderr,2971"Applied patch ", patch," cleanly.\n");2972return0;2973}29742975/* This should not happen, because a removal patch that leaves2976 * contents are marked "rejected" at the patch level.2977 */2978if(!patch->new_name)2979die("internal error");29802981/* Say this even without --verbose */2982say_patch_name(stderr,"Applying patch ", patch," with");2983fprintf(stderr,"%drejects...\n", cnt);29842985 cnt =strlen(patch->new_name);2986if(ARRAY_SIZE(namebuf) <= cnt +5) {2987 cnt =ARRAY_SIZE(namebuf) -5;2988warning("truncating .rej filename to %.*s.rej",2989 cnt -1, patch->new_name);2990}2991memcpy(namebuf, patch->new_name, cnt);2992memcpy(namebuf + cnt,".rej",5);29932994 rej =fopen(namebuf,"w");2995if(!rej)2996returnerror("cannot open%s:%s", namebuf,strerror(errno));29972998/* Normal git tools never deal with .rej, so do not pretend2999 * this is a git patch by saying --git nor give extended3000 * headers. While at it, maybe please "kompare" that wants3001 * the trailing TAB and some garbage at the end of line ;-).3002 */3003fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",3004 patch->new_name, patch->new_name);3005for(cnt =1, frag = patch->fragments;3006 frag;3007 cnt++, frag = frag->next) {3008if(!frag->rejected) {3009fprintf(stderr,"Hunk #%dapplied cleanly.\n", cnt);3010continue;3011}3012fprintf(stderr,"Rejected hunk #%d.\n", cnt);3013fprintf(rej,"%.*s", frag->size, frag->patch);3014if(frag->patch[frag->size-1] !='\n')3015fputc('\n', rej);3016}3017fclose(rej);3018return-1;3019}30203021static intwrite_out_results(struct patch *list,int skipped_patch)3022{3023int phase;3024int errs =0;3025struct patch *l;30263027if(!list && !skipped_patch)3028returnerror("No changes");30293030for(phase =0; phase <2; phase++) {3031 l = list;3032while(l) {3033if(l->rejected)3034 errs =1;3035else{3036write_out_one_result(l, phase);3037if(phase ==1&&write_out_one_reject(l))3038 errs =1;3039}3040 l = l->next;3041}3042}3043return errs;3044}30453046static struct lock_file lock_file;30473048static struct string_list limit_by_name;3049static int has_include;3050static voidadd_name_limit(const char*name,int exclude)3051{3052struct string_list_item *it;30533054 it =string_list_append(name, &limit_by_name);3055 it->util = exclude ? NULL : (void*)1;3056}30573058static intuse_patch(struct patch *p)3059{3060const char*pathname = p->new_name ? p->new_name : p->old_name;3061int i;30623063/* Paths outside are not touched regardless of "--include" */3064if(0< prefix_length) {3065int pathlen =strlen(pathname);3066if(pathlen <= prefix_length ||3067memcmp(prefix, pathname, prefix_length))3068return0;3069}30703071/* See if it matches any of exclude/include rule */3072for(i =0; i < limit_by_name.nr; i++) {3073struct string_list_item *it = &limit_by_name.items[i];3074if(!fnmatch(it->string, pathname,0))3075return(it->util != NULL);3076}30773078/*3079 * If we had any include, a path that does not match any rule is3080 * not used. Otherwise, we saw bunch of exclude rules (or none)3081 * and such a path is used.3082 */3083return!has_include;3084}308530863087static voidprefix_one(char**name)3088{3089char*old_name = *name;3090if(!old_name)3091return;3092*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3093free(old_name);3094}30953096static voidprefix_patches(struct patch *p)3097{3098if(!prefix || p->is_toplevel_relative)3099return;3100for( ; p; p = p->next) {3101if(p->new_name == p->old_name) {3102char*prefixed = p->new_name;3103prefix_one(&prefixed);3104 p->new_name = p->old_name = prefixed;3105}3106else{3107prefix_one(&p->new_name);3108prefix_one(&p->old_name);3109}3110}3111}31123113#define INACCURATE_EOF (1<<0)3114#define RECOUNT (1<<1)31153116static intapply_patch(int fd,const char*filename,int options)3117{3118size_t offset;3119struct strbuf buf = STRBUF_INIT;3120struct patch *list = NULL, **listp = &list;3121int skipped_patch =0;31223123/* FIXME - memory leak when using multiple patch files as inputs */3124memset(&fn_table,0,sizeof(struct string_list));3125 patch_input_file = filename;3126read_patch_file(&buf, fd);3127 offset =0;3128while(offset < buf.len) {3129struct patch *patch;3130int nr;31313132 patch =xcalloc(1,sizeof(*patch));3133 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3134 patch->recount = !!(options & RECOUNT);3135 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3136if(nr <0)3137break;3138if(apply_in_reverse)3139reverse_patches(patch);3140if(prefix)3141prefix_patches(patch);3142if(use_patch(patch)) {3143patch_stats(patch);3144*listp = patch;3145 listp = &patch->next;3146}3147else{3148/* perhaps free it a bit better? */3149free(patch);3150 skipped_patch++;3151}3152 offset += nr;3153}31543155if(whitespace_error && (ws_error_action == die_on_ws_error))3156 apply =0;31573158 update_index = check_index && apply;3159if(update_index && newfd <0)3160 newfd =hold_locked_index(&lock_file,1);31613162if(check_index) {3163if(read_cache() <0)3164die("unable to read index file");3165}31663167if((check || apply) &&3168check_patch_list(list) <0&&3169!apply_with_reject)3170exit(1);31713172if(apply &&write_out_results(list, skipped_patch))3173exit(1);31743175if(fake_ancestor)3176build_fake_ancestor(list, fake_ancestor);31773178if(diffstat)3179stat_patch_list(list);31803181if(numstat)3182numstat_patch_list(list);31833184if(summary)3185summary_patch_list(list);31863187strbuf_release(&buf);3188return0;3189}31903191static intgit_apply_config(const char*var,const char*value,void*cb)3192{3193if(!strcmp(var,"apply.whitespace"))3194returngit_config_string(&apply_default_whitespace, var, value);3195returngit_default_config(var, value, cb);3196}31973198static intoption_parse_exclude(const struct option *opt,3199const char*arg,int unset)3200{3201add_name_limit(arg,1);3202return0;3203}32043205static intoption_parse_include(const struct option *opt,3206const char*arg,int unset)3207{3208add_name_limit(arg,0);3209 has_include =1;3210return0;3211}32123213static intoption_parse_p(const struct option *opt,3214const char*arg,int unset)3215{3216 p_value =atoi(arg);3217 p_value_known =1;3218return0;3219}32203221static intoption_parse_z(const struct option *opt,3222const char*arg,int unset)3223{3224if(unset)3225 line_termination ='\n';3226else3227 line_termination =0;3228return0;3229}32303231static intoption_parse_whitespace(const struct option *opt,3232const char*arg,int unset)3233{3234const char**whitespace_option = opt->value;32353236*whitespace_option = arg;3237parse_whitespace_option(arg);3238return0;3239}32403241static intoption_parse_directory(const struct option *opt,3242const char*arg,int unset)3243{3244 root_len =strlen(arg);3245if(root_len && arg[root_len -1] !='/') {3246char*new_root;3247 root = new_root =xmalloc(root_len +2);3248strcpy(new_root, arg);3249strcpy(new_root + root_len++,"/");3250}else3251 root = arg;3252return0;3253}32543255intcmd_apply(int argc,const char**argv,const char*unused_prefix)3256{3257int i;3258int errs =0;3259int is_not_gitdir;3260int binary;3261int force_apply =0;32623263const char*whitespace_option = NULL;32643265struct option builtin_apply_options[] = {3266{ OPTION_CALLBACK,0,"exclude", NULL,"path",3267"don't apply changes matching the given path",32680, option_parse_exclude },3269{ OPTION_CALLBACK,0,"include", NULL,"path",3270"apply changes matching the given path",32710, option_parse_include },3272{ OPTION_CALLBACK,'p', NULL, NULL,"num",3273"remove <num> leading slashes from traditional diff paths",32740, option_parse_p },3275OPT_BOOLEAN(0,"no-add", &no_add,3276"ignore additions made by the patch"),3277OPT_BOOLEAN(0,"stat", &diffstat,3278"instead of applying the patch, output diffstat for the input"),3279{ OPTION_BOOLEAN,0,"allow-binary-replacement", &binary,3280 NULL,"old option, now no-op",3281 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3282{ OPTION_BOOLEAN,0,"binary", &binary,3283 NULL,"old option, now no-op",3284 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3285OPT_BOOLEAN(0,"numstat", &numstat,3286"shows number of added and deleted lines in decimal notation"),3287OPT_BOOLEAN(0,"summary", &summary,3288"instead of applying the patch, output a summary for the input"),3289OPT_BOOLEAN(0,"check", &check,3290"instead of applying the patch, see if the patch is applicable"),3291OPT_BOOLEAN(0,"index", &check_index,3292"make sure the patch is applicable to the current index"),3293OPT_BOOLEAN(0,"cached", &cached,3294"apply a patch without touching the working tree"),3295OPT_BOOLEAN(0,"apply", &force_apply,3296"also apply the patch (use with --stat/--summary/--check)"),3297OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,3298"build a temporary index based on embedded index information"),3299{ OPTION_CALLBACK,'z', NULL, NULL, NULL,3300"paths are separated with NUL character",3301 PARSE_OPT_NOARG, option_parse_z },3302OPT_INTEGER('C', NULL, &p_context,3303"ensure at least <n> lines of context match"),3304{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,"action",3305"detect new or modified lines that have whitespace errors",33060, option_parse_whitespace },3307OPT_BOOLEAN('R',"reverse", &apply_in_reverse,3308"apply the patch in reverse"),3309OPT_BOOLEAN(0,"unidiff-zero", &unidiff_zero,3310"don't expect at least one line of context"),3311OPT_BOOLEAN(0,"reject", &apply_with_reject,3312"leave the rejected hunks in corresponding *.rej files"),3313OPT__VERBOSE(&apply_verbosely),3314OPT_BIT(0,"inaccurate-eof", &options,3315"tolerate incorrectly detected missing new-line at the end of file",3316 INACCURATE_EOF),3317OPT_BIT(0,"recount", &options,3318"do not trust the line counts in the hunk headers",3319 RECOUNT),3320{ OPTION_CALLBACK,0,"directory", NULL,"root",3321"prepend <root> to all filenames",33220, option_parse_directory },3323OPT_END()3324};33253326 prefix =setup_git_directory_gently(&is_not_gitdir);3327 prefix_length = prefix ?strlen(prefix) :0;3328git_config(git_apply_config, NULL);3329if(apply_default_whitespace)3330parse_whitespace_option(apply_default_whitespace);33313332 argc =parse_options(argc, argv, prefix, builtin_apply_options,3333 apply_usage,0);33343335if(apply_with_reject)3336 apply = apply_verbosely =1;3337if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))3338 apply =0;3339if(check_index && is_not_gitdir)3340die("--index outside a repository");3341if(cached) {3342if(is_not_gitdir)3343die("--cached outside a repository");3344 check_index =1;3345}3346for(i =0; i < argc; i++) {3347const char*arg = argv[i];3348int fd;33493350if(!strcmp(arg,"-")) {3351 errs |=apply_patch(0,"<stdin>", options);3352 read_stdin =0;3353continue;3354}else if(0< prefix_length)3355 arg =prefix_filename(prefix, prefix_length, arg);33563357 fd =open(arg, O_RDONLY);3358if(fd <0)3359die_errno("can't open patch '%s'", arg);3360 read_stdin =0;3361set_default_whitespace_mode(whitespace_option);3362 errs |=apply_patch(fd, arg, options);3363close(fd);3364}3365set_default_whitespace_mode(whitespace_option);3366if(read_stdin)3367 errs |=apply_patch(0,"<stdin>", options);3368if(whitespace_error) {3369if(squelch_whitespace_errors &&3370 squelch_whitespace_errors < whitespace_error) {3371int squelched =3372 whitespace_error - squelch_whitespace_errors;3373warning("squelched%d"3374"whitespace error%s",3375 squelched,3376 squelched ==1?"":"s");3377}3378if(ws_error_action == die_on_ws_error)3379die("%dline%sadd%swhitespace errors.",3380 whitespace_error,3381 whitespace_error ==1?"":"s",3382 whitespace_error ==1?"s":"");3383if(applied_after_fixing_ws && apply)3384warning("%dline%sapplied after"3385" fixing whitespace errors.",3386 applied_after_fixing_ws,3387 applied_after_fixing_ws ==1?"":"s");3388else if(whitespace_error)3389warning("%dline%sadd%swhitespace errors.",3390 whitespace_error,3391 whitespace_error ==1?"":"s",3392 whitespace_error ==1?"s":"");3393}33943395if(update_index) {3396if(write_cache(newfd, active_cache, active_nr) ||3397commit_locked_index(&lock_file))3398die("Unable to write new index file");3399}34003401return!!errs;3402}