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 16/* 17 * --check turns on checking that the working tree matches the 18 * files that are being modified, but doesn't apply the patch 19 * --stat does just a diffstat, and doesn't actually apply 20 * --numstat does numeric diffstat, and doesn't actually apply 21 * --index-info shows the old and new index info for paths if available. 22 * --index updates the cache as well. 23 * --cached updates only the cache without ever touching the working tree. 24 */ 25static const char*prefix; 26static int prefix_length = -1; 27static int newfd = -1; 28 29static int unidiff_zero; 30static int p_value =1; 31static int p_value_known; 32static int check_index; 33static int update_index; 34static int cached; 35static int diffstat; 36static int numstat; 37static int summary; 38static int check; 39static int apply =1; 40static int apply_in_reverse; 41static int apply_with_reject; 42static int apply_verbosely; 43static int no_add; 44static const char*fake_ancestor; 45static int line_termination ='\n'; 46static unsigned long p_context = ULONG_MAX; 47static const char apply_usage[] = 48"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>..."; 49 50static enum ws_error_action { 51 nowarn_ws_error, 52 warn_on_ws_error, 53 die_on_ws_error, 54 correct_ws_error, 55} ws_error_action = warn_on_ws_error; 56static int whitespace_error; 57static int squelch_whitespace_errors =5; 58static int applied_after_fixing_ws; 59static const char*patch_input_file; 60static const char*root; 61static int root_len; 62 63static voidparse_whitespace_option(const char*option) 64{ 65if(!option) { 66 ws_error_action = warn_on_ws_error; 67return; 68} 69if(!strcmp(option,"warn")) { 70 ws_error_action = warn_on_ws_error; 71return; 72} 73if(!strcmp(option,"nowarn")) { 74 ws_error_action = nowarn_ws_error; 75return; 76} 77if(!strcmp(option,"error")) { 78 ws_error_action = die_on_ws_error; 79return; 80} 81if(!strcmp(option,"error-all")) { 82 ws_error_action = die_on_ws_error; 83 squelch_whitespace_errors =0; 84return; 85} 86if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 87 ws_error_action = correct_ws_error; 88return; 89} 90die("unrecognized whitespace option '%s'", option); 91} 92 93static voidset_default_whitespace_mode(const char*whitespace_option) 94{ 95if(!whitespace_option && !apply_default_whitespace) 96 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 97} 98 99/* 100 * For "diff-stat" like behaviour, we keep track of the biggest change 101 * we've seen, and the longest filename. That allows us to do simple 102 * scaling. 103 */ 104static int max_change, max_len; 105 106/* 107 * Various "current state", notably line numbers and what 108 * file (and how) we're patching right now.. The "is_xxxx" 109 * things are flags, where -1 means "don't know yet". 110 */ 111static int linenr =1; 112 113/* 114 * This represents one "hunk" from a patch, starting with 115 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 116 * patch text is pointed at by patch, and its byte length 117 * is stored in size. leading and trailing are the number 118 * of context lines. 119 */ 120struct fragment { 121unsigned long leading, trailing; 122unsigned long oldpos, oldlines; 123unsigned long newpos, newlines; 124const char*patch; 125int size; 126int rejected; 127struct fragment *next; 128}; 129 130/* 131 * When dealing with a binary patch, we reuse "leading" field 132 * to store the type of the binary hunk, either deflated "delta" 133 * or deflated "literal". 134 */ 135#define binary_patch_method leading 136#define BINARY_DELTA_DEFLATED 1 137#define BINARY_LITERAL_DEFLATED 2 138 139/* 140 * This represents a "patch" to a file, both metainfo changes 141 * such as creation/deletion, filemode and content changes represented 142 * as a series of fragments. 143 */ 144struct patch { 145char*new_name, *old_name, *def_name; 146unsigned int old_mode, new_mode; 147int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 148int rejected; 149unsigned ws_rule; 150unsigned long deflate_origlen; 151int lines_added, lines_deleted; 152int score; 153unsigned int is_toplevel_relative:1; 154unsigned int inaccurate_eof:1; 155unsigned int is_binary:1; 156unsigned int is_copy:1; 157unsigned int is_rename:1; 158struct fragment *fragments; 159char*result; 160size_t resultsize; 161char old_sha1_prefix[41]; 162char new_sha1_prefix[41]; 163struct patch *next; 164}; 165 166/* 167 * A line in a file, len-bytes long (includes the terminating LF, 168 * except for an incomplete line at the end if the file ends with 169 * one), and its contents hashes to 'hash'. 170 */ 171struct line { 172size_t len; 173unsigned hash :24; 174unsigned flag :8; 175#define LINE_COMMON 1 176}; 177 178/* 179 * This represents a "file", which is an array of "lines". 180 */ 181struct image { 182char*buf; 183size_t len; 184size_t nr; 185size_t alloc; 186struct line *line_allocated; 187struct line *line; 188}; 189 190static uint32_thash_line(const char*cp,size_t len) 191{ 192size_t i; 193uint32_t h; 194for(i =0, h =0; i < len; i++) { 195if(!isspace(cp[i])) { 196 h = h *3+ (cp[i] &0xff); 197} 198} 199return h; 200} 201 202static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 203{ 204ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 205 img->line_allocated[img->nr].len = len; 206 img->line_allocated[img->nr].hash =hash_line(bol, len); 207 img->line_allocated[img->nr].flag = flag; 208 img->nr++; 209} 210 211static voidprepare_image(struct image *image,char*buf,size_t len, 212int prepare_linetable) 213{ 214const char*cp, *ep; 215 216memset(image,0,sizeof(*image)); 217 image->buf = buf; 218 image->len = len; 219 220if(!prepare_linetable) 221return; 222 223 ep = image->buf + image->len; 224 cp = image->buf; 225while(cp < ep) { 226const char*next; 227for(next = cp; next < ep && *next !='\n'; next++) 228; 229if(next < ep) 230 next++; 231add_line_info(image, cp, next - cp,0); 232 cp = next; 233} 234 image->line = image->line_allocated; 235} 236 237static voidclear_image(struct image *image) 238{ 239free(image->buf); 240 image->buf = NULL; 241 image->len =0; 242} 243 244static voidsay_patch_name(FILE*output,const char*pre, 245struct patch *patch,const char*post) 246{ 247fputs(pre, output); 248if(patch->old_name && patch->new_name && 249strcmp(patch->old_name, patch->new_name)) { 250quote_c_style(patch->old_name, NULL, output,0); 251fputs(" => ", output); 252quote_c_style(patch->new_name, NULL, output,0); 253}else{ 254const char*n = patch->new_name; 255if(!n) 256 n = patch->old_name; 257quote_c_style(n, NULL, output,0); 258} 259fputs(post, output); 260} 261 262#define CHUNKSIZE (8192) 263#define SLOP (16) 264 265static voidread_patch_file(struct strbuf *sb,int fd) 266{ 267if(strbuf_read(sb, fd,0) <0) 268die("git-apply: read returned%s",strerror(errno)); 269 270/* 271 * Make sure that we have some slop in the buffer 272 * so that we can do speculative "memcmp" etc, and 273 * see to it that it is NUL-filled. 274 */ 275strbuf_grow(sb, SLOP); 276memset(sb->buf + sb->len,0, SLOP); 277} 278 279static unsigned longlinelen(const char*buffer,unsigned long size) 280{ 281unsigned long len =0; 282while(size--) { 283 len++; 284if(*buffer++ =='\n') 285break; 286} 287return len; 288} 289 290static intis_dev_null(const char*str) 291{ 292return!memcmp("/dev/null", str,9) &&isspace(str[9]); 293} 294 295#define TERM_SPACE 1 296#define TERM_TAB 2 297 298static intname_terminate(const char*name,int namelen,int c,int terminate) 299{ 300if(c ==' '&& !(terminate & TERM_SPACE)) 301return0; 302if(c =='\t'&& !(terminate & TERM_TAB)) 303return0; 304 305return1; 306} 307 308static char*find_name(const char*line,char*def,int p_value,int terminate) 309{ 310int len; 311const char*start = line; 312 313if(*line =='"') { 314struct strbuf name; 315 316/* 317 * Proposed "new-style" GNU patch/diff format; see 318 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2 319 */ 320strbuf_init(&name,0); 321if(!unquote_c_style(&name, line, NULL)) { 322char*cp; 323 324for(cp = name.buf; p_value; p_value--) { 325 cp =strchr(cp,'/'); 326if(!cp) 327break; 328 cp++; 329} 330if(cp) { 331/* name can later be freed, so we need 332 * to memmove, not just return cp 333 */ 334strbuf_remove(&name,0, cp - name.buf); 335free(def); 336if(root) 337strbuf_insert(&name,0, root, root_len); 338returnstrbuf_detach(&name, NULL); 339} 340} 341strbuf_release(&name); 342} 343 344for(;;) { 345char c = *line; 346 347if(isspace(c)) { 348if(c =='\n') 349break; 350if(name_terminate(start, line-start, c, terminate)) 351break; 352} 353 line++; 354if(c =='/'&& !--p_value) 355 start = line; 356} 357if(!start) 358return def; 359 len = line - start; 360if(!len) 361return def; 362 363/* 364 * Generally we prefer the shorter name, especially 365 * if the other one is just a variation of that with 366 * something else tacked on to the end (ie "file.orig" 367 * or "file~"). 368 */ 369if(def) { 370int deflen =strlen(def); 371if(deflen < len && !strncmp(start, def, deflen)) 372return def; 373free(def); 374} 375 376if(root) { 377char*ret =xmalloc(root_len + len +1); 378strcpy(ret, root); 379memcpy(ret + root_len, start, len); 380 ret[root_len + len] ='\0'; 381return ret; 382} 383 384returnxmemdupz(start, len); 385} 386 387static intcount_slashes(const char*cp) 388{ 389int cnt =0; 390char ch; 391 392while((ch = *cp++)) 393if(ch =='/') 394 cnt++; 395return cnt; 396} 397 398/* 399 * Given the string after "--- " or "+++ ", guess the appropriate 400 * p_value for the given patch. 401 */ 402static intguess_p_value(const char*nameline) 403{ 404char*name, *cp; 405int val = -1; 406 407if(is_dev_null(nameline)) 408return-1; 409 name =find_name(nameline, NULL,0, TERM_SPACE | TERM_TAB); 410if(!name) 411return-1; 412 cp =strchr(name,'/'); 413if(!cp) 414 val =0; 415else if(prefix) { 416/* 417 * Does it begin with "a/$our-prefix" and such? Then this is 418 * very likely to apply to our directory. 419 */ 420if(!strncmp(name, prefix, prefix_length)) 421 val =count_slashes(prefix); 422else{ 423 cp++; 424if(!strncmp(cp, prefix, prefix_length)) 425 val =count_slashes(prefix) +1; 426} 427} 428free(name); 429return val; 430} 431 432/* 433 * Get the name etc info from the ---/+++ lines of a traditional patch header 434 * 435 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 436 * files, we can happily check the index for a match, but for creating a 437 * new file we should try to match whatever "patch" does. I have no idea. 438 */ 439static voidparse_traditional_patch(const char*first,const char*second,struct patch *patch) 440{ 441char*name; 442 443 first +=4;/* skip "--- " */ 444 second +=4;/* skip "+++ " */ 445if(!p_value_known) { 446int p, q; 447 p =guess_p_value(first); 448 q =guess_p_value(second); 449if(p <0) p = q; 450if(0<= p && p == q) { 451 p_value = p; 452 p_value_known =1; 453} 454} 455if(is_dev_null(first)) { 456 patch->is_new =1; 457 patch->is_delete =0; 458 name =find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB); 459 patch->new_name = name; 460}else if(is_dev_null(second)) { 461 patch->is_new =0; 462 patch->is_delete =1; 463 name =find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB); 464 patch->old_name = name; 465}else{ 466 name =find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB); 467 name =find_name(second, name, p_value, TERM_SPACE | TERM_TAB); 468 patch->old_name = patch->new_name = name; 469} 470if(!name) 471die("unable to find filename in patch at line%d", linenr); 472} 473 474static intgitdiff_hdrend(const char*line,struct patch *patch) 475{ 476return-1; 477} 478 479/* 480 * We're anal about diff header consistency, to make 481 * sure that we don't end up having strange ambiguous 482 * patches floating around. 483 * 484 * As a result, gitdiff_{old|new}name() will check 485 * their names against any previous information, just 486 * to make sure.. 487 */ 488static char*gitdiff_verify_name(const char*line,int isnull,char*orig_name,const char*oldnew) 489{ 490if(!orig_name && !isnull) 491returnfind_name(line, NULL, p_value, TERM_TAB); 492 493if(orig_name) { 494int len; 495const char*name; 496char*another; 497 name = orig_name; 498 len =strlen(name); 499if(isnull) 500die("git-apply: bad git-diff - expected /dev/null, got%son line%d", name, linenr); 501 another =find_name(line, NULL, p_value, TERM_TAB); 502if(!another ||memcmp(another, name, len)) 503die("git-apply: bad git-diff - inconsistent%sfilename on line%d", oldnew, linenr); 504free(another); 505return orig_name; 506} 507else{ 508/* expect "/dev/null" */ 509if(memcmp("/dev/null", line,9) || line[9] !='\n') 510die("git-apply: bad git-diff - expected /dev/null on line%d", linenr); 511return NULL; 512} 513} 514 515static intgitdiff_oldname(const char*line,struct patch *patch) 516{ 517 patch->old_name =gitdiff_verify_name(line, patch->is_new, patch->old_name,"old"); 518return0; 519} 520 521static intgitdiff_newname(const char*line,struct patch *patch) 522{ 523 patch->new_name =gitdiff_verify_name(line, patch->is_delete, patch->new_name,"new"); 524return0; 525} 526 527static intgitdiff_oldmode(const char*line,struct patch *patch) 528{ 529 patch->old_mode =strtoul(line, NULL,8); 530return0; 531} 532 533static intgitdiff_newmode(const char*line,struct patch *patch) 534{ 535 patch->new_mode =strtoul(line, NULL,8); 536return0; 537} 538 539static intgitdiff_delete(const char*line,struct patch *patch) 540{ 541 patch->is_delete =1; 542 patch->old_name = patch->def_name; 543returngitdiff_oldmode(line, patch); 544} 545 546static intgitdiff_newfile(const char*line,struct patch *patch) 547{ 548 patch->is_new =1; 549 patch->new_name = patch->def_name; 550returngitdiff_newmode(line, patch); 551} 552 553static intgitdiff_copysrc(const char*line,struct patch *patch) 554{ 555 patch->is_copy =1; 556 patch->old_name =find_name(line, NULL,0,0); 557return0; 558} 559 560static intgitdiff_copydst(const char*line,struct patch *patch) 561{ 562 patch->is_copy =1; 563 patch->new_name =find_name(line, NULL,0,0); 564return0; 565} 566 567static intgitdiff_renamesrc(const char*line,struct patch *patch) 568{ 569 patch->is_rename =1; 570 patch->old_name =find_name(line, NULL,0,0); 571return0; 572} 573 574static intgitdiff_renamedst(const char*line,struct patch *patch) 575{ 576 patch->is_rename =1; 577 patch->new_name =find_name(line, NULL,0,0); 578return0; 579} 580 581static intgitdiff_similarity(const char*line,struct patch *patch) 582{ 583if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 584 patch->score =0; 585return0; 586} 587 588static intgitdiff_dissimilarity(const char*line,struct patch *patch) 589{ 590if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 591 patch->score =0; 592return0; 593} 594 595static intgitdiff_index(const char*line,struct patch *patch) 596{ 597/* 598 * index line is N hexadecimal, "..", N hexadecimal, 599 * and optional space with octal mode. 600 */ 601const char*ptr, *eol; 602int len; 603 604 ptr =strchr(line,'.'); 605if(!ptr || ptr[1] !='.'||40< ptr - line) 606return0; 607 len = ptr - line; 608memcpy(patch->old_sha1_prefix, line, len); 609 patch->old_sha1_prefix[len] =0; 610 611 line = ptr +2; 612 ptr =strchr(line,' '); 613 eol =strchr(line,'\n'); 614 615if(!ptr || eol < ptr) 616 ptr = eol; 617 len = ptr - line; 618 619if(40< len) 620return0; 621memcpy(patch->new_sha1_prefix, line, len); 622 patch->new_sha1_prefix[len] =0; 623if(*ptr ==' ') 624 patch->new_mode = patch->old_mode =strtoul(ptr+1, NULL,8); 625return0; 626} 627 628/* 629 * This is normal for a diff that doesn't change anything: we'll fall through 630 * into the next diff. Tell the parser to break out. 631 */ 632static intgitdiff_unrecognized(const char*line,struct patch *patch) 633{ 634return-1; 635} 636 637static const char*stop_at_slash(const char*line,int llen) 638{ 639int i; 640 641for(i =0; i < llen; i++) { 642int ch = line[i]; 643if(ch =='/') 644return line + i; 645} 646return NULL; 647} 648 649/* 650 * This is to extract the same name that appears on "diff --git" 651 * line. We do not find and return anything if it is a rename 652 * patch, and it is OK because we will find the name elsewhere. 653 * We need to reliably find name only when it is mode-change only, 654 * creation or deletion of an empty file. In any of these cases, 655 * both sides are the same name under a/ and b/ respectively. 656 */ 657static char*git_header_name(char*line,int llen) 658{ 659const char*name; 660const char*second = NULL; 661size_t len; 662 663 line +=strlen("diff --git "); 664 llen -=strlen("diff --git "); 665 666if(*line =='"') { 667const char*cp; 668struct strbuf first; 669struct strbuf sp; 670 671strbuf_init(&first,0); 672strbuf_init(&sp,0); 673 674if(unquote_c_style(&first, line, &second)) 675goto free_and_fail1; 676 677/* advance to the first slash */ 678 cp =stop_at_slash(first.buf, first.len); 679/* we do not accept absolute paths */ 680if(!cp || cp == first.buf) 681goto free_and_fail1; 682strbuf_remove(&first,0, cp +1- first.buf); 683 684/* 685 * second points at one past closing dq of name. 686 * find the second name. 687 */ 688while((second < line + llen) &&isspace(*second)) 689 second++; 690 691if(line + llen <= second) 692goto free_and_fail1; 693if(*second =='"') { 694if(unquote_c_style(&sp, second, NULL)) 695goto free_and_fail1; 696 cp =stop_at_slash(sp.buf, sp.len); 697if(!cp || cp == sp.buf) 698goto free_and_fail1; 699/* They must match, otherwise ignore */ 700if(strcmp(cp +1, first.buf)) 701goto free_and_fail1; 702strbuf_release(&sp); 703returnstrbuf_detach(&first, NULL); 704} 705 706/* unquoted second */ 707 cp =stop_at_slash(second, line + llen - second); 708if(!cp || cp == second) 709goto free_and_fail1; 710 cp++; 711if(line + llen - cp != first.len +1|| 712memcmp(first.buf, cp, first.len)) 713goto free_and_fail1; 714returnstrbuf_detach(&first, NULL); 715 716 free_and_fail1: 717strbuf_release(&first); 718strbuf_release(&sp); 719return NULL; 720} 721 722/* unquoted first name */ 723 name =stop_at_slash(line, llen); 724if(!name || name == line) 725return NULL; 726 name++; 727 728/* 729 * since the first name is unquoted, a dq if exists must be 730 * the beginning of the second name. 731 */ 732for(second = name; second < line + llen; second++) { 733if(*second =='"') { 734struct strbuf sp; 735const char*np; 736 737strbuf_init(&sp,0); 738if(unquote_c_style(&sp, second, NULL)) 739goto free_and_fail2; 740 741 np =stop_at_slash(sp.buf, sp.len); 742if(!np || np == sp.buf) 743goto free_and_fail2; 744 np++; 745 746 len = sp.buf + sp.len - np; 747if(len < second - name && 748!strncmp(np, name, len) && 749isspace(name[len])) { 750/* Good */ 751strbuf_remove(&sp,0, np - sp.buf); 752returnstrbuf_detach(&sp, NULL); 753} 754 755 free_and_fail2: 756strbuf_release(&sp); 757return NULL; 758} 759} 760 761/* 762 * Accept a name only if it shows up twice, exactly the same 763 * form. 764 */ 765for(len =0; ; len++) { 766switch(name[len]) { 767default: 768continue; 769case'\n': 770return NULL; 771case'\t':case' ': 772 second = name+len; 773for(;;) { 774char c = *second++; 775if(c =='\n') 776return NULL; 777if(c =='/') 778break; 779} 780if(second[len] =='\n'&& !memcmp(name, second, len)) { 781returnxmemdupz(name, len); 782} 783} 784} 785} 786 787/* Verify that we recognize the lines following a git header */ 788static intparse_git_header(char*line,int len,unsigned int size,struct patch *patch) 789{ 790unsigned long offset; 791 792/* A git diff has explicit new/delete information, so we don't guess */ 793 patch->is_new =0; 794 patch->is_delete =0; 795 796/* 797 * Some things may not have the old name in the 798 * rest of the headers anywhere (pure mode changes, 799 * or removing or adding empty files), so we get 800 * the default name from the header. 801 */ 802 patch->def_name =git_header_name(line, len); 803 804 line += len; 805 size -= len; 806 linenr++; 807for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) { 808static const struct opentry { 809const char*str; 810int(*fn)(const char*,struct patch *); 811} optable[] = { 812{"@@ -", gitdiff_hdrend }, 813{"--- ", gitdiff_oldname }, 814{"+++ ", gitdiff_newname }, 815{"old mode ", gitdiff_oldmode }, 816{"new mode ", gitdiff_newmode }, 817{"deleted file mode ", gitdiff_delete }, 818{"new file mode ", gitdiff_newfile }, 819{"copy from ", gitdiff_copysrc }, 820{"copy to ", gitdiff_copydst }, 821{"rename old ", gitdiff_renamesrc }, 822{"rename new ", gitdiff_renamedst }, 823{"rename from ", gitdiff_renamesrc }, 824{"rename to ", gitdiff_renamedst }, 825{"similarity index ", gitdiff_similarity }, 826{"dissimilarity index ", gitdiff_dissimilarity }, 827{"index ", gitdiff_index }, 828{"", gitdiff_unrecognized }, 829}; 830int i; 831 832 len =linelen(line, size); 833if(!len || line[len-1] !='\n') 834break; 835for(i =0; i <ARRAY_SIZE(optable); i++) { 836const struct opentry *p = optable + i; 837int oplen =strlen(p->str); 838if(len < oplen ||memcmp(p->str, line, oplen)) 839continue; 840if(p->fn(line + oplen, patch) <0) 841return offset; 842break; 843} 844} 845 846return offset; 847} 848 849static intparse_num(const char*line,unsigned long*p) 850{ 851char*ptr; 852 853if(!isdigit(*line)) 854return0; 855*p =strtoul(line, &ptr,10); 856return ptr - line; 857} 858 859static intparse_range(const char*line,int len,int offset,const char*expect, 860unsigned long*p1,unsigned long*p2) 861{ 862int digits, ex; 863 864if(offset <0|| offset >= len) 865return-1; 866 line += offset; 867 len -= offset; 868 869 digits =parse_num(line, p1); 870if(!digits) 871return-1; 872 873 offset += digits; 874 line += digits; 875 len -= digits; 876 877*p2 =1; 878if(*line ==',') { 879 digits =parse_num(line+1, p2); 880if(!digits) 881return-1; 882 883 offset += digits+1; 884 line += digits+1; 885 len -= digits+1; 886} 887 888 ex =strlen(expect); 889if(ex > len) 890return-1; 891if(memcmp(line, expect, ex)) 892return-1; 893 894return offset + ex; 895} 896 897/* 898 * Parse a unified diff fragment header of the 899 * form "@@ -a,b +c,d @@" 900 */ 901static intparse_fragment_header(char*line,int len,struct fragment *fragment) 902{ 903int offset; 904 905if(!len || line[len-1] !='\n') 906return-1; 907 908/* Figure out the number of lines in a fragment */ 909 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines); 910 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines); 911 912return offset; 913} 914 915static intfind_header(char*line,unsigned long size,int*hdrsize,struct patch *patch) 916{ 917unsigned long offset, len; 918 919 patch->is_toplevel_relative =0; 920 patch->is_rename = patch->is_copy =0; 921 patch->is_new = patch->is_delete = -1; 922 patch->old_mode = patch->new_mode =0; 923 patch->old_name = patch->new_name = NULL; 924for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) { 925unsigned long nextlen; 926 927 len =linelen(line, size); 928if(!len) 929break; 930 931/* Testing this early allows us to take a few shortcuts.. */ 932if(len <6) 933continue; 934 935/* 936 * Make sure we don't find any unconnected patch fragments. 937 * That's a sign that we didn't find a header, and that a 938 * patch has become corrupted/broken up. 939 */ 940if(!memcmp("@@ -", line,4)) { 941struct fragment dummy; 942if(parse_fragment_header(line, len, &dummy) <0) 943continue; 944die("patch fragment without header at line%d: %.*s", 945 linenr, (int)len-1, line); 946} 947 948if(size < len +6) 949break; 950 951/* 952 * Git patch? It might not have a real patch, just a rename 953 * or mode change, so we handle that specially 954 */ 955if(!memcmp("diff --git ", line,11)) { 956int git_hdr_len =parse_git_header(line, len, size, patch); 957if(git_hdr_len <= len) 958continue; 959if(!patch->old_name && !patch->new_name) { 960if(!patch->def_name) 961die("git diff header lacks filename information (line%d)", linenr); 962 patch->old_name = patch->new_name = patch->def_name; 963} 964 patch->is_toplevel_relative =1; 965*hdrsize = git_hdr_len; 966return offset; 967} 968 969/* --- followed by +++ ? */ 970if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4)) 971continue; 972 973/* 974 * We only accept unified patches, so we want it to 975 * at least have "@@ -a,b +c,d @@\n", which is 14 chars 976 * minimum ("@@ -0,0 +1 @@\n" is the shortest). 977 */ 978 nextlen =linelen(line + len, size - len); 979if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4)) 980continue; 981 982/* Ok, we'll consider it a patch */ 983parse_traditional_patch(line, line+len, patch); 984*hdrsize = len + nextlen; 985 linenr +=2; 986return offset; 987} 988return-1; 989} 990 991static voidcheck_whitespace(const char*line,int len,unsigned ws_rule) 992{ 993char*err; 994unsigned result =check_and_emit_line(line +1, len -1, ws_rule, 995 NULL, NULL, NULL, NULL); 996if(!result) 997return; 998 999 whitespace_error++;1000if(squelch_whitespace_errors &&1001 squelch_whitespace_errors < whitespace_error)1002;1003else{1004 err =whitespace_error_string(result);1005fprintf(stderr,"%s:%d:%s.\n%.*s\n",1006 patch_input_file, linenr, err, len -2, line +1);1007free(err);1008}1009}10101011/*1012 * Parse a unified diff. Note that this really needs to parse each1013 * fragment separately, since the only way to know the difference1014 * between a "---" that is part of a patch, and a "---" that starts1015 * the next patch is to look at the line counts..1016 */1017static intparse_fragment(char*line,unsigned long size,1018struct patch *patch,struct fragment *fragment)1019{1020int added, deleted;1021int len =linelen(line, size), offset;1022unsigned long oldlines, newlines;1023unsigned long leading, trailing;10241025 offset =parse_fragment_header(line, len, fragment);1026if(offset <0)1027return-1;1028 oldlines = fragment->oldlines;1029 newlines = fragment->newlines;1030 leading =0;1031 trailing =0;10321033/* Parse the thing.. */1034 line += len;1035 size -= len;1036 linenr++;1037 added = deleted =0;1038for(offset = len;10390< size;1040 offset += len, size -= len, line += len, linenr++) {1041if(!oldlines && !newlines)1042break;1043 len =linelen(line, size);1044if(!len || line[len-1] !='\n')1045return-1;1046switch(*line) {1047default:1048return-1;1049case'\n':/* newer GNU diff, an empty context line */1050case' ':1051 oldlines--;1052 newlines--;1053if(!deleted && !added)1054 leading++;1055 trailing++;1056break;1057case'-':1058if(apply_in_reverse &&1059 ws_error_action != nowarn_ws_error)1060check_whitespace(line, len, patch->ws_rule);1061 deleted++;1062 oldlines--;1063 trailing =0;1064break;1065case'+':1066if(!apply_in_reverse &&1067 ws_error_action != nowarn_ws_error)1068check_whitespace(line, len, patch->ws_rule);1069 added++;1070 newlines--;1071 trailing =0;1072break;10731074/*1075 * We allow "\ No newline at end of file". Depending1076 * on locale settings when the patch was produced we1077 * don't know what this line looks like. The only1078 * thing we do know is that it begins with "\ ".1079 * Checking for 12 is just for sanity check -- any1080 * l10n of "\ No newline..." is at least that long.1081 */1082case'\\':1083if(len <12||memcmp(line,"\\",2))1084return-1;1085break;1086}1087}1088if(oldlines || newlines)1089return-1;1090 fragment->leading = leading;1091 fragment->trailing = trailing;10921093/*1094 * If a fragment ends with an incomplete line, we failed to include1095 * it in the above loop because we hit oldlines == newlines == 01096 * before seeing it.1097 */1098if(12< size && !memcmp(line,"\\",2))1099 offset +=linelen(line, size);11001101 patch->lines_added += added;1102 patch->lines_deleted += deleted;11031104if(0< patch->is_new && oldlines)1105returnerror("new file depends on old contents");1106if(0< patch->is_delete && newlines)1107returnerror("deleted file still has contents");1108return offset;1109}11101111static intparse_single_patch(char*line,unsigned long size,struct patch *patch)1112{1113unsigned long offset =0;1114unsigned long oldlines =0, newlines =0, context =0;1115struct fragment **fragp = &patch->fragments;11161117while(size >4&& !memcmp(line,"@@ -",4)) {1118struct fragment *fragment;1119int len;11201121 fragment =xcalloc(1,sizeof(*fragment));1122 len =parse_fragment(line, size, patch, fragment);1123if(len <=0)1124die("corrupt patch at line%d", linenr);1125 fragment->patch = line;1126 fragment->size = len;1127 oldlines += fragment->oldlines;1128 newlines += fragment->newlines;1129 context += fragment->leading + fragment->trailing;11301131*fragp = fragment;1132 fragp = &fragment->next;11331134 offset += len;1135 line += len;1136 size -= len;1137}11381139/*1140 * If something was removed (i.e. we have old-lines) it cannot1141 * be creation, and if something was added it cannot be1142 * deletion. However, the reverse is not true; --unified=01143 * patches that only add are not necessarily creation even1144 * though they do not have any old lines, and ones that only1145 * delete are not necessarily deletion.1146 *1147 * Unfortunately, a real creation/deletion patch do _not_ have1148 * any context line by definition, so we cannot safely tell it1149 * apart with --unified=0 insanity. At least if the patch has1150 * more than one hunk it is not creation or deletion.1151 */1152if(patch->is_new <0&&1153(oldlines || (patch->fragments && patch->fragments->next)))1154 patch->is_new =0;1155if(patch->is_delete <0&&1156(newlines || (patch->fragments && patch->fragments->next)))1157 patch->is_delete =0;11581159if(0< patch->is_new && oldlines)1160die("new file%sdepends on old contents", patch->new_name);1161if(0< patch->is_delete && newlines)1162die("deleted file%sstill has contents", patch->old_name);1163if(!patch->is_delete && !newlines && context)1164fprintf(stderr,"** warning: file%sbecomes empty but "1165"is not deleted\n", patch->new_name);11661167return offset;1168}11691170staticinlineintmetadata_changes(struct patch *patch)1171{1172return patch->is_rename >0||1173 patch->is_copy >0||1174 patch->is_new >0||1175 patch->is_delete ||1176(patch->old_mode && patch->new_mode &&1177 patch->old_mode != patch->new_mode);1178}11791180static char*inflate_it(const void*data,unsigned long size,1181unsigned long inflated_size)1182{1183 z_stream stream;1184void*out;1185int st;11861187memset(&stream,0,sizeof(stream));11881189 stream.next_in = (unsigned char*)data;1190 stream.avail_in = size;1191 stream.next_out = out =xmalloc(inflated_size);1192 stream.avail_out = inflated_size;1193inflateInit(&stream);1194 st =inflate(&stream, Z_FINISH);1195if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1196free(out);1197return NULL;1198}1199return out;1200}12011202static struct fragment *parse_binary_hunk(char**buf_p,1203unsigned long*sz_p,1204int*status_p,1205int*used_p)1206{1207/*1208 * Expect a line that begins with binary patch method ("literal"1209 * or "delta"), followed by the length of data before deflating.1210 * a sequence of 'length-byte' followed by base-85 encoded data1211 * should follow, terminated by a newline.1212 *1213 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1214 * and we would limit the patch line to 66 characters,1215 * so one line can fit up to 13 groups that would decode1216 * to 52 bytes max. The length byte 'A'-'Z' corresponds1217 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1218 */1219int llen, used;1220unsigned long size = *sz_p;1221char*buffer = *buf_p;1222int patch_method;1223unsigned long origlen;1224char*data = NULL;1225int hunk_size =0;1226struct fragment *frag;12271228 llen =linelen(buffer, size);1229 used = llen;12301231*status_p =0;12321233if(!prefixcmp(buffer,"delta ")) {1234 patch_method = BINARY_DELTA_DEFLATED;1235 origlen =strtoul(buffer +6, NULL,10);1236}1237else if(!prefixcmp(buffer,"literal ")) {1238 patch_method = BINARY_LITERAL_DEFLATED;1239 origlen =strtoul(buffer +8, NULL,10);1240}1241else1242return NULL;12431244 linenr++;1245 buffer += llen;1246while(1) {1247int byte_length, max_byte_length, newsize;1248 llen =linelen(buffer, size);1249 used += llen;1250 linenr++;1251if(llen ==1) {1252/* consume the blank line */1253 buffer++;1254 size--;1255break;1256}1257/*1258 * Minimum line is "A00000\n" which is 7-byte long,1259 * and the line length must be multiple of 5 plus 2.1260 */1261if((llen <7) || (llen-2) %5)1262goto corrupt;1263 max_byte_length = (llen -2) /5*4;1264 byte_length = *buffer;1265if('A'<= byte_length && byte_length <='Z')1266 byte_length = byte_length -'A'+1;1267else if('a'<= byte_length && byte_length <='z')1268 byte_length = byte_length -'a'+27;1269else1270goto corrupt;1271/* if the input length was not multiple of 4, we would1272 * have filler at the end but the filler should never1273 * exceed 3 bytes1274 */1275if(max_byte_length < byte_length ||1276 byte_length <= max_byte_length -4)1277goto corrupt;1278 newsize = hunk_size + byte_length;1279 data =xrealloc(data, newsize);1280if(decode_85(data + hunk_size, buffer +1, byte_length))1281goto corrupt;1282 hunk_size = newsize;1283 buffer += llen;1284 size -= llen;1285}12861287 frag =xcalloc(1,sizeof(*frag));1288 frag->patch =inflate_it(data, hunk_size, origlen);1289if(!frag->patch)1290goto corrupt;1291free(data);1292 frag->size = origlen;1293*buf_p = buffer;1294*sz_p = size;1295*used_p = used;1296 frag->binary_patch_method = patch_method;1297return frag;12981299 corrupt:1300free(data);1301*status_p = -1;1302error("corrupt binary patch at line%d: %.*s",1303 linenr-1, llen-1, buffer);1304return NULL;1305}13061307static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1308{1309/*1310 * We have read "GIT binary patch\n"; what follows is a line1311 * that says the patch method (currently, either "literal" or1312 * "delta") and the length of data before deflating; a1313 * sequence of 'length-byte' followed by base-85 encoded data1314 * follows.1315 *1316 * When a binary patch is reversible, there is another binary1317 * hunk in the same format, starting with patch method (either1318 * "literal" or "delta") with the length of data, and a sequence1319 * of length-byte + base-85 encoded data, terminated with another1320 * empty line. This data, when applied to the postimage, produces1321 * the preimage.1322 */1323struct fragment *forward;1324struct fragment *reverse;1325int status;1326int used, used_1;13271328 forward =parse_binary_hunk(&buffer, &size, &status, &used);1329if(!forward && !status)1330/* there has to be one hunk (forward hunk) */1331returnerror("unrecognized binary patch at line%d", linenr-1);1332if(status)1333/* otherwise we already gave an error message */1334return status;13351336 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1337if(reverse)1338 used += used_1;1339else if(status) {1340/*1341 * Not having reverse hunk is not an error, but having1342 * a corrupt reverse hunk is.1343 */1344free((void*) forward->patch);1345free(forward);1346return status;1347}1348 forward->next = reverse;1349 patch->fragments = forward;1350 patch->is_binary =1;1351return used;1352}13531354static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1355{1356int hdrsize, patchsize;1357int offset =find_header(buffer, size, &hdrsize, patch);13581359if(offset <0)1360return offset;13611362 patch->ws_rule =whitespace_rule(patch->new_name1363? patch->new_name1364: patch->old_name);13651366 patchsize =parse_single_patch(buffer + offset + hdrsize,1367 size - offset - hdrsize, patch);13681369if(!patchsize) {1370static const char*binhdr[] = {1371"Binary files ",1372"Files ",1373 NULL,1374};1375static const char git_binary[] ="GIT binary patch\n";1376int i;1377int hd = hdrsize + offset;1378unsigned long llen =linelen(buffer + hd, size - hd);13791380if(llen ==sizeof(git_binary) -1&&1381!memcmp(git_binary, buffer + hd, llen)) {1382int used;1383 linenr++;1384 used =parse_binary(buffer + hd + llen,1385 size - hd - llen, patch);1386if(used)1387 patchsize = used + llen;1388else1389 patchsize =0;1390}1391else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1392for(i =0; binhdr[i]; i++) {1393int len =strlen(binhdr[i]);1394if(len < size - hd &&1395!memcmp(binhdr[i], buffer + hd, len)) {1396 linenr++;1397 patch->is_binary =1;1398 patchsize = llen;1399break;1400}1401}1402}14031404/* Empty patch cannot be applied if it is a text patch1405 * without metadata change. A binary patch appears1406 * empty to us here.1407 */1408if((apply || check) &&1409(!patch->is_binary && !metadata_changes(patch)))1410die("patch with only garbage at line%d", linenr);1411}14121413return offset + hdrsize + patchsize;1414}14151416#define swap(a,b) myswap((a),(b),sizeof(a))14171418#define myswap(a, b, size) do { \1419 unsigned char mytmp[size]; \1420 memcpy(mytmp, &a, size); \1421 memcpy(&a, &b, size); \1422 memcpy(&b, mytmp, size); \1423} while (0)14241425static voidreverse_patches(struct patch *p)1426{1427for(; p; p = p->next) {1428struct fragment *frag = p->fragments;14291430swap(p->new_name, p->old_name);1431swap(p->new_mode, p->old_mode);1432swap(p->is_new, p->is_delete);1433swap(p->lines_added, p->lines_deleted);1434swap(p->old_sha1_prefix, p->new_sha1_prefix);14351436for(; frag; frag = frag->next) {1437swap(frag->newpos, frag->oldpos);1438swap(frag->newlines, frag->oldlines);1439}1440}1441}14421443static const char pluses[] =1444"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";1445static const char minuses[]=1446"----------------------------------------------------------------------";14471448static voidshow_stats(struct patch *patch)1449{1450struct strbuf qname;1451char*cp = patch->new_name ? patch->new_name : patch->old_name;1452int max, add, del;14531454strbuf_init(&qname,0);1455quote_c_style(cp, &qname, NULL,0);14561457/*1458 * "scale" the filename1459 */1460 max = max_len;1461if(max >50)1462 max =50;14631464if(qname.len > max) {1465 cp =strchr(qname.buf + qname.len +3- max,'/');1466if(!cp)1467 cp = qname.buf + qname.len +3- max;1468strbuf_splice(&qname,0, cp - qname.buf,"...",3);1469}14701471if(patch->is_binary) {1472printf(" %-*s | Bin\n", max, qname.buf);1473strbuf_release(&qname);1474return;1475}14761477printf(" %-*s |", max, qname.buf);1478strbuf_release(&qname);14791480/*1481 * scale the add/delete1482 */1483 max = max + max_change >70?70- max : max_change;1484 add = patch->lines_added;1485 del = patch->lines_deleted;14861487if(max_change >0) {1488int total = ((add + del) * max + max_change /2) / max_change;1489 add = (add * max + max_change /2) / max_change;1490 del = total - add;1491}1492printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,1493 add, pluses, del, minuses);1494}14951496static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)1497{1498switch(st->st_mode & S_IFMT) {1499case S_IFLNK:1500strbuf_grow(buf, st->st_size);1501if(readlink(path, buf->buf, st->st_size) != st->st_size)1502return-1;1503strbuf_setlen(buf, st->st_size);1504return0;1505case S_IFREG:1506if(strbuf_read_file(buf, path, st->st_size) != st->st_size)1507returnerror("unable to open or read%s", path);1508convert_to_git(path, buf->buf, buf->len, buf,0);1509return0;1510default:1511return-1;1512}1513}15141515static voidupdate_pre_post_images(struct image *preimage,1516struct image *postimage,1517char*buf,1518size_t len)1519{1520int i, ctx;1521char*new, *old, *fixed;1522struct image fixed_preimage;15231524/*1525 * Update the preimage with whitespace fixes. Note that we1526 * are not losing preimage->buf -- apply_one_fragment() will1527 * free "oldlines".1528 */1529prepare_image(&fixed_preimage, buf, len,1);1530assert(fixed_preimage.nr == preimage->nr);1531for(i =0; i < preimage->nr; i++)1532 fixed_preimage.line[i].flag = preimage->line[i].flag;1533free(preimage->line_allocated);1534*preimage = fixed_preimage;15351536/*1537 * Adjust the common context lines in postimage, in place.1538 * This is possible because whitespace fixing does not make1539 * the string grow.1540 */1541new= old = postimage->buf;1542 fixed = preimage->buf;1543for(i = ctx =0; i < postimage->nr; i++) {1544size_t len = postimage->line[i].len;1545if(!(postimage->line[i].flag & LINE_COMMON)) {1546/* an added line -- no counterparts in preimage */1547memmove(new, old, len);1548 old += len;1549new+= len;1550continue;1551}15521553/* a common context -- skip it in the original postimage */1554 old += len;15551556/* and find the corresponding one in the fixed preimage */1557while(ctx < preimage->nr &&1558!(preimage->line[ctx].flag & LINE_COMMON)) {1559 fixed += preimage->line[ctx].len;1560 ctx++;1561}1562if(preimage->nr <= ctx)1563die("oops");15641565/* and copy it in, while fixing the line length */1566 len = preimage->line[ctx].len;1567memcpy(new, fixed, len);1568new+= len;1569 fixed += len;1570 postimage->line[i].len = len;1571 ctx++;1572}15731574/* Fix the length of the whole thing */1575 postimage->len =new- postimage->buf;1576}15771578static intmatch_fragment(struct image *img,1579struct image *preimage,1580struct image *postimage,1581unsigned longtry,1582int try_lno,1583unsigned ws_rule,1584int match_beginning,int match_end)1585{1586int i;1587char*fixed_buf, *buf, *orig, *target;15881589if(preimage->nr + try_lno > img->nr)1590return0;15911592if(match_beginning && try_lno)1593return0;15941595if(match_end && preimage->nr + try_lno != img->nr)1596return0;15971598/* Quick hash check */1599for(i =0; i < preimage->nr; i++)1600if(preimage->line[i].hash != img->line[try_lno + i].hash)1601return0;16021603/*1604 * Do we have an exact match? If we were told to match1605 * at the end, size must be exactly at try+fragsize,1606 * otherwise try+fragsize must be still within the preimage,1607 * and either case, the old piece should match the preimage1608 * exactly.1609 */1610if((match_end1611? (try+ preimage->len == img->len)1612: (try+ preimage->len <= img->len)) &&1613!memcmp(img->buf +try, preimage->buf, preimage->len))1614return1;16151616if(ws_error_action != correct_ws_error)1617return0;16181619/*1620 * The hunk does not apply byte-by-byte, but the hash says1621 * it might with whitespace fuzz.1622 */1623 fixed_buf =xmalloc(preimage->len +1);1624 buf = fixed_buf;1625 orig = preimage->buf;1626 target = img->buf +try;1627for(i =0; i < preimage->nr; i++) {1628size_t fixlen;/* length after fixing the preimage */1629size_t oldlen = preimage->line[i].len;1630size_t tgtlen = img->line[try_lno + i].len;1631size_t tgtfixlen;/* length after fixing the target line */1632char tgtfixbuf[1024], *tgtfix;1633int match;16341635/* Try fixing the line in the preimage */1636 fixlen =ws_fix_copy(buf, orig, oldlen, ws_rule, NULL);16371638/* Try fixing the line in the target */1639if(sizeof(tgtfixbuf) < tgtlen)1640 tgtfix = tgtfixbuf;1641else1642 tgtfix =xmalloc(tgtlen);1643 tgtfixlen =ws_fix_copy(tgtfix, target, tgtlen, ws_rule, NULL);16441645/*1646 * If they match, either the preimage was based on1647 * a version before our tree fixed whitespace breakage,1648 * or we are lacking a whitespace-fix patch the tree1649 * the preimage was based on already had (i.e. target1650 * has whitespace breakage, the preimage doesn't).1651 * In either case, we are fixing the whitespace breakages1652 * so we might as well take the fix together with their1653 * real change.1654 */1655 match = (tgtfixlen == fixlen && !memcmp(tgtfix, buf, fixlen));16561657if(tgtfix != tgtfixbuf)1658free(tgtfix);1659if(!match)1660goto unmatch_exit;16611662 orig += oldlen;1663 buf += fixlen;1664 target += tgtlen;1665}16661667/*1668 * Yes, the preimage is based on an older version that still1669 * has whitespace breakages unfixed, and fixing them makes the1670 * hunk match. Update the context lines in the postimage.1671 */1672update_pre_post_images(preimage, postimage,1673 fixed_buf, buf - fixed_buf);1674return1;16751676 unmatch_exit:1677free(fixed_buf);1678return0;1679}16801681static intfind_pos(struct image *img,1682struct image *preimage,1683struct image *postimage,1684int line,1685unsigned ws_rule,1686int match_beginning,int match_end)1687{1688int i;1689unsigned long backwards, forwards,try;1690int backwards_lno, forwards_lno, try_lno;16911692if(preimage->nr > img->nr)1693return-1;16941695/*1696 * If match_begining or match_end is specified, there is no1697 * point starting from a wrong line that will never match and1698 * wander around and wait for a match at the specified end.1699 */1700if(match_beginning)1701 line =0;1702else if(match_end)1703 line = img->nr - preimage->nr;17041705if(line > img->nr)1706 line = img->nr;17071708try=0;1709for(i =0; i < line; i++)1710try+= img->line[i].len;17111712/*1713 * There's probably some smart way to do this, but I'll leave1714 * that to the smart and beautiful people. I'm simple and stupid.1715 */1716 backwards =try;1717 backwards_lno = line;1718 forwards =try;1719 forwards_lno = line;1720 try_lno = line;17211722for(i =0; ; i++) {1723if(match_fragment(img, preimage, postimage,1724try, try_lno, ws_rule,1725 match_beginning, match_end))1726return try_lno;17271728 again:1729if(backwards_lno ==0&& forwards_lno == img->nr)1730break;17311732if(i &1) {1733if(backwards_lno ==0) {1734 i++;1735goto again;1736}1737 backwards_lno--;1738 backwards -= img->line[backwards_lno].len;1739try= backwards;1740 try_lno = backwards_lno;1741}else{1742if(forwards_lno == img->nr) {1743 i++;1744goto again;1745}1746 forwards += img->line[forwards_lno].len;1747 forwards_lno++;1748try= forwards;1749 try_lno = forwards_lno;1750}17511752}1753return-1;1754}17551756static voidremove_first_line(struct image *img)1757{1758 img->buf += img->line[0].len;1759 img->len -= img->line[0].len;1760 img->line++;1761 img->nr--;1762}17631764static voidremove_last_line(struct image *img)1765{1766 img->len -= img->line[--img->nr].len;1767}17681769static voidupdate_image(struct image *img,1770int applied_pos,1771struct image *preimage,1772struct image *postimage)1773{1774/*1775 * remove the copy of preimage at offset in img1776 * and replace it with postimage1777 */1778int i, nr;1779size_t remove_count, insert_count, applied_at =0;1780char*result;17811782for(i =0; i < applied_pos; i++)1783 applied_at += img->line[i].len;17841785 remove_count =0;1786for(i =0; i < preimage->nr; i++)1787 remove_count += img->line[applied_pos + i].len;1788 insert_count = postimage->len;17891790/* Adjust the contents */1791 result =xmalloc(img->len + insert_count - remove_count +1);1792memcpy(result, img->buf, applied_at);1793memcpy(result + applied_at, postimage->buf, postimage->len);1794memcpy(result + applied_at + postimage->len,1795 img->buf + (applied_at + remove_count),1796 img->len - (applied_at + remove_count));1797free(img->buf);1798 img->buf = result;1799 img->len += insert_count - remove_count;1800 result[img->len] ='\0';18011802/* Adjust the line table */1803 nr = img->nr + postimage->nr - preimage->nr;1804if(preimage->nr < postimage->nr) {1805/*1806 * NOTE: this knows that we never call remove_first_line()1807 * on anything other than pre/post image.1808 */1809 img->line =xrealloc(img->line, nr *sizeof(*img->line));1810 img->line_allocated = img->line;1811}1812if(preimage->nr != postimage->nr)1813memmove(img->line + applied_pos + postimage->nr,1814 img->line + applied_pos + preimage->nr,1815(img->nr - (applied_pos + preimage->nr)) *1816sizeof(*img->line));1817memcpy(img->line + applied_pos,1818 postimage->line,1819 postimage->nr *sizeof(*img->line));1820 img->nr = nr;1821}18221823static intapply_one_fragment(struct image *img,struct fragment *frag,1824int inaccurate_eof,unsigned ws_rule)1825{1826int match_beginning, match_end;1827const char*patch = frag->patch;1828int size = frag->size;1829char*old, *new, *oldlines, *newlines;1830int new_blank_lines_at_end =0;1831unsigned long leading, trailing;1832int pos, applied_pos;1833struct image preimage;1834struct image postimage;18351836memset(&preimage,0,sizeof(preimage));1837memset(&postimage,0,sizeof(postimage));1838 oldlines =xmalloc(size);1839 newlines =xmalloc(size);18401841 old = oldlines;1842new= newlines;1843while(size >0) {1844char first;1845int len =linelen(patch, size);1846int plen, added;1847int added_blank_line =0;18481849if(!len)1850break;18511852/*1853 * "plen" is how much of the line we should use for1854 * the actual patch data. Normally we just remove the1855 * first character on the line, but if the line is1856 * followed by "\ No newline", then we also remove the1857 * last one (which is the newline, of course).1858 */1859 plen = len -1;1860if(len < size && patch[len] =='\\')1861 plen--;1862 first = *patch;1863if(apply_in_reverse) {1864if(first =='-')1865 first ='+';1866else if(first =='+')1867 first ='-';1868}18691870switch(first) {1871case'\n':1872/* Newer GNU diff, empty context line */1873if(plen <0)1874/* ... followed by '\No newline'; nothing */1875break;1876*old++ ='\n';1877*new++ ='\n';1878add_line_info(&preimage,"\n",1, LINE_COMMON);1879add_line_info(&postimage,"\n",1, LINE_COMMON);1880break;1881case' ':1882case'-':1883memcpy(old, patch +1, plen);1884add_line_info(&preimage, old, plen,1885(first ==' '? LINE_COMMON :0));1886 old += plen;1887if(first =='-')1888break;1889/* Fall-through for ' ' */1890case'+':1891/* --no-add does not add new lines */1892if(first =='+'&& no_add)1893break;18941895if(first !='+'||1896!whitespace_error ||1897 ws_error_action != correct_ws_error) {1898memcpy(new, patch +1, plen);1899 added = plen;1900}1901else{1902 added =ws_fix_copy(new, patch +1, plen, ws_rule, &applied_after_fixing_ws);1903}1904add_line_info(&postimage,new, added,1905(first =='+'?0: LINE_COMMON));1906new+= added;1907if(first =='+'&&1908 added ==1&&new[-1] =='\n')1909 added_blank_line =1;1910break;1911case'@':case'\\':1912/* Ignore it, we already handled it */1913break;1914default:1915if(apply_verbosely)1916error("invalid start of line: '%c'", first);1917return-1;1918}1919if(added_blank_line)1920 new_blank_lines_at_end++;1921else1922 new_blank_lines_at_end =0;1923 patch += len;1924 size -= len;1925}1926if(inaccurate_eof &&1927 old > oldlines && old[-1] =='\n'&&1928new> newlines &&new[-1] =='\n') {1929 old--;1930new--;1931}19321933 leading = frag->leading;1934 trailing = frag->trailing;19351936/*1937 * A hunk to change lines at the beginning would begin with1938 * @@ -1,L +N,M @@1939 *1940 * And a hunk to add to an empty file would begin with1941 * @@ -0,0 +N,M @@1942 *1943 * In other words, a hunk that is (frag->oldpos <= 1) with or1944 * without leading context must match at the beginning.1945 */1946 match_beginning = frag->oldpos <=1;19471948/*1949 * A hunk without trailing lines must match at the end.1950 * However, we simply cannot tell if a hunk must match end1951 * from the lack of trailing lines if the patch was generated1952 * with unidiff without any context.1953 */1954 match_end = !unidiff_zero && !trailing;19551956 pos = frag->newpos ? (frag->newpos -1) :0;1957 preimage.buf = oldlines;1958 preimage.len = old - oldlines;1959 postimage.buf = newlines;1960 postimage.len =new- newlines;1961 preimage.line = preimage.line_allocated;1962 postimage.line = postimage.line_allocated;19631964for(;;) {19651966 applied_pos =find_pos(img, &preimage, &postimage, pos,1967 ws_rule, match_beginning, match_end);19681969if(applied_pos >=0)1970break;19711972/* Am I at my context limits? */1973if((leading <= p_context) && (trailing <= p_context))1974break;1975if(match_beginning || match_end) {1976 match_beginning = match_end =0;1977continue;1978}19791980/*1981 * Reduce the number of context lines; reduce both1982 * leading and trailing if they are equal otherwise1983 * just reduce the larger context.1984 */1985if(leading >= trailing) {1986remove_first_line(&preimage);1987remove_first_line(&postimage);1988 pos--;1989 leading--;1990}1991if(trailing > leading) {1992remove_last_line(&preimage);1993remove_last_line(&postimage);1994 trailing--;1995}1996}19971998if(applied_pos >=0) {1999if(ws_error_action == correct_ws_error &&2000 new_blank_lines_at_end &&2001 postimage.nr + applied_pos == img->nr) {2002/*2003 * If the patch application adds blank lines2004 * at the end, and if the patch applies at the2005 * end of the image, remove those added blank2006 * lines.2007 */2008while(new_blank_lines_at_end--)2009remove_last_line(&postimage);2010}20112012/*2013 * Warn if it was necessary to reduce the number2014 * of context lines.2015 */2016if((leading != frag->leading) ||2017(trailing != frag->trailing))2018fprintf(stderr,"Context reduced to (%ld/%ld)"2019" to apply fragment at%d\n",2020 leading, trailing, applied_pos+1);2021update_image(img, applied_pos, &preimage, &postimage);2022}else{2023if(apply_verbosely)2024error("while searching for:\n%.*s",2025(int)(old - oldlines), oldlines);2026}20272028free(oldlines);2029free(newlines);2030free(preimage.line_allocated);2031free(postimage.line_allocated);20322033return(applied_pos <0);2034}20352036static intapply_binary_fragment(struct image *img,struct patch *patch)2037{2038struct fragment *fragment = patch->fragments;2039unsigned long len;2040void*dst;20412042/* Binary patch is irreversible without the optional second hunk */2043if(apply_in_reverse) {2044if(!fragment->next)2045returnerror("cannot reverse-apply a binary patch "2046"without the reverse hunk to '%s'",2047 patch->new_name2048? patch->new_name : patch->old_name);2049 fragment = fragment->next;2050}2051switch(fragment->binary_patch_method) {2052case BINARY_DELTA_DEFLATED:2053 dst =patch_delta(img->buf, img->len, fragment->patch,2054 fragment->size, &len);2055if(!dst)2056return-1;2057clear_image(img);2058 img->buf = dst;2059 img->len = len;2060return0;2061case BINARY_LITERAL_DEFLATED:2062clear_image(img);2063 img->len = fragment->size;2064 img->buf =xmalloc(img->len+1);2065memcpy(img->buf, fragment->patch, img->len);2066 img->buf[img->len] ='\0';2067return0;2068}2069return-1;2070}20712072static intapply_binary(struct image *img,struct patch *patch)2073{2074const char*name = patch->old_name ? patch->old_name : patch->new_name;2075unsigned char sha1[20];20762077/*2078 * For safety, we require patch index line to contain2079 * full 40-byte textual SHA1 for old and new, at least for now.2080 */2081if(strlen(patch->old_sha1_prefix) !=40||2082strlen(patch->new_sha1_prefix) !=40||2083get_sha1_hex(patch->old_sha1_prefix, sha1) ||2084get_sha1_hex(patch->new_sha1_prefix, sha1))2085returnerror("cannot apply binary patch to '%s' "2086"without full index line", name);20872088if(patch->old_name) {2089/*2090 * See if the old one matches what the patch2091 * applies to.2092 */2093hash_sha1_file(img->buf, img->len, blob_type, sha1);2094if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2095returnerror("the patch applies to '%s' (%s), "2096"which does not match the "2097"current contents.",2098 name,sha1_to_hex(sha1));2099}2100else{2101/* Otherwise, the old one must be empty. */2102if(img->len)2103returnerror("the patch applies to an empty "2104"'%s' but it is not empty", name);2105}21062107get_sha1_hex(patch->new_sha1_prefix, sha1);2108if(is_null_sha1(sha1)) {2109clear_image(img);2110return0;/* deletion patch */2111}21122113if(has_sha1_file(sha1)) {2114/* We already have the postimage */2115enum object_type type;2116unsigned long size;2117char*result;21182119 result =read_sha1_file(sha1, &type, &size);2120if(!result)2121returnerror("the necessary postimage%sfor "2122"'%s' cannot be read",2123 patch->new_sha1_prefix, name);2124clear_image(img);2125 img->buf = result;2126 img->len = size;2127}else{2128/*2129 * We have verified buf matches the preimage;2130 * apply the patch data to it, which is stored2131 * in the patch->fragments->{patch,size}.2132 */2133if(apply_binary_fragment(img, patch))2134returnerror("binary patch does not apply to '%s'",2135 name);21362137/* verify that the result matches */2138hash_sha1_file(img->buf, img->len, blob_type, sha1);2139if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2140returnerror("binary patch to '%s' creates incorrect result (expecting%s, got%s)",2141 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2142}21432144return0;2145}21462147static intapply_fragments(struct image *img,struct patch *patch)2148{2149struct fragment *frag = patch->fragments;2150const char*name = patch->old_name ? patch->old_name : patch->new_name;2151unsigned ws_rule = patch->ws_rule;2152unsigned inaccurate_eof = patch->inaccurate_eof;21532154if(patch->is_binary)2155returnapply_binary(img, patch);21562157while(frag) {2158if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule)) {2159error("patch failed:%s:%ld", name, frag->oldpos);2160if(!apply_with_reject)2161return-1;2162 frag->rejected =1;2163}2164 frag = frag->next;2165}2166return0;2167}21682169static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2170{2171if(!ce)2172return0;21732174if(S_ISGITLINK(ce->ce_mode)) {2175strbuf_grow(buf,100);2176strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2177}else{2178enum object_type type;2179unsigned long sz;2180char*result;21812182 result =read_sha1_file(ce->sha1, &type, &sz);2183if(!result)2184return-1;2185/* XXX read_sha1_file NUL-terminates */2186strbuf_attach(buf, result, sz, sz +1);2187}2188return0;2189}21902191static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)2192{2193struct strbuf buf;2194struct image image;2195size_t len;2196char*img;21972198strbuf_init(&buf,0);2199if(cached) {2200if(read_file_or_gitlink(ce, &buf))2201returnerror("read of%sfailed", patch->old_name);2202}else if(patch->old_name) {2203if(S_ISGITLINK(patch->old_mode)) {2204if(ce) {2205read_file_or_gitlink(ce, &buf);2206}else{2207/*2208 * There is no way to apply subproject2209 * patch without looking at the index.2210 */2211 patch->fragments = NULL;2212}2213}else{2214if(read_old_data(st, patch->old_name, &buf))2215returnerror("read of%sfailed", patch->old_name);2216}2217}22182219 img =strbuf_detach(&buf, &len);2220prepare_image(&image, img, len, !patch->is_binary);22212222if(apply_fragments(&image, patch) <0)2223return-1;/* note with --reject this succeeds. */2224 patch->result = image.buf;2225 patch->resultsize = image.len;2226free(image.line_allocated);22272228if(0< patch->is_delete && patch->resultsize)2229returnerror("removal patch leaves file contents");22302231return0;2232}22332234static intcheck_to_create_blob(const char*new_name,int ok_if_exists)2235{2236struct stat nst;2237if(!lstat(new_name, &nst)) {2238if(S_ISDIR(nst.st_mode) || ok_if_exists)2239return0;2240/*2241 * A leading component of new_name might be a symlink2242 * that is going to be removed with this patch, but2243 * still pointing at somewhere that has the path.2244 * In such a case, path "new_name" does not exist as2245 * far as git is concerned.2246 */2247if(has_symlink_leading_path(strlen(new_name), new_name))2248return0;22492250returnerror("%s: already exists in working directory", new_name);2251}2252else if((errno != ENOENT) && (errno != ENOTDIR))2253returnerror("%s:%s", new_name,strerror(errno));2254return0;2255}22562257static intverify_index_match(struct cache_entry *ce,struct stat *st)2258{2259if(S_ISGITLINK(ce->ce_mode)) {2260if(!S_ISDIR(st->st_mode))2261return-1;2262return0;2263}2264returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID);2265}22662267static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)2268{2269const char*old_name = patch->old_name;2270int stat_ret =0;2271unsigned st_mode =0;22722273/*2274 * Make sure that we do not have local modifications from the2275 * index when we are looking at the index. Also make sure2276 * we have the preimage file to be patched in the work tree,2277 * unless --cached, which tells git to apply only in the index.2278 */2279if(!old_name)2280return0;22812282assert(patch->is_new <=0);2283if(!cached) {2284 stat_ret =lstat(old_name, st);2285if(stat_ret && errno != ENOENT)2286returnerror("%s:%s", old_name,strerror(errno));2287}2288if(check_index) {2289int pos =cache_name_pos(old_name,strlen(old_name));2290if(pos <0) {2291if(patch->is_new <0)2292goto is_new;2293returnerror("%s: does not exist in index", old_name);2294}2295*ce = active_cache[pos];2296if(stat_ret <0) {2297struct checkout costate;2298/* checkout */2299 costate.base_dir ="";2300 costate.base_dir_len =0;2301 costate.force =0;2302 costate.quiet =0;2303 costate.not_new =0;2304 costate.refresh_cache =1;2305if(checkout_entry(*ce, &costate, NULL) ||2306lstat(old_name, st))2307return-1;2308}2309if(!cached &&verify_index_match(*ce, st))2310returnerror("%s: does not match index", old_name);2311if(cached)2312 st_mode = (*ce)->ce_mode;2313}else if(stat_ret <0) {2314if(patch->is_new <0)2315goto is_new;2316returnerror("%s:%s", old_name,strerror(errno));2317}23182319if(!cached)2320 st_mode =ce_mode_from_stat(*ce, st->st_mode);23212322if(patch->is_new <0)2323 patch->is_new =0;2324if(!patch->old_mode)2325 patch->old_mode = st_mode;2326if((st_mode ^ patch->old_mode) & S_IFMT)2327returnerror("%s: wrong type", old_name);2328if(st_mode != patch->old_mode)2329fprintf(stderr,"warning:%shas type%o, expected%o\n",2330 old_name, st_mode, patch->old_mode);2331return0;23322333 is_new:2334 patch->is_new =1;2335 patch->is_delete =0;2336 patch->old_name = NULL;2337return0;2338}23392340static intcheck_patch(struct patch *patch,struct patch *prev_patch)2341{2342struct stat st;2343const char*old_name = patch->old_name;2344const char*new_name = patch->new_name;2345const char*name = old_name ? old_name : new_name;2346struct cache_entry *ce = NULL;2347int ok_if_exists;2348int status;23492350 patch->rejected =1;/* we will drop this after we succeed */23512352 status =check_preimage(patch, &ce, &st);2353if(status)2354return status;2355 old_name = patch->old_name;23562357if(new_name && prev_patch &&0< prev_patch->is_delete &&2358!strcmp(prev_patch->old_name, new_name))2359/*2360 * A type-change diff is always split into a patch to2361 * delete old, immediately followed by a patch to2362 * create new (see diff.c::run_diff()); in such a case2363 * it is Ok that the entry to be deleted by the2364 * previous patch is still in the working tree and in2365 * the index.2366 */2367 ok_if_exists =1;2368else2369 ok_if_exists =0;23702371if(new_name &&2372((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {2373if(check_index &&2374cache_name_pos(new_name,strlen(new_name)) >=0&&2375!ok_if_exists)2376returnerror("%s: already exists in index", new_name);2377if(!cached) {2378int err =check_to_create_blob(new_name, ok_if_exists);2379if(err)2380return err;2381}2382if(!patch->new_mode) {2383if(0< patch->is_new)2384 patch->new_mode = S_IFREG |0644;2385else2386 patch->new_mode = patch->old_mode;2387}2388}23892390if(new_name && old_name) {2391int same = !strcmp(old_name, new_name);2392if(!patch->new_mode)2393 patch->new_mode = patch->old_mode;2394if((patch->old_mode ^ patch->new_mode) & S_IFMT)2395returnerror("new mode (%o) of%sdoes not match old mode (%o)%s%s",2396 patch->new_mode, new_name, patch->old_mode,2397 same ?"":" of ", same ?"": old_name);2398}23992400if(apply_data(patch, &st, ce) <0)2401returnerror("%s: patch does not apply", name);2402 patch->rejected =0;2403return0;2404}24052406static intcheck_patch_list(struct patch *patch)2407{2408struct patch *prev_patch = NULL;2409int err =0;24102411for(prev_patch = NULL; patch ; patch = patch->next) {2412if(apply_verbosely)2413say_patch_name(stderr,2414"Checking patch ", patch,"...\n");2415 err |=check_patch(patch, prev_patch);2416 prev_patch = patch;2417}2418return err;2419}24202421/* This function tries to read the sha1 from the current index */2422static intget_current_sha1(const char*path,unsigned char*sha1)2423{2424int pos;24252426if(read_cache() <0)2427return-1;2428 pos =cache_name_pos(path,strlen(path));2429if(pos <0)2430return-1;2431hashcpy(sha1, active_cache[pos]->sha1);2432return0;2433}24342435/* Build an index that contains the just the files needed for a 3way merge */2436static voidbuild_fake_ancestor(struct patch *list,const char*filename)2437{2438struct patch *patch;2439struct index_state result = {0};2440int fd;24412442/* Once we start supporting the reverse patch, it may be2443 * worth showing the new sha1 prefix, but until then...2444 */2445for(patch = list; patch; patch = patch->next) {2446const unsigned char*sha1_ptr;2447unsigned char sha1[20];2448struct cache_entry *ce;2449const char*name;24502451 name = patch->old_name ? patch->old_name : patch->new_name;2452if(0< patch->is_new)2453continue;2454else if(get_sha1(patch->old_sha1_prefix, sha1))2455/* git diff has no index line for mode/type changes */2456if(!patch->lines_added && !patch->lines_deleted) {2457if(get_current_sha1(patch->new_name, sha1) ||2458get_current_sha1(patch->old_name, sha1))2459die("mode change for%s, which is not "2460"in current HEAD", name);2461 sha1_ptr = sha1;2462}else2463die("sha1 information is lacking or useless "2464"(%s).", name);2465else2466 sha1_ptr = sha1;24672468 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);2469if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))2470die("Could not add%sto temporary index", name);2471}24722473 fd =open(filename, O_WRONLY | O_CREAT,0666);2474if(fd <0||write_index(&result, fd) ||close(fd))2475die("Could not write temporary index to%s", filename);24762477discard_index(&result);2478}24792480static voidstat_patch_list(struct patch *patch)2481{2482int files, adds, dels;24832484for(files = adds = dels =0; patch ; patch = patch->next) {2485 files++;2486 adds += patch->lines_added;2487 dels += patch->lines_deleted;2488show_stats(patch);2489}24902491printf("%dfiles changed,%dinsertions(+),%ddeletions(-)\n", files, adds, dels);2492}24932494static voidnumstat_patch_list(struct patch *patch)2495{2496for( ; patch; patch = patch->next) {2497const char*name;2498 name = patch->new_name ? patch->new_name : patch->old_name;2499if(patch->is_binary)2500printf("-\t-\t");2501else2502printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);2503write_name_quoted(name, stdout, line_termination);2504}2505}25062507static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)2508{2509if(mode)2510printf("%smode%06o%s\n", newdelete, mode, name);2511else2512printf("%s %s\n", newdelete, name);2513}25142515static voidshow_mode_change(struct patch *p,int show_name)2516{2517if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {2518if(show_name)2519printf(" mode change%06o =>%06o%s\n",2520 p->old_mode, p->new_mode, p->new_name);2521else2522printf(" mode change%06o =>%06o\n",2523 p->old_mode, p->new_mode);2524}2525}25262527static voidshow_rename_copy(struct patch *p)2528{2529const char*renamecopy = p->is_rename ?"rename":"copy";2530const char*old, *new;25312532/* Find common prefix */2533 old = p->old_name;2534new= p->new_name;2535while(1) {2536const char*slash_old, *slash_new;2537 slash_old =strchr(old,'/');2538 slash_new =strchr(new,'/');2539if(!slash_old ||2540!slash_new ||2541 slash_old - old != slash_new -new||2542memcmp(old,new, slash_new -new))2543break;2544 old = slash_old +1;2545new= slash_new +1;2546}2547/* p->old_name thru old is the common prefix, and old and new2548 * through the end of names are renames2549 */2550if(old != p->old_name)2551printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,2552(int)(old - p->old_name), p->old_name,2553 old,new, p->score);2554else2555printf("%s %s=>%s(%d%%)\n", renamecopy,2556 p->old_name, p->new_name, p->score);2557show_mode_change(p,0);2558}25592560static voidsummary_patch_list(struct patch *patch)2561{2562struct patch *p;25632564for(p = patch; p; p = p->next) {2565if(p->is_new)2566show_file_mode_name("create", p->new_mode, p->new_name);2567else if(p->is_delete)2568show_file_mode_name("delete", p->old_mode, p->old_name);2569else{2570if(p->is_rename || p->is_copy)2571show_rename_copy(p);2572else{2573if(p->score) {2574printf(" rewrite%s(%d%%)\n",2575 p->new_name, p->score);2576show_mode_change(p,0);2577}2578else2579show_mode_change(p,1);2580}2581}2582}2583}25842585static voidpatch_stats(struct patch *patch)2586{2587int lines = patch->lines_added + patch->lines_deleted;25882589if(lines > max_change)2590 max_change = lines;2591if(patch->old_name) {2592int len =quote_c_style(patch->old_name, NULL, NULL,0);2593if(!len)2594 len =strlen(patch->old_name);2595if(len > max_len)2596 max_len = len;2597}2598if(patch->new_name) {2599int len =quote_c_style(patch->new_name, NULL, NULL,0);2600if(!len)2601 len =strlen(patch->new_name);2602if(len > max_len)2603 max_len = len;2604}2605}26062607static voidremove_file(struct patch *patch,int rmdir_empty)2608{2609if(update_index) {2610if(remove_file_from_cache(patch->old_name) <0)2611die("unable to remove%sfrom index", patch->old_name);2612}2613if(!cached) {2614if(S_ISGITLINK(patch->old_mode)) {2615if(rmdir(patch->old_name))2616warning("unable to remove submodule%s",2617 patch->old_name);2618}else if(!unlink(patch->old_name) && rmdir_empty) {2619char*name =xstrdup(patch->old_name);2620char*end =strrchr(name,'/');2621while(end) {2622*end =0;2623if(rmdir(name))2624break;2625 end =strrchr(name,'/');2626}2627free(name);2628}2629}2630}26312632static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)2633{2634struct stat st;2635struct cache_entry *ce;2636int namelen =strlen(path);2637unsigned ce_size =cache_entry_size(namelen);26382639if(!update_index)2640return;26412642 ce =xcalloc(1, ce_size);2643memcpy(ce->name, path, namelen);2644 ce->ce_mode =create_ce_mode(mode);2645 ce->ce_flags = namelen;2646if(S_ISGITLINK(mode)) {2647const char*s = buf;26482649if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))2650die("corrupt patch for subproject%s", path);2651}else{2652if(!cached) {2653if(lstat(path, &st) <0)2654die("unable to stat newly created file%s",2655 path);2656fill_stat_cache_info(ce, &st);2657}2658if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)2659die("unable to create backing store for newly created file%s", path);2660}2661if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)2662die("unable to add cache entry for%s", path);2663}26642665static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)2666{2667int fd;2668struct strbuf nbuf;26692670if(S_ISGITLINK(mode)) {2671struct stat st;2672if(!lstat(path, &st) &&S_ISDIR(st.st_mode))2673return0;2674returnmkdir(path,0777);2675}26762677if(has_symlinks &&S_ISLNK(mode))2678/* Although buf:size is counted string, it also is NUL2679 * terminated.2680 */2681returnsymlink(buf, path);26822683 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);2684if(fd <0)2685return-1;26862687strbuf_init(&nbuf,0);2688if(convert_to_working_tree(path, buf, size, &nbuf)) {2689 size = nbuf.len;2690 buf = nbuf.buf;2691}2692write_or_die(fd, buf, size);2693strbuf_release(&nbuf);26942695if(close(fd) <0)2696die("closing file%s:%s", path,strerror(errno));2697return0;2698}26992700/*2701 * We optimistically assume that the directories exist,2702 * which is true 99% of the time anyway. If they don't,2703 * we create them and try again.2704 */2705static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)2706{2707if(cached)2708return;2709if(!try_create_file(path, mode, buf, size))2710return;27112712if(errno == ENOENT) {2713if(safe_create_leading_directories(path))2714return;2715if(!try_create_file(path, mode, buf, size))2716return;2717}27182719if(errno == EEXIST || errno == EACCES) {2720/* We may be trying to create a file where a directory2721 * used to be.2722 */2723struct stat st;2724if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))2725 errno = EEXIST;2726}27272728if(errno == EEXIST) {2729unsigned int nr =getpid();27302731for(;;) {2732const char*newpath;2733 newpath =mkpath("%s~%u", path, nr);2734if(!try_create_file(newpath, mode, buf, size)) {2735if(!rename(newpath, path))2736return;2737unlink(newpath);2738break;2739}2740if(errno != EEXIST)2741break;2742++nr;2743}2744}2745die("unable to write file%smode%o", path, mode);2746}27472748static voidcreate_file(struct patch *patch)2749{2750char*path = patch->new_name;2751unsigned mode = patch->new_mode;2752unsigned long size = patch->resultsize;2753char*buf = patch->result;27542755if(!mode)2756 mode = S_IFREG |0644;2757create_one_file(path, mode, buf, size);2758add_index_file(path, mode, buf, size);2759}27602761/* phase zero is to remove, phase one is to create */2762static voidwrite_out_one_result(struct patch *patch,int phase)2763{2764if(patch->is_delete >0) {2765if(phase ==0)2766remove_file(patch,1);2767return;2768}2769if(patch->is_new >0|| patch->is_copy) {2770if(phase ==1)2771create_file(patch);2772return;2773}2774/*2775 * Rename or modification boils down to the same2776 * thing: remove the old, write the new2777 */2778if(phase ==0)2779remove_file(patch, patch->is_rename);2780if(phase ==1)2781create_file(patch);2782}27832784static intwrite_out_one_reject(struct patch *patch)2785{2786FILE*rej;2787char namebuf[PATH_MAX];2788struct fragment *frag;2789int cnt =0;27902791for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {2792if(!frag->rejected)2793continue;2794 cnt++;2795}27962797if(!cnt) {2798if(apply_verbosely)2799say_patch_name(stderr,2800"Applied patch ", patch," cleanly.\n");2801return0;2802}28032804/* This should not happen, because a removal patch that leaves2805 * contents are marked "rejected" at the patch level.2806 */2807if(!patch->new_name)2808die("internal error");28092810/* Say this even without --verbose */2811say_patch_name(stderr,"Applying patch ", patch," with");2812fprintf(stderr,"%drejects...\n", cnt);28132814 cnt =strlen(patch->new_name);2815if(ARRAY_SIZE(namebuf) <= cnt +5) {2816 cnt =ARRAY_SIZE(namebuf) -5;2817fprintf(stderr,2818"warning: truncating .rej filename to %.*s.rej",2819 cnt -1, patch->new_name);2820}2821memcpy(namebuf, patch->new_name, cnt);2822memcpy(namebuf + cnt,".rej",5);28232824 rej =fopen(namebuf,"w");2825if(!rej)2826returnerror("cannot open%s:%s", namebuf,strerror(errno));28272828/* Normal git tools never deal with .rej, so do not pretend2829 * this is a git patch by saying --git nor give extended2830 * headers. While at it, maybe please "kompare" that wants2831 * the trailing TAB and some garbage at the end of line ;-).2832 */2833fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",2834 patch->new_name, patch->new_name);2835for(cnt =1, frag = patch->fragments;2836 frag;2837 cnt++, frag = frag->next) {2838if(!frag->rejected) {2839fprintf(stderr,"Hunk #%dapplied cleanly.\n", cnt);2840continue;2841}2842fprintf(stderr,"Rejected hunk #%d.\n", cnt);2843fprintf(rej,"%.*s", frag->size, frag->patch);2844if(frag->patch[frag->size-1] !='\n')2845fputc('\n', rej);2846}2847fclose(rej);2848return-1;2849}28502851static intwrite_out_results(struct patch *list,int skipped_patch)2852{2853int phase;2854int errs =0;2855struct patch *l;28562857if(!list && !skipped_patch)2858returnerror("No changes");28592860for(phase =0; phase <2; phase++) {2861 l = list;2862while(l) {2863if(l->rejected)2864 errs =1;2865else{2866write_out_one_result(l, phase);2867if(phase ==1&&write_out_one_reject(l))2868 errs =1;2869}2870 l = l->next;2871}2872}2873return errs;2874}28752876static struct lock_file lock_file;28772878static struct excludes {2879struct excludes *next;2880const char*path;2881} *excludes;28822883static intuse_patch(struct patch *p)2884{2885const char*pathname = p->new_name ? p->new_name : p->old_name;2886struct excludes *x = excludes;2887while(x) {2888if(fnmatch(x->path, pathname,0) ==0)2889return0;2890 x = x->next;2891}2892if(0< prefix_length) {2893int pathlen =strlen(pathname);2894if(pathlen <= prefix_length ||2895memcmp(prefix, pathname, prefix_length))2896return0;2897}2898return1;2899}29002901static voidprefix_one(char**name)2902{2903char*old_name = *name;2904if(!old_name)2905return;2906*name =xstrdup(prefix_filename(prefix, prefix_length, *name));2907free(old_name);2908}29092910static voidprefix_patches(struct patch *p)2911{2912if(!prefix || p->is_toplevel_relative)2913return;2914for( ; p; p = p->next) {2915if(p->new_name == p->old_name) {2916char*prefixed = p->new_name;2917prefix_one(&prefixed);2918 p->new_name = p->old_name = prefixed;2919}2920else{2921prefix_one(&p->new_name);2922prefix_one(&p->old_name);2923}2924}2925}29262927static intapply_patch(int fd,const char*filename,int inaccurate_eof)2928{2929size_t offset;2930struct strbuf buf;2931struct patch *list = NULL, **listp = &list;2932int skipped_patch =0;29332934strbuf_init(&buf,0);2935 patch_input_file = filename;2936read_patch_file(&buf, fd);2937 offset =0;2938while(offset < buf.len) {2939struct patch *patch;2940int nr;29412942 patch =xcalloc(1,sizeof(*patch));2943 patch->inaccurate_eof = inaccurate_eof;2944 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);2945if(nr <0)2946break;2947if(apply_in_reverse)2948reverse_patches(patch);2949if(prefix)2950prefix_patches(patch);2951if(use_patch(patch)) {2952patch_stats(patch);2953*listp = patch;2954 listp = &patch->next;2955}2956else{2957/* perhaps free it a bit better? */2958free(patch);2959 skipped_patch++;2960}2961 offset += nr;2962}29632964if(whitespace_error && (ws_error_action == die_on_ws_error))2965 apply =0;29662967 update_index = check_index && apply;2968if(update_index && newfd <0)2969 newfd =hold_locked_index(&lock_file,1);29702971if(check_index) {2972if(read_cache() <0)2973die("unable to read index file");2974}29752976if((check || apply) &&2977check_patch_list(list) <0&&2978!apply_with_reject)2979exit(1);29802981if(apply &&write_out_results(list, skipped_patch))2982exit(1);29832984if(fake_ancestor)2985build_fake_ancestor(list, fake_ancestor);29862987if(diffstat)2988stat_patch_list(list);29892990if(numstat)2991numstat_patch_list(list);29922993if(summary)2994summary_patch_list(list);29952996strbuf_release(&buf);2997return0;2998}29993000static intgit_apply_config(const char*var,const char*value,void*cb)3001{3002if(!strcmp(var,"apply.whitespace"))3003returngit_config_string(&apply_default_whitespace, var, value);3004returngit_default_config(var, value, cb);3005}300630073008intcmd_apply(int argc,const char**argv,const char*unused_prefix)3009{3010int i;3011int read_stdin =1;3012int inaccurate_eof =0;3013int errs =0;3014int is_not_gitdir;30153016const char*whitespace_option = NULL;30173018 prefix =setup_git_directory_gently(&is_not_gitdir);3019 prefix_length = prefix ?strlen(prefix) :0;3020git_config(git_apply_config, NULL);3021if(apply_default_whitespace)3022parse_whitespace_option(apply_default_whitespace);30233024for(i =1; i < argc; i++) {3025const char*arg = argv[i];3026char*end;3027int fd;30283029if(!strcmp(arg,"-")) {3030 errs |=apply_patch(0,"<stdin>", inaccurate_eof);3031 read_stdin =0;3032continue;3033}3034if(!prefixcmp(arg,"--exclude=")) {3035struct excludes *x =xmalloc(sizeof(*x));3036 x->path = arg +10;3037 x->next = excludes;3038 excludes = x;3039continue;3040}3041if(!prefixcmp(arg,"-p")) {3042 p_value =atoi(arg +2);3043 p_value_known =1;3044continue;3045}3046if(!strcmp(arg,"--no-add")) {3047 no_add =1;3048continue;3049}3050if(!strcmp(arg,"--stat")) {3051 apply =0;3052 diffstat =1;3053continue;3054}3055if(!strcmp(arg,"--allow-binary-replacement") ||3056!strcmp(arg,"--binary")) {3057continue;/* now no-op */3058}3059if(!strcmp(arg,"--numstat")) {3060 apply =0;3061 numstat =1;3062continue;3063}3064if(!strcmp(arg,"--summary")) {3065 apply =0;3066 summary =1;3067continue;3068}3069if(!strcmp(arg,"--check")) {3070 apply =0;3071 check =1;3072continue;3073}3074if(!strcmp(arg,"--index")) {3075if(is_not_gitdir)3076die("--index outside a repository");3077 check_index =1;3078continue;3079}3080if(!strcmp(arg,"--cached")) {3081if(is_not_gitdir)3082die("--cached outside a repository");3083 check_index =1;3084 cached =1;3085continue;3086}3087if(!strcmp(arg,"--apply")) {3088 apply =1;3089continue;3090}3091if(!strcmp(arg,"--build-fake-ancestor")) {3092 apply =0;3093if(++i >= argc)3094die("need a filename");3095 fake_ancestor = argv[i];3096continue;3097}3098if(!strcmp(arg,"-z")) {3099 line_termination =0;3100continue;3101}3102if(!prefixcmp(arg,"-C")) {3103 p_context =strtoul(arg +2, &end,0);3104if(*end !='\0')3105die("unrecognized context count '%s'", arg +2);3106continue;3107}3108if(!prefixcmp(arg,"--whitespace=")) {3109 whitespace_option = arg +13;3110parse_whitespace_option(arg +13);3111continue;3112}3113if(!strcmp(arg,"-R") || !strcmp(arg,"--reverse")) {3114 apply_in_reverse =1;3115continue;3116}3117if(!strcmp(arg,"--unidiff-zero")) {3118 unidiff_zero =1;3119continue;3120}3121if(!strcmp(arg,"--reject")) {3122 apply = apply_with_reject = apply_verbosely =1;3123continue;3124}3125if(!strcmp(arg,"-v") || !strcmp(arg,"--verbose")) {3126 apply_verbosely =1;3127continue;3128}3129if(!strcmp(arg,"--inaccurate-eof")) {3130 inaccurate_eof =1;3131continue;3132}3133if(!prefixcmp(arg,"--root=")) {3134 arg +=strlen("--root=");3135 root_len =strlen(arg);3136if(root_len && arg[root_len -1] !='/') {3137char*new_root;3138 root = new_root =xmalloc(root_len +2);3139strcpy(new_root, arg);3140strcpy(new_root + root_len++,"/");3141}else3142 root = arg;3143continue;3144}3145if(0< prefix_length)3146 arg =prefix_filename(prefix, prefix_length, arg);31473148 fd =open(arg, O_RDONLY);3149if(fd <0)3150die("can't open patch '%s':%s", arg,strerror(errno));3151 read_stdin =0;3152set_default_whitespace_mode(whitespace_option);3153 errs |=apply_patch(fd, arg, inaccurate_eof);3154close(fd);3155}3156set_default_whitespace_mode(whitespace_option);3157if(read_stdin)3158 errs |=apply_patch(0,"<stdin>", inaccurate_eof);3159if(whitespace_error) {3160if(squelch_whitespace_errors &&3161 squelch_whitespace_errors < whitespace_error) {3162int squelched =3163 whitespace_error - squelch_whitespace_errors;3164fprintf(stderr,"warning: squelched%d"3165"whitespace error%s\n",3166 squelched,3167 squelched ==1?"":"s");3168}3169if(ws_error_action == die_on_ws_error)3170die("%dline%sadd%swhitespace errors.",3171 whitespace_error,3172 whitespace_error ==1?"":"s",3173 whitespace_error ==1?"s":"");3174if(applied_after_fixing_ws && apply)3175fprintf(stderr,"warning:%dline%sapplied after"3176" fixing whitespace errors.\n",3177 applied_after_fixing_ws,3178 applied_after_fixing_ws ==1?"":"s");3179else if(whitespace_error)3180fprintf(stderr,"warning:%dline%sadd%swhitespace errors.\n",3181 whitespace_error,3182 whitespace_error ==1?"":"s",3183 whitespace_error ==1?"s":"");3184}31853186if(update_index) {3187if(write_cache(newfd, active_cache, active_nr) ||3188commit_locked_index(&lock_file))3189die("Unable to write new index file");3190}31913192return!!errs;3193}