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(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {3145remove_path(patch->old_name);3146}3147}3148}31493150static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)3151{3152struct stat st;3153struct cache_entry *ce;3154int namelen =strlen(path);3155unsigned ce_size =cache_entry_size(namelen);31563157if(!update_index)3158return;31593160 ce =xcalloc(1, ce_size);3161memcpy(ce->name, path, namelen);3162 ce->ce_mode =create_ce_mode(mode);3163 ce->ce_flags = namelen;3164if(S_ISGITLINK(mode)) {3165const char*s = buf;31663167if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))3168die("corrupt patch for subproject%s", path);3169}else{3170if(!cached) {3171if(lstat(path, &st) <0)3172die_errno("unable to stat newly created file '%s'",3173 path);3174fill_stat_cache_info(ce, &st);3175}3176if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)3177die("unable to create backing store for newly created file%s", path);3178}3179if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3180die("unable to add cache entry for%s", path);3181}31823183static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)3184{3185int fd;3186struct strbuf nbuf = STRBUF_INIT;31873188if(S_ISGITLINK(mode)) {3189struct stat st;3190if(!lstat(path, &st) &&S_ISDIR(st.st_mode))3191return0;3192returnmkdir(path,0777);3193}31943195if(has_symlinks &&S_ISLNK(mode))3196/* Although buf:size is counted string, it also is NUL3197 * terminated.3198 */3199returnsymlink(buf, path);32003201 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);3202if(fd <0)3203return-1;32043205if(convert_to_working_tree(path, buf, size, &nbuf)) {3206 size = nbuf.len;3207 buf = nbuf.buf;3208}3209write_or_die(fd, buf, size);3210strbuf_release(&nbuf);32113212if(close(fd) <0)3213die_errno("closing file '%s'", path);3214return0;3215}32163217/*3218 * We optimistically assume that the directories exist,3219 * which is true 99% of the time anyway. If they don't,3220 * we create them and try again.3221 */3222static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)3223{3224if(cached)3225return;3226if(!try_create_file(path, mode, buf, size))3227return;32283229if(errno == ENOENT) {3230if(safe_create_leading_directories(path))3231return;3232if(!try_create_file(path, mode, buf, size))3233return;3234}32353236if(errno == EEXIST || errno == EACCES) {3237/* We may be trying to create a file where a directory3238 * used to be.3239 */3240struct stat st;3241if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))3242 errno = EEXIST;3243}32443245if(errno == EEXIST) {3246unsigned int nr =getpid();32473248for(;;) {3249char newpath[PATH_MAX];3250mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);3251if(!try_create_file(newpath, mode, buf, size)) {3252if(!rename(newpath, path))3253return;3254unlink_or_warn(newpath);3255break;3256}3257if(errno != EEXIST)3258break;3259++nr;3260}3261}3262die_errno("unable to write file '%s' mode%o", path, mode);3263}32643265static voidcreate_file(struct patch *patch)3266{3267char*path = patch->new_name;3268unsigned mode = patch->new_mode;3269unsigned long size = patch->resultsize;3270char*buf = patch->result;32713272if(!mode)3273 mode = S_IFREG |0644;3274create_one_file(path, mode, buf, size);3275add_index_file(path, mode, buf, size);3276}32773278/* phase zero is to remove, phase one is to create */3279static voidwrite_out_one_result(struct patch *patch,int phase)3280{3281if(patch->is_delete >0) {3282if(phase ==0)3283remove_file(patch,1);3284return;3285}3286if(patch->is_new >0|| patch->is_copy) {3287if(phase ==1)3288create_file(patch);3289return;3290}3291/*3292 * Rename or modification boils down to the same3293 * thing: remove the old, write the new3294 */3295if(phase ==0)3296remove_file(patch, patch->is_rename);3297if(phase ==1)3298create_file(patch);3299}33003301static intwrite_out_one_reject(struct patch *patch)3302{3303FILE*rej;3304char namebuf[PATH_MAX];3305struct fragment *frag;3306int cnt =0;33073308for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {3309if(!frag->rejected)3310continue;3311 cnt++;3312}33133314if(!cnt) {3315if(apply_verbosely)3316say_patch_name(stderr,3317"Applied patch ", patch," cleanly.\n");3318return0;3319}33203321/* This should not happen, because a removal patch that leaves3322 * contents are marked "rejected" at the patch level.3323 */3324if(!patch->new_name)3325die("internal error");33263327/* Say this even without --verbose */3328say_patch_name(stderr,"Applying patch ", patch," with");3329fprintf(stderr,"%drejects...\n", cnt);33303331 cnt =strlen(patch->new_name);3332if(ARRAY_SIZE(namebuf) <= cnt +5) {3333 cnt =ARRAY_SIZE(namebuf) -5;3334warning("truncating .rej filename to %.*s.rej",3335 cnt -1, patch->new_name);3336}3337memcpy(namebuf, patch->new_name, cnt);3338memcpy(namebuf + cnt,".rej",5);33393340 rej =fopen(namebuf,"w");3341if(!rej)3342returnerror("cannot open%s:%s", namebuf,strerror(errno));33433344/* Normal git tools never deal with .rej, so do not pretend3345 * this is a git patch by saying --git nor give extended3346 * headers. While at it, maybe please "kompare" that wants3347 * the trailing TAB and some garbage at the end of line ;-).3348 */3349fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",3350 patch->new_name, patch->new_name);3351for(cnt =1, frag = patch->fragments;3352 frag;3353 cnt++, frag = frag->next) {3354if(!frag->rejected) {3355fprintf(stderr,"Hunk #%dapplied cleanly.\n", cnt);3356continue;3357}3358fprintf(stderr,"Rejected hunk #%d.\n", cnt);3359fprintf(rej,"%.*s", frag->size, frag->patch);3360if(frag->patch[frag->size-1] !='\n')3361fputc('\n', rej);3362}3363fclose(rej);3364return-1;3365}33663367static intwrite_out_results(struct patch *list,int skipped_patch)3368{3369int phase;3370int errs =0;3371struct patch *l;33723373if(!list && !skipped_patch)3374returnerror("No changes");33753376for(phase =0; phase <2; phase++) {3377 l = list;3378while(l) {3379if(l->rejected)3380 errs =1;3381else{3382write_out_one_result(l, phase);3383if(phase ==1&&write_out_one_reject(l))3384 errs =1;3385}3386 l = l->next;3387}3388}3389return errs;3390}33913392static struct lock_file lock_file;33933394static struct string_list limit_by_name;3395static int has_include;3396static voidadd_name_limit(const char*name,int exclude)3397{3398struct string_list_item *it;33993400 it =string_list_append(name, &limit_by_name);3401 it->util = exclude ? NULL : (void*)1;3402}34033404static intuse_patch(struct patch *p)3405{3406const char*pathname = p->new_name ? p->new_name : p->old_name;3407int i;34083409/* Paths outside are not touched regardless of "--include" */3410if(0< prefix_length) {3411int pathlen =strlen(pathname);3412if(pathlen <= prefix_length ||3413memcmp(prefix, pathname, prefix_length))3414return0;3415}34163417/* See if it matches any of exclude/include rule */3418for(i =0; i < limit_by_name.nr; i++) {3419struct string_list_item *it = &limit_by_name.items[i];3420if(!fnmatch(it->string, pathname,0))3421return(it->util != NULL);3422}34233424/*3425 * If we had any include, a path that does not match any rule is3426 * not used. Otherwise, we saw bunch of exclude rules (or none)3427 * and such a path is used.3428 */3429return!has_include;3430}343134323433static voidprefix_one(char**name)3434{3435char*old_name = *name;3436if(!old_name)3437return;3438*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3439free(old_name);3440}34413442static voidprefix_patches(struct patch *p)3443{3444if(!prefix || p->is_toplevel_relative)3445return;3446for( ; p; p = p->next) {3447if(p->new_name == p->old_name) {3448char*prefixed = p->new_name;3449prefix_one(&prefixed);3450 p->new_name = p->old_name = prefixed;3451}3452else{3453prefix_one(&p->new_name);3454prefix_one(&p->old_name);3455}3456}3457}34583459#define INACCURATE_EOF (1<<0)3460#define RECOUNT (1<<1)34613462static intapply_patch(int fd,const char*filename,int options)3463{3464size_t offset;3465struct strbuf buf = STRBUF_INIT;3466struct patch *list = NULL, **listp = &list;3467int skipped_patch =0;34683469/* FIXME - memory leak when using multiple patch files as inputs */3470memset(&fn_table,0,sizeof(struct string_list));3471 patch_input_file = filename;3472read_patch_file(&buf, fd);3473 offset =0;3474while(offset < buf.len) {3475struct patch *patch;3476int nr;34773478 patch =xcalloc(1,sizeof(*patch));3479 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3480 patch->recount = !!(options & RECOUNT);3481 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3482if(nr <0)3483break;3484if(apply_in_reverse)3485reverse_patches(patch);3486if(prefix)3487prefix_patches(patch);3488if(use_patch(patch)) {3489patch_stats(patch);3490*listp = patch;3491 listp = &patch->next;3492}3493else{3494/* perhaps free it a bit better? */3495free(patch);3496 skipped_patch++;3497}3498 offset += nr;3499}35003501if(whitespace_error && (ws_error_action == die_on_ws_error))3502 apply =0;35033504 update_index = check_index && apply;3505if(update_index && newfd <0)3506 newfd =hold_locked_index(&lock_file,1);35073508if(check_index) {3509if(read_cache() <0)3510die("unable to read index file");3511}35123513if((check || apply) &&3514check_patch_list(list) <0&&3515!apply_with_reject)3516exit(1);35173518if(apply &&write_out_results(list, skipped_patch))3519exit(1);35203521if(fake_ancestor)3522build_fake_ancestor(list, fake_ancestor);35233524if(diffstat)3525stat_patch_list(list);35263527if(numstat)3528numstat_patch_list(list);35293530if(summary)3531summary_patch_list(list);35323533strbuf_release(&buf);3534return0;3535}35363537static intgit_apply_config(const char*var,const char*value,void*cb)3538{3539if(!strcmp(var,"apply.whitespace"))3540returngit_config_string(&apply_default_whitespace, var, value);3541else if(!strcmp(var,"apply.ignorewhitespace"))3542returngit_config_string(&apply_default_ignorewhitespace, var, value);3543returngit_default_config(var, value, cb);3544}35453546static intoption_parse_exclude(const struct option *opt,3547const char*arg,int unset)3548{3549add_name_limit(arg,1);3550return0;3551}35523553static intoption_parse_include(const struct option *opt,3554const char*arg,int unset)3555{3556add_name_limit(arg,0);3557 has_include =1;3558return0;3559}35603561static intoption_parse_p(const struct option *opt,3562const char*arg,int unset)3563{3564 p_value =atoi(arg);3565 p_value_known =1;3566return0;3567}35683569static intoption_parse_z(const struct option *opt,3570const char*arg,int unset)3571{3572if(unset)3573 line_termination ='\n';3574else3575 line_termination =0;3576return0;3577}35783579static intoption_parse_space_change(const struct option *opt,3580const char*arg,int unset)3581{3582if(unset)3583 ws_ignore_action = ignore_ws_none;3584else3585 ws_ignore_action = ignore_ws_change;3586return0;3587}35883589static intoption_parse_whitespace(const struct option *opt,3590const char*arg,int unset)3591{3592const char**whitespace_option = opt->value;35933594*whitespace_option = arg;3595parse_whitespace_option(arg);3596return0;3597}35983599static intoption_parse_directory(const struct option *opt,3600const char*arg,int unset)3601{3602 root_len =strlen(arg);3603if(root_len && arg[root_len -1] !='/') {3604char*new_root;3605 root = new_root =xmalloc(root_len +2);3606strcpy(new_root, arg);3607strcpy(new_root + root_len++,"/");3608}else3609 root = arg;3610return0;3611}36123613intcmd_apply(int argc,const char**argv,const char*unused_prefix)3614{3615int i;3616int errs =0;3617int is_not_gitdir;3618int binary;3619int force_apply =0;36203621const char*whitespace_option = NULL;36223623struct option builtin_apply_options[] = {3624{ OPTION_CALLBACK,0,"exclude", NULL,"path",3625"don't apply changes matching the given path",36260, option_parse_exclude },3627{ OPTION_CALLBACK,0,"include", NULL,"path",3628"apply changes matching the given path",36290, option_parse_include },3630{ OPTION_CALLBACK,'p', NULL, NULL,"num",3631"remove <num> leading slashes from traditional diff paths",36320, option_parse_p },3633OPT_BOOLEAN(0,"no-add", &no_add,3634"ignore additions made by the patch"),3635OPT_BOOLEAN(0,"stat", &diffstat,3636"instead of applying the patch, output diffstat for the input"),3637{ OPTION_BOOLEAN,0,"allow-binary-replacement", &binary,3638 NULL,"old option, now no-op",3639 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3640{ OPTION_BOOLEAN,0,"binary", &binary,3641 NULL,"old option, now no-op",3642 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3643OPT_BOOLEAN(0,"numstat", &numstat,3644"shows number of added and deleted lines in decimal notation"),3645OPT_BOOLEAN(0,"summary", &summary,3646"instead of applying the patch, output a summary for the input"),3647OPT_BOOLEAN(0,"check", &check,3648"instead of applying the patch, see if the patch is applicable"),3649OPT_BOOLEAN(0,"index", &check_index,3650"make sure the patch is applicable to the current index"),3651OPT_BOOLEAN(0,"cached", &cached,3652"apply a patch without touching the working tree"),3653OPT_BOOLEAN(0,"apply", &force_apply,3654"also apply the patch (use with --stat/--summary/--check)"),3655OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,3656"build a temporary index based on embedded index information"),3657{ OPTION_CALLBACK,'z', NULL, NULL, NULL,3658"paths are separated with NUL character",3659 PARSE_OPT_NOARG, option_parse_z },3660OPT_INTEGER('C', NULL, &p_context,3661"ensure at least <n> lines of context match"),3662{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,"action",3663"detect new or modified lines that have whitespace errors",36640, option_parse_whitespace },3665{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,3666"ignore changes in whitespace when finding context",3667 PARSE_OPT_NOARG, option_parse_space_change },3668{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,3669"ignore changes in whitespace when finding context",3670 PARSE_OPT_NOARG, option_parse_space_change },3671OPT_BOOLEAN('R',"reverse", &apply_in_reverse,3672"apply the patch in reverse"),3673OPT_BOOLEAN(0,"unidiff-zero", &unidiff_zero,3674"don't expect at least one line of context"),3675OPT_BOOLEAN(0,"reject", &apply_with_reject,3676"leave the rejected hunks in corresponding *.rej files"),3677OPT__VERBOSE(&apply_verbosely),3678OPT_BIT(0,"inaccurate-eof", &options,3679"tolerate incorrectly detected missing new-line at the end of file",3680 INACCURATE_EOF),3681OPT_BIT(0,"recount", &options,3682"do not trust the line counts in the hunk headers",3683 RECOUNT),3684{ OPTION_CALLBACK,0,"directory", NULL,"root",3685"prepend <root> to all filenames",36860, option_parse_directory },3687OPT_END()3688};36893690 prefix =setup_git_directory_gently(&is_not_gitdir);3691 prefix_length = prefix ?strlen(prefix) :0;3692git_config(git_apply_config, NULL);3693if(apply_default_whitespace)3694parse_whitespace_option(apply_default_whitespace);3695if(apply_default_ignorewhitespace)3696parse_ignorewhitespace_option(apply_default_ignorewhitespace);36973698 argc =parse_options(argc, argv, prefix, builtin_apply_options,3699 apply_usage,0);37003701if(apply_with_reject)3702 apply = apply_verbosely =1;3703if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))3704 apply =0;3705if(check_index && is_not_gitdir)3706die("--index outside a repository");3707if(cached) {3708if(is_not_gitdir)3709die("--cached outside a repository");3710 check_index =1;3711}3712for(i =0; i < argc; i++) {3713const char*arg = argv[i];3714int fd;37153716if(!strcmp(arg,"-")) {3717 errs |=apply_patch(0,"<stdin>", options);3718 read_stdin =0;3719continue;3720}else if(0< prefix_length)3721 arg =prefix_filename(prefix, prefix_length, arg);37223723 fd =open(arg, O_RDONLY);3724if(fd <0)3725die_errno("can't open patch '%s'", arg);3726 read_stdin =0;3727set_default_whitespace_mode(whitespace_option);3728 errs |=apply_patch(fd, arg, options);3729close(fd);3730}3731set_default_whitespace_mode(whitespace_option);3732if(read_stdin)3733 errs |=apply_patch(0,"<stdin>", options);3734if(whitespace_error) {3735if(squelch_whitespace_errors &&3736 squelch_whitespace_errors < whitespace_error) {3737int squelched =3738 whitespace_error - squelch_whitespace_errors;3739warning("squelched%d"3740"whitespace error%s",3741 squelched,3742 squelched ==1?"":"s");3743}3744if(ws_error_action == die_on_ws_error)3745die("%dline%sadd%swhitespace errors.",3746 whitespace_error,3747 whitespace_error ==1?"":"s",3748 whitespace_error ==1?"s":"");3749if(applied_after_fixing_ws && apply)3750warning("%dline%sapplied after"3751" fixing whitespace errors.",3752 applied_after_fixing_ws,3753 applied_after_fixing_ws ==1?"":"s");3754else if(whitespace_error)3755warning("%dline%sadd%swhitespace errors.",3756 whitespace_error,3757 whitespace_error ==1?"":"s",3758 whitespace_error ==1?"s":"");3759}37603761if(update_index) {3762if(write_cache(newfd, active_cache, active_nr) ||3763commit_locked_index(&lock_file))3764die("Unable to write new index file");3765}37663767return!!errs;3768}