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;1857struct strbuf fixed;1858size_t fixed_len;1859int preimage_limit;18601861if(preimage->nr + try_lno <= img->nr) {1862/*1863 * The hunk falls within the boundaries of img.1864 */1865 preimage_limit = preimage->nr;1866if(match_end && (preimage->nr + try_lno != img->nr))1867return0;1868}else if(ws_error_action == correct_ws_error &&1869(ws_rule & WS_BLANK_AT_EOF)) {1870/*1871 * This hunk extends beyond the end of img, and we are1872 * removing blank lines at the end of the file. This1873 * many lines from the beginning of the preimage must1874 * match with img, and the remainder of the preimage1875 * must be blank.1876 */1877 preimage_limit = img->nr - try_lno;1878}else{1879/*1880 * The hunk extends beyond the end of the img and1881 * we are not removing blanks at the end, so we1882 * should reject the hunk at this position.1883 */1884return0;1885}18861887if(match_beginning && try_lno)1888return0;18891890/* Quick hash check */1891for(i =0; i < preimage_limit; i++)1892if(preimage->line[i].hash != img->line[try_lno + i].hash)1893return0;18941895if(preimage_limit == preimage->nr) {1896/*1897 * Do we have an exact match? If we were told to match1898 * at the end, size must be exactly at try+fragsize,1899 * otherwise try+fragsize must be still within the preimage,1900 * and either case, the old piece should match the preimage1901 * exactly.1902 */1903if((match_end1904? (try+ preimage->len == img->len)1905: (try+ preimage->len <= img->len)) &&1906!memcmp(img->buf +try, preimage->buf, preimage->len))1907return1;1908}else{1909/*1910 * The preimage extends beyond the end of img, so1911 * there cannot be an exact match.1912 *1913 * There must be one non-blank context line that match1914 * a line before the end of img.1915 */1916char*buf_end;19171918 buf = preimage->buf;1919 buf_end = buf;1920for(i =0; i < preimage_limit; i++)1921 buf_end += preimage->line[i].len;19221923for( ; buf < buf_end; buf++)1924if(!isspace(*buf))1925break;1926if(buf == buf_end)1927return0;1928}19291930/*1931 * No exact match. If we are ignoring whitespace, run a line-by-line1932 * fuzzy matching. We collect all the line length information because1933 * we need it to adjust whitespace if we match.1934 */1935if(ws_ignore_action == ignore_ws_change) {1936size_t imgoff =0;1937size_t preoff =0;1938size_t postlen = postimage->len;1939size_t extra_chars;1940char*preimage_eof;1941char*preimage_end;1942for(i =0; i < preimage_limit; i++) {1943size_t prelen = preimage->line[i].len;1944size_t imglen = img->line[try_lno+i].len;19451946if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,1947 preimage->buf + preoff, prelen))1948return0;1949if(preimage->line[i].flag & LINE_COMMON)1950 postlen += imglen - prelen;1951 imgoff += imglen;1952 preoff += prelen;1953}19541955/*1956 * Ok, the preimage matches with whitespace fuzz.1957 *1958 * imgoff now holds the true length of the target that1959 * matches the preimage before the end of the file.1960 *1961 * Count the number of characters in the preimage that fall1962 * beyond the end of the file and make sure that all of them1963 * are whitespace characters. (This can only happen if1964 * we are removing blank lines at the end of the file.)1965 */1966 buf = preimage_eof = preimage->buf + preoff;1967for( ; i < preimage->nr; i++)1968 preoff += preimage->line[i].len;1969 preimage_end = preimage->buf + preoff;1970for( ; buf < preimage_end; buf++)1971if(!isspace(*buf))1972return0;19731974/*1975 * Update the preimage and the common postimage context1976 * lines to use the same whitespace as the target.1977 * If whitespace is missing in the target (i.e.1978 * if the preimage extends beyond the end of the file),1979 * use the whitespace from the preimage.1980 */1981 extra_chars = preimage_end - preimage_eof;1982strbuf_init(&fixed, imgoff + extra_chars);1983strbuf_add(&fixed, img->buf +try, imgoff);1984strbuf_add(&fixed, preimage_eof, extra_chars);1985 fixed_buf =strbuf_detach(&fixed, &fixed_len);1986update_pre_post_images(preimage, postimage,1987 fixed_buf, fixed_len, postlen);1988return1;1989}19901991if(ws_error_action != correct_ws_error)1992return0;19931994/*1995 * The hunk does not apply byte-by-byte, but the hash says1996 * it might with whitespace fuzz. We haven't been asked to1997 * ignore whitespace, we were asked to correct whitespace1998 * errors, so let's try matching after whitespace correction.1999 *2000 * The preimage may extend beyond the end of the file,2001 * but in this loop we will only handle the part of the2002 * preimage that falls within the file.2003 */2004strbuf_init(&fixed, preimage->len +1);2005 orig = preimage->buf;2006 target = img->buf +try;2007for(i =0; i < preimage_limit; i++) {2008size_t oldlen = preimage->line[i].len;2009size_t tgtlen = img->line[try_lno + i].len;2010size_t fixstart = fixed.len;2011struct strbuf tgtfix;2012int match;20132014/* Try fixing the line in the preimage */2015ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);20162017/* Try fixing the line in the target */2018strbuf_init(&tgtfix, tgtlen);2019ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);20202021/*2022 * If they match, either the preimage was based on2023 * a version before our tree fixed whitespace breakage,2024 * or we are lacking a whitespace-fix patch the tree2025 * the preimage was based on already had (i.e. target2026 * has whitespace breakage, the preimage doesn't).2027 * In either case, we are fixing the whitespace breakages2028 * so we might as well take the fix together with their2029 * real change.2030 */2031 match = (tgtfix.len == fixed.len - fixstart &&2032!memcmp(tgtfix.buf, fixed.buf + fixstart,2033 fixed.len - fixstart));20342035strbuf_release(&tgtfix);2036if(!match)2037goto unmatch_exit;20382039 orig += oldlen;2040 target += tgtlen;2041}204220432044/*2045 * Now handle the lines in the preimage that falls beyond the2046 * end of the file (if any). They will only match if they are2047 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2048 * false).2049 */2050for( ; i < preimage->nr; i++) {2051size_t fixstart = fixed.len;/* start of the fixed preimage */2052size_t oldlen = preimage->line[i].len;2053int j;20542055/* Try fixing the line in the preimage */2056ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);20572058for(j = fixstart; j < fixed.len; j++)2059if(!isspace(fixed.buf[j]))2060goto unmatch_exit;20612062 orig += oldlen;2063}20642065/*2066 * Yes, the preimage is based on an older version that still2067 * has whitespace breakages unfixed, and fixing them makes the2068 * hunk match. Update the context lines in the postimage.2069 */2070 fixed_buf =strbuf_detach(&fixed, &fixed_len);2071update_pre_post_images(preimage, postimage,2072 fixed_buf, fixed_len,0);2073return1;20742075 unmatch_exit:2076strbuf_release(&fixed);2077return0;2078}20792080static intfind_pos(struct image *img,2081struct image *preimage,2082struct image *postimage,2083int line,2084unsigned ws_rule,2085int match_beginning,int match_end)2086{2087int i;2088unsigned long backwards, forwards,try;2089int backwards_lno, forwards_lno, try_lno;20902091/*2092 * If match_beginning or match_end is specified, there is no2093 * point starting from a wrong line that will never match and2094 * wander around and wait for a match at the specified end.2095 */2096if(match_beginning)2097 line =0;2098else if(match_end)2099 line = img->nr - preimage->nr;21002101/*2102 * Because the comparison is unsigned, the following test2103 * will also take care of a negative line number that can2104 * result when match_end and preimage is larger than the target.2105 */2106if((size_t) line > img->nr)2107 line = img->nr;21082109try=0;2110for(i =0; i < line; i++)2111try+= img->line[i].len;21122113/*2114 * There's probably some smart way to do this, but I'll leave2115 * that to the smart and beautiful people. I'm simple and stupid.2116 */2117 backwards =try;2118 backwards_lno = line;2119 forwards =try;2120 forwards_lno = line;2121 try_lno = line;21222123for(i =0; ; i++) {2124if(match_fragment(img, preimage, postimage,2125try, try_lno, ws_rule,2126 match_beginning, match_end))2127return try_lno;21282129 again:2130if(backwards_lno ==0&& forwards_lno == img->nr)2131break;21322133if(i &1) {2134if(backwards_lno ==0) {2135 i++;2136goto again;2137}2138 backwards_lno--;2139 backwards -= img->line[backwards_lno].len;2140try= backwards;2141 try_lno = backwards_lno;2142}else{2143if(forwards_lno == img->nr) {2144 i++;2145goto again;2146}2147 forwards += img->line[forwards_lno].len;2148 forwards_lno++;2149try= forwards;2150 try_lno = forwards_lno;2151}21522153}2154return-1;2155}21562157static voidremove_first_line(struct image *img)2158{2159 img->buf += img->line[0].len;2160 img->len -= img->line[0].len;2161 img->line++;2162 img->nr--;2163}21642165static voidremove_last_line(struct image *img)2166{2167 img->len -= img->line[--img->nr].len;2168}21692170static voidupdate_image(struct image *img,2171int applied_pos,2172struct image *preimage,2173struct image *postimage)2174{2175/*2176 * remove the copy of preimage at offset in img2177 * and replace it with postimage2178 */2179int i, nr;2180size_t remove_count, insert_count, applied_at =0;2181char*result;2182int preimage_limit;21832184/*2185 * If we are removing blank lines at the end of img,2186 * the preimage may extend beyond the end.2187 * If that is the case, we must be careful only to2188 * remove the part of the preimage that falls within2189 * the boundaries of img. Initialize preimage_limit2190 * to the number of lines in the preimage that falls2191 * within the boundaries.2192 */2193 preimage_limit = preimage->nr;2194if(preimage_limit > img->nr - applied_pos)2195 preimage_limit = img->nr - applied_pos;21962197for(i =0; i < applied_pos; i++)2198 applied_at += img->line[i].len;21992200 remove_count =0;2201for(i =0; i < preimage_limit; i++)2202 remove_count += img->line[applied_pos + i].len;2203 insert_count = postimage->len;22042205/* Adjust the contents */2206 result =xmalloc(img->len + insert_count - remove_count +1);2207memcpy(result, img->buf, applied_at);2208memcpy(result + applied_at, postimage->buf, postimage->len);2209memcpy(result + applied_at + postimage->len,2210 img->buf + (applied_at + remove_count),2211 img->len - (applied_at + remove_count));2212free(img->buf);2213 img->buf = result;2214 img->len += insert_count - remove_count;2215 result[img->len] ='\0';22162217/* Adjust the line table */2218 nr = img->nr + postimage->nr - preimage_limit;2219if(preimage_limit < postimage->nr) {2220/*2221 * NOTE: this knows that we never call remove_first_line()2222 * on anything other than pre/post image.2223 */2224 img->line =xrealloc(img->line, nr *sizeof(*img->line));2225 img->line_allocated = img->line;2226}2227if(preimage_limit != postimage->nr)2228memmove(img->line + applied_pos + postimage->nr,2229 img->line + applied_pos + preimage_limit,2230(img->nr - (applied_pos + preimage_limit)) *2231sizeof(*img->line));2232memcpy(img->line + applied_pos,2233 postimage->line,2234 postimage->nr *sizeof(*img->line));2235 img->nr = nr;2236}22372238static intapply_one_fragment(struct image *img,struct fragment *frag,2239int inaccurate_eof,unsigned ws_rule)2240{2241int match_beginning, match_end;2242const char*patch = frag->patch;2243int size = frag->size;2244char*old, *oldlines;2245struct strbuf newlines;2246int new_blank_lines_at_end =0;2247unsigned long leading, trailing;2248int pos, applied_pos;2249struct image preimage;2250struct image postimage;22512252memset(&preimage,0,sizeof(preimage));2253memset(&postimage,0,sizeof(postimage));2254 oldlines =xmalloc(size);2255strbuf_init(&newlines, size);22562257 old = oldlines;2258while(size >0) {2259char first;2260int len =linelen(patch, size);2261int plen;2262int added_blank_line =0;2263int is_blank_context =0;2264size_t start;22652266if(!len)2267break;22682269/*2270 * "plen" is how much of the line we should use for2271 * the actual patch data. Normally we just remove the2272 * first character on the line, but if the line is2273 * followed by "\ No newline", then we also remove the2274 * last one (which is the newline, of course).2275 */2276 plen = len -1;2277if(len < size && patch[len] =='\\')2278 plen--;2279 first = *patch;2280if(apply_in_reverse) {2281if(first =='-')2282 first ='+';2283else if(first =='+')2284 first ='-';2285}22862287switch(first) {2288case'\n':2289/* Newer GNU diff, empty context line */2290if(plen <0)2291/* ... followed by '\No newline'; nothing */2292break;2293*old++ ='\n';2294strbuf_addch(&newlines,'\n');2295add_line_info(&preimage,"\n",1, LINE_COMMON);2296add_line_info(&postimage,"\n",1, LINE_COMMON);2297 is_blank_context =1;2298break;2299case' ':2300if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2301ws_blank_line(patch +1, plen, ws_rule))2302 is_blank_context =1;2303case'-':2304memcpy(old, patch +1, plen);2305add_line_info(&preimage, old, plen,2306(first ==' '? LINE_COMMON :0));2307 old += plen;2308if(first =='-')2309break;2310/* Fall-through for ' ' */2311case'+':2312/* --no-add does not add new lines */2313if(first =='+'&& no_add)2314break;23152316 start = newlines.len;2317if(first !='+'||2318!whitespace_error ||2319 ws_error_action != correct_ws_error) {2320strbuf_add(&newlines, patch +1, plen);2321}2322else{2323ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2324}2325add_line_info(&postimage, newlines.buf + start, newlines.len - start,2326(first =='+'?0: LINE_COMMON));2327if(first =='+'&&2328(ws_rule & WS_BLANK_AT_EOF) &&2329ws_blank_line(patch +1, plen, ws_rule))2330 added_blank_line =1;2331break;2332case'@':case'\\':2333/* Ignore it, we already handled it */2334break;2335default:2336if(apply_verbosely)2337error("invalid start of line: '%c'", first);2338return-1;2339}2340if(added_blank_line)2341 new_blank_lines_at_end++;2342else if(is_blank_context)2343;2344else2345 new_blank_lines_at_end =0;2346 patch += len;2347 size -= len;2348}2349if(inaccurate_eof &&2350 old > oldlines && old[-1] =='\n'&&2351 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2352 old--;2353strbuf_setlen(&newlines, newlines.len -1);2354}23552356 leading = frag->leading;2357 trailing = frag->trailing;23582359/*2360 * A hunk to change lines at the beginning would begin with2361 * @@ -1,L +N,M @@2362 * but we need to be careful. -U0 that inserts before the second2363 * line also has this pattern.2364 *2365 * And a hunk to add to an empty file would begin with2366 * @@ -0,0 +N,M @@2367 *2368 * In other words, a hunk that is (frag->oldpos <= 1) with or2369 * without leading context must match at the beginning.2370 */2371 match_beginning = (!frag->oldpos ||2372(frag->oldpos ==1&& !unidiff_zero));23732374/*2375 * A hunk without trailing lines must match at the end.2376 * However, we simply cannot tell if a hunk must match end2377 * from the lack of trailing lines if the patch was generated2378 * with unidiff without any context.2379 */2380 match_end = !unidiff_zero && !trailing;23812382 pos = frag->newpos ? (frag->newpos -1) :0;2383 preimage.buf = oldlines;2384 preimage.len = old - oldlines;2385 postimage.buf = newlines.buf;2386 postimage.len = newlines.len;2387 preimage.line = preimage.line_allocated;2388 postimage.line = postimage.line_allocated;23892390for(;;) {23912392 applied_pos =find_pos(img, &preimage, &postimage, pos,2393 ws_rule, match_beginning, match_end);23942395if(applied_pos >=0)2396break;23972398/* Am I at my context limits? */2399if((leading <= p_context) && (trailing <= p_context))2400break;2401if(match_beginning || match_end) {2402 match_beginning = match_end =0;2403continue;2404}24052406/*2407 * Reduce the number of context lines; reduce both2408 * leading and trailing if they are equal otherwise2409 * just reduce the larger context.2410 */2411if(leading >= trailing) {2412remove_first_line(&preimage);2413remove_first_line(&postimage);2414 pos--;2415 leading--;2416}2417if(trailing > leading) {2418remove_last_line(&preimage);2419remove_last_line(&postimage);2420 trailing--;2421}2422}24232424if(applied_pos >=0) {2425if(new_blank_lines_at_end &&2426 preimage.nr + applied_pos >= img->nr &&2427(ws_rule & WS_BLANK_AT_EOF) &&2428 ws_error_action != nowarn_ws_error) {2429record_ws_error(WS_BLANK_AT_EOF,"+",1, frag->linenr);2430if(ws_error_action == correct_ws_error) {2431while(new_blank_lines_at_end--)2432remove_last_line(&postimage);2433}2434/*2435 * We would want to prevent write_out_results()2436 * from taking place in apply_patch() that follows2437 * the callchain led us here, which is:2438 * apply_patch->check_patch_list->check_patch->2439 * apply_data->apply_fragments->apply_one_fragment2440 */2441if(ws_error_action == die_on_ws_error)2442 apply =0;2443}24442445/*2446 * Warn if it was necessary to reduce the number2447 * of context lines.2448 */2449if((leading != frag->leading) ||2450(trailing != frag->trailing))2451fprintf(stderr,"Context reduced to (%ld/%ld)"2452" to apply fragment at%d\n",2453 leading, trailing, applied_pos+1);2454update_image(img, applied_pos, &preimage, &postimage);2455}else{2456if(apply_verbosely)2457error("while searching for:\n%.*s",2458(int)(old - oldlines), oldlines);2459}24602461free(oldlines);2462strbuf_release(&newlines);2463free(preimage.line_allocated);2464free(postimage.line_allocated);24652466return(applied_pos <0);2467}24682469static intapply_binary_fragment(struct image *img,struct patch *patch)2470{2471struct fragment *fragment = patch->fragments;2472unsigned long len;2473void*dst;24742475/* Binary patch is irreversible without the optional second hunk */2476if(apply_in_reverse) {2477if(!fragment->next)2478returnerror("cannot reverse-apply a binary patch "2479"without the reverse hunk to '%s'",2480 patch->new_name2481? patch->new_name : patch->old_name);2482 fragment = fragment->next;2483}2484switch(fragment->binary_patch_method) {2485case BINARY_DELTA_DEFLATED:2486 dst =patch_delta(img->buf, img->len, fragment->patch,2487 fragment->size, &len);2488if(!dst)2489return-1;2490clear_image(img);2491 img->buf = dst;2492 img->len = len;2493return0;2494case BINARY_LITERAL_DEFLATED:2495clear_image(img);2496 img->len = fragment->size;2497 img->buf =xmalloc(img->len+1);2498memcpy(img->buf, fragment->patch, img->len);2499 img->buf[img->len] ='\0';2500return0;2501}2502return-1;2503}25042505static intapply_binary(struct image *img,struct patch *patch)2506{2507const char*name = patch->old_name ? patch->old_name : patch->new_name;2508unsigned char sha1[20];25092510/*2511 * For safety, we require patch index line to contain2512 * full 40-byte textual SHA1 for old and new, at least for now.2513 */2514if(strlen(patch->old_sha1_prefix) !=40||2515strlen(patch->new_sha1_prefix) !=40||2516get_sha1_hex(patch->old_sha1_prefix, sha1) ||2517get_sha1_hex(patch->new_sha1_prefix, sha1))2518returnerror("cannot apply binary patch to '%s' "2519"without full index line", name);25202521if(patch->old_name) {2522/*2523 * See if the old one matches what the patch2524 * applies to.2525 */2526hash_sha1_file(img->buf, img->len, blob_type, sha1);2527if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2528returnerror("the patch applies to '%s' (%s), "2529"which does not match the "2530"current contents.",2531 name,sha1_to_hex(sha1));2532}2533else{2534/* Otherwise, the old one must be empty. */2535if(img->len)2536returnerror("the patch applies to an empty "2537"'%s' but it is not empty", name);2538}25392540get_sha1_hex(patch->new_sha1_prefix, sha1);2541if(is_null_sha1(sha1)) {2542clear_image(img);2543return0;/* deletion patch */2544}25452546if(has_sha1_file(sha1)) {2547/* We already have the postimage */2548enum object_type type;2549unsigned long size;2550char*result;25512552 result =read_sha1_file(sha1, &type, &size);2553if(!result)2554returnerror("the necessary postimage%sfor "2555"'%s' cannot be read",2556 patch->new_sha1_prefix, name);2557clear_image(img);2558 img->buf = result;2559 img->len = size;2560}else{2561/*2562 * We have verified buf matches the preimage;2563 * apply the patch data to it, which is stored2564 * in the patch->fragments->{patch,size}.2565 */2566if(apply_binary_fragment(img, patch))2567returnerror("binary patch does not apply to '%s'",2568 name);25692570/* verify that the result matches */2571hash_sha1_file(img->buf, img->len, blob_type, sha1);2572if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2573returnerror("binary patch to '%s' creates incorrect result (expecting%s, got%s)",2574 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2575}25762577return0;2578}25792580static intapply_fragments(struct image *img,struct patch *patch)2581{2582struct fragment *frag = patch->fragments;2583const char*name = patch->old_name ? patch->old_name : patch->new_name;2584unsigned ws_rule = patch->ws_rule;2585unsigned inaccurate_eof = patch->inaccurate_eof;25862587if(patch->is_binary)2588returnapply_binary(img, patch);25892590while(frag) {2591if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule)) {2592error("patch failed:%s:%ld", name, frag->oldpos);2593if(!apply_with_reject)2594return-1;2595 frag->rejected =1;2596}2597 frag = frag->next;2598}2599return0;2600}26012602static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2603{2604if(!ce)2605return0;26062607if(S_ISGITLINK(ce->ce_mode)) {2608strbuf_grow(buf,100);2609strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2610}else{2611enum object_type type;2612unsigned long sz;2613char*result;26142615 result =read_sha1_file(ce->sha1, &type, &sz);2616if(!result)2617return-1;2618/* XXX read_sha1_file NUL-terminates */2619strbuf_attach(buf, result, sz, sz +1);2620}2621return0;2622}26232624static struct patch *in_fn_table(const char*name)2625{2626struct string_list_item *item;26272628if(name == NULL)2629return NULL;26302631 item =string_list_lookup(name, &fn_table);2632if(item != NULL)2633return(struct patch *)item->util;26342635return NULL;2636}26372638/*2639 * item->util in the filename table records the status of the path.2640 * Usually it points at a patch (whose result records the contents2641 * of it after applying it), but it could be PATH_WAS_DELETED for a2642 * path that a previously applied patch has already removed.2643 */2644#define PATH_TO_BE_DELETED ((struct patch *) -2)2645#define PATH_WAS_DELETED ((struct patch *) -1)26462647static intto_be_deleted(struct patch *patch)2648{2649return patch == PATH_TO_BE_DELETED;2650}26512652static intwas_deleted(struct patch *patch)2653{2654return patch == PATH_WAS_DELETED;2655}26562657static voidadd_to_fn_table(struct patch *patch)2658{2659struct string_list_item *item;26602661/*2662 * Always add new_name unless patch is a deletion2663 * This should cover the cases for normal diffs,2664 * file creations and copies2665 */2666if(patch->new_name != NULL) {2667 item =string_list_insert(patch->new_name, &fn_table);2668 item->util = patch;2669}26702671/*2672 * store a failure on rename/deletion cases because2673 * later chunks shouldn't patch old names2674 */2675if((patch->new_name == NULL) || (patch->is_rename)) {2676 item =string_list_insert(patch->old_name, &fn_table);2677 item->util = PATH_WAS_DELETED;2678}2679}26802681static voidprepare_fn_table(struct patch *patch)2682{2683/*2684 * store information about incoming file deletion2685 */2686while(patch) {2687if((patch->new_name == NULL) || (patch->is_rename)) {2688struct string_list_item *item;2689 item =string_list_insert(patch->old_name, &fn_table);2690 item->util = PATH_TO_BE_DELETED;2691}2692 patch = patch->next;2693}2694}26952696static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)2697{2698struct strbuf buf = STRBUF_INIT;2699struct image image;2700size_t len;2701char*img;2702struct patch *tpatch;27032704if(!(patch->is_copy || patch->is_rename) &&2705(tpatch =in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {2706if(was_deleted(tpatch)) {2707returnerror("patch%shas been renamed/deleted",2708 patch->old_name);2709}2710/* We have a patched copy in memory use that */2711strbuf_add(&buf, tpatch->result, tpatch->resultsize);2712}else if(cached) {2713if(read_file_or_gitlink(ce, &buf))2714returnerror("read of%sfailed", patch->old_name);2715}else if(patch->old_name) {2716if(S_ISGITLINK(patch->old_mode)) {2717if(ce) {2718read_file_or_gitlink(ce, &buf);2719}else{2720/*2721 * There is no way to apply subproject2722 * patch without looking at the index.2723 */2724 patch->fragments = NULL;2725}2726}else{2727if(read_old_data(st, patch->old_name, &buf))2728returnerror("read of%sfailed", patch->old_name);2729}2730}27312732 img =strbuf_detach(&buf, &len);2733prepare_image(&image, img, len, !patch->is_binary);27342735if(apply_fragments(&image, patch) <0)2736return-1;/* note with --reject this succeeds. */2737 patch->result = image.buf;2738 patch->resultsize = image.len;2739add_to_fn_table(patch);2740free(image.line_allocated);27412742if(0< patch->is_delete && patch->resultsize)2743returnerror("removal patch leaves file contents");27442745return0;2746}27472748static intcheck_to_create_blob(const char*new_name,int ok_if_exists)2749{2750struct stat nst;2751if(!lstat(new_name, &nst)) {2752if(S_ISDIR(nst.st_mode) || ok_if_exists)2753return0;2754/*2755 * A leading component of new_name might be a symlink2756 * that is going to be removed with this patch, but2757 * still pointing at somewhere that has the path.2758 * In such a case, path "new_name" does not exist as2759 * far as git is concerned.2760 */2761if(has_symlink_leading_path(new_name,strlen(new_name)))2762return0;27632764returnerror("%s: already exists in working directory", new_name);2765}2766else if((errno != ENOENT) && (errno != ENOTDIR))2767returnerror("%s:%s", new_name,strerror(errno));2768return0;2769}27702771static intverify_index_match(struct cache_entry *ce,struct stat *st)2772{2773if(S_ISGITLINK(ce->ce_mode)) {2774if(!S_ISDIR(st->st_mode))2775return-1;2776return0;2777}2778returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);2779}27802781static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)2782{2783const char*old_name = patch->old_name;2784struct patch *tpatch = NULL;2785int stat_ret =0;2786unsigned st_mode =0;27872788/*2789 * Make sure that we do not have local modifications from the2790 * index when we are looking at the index. Also make sure2791 * we have the preimage file to be patched in the work tree,2792 * unless --cached, which tells git to apply only in the index.2793 */2794if(!old_name)2795return0;27962797assert(patch->is_new <=0);27982799if(!(patch->is_copy || patch->is_rename) &&2800(tpatch =in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {2801if(was_deleted(tpatch))2802returnerror("%s: has been deleted/renamed", old_name);2803 st_mode = tpatch->new_mode;2804}else if(!cached) {2805 stat_ret =lstat(old_name, st);2806if(stat_ret && errno != ENOENT)2807returnerror("%s:%s", old_name,strerror(errno));2808}28092810if(to_be_deleted(tpatch))2811 tpatch = NULL;28122813if(check_index && !tpatch) {2814int pos =cache_name_pos(old_name,strlen(old_name));2815if(pos <0) {2816if(patch->is_new <0)2817goto is_new;2818returnerror("%s: does not exist in index", old_name);2819}2820*ce = active_cache[pos];2821if(stat_ret <0) {2822struct checkout costate;2823/* checkout */2824memset(&costate,0,sizeof(costate));2825 costate.base_dir ="";2826 costate.refresh_cache =1;2827if(checkout_entry(*ce, &costate, NULL) ||2828lstat(old_name, st))2829return-1;2830}2831if(!cached &&verify_index_match(*ce, st))2832returnerror("%s: does not match index", old_name);2833if(cached)2834 st_mode = (*ce)->ce_mode;2835}else if(stat_ret <0) {2836if(patch->is_new <0)2837goto is_new;2838returnerror("%s:%s", old_name,strerror(errno));2839}28402841if(!cached && !tpatch)2842 st_mode =ce_mode_from_stat(*ce, st->st_mode);28432844if(patch->is_new <0)2845 patch->is_new =0;2846if(!patch->old_mode)2847 patch->old_mode = st_mode;2848if((st_mode ^ patch->old_mode) & S_IFMT)2849returnerror("%s: wrong type", old_name);2850if(st_mode != patch->old_mode)2851warning("%shas type%o, expected%o",2852 old_name, st_mode, patch->old_mode);2853if(!patch->new_mode && !patch->is_delete)2854 patch->new_mode = st_mode;2855return0;28562857 is_new:2858 patch->is_new =1;2859 patch->is_delete =0;2860 patch->old_name = NULL;2861return0;2862}28632864static intcheck_patch(struct patch *patch)2865{2866struct stat st;2867const char*old_name = patch->old_name;2868const char*new_name = patch->new_name;2869const char*name = old_name ? old_name : new_name;2870struct cache_entry *ce = NULL;2871struct patch *tpatch;2872int ok_if_exists;2873int status;28742875 patch->rejected =1;/* we will drop this after we succeed */28762877 status =check_preimage(patch, &ce, &st);2878if(status)2879return status;2880 old_name = patch->old_name;28812882if((tpatch =in_fn_table(new_name)) &&2883(was_deleted(tpatch) ||to_be_deleted(tpatch)))2884/*2885 * A type-change diff is always split into a patch to2886 * delete old, immediately followed by a patch to2887 * create new (see diff.c::run_diff()); in such a case2888 * it is Ok that the entry to be deleted by the2889 * previous patch is still in the working tree and in2890 * the index.2891 */2892 ok_if_exists =1;2893else2894 ok_if_exists =0;28952896if(new_name &&2897((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {2898if(check_index &&2899cache_name_pos(new_name,strlen(new_name)) >=0&&2900!ok_if_exists)2901returnerror("%s: already exists in index", new_name);2902if(!cached) {2903int err =check_to_create_blob(new_name, ok_if_exists);2904if(err)2905return err;2906}2907if(!patch->new_mode) {2908if(0< patch->is_new)2909 patch->new_mode = S_IFREG |0644;2910else2911 patch->new_mode = patch->old_mode;2912}2913}29142915if(new_name && old_name) {2916int same = !strcmp(old_name, new_name);2917if(!patch->new_mode)2918 patch->new_mode = patch->old_mode;2919if((patch->old_mode ^ patch->new_mode) & S_IFMT)2920returnerror("new mode (%o) of%sdoes not match old mode (%o)%s%s",2921 patch->new_mode, new_name, patch->old_mode,2922 same ?"":" of ", same ?"": old_name);2923}29242925if(apply_data(patch, &st, ce) <0)2926returnerror("%s: patch does not apply", name);2927 patch->rejected =0;2928return0;2929}29302931static intcheck_patch_list(struct patch *patch)2932{2933int err =0;29342935prepare_fn_table(patch);2936while(patch) {2937if(apply_verbosely)2938say_patch_name(stderr,2939"Checking patch ", patch,"...\n");2940 err |=check_patch(patch);2941 patch = patch->next;2942}2943return err;2944}29452946/* This function tries to read the sha1 from the current index */2947static intget_current_sha1(const char*path,unsigned char*sha1)2948{2949int pos;29502951if(read_cache() <0)2952return-1;2953 pos =cache_name_pos(path,strlen(path));2954if(pos <0)2955return-1;2956hashcpy(sha1, active_cache[pos]->sha1);2957return0;2958}29592960/* Build an index that contains the just the files needed for a 3way merge */2961static voidbuild_fake_ancestor(struct patch *list,const char*filename)2962{2963struct patch *patch;2964struct index_state result = { NULL };2965int fd;29662967/* Once we start supporting the reverse patch, it may be2968 * worth showing the new sha1 prefix, but until then...2969 */2970for(patch = list; patch; patch = patch->next) {2971const unsigned char*sha1_ptr;2972unsigned char sha1[20];2973struct cache_entry *ce;2974const char*name;29752976 name = patch->old_name ? patch->old_name : patch->new_name;2977if(0< patch->is_new)2978continue;2979else if(get_sha1(patch->old_sha1_prefix, sha1))2980/* git diff has no index line for mode/type changes */2981if(!patch->lines_added && !patch->lines_deleted) {2982if(get_current_sha1(patch->new_name, sha1) ||2983get_current_sha1(patch->old_name, sha1))2984die("mode change for%s, which is not "2985"in current HEAD", name);2986 sha1_ptr = sha1;2987}else2988die("sha1 information is lacking or useless "2989"(%s).", name);2990else2991 sha1_ptr = sha1;29922993 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);2994if(!ce)2995die("make_cache_entry failed for path '%s'", name);2996if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))2997die("Could not add%sto temporary index", name);2998}29993000 fd =open(filename, O_WRONLY | O_CREAT,0666);3001if(fd <0||write_index(&result, fd) ||close(fd))3002die("Could not write temporary index to%s", filename);30033004discard_index(&result);3005}30063007static voidstat_patch_list(struct patch *patch)3008{3009int files, adds, dels;30103011for(files = adds = dels =0; patch ; patch = patch->next) {3012 files++;3013 adds += patch->lines_added;3014 dels += patch->lines_deleted;3015show_stats(patch);3016}30173018printf("%dfiles changed,%dinsertions(+),%ddeletions(-)\n", files, adds, dels);3019}30203021static voidnumstat_patch_list(struct patch *patch)3022{3023for( ; patch; patch = patch->next) {3024const char*name;3025 name = patch->new_name ? patch->new_name : patch->old_name;3026if(patch->is_binary)3027printf("-\t-\t");3028else3029printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3030write_name_quoted(name, stdout, line_termination);3031}3032}30333034static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3035{3036if(mode)3037printf("%smode%06o%s\n", newdelete, mode, name);3038else3039printf("%s %s\n", newdelete, name);3040}30413042static voidshow_mode_change(struct patch *p,int show_name)3043{3044if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3045if(show_name)3046printf(" mode change%06o =>%06o%s\n",3047 p->old_mode, p->new_mode, p->new_name);3048else3049printf(" mode change%06o =>%06o\n",3050 p->old_mode, p->new_mode);3051}3052}30533054static voidshow_rename_copy(struct patch *p)3055{3056const char*renamecopy = p->is_rename ?"rename":"copy";3057const char*old, *new;30583059/* Find common prefix */3060 old = p->old_name;3061new= p->new_name;3062while(1) {3063const char*slash_old, *slash_new;3064 slash_old =strchr(old,'/');3065 slash_new =strchr(new,'/');3066if(!slash_old ||3067!slash_new ||3068 slash_old - old != slash_new -new||3069memcmp(old,new, slash_new -new))3070break;3071 old = slash_old +1;3072new= slash_new +1;3073}3074/* p->old_name thru old is the common prefix, and old and new3075 * through the end of names are renames3076 */3077if(old != p->old_name)3078printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,3079(int)(old - p->old_name), p->old_name,3080 old,new, p->score);3081else3082printf("%s %s=>%s(%d%%)\n", renamecopy,3083 p->old_name, p->new_name, p->score);3084show_mode_change(p,0);3085}30863087static voidsummary_patch_list(struct patch *patch)3088{3089struct patch *p;30903091for(p = patch; p; p = p->next) {3092if(p->is_new)3093show_file_mode_name("create", p->new_mode, p->new_name);3094else if(p->is_delete)3095show_file_mode_name("delete", p->old_mode, p->old_name);3096else{3097if(p->is_rename || p->is_copy)3098show_rename_copy(p);3099else{3100if(p->score) {3101printf(" rewrite%s(%d%%)\n",3102 p->new_name, p->score);3103show_mode_change(p,0);3104}3105else3106show_mode_change(p,1);3107}3108}3109}3110}31113112static voidpatch_stats(struct patch *patch)3113{3114int lines = patch->lines_added + patch->lines_deleted;31153116if(lines > max_change)3117 max_change = lines;3118if(patch->old_name) {3119int len =quote_c_style(patch->old_name, NULL, NULL,0);3120if(!len)3121 len =strlen(patch->old_name);3122if(len > max_len)3123 max_len = len;3124}3125if(patch->new_name) {3126int len =quote_c_style(patch->new_name, NULL, NULL,0);3127if(!len)3128 len =strlen(patch->new_name);3129if(len > max_len)3130 max_len = len;3131}3132}31333134static voidremove_file(struct patch *patch,int rmdir_empty)3135{3136if(update_index) {3137if(remove_file_from_cache(patch->old_name) <0)3138die("unable to remove%sfrom index", patch->old_name);3139}3140if(!cached) {3141if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {3142remove_path(patch->old_name);3143}3144}3145}31463147static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)3148{3149struct stat st;3150struct cache_entry *ce;3151int namelen =strlen(path);3152unsigned ce_size =cache_entry_size(namelen);31533154if(!update_index)3155return;31563157 ce =xcalloc(1, ce_size);3158memcpy(ce->name, path, namelen);3159 ce->ce_mode =create_ce_mode(mode);3160 ce->ce_flags = namelen;3161if(S_ISGITLINK(mode)) {3162const char*s = buf;31633164if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))3165die("corrupt patch for subproject%s", path);3166}else{3167if(!cached) {3168if(lstat(path, &st) <0)3169die_errno("unable to stat newly created file '%s'",3170 path);3171fill_stat_cache_info(ce, &st);3172}3173if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)3174die("unable to create backing store for newly created file%s", path);3175}3176if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3177die("unable to add cache entry for%s", path);3178}31793180static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)3181{3182int fd;3183struct strbuf nbuf = STRBUF_INIT;31843185if(S_ISGITLINK(mode)) {3186struct stat st;3187if(!lstat(path, &st) &&S_ISDIR(st.st_mode))3188return0;3189returnmkdir(path,0777);3190}31913192if(has_symlinks &&S_ISLNK(mode))3193/* Although buf:size is counted string, it also is NUL3194 * terminated.3195 */3196returnsymlink(buf, path);31973198 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);3199if(fd <0)3200return-1;32013202if(convert_to_working_tree(path, buf, size, &nbuf)) {3203 size = nbuf.len;3204 buf = nbuf.buf;3205}3206write_or_die(fd, buf, size);3207strbuf_release(&nbuf);32083209if(close(fd) <0)3210die_errno("closing file '%s'", path);3211return0;3212}32133214/*3215 * We optimistically assume that the directories exist,3216 * which is true 99% of the time anyway. If they don't,3217 * we create them and try again.3218 */3219static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)3220{3221if(cached)3222return;3223if(!try_create_file(path, mode, buf, size))3224return;32253226if(errno == ENOENT) {3227if(safe_create_leading_directories(path))3228return;3229if(!try_create_file(path, mode, buf, size))3230return;3231}32323233if(errno == EEXIST || errno == EACCES) {3234/* We may be trying to create a file where a directory3235 * used to be.3236 */3237struct stat st;3238if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))3239 errno = EEXIST;3240}32413242if(errno == EEXIST) {3243unsigned int nr =getpid();32443245for(;;) {3246char newpath[PATH_MAX];3247mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);3248if(!try_create_file(newpath, mode, buf, size)) {3249if(!rename(newpath, path))3250return;3251unlink_or_warn(newpath);3252break;3253}3254if(errno != EEXIST)3255break;3256++nr;3257}3258}3259die_errno("unable to write file '%s' mode%o", path, mode);3260}32613262static voidcreate_file(struct patch *patch)3263{3264char*path = patch->new_name;3265unsigned mode = patch->new_mode;3266unsigned long size = patch->resultsize;3267char*buf = patch->result;32683269if(!mode)3270 mode = S_IFREG |0644;3271create_one_file(path, mode, buf, size);3272add_index_file(path, mode, buf, size);3273}32743275/* phase zero is to remove, phase one is to create */3276static voidwrite_out_one_result(struct patch *patch,int phase)3277{3278if(patch->is_delete >0) {3279if(phase ==0)3280remove_file(patch,1);3281return;3282}3283if(patch->is_new >0|| patch->is_copy) {3284if(phase ==1)3285create_file(patch);3286return;3287}3288/*3289 * Rename or modification boils down to the same3290 * thing: remove the old, write the new3291 */3292if(phase ==0)3293remove_file(patch, patch->is_rename);3294if(phase ==1)3295create_file(patch);3296}32973298static intwrite_out_one_reject(struct patch *patch)3299{3300FILE*rej;3301char namebuf[PATH_MAX];3302struct fragment *frag;3303int cnt =0;33043305for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {3306if(!frag->rejected)3307continue;3308 cnt++;3309}33103311if(!cnt) {3312if(apply_verbosely)3313say_patch_name(stderr,3314"Applied patch ", patch," cleanly.\n");3315return0;3316}33173318/* This should not happen, because a removal patch that leaves3319 * contents are marked "rejected" at the patch level.3320 */3321if(!patch->new_name)3322die("internal error");33233324/* Say this even without --verbose */3325say_patch_name(stderr,"Applying patch ", patch," with");3326fprintf(stderr,"%drejects...\n", cnt);33273328 cnt =strlen(patch->new_name);3329if(ARRAY_SIZE(namebuf) <= cnt +5) {3330 cnt =ARRAY_SIZE(namebuf) -5;3331warning("truncating .rej filename to %.*s.rej",3332 cnt -1, patch->new_name);3333}3334memcpy(namebuf, patch->new_name, cnt);3335memcpy(namebuf + cnt,".rej",5);33363337 rej =fopen(namebuf,"w");3338if(!rej)3339returnerror("cannot open%s:%s", namebuf,strerror(errno));33403341/* Normal git tools never deal with .rej, so do not pretend3342 * this is a git patch by saying --git nor give extended3343 * headers. While at it, maybe please "kompare" that wants3344 * the trailing TAB and some garbage at the end of line ;-).3345 */3346fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",3347 patch->new_name, patch->new_name);3348for(cnt =1, frag = patch->fragments;3349 frag;3350 cnt++, frag = frag->next) {3351if(!frag->rejected) {3352fprintf(stderr,"Hunk #%dapplied cleanly.\n", cnt);3353continue;3354}3355fprintf(stderr,"Rejected hunk #%d.\n", cnt);3356fprintf(rej,"%.*s", frag->size, frag->patch);3357if(frag->patch[frag->size-1] !='\n')3358fputc('\n', rej);3359}3360fclose(rej);3361return-1;3362}33633364static intwrite_out_results(struct patch *list,int skipped_patch)3365{3366int phase;3367int errs =0;3368struct patch *l;33693370if(!list && !skipped_patch)3371returnerror("No changes");33723373for(phase =0; phase <2; phase++) {3374 l = list;3375while(l) {3376if(l->rejected)3377 errs =1;3378else{3379write_out_one_result(l, phase);3380if(phase ==1&&write_out_one_reject(l))3381 errs =1;3382}3383 l = l->next;3384}3385}3386return errs;3387}33883389static struct lock_file lock_file;33903391static struct string_list limit_by_name;3392static int has_include;3393static voidadd_name_limit(const char*name,int exclude)3394{3395struct string_list_item *it;33963397 it =string_list_append(name, &limit_by_name);3398 it->util = exclude ? NULL : (void*)1;3399}34003401static intuse_patch(struct patch *p)3402{3403const char*pathname = p->new_name ? p->new_name : p->old_name;3404int i;34053406/* Paths outside are not touched regardless of "--include" */3407if(0< prefix_length) {3408int pathlen =strlen(pathname);3409if(pathlen <= prefix_length ||3410memcmp(prefix, pathname, prefix_length))3411return0;3412}34133414/* See if it matches any of exclude/include rule */3415for(i =0; i < limit_by_name.nr; i++) {3416struct string_list_item *it = &limit_by_name.items[i];3417if(!fnmatch(it->string, pathname,0))3418return(it->util != NULL);3419}34203421/*3422 * If we had any include, a path that does not match any rule is3423 * not used. Otherwise, we saw bunch of exclude rules (or none)3424 * and such a path is used.3425 */3426return!has_include;3427}342834293430static voidprefix_one(char**name)3431{3432char*old_name = *name;3433if(!old_name)3434return;3435*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3436free(old_name);3437}34383439static voidprefix_patches(struct patch *p)3440{3441if(!prefix || p->is_toplevel_relative)3442return;3443for( ; p; p = p->next) {3444if(p->new_name == p->old_name) {3445char*prefixed = p->new_name;3446prefix_one(&prefixed);3447 p->new_name = p->old_name = prefixed;3448}3449else{3450prefix_one(&p->new_name);3451prefix_one(&p->old_name);3452}3453}3454}34553456#define INACCURATE_EOF (1<<0)3457#define RECOUNT (1<<1)34583459static intapply_patch(int fd,const char*filename,int options)3460{3461size_t offset;3462struct strbuf buf = STRBUF_INIT;3463struct patch *list = NULL, **listp = &list;3464int skipped_patch =0;34653466/* FIXME - memory leak when using multiple patch files as inputs */3467memset(&fn_table,0,sizeof(struct string_list));3468 patch_input_file = filename;3469read_patch_file(&buf, fd);3470 offset =0;3471while(offset < buf.len) {3472struct patch *patch;3473int nr;34743475 patch =xcalloc(1,sizeof(*patch));3476 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3477 patch->recount = !!(options & RECOUNT);3478 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3479if(nr <0)3480break;3481if(apply_in_reverse)3482reverse_patches(patch);3483if(prefix)3484prefix_patches(patch);3485if(use_patch(patch)) {3486patch_stats(patch);3487*listp = patch;3488 listp = &patch->next;3489}3490else{3491/* perhaps free it a bit better? */3492free(patch);3493 skipped_patch++;3494}3495 offset += nr;3496}34973498if(whitespace_error && (ws_error_action == die_on_ws_error))3499 apply =0;35003501 update_index = check_index && apply;3502if(update_index && newfd <0)3503 newfd =hold_locked_index(&lock_file,1);35043505if(check_index) {3506if(read_cache() <0)3507die("unable to read index file");3508}35093510if((check || apply) &&3511check_patch_list(list) <0&&3512!apply_with_reject)3513exit(1);35143515if(apply &&write_out_results(list, skipped_patch))3516exit(1);35173518if(fake_ancestor)3519build_fake_ancestor(list, fake_ancestor);35203521if(diffstat)3522stat_patch_list(list);35233524if(numstat)3525numstat_patch_list(list);35263527if(summary)3528summary_patch_list(list);35293530strbuf_release(&buf);3531return0;3532}35333534static intgit_apply_config(const char*var,const char*value,void*cb)3535{3536if(!strcmp(var,"apply.whitespace"))3537returngit_config_string(&apply_default_whitespace, var, value);3538else if(!strcmp(var,"apply.ignorewhitespace"))3539returngit_config_string(&apply_default_ignorewhitespace, var, value);3540returngit_default_config(var, value, cb);3541}35423543static intoption_parse_exclude(const struct option *opt,3544const char*arg,int unset)3545{3546add_name_limit(arg,1);3547return0;3548}35493550static intoption_parse_include(const struct option *opt,3551const char*arg,int unset)3552{3553add_name_limit(arg,0);3554 has_include =1;3555return0;3556}35573558static intoption_parse_p(const struct option *opt,3559const char*arg,int unset)3560{3561 p_value =atoi(arg);3562 p_value_known =1;3563return0;3564}35653566static intoption_parse_z(const struct option *opt,3567const char*arg,int unset)3568{3569if(unset)3570 line_termination ='\n';3571else3572 line_termination =0;3573return0;3574}35753576static intoption_parse_space_change(const struct option *opt,3577const char*arg,int unset)3578{3579if(unset)3580 ws_ignore_action = ignore_ws_none;3581else3582 ws_ignore_action = ignore_ws_change;3583return0;3584}35853586static intoption_parse_whitespace(const struct option *opt,3587const char*arg,int unset)3588{3589const char**whitespace_option = opt->value;35903591*whitespace_option = arg;3592parse_whitespace_option(arg);3593return0;3594}35953596static intoption_parse_directory(const struct option *opt,3597const char*arg,int unset)3598{3599 root_len =strlen(arg);3600if(root_len && arg[root_len -1] !='/') {3601char*new_root;3602 root = new_root =xmalloc(root_len +2);3603strcpy(new_root, arg);3604strcpy(new_root + root_len++,"/");3605}else3606 root = arg;3607return0;3608}36093610intcmd_apply(int argc,const char**argv,const char*unused_prefix)3611{3612int i;3613int errs =0;3614int is_not_gitdir;3615int binary;3616int force_apply =0;36173618const char*whitespace_option = NULL;36193620struct option builtin_apply_options[] = {3621{ OPTION_CALLBACK,0,"exclude", NULL,"path",3622"don't apply changes matching the given path",36230, option_parse_exclude },3624{ OPTION_CALLBACK,0,"include", NULL,"path",3625"apply changes matching the given path",36260, option_parse_include },3627{ OPTION_CALLBACK,'p', NULL, NULL,"num",3628"remove <num> leading slashes from traditional diff paths",36290, option_parse_p },3630OPT_BOOLEAN(0,"no-add", &no_add,3631"ignore additions made by the patch"),3632OPT_BOOLEAN(0,"stat", &diffstat,3633"instead of applying the patch, output diffstat for the input"),3634{ OPTION_BOOLEAN,0,"allow-binary-replacement", &binary,3635 NULL,"old option, now no-op",3636 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3637{ OPTION_BOOLEAN,0,"binary", &binary,3638 NULL,"old option, now no-op",3639 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3640OPT_BOOLEAN(0,"numstat", &numstat,3641"shows number of added and deleted lines in decimal notation"),3642OPT_BOOLEAN(0,"summary", &summary,3643"instead of applying the patch, output a summary for the input"),3644OPT_BOOLEAN(0,"check", &check,3645"instead of applying the patch, see if the patch is applicable"),3646OPT_BOOLEAN(0,"index", &check_index,3647"make sure the patch is applicable to the current index"),3648OPT_BOOLEAN(0,"cached", &cached,3649"apply a patch without touching the working tree"),3650OPT_BOOLEAN(0,"apply", &force_apply,3651"also apply the patch (use with --stat/--summary/--check)"),3652OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,3653"build a temporary index based on embedded index information"),3654{ OPTION_CALLBACK,'z', NULL, NULL, NULL,3655"paths are separated with NUL character",3656 PARSE_OPT_NOARG, option_parse_z },3657OPT_INTEGER('C', NULL, &p_context,3658"ensure at least <n> lines of context match"),3659{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,"action",3660"detect new or modified lines that have whitespace errors",36610, option_parse_whitespace },3662{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,3663"ignore changes in whitespace when finding context",3664 PARSE_OPT_NOARG, option_parse_space_change },3665{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,3666"ignore changes in whitespace when finding context",3667 PARSE_OPT_NOARG, option_parse_space_change },3668OPT_BOOLEAN('R',"reverse", &apply_in_reverse,3669"apply the patch in reverse"),3670OPT_BOOLEAN(0,"unidiff-zero", &unidiff_zero,3671"don't expect at least one line of context"),3672OPT_BOOLEAN(0,"reject", &apply_with_reject,3673"leave the rejected hunks in corresponding *.rej files"),3674OPT__VERBOSE(&apply_verbosely),3675OPT_BIT(0,"inaccurate-eof", &options,3676"tolerate incorrectly detected missing new-line at the end of file",3677 INACCURATE_EOF),3678OPT_BIT(0,"recount", &options,3679"do not trust the line counts in the hunk headers",3680 RECOUNT),3681{ OPTION_CALLBACK,0,"directory", NULL,"root",3682"prepend <root> to all filenames",36830, option_parse_directory },3684OPT_END()3685};36863687 prefix =setup_git_directory_gently(&is_not_gitdir);3688 prefix_length = prefix ?strlen(prefix) :0;3689git_config(git_apply_config, NULL);3690if(apply_default_whitespace)3691parse_whitespace_option(apply_default_whitespace);3692if(apply_default_ignorewhitespace)3693parse_ignorewhitespace_option(apply_default_ignorewhitespace);36943695 argc =parse_options(argc, argv, prefix, builtin_apply_options,3696 apply_usage,0);36973698if(apply_with_reject)3699 apply = apply_verbosely =1;3700if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))3701 apply =0;3702if(check_index && is_not_gitdir)3703die("--index outside a repository");3704if(cached) {3705if(is_not_gitdir)3706die("--cached outside a repository");3707 check_index =1;3708}3709for(i =0; i < argc; i++) {3710const char*arg = argv[i];3711int fd;37123713if(!strcmp(arg,"-")) {3714 errs |=apply_patch(0,"<stdin>", options);3715 read_stdin =0;3716continue;3717}else if(0< prefix_length)3718 arg =prefix_filename(prefix, prefix_length, arg);37193720 fd =open(arg, O_RDONLY);3721if(fd <0)3722die_errno("can't open patch '%s'", arg);3723 read_stdin =0;3724set_default_whitespace_mode(whitespace_option);3725 errs |=apply_patch(fd, arg, options);3726close(fd);3727}3728set_default_whitespace_mode(whitespace_option);3729if(read_stdin)3730 errs |=apply_patch(0,"<stdin>", options);3731if(whitespace_error) {3732if(squelch_whitespace_errors &&3733 squelch_whitespace_errors < whitespace_error) {3734int squelched =3735 whitespace_error - squelch_whitespace_errors;3736warning("squelched%d"3737"whitespace error%s",3738 squelched,3739 squelched ==1?"":"s");3740}3741if(ws_error_action == die_on_ws_error)3742die("%dline%sadd%swhitespace errors.",3743 whitespace_error,3744 whitespace_error ==1?"":"s",3745 whitespace_error ==1?"s":"");3746if(applied_after_fixing_ws && apply)3747warning("%dline%sapplied after"3748" fixing whitespace errors.",3749 applied_after_fixing_ws,3750 applied_after_fixing_ws ==1?"":"s");3751else if(whitespace_error)3752warning("%dline%sadd%swhitespace errors.",3753 whitespace_error,3754 whitespace_error ==1?"":"s",3755 whitespace_error ==1?"s":"");3756}37573758if(update_index) {3759if(write_cache(newfd, active_cache, active_nr) ||3760commit_locked_index(&lock_file))3761die("Unable to write new index file");3762}37633764return!!errs;3765}