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; 64 65static enum ws_ignore { 66 ignore_ws_none, 67 ignore_ws_change, 68} ws_ignore_action = ignore_ws_none; 69 70 71static const char*patch_input_file; 72static const char*root; 73static int root_len; 74static int read_stdin =1; 75static int options; 76 77static voidparse_whitespace_option(const char*option) 78{ 79if(!option) { 80 ws_error_action = warn_on_ws_error; 81return; 82} 83if(!strcmp(option,"warn")) { 84 ws_error_action = warn_on_ws_error; 85return; 86} 87if(!strcmp(option,"nowarn")) { 88 ws_error_action = nowarn_ws_error; 89return; 90} 91if(!strcmp(option,"error")) { 92 ws_error_action = die_on_ws_error; 93return; 94} 95if(!strcmp(option,"error-all")) { 96 ws_error_action = die_on_ws_error; 97 squelch_whitespace_errors =0; 98return; 99} 100if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 101 ws_error_action = correct_ws_error; 102return; 103} 104die("unrecognized whitespace option '%s'", option); 105} 106 107static voidparse_ignorewhitespace_option(const char*option) 108{ 109if(!option || !strcmp(option,"no") || 110!strcmp(option,"false") || !strcmp(option,"never") || 111!strcmp(option,"none")) { 112 ws_ignore_action = ignore_ws_none; 113return; 114} 115if(!strcmp(option,"change")) { 116 ws_ignore_action = ignore_ws_change; 117return; 118} 119die("unrecognized whitespace ignore option '%s'", option); 120} 121 122static voidset_default_whitespace_mode(const char*whitespace_option) 123{ 124if(!whitespace_option && !apply_default_whitespace) 125 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 126} 127 128/* 129 * For "diff-stat" like behaviour, we keep track of the biggest change 130 * we've seen, and the longest filename. That allows us to do simple 131 * scaling. 132 */ 133static int max_change, max_len; 134 135/* 136 * Various "current state", notably line numbers and what 137 * file (and how) we're patching right now.. The "is_xxxx" 138 * things are flags, where -1 means "don't know yet". 139 */ 140static int linenr =1; 141 142/* 143 * This represents one "hunk" from a patch, starting with 144 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 145 * patch text is pointed at by patch, and its byte length 146 * is stored in size. leading and trailing are the number 147 * of context lines. 148 */ 149struct fragment { 150unsigned long leading, trailing; 151unsigned long oldpos, oldlines; 152unsigned long newpos, newlines; 153const char*patch; 154int size; 155int rejected; 156int linenr; 157struct fragment *next; 158}; 159 160/* 161 * When dealing with a binary patch, we reuse "leading" field 162 * to store the type of the binary hunk, either deflated "delta" 163 * or deflated "literal". 164 */ 165#define binary_patch_method leading 166#define BINARY_DELTA_DEFLATED 1 167#define BINARY_LITERAL_DEFLATED 2 168 169/* 170 * This represents a "patch" to a file, both metainfo changes 171 * such as creation/deletion, filemode and content changes represented 172 * as a series of fragments. 173 */ 174struct patch { 175char*new_name, *old_name, *def_name; 176unsigned int old_mode, new_mode; 177int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 178int rejected; 179unsigned ws_rule; 180unsigned long deflate_origlen; 181int lines_added, lines_deleted; 182int score; 183unsigned int is_toplevel_relative:1; 184unsigned int inaccurate_eof:1; 185unsigned int is_binary:1; 186unsigned int is_copy:1; 187unsigned int is_rename:1; 188unsigned int recount:1; 189struct fragment *fragments; 190char*result; 191size_t resultsize; 192char old_sha1_prefix[41]; 193char new_sha1_prefix[41]; 194struct patch *next; 195}; 196 197/* 198 * A line in a file, len-bytes long (includes the terminating LF, 199 * except for an incomplete line at the end if the file ends with 200 * one), and its contents hashes to 'hash'. 201 */ 202struct line { 203size_t len; 204unsigned hash :24; 205unsigned flag :8; 206#define LINE_COMMON 1 207}; 208 209/* 210 * This represents a "file", which is an array of "lines". 211 */ 212struct image { 213char*buf; 214size_t len; 215size_t nr; 216size_t alloc; 217struct line *line_allocated; 218struct line *line; 219}; 220 221/* 222 * Records filenames that have been touched, in order to handle 223 * the case where more than one patches touch the same file. 224 */ 225 226static struct string_list fn_table; 227 228static uint32_thash_line(const char*cp,size_t len) 229{ 230size_t i; 231uint32_t h; 232for(i =0, h =0; i < len; i++) { 233if(!isspace(cp[i])) { 234 h = h *3+ (cp[i] &0xff); 235} 236} 237return h; 238} 239 240/* 241 * Compare lines s1 of length n1 and s2 of length n2, ignoring 242 * whitespace difference. Returns 1 if they match, 0 otherwise 243 */ 244static intfuzzy_matchlines(const char*s1,size_t n1, 245const char*s2,size_t n2) 246{ 247const char*last1 = s1 + n1 -1; 248const char*last2 = s2 + n2 -1; 249int result =0; 250 251if(n1 <0|| n2 <0) 252return0; 253 254/* ignore line endings */ 255while((*last1 =='\r') || (*last1 =='\n')) 256 last1--; 257while((*last2 =='\r') || (*last2 =='\n')) 258 last2--; 259 260/* skip leading whitespace */ 261while(isspace(*s1) && (s1 <= last1)) 262 s1++; 263while(isspace(*s2) && (s2 <= last2)) 264 s2++; 265/* early return if both lines are empty */ 266if((s1 > last1) && (s2 > last2)) 267return1; 268while(!result) { 269 result = *s1++ - *s2++; 270/* 271 * Skip whitespace inside. We check for whitespace on 272 * both buffers because we don't want "a b" to match 273 * "ab" 274 */ 275if(isspace(*s1) &&isspace(*s2)) { 276while(isspace(*s1) && s1 <= last1) 277 s1++; 278while(isspace(*s2) && s2 <= last2) 279 s2++; 280} 281/* 282 * If we reached the end on one side only, 283 * lines don't match 284 */ 285if( 286((s2 > last2) && (s1 <= last1)) || 287((s1 > last1) && (s2 <= last2))) 288return0; 289if((s1 > last1) && (s2 > last2)) 290break; 291} 292 293return!result; 294} 295 296static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 297{ 298ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 299 img->line_allocated[img->nr].len = len; 300 img->line_allocated[img->nr].hash =hash_line(bol, len); 301 img->line_allocated[img->nr].flag = flag; 302 img->nr++; 303} 304 305static voidprepare_image(struct image *image,char*buf,size_t len, 306int prepare_linetable) 307{ 308const char*cp, *ep; 309 310memset(image,0,sizeof(*image)); 311 image->buf = buf; 312 image->len = len; 313 314if(!prepare_linetable) 315return; 316 317 ep = image->buf + image->len; 318 cp = image->buf; 319while(cp < ep) { 320const char*next; 321for(next = cp; next < ep && *next !='\n'; next++) 322; 323if(next < ep) 324 next++; 325add_line_info(image, cp, next - cp,0); 326 cp = next; 327} 328 image->line = image->line_allocated; 329} 330 331static voidclear_image(struct image *image) 332{ 333free(image->buf); 334 image->buf = NULL; 335 image->len =0; 336} 337 338static voidsay_patch_name(FILE*output,const char*pre, 339struct patch *patch,const char*post) 340{ 341fputs(pre, output); 342if(patch->old_name && patch->new_name && 343strcmp(patch->old_name, patch->new_name)) { 344quote_c_style(patch->old_name, NULL, output,0); 345fputs(" => ", output); 346quote_c_style(patch->new_name, NULL, output,0); 347}else{ 348const char*n = patch->new_name; 349if(!n) 350 n = patch->old_name; 351quote_c_style(n, NULL, output,0); 352} 353fputs(post, output); 354} 355 356#define CHUNKSIZE (8192) 357#define SLOP (16) 358 359static voidread_patch_file(struct strbuf *sb,int fd) 360{ 361if(strbuf_read(sb, fd,0) <0) 362die_errno("git apply: failed to read"); 363 364/* 365 * Make sure that we have some slop in the buffer 366 * so that we can do speculative "memcmp" etc, and 367 * see to it that it is NUL-filled. 368 */ 369strbuf_grow(sb, SLOP); 370memset(sb->buf + sb->len,0, SLOP); 371} 372 373static unsigned longlinelen(const char*buffer,unsigned long size) 374{ 375unsigned long len =0; 376while(size--) { 377 len++; 378if(*buffer++ =='\n') 379break; 380} 381return len; 382} 383 384static intis_dev_null(const char*str) 385{ 386return!memcmp("/dev/null", str,9) &&isspace(str[9]); 387} 388 389#define TERM_SPACE 1 390#define TERM_TAB 2 391 392static intname_terminate(const char*name,int namelen,int c,int terminate) 393{ 394if(c ==' '&& !(terminate & TERM_SPACE)) 395return0; 396if(c =='\t'&& !(terminate & TERM_TAB)) 397return0; 398 399return1; 400} 401 402/* remove double slashes to make --index work with such filenames */ 403static char*squash_slash(char*name) 404{ 405int i =0, j =0; 406 407if(!name) 408return NULL; 409 410while(name[i]) { 411if((name[j++] = name[i++]) =='/') 412while(name[i] =='/') 413 i++; 414} 415 name[j] ='\0'; 416return name; 417} 418 419static char*find_name(const char*line,char*def,int p_value,int terminate) 420{ 421int len; 422const char*start = NULL; 423 424if(p_value ==0) 425 start = line; 426 427if(*line =='"') { 428struct strbuf name = STRBUF_INIT; 429 430/* 431 * Proposed "new-style" GNU patch/diff format; see 432 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2 433 */ 434if(!unquote_c_style(&name, line, NULL)) { 435char*cp; 436 437for(cp = name.buf; p_value; p_value--) { 438 cp =strchr(cp,'/'); 439if(!cp) 440break; 441 cp++; 442} 443if(cp) { 444/* name can later be freed, so we need 445 * to memmove, not just return cp 446 */ 447strbuf_remove(&name,0, cp - name.buf); 448free(def); 449if(root) 450strbuf_insert(&name,0, root, root_len); 451returnsquash_slash(strbuf_detach(&name, NULL)); 452} 453} 454strbuf_release(&name); 455} 456 457for(;;) { 458char c = *line; 459 460if(isspace(c)) { 461if(c =='\n') 462break; 463if(name_terminate(start, line-start, c, terminate)) 464break; 465} 466 line++; 467if(c =='/'&& !--p_value) 468 start = line; 469} 470if(!start) 471returnsquash_slash(def); 472 len = line - start; 473if(!len) 474returnsquash_slash(def); 475 476/* 477 * Generally we prefer the shorter name, especially 478 * if the other one is just a variation of that with 479 * something else tacked on to the end (ie "file.orig" 480 * or "file~"). 481 */ 482if(def) { 483int deflen =strlen(def); 484if(deflen < len && !strncmp(start, def, deflen)) 485returnsquash_slash(def); 486free(def); 487} 488 489if(root) { 490char*ret =xmalloc(root_len + len +1); 491strcpy(ret, root); 492memcpy(ret + root_len, start, len); 493 ret[root_len + len] ='\0'; 494returnsquash_slash(ret); 495} 496 497returnsquash_slash(xmemdupz(start, len)); 498} 499 500static intcount_slashes(const char*cp) 501{ 502int cnt =0; 503char ch; 504 505while((ch = *cp++)) 506if(ch =='/') 507 cnt++; 508return cnt; 509} 510 511/* 512 * Given the string after "--- " or "+++ ", guess the appropriate 513 * p_value for the given patch. 514 */ 515static intguess_p_value(const char*nameline) 516{ 517char*name, *cp; 518int val = -1; 519 520if(is_dev_null(nameline)) 521return-1; 522 name =find_name(nameline, NULL,0, TERM_SPACE | TERM_TAB); 523if(!name) 524return-1; 525 cp =strchr(name,'/'); 526if(!cp) 527 val =0; 528else if(prefix) { 529/* 530 * Does it begin with "a/$our-prefix" and such? Then this is 531 * very likely to apply to our directory. 532 */ 533if(!strncmp(name, prefix, prefix_length)) 534 val =count_slashes(prefix); 535else{ 536 cp++; 537if(!strncmp(cp, prefix, prefix_length)) 538 val =count_slashes(prefix) +1; 539} 540} 541free(name); 542return val; 543} 544 545/* 546 * Does the ---/+++ line has the POSIX timestamp after the last HT? 547 * GNU diff puts epoch there to signal a creation/deletion event. Is 548 * this such a timestamp? 549 */ 550static inthas_epoch_timestamp(const char*nameline) 551{ 552/* 553 * We are only interested in epoch timestamp; any non-zero 554 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 555 * For the same reason, the date must be either 1969-12-31 or 556 * 1970-01-01, and the seconds part must be "00". 557 */ 558const char stamp_regexp[] = 559"^(1969-12-31|1970-01-01)" 560" " 561"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 562" " 563"([-+][0-2][0-9][0-5][0-9])\n"; 564const char*timestamp = NULL, *cp; 565static regex_t *stamp; 566 regmatch_t m[10]; 567int zoneoffset; 568int hourminute; 569int status; 570 571for(cp = nameline; *cp !='\n'; cp++) { 572if(*cp =='\t') 573 timestamp = cp +1; 574} 575if(!timestamp) 576return0; 577if(!stamp) { 578 stamp =xmalloc(sizeof(*stamp)); 579if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 580warning("Cannot prepare timestamp regexp%s", 581 stamp_regexp); 582return0; 583} 584} 585 586 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 587if(status) { 588if(status != REG_NOMATCH) 589warning("regexec returned%dfor input:%s", 590 status, timestamp); 591return0; 592} 593 594 zoneoffset =strtol(timestamp + m[3].rm_so +1, NULL,10); 595 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 596if(timestamp[m[3].rm_so] =='-') 597 zoneoffset = -zoneoffset; 598 599/* 600 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 601 * (west of GMT) or 1970-01-01 (east of GMT) 602 */ 603if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 604(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 605return0; 606 607 hourminute = (strtol(timestamp +11, NULL,10) *60+ 608strtol(timestamp +14, NULL,10) - 609 zoneoffset); 610 611return((zoneoffset <0&& hourminute ==1440) || 612(0<= zoneoffset && !hourminute)); 613} 614 615/* 616 * Get the name etc info from the ---/+++ lines of a traditional patch header 617 * 618 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 619 * files, we can happily check the index for a match, but for creating a 620 * new file we should try to match whatever "patch" does. I have no idea. 621 */ 622static voidparse_traditional_patch(const char*first,const char*second,struct patch *patch) 623{ 624char*name; 625 626 first +=4;/* skip "--- " */ 627 second +=4;/* skip "+++ " */ 628if(!p_value_known) { 629int p, q; 630 p =guess_p_value(first); 631 q =guess_p_value(second); 632if(p <0) p = q; 633if(0<= p && p == q) { 634 p_value = p; 635 p_value_known =1; 636} 637} 638if(is_dev_null(first)) { 639 patch->is_new =1; 640 patch->is_delete =0; 641 name =find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB); 642 patch->new_name = name; 643}else if(is_dev_null(second)) { 644 patch->is_new =0; 645 patch->is_delete =1; 646 name =find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB); 647 patch->old_name = name; 648}else{ 649 name =find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB); 650 name =find_name(second, name, p_value, TERM_SPACE | TERM_TAB); 651if(has_epoch_timestamp(first)) { 652 patch->is_new =1; 653 patch->is_delete =0; 654 patch->new_name = name; 655}else if(has_epoch_timestamp(second)) { 656 patch->is_new =0; 657 patch->is_delete =1; 658 patch->old_name = name; 659}else{ 660 patch->old_name = patch->new_name = name; 661} 662} 663if(!name) 664die("unable to find filename in patch at line%d", linenr); 665} 666 667static intgitdiff_hdrend(const char*line,struct patch *patch) 668{ 669return-1; 670} 671 672/* 673 * We're anal about diff header consistency, to make 674 * sure that we don't end up having strange ambiguous 675 * patches floating around. 676 * 677 * As a result, gitdiff_{old|new}name() will check 678 * their names against any previous information, just 679 * to make sure.. 680 */ 681static char*gitdiff_verify_name(const char*line,int isnull,char*orig_name,const char*oldnew) 682{ 683if(!orig_name && !isnull) 684returnfind_name(line, NULL, p_value, TERM_TAB); 685 686if(orig_name) { 687int len; 688const char*name; 689char*another; 690 name = orig_name; 691 len =strlen(name); 692if(isnull) 693die("git apply: bad git-diff - expected /dev/null, got%son line%d", name, linenr); 694 another =find_name(line, NULL, p_value, TERM_TAB); 695if(!another ||memcmp(another, name, len +1)) 696die("git apply: bad git-diff - inconsistent%sfilename on line%d", oldnew, linenr); 697free(another); 698return orig_name; 699} 700else{ 701/* expect "/dev/null" */ 702if(memcmp("/dev/null", line,9) || line[9] !='\n') 703die("git apply: bad git-diff - expected /dev/null on line%d", linenr); 704return NULL; 705} 706} 707 708static intgitdiff_oldname(const char*line,struct patch *patch) 709{ 710 patch->old_name =gitdiff_verify_name(line, patch->is_new, patch->old_name,"old"); 711return0; 712} 713 714static intgitdiff_newname(const char*line,struct patch *patch) 715{ 716 patch->new_name =gitdiff_verify_name(line, patch->is_delete, patch->new_name,"new"); 717return0; 718} 719 720static intgitdiff_oldmode(const char*line,struct patch *patch) 721{ 722 patch->old_mode =strtoul(line, NULL,8); 723return0; 724} 725 726static intgitdiff_newmode(const char*line,struct patch *patch) 727{ 728 patch->new_mode =strtoul(line, NULL,8); 729return0; 730} 731 732static intgitdiff_delete(const char*line,struct patch *patch) 733{ 734 patch->is_delete =1; 735 patch->old_name = patch->def_name; 736returngitdiff_oldmode(line, patch); 737} 738 739static intgitdiff_newfile(const char*line,struct patch *patch) 740{ 741 patch->is_new =1; 742 patch->new_name = patch->def_name; 743returngitdiff_newmode(line, patch); 744} 745 746static intgitdiff_copysrc(const char*line,struct patch *patch) 747{ 748 patch->is_copy =1; 749 patch->old_name =find_name(line, NULL,0,0); 750return0; 751} 752 753static intgitdiff_copydst(const char*line,struct patch *patch) 754{ 755 patch->is_copy =1; 756 patch->new_name =find_name(line, NULL,0,0); 757return0; 758} 759 760static intgitdiff_renamesrc(const char*line,struct patch *patch) 761{ 762 patch->is_rename =1; 763 patch->old_name =find_name(line, NULL,0,0); 764return0; 765} 766 767static intgitdiff_renamedst(const char*line,struct patch *patch) 768{ 769 patch->is_rename =1; 770 patch->new_name =find_name(line, NULL,0,0); 771return0; 772} 773 774static intgitdiff_similarity(const char*line,struct patch *patch) 775{ 776if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 777 patch->score =0; 778return0; 779} 780 781static intgitdiff_dissimilarity(const char*line,struct patch *patch) 782{ 783if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 784 patch->score =0; 785return0; 786} 787 788static intgitdiff_index(const char*line,struct patch *patch) 789{ 790/* 791 * index line is N hexadecimal, "..", N hexadecimal, 792 * and optional space with octal mode. 793 */ 794const char*ptr, *eol; 795int len; 796 797 ptr =strchr(line,'.'); 798if(!ptr || ptr[1] !='.'||40< ptr - line) 799return0; 800 len = ptr - line; 801memcpy(patch->old_sha1_prefix, line, len); 802 patch->old_sha1_prefix[len] =0; 803 804 line = ptr +2; 805 ptr =strchr(line,' '); 806 eol =strchr(line,'\n'); 807 808if(!ptr || eol < ptr) 809 ptr = eol; 810 len = ptr - line; 811 812if(40< len) 813return0; 814memcpy(patch->new_sha1_prefix, line, len); 815 patch->new_sha1_prefix[len] =0; 816if(*ptr ==' ') 817 patch->old_mode =strtoul(ptr+1, NULL,8); 818return0; 819} 820 821/* 822 * This is normal for a diff that doesn't change anything: we'll fall through 823 * into the next diff. Tell the parser to break out. 824 */ 825static intgitdiff_unrecognized(const char*line,struct patch *patch) 826{ 827return-1; 828} 829 830static const char*stop_at_slash(const char*line,int llen) 831{ 832int nslash = p_value; 833int i; 834 835for(i =0; i < llen; i++) { 836int ch = line[i]; 837if(ch =='/'&& --nslash <=0) 838return&line[i]; 839} 840return NULL; 841} 842 843/* 844 * This is to extract the same name that appears on "diff --git" 845 * line. We do not find and return anything if it is a rename 846 * patch, and it is OK because we will find the name elsewhere. 847 * We need to reliably find name only when it is mode-change only, 848 * creation or deletion of an empty file. In any of these cases, 849 * both sides are the same name under a/ and b/ respectively. 850 */ 851static char*git_header_name(char*line,int llen) 852{ 853const char*name; 854const char*second = NULL; 855size_t len; 856 857 line +=strlen("diff --git "); 858 llen -=strlen("diff --git "); 859 860if(*line =='"') { 861const char*cp; 862struct strbuf first = STRBUF_INIT; 863struct strbuf sp = STRBUF_INIT; 864 865if(unquote_c_style(&first, line, &second)) 866goto free_and_fail1; 867 868/* advance to the first slash */ 869 cp =stop_at_slash(first.buf, first.len); 870/* we do not accept absolute paths */ 871if(!cp || cp == first.buf) 872goto free_and_fail1; 873strbuf_remove(&first,0, cp +1- first.buf); 874 875/* 876 * second points at one past closing dq of name. 877 * find the second name. 878 */ 879while((second < line + llen) &&isspace(*second)) 880 second++; 881 882if(line + llen <= second) 883goto free_and_fail1; 884if(*second =='"') { 885if(unquote_c_style(&sp, second, NULL)) 886goto free_and_fail1; 887 cp =stop_at_slash(sp.buf, sp.len); 888if(!cp || cp == sp.buf) 889goto free_and_fail1; 890/* They must match, otherwise ignore */ 891if(strcmp(cp +1, first.buf)) 892goto free_and_fail1; 893strbuf_release(&sp); 894returnstrbuf_detach(&first, NULL); 895} 896 897/* unquoted second */ 898 cp =stop_at_slash(second, line + llen - second); 899if(!cp || cp == second) 900goto free_and_fail1; 901 cp++; 902if(line + llen - cp != first.len +1|| 903memcmp(first.buf, cp, first.len)) 904goto free_and_fail1; 905returnstrbuf_detach(&first, NULL); 906 907 free_and_fail1: 908strbuf_release(&first); 909strbuf_release(&sp); 910return NULL; 911} 912 913/* unquoted first name */ 914 name =stop_at_slash(line, llen); 915if(!name || name == line) 916return NULL; 917 name++; 918 919/* 920 * since the first name is unquoted, a dq if exists must be 921 * the beginning of the second name. 922 */ 923for(second = name; second < line + llen; second++) { 924if(*second =='"') { 925struct strbuf sp = STRBUF_INIT; 926const char*np; 927 928if(unquote_c_style(&sp, second, NULL)) 929goto free_and_fail2; 930 931 np =stop_at_slash(sp.buf, sp.len); 932if(!np || np == sp.buf) 933goto free_and_fail2; 934 np++; 935 936 len = sp.buf + sp.len - np; 937if(len < second - name && 938!strncmp(np, name, len) && 939isspace(name[len])) { 940/* Good */ 941strbuf_remove(&sp,0, np - sp.buf); 942returnstrbuf_detach(&sp, NULL); 943} 944 945 free_and_fail2: 946strbuf_release(&sp); 947return NULL; 948} 949} 950 951/* 952 * Accept a name only if it shows up twice, exactly the same 953 * form. 954 */ 955for(len =0; ; len++) { 956switch(name[len]) { 957default: 958continue; 959case'\n': 960return NULL; 961case'\t':case' ': 962 second = name+len; 963for(;;) { 964char c = *second++; 965if(c =='\n') 966return NULL; 967if(c =='/') 968break; 969} 970if(second[len] =='\n'&& !memcmp(name, second, len)) { 971returnxmemdupz(name, len); 972} 973} 974} 975} 976 977/* Verify that we recognize the lines following a git header */ 978static intparse_git_header(char*line,int len,unsigned int size,struct patch *patch) 979{ 980unsigned long offset; 981 982/* A git diff has explicit new/delete information, so we don't guess */ 983 patch->is_new =0; 984 patch->is_delete =0; 985 986/* 987 * Some things may not have the old name in the 988 * rest of the headers anywhere (pure mode changes, 989 * or removing or adding empty files), so we get 990 * the default name from the header. 991 */ 992 patch->def_name =git_header_name(line, len); 993if(patch->def_name && root) { 994char*s =xmalloc(root_len +strlen(patch->def_name) +1); 995strcpy(s, root); 996strcpy(s + root_len, patch->def_name); 997free(patch->def_name); 998 patch->def_name = s; 999}10001001 line += len;1002 size -= len;1003 linenr++;1004for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) {1005static const struct opentry {1006const char*str;1007int(*fn)(const char*,struct patch *);1008} optable[] = {1009{"@@ -", gitdiff_hdrend },1010{"--- ", gitdiff_oldname },1011{"+++ ", gitdiff_newname },1012{"old mode ", gitdiff_oldmode },1013{"new mode ", gitdiff_newmode },1014{"deleted file mode ", gitdiff_delete },1015{"new file mode ", gitdiff_newfile },1016{"copy from ", gitdiff_copysrc },1017{"copy to ", gitdiff_copydst },1018{"rename old ", gitdiff_renamesrc },1019{"rename new ", gitdiff_renamedst },1020{"rename from ", gitdiff_renamesrc },1021{"rename to ", gitdiff_renamedst },1022{"similarity index ", gitdiff_similarity },1023{"dissimilarity index ", gitdiff_dissimilarity },1024{"index ", gitdiff_index },1025{"", gitdiff_unrecognized },1026};1027int i;10281029 len =linelen(line, size);1030if(!len || line[len-1] !='\n')1031break;1032for(i =0; i <ARRAY_SIZE(optable); i++) {1033const struct opentry *p = optable + i;1034int oplen =strlen(p->str);1035if(len < oplen ||memcmp(p->str, line, oplen))1036continue;1037if(p->fn(line + oplen, patch) <0)1038return offset;1039break;1040}1041}10421043return offset;1044}10451046static intparse_num(const char*line,unsigned long*p)1047{1048char*ptr;10491050if(!isdigit(*line))1051return0;1052*p =strtoul(line, &ptr,10);1053return ptr - line;1054}10551056static intparse_range(const char*line,int len,int offset,const char*expect,1057unsigned long*p1,unsigned long*p2)1058{1059int digits, ex;10601061if(offset <0|| offset >= len)1062return-1;1063 line += offset;1064 len -= offset;10651066 digits =parse_num(line, p1);1067if(!digits)1068return-1;10691070 offset += digits;1071 line += digits;1072 len -= digits;10731074*p2 =1;1075if(*line ==',') {1076 digits =parse_num(line+1, p2);1077if(!digits)1078return-1;10791080 offset += digits+1;1081 line += digits+1;1082 len -= digits+1;1083}10841085 ex =strlen(expect);1086if(ex > len)1087return-1;1088if(memcmp(line, expect, ex))1089return-1;10901091return offset + ex;1092}10931094static voidrecount_diff(char*line,int size,struct fragment *fragment)1095{1096int oldlines =0, newlines =0, ret =0;10971098if(size <1) {1099warning("recount: ignore empty hunk");1100return;1101}11021103for(;;) {1104int len =linelen(line, size);1105 size -= len;1106 line += len;11071108if(size <1)1109break;11101111switch(*line) {1112case' ':case'\n':1113 newlines++;1114/* fall through */1115case'-':1116 oldlines++;1117continue;1118case'+':1119 newlines++;1120continue;1121case'\\':1122continue;1123case'@':1124 ret = size <3||prefixcmp(line,"@@ ");1125break;1126case'd':1127 ret = size <5||prefixcmp(line,"diff ");1128break;1129default:1130 ret = -1;1131break;1132}1133if(ret) {1134warning("recount: unexpected line: %.*s",1135(int)linelen(line, size), line);1136return;1137}1138break;1139}1140 fragment->oldlines = oldlines;1141 fragment->newlines = newlines;1142}11431144/*1145 * Parse a unified diff fragment header of the1146 * form "@@ -a,b +c,d @@"1147 */1148static intparse_fragment_header(char*line,int len,struct fragment *fragment)1149{1150int offset;11511152if(!len || line[len-1] !='\n')1153return-1;11541155/* Figure out the number of lines in a fragment */1156 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1157 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);11581159return offset;1160}11611162static intfind_header(char*line,unsigned long size,int*hdrsize,struct patch *patch)1163{1164unsigned long offset, len;11651166 patch->is_toplevel_relative =0;1167 patch->is_rename = patch->is_copy =0;1168 patch->is_new = patch->is_delete = -1;1169 patch->old_mode = patch->new_mode =0;1170 patch->old_name = patch->new_name = NULL;1171for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) {1172unsigned long nextlen;11731174 len =linelen(line, size);1175if(!len)1176break;11771178/* Testing this early allows us to take a few shortcuts.. */1179if(len <6)1180continue;11811182/*1183 * Make sure we don't find any unconnected patch fragments.1184 * That's a sign that we didn't find a header, and that a1185 * patch has become corrupted/broken up.1186 */1187if(!memcmp("@@ -", line,4)) {1188struct fragment dummy;1189if(parse_fragment_header(line, len, &dummy) <0)1190continue;1191die("patch fragment without header at line%d: %.*s",1192 linenr, (int)len-1, line);1193}11941195if(size < len +6)1196break;11971198/*1199 * Git patch? It might not have a real patch, just a rename1200 * or mode change, so we handle that specially1201 */1202if(!memcmp("diff --git ", line,11)) {1203int git_hdr_len =parse_git_header(line, len, size, patch);1204if(git_hdr_len <= len)1205continue;1206if(!patch->old_name && !patch->new_name) {1207if(!patch->def_name)1208die("git diff header lacks filename information when removing "1209"%dleading pathname components (line%d)", p_value, linenr);1210 patch->old_name = patch->new_name = patch->def_name;1211}1212 patch->is_toplevel_relative =1;1213*hdrsize = git_hdr_len;1214return offset;1215}12161217/* --- followed by +++ ? */1218if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1219continue;12201221/*1222 * We only accept unified patches, so we want it to1223 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1224 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1225 */1226 nextlen =linelen(line + len, size - len);1227if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1228continue;12291230/* Ok, we'll consider it a patch */1231parse_traditional_patch(line, line+len, patch);1232*hdrsize = len + nextlen;1233 linenr +=2;1234return offset;1235}1236return-1;1237}12381239static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1240{1241char*err;12421243if(!result)1244return;12451246 whitespace_error++;1247if(squelch_whitespace_errors &&1248 squelch_whitespace_errors < whitespace_error)1249return;12501251 err =whitespace_error_string(result);1252fprintf(stderr,"%s:%d:%s.\n%.*s\n",1253 patch_input_file, linenr, err, len, line);1254free(err);1255}12561257static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1258{1259unsigned result =ws_check(line +1, len -1, ws_rule);12601261record_ws_error(result, line +1, len -2, linenr);1262}12631264/*1265 * Parse a unified diff. Note that this really needs to parse each1266 * fragment separately, since the only way to know the difference1267 * between a "---" that is part of a patch, and a "---" that starts1268 * the next patch is to look at the line counts..1269 */1270static intparse_fragment(char*line,unsigned long size,1271struct patch *patch,struct fragment *fragment)1272{1273int added, deleted;1274int len =linelen(line, size), offset;1275unsigned long oldlines, newlines;1276unsigned long leading, trailing;12771278 offset =parse_fragment_header(line, len, fragment);1279if(offset <0)1280return-1;1281if(offset >0&& patch->recount)1282recount_diff(line + offset, size - offset, fragment);1283 oldlines = fragment->oldlines;1284 newlines = fragment->newlines;1285 leading =0;1286 trailing =0;12871288/* Parse the thing.. */1289 line += len;1290 size -= len;1291 linenr++;1292 added = deleted =0;1293for(offset = len;12940< size;1295 offset += len, size -= len, line += len, linenr++) {1296if(!oldlines && !newlines)1297break;1298 len =linelen(line, size);1299if(!len || line[len-1] !='\n')1300return-1;1301switch(*line) {1302default:1303return-1;1304case'\n':/* newer GNU diff, an empty context line */1305case' ':1306 oldlines--;1307 newlines--;1308if(!deleted && !added)1309 leading++;1310 trailing++;1311break;1312case'-':1313if(apply_in_reverse &&1314 ws_error_action != nowarn_ws_error)1315check_whitespace(line, len, patch->ws_rule);1316 deleted++;1317 oldlines--;1318 trailing =0;1319break;1320case'+':1321if(!apply_in_reverse &&1322 ws_error_action != nowarn_ws_error)1323check_whitespace(line, len, patch->ws_rule);1324 added++;1325 newlines--;1326 trailing =0;1327break;13281329/*1330 * We allow "\ No newline at end of file". Depending1331 * on locale settings when the patch was produced we1332 * don't know what this line looks like. The only1333 * thing we do know is that it begins with "\ ".1334 * Checking for 12 is just for sanity check -- any1335 * l10n of "\ No newline..." is at least that long.1336 */1337case'\\':1338if(len <12||memcmp(line,"\\",2))1339return-1;1340break;1341}1342}1343if(oldlines || newlines)1344return-1;1345 fragment->leading = leading;1346 fragment->trailing = trailing;13471348/*1349 * If a fragment ends with an incomplete line, we failed to include1350 * it in the above loop because we hit oldlines == newlines == 01351 * before seeing it.1352 */1353if(12< size && !memcmp(line,"\\",2))1354 offset +=linelen(line, size);13551356 patch->lines_added += added;1357 patch->lines_deleted += deleted;13581359if(0< patch->is_new && oldlines)1360returnerror("new file depends on old contents");1361if(0< patch->is_delete && newlines)1362returnerror("deleted file still has contents");1363return offset;1364}13651366static intparse_single_patch(char*line,unsigned long size,struct patch *patch)1367{1368unsigned long offset =0;1369unsigned long oldlines =0, newlines =0, context =0;1370struct fragment **fragp = &patch->fragments;13711372while(size >4&& !memcmp(line,"@@ -",4)) {1373struct fragment *fragment;1374int len;13751376 fragment =xcalloc(1,sizeof(*fragment));1377 fragment->linenr = linenr;1378 len =parse_fragment(line, size, patch, fragment);1379if(len <=0)1380die("corrupt patch at line%d", linenr);1381 fragment->patch = line;1382 fragment->size = len;1383 oldlines += fragment->oldlines;1384 newlines += fragment->newlines;1385 context += fragment->leading + fragment->trailing;13861387*fragp = fragment;1388 fragp = &fragment->next;13891390 offset += len;1391 line += len;1392 size -= len;1393}13941395/*1396 * If something was removed (i.e. we have old-lines) it cannot1397 * be creation, and if something was added it cannot be1398 * deletion. However, the reverse is not true; --unified=01399 * patches that only add are not necessarily creation even1400 * though they do not have any old lines, and ones that only1401 * delete are not necessarily deletion.1402 *1403 * Unfortunately, a real creation/deletion patch do _not_ have1404 * any context line by definition, so we cannot safely tell it1405 * apart with --unified=0 insanity. At least if the patch has1406 * more than one hunk it is not creation or deletion.1407 */1408if(patch->is_new <0&&1409(oldlines || (patch->fragments && patch->fragments->next)))1410 patch->is_new =0;1411if(patch->is_delete <0&&1412(newlines || (patch->fragments && patch->fragments->next)))1413 patch->is_delete =0;14141415if(0< patch->is_new && oldlines)1416die("new file%sdepends on old contents", patch->new_name);1417if(0< patch->is_delete && newlines)1418die("deleted file%sstill has contents", patch->old_name);1419if(!patch->is_delete && !newlines && context)1420fprintf(stderr,"** warning: file%sbecomes empty but "1421"is not deleted\n", patch->new_name);14221423return offset;1424}14251426staticinlineintmetadata_changes(struct patch *patch)1427{1428return patch->is_rename >0||1429 patch->is_copy >0||1430 patch->is_new >0||1431 patch->is_delete ||1432(patch->old_mode && patch->new_mode &&1433 patch->old_mode != patch->new_mode);1434}14351436static char*inflate_it(const void*data,unsigned long size,1437unsigned long inflated_size)1438{1439 z_stream stream;1440void*out;1441int st;14421443memset(&stream,0,sizeof(stream));14441445 stream.next_in = (unsigned char*)data;1446 stream.avail_in = size;1447 stream.next_out = out =xmalloc(inflated_size);1448 stream.avail_out = inflated_size;1449git_inflate_init(&stream);1450 st =git_inflate(&stream, Z_FINISH);1451git_inflate_end(&stream);1452if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1453free(out);1454return NULL;1455}1456return out;1457}14581459static struct fragment *parse_binary_hunk(char**buf_p,1460unsigned long*sz_p,1461int*status_p,1462int*used_p)1463{1464/*1465 * Expect a line that begins with binary patch method ("literal"1466 * or "delta"), followed by the length of data before deflating.1467 * a sequence of 'length-byte' followed by base-85 encoded data1468 * should follow, terminated by a newline.1469 *1470 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1471 * and we would limit the patch line to 66 characters,1472 * so one line can fit up to 13 groups that would decode1473 * to 52 bytes max. The length byte 'A'-'Z' corresponds1474 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1475 */1476int llen, used;1477unsigned long size = *sz_p;1478char*buffer = *buf_p;1479int patch_method;1480unsigned long origlen;1481char*data = NULL;1482int hunk_size =0;1483struct fragment *frag;14841485 llen =linelen(buffer, size);1486 used = llen;14871488*status_p =0;14891490if(!prefixcmp(buffer,"delta ")) {1491 patch_method = BINARY_DELTA_DEFLATED;1492 origlen =strtoul(buffer +6, NULL,10);1493}1494else if(!prefixcmp(buffer,"literal ")) {1495 patch_method = BINARY_LITERAL_DEFLATED;1496 origlen =strtoul(buffer +8, NULL,10);1497}1498else1499return NULL;15001501 linenr++;1502 buffer += llen;1503while(1) {1504int byte_length, max_byte_length, newsize;1505 llen =linelen(buffer, size);1506 used += llen;1507 linenr++;1508if(llen ==1) {1509/* consume the blank line */1510 buffer++;1511 size--;1512break;1513}1514/*1515 * Minimum line is "A00000\n" which is 7-byte long,1516 * and the line length must be multiple of 5 plus 2.1517 */1518if((llen <7) || (llen-2) %5)1519goto corrupt;1520 max_byte_length = (llen -2) /5*4;1521 byte_length = *buffer;1522if('A'<= byte_length && byte_length <='Z')1523 byte_length = byte_length -'A'+1;1524else if('a'<= byte_length && byte_length <='z')1525 byte_length = byte_length -'a'+27;1526else1527goto corrupt;1528/* if the input length was not multiple of 4, we would1529 * have filler at the end but the filler should never1530 * exceed 3 bytes1531 */1532if(max_byte_length < byte_length ||1533 byte_length <= max_byte_length -4)1534goto corrupt;1535 newsize = hunk_size + byte_length;1536 data =xrealloc(data, newsize);1537if(decode_85(data + hunk_size, buffer +1, byte_length))1538goto corrupt;1539 hunk_size = newsize;1540 buffer += llen;1541 size -= llen;1542}15431544 frag =xcalloc(1,sizeof(*frag));1545 frag->patch =inflate_it(data, hunk_size, origlen);1546if(!frag->patch)1547goto corrupt;1548free(data);1549 frag->size = origlen;1550*buf_p = buffer;1551*sz_p = size;1552*used_p = used;1553 frag->binary_patch_method = patch_method;1554return frag;15551556 corrupt:1557free(data);1558*status_p = -1;1559error("corrupt binary patch at line%d: %.*s",1560 linenr-1, llen-1, buffer);1561return NULL;1562}15631564static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1565{1566/*1567 * We have read "GIT binary patch\n"; what follows is a line1568 * that says the patch method (currently, either "literal" or1569 * "delta") and the length of data before deflating; a1570 * sequence of 'length-byte' followed by base-85 encoded data1571 * follows.1572 *1573 * When a binary patch is reversible, there is another binary1574 * hunk in the same format, starting with patch method (either1575 * "literal" or "delta") with the length of data, and a sequence1576 * of length-byte + base-85 encoded data, terminated with another1577 * empty line. This data, when applied to the postimage, produces1578 * the preimage.1579 */1580struct fragment *forward;1581struct fragment *reverse;1582int status;1583int used, used_1;15841585 forward =parse_binary_hunk(&buffer, &size, &status, &used);1586if(!forward && !status)1587/* there has to be one hunk (forward hunk) */1588returnerror("unrecognized binary patch at line%d", linenr-1);1589if(status)1590/* otherwise we already gave an error message */1591return status;15921593 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1594if(reverse)1595 used += used_1;1596else if(status) {1597/*1598 * Not having reverse hunk is not an error, but having1599 * a corrupt reverse hunk is.1600 */1601free((void*) forward->patch);1602free(forward);1603return status;1604}1605 forward->next = reverse;1606 patch->fragments = forward;1607 patch->is_binary =1;1608return used;1609}16101611static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1612{1613int hdrsize, patchsize;1614int offset =find_header(buffer, size, &hdrsize, patch);16151616if(offset <0)1617return offset;16181619 patch->ws_rule =whitespace_rule(patch->new_name1620? patch->new_name1621: patch->old_name);16221623 patchsize =parse_single_patch(buffer + offset + hdrsize,1624 size - offset - hdrsize, patch);16251626if(!patchsize) {1627static const char*binhdr[] = {1628"Binary files ",1629"Files ",1630 NULL,1631};1632static const char git_binary[] ="GIT binary patch\n";1633int i;1634int hd = hdrsize + offset;1635unsigned long llen =linelen(buffer + hd, size - hd);16361637if(llen ==sizeof(git_binary) -1&&1638!memcmp(git_binary, buffer + hd, llen)) {1639int used;1640 linenr++;1641 used =parse_binary(buffer + hd + llen,1642 size - hd - llen, patch);1643if(used)1644 patchsize = used + llen;1645else1646 patchsize =0;1647}1648else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1649for(i =0; binhdr[i]; i++) {1650int len =strlen(binhdr[i]);1651if(len < size - hd &&1652!memcmp(binhdr[i], buffer + hd, len)) {1653 linenr++;1654 patch->is_binary =1;1655 patchsize = llen;1656break;1657}1658}1659}16601661/* Empty patch cannot be applied if it is a text patch1662 * without metadata change. A binary patch appears1663 * empty to us here.1664 */1665if((apply || check) &&1666(!patch->is_binary && !metadata_changes(patch)))1667die("patch with only garbage at line%d", linenr);1668}16691670return offset + hdrsize + patchsize;1671}16721673#define swap(a,b) myswap((a),(b),sizeof(a))16741675#define myswap(a, b, size) do { \1676 unsigned char mytmp[size]; \1677 memcpy(mytmp, &a, size); \1678 memcpy(&a, &b, size); \1679 memcpy(&b, mytmp, size); \1680} while (0)16811682static voidreverse_patches(struct patch *p)1683{1684for(; p; p = p->next) {1685struct fragment *frag = p->fragments;16861687swap(p->new_name, p->old_name);1688swap(p->new_mode, p->old_mode);1689swap(p->is_new, p->is_delete);1690swap(p->lines_added, p->lines_deleted);1691swap(p->old_sha1_prefix, p->new_sha1_prefix);16921693for(; frag; frag = frag->next) {1694swap(frag->newpos, frag->oldpos);1695swap(frag->newlines, frag->oldlines);1696}1697}1698}16991700static const char pluses[] =1701"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";1702static const char minuses[]=1703"----------------------------------------------------------------------";17041705static voidshow_stats(struct patch *patch)1706{1707struct strbuf qname = STRBUF_INIT;1708char*cp = patch->new_name ? patch->new_name : patch->old_name;1709int max, add, del;17101711quote_c_style(cp, &qname, NULL,0);17121713/*1714 * "scale" the filename1715 */1716 max = max_len;1717if(max >50)1718 max =50;17191720if(qname.len > max) {1721 cp =strchr(qname.buf + qname.len +3- max,'/');1722if(!cp)1723 cp = qname.buf + qname.len +3- max;1724strbuf_splice(&qname,0, cp - qname.buf,"...",3);1725}17261727if(patch->is_binary) {1728printf(" %-*s | Bin\n", max, qname.buf);1729strbuf_release(&qname);1730return;1731}17321733printf(" %-*s |", max, qname.buf);1734strbuf_release(&qname);17351736/*1737 * scale the add/delete1738 */1739 max = max + max_change >70?70- max : max_change;1740 add = patch->lines_added;1741 del = patch->lines_deleted;17421743if(max_change >0) {1744int total = ((add + del) * max + max_change /2) / max_change;1745 add = (add * max + max_change /2) / max_change;1746 del = total - add;1747}1748printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,1749 add, pluses, del, minuses);1750}17511752static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)1753{1754switch(st->st_mode & S_IFMT) {1755case S_IFLNK:1756if(strbuf_readlink(buf, path, st->st_size) <0)1757returnerror("unable to read symlink%s", path);1758return0;1759case S_IFREG:1760if(strbuf_read_file(buf, path, st->st_size) != st->st_size)1761returnerror("unable to open or read%s", path);1762convert_to_git(path, buf->buf, buf->len, buf,0);1763return0;1764default:1765return-1;1766}1767}17681769/*1770 * Update the preimage, and the common lines in postimage,1771 * from buffer buf of length len. If postlen is 0 the postimage1772 * is updated in place, otherwise it's updated on a new buffer1773 * of length postlen1774 */17751776static voidupdate_pre_post_images(struct image *preimage,1777struct image *postimage,1778char*buf,1779size_t len,size_t postlen)1780{1781int i, ctx;1782char*new, *old, *fixed;1783struct image fixed_preimage;17841785/*1786 * Update the preimage with whitespace fixes. Note that we1787 * are not losing preimage->buf -- apply_one_fragment() will1788 * free "oldlines".1789 */1790prepare_image(&fixed_preimage, buf, len,1);1791assert(fixed_preimage.nr == preimage->nr);1792for(i =0; i < preimage->nr; i++)1793 fixed_preimage.line[i].flag = preimage->line[i].flag;1794free(preimage->line_allocated);1795*preimage = fixed_preimage;17961797/*1798 * Adjust the common context lines in postimage. This can be1799 * done in-place when we are just doing whitespace fixing,1800 * which does not make the string grow, but needs a new buffer1801 * when ignoring whitespace causes the update, since in this case1802 * we could have e.g. tabs converted to multiple spaces.1803 * We trust the caller to tell us if the update can be done1804 * in place (postlen==0) or not.1805 */1806 old = postimage->buf;1807if(postlen)1808new= postimage->buf =xmalloc(postlen);1809else1810new= old;1811 fixed = preimage->buf;1812for(i = ctx =0; i < postimage->nr; i++) {1813size_t len = postimage->line[i].len;1814if(!(postimage->line[i].flag & LINE_COMMON)) {1815/* an added line -- no counterparts in preimage */1816memmove(new, old, len);1817 old += len;1818new+= len;1819continue;1820}18211822/* a common context -- skip it in the original postimage */1823 old += len;18241825/* and find the corresponding one in the fixed preimage */1826while(ctx < preimage->nr &&1827!(preimage->line[ctx].flag & LINE_COMMON)) {1828 fixed += preimage->line[ctx].len;1829 ctx++;1830}1831if(preimage->nr <= ctx)1832die("oops");18331834/* and copy it in, while fixing the line length */1835 len = preimage->line[ctx].len;1836memcpy(new, fixed, len);1837new+= len;1838 fixed += len;1839 postimage->line[i].len = len;1840 ctx++;1841}18421843/* Fix the length of the whole thing */1844 postimage->len =new- postimage->buf;1845}18461847static intmatch_fragment(struct image *img,1848struct image *preimage,1849struct image *postimage,1850unsigned longtry,1851int try_lno,1852unsigned ws_rule,1853int match_beginning,int match_end)1854{1855int i;1856char*fixed_buf, *buf, *orig, *target;1857int preimage_limit;18581859if(preimage->nr + try_lno <= img->nr) {1860/*1861 * The hunk falls within the boundaries of img.1862 */1863 preimage_limit = preimage->nr;1864if(match_end && (preimage->nr + try_lno != img->nr))1865return0;1866}else if(ws_error_action == correct_ws_error &&1867(ws_rule & WS_BLANK_AT_EOF) && match_end) {1868/*1869 * This hunk that matches at the end extends beyond1870 * the end of img, and we are removing blank lines1871 * at the end of the file. This many lines from the1872 * beginning of the preimage must match with img, and1873 * the remainder of the preimage must be blank.1874 */1875 preimage_limit = img->nr - try_lno;1876}else{1877/*1878 * The hunk extends beyond the end of the img and1879 * we are not removing blanks at the end, so we1880 * should reject the hunk at this position.1881 */1882return0;1883}18841885if(match_beginning && try_lno)1886return0;18871888/* Quick hash check */1889for(i =0; i < preimage_limit; i++)1890if(preimage->line[i].hash != img->line[try_lno + i].hash)1891return0;18921893if(preimage_limit == preimage->nr) {1894/*1895 * Do we have an exact match? If we were told to match1896 * at the end, size must be exactly at try+fragsize,1897 * otherwise try+fragsize must be still within the preimage,1898 * and either case, the old piece should match the preimage1899 * exactly.1900 */1901if((match_end1902? (try+ preimage->len == img->len)1903: (try+ preimage->len <= img->len)) &&1904!memcmp(img->buf +try, preimage->buf, preimage->len))1905return1;1906}else{1907/*1908 * The preimage extends beyond the end of img, so1909 * there cannot be an exact match.1910 *1911 * There must be one non-blank context line that match1912 * a line before the end of img.1913 */1914char*buf_end;19151916 buf = preimage->buf;1917 buf_end = buf;1918for(i =0; i < preimage_limit; i++)1919 buf_end += preimage->line[i].len;19201921for( ; buf < buf_end; buf++)1922if(!isspace(*buf))1923break;1924if(buf == buf_end)1925return0;1926}19271928/*1929 * No exact match. If we are ignoring whitespace, run a line-by-line1930 * fuzzy matching. We collect all the line length information because1931 * we need it to adjust whitespace if we match.1932 */1933if(ws_ignore_action == ignore_ws_change) {1934size_t imgoff =0;1935size_t preoff =0;1936size_t postlen = postimage->len;1937size_t extra_chars;1938char*preimage_eof;1939char*preimage_end;1940for(i =0; i < preimage_limit; i++) {1941size_t prelen = preimage->line[i].len;1942size_t imglen = img->line[try_lno+i].len;19431944if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,1945 preimage->buf + preoff, prelen))1946return0;1947if(preimage->line[i].flag & LINE_COMMON)1948 postlen += imglen - prelen;1949 imgoff += imglen;1950 preoff += prelen;1951}19521953/*1954 * Ok, the preimage matches with whitespace fuzz.1955 *1956 * imgoff now holds the true length of the target that1957 * matches the preimage before the end of the file.1958 *1959 * Count the number of characters in the preimage that fall1960 * beyond the end of the file and make sure that all of them1961 * are whitespace characters. (This can only happen if1962 * we are removing blank lines at the end of the file.)1963 */1964 buf = preimage_eof = preimage->buf + preoff;1965for( ; i < preimage->nr; i++)1966 preoff += preimage->line[i].len;1967 preimage_end = preimage->buf + preoff;1968for( ; buf < preimage_end; buf++)1969if(!isspace(*buf))1970return0;19711972/*1973 * Update the preimage and the common postimage context1974 * lines to use the same whitespace as the target.1975 * If whitespace is missing in the target (i.e.1976 * if the preimage extends beyond the end of the file),1977 * use the whitespace from the preimage.1978 */1979 extra_chars = preimage_end - preimage_eof;1980 fixed_buf =xmalloc(imgoff + extra_chars);1981memcpy(fixed_buf, img->buf +try, imgoff);1982memcpy(fixed_buf + imgoff, preimage_eof, extra_chars);1983 imgoff += extra_chars;1984update_pre_post_images(preimage, postimage,1985 fixed_buf, imgoff, postlen);1986return1;1987}19881989if(ws_error_action != correct_ws_error)1990return0;19911992/*1993 * The hunk does not apply byte-by-byte, but the hash says1994 * it might with whitespace fuzz. We haven't been asked to1995 * ignore whitespace, we were asked to correct whitespace1996 * errors, so let's try matching after whitespace correction.1997 *1998 * The preimage may extend beyond the end of the file,1999 * but in this loop we will only handle the part of the2000 * preimage that falls within the file.2001 */2002 fixed_buf =xmalloc(preimage->len +1);2003 buf = fixed_buf;2004 orig = preimage->buf;2005 target = img->buf +try;2006for(i =0; i < preimage_limit; i++) {2007size_t fixlen;/* length after fixing the preimage */2008size_t oldlen = preimage->line[i].len;2009size_t tgtlen = img->line[try_lno + i].len;2010size_t tgtfixlen;/* length after fixing the target line */2011char tgtfixbuf[1024], *tgtfix;2012int match;20132014/* Try fixing the line in the preimage */2015 fixlen =ws_fix_copy(buf, orig, oldlen, ws_rule, NULL);20162017/* Try fixing the line in the target */2018if(sizeof(tgtfixbuf) > tgtlen)2019 tgtfix = tgtfixbuf;2020else2021 tgtfix =xmalloc(tgtlen);2022 tgtfixlen =ws_fix_copy(tgtfix, target, tgtlen, ws_rule, NULL);20232024/*2025 * If they match, either the preimage was based on2026 * a version before our tree fixed whitespace breakage,2027 * or we are lacking a whitespace-fix patch the tree2028 * the preimage was based on already had (i.e. target2029 * has whitespace breakage, the preimage doesn't).2030 * In either case, we are fixing the whitespace breakages2031 * so we might as well take the fix together with their2032 * real change.2033 */2034 match = (tgtfixlen == fixlen && !memcmp(tgtfix, buf, fixlen));20352036if(tgtfix != tgtfixbuf)2037free(tgtfix);2038if(!match)2039goto unmatch_exit;20402041 orig += oldlen;2042 buf += fixlen;2043 target += tgtlen;2044}204520462047/*2048 * Now handle the lines in the preimage that falls beyond the2049 * end of the file (if any). They will only match if they are2050 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2051 * false).2052 */2053for( ; i < preimage->nr; i++) {2054size_t fixlen;/* length after fixing the preimage */2055size_t oldlen = preimage->line[i].len;2056int j;20572058/* Try fixing the line in the preimage */2059 fixlen =ws_fix_copy(buf, orig, oldlen, ws_rule, NULL);20602061for(j =0; j < fixlen; j++)2062if(!isspace(buf[j]))2063goto unmatch_exit;20642065 orig += oldlen;2066 buf += fixlen;2067}20682069/*2070 * Yes, the preimage is based on an older version that still2071 * has whitespace breakages unfixed, and fixing them makes the2072 * hunk match. Update the context lines in the postimage.2073 */2074update_pre_post_images(preimage, postimage,2075 fixed_buf, buf - fixed_buf,0);2076return1;20772078 unmatch_exit:2079free(fixed_buf);2080return0;2081}20822083static intfind_pos(struct image *img,2084struct image *preimage,2085struct image *postimage,2086int line,2087unsigned ws_rule,2088int match_beginning,int match_end)2089{2090int i;2091unsigned long backwards, forwards,try;2092int backwards_lno, forwards_lno, try_lno;20932094/*2095 * If match_beginning or match_end is specified, there is no2096 * point starting from a wrong line that will never match and2097 * wander around and wait for a match at the specified end.2098 */2099if(match_beginning)2100 line =0;2101else if(match_end)2102 line = img->nr - preimage->nr;21032104/*2105 * Because the comparison is unsigned, the following test2106 * will also take care of a negative line number that can2107 * result when match_end and preimage is larger than the target.2108 */2109if((size_t) line > img->nr)2110 line = img->nr;21112112try=0;2113for(i =0; i < line; i++)2114try+= img->line[i].len;21152116/*2117 * There's probably some smart way to do this, but I'll leave2118 * that to the smart and beautiful people. I'm simple and stupid.2119 */2120 backwards =try;2121 backwards_lno = line;2122 forwards =try;2123 forwards_lno = line;2124 try_lno = line;21252126for(i =0; ; i++) {2127if(match_fragment(img, preimage, postimage,2128try, try_lno, ws_rule,2129 match_beginning, match_end))2130return try_lno;21312132 again:2133if(backwards_lno ==0&& forwards_lno == img->nr)2134break;21352136if(i &1) {2137if(backwards_lno ==0) {2138 i++;2139goto again;2140}2141 backwards_lno--;2142 backwards -= img->line[backwards_lno].len;2143try= backwards;2144 try_lno = backwards_lno;2145}else{2146if(forwards_lno == img->nr) {2147 i++;2148goto again;2149}2150 forwards += img->line[forwards_lno].len;2151 forwards_lno++;2152try= forwards;2153 try_lno = forwards_lno;2154}21552156}2157return-1;2158}21592160static voidremove_first_line(struct image *img)2161{2162 img->buf += img->line[0].len;2163 img->len -= img->line[0].len;2164 img->line++;2165 img->nr--;2166}21672168static voidremove_last_line(struct image *img)2169{2170 img->len -= img->line[--img->nr].len;2171}21722173static voidupdate_image(struct image *img,2174int applied_pos,2175struct image *preimage,2176struct image *postimage)2177{2178/*2179 * remove the copy of preimage at offset in img2180 * and replace it with postimage2181 */2182int i, nr;2183size_t remove_count, insert_count, applied_at =0;2184char*result;2185int preimage_limit;21862187/*2188 * If we are removing blank lines at the end of img,2189 * the preimage may extend beyond the end.2190 * If that is the case, we must be careful only to2191 * remove the part of the preimage that falls within2192 * the boundaries of img. Initialize preimage_limit2193 * to the number of lines in the preimage that falls2194 * within the boundaries.2195 */2196 preimage_limit = preimage->nr;2197if(preimage_limit > img->nr - applied_pos)2198 preimage_limit = img->nr - applied_pos;21992200for(i =0; i < applied_pos; i++)2201 applied_at += img->line[i].len;22022203 remove_count =0;2204for(i =0; i < preimage_limit; i++)2205 remove_count += img->line[applied_pos + i].len;2206 insert_count = postimage->len;22072208/* Adjust the contents */2209 result =xmalloc(img->len + insert_count - remove_count +1);2210memcpy(result, img->buf, applied_at);2211memcpy(result + applied_at, postimage->buf, postimage->len);2212memcpy(result + applied_at + postimage->len,2213 img->buf + (applied_at + remove_count),2214 img->len - (applied_at + remove_count));2215free(img->buf);2216 img->buf = result;2217 img->len += insert_count - remove_count;2218 result[img->len] ='\0';22192220/* Adjust the line table */2221 nr = img->nr + postimage->nr - preimage_limit;2222if(preimage_limit < postimage->nr) {2223/*2224 * NOTE: this knows that we never call remove_first_line()2225 * on anything other than pre/post image.2226 */2227 img->line =xrealloc(img->line, nr *sizeof(*img->line));2228 img->line_allocated = img->line;2229}2230if(preimage_limit != postimage->nr)2231memmove(img->line + applied_pos + postimage->nr,2232 img->line + applied_pos + preimage_limit,2233(img->nr - (applied_pos + preimage_limit)) *2234sizeof(*img->line));2235memcpy(img->line + applied_pos,2236 postimage->line,2237 postimage->nr *sizeof(*img->line));2238 img->nr = nr;2239}22402241static intapply_one_fragment(struct image *img,struct fragment *frag,2242int inaccurate_eof,unsigned ws_rule)2243{2244int match_beginning, match_end;2245const char*patch = frag->patch;2246int size = frag->size;2247char*old, *new, *oldlines, *newlines;2248int new_blank_lines_at_end =0;2249unsigned long leading, trailing;2250int pos, applied_pos;2251struct image preimage;2252struct image postimage;22532254memset(&preimage,0,sizeof(preimage));2255memset(&postimage,0,sizeof(postimage));2256 oldlines =xmalloc(size);2257 newlines =xmalloc(size);22582259 old = oldlines;2260new= newlines;2261while(size >0) {2262char first;2263int len =linelen(patch, size);2264int plen, added;2265int added_blank_line =0;2266int is_blank_context =0;22672268if(!len)2269break;22702271/*2272 * "plen" is how much of the line we should use for2273 * the actual patch data. Normally we just remove the2274 * first character on the line, but if the line is2275 * followed by "\ No newline", then we also remove the2276 * last one (which is the newline, of course).2277 */2278 plen = len -1;2279if(len < size && patch[len] =='\\')2280 plen--;2281 first = *patch;2282if(apply_in_reverse) {2283if(first =='-')2284 first ='+';2285else if(first =='+')2286 first ='-';2287}22882289switch(first) {2290case'\n':2291/* Newer GNU diff, empty context line */2292if(plen <0)2293/* ... followed by '\No newline'; nothing */2294break;2295*old++ ='\n';2296*new++ ='\n';2297add_line_info(&preimage,"\n",1, LINE_COMMON);2298add_line_info(&postimage,"\n",1, LINE_COMMON);2299 is_blank_context =1;2300break;2301case' ':2302if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2303ws_blank_line(patch +1, plen, ws_rule))2304 is_blank_context =1;2305case'-':2306memcpy(old, patch +1, plen);2307add_line_info(&preimage, old, plen,2308(first ==' '? LINE_COMMON :0));2309 old += plen;2310if(first =='-')2311break;2312/* Fall-through for ' ' */2313case'+':2314/* --no-add does not add new lines */2315if(first =='+'&& no_add)2316break;23172318if(first !='+'||2319!whitespace_error ||2320 ws_error_action != correct_ws_error) {2321memcpy(new, patch +1, plen);2322 added = plen;2323}2324else{2325 added =ws_fix_copy(new, patch +1, plen, ws_rule, &applied_after_fixing_ws);2326}2327add_line_info(&postimage,new, added,2328(first =='+'?0: LINE_COMMON));2329new+= added;2330if(first =='+'&&2331(ws_rule & WS_BLANK_AT_EOF) &&2332ws_blank_line(patch +1, plen, ws_rule))2333 added_blank_line =1;2334break;2335case'@':case'\\':2336/* Ignore it, we already handled it */2337break;2338default:2339if(apply_verbosely)2340error("invalid start of line: '%c'", first);2341return-1;2342}2343if(added_blank_line)2344 new_blank_lines_at_end++;2345else if(is_blank_context)2346;2347else2348 new_blank_lines_at_end =0;2349 patch += len;2350 size -= len;2351}2352if(inaccurate_eof &&2353 old > oldlines && old[-1] =='\n'&&2354new> newlines &&new[-1] =='\n') {2355 old--;2356new--;2357}23582359 leading = frag->leading;2360 trailing = frag->trailing;23612362/*2363 * A hunk to change lines at the beginning would begin with2364 * @@ -1,L +N,M @@2365 * but we need to be careful. -U0 that inserts before the second2366 * line also has this pattern.2367 *2368 * And a hunk to add to an empty file would begin with2369 * @@ -0,0 +N,M @@2370 *2371 * In other words, a hunk that is (frag->oldpos <= 1) with or2372 * without leading context must match at the beginning.2373 */2374 match_beginning = (!frag->oldpos ||2375(frag->oldpos ==1&& !unidiff_zero));23762377/*2378 * A hunk without trailing lines must match at the end.2379 * However, we simply cannot tell if a hunk must match end2380 * from the lack of trailing lines if the patch was generated2381 * with unidiff without any context.2382 */2383 match_end = !unidiff_zero && !trailing;23842385 pos = frag->newpos ? (frag->newpos -1) :0;2386 preimage.buf = oldlines;2387 preimage.len = old - oldlines;2388 postimage.buf = newlines;2389 postimage.len =new- newlines;2390 preimage.line = preimage.line_allocated;2391 postimage.line = postimage.line_allocated;23922393for(;;) {23942395 applied_pos =find_pos(img, &preimage, &postimage, pos,2396 ws_rule, match_beginning, match_end);23972398if(applied_pos >=0)2399break;24002401/* Am I at my context limits? */2402if((leading <= p_context) && (trailing <= p_context))2403break;2404if(match_beginning || match_end) {2405 match_beginning = match_end =0;2406continue;2407}24082409/*2410 * Reduce the number of context lines; reduce both2411 * leading and trailing if they are equal otherwise2412 * just reduce the larger context.2413 */2414if(leading >= trailing) {2415remove_first_line(&preimage);2416remove_first_line(&postimage);2417 pos--;2418 leading--;2419}2420if(trailing > leading) {2421remove_last_line(&preimage);2422remove_last_line(&postimage);2423 trailing--;2424}2425}24262427if(applied_pos >=0) {2428if(new_blank_lines_at_end &&2429 preimage.nr + applied_pos >= img->nr &&2430(ws_rule & WS_BLANK_AT_EOF) &&2431 ws_error_action != nowarn_ws_error) {2432record_ws_error(WS_BLANK_AT_EOF,"+",1, frag->linenr);2433if(ws_error_action == correct_ws_error) {2434while(new_blank_lines_at_end--)2435remove_last_line(&postimage);2436}2437/*2438 * We would want to prevent write_out_results()2439 * from taking place in apply_patch() that follows2440 * the callchain led us here, which is:2441 * apply_patch->check_patch_list->check_patch->2442 * apply_data->apply_fragments->apply_one_fragment2443 */2444if(ws_error_action == die_on_ws_error)2445 apply =0;2446}24472448/*2449 * Warn if it was necessary to reduce the number2450 * of context lines.2451 */2452if((leading != frag->leading) ||2453(trailing != frag->trailing))2454fprintf(stderr,"Context reduced to (%ld/%ld)"2455" to apply fragment at%d\n",2456 leading, trailing, applied_pos+1);2457update_image(img, applied_pos, &preimage, &postimage);2458}else{2459if(apply_verbosely)2460error("while searching for:\n%.*s",2461(int)(old - oldlines), oldlines);2462}24632464free(oldlines);2465free(newlines);2466free(preimage.line_allocated);2467free(postimage.line_allocated);24682469return(applied_pos <0);2470}24712472static intapply_binary_fragment(struct image *img,struct patch *patch)2473{2474struct fragment *fragment = patch->fragments;2475unsigned long len;2476void*dst;24772478/* Binary patch is irreversible without the optional second hunk */2479if(apply_in_reverse) {2480if(!fragment->next)2481returnerror("cannot reverse-apply a binary patch "2482"without the reverse hunk to '%s'",2483 patch->new_name2484? patch->new_name : patch->old_name);2485 fragment = fragment->next;2486}2487switch(fragment->binary_patch_method) {2488case BINARY_DELTA_DEFLATED:2489 dst =patch_delta(img->buf, img->len, fragment->patch,2490 fragment->size, &len);2491if(!dst)2492return-1;2493clear_image(img);2494 img->buf = dst;2495 img->len = len;2496return0;2497case BINARY_LITERAL_DEFLATED:2498clear_image(img);2499 img->len = fragment->size;2500 img->buf =xmalloc(img->len+1);2501memcpy(img->buf, fragment->patch, img->len);2502 img->buf[img->len] ='\0';2503return0;2504}2505return-1;2506}25072508static intapply_binary(struct image *img,struct patch *patch)2509{2510const char*name = patch->old_name ? patch->old_name : patch->new_name;2511unsigned char sha1[20];25122513/*2514 * For safety, we require patch index line to contain2515 * full 40-byte textual SHA1 for old and new, at least for now.2516 */2517if(strlen(patch->old_sha1_prefix) !=40||2518strlen(patch->new_sha1_prefix) !=40||2519get_sha1_hex(patch->old_sha1_prefix, sha1) ||2520get_sha1_hex(patch->new_sha1_prefix, sha1))2521returnerror("cannot apply binary patch to '%s' "2522"without full index line", name);25232524if(patch->old_name) {2525/*2526 * See if the old one matches what the patch2527 * applies to.2528 */2529hash_sha1_file(img->buf, img->len, blob_type, sha1);2530if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2531returnerror("the patch applies to '%s' (%s), "2532"which does not match the "2533"current contents.",2534 name,sha1_to_hex(sha1));2535}2536else{2537/* Otherwise, the old one must be empty. */2538if(img->len)2539returnerror("the patch applies to an empty "2540"'%s' but it is not empty", name);2541}25422543get_sha1_hex(patch->new_sha1_prefix, sha1);2544if(is_null_sha1(sha1)) {2545clear_image(img);2546return0;/* deletion patch */2547}25482549if(has_sha1_file(sha1)) {2550/* We already have the postimage */2551enum object_type type;2552unsigned long size;2553char*result;25542555 result =read_sha1_file(sha1, &type, &size);2556if(!result)2557returnerror("the necessary postimage%sfor "2558"'%s' cannot be read",2559 patch->new_sha1_prefix, name);2560clear_image(img);2561 img->buf = result;2562 img->len = size;2563}else{2564/*2565 * We have verified buf matches the preimage;2566 * apply the patch data to it, which is stored2567 * in the patch->fragments->{patch,size}.2568 */2569if(apply_binary_fragment(img, patch))2570returnerror("binary patch does not apply to '%s'",2571 name);25722573/* verify that the result matches */2574hash_sha1_file(img->buf, img->len, blob_type, sha1);2575if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2576returnerror("binary patch to '%s' creates incorrect result (expecting%s, got%s)",2577 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2578}25792580return0;2581}25822583static intapply_fragments(struct image *img,struct patch *patch)2584{2585struct fragment *frag = patch->fragments;2586const char*name = patch->old_name ? patch->old_name : patch->new_name;2587unsigned ws_rule = patch->ws_rule;2588unsigned inaccurate_eof = patch->inaccurate_eof;25892590if(patch->is_binary)2591returnapply_binary(img, patch);25922593while(frag) {2594if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule)) {2595error("patch failed:%s:%ld", name, frag->oldpos);2596if(!apply_with_reject)2597return-1;2598 frag->rejected =1;2599}2600 frag = frag->next;2601}2602return0;2603}26042605static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2606{2607if(!ce)2608return0;26092610if(S_ISGITLINK(ce->ce_mode)) {2611strbuf_grow(buf,100);2612strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2613}else{2614enum object_type type;2615unsigned long sz;2616char*result;26172618 result =read_sha1_file(ce->sha1, &type, &sz);2619if(!result)2620return-1;2621/* XXX read_sha1_file NUL-terminates */2622strbuf_attach(buf, result, sz, sz +1);2623}2624return0;2625}26262627static struct patch *in_fn_table(const char*name)2628{2629struct string_list_item *item;26302631if(name == NULL)2632return NULL;26332634 item =string_list_lookup(name, &fn_table);2635if(item != NULL)2636return(struct patch *)item->util;26372638return NULL;2639}26402641/*2642 * item->util in the filename table records the status of the path.2643 * Usually it points at a patch (whose result records the contents2644 * of it after applying it), but it could be PATH_WAS_DELETED for a2645 * path that a previously applied patch has already removed.2646 */2647#define PATH_TO_BE_DELETED ((struct patch *) -2)2648#define PATH_WAS_DELETED ((struct patch *) -1)26492650static intto_be_deleted(struct patch *patch)2651{2652return patch == PATH_TO_BE_DELETED;2653}26542655static intwas_deleted(struct patch *patch)2656{2657return patch == PATH_WAS_DELETED;2658}26592660static voidadd_to_fn_table(struct patch *patch)2661{2662struct string_list_item *item;26632664/*2665 * Always add new_name unless patch is a deletion2666 * This should cover the cases for normal diffs,2667 * file creations and copies2668 */2669if(patch->new_name != NULL) {2670 item =string_list_insert(patch->new_name, &fn_table);2671 item->util = patch;2672}26732674/*2675 * store a failure on rename/deletion cases because2676 * later chunks shouldn't patch old names2677 */2678if((patch->new_name == NULL) || (patch->is_rename)) {2679 item =string_list_insert(patch->old_name, &fn_table);2680 item->util = PATH_WAS_DELETED;2681}2682}26832684static voidprepare_fn_table(struct patch *patch)2685{2686/*2687 * store information about incoming file deletion2688 */2689while(patch) {2690if((patch->new_name == NULL) || (patch->is_rename)) {2691struct string_list_item *item;2692 item =string_list_insert(patch->old_name, &fn_table);2693 item->util = PATH_TO_BE_DELETED;2694}2695 patch = patch->next;2696}2697}26982699static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)2700{2701struct strbuf buf = STRBUF_INIT;2702struct image image;2703size_t len;2704char*img;2705struct patch *tpatch;27062707if(!(patch->is_copy || patch->is_rename) &&2708(tpatch =in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {2709if(was_deleted(tpatch)) {2710returnerror("patch%shas been renamed/deleted",2711 patch->old_name);2712}2713/* We have a patched copy in memory use that */2714strbuf_add(&buf, tpatch->result, tpatch->resultsize);2715}else if(cached) {2716if(read_file_or_gitlink(ce, &buf))2717returnerror("read of%sfailed", patch->old_name);2718}else if(patch->old_name) {2719if(S_ISGITLINK(patch->old_mode)) {2720if(ce) {2721read_file_or_gitlink(ce, &buf);2722}else{2723/*2724 * There is no way to apply subproject2725 * patch without looking at the index.2726 */2727 patch->fragments = NULL;2728}2729}else{2730if(read_old_data(st, patch->old_name, &buf))2731returnerror("read of%sfailed", patch->old_name);2732}2733}27342735 img =strbuf_detach(&buf, &len);2736prepare_image(&image, img, len, !patch->is_binary);27372738if(apply_fragments(&image, patch) <0)2739return-1;/* note with --reject this succeeds. */2740 patch->result = image.buf;2741 patch->resultsize = image.len;2742add_to_fn_table(patch);2743free(image.line_allocated);27442745if(0< patch->is_delete && patch->resultsize)2746returnerror("removal patch leaves file contents");27472748return0;2749}27502751static intcheck_to_create_blob(const char*new_name,int ok_if_exists)2752{2753struct stat nst;2754if(!lstat(new_name, &nst)) {2755if(S_ISDIR(nst.st_mode) || ok_if_exists)2756return0;2757/*2758 * A leading component of new_name might be a symlink2759 * that is going to be removed with this patch, but2760 * still pointing at somewhere that has the path.2761 * In such a case, path "new_name" does not exist as2762 * far as git is concerned.2763 */2764if(has_symlink_leading_path(new_name,strlen(new_name)))2765return0;27662767returnerror("%s: already exists in working directory", new_name);2768}2769else if((errno != ENOENT) && (errno != ENOTDIR))2770returnerror("%s:%s", new_name,strerror(errno));2771return0;2772}27732774static intverify_index_match(struct cache_entry *ce,struct stat *st)2775{2776if(S_ISGITLINK(ce->ce_mode)) {2777if(!S_ISDIR(st->st_mode))2778return-1;2779return0;2780}2781returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);2782}27832784static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)2785{2786const char*old_name = patch->old_name;2787struct patch *tpatch = NULL;2788int stat_ret =0;2789unsigned st_mode =0;27902791/*2792 * Make sure that we do not have local modifications from the2793 * index when we are looking at the index. Also make sure2794 * we have the preimage file to be patched in the work tree,2795 * unless --cached, which tells git to apply only in the index.2796 */2797if(!old_name)2798return0;27992800assert(patch->is_new <=0);28012802if(!(patch->is_copy || patch->is_rename) &&2803(tpatch =in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {2804if(was_deleted(tpatch))2805returnerror("%s: has been deleted/renamed", old_name);2806 st_mode = tpatch->new_mode;2807}else if(!cached) {2808 stat_ret =lstat(old_name, st);2809if(stat_ret && errno != ENOENT)2810returnerror("%s:%s", old_name,strerror(errno));2811}28122813if(to_be_deleted(tpatch))2814 tpatch = NULL;28152816if(check_index && !tpatch) {2817int pos =cache_name_pos(old_name,strlen(old_name));2818if(pos <0) {2819if(patch->is_new <0)2820goto is_new;2821returnerror("%s: does not exist in index", old_name);2822}2823*ce = active_cache[pos];2824if(stat_ret <0) {2825struct checkout costate;2826/* checkout */2827memset(&costate,0,sizeof(costate));2828 costate.base_dir ="";2829 costate.refresh_cache =1;2830if(checkout_entry(*ce, &costate, NULL) ||2831lstat(old_name, st))2832return-1;2833}2834if(!cached &&verify_index_match(*ce, st))2835returnerror("%s: does not match index", old_name);2836if(cached)2837 st_mode = (*ce)->ce_mode;2838}else if(stat_ret <0) {2839if(patch->is_new <0)2840goto is_new;2841returnerror("%s:%s", old_name,strerror(errno));2842}28432844if(!cached && !tpatch)2845 st_mode =ce_mode_from_stat(*ce, st->st_mode);28462847if(patch->is_new <0)2848 patch->is_new =0;2849if(!patch->old_mode)2850 patch->old_mode = st_mode;2851if((st_mode ^ patch->old_mode) & S_IFMT)2852returnerror("%s: wrong type", old_name);2853if(st_mode != patch->old_mode)2854warning("%shas type%o, expected%o",2855 old_name, st_mode, patch->old_mode);2856if(!patch->new_mode && !patch->is_delete)2857 patch->new_mode = st_mode;2858return0;28592860 is_new:2861 patch->is_new =1;2862 patch->is_delete =0;2863 patch->old_name = NULL;2864return0;2865}28662867static intcheck_patch(struct patch *patch)2868{2869struct stat st;2870const char*old_name = patch->old_name;2871const char*new_name = patch->new_name;2872const char*name = old_name ? old_name : new_name;2873struct cache_entry *ce = NULL;2874struct patch *tpatch;2875int ok_if_exists;2876int status;28772878 patch->rejected =1;/* we will drop this after we succeed */28792880 status =check_preimage(patch, &ce, &st);2881if(status)2882return status;2883 old_name = patch->old_name;28842885if((tpatch =in_fn_table(new_name)) &&2886(was_deleted(tpatch) ||to_be_deleted(tpatch)))2887/*2888 * A type-change diff is always split into a patch to2889 * delete old, immediately followed by a patch to2890 * create new (see diff.c::run_diff()); in such a case2891 * it is Ok that the entry to be deleted by the2892 * previous patch is still in the working tree and in2893 * the index.2894 */2895 ok_if_exists =1;2896else2897 ok_if_exists =0;28982899if(new_name &&2900((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {2901if(check_index &&2902cache_name_pos(new_name,strlen(new_name)) >=0&&2903!ok_if_exists)2904returnerror("%s: already exists in index", new_name);2905if(!cached) {2906int err =check_to_create_blob(new_name, ok_if_exists);2907if(err)2908return err;2909}2910if(!patch->new_mode) {2911if(0< patch->is_new)2912 patch->new_mode = S_IFREG |0644;2913else2914 patch->new_mode = patch->old_mode;2915}2916}29172918if(new_name && old_name) {2919int same = !strcmp(old_name, new_name);2920if(!patch->new_mode)2921 patch->new_mode = patch->old_mode;2922if((patch->old_mode ^ patch->new_mode) & S_IFMT)2923returnerror("new mode (%o) of%sdoes not match old mode (%o)%s%s",2924 patch->new_mode, new_name, patch->old_mode,2925 same ?"":" of ", same ?"": old_name);2926}29272928if(apply_data(patch, &st, ce) <0)2929returnerror("%s: patch does not apply", name);2930 patch->rejected =0;2931return0;2932}29332934static intcheck_patch_list(struct patch *patch)2935{2936int err =0;29372938prepare_fn_table(patch);2939while(patch) {2940if(apply_verbosely)2941say_patch_name(stderr,2942"Checking patch ", patch,"...\n");2943 err |=check_patch(patch);2944 patch = patch->next;2945}2946return err;2947}29482949/* This function tries to read the sha1 from the current index */2950static intget_current_sha1(const char*path,unsigned char*sha1)2951{2952int pos;29532954if(read_cache() <0)2955return-1;2956 pos =cache_name_pos(path,strlen(path));2957if(pos <0)2958return-1;2959hashcpy(sha1, active_cache[pos]->sha1);2960return0;2961}29622963/* Build an index that contains the just the files needed for a 3way merge */2964static voidbuild_fake_ancestor(struct patch *list,const char*filename)2965{2966struct patch *patch;2967struct index_state result = { NULL };2968int fd;29692970/* Once we start supporting the reverse patch, it may be2971 * worth showing the new sha1 prefix, but until then...2972 */2973for(patch = list; patch; patch = patch->next) {2974const unsigned char*sha1_ptr;2975unsigned char sha1[20];2976struct cache_entry *ce;2977const char*name;29782979 name = patch->old_name ? patch->old_name : patch->new_name;2980if(0< patch->is_new)2981continue;2982else if(get_sha1(patch->old_sha1_prefix, sha1))2983/* git diff has no index line for mode/type changes */2984if(!patch->lines_added && !patch->lines_deleted) {2985if(get_current_sha1(patch->new_name, sha1) ||2986get_current_sha1(patch->old_name, sha1))2987die("mode change for%s, which is not "2988"in current HEAD", name);2989 sha1_ptr = sha1;2990}else2991die("sha1 information is lacking or useless "2992"(%s).", name);2993else2994 sha1_ptr = sha1;29952996 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);2997if(!ce)2998die("make_cache_entry failed for path '%s'", name);2999if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3000die("Could not add%sto temporary index", name);3001}30023003 fd =open(filename, O_WRONLY | O_CREAT,0666);3004if(fd <0||write_index(&result, fd) ||close(fd))3005die("Could not write temporary index to%s", filename);30063007discard_index(&result);3008}30093010static voidstat_patch_list(struct patch *patch)3011{3012int files, adds, dels;30133014for(files = adds = dels =0; patch ; patch = patch->next) {3015 files++;3016 adds += patch->lines_added;3017 dels += patch->lines_deleted;3018show_stats(patch);3019}30203021printf("%dfiles changed,%dinsertions(+),%ddeletions(-)\n", files, adds, dels);3022}30233024static voidnumstat_patch_list(struct patch *patch)3025{3026for( ; patch; patch = patch->next) {3027const char*name;3028 name = patch->new_name ? patch->new_name : patch->old_name;3029if(patch->is_binary)3030printf("-\t-\t");3031else3032printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3033write_name_quoted(name, stdout, line_termination);3034}3035}30363037static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3038{3039if(mode)3040printf("%smode%06o%s\n", newdelete, mode, name);3041else3042printf("%s %s\n", newdelete, name);3043}30443045static voidshow_mode_change(struct patch *p,int show_name)3046{3047if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3048if(show_name)3049printf(" mode change%06o =>%06o%s\n",3050 p->old_mode, p->new_mode, p->new_name);3051else3052printf(" mode change%06o =>%06o\n",3053 p->old_mode, p->new_mode);3054}3055}30563057static voidshow_rename_copy(struct patch *p)3058{3059const char*renamecopy = p->is_rename ?"rename":"copy";3060const char*old, *new;30613062/* Find common prefix */3063 old = p->old_name;3064new= p->new_name;3065while(1) {3066const char*slash_old, *slash_new;3067 slash_old =strchr(old,'/');3068 slash_new =strchr(new,'/');3069if(!slash_old ||3070!slash_new ||3071 slash_old - old != slash_new -new||3072memcmp(old,new, slash_new -new))3073break;3074 old = slash_old +1;3075new= slash_new +1;3076}3077/* p->old_name thru old is the common prefix, and old and new3078 * through the end of names are renames3079 */3080if(old != p->old_name)3081printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,3082(int)(old - p->old_name), p->old_name,3083 old,new, p->score);3084else3085printf("%s %s=>%s(%d%%)\n", renamecopy,3086 p->old_name, p->new_name, p->score);3087show_mode_change(p,0);3088}30893090static voidsummary_patch_list(struct patch *patch)3091{3092struct patch *p;30933094for(p = patch; p; p = p->next) {3095if(p->is_new)3096show_file_mode_name("create", p->new_mode, p->new_name);3097else if(p->is_delete)3098show_file_mode_name("delete", p->old_mode, p->old_name);3099else{3100if(p->is_rename || p->is_copy)3101show_rename_copy(p);3102else{3103if(p->score) {3104printf(" rewrite%s(%d%%)\n",3105 p->new_name, p->score);3106show_mode_change(p,0);3107}3108else3109show_mode_change(p,1);3110}3111}3112}3113}31143115static voidpatch_stats(struct patch *patch)3116{3117int lines = patch->lines_added + patch->lines_deleted;31183119if(lines > max_change)3120 max_change = lines;3121if(patch->old_name) {3122int len =quote_c_style(patch->old_name, NULL, NULL,0);3123if(!len)3124 len =strlen(patch->old_name);3125if(len > max_len)3126 max_len = len;3127}3128if(patch->new_name) {3129int len =quote_c_style(patch->new_name, NULL, NULL,0);3130if(!len)3131 len =strlen(patch->new_name);3132if(len > max_len)3133 max_len = len;3134}3135}31363137static voidremove_file(struct patch *patch,int rmdir_empty)3138{3139if(update_index) {3140if(remove_file_from_cache(patch->old_name) <0)3141die("unable to remove%sfrom index", patch->old_name);3142}3143if(!cached) {3144if(S_ISGITLINK(patch->old_mode)) {3145if(rmdir(patch->old_name))3146warning("unable to remove submodule%s",3147 patch->old_name);3148}else if(!unlink_or_warn(patch->old_name) && rmdir_empty) {3149remove_path(patch->old_name);3150}3151}3152}31533154static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)3155{3156struct stat st;3157struct cache_entry *ce;3158int namelen =strlen(path);3159unsigned ce_size =cache_entry_size(namelen);31603161if(!update_index)3162return;31633164 ce =xcalloc(1, ce_size);3165memcpy(ce->name, path, namelen);3166 ce->ce_mode =create_ce_mode(mode);3167 ce->ce_flags = namelen;3168if(S_ISGITLINK(mode)) {3169const char*s = buf;31703171if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))3172die("corrupt patch for subproject%s", path);3173}else{3174if(!cached) {3175if(lstat(path, &st) <0)3176die_errno("unable to stat newly created file '%s'",3177 path);3178fill_stat_cache_info(ce, &st);3179}3180if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)3181die("unable to create backing store for newly created file%s", path);3182}3183if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3184die("unable to add cache entry for%s", path);3185}31863187static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)3188{3189int fd;3190struct strbuf nbuf = STRBUF_INIT;31913192if(S_ISGITLINK(mode)) {3193struct stat st;3194if(!lstat(path, &st) &&S_ISDIR(st.st_mode))3195return0;3196returnmkdir(path,0777);3197}31983199if(has_symlinks &&S_ISLNK(mode))3200/* Although buf:size is counted string, it also is NUL3201 * terminated.3202 */3203returnsymlink(buf, path);32043205 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);3206if(fd <0)3207return-1;32083209if(convert_to_working_tree(path, buf, size, &nbuf)) {3210 size = nbuf.len;3211 buf = nbuf.buf;3212}3213write_or_die(fd, buf, size);3214strbuf_release(&nbuf);32153216if(close(fd) <0)3217die_errno("closing file '%s'", path);3218return0;3219}32203221/*3222 * We optimistically assume that the directories exist,3223 * which is true 99% of the time anyway. If they don't,3224 * we create them and try again.3225 */3226static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)3227{3228if(cached)3229return;3230if(!try_create_file(path, mode, buf, size))3231return;32323233if(errno == ENOENT) {3234if(safe_create_leading_directories(path))3235return;3236if(!try_create_file(path, mode, buf, size))3237return;3238}32393240if(errno == EEXIST || errno == EACCES) {3241/* We may be trying to create a file where a directory3242 * used to be.3243 */3244struct stat st;3245if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))3246 errno = EEXIST;3247}32483249if(errno == EEXIST) {3250unsigned int nr =getpid();32513252for(;;) {3253char newpath[PATH_MAX];3254mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);3255if(!try_create_file(newpath, mode, buf, size)) {3256if(!rename(newpath, path))3257return;3258unlink_or_warn(newpath);3259break;3260}3261if(errno != EEXIST)3262break;3263++nr;3264}3265}3266die_errno("unable to write file '%s' mode%o", path, mode);3267}32683269static voidcreate_file(struct patch *patch)3270{3271char*path = patch->new_name;3272unsigned mode = patch->new_mode;3273unsigned long size = patch->resultsize;3274char*buf = patch->result;32753276if(!mode)3277 mode = S_IFREG |0644;3278create_one_file(path, mode, buf, size);3279add_index_file(path, mode, buf, size);3280}32813282/* phase zero is to remove, phase one is to create */3283static voidwrite_out_one_result(struct patch *patch,int phase)3284{3285if(patch->is_delete >0) {3286if(phase ==0)3287remove_file(patch,1);3288return;3289}3290if(patch->is_new >0|| patch->is_copy) {3291if(phase ==1)3292create_file(patch);3293return;3294}3295/*3296 * Rename or modification boils down to the same3297 * thing: remove the old, write the new3298 */3299if(phase ==0)3300remove_file(patch, patch->is_rename);3301if(phase ==1)3302create_file(patch);3303}33043305static intwrite_out_one_reject(struct patch *patch)3306{3307FILE*rej;3308char namebuf[PATH_MAX];3309struct fragment *frag;3310int cnt =0;33113312for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {3313if(!frag->rejected)3314continue;3315 cnt++;3316}33173318if(!cnt) {3319if(apply_verbosely)3320say_patch_name(stderr,3321"Applied patch ", patch," cleanly.\n");3322return0;3323}33243325/* This should not happen, because a removal patch that leaves3326 * contents are marked "rejected" at the patch level.3327 */3328if(!patch->new_name)3329die("internal error");33303331/* Say this even without --verbose */3332say_patch_name(stderr,"Applying patch ", patch," with");3333fprintf(stderr,"%drejects...\n", cnt);33343335 cnt =strlen(patch->new_name);3336if(ARRAY_SIZE(namebuf) <= cnt +5) {3337 cnt =ARRAY_SIZE(namebuf) -5;3338warning("truncating .rej filename to %.*s.rej",3339 cnt -1, patch->new_name);3340}3341memcpy(namebuf, patch->new_name, cnt);3342memcpy(namebuf + cnt,".rej",5);33433344 rej =fopen(namebuf,"w");3345if(!rej)3346returnerror("cannot open%s:%s", namebuf,strerror(errno));33473348/* Normal git tools never deal with .rej, so do not pretend3349 * this is a git patch by saying --git nor give extended3350 * headers. While at it, maybe please "kompare" that wants3351 * the trailing TAB and some garbage at the end of line ;-).3352 */3353fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",3354 patch->new_name, patch->new_name);3355for(cnt =1, frag = patch->fragments;3356 frag;3357 cnt++, frag = frag->next) {3358if(!frag->rejected) {3359fprintf(stderr,"Hunk #%dapplied cleanly.\n", cnt);3360continue;3361}3362fprintf(stderr,"Rejected hunk #%d.\n", cnt);3363fprintf(rej,"%.*s", frag->size, frag->patch);3364if(frag->patch[frag->size-1] !='\n')3365fputc('\n', rej);3366}3367fclose(rej);3368return-1;3369}33703371static intwrite_out_results(struct patch *list,int skipped_patch)3372{3373int phase;3374int errs =0;3375struct patch *l;33763377if(!list && !skipped_patch)3378returnerror("No changes");33793380for(phase =0; phase <2; phase++) {3381 l = list;3382while(l) {3383if(l->rejected)3384 errs =1;3385else{3386write_out_one_result(l, phase);3387if(phase ==1&&write_out_one_reject(l))3388 errs =1;3389}3390 l = l->next;3391}3392}3393return errs;3394}33953396static struct lock_file lock_file;33973398static struct string_list limit_by_name;3399static int has_include;3400static voidadd_name_limit(const char*name,int exclude)3401{3402struct string_list_item *it;34033404 it =string_list_append(name, &limit_by_name);3405 it->util = exclude ? NULL : (void*)1;3406}34073408static intuse_patch(struct patch *p)3409{3410const char*pathname = p->new_name ? p->new_name : p->old_name;3411int i;34123413/* Paths outside are not touched regardless of "--include" */3414if(0< prefix_length) {3415int pathlen =strlen(pathname);3416if(pathlen <= prefix_length ||3417memcmp(prefix, pathname, prefix_length))3418return0;3419}34203421/* See if it matches any of exclude/include rule */3422for(i =0; i < limit_by_name.nr; i++) {3423struct string_list_item *it = &limit_by_name.items[i];3424if(!fnmatch(it->string, pathname,0))3425return(it->util != NULL);3426}34273428/*3429 * If we had any include, a path that does not match any rule is3430 * not used. Otherwise, we saw bunch of exclude rules (or none)3431 * and such a path is used.3432 */3433return!has_include;3434}343534363437static voidprefix_one(char**name)3438{3439char*old_name = *name;3440if(!old_name)3441return;3442*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3443free(old_name);3444}34453446static voidprefix_patches(struct patch *p)3447{3448if(!prefix || p->is_toplevel_relative)3449return;3450for( ; p; p = p->next) {3451if(p->new_name == p->old_name) {3452char*prefixed = p->new_name;3453prefix_one(&prefixed);3454 p->new_name = p->old_name = prefixed;3455}3456else{3457prefix_one(&p->new_name);3458prefix_one(&p->old_name);3459}3460}3461}34623463#define INACCURATE_EOF (1<<0)3464#define RECOUNT (1<<1)34653466static intapply_patch(int fd,const char*filename,int options)3467{3468size_t offset;3469struct strbuf buf = STRBUF_INIT;3470struct patch *list = NULL, **listp = &list;3471int skipped_patch =0;34723473/* FIXME - memory leak when using multiple patch files as inputs */3474memset(&fn_table,0,sizeof(struct string_list));3475 patch_input_file = filename;3476read_patch_file(&buf, fd);3477 offset =0;3478while(offset < buf.len) {3479struct patch *patch;3480int nr;34813482 patch =xcalloc(1,sizeof(*patch));3483 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3484 patch->recount = !!(options & RECOUNT);3485 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3486if(nr <0)3487break;3488if(apply_in_reverse)3489reverse_patches(patch);3490if(prefix)3491prefix_patches(patch);3492if(use_patch(patch)) {3493patch_stats(patch);3494*listp = patch;3495 listp = &patch->next;3496}3497else{3498/* perhaps free it a bit better? */3499free(patch);3500 skipped_patch++;3501}3502 offset += nr;3503}35043505if(whitespace_error && (ws_error_action == die_on_ws_error))3506 apply =0;35073508 update_index = check_index && apply;3509if(update_index && newfd <0)3510 newfd =hold_locked_index(&lock_file,1);35113512if(check_index) {3513if(read_cache() <0)3514die("unable to read index file");3515}35163517if((check || apply) &&3518check_patch_list(list) <0&&3519!apply_with_reject)3520exit(1);35213522if(apply &&write_out_results(list, skipped_patch))3523exit(1);35243525if(fake_ancestor)3526build_fake_ancestor(list, fake_ancestor);35273528if(diffstat)3529stat_patch_list(list);35303531if(numstat)3532numstat_patch_list(list);35333534if(summary)3535summary_patch_list(list);35363537strbuf_release(&buf);3538return0;3539}35403541static intgit_apply_config(const char*var,const char*value,void*cb)3542{3543if(!strcmp(var,"apply.whitespace"))3544returngit_config_string(&apply_default_whitespace, var, value);3545else if(!strcmp(var,"apply.ignorewhitespace"))3546returngit_config_string(&apply_default_ignorewhitespace, var, value);3547returngit_default_config(var, value, cb);3548}35493550static intoption_parse_exclude(const struct option *opt,3551const char*arg,int unset)3552{3553add_name_limit(arg,1);3554return0;3555}35563557static intoption_parse_include(const struct option *opt,3558const char*arg,int unset)3559{3560add_name_limit(arg,0);3561 has_include =1;3562return0;3563}35643565static intoption_parse_p(const struct option *opt,3566const char*arg,int unset)3567{3568 p_value =atoi(arg);3569 p_value_known =1;3570return0;3571}35723573static intoption_parse_z(const struct option *opt,3574const char*arg,int unset)3575{3576if(unset)3577 line_termination ='\n';3578else3579 line_termination =0;3580return0;3581}35823583static intoption_parse_space_change(const struct option *opt,3584const char*arg,int unset)3585{3586if(unset)3587 ws_ignore_action = ignore_ws_none;3588else3589 ws_ignore_action = ignore_ws_change;3590return0;3591}35923593static intoption_parse_whitespace(const struct option *opt,3594const char*arg,int unset)3595{3596const char**whitespace_option = opt->value;35973598*whitespace_option = arg;3599parse_whitespace_option(arg);3600return0;3601}36023603static intoption_parse_directory(const struct option *opt,3604const char*arg,int unset)3605{3606 root_len =strlen(arg);3607if(root_len && arg[root_len -1] !='/') {3608char*new_root;3609 root = new_root =xmalloc(root_len +2);3610strcpy(new_root, arg);3611strcpy(new_root + root_len++,"/");3612}else3613 root = arg;3614return0;3615}36163617intcmd_apply(int argc,const char**argv,const char*unused_prefix)3618{3619int i;3620int errs =0;3621int is_not_gitdir;3622int binary;3623int force_apply =0;36243625const char*whitespace_option = NULL;36263627struct option builtin_apply_options[] = {3628{ OPTION_CALLBACK,0,"exclude", NULL,"path",3629"don't apply changes matching the given path",36300, option_parse_exclude },3631{ OPTION_CALLBACK,0,"include", NULL,"path",3632"apply changes matching the given path",36330, option_parse_include },3634{ OPTION_CALLBACK,'p', NULL, NULL,"num",3635"remove <num> leading slashes from traditional diff paths",36360, option_parse_p },3637OPT_BOOLEAN(0,"no-add", &no_add,3638"ignore additions made by the patch"),3639OPT_BOOLEAN(0,"stat", &diffstat,3640"instead of applying the patch, output diffstat for the input"),3641{ OPTION_BOOLEAN,0,"allow-binary-replacement", &binary,3642 NULL,"old option, now no-op",3643 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3644{ OPTION_BOOLEAN,0,"binary", &binary,3645 NULL,"old option, now no-op",3646 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3647OPT_BOOLEAN(0,"numstat", &numstat,3648"shows number of added and deleted lines in decimal notation"),3649OPT_BOOLEAN(0,"summary", &summary,3650"instead of applying the patch, output a summary for the input"),3651OPT_BOOLEAN(0,"check", &check,3652"instead of applying the patch, see if the patch is applicable"),3653OPT_BOOLEAN(0,"index", &check_index,3654"make sure the patch is applicable to the current index"),3655OPT_BOOLEAN(0,"cached", &cached,3656"apply a patch without touching the working tree"),3657OPT_BOOLEAN(0,"apply", &force_apply,3658"also apply the patch (use with --stat/--summary/--check)"),3659OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,3660"build a temporary index based on embedded index information"),3661{ OPTION_CALLBACK,'z', NULL, NULL, NULL,3662"paths are separated with NUL character",3663 PARSE_OPT_NOARG, option_parse_z },3664OPT_INTEGER('C', NULL, &p_context,3665"ensure at least <n> lines of context match"),3666{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,"action",3667"detect new or modified lines that have whitespace errors",36680, option_parse_whitespace },3669{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,3670"ignore changes in whitespace when finding context",3671 PARSE_OPT_NOARG, option_parse_space_change },3672{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,3673"ignore changes in whitespace when finding context",3674 PARSE_OPT_NOARG, option_parse_space_change },3675OPT_BOOLEAN('R',"reverse", &apply_in_reverse,3676"apply the patch in reverse"),3677OPT_BOOLEAN(0,"unidiff-zero", &unidiff_zero,3678"don't expect at least one line of context"),3679OPT_BOOLEAN(0,"reject", &apply_with_reject,3680"leave the rejected hunks in corresponding *.rej files"),3681OPT__VERBOSE(&apply_verbosely),3682OPT_BIT(0,"inaccurate-eof", &options,3683"tolerate incorrectly detected missing new-line at the end of file",3684 INACCURATE_EOF),3685OPT_BIT(0,"recount", &options,3686"do not trust the line counts in the hunk headers",3687 RECOUNT),3688{ OPTION_CALLBACK,0,"directory", NULL,"root",3689"prepend <root> to all filenames",36900, option_parse_directory },3691OPT_END()3692};36933694 prefix =setup_git_directory_gently(&is_not_gitdir);3695 prefix_length = prefix ?strlen(prefix) :0;3696git_config(git_apply_config, NULL);3697if(apply_default_whitespace)3698parse_whitespace_option(apply_default_whitespace);3699if(apply_default_ignorewhitespace)3700parse_ignorewhitespace_option(apply_default_ignorewhitespace);37013702 argc =parse_options(argc, argv, prefix, builtin_apply_options,3703 apply_usage,0);37043705if(apply_with_reject)3706 apply = apply_verbosely =1;3707if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))3708 apply =0;3709if(check_index && is_not_gitdir)3710die("--index outside a repository");3711if(cached) {3712if(is_not_gitdir)3713die("--cached outside a repository");3714 check_index =1;3715}3716for(i =0; i < argc; i++) {3717const char*arg = argv[i];3718int fd;37193720if(!strcmp(arg,"-")) {3721 errs |=apply_patch(0,"<stdin>", options);3722 read_stdin =0;3723continue;3724}else if(0< prefix_length)3725 arg =prefix_filename(prefix, prefix_length, arg);37263727 fd =open(arg, O_RDONLY);3728if(fd <0)3729die_errno("can't open patch '%s'", arg);3730 read_stdin =0;3731set_default_whitespace_mode(whitespace_option);3732 errs |=apply_patch(fd, arg, options);3733close(fd);3734}3735set_default_whitespace_mode(whitespace_option);3736if(read_stdin)3737 errs |=apply_patch(0,"<stdin>", options);3738if(whitespace_error) {3739if(squelch_whitespace_errors &&3740 squelch_whitespace_errors < whitespace_error) {3741int squelched =3742 whitespace_error - squelch_whitespace_errors;3743warning("squelched%d"3744"whitespace error%s",3745 squelched,3746 squelched ==1?"":"s");3747}3748if(ws_error_action == die_on_ws_error)3749die("%dline%sadd%swhitespace errors.",3750 whitespace_error,3751 whitespace_error ==1?"":"s",3752 whitespace_error ==1?"s":"");3753if(applied_after_fixing_ws && apply)3754warning("%dline%sapplied after"3755" fixing whitespace errors.",3756 applied_after_fixing_ws,3757 applied_after_fixing_ws ==1?"":"s");3758else if(whitespace_error)3759warning("%dline%sadd%swhitespace errors.",3760 whitespace_error,3761 whitespace_error ==1?"":"s",3762 whitespace_error ==1?"s":"");3763}37643765if(update_index) {3766if(write_cache(newfd, active_cache, active_nr) ||3767commit_locked_index(&lock_file))3768die("Unable to write new index file");3769}37703771return!!errs;3772}