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_gnu(const char*line,char*def,int p_value) 420{ 421struct strbuf name = STRBUF_INIT; 422char*cp; 423 424/* 425 * Proposed "new-style" GNU patch/diff format; see 426 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2 427 */ 428if(unquote_c_style(&name, line, NULL)) { 429strbuf_release(&name); 430return NULL; 431} 432 433for(cp = name.buf; p_value; p_value--) { 434 cp =strchr(cp,'/'); 435if(!cp) { 436strbuf_release(&name); 437return NULL; 438} 439 cp++; 440} 441 442/* name can later be freed, so we need 443 * to memmove, not just return cp 444 */ 445strbuf_remove(&name,0, cp - name.buf); 446free(def); 447if(root) 448strbuf_insert(&name,0, root, root_len); 449returnsquash_slash(strbuf_detach(&name, NULL)); 450} 451 452static size_tsane_tz_len(const char*line,size_t len) 453{ 454const char*tz, *p; 455 456if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 457return0; 458 tz = line + len -strlen(" +0500"); 459 460if(tz[1] !='+'&& tz[1] !='-') 461return0; 462 463for(p = tz +2; p != line + len; p++) 464if(!isdigit(*p)) 465return0; 466 467return line + len - tz; 468} 469 470static size_ttz_with_colon_len(const char*line,size_t len) 471{ 472const char*tz, *p; 473 474if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 475return0; 476 tz = line + len -strlen(" +08:00"); 477 478if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 479return0; 480 p = tz +2; 481if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 482!isdigit(*p++) || !isdigit(*p++)) 483return0; 484 485return line + len - tz; 486} 487 488static size_tdate_len(const char*line,size_t len) 489{ 490const char*date, *p; 491 492if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 493return0; 494 p = date = line + len -strlen("72-02-05"); 495 496if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 497!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 498!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 499return0; 500 501if(date - line >=strlen("19") && 502isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 503 date -=strlen("19"); 504 505return line + len - date; 506} 507 508static size_tshort_time_len(const char*line,size_t len) 509{ 510const char*time, *p; 511 512if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 513return0; 514 p = time = line + len -strlen(" 07:01:32"); 515 516/* Permit 1-digit hours? */ 517if(*p++ !=' '|| 518!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 519!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 520!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 521return0; 522 523return line + len - time; 524} 525 526static size_tfractional_time_len(const char*line,size_t len) 527{ 528const char*p; 529size_t n; 530 531/* Expected format: 19:41:17.620000023 */ 532if(!len || !isdigit(line[len -1])) 533return0; 534 p = line + len -1; 535 536/* Fractional seconds. */ 537while(p > line &&isdigit(*p)) 538 p--; 539if(*p !='.') 540return0; 541 542/* Hours, minutes, and whole seconds. */ 543 n =short_time_len(line, p - line); 544if(!n) 545return0; 546 547return line + len - p + n; 548} 549 550static size_ttrailing_spaces_len(const char*line,size_t len) 551{ 552const char*p; 553 554/* Expected format: ' ' x (1 or more) */ 555if(!len || line[len -1] !=' ') 556return0; 557 558 p = line + len; 559while(p != line) { 560 p--; 561if(*p !=' ') 562return line + len - (p +1); 563} 564 565/* All spaces! */ 566return len; 567} 568 569static size_tdiff_timestamp_len(const char*line,size_t len) 570{ 571const char*end = line + len; 572size_t n; 573 574/* 575 * Posix: 2010-07-05 19:41:17 576 * GNU: 2010-07-05 19:41:17.620000023 -0500 577 */ 578 579if(!isdigit(end[-1])) 580return0; 581 582 n =sane_tz_len(line, end - line); 583if(!n) 584 n =tz_with_colon_len(line, end - line); 585 end -= n; 586 587 n =short_time_len(line, end - line); 588if(!n) 589 n =fractional_time_len(line, end - line); 590 end -= n; 591 592 n =date_len(line, end - line); 593if(!n)/* No date. Too bad. */ 594return0; 595 end -= n; 596 597if(end == line)/* No space before date. */ 598return0; 599if(end[-1] =='\t') {/* Success! */ 600 end--; 601return line + len - end; 602} 603if(end[-1] !=' ')/* No space before date. */ 604return0; 605 606/* Whitespace damage. */ 607 end -=trailing_spaces_len(line, end - line); 608return line + len - end; 609} 610 611static char*find_name_common(const char*line,char*def,int p_value, 612const char*end,int terminate) 613{ 614int len; 615const char*start = NULL; 616 617if(p_value ==0) 618 start = line; 619while(line != end) { 620char c = *line; 621 622if(!end &&isspace(c)) { 623if(c =='\n') 624break; 625if(name_terminate(start, line-start, c, terminate)) 626break; 627} 628 line++; 629if(c =='/'&& !--p_value) 630 start = line; 631} 632if(!start) 633returnsquash_slash(def); 634 len = line - start; 635if(!len) 636returnsquash_slash(def); 637 638/* 639 * Generally we prefer the shorter name, especially 640 * if the other one is just a variation of that with 641 * something else tacked on to the end (ie "file.orig" 642 * or "file~"). 643 */ 644if(def) { 645int deflen =strlen(def); 646if(deflen < len && !strncmp(start, def, deflen)) 647returnsquash_slash(def); 648free(def); 649} 650 651if(root) { 652char*ret =xmalloc(root_len + len +1); 653strcpy(ret, root); 654memcpy(ret + root_len, start, len); 655 ret[root_len + len] ='\0'; 656returnsquash_slash(ret); 657} 658 659returnsquash_slash(xmemdupz(start, len)); 660} 661 662static char*find_name(const char*line,char*def,int p_value,int terminate) 663{ 664if(*line =='"') { 665char*name =find_name_gnu(line, def, p_value); 666if(name) 667return name; 668} 669 670returnfind_name_common(line, def, p_value, NULL, terminate); 671} 672 673static char*find_name_traditional(const char*line,char*def,int p_value) 674{ 675size_t len =strlen(line); 676size_t date_len; 677 678if(*line =='"') { 679char*name =find_name_gnu(line, def, p_value); 680if(name) 681return name; 682} 683 684 len =strchrnul(line,'\n') - line; 685 date_len =diff_timestamp_len(line, len); 686if(!date_len) 687returnfind_name_common(line, def, p_value, NULL, TERM_TAB); 688 len -= date_len; 689 690returnfind_name_common(line, def, p_value, line + len,0); 691} 692 693static intcount_slashes(const char*cp) 694{ 695int cnt =0; 696char ch; 697 698while((ch = *cp++)) 699if(ch =='/') 700 cnt++; 701return cnt; 702} 703 704/* 705 * Given the string after "--- " or "+++ ", guess the appropriate 706 * p_value for the given patch. 707 */ 708static intguess_p_value(const char*nameline) 709{ 710char*name, *cp; 711int val = -1; 712 713if(is_dev_null(nameline)) 714return-1; 715 name =find_name_traditional(nameline, NULL,0); 716if(!name) 717return-1; 718 cp =strchr(name,'/'); 719if(!cp) 720 val =0; 721else if(prefix) { 722/* 723 * Does it begin with "a/$our-prefix" and such? Then this is 724 * very likely to apply to our directory. 725 */ 726if(!strncmp(name, prefix, prefix_length)) 727 val =count_slashes(prefix); 728else{ 729 cp++; 730if(!strncmp(cp, prefix, prefix_length)) 731 val =count_slashes(prefix) +1; 732} 733} 734free(name); 735return val; 736} 737 738/* 739 * Does the ---/+++ line has the POSIX timestamp after the last HT? 740 * GNU diff puts epoch there to signal a creation/deletion event. Is 741 * this such a timestamp? 742 */ 743static inthas_epoch_timestamp(const char*nameline) 744{ 745/* 746 * We are only interested in epoch timestamp; any non-zero 747 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 748 * For the same reason, the date must be either 1969-12-31 or 749 * 1970-01-01, and the seconds part must be "00". 750 */ 751const char stamp_regexp[] = 752"^(1969-12-31|1970-01-01)" 753" " 754"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 755" " 756"([-+][0-2][0-9]:?[0-5][0-9])\n"; 757const char*timestamp = NULL, *cp, *colon; 758static regex_t *stamp; 759 regmatch_t m[10]; 760int zoneoffset; 761int hourminute; 762int status; 763 764for(cp = nameline; *cp !='\n'; cp++) { 765if(*cp =='\t') 766 timestamp = cp +1; 767} 768if(!timestamp) 769return0; 770if(!stamp) { 771 stamp =xmalloc(sizeof(*stamp)); 772if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 773warning("Cannot prepare timestamp regexp%s", 774 stamp_regexp); 775return0; 776} 777} 778 779 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 780if(status) { 781if(status != REG_NOMATCH) 782warning("regexec returned%dfor input:%s", 783 status, timestamp); 784return0; 785} 786 787 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 788if(*colon ==':') 789 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 790else 791 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 792if(timestamp[m[3].rm_so] =='-') 793 zoneoffset = -zoneoffset; 794 795/* 796 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 797 * (west of GMT) or 1970-01-01 (east of GMT) 798 */ 799if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 800(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 801return0; 802 803 hourminute = (strtol(timestamp +11, NULL,10) *60+ 804strtol(timestamp +14, NULL,10) - 805 zoneoffset); 806 807return((zoneoffset <0&& hourminute ==1440) || 808(0<= zoneoffset && !hourminute)); 809} 810 811/* 812 * Get the name etc info from the ---/+++ lines of a traditional patch header 813 * 814 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 815 * files, we can happily check the index for a match, but for creating a 816 * new file we should try to match whatever "patch" does. I have no idea. 817 */ 818static voidparse_traditional_patch(const char*first,const char*second,struct patch *patch) 819{ 820char*name; 821 822 first +=4;/* skip "--- " */ 823 second +=4;/* skip "+++ " */ 824if(!p_value_known) { 825int p, q; 826 p =guess_p_value(first); 827 q =guess_p_value(second); 828if(p <0) p = q; 829if(0<= p && p == q) { 830 p_value = p; 831 p_value_known =1; 832} 833} 834if(is_dev_null(first)) { 835 patch->is_new =1; 836 patch->is_delete =0; 837 name =find_name_traditional(second, NULL, p_value); 838 patch->new_name = name; 839}else if(is_dev_null(second)) { 840 patch->is_new =0; 841 patch->is_delete =1; 842 name =find_name_traditional(first, NULL, p_value); 843 patch->old_name = name; 844}else{ 845 name =find_name_traditional(first, NULL, p_value); 846 name =find_name_traditional(second, name, p_value); 847if(has_epoch_timestamp(first)) { 848 patch->is_new =1; 849 patch->is_delete =0; 850 patch->new_name = name; 851}else if(has_epoch_timestamp(second)) { 852 patch->is_new =0; 853 patch->is_delete =1; 854 patch->old_name = name; 855}else{ 856 patch->old_name = patch->new_name = name; 857} 858} 859if(!name) 860die("unable to find filename in patch at line%d", linenr); 861} 862 863static intgitdiff_hdrend(const char*line,struct patch *patch) 864{ 865return-1; 866} 867 868/* 869 * We're anal about diff header consistency, to make 870 * sure that we don't end up having strange ambiguous 871 * patches floating around. 872 * 873 * As a result, gitdiff_{old|new}name() will check 874 * their names against any previous information, just 875 * to make sure.. 876 */ 877static char*gitdiff_verify_name(const char*line,int isnull,char*orig_name,const char*oldnew) 878{ 879if(!orig_name && !isnull) 880returnfind_name(line, NULL, p_value, TERM_TAB); 881 882if(orig_name) { 883int len; 884const char*name; 885char*another; 886 name = orig_name; 887 len =strlen(name); 888if(isnull) 889die("git apply: bad git-diff - expected /dev/null, got%son line%d", name, linenr); 890 another =find_name(line, NULL, p_value, TERM_TAB); 891if(!another ||memcmp(another, name, len +1)) 892die("git apply: bad git-diff - inconsistent%sfilename on line%d", oldnew, linenr); 893free(another); 894return orig_name; 895} 896else{ 897/* expect "/dev/null" */ 898if(memcmp("/dev/null", line,9) || line[9] !='\n') 899die("git apply: bad git-diff - expected /dev/null on line%d", linenr); 900return NULL; 901} 902} 903 904static intgitdiff_oldname(const char*line,struct patch *patch) 905{ 906 patch->old_name =gitdiff_verify_name(line, patch->is_new, patch->old_name,"old"); 907return0; 908} 909 910static intgitdiff_newname(const char*line,struct patch *patch) 911{ 912 patch->new_name =gitdiff_verify_name(line, patch->is_delete, patch->new_name,"new"); 913return0; 914} 915 916static intgitdiff_oldmode(const char*line,struct patch *patch) 917{ 918 patch->old_mode =strtoul(line, NULL,8); 919return0; 920} 921 922static intgitdiff_newmode(const char*line,struct patch *patch) 923{ 924 patch->new_mode =strtoul(line, NULL,8); 925return0; 926} 927 928static intgitdiff_delete(const char*line,struct patch *patch) 929{ 930 patch->is_delete =1; 931 patch->old_name = patch->def_name; 932returngitdiff_oldmode(line, patch); 933} 934 935static intgitdiff_newfile(const char*line,struct patch *patch) 936{ 937 patch->is_new =1; 938 patch->new_name = patch->def_name; 939returngitdiff_newmode(line, patch); 940} 941 942static intgitdiff_copysrc(const char*line,struct patch *patch) 943{ 944 patch->is_copy =1; 945 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0); 946return0; 947} 948 949static intgitdiff_copydst(const char*line,struct patch *patch) 950{ 951 patch->is_copy =1; 952 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0); 953return0; 954} 955 956static intgitdiff_renamesrc(const char*line,struct patch *patch) 957{ 958 patch->is_rename =1; 959 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0); 960return0; 961} 962 963static intgitdiff_renamedst(const char*line,struct patch *patch) 964{ 965 patch->is_rename =1; 966 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0); 967return0; 968} 969 970static intgitdiff_similarity(const char*line,struct patch *patch) 971{ 972if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 973 patch->score =0; 974return0; 975} 976 977static intgitdiff_dissimilarity(const char*line,struct patch *patch) 978{ 979if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 980 patch->score =0; 981return0; 982} 983 984static intgitdiff_index(const char*line,struct patch *patch) 985{ 986/* 987 * index line is N hexadecimal, "..", N hexadecimal, 988 * and optional space with octal mode. 989 */ 990const char*ptr, *eol; 991int len; 992 993 ptr =strchr(line,'.'); 994if(!ptr || ptr[1] !='.'||40< ptr - line) 995return0; 996 len = ptr - line; 997memcpy(patch->old_sha1_prefix, line, len); 998 patch->old_sha1_prefix[len] =0; 9991000 line = ptr +2;1001 ptr =strchr(line,' ');1002 eol =strchr(line,'\n');10031004if(!ptr || eol < ptr)1005 ptr = eol;1006 len = ptr - line;10071008if(40< len)1009return0;1010memcpy(patch->new_sha1_prefix, line, len);1011 patch->new_sha1_prefix[len] =0;1012if(*ptr ==' ')1013 patch->old_mode =strtoul(ptr+1, NULL,8);1014return0;1015}10161017/*1018 * This is normal for a diff that doesn't change anything: we'll fall through1019 * into the next diff. Tell the parser to break out.1020 */1021static intgitdiff_unrecognized(const char*line,struct patch *patch)1022{1023return-1;1024}10251026static const char*stop_at_slash(const char*line,int llen)1027{1028int nslash = p_value;1029int i;10301031for(i =0; i < llen; i++) {1032int ch = line[i];1033if(ch =='/'&& --nslash <=0)1034return&line[i];1035}1036return NULL;1037}10381039/*1040 * This is to extract the same name that appears on "diff --git"1041 * line. We do not find and return anything if it is a rename1042 * patch, and it is OK because we will find the name elsewhere.1043 * We need to reliably find name only when it is mode-change only,1044 * creation or deletion of an empty file. In any of these cases,1045 * both sides are the same name under a/ and b/ respectively.1046 */1047static char*git_header_name(char*line,int llen)1048{1049const char*name;1050const char*second = NULL;1051size_t len, line_len;10521053 line +=strlen("diff --git ");1054 llen -=strlen("diff --git ");10551056if(*line =='"') {1057const char*cp;1058struct strbuf first = STRBUF_INIT;1059struct strbuf sp = STRBUF_INIT;10601061if(unquote_c_style(&first, line, &second))1062goto free_and_fail1;10631064/* advance to the first slash */1065 cp =stop_at_slash(first.buf, first.len);1066/* we do not accept absolute paths */1067if(!cp || cp == first.buf)1068goto free_and_fail1;1069strbuf_remove(&first,0, cp +1- first.buf);10701071/*1072 * second points at one past closing dq of name.1073 * find the second name.1074 */1075while((second < line + llen) &&isspace(*second))1076 second++;10771078if(line + llen <= second)1079goto free_and_fail1;1080if(*second =='"') {1081if(unquote_c_style(&sp, second, NULL))1082goto free_and_fail1;1083 cp =stop_at_slash(sp.buf, sp.len);1084if(!cp || cp == sp.buf)1085goto free_and_fail1;1086/* They must match, otherwise ignore */1087if(strcmp(cp +1, first.buf))1088goto free_and_fail1;1089strbuf_release(&sp);1090returnstrbuf_detach(&first, NULL);1091}10921093/* unquoted second */1094 cp =stop_at_slash(second, line + llen - second);1095if(!cp || cp == second)1096goto free_and_fail1;1097 cp++;1098if(line + llen - cp != first.len +1||1099memcmp(first.buf, cp, first.len))1100goto free_and_fail1;1101returnstrbuf_detach(&first, NULL);11021103 free_and_fail1:1104strbuf_release(&first);1105strbuf_release(&sp);1106return NULL;1107}11081109/* unquoted first name */1110 name =stop_at_slash(line, llen);1111if(!name || name == line)1112return NULL;1113 name++;11141115/*1116 * since the first name is unquoted, a dq if exists must be1117 * the beginning of the second name.1118 */1119for(second = name; second < line + llen; second++) {1120if(*second =='"') {1121struct strbuf sp = STRBUF_INIT;1122const char*np;11231124if(unquote_c_style(&sp, second, NULL))1125goto free_and_fail2;11261127 np =stop_at_slash(sp.buf, sp.len);1128if(!np || np == sp.buf)1129goto free_and_fail2;1130 np++;11311132 len = sp.buf + sp.len - np;1133if(len < second - name &&1134!strncmp(np, name, len) &&1135isspace(name[len])) {1136/* Good */1137strbuf_remove(&sp,0, np - sp.buf);1138returnstrbuf_detach(&sp, NULL);1139}11401141 free_and_fail2:1142strbuf_release(&sp);1143return NULL;1144}1145}11461147/*1148 * Accept a name only if it shows up twice, exactly the same1149 * form.1150 */1151 second =strchr(name,'\n');1152if(!second)1153return NULL;1154 line_len = second - name;1155for(len =0; ; len++) {1156switch(name[len]) {1157default:1158continue;1159case'\n':1160return NULL;1161case'\t':case' ':1162 second =stop_at_slash(name + len, line_len - len);1163if(!second)1164return NULL;1165 second++;1166if(second[len] =='\n'&& !strncmp(name, second, len)) {1167returnxmemdupz(name, len);1168}1169}1170}1171}11721173/* Verify that we recognize the lines following a git header */1174static intparse_git_header(char*line,int len,unsigned int size,struct patch *patch)1175{1176unsigned long offset;11771178/* A git diff has explicit new/delete information, so we don't guess */1179 patch->is_new =0;1180 patch->is_delete =0;11811182/*1183 * Some things may not have the old name in the1184 * rest of the headers anywhere (pure mode changes,1185 * or removing or adding empty files), so we get1186 * the default name from the header.1187 */1188 patch->def_name =git_header_name(line, len);1189if(patch->def_name && root) {1190char*s =xmalloc(root_len +strlen(patch->def_name) +1);1191strcpy(s, root);1192strcpy(s + root_len, patch->def_name);1193free(patch->def_name);1194 patch->def_name = s;1195}11961197 line += len;1198 size -= len;1199 linenr++;1200for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) {1201static const struct opentry {1202const char*str;1203int(*fn)(const char*,struct patch *);1204} optable[] = {1205{"@@ -", gitdiff_hdrend },1206{"--- ", gitdiff_oldname },1207{"+++ ", gitdiff_newname },1208{"old mode ", gitdiff_oldmode },1209{"new mode ", gitdiff_newmode },1210{"deleted file mode ", gitdiff_delete },1211{"new file mode ", gitdiff_newfile },1212{"copy from ", gitdiff_copysrc },1213{"copy to ", gitdiff_copydst },1214{"rename old ", gitdiff_renamesrc },1215{"rename new ", gitdiff_renamedst },1216{"rename from ", gitdiff_renamesrc },1217{"rename to ", gitdiff_renamedst },1218{"similarity index ", gitdiff_similarity },1219{"dissimilarity index ", gitdiff_dissimilarity },1220{"index ", gitdiff_index },1221{"", gitdiff_unrecognized },1222};1223int i;12241225 len =linelen(line, size);1226if(!len || line[len-1] !='\n')1227break;1228for(i =0; i <ARRAY_SIZE(optable); i++) {1229const struct opentry *p = optable + i;1230int oplen =strlen(p->str);1231if(len < oplen ||memcmp(p->str, line, oplen))1232continue;1233if(p->fn(line + oplen, patch) <0)1234return offset;1235break;1236}1237}12381239return offset;1240}12411242static intparse_num(const char*line,unsigned long*p)1243{1244char*ptr;12451246if(!isdigit(*line))1247return0;1248*p =strtoul(line, &ptr,10);1249return ptr - line;1250}12511252static intparse_range(const char*line,int len,int offset,const char*expect,1253unsigned long*p1,unsigned long*p2)1254{1255int digits, ex;12561257if(offset <0|| offset >= len)1258return-1;1259 line += offset;1260 len -= offset;12611262 digits =parse_num(line, p1);1263if(!digits)1264return-1;12651266 offset += digits;1267 line += digits;1268 len -= digits;12691270*p2 =1;1271if(*line ==',') {1272 digits =parse_num(line+1, p2);1273if(!digits)1274return-1;12751276 offset += digits+1;1277 line += digits+1;1278 len -= digits+1;1279}12801281 ex =strlen(expect);1282if(ex > len)1283return-1;1284if(memcmp(line, expect, ex))1285return-1;12861287return offset + ex;1288}12891290static voidrecount_diff(char*line,int size,struct fragment *fragment)1291{1292int oldlines =0, newlines =0, ret =0;12931294if(size <1) {1295warning("recount: ignore empty hunk");1296return;1297}12981299for(;;) {1300int len =linelen(line, size);1301 size -= len;1302 line += len;13031304if(size <1)1305break;13061307switch(*line) {1308case' ':case'\n':1309 newlines++;1310/* fall through */1311case'-':1312 oldlines++;1313continue;1314case'+':1315 newlines++;1316continue;1317case'\\':1318continue;1319case'@':1320 ret = size <3||prefixcmp(line,"@@ ");1321break;1322case'd':1323 ret = size <5||prefixcmp(line,"diff ");1324break;1325default:1326 ret = -1;1327break;1328}1329if(ret) {1330warning("recount: unexpected line: %.*s",1331(int)linelen(line, size), line);1332return;1333}1334break;1335}1336 fragment->oldlines = oldlines;1337 fragment->newlines = newlines;1338}13391340/*1341 * Parse a unified diff fragment header of the1342 * form "@@ -a,b +c,d @@"1343 */1344static intparse_fragment_header(char*line,int len,struct fragment *fragment)1345{1346int offset;13471348if(!len || line[len-1] !='\n')1349return-1;13501351/* Figure out the number of lines in a fragment */1352 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1353 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);13541355return offset;1356}13571358static intfind_header(char*line,unsigned long size,int*hdrsize,struct patch *patch)1359{1360unsigned long offset, len;13611362 patch->is_toplevel_relative =0;1363 patch->is_rename = patch->is_copy =0;1364 patch->is_new = patch->is_delete = -1;1365 patch->old_mode = patch->new_mode =0;1366 patch->old_name = patch->new_name = NULL;1367for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) {1368unsigned long nextlen;13691370 len =linelen(line, size);1371if(!len)1372break;13731374/* Testing this early allows us to take a few shortcuts.. */1375if(len <6)1376continue;13771378/*1379 * Make sure we don't find any unconnected patch fragments.1380 * That's a sign that we didn't find a header, and that a1381 * patch has become corrupted/broken up.1382 */1383if(!memcmp("@@ -", line,4)) {1384struct fragment dummy;1385if(parse_fragment_header(line, len, &dummy) <0)1386continue;1387die("patch fragment without header at line%d: %.*s",1388 linenr, (int)len-1, line);1389}13901391if(size < len +6)1392break;13931394/*1395 * Git patch? It might not have a real patch, just a rename1396 * or mode change, so we handle that specially1397 */1398if(!memcmp("diff --git ", line,11)) {1399int git_hdr_len =parse_git_header(line, len, size, patch);1400if(git_hdr_len <= len)1401continue;1402if(!patch->old_name && !patch->new_name) {1403if(!patch->def_name)1404die("git diff header lacks filename information when removing "1405"%dleading pathname components (line%d)", p_value, linenr);1406 patch->old_name = patch->new_name = patch->def_name;1407}1408 patch->is_toplevel_relative =1;1409*hdrsize = git_hdr_len;1410return offset;1411}14121413/* --- followed by +++ ? */1414if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1415continue;14161417/*1418 * We only accept unified patches, so we want it to1419 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1420 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1421 */1422 nextlen =linelen(line + len, size - len);1423if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1424continue;14251426/* Ok, we'll consider it a patch */1427parse_traditional_patch(line, line+len, patch);1428*hdrsize = len + nextlen;1429 linenr +=2;1430return offset;1431}1432return-1;1433}14341435static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1436{1437char*err;14381439if(!result)1440return;14411442 whitespace_error++;1443if(squelch_whitespace_errors &&1444 squelch_whitespace_errors < whitespace_error)1445return;14461447 err =whitespace_error_string(result);1448fprintf(stderr,"%s:%d:%s.\n%.*s\n",1449 patch_input_file, linenr, err, len, line);1450free(err);1451}14521453static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1454{1455unsigned result =ws_check(line +1, len -1, ws_rule);14561457record_ws_error(result, line +1, len -2, linenr);1458}14591460/*1461 * Parse a unified diff. Note that this really needs to parse each1462 * fragment separately, since the only way to know the difference1463 * between a "---" that is part of a patch, and a "---" that starts1464 * the next patch is to look at the line counts..1465 */1466static intparse_fragment(char*line,unsigned long size,1467struct patch *patch,struct fragment *fragment)1468{1469int added, deleted;1470int len =linelen(line, size), offset;1471unsigned long oldlines, newlines;1472unsigned long leading, trailing;14731474 offset =parse_fragment_header(line, len, fragment);1475if(offset <0)1476return-1;1477if(offset >0&& patch->recount)1478recount_diff(line + offset, size - offset, fragment);1479 oldlines = fragment->oldlines;1480 newlines = fragment->newlines;1481 leading =0;1482 trailing =0;14831484/* Parse the thing.. */1485 line += len;1486 size -= len;1487 linenr++;1488 added = deleted =0;1489for(offset = len;14900< size;1491 offset += len, size -= len, line += len, linenr++) {1492if(!oldlines && !newlines)1493break;1494 len =linelen(line, size);1495if(!len || line[len-1] !='\n')1496return-1;1497switch(*line) {1498default:1499return-1;1500case'\n':/* newer GNU diff, an empty context line */1501case' ':1502 oldlines--;1503 newlines--;1504if(!deleted && !added)1505 leading++;1506 trailing++;1507break;1508case'-':1509if(apply_in_reverse &&1510 ws_error_action != nowarn_ws_error)1511check_whitespace(line, len, patch->ws_rule);1512 deleted++;1513 oldlines--;1514 trailing =0;1515break;1516case'+':1517if(!apply_in_reverse &&1518 ws_error_action != nowarn_ws_error)1519check_whitespace(line, len, patch->ws_rule);1520 added++;1521 newlines--;1522 trailing =0;1523break;15241525/*1526 * We allow "\ No newline at end of file". Depending1527 * on locale settings when the patch was produced we1528 * don't know what this line looks like. The only1529 * thing we do know is that it begins with "\ ".1530 * Checking for 12 is just for sanity check -- any1531 * l10n of "\ No newline..." is at least that long.1532 */1533case'\\':1534if(len <12||memcmp(line,"\\",2))1535return-1;1536break;1537}1538}1539if(oldlines || newlines)1540return-1;1541 fragment->leading = leading;1542 fragment->trailing = trailing;15431544/*1545 * If a fragment ends with an incomplete line, we failed to include1546 * it in the above loop because we hit oldlines == newlines == 01547 * before seeing it.1548 */1549if(12< size && !memcmp(line,"\\",2))1550 offset +=linelen(line, size);15511552 patch->lines_added += added;1553 patch->lines_deleted += deleted;15541555if(0< patch->is_new && oldlines)1556returnerror("new file depends on old contents");1557if(0< patch->is_delete && newlines)1558returnerror("deleted file still has contents");1559return offset;1560}15611562static intparse_single_patch(char*line,unsigned long size,struct patch *patch)1563{1564unsigned long offset =0;1565unsigned long oldlines =0, newlines =0, context =0;1566struct fragment **fragp = &patch->fragments;15671568while(size >4&& !memcmp(line,"@@ -",4)) {1569struct fragment *fragment;1570int len;15711572 fragment =xcalloc(1,sizeof(*fragment));1573 fragment->linenr = linenr;1574 len =parse_fragment(line, size, patch, fragment);1575if(len <=0)1576die("corrupt patch at line%d", linenr);1577 fragment->patch = line;1578 fragment->size = len;1579 oldlines += fragment->oldlines;1580 newlines += fragment->newlines;1581 context += fragment->leading + fragment->trailing;15821583*fragp = fragment;1584 fragp = &fragment->next;15851586 offset += len;1587 line += len;1588 size -= len;1589}15901591/*1592 * If something was removed (i.e. we have old-lines) it cannot1593 * be creation, and if something was added it cannot be1594 * deletion. However, the reverse is not true; --unified=01595 * patches that only add are not necessarily creation even1596 * though they do not have any old lines, and ones that only1597 * delete are not necessarily deletion.1598 *1599 * Unfortunately, a real creation/deletion patch do _not_ have1600 * any context line by definition, so we cannot safely tell it1601 * apart with --unified=0 insanity. At least if the patch has1602 * more than one hunk it is not creation or deletion.1603 */1604if(patch->is_new <0&&1605(oldlines || (patch->fragments && patch->fragments->next)))1606 patch->is_new =0;1607if(patch->is_delete <0&&1608(newlines || (patch->fragments && patch->fragments->next)))1609 patch->is_delete =0;16101611if(0< patch->is_new && oldlines)1612die("new file%sdepends on old contents", patch->new_name);1613if(0< patch->is_delete && newlines)1614die("deleted file%sstill has contents", patch->old_name);1615if(!patch->is_delete && !newlines && context)1616fprintf(stderr,"** warning: file%sbecomes empty but "1617"is not deleted\n", patch->new_name);16181619return offset;1620}16211622staticinlineintmetadata_changes(struct patch *patch)1623{1624return patch->is_rename >0||1625 patch->is_copy >0||1626 patch->is_new >0||1627 patch->is_delete ||1628(patch->old_mode && patch->new_mode &&1629 patch->old_mode != patch->new_mode);1630}16311632static char*inflate_it(const void*data,unsigned long size,1633unsigned long inflated_size)1634{1635 z_stream stream;1636void*out;1637int st;16381639memset(&stream,0,sizeof(stream));16401641 stream.next_in = (unsigned char*)data;1642 stream.avail_in = size;1643 stream.next_out = out =xmalloc(inflated_size);1644 stream.avail_out = inflated_size;1645git_inflate_init(&stream);1646 st =git_inflate(&stream, Z_FINISH);1647git_inflate_end(&stream);1648if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1649free(out);1650return NULL;1651}1652return out;1653}16541655static struct fragment *parse_binary_hunk(char**buf_p,1656unsigned long*sz_p,1657int*status_p,1658int*used_p)1659{1660/*1661 * Expect a line that begins with binary patch method ("literal"1662 * or "delta"), followed by the length of data before deflating.1663 * a sequence of 'length-byte' followed by base-85 encoded data1664 * should follow, terminated by a newline.1665 *1666 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1667 * and we would limit the patch line to 66 characters,1668 * so one line can fit up to 13 groups that would decode1669 * to 52 bytes max. The length byte 'A'-'Z' corresponds1670 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1671 */1672int llen, used;1673unsigned long size = *sz_p;1674char*buffer = *buf_p;1675int patch_method;1676unsigned long origlen;1677char*data = NULL;1678int hunk_size =0;1679struct fragment *frag;16801681 llen =linelen(buffer, size);1682 used = llen;16831684*status_p =0;16851686if(!prefixcmp(buffer,"delta ")) {1687 patch_method = BINARY_DELTA_DEFLATED;1688 origlen =strtoul(buffer +6, NULL,10);1689}1690else if(!prefixcmp(buffer,"literal ")) {1691 patch_method = BINARY_LITERAL_DEFLATED;1692 origlen =strtoul(buffer +8, NULL,10);1693}1694else1695return NULL;16961697 linenr++;1698 buffer += llen;1699while(1) {1700int byte_length, max_byte_length, newsize;1701 llen =linelen(buffer, size);1702 used += llen;1703 linenr++;1704if(llen ==1) {1705/* consume the blank line */1706 buffer++;1707 size--;1708break;1709}1710/*1711 * Minimum line is "A00000\n" which is 7-byte long,1712 * and the line length must be multiple of 5 plus 2.1713 */1714if((llen <7) || (llen-2) %5)1715goto corrupt;1716 max_byte_length = (llen -2) /5*4;1717 byte_length = *buffer;1718if('A'<= byte_length && byte_length <='Z')1719 byte_length = byte_length -'A'+1;1720else if('a'<= byte_length && byte_length <='z')1721 byte_length = byte_length -'a'+27;1722else1723goto corrupt;1724/* if the input length was not multiple of 4, we would1725 * have filler at the end but the filler should never1726 * exceed 3 bytes1727 */1728if(max_byte_length < byte_length ||1729 byte_length <= max_byte_length -4)1730goto corrupt;1731 newsize = hunk_size + byte_length;1732 data =xrealloc(data, newsize);1733if(decode_85(data + hunk_size, buffer +1, byte_length))1734goto corrupt;1735 hunk_size = newsize;1736 buffer += llen;1737 size -= llen;1738}17391740 frag =xcalloc(1,sizeof(*frag));1741 frag->patch =inflate_it(data, hunk_size, origlen);1742if(!frag->patch)1743goto corrupt;1744free(data);1745 frag->size = origlen;1746*buf_p = buffer;1747*sz_p = size;1748*used_p = used;1749 frag->binary_patch_method = patch_method;1750return frag;17511752 corrupt:1753free(data);1754*status_p = -1;1755error("corrupt binary patch at line%d: %.*s",1756 linenr-1, llen-1, buffer);1757return NULL;1758}17591760static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1761{1762/*1763 * We have read "GIT binary patch\n"; what follows is a line1764 * that says the patch method (currently, either "literal" or1765 * "delta") and the length of data before deflating; a1766 * sequence of 'length-byte' followed by base-85 encoded data1767 * follows.1768 *1769 * When a binary patch is reversible, there is another binary1770 * hunk in the same format, starting with patch method (either1771 * "literal" or "delta") with the length of data, and a sequence1772 * of length-byte + base-85 encoded data, terminated with another1773 * empty line. This data, when applied to the postimage, produces1774 * the preimage.1775 */1776struct fragment *forward;1777struct fragment *reverse;1778int status;1779int used, used_1;17801781 forward =parse_binary_hunk(&buffer, &size, &status, &used);1782if(!forward && !status)1783/* there has to be one hunk (forward hunk) */1784returnerror("unrecognized binary patch at line%d", linenr-1);1785if(status)1786/* otherwise we already gave an error message */1787return status;17881789 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1790if(reverse)1791 used += used_1;1792else if(status) {1793/*1794 * Not having reverse hunk is not an error, but having1795 * a corrupt reverse hunk is.1796 */1797free((void*) forward->patch);1798free(forward);1799return status;1800}1801 forward->next = reverse;1802 patch->fragments = forward;1803 patch->is_binary =1;1804return used;1805}18061807static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1808{1809int hdrsize, patchsize;1810int offset =find_header(buffer, size, &hdrsize, patch);18111812if(offset <0)1813return offset;18141815 patch->ws_rule =whitespace_rule(patch->new_name1816? patch->new_name1817: patch->old_name);18181819 patchsize =parse_single_patch(buffer + offset + hdrsize,1820 size - offset - hdrsize, patch);18211822if(!patchsize) {1823static const char*binhdr[] = {1824"Binary files ",1825"Files ",1826 NULL,1827};1828static const char git_binary[] ="GIT binary patch\n";1829int i;1830int hd = hdrsize + offset;1831unsigned long llen =linelen(buffer + hd, size - hd);18321833if(llen ==sizeof(git_binary) -1&&1834!memcmp(git_binary, buffer + hd, llen)) {1835int used;1836 linenr++;1837 used =parse_binary(buffer + hd + llen,1838 size - hd - llen, patch);1839if(used)1840 patchsize = used + llen;1841else1842 patchsize =0;1843}1844else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1845for(i =0; binhdr[i]; i++) {1846int len =strlen(binhdr[i]);1847if(len < size - hd &&1848!memcmp(binhdr[i], buffer + hd, len)) {1849 linenr++;1850 patch->is_binary =1;1851 patchsize = llen;1852break;1853}1854}1855}18561857/* Empty patch cannot be applied if it is a text patch1858 * without metadata change. A binary patch appears1859 * empty to us here.1860 */1861if((apply || check) &&1862(!patch->is_binary && !metadata_changes(patch)))1863die("patch with only garbage at line%d", linenr);1864}18651866return offset + hdrsize + patchsize;1867}18681869#define swap(a,b) myswap((a),(b),sizeof(a))18701871#define myswap(a, b, size) do { \1872 unsigned char mytmp[size]; \1873 memcpy(mytmp, &a, size); \1874 memcpy(&a, &b, size); \1875 memcpy(&b, mytmp, size); \1876} while (0)18771878static voidreverse_patches(struct patch *p)1879{1880for(; p; p = p->next) {1881struct fragment *frag = p->fragments;18821883swap(p->new_name, p->old_name);1884swap(p->new_mode, p->old_mode);1885swap(p->is_new, p->is_delete);1886swap(p->lines_added, p->lines_deleted);1887swap(p->old_sha1_prefix, p->new_sha1_prefix);18881889for(; frag; frag = frag->next) {1890swap(frag->newpos, frag->oldpos);1891swap(frag->newlines, frag->oldlines);1892}1893}1894}18951896static const char pluses[] =1897"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";1898static const char minuses[]=1899"----------------------------------------------------------------------";19001901static voidshow_stats(struct patch *patch)1902{1903struct strbuf qname = STRBUF_INIT;1904char*cp = patch->new_name ? patch->new_name : patch->old_name;1905int max, add, del;19061907quote_c_style(cp, &qname, NULL,0);19081909/*1910 * "scale" the filename1911 */1912 max = max_len;1913if(max >50)1914 max =50;19151916if(qname.len > max) {1917 cp =strchr(qname.buf + qname.len +3- max,'/');1918if(!cp)1919 cp = qname.buf + qname.len +3- max;1920strbuf_splice(&qname,0, cp - qname.buf,"...",3);1921}19221923if(patch->is_binary) {1924printf(" %-*s | Bin\n", max, qname.buf);1925strbuf_release(&qname);1926return;1927}19281929printf(" %-*s |", max, qname.buf);1930strbuf_release(&qname);19311932/*1933 * scale the add/delete1934 */1935 max = max + max_change >70?70- max : max_change;1936 add = patch->lines_added;1937 del = patch->lines_deleted;19381939if(max_change >0) {1940int total = ((add + del) * max + max_change /2) / max_change;1941 add = (add * max + max_change /2) / max_change;1942 del = total - add;1943}1944printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,1945 add, pluses, del, minuses);1946}19471948static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)1949{1950switch(st->st_mode & S_IFMT) {1951case S_IFLNK:1952if(strbuf_readlink(buf, path, st->st_size) <0)1953returnerror("unable to read symlink%s", path);1954return0;1955case S_IFREG:1956if(strbuf_read_file(buf, path, st->st_size) != st->st_size)1957returnerror("unable to open or read%s", path);1958convert_to_git(path, buf->buf, buf->len, buf,0);1959return0;1960default:1961return-1;1962}1963}19641965/*1966 * Update the preimage, and the common lines in postimage,1967 * from buffer buf of length len. If postlen is 0 the postimage1968 * is updated in place, otherwise it's updated on a new buffer1969 * of length postlen1970 */19711972static voidupdate_pre_post_images(struct image *preimage,1973struct image *postimage,1974char*buf,1975size_t len,size_t postlen)1976{1977int i, ctx;1978char*new, *old, *fixed;1979struct image fixed_preimage;19801981/*1982 * Update the preimage with whitespace fixes. Note that we1983 * are not losing preimage->buf -- apply_one_fragment() will1984 * free "oldlines".1985 */1986prepare_image(&fixed_preimage, buf, len,1);1987assert(fixed_preimage.nr == preimage->nr);1988for(i =0; i < preimage->nr; i++)1989 fixed_preimage.line[i].flag = preimage->line[i].flag;1990free(preimage->line_allocated);1991*preimage = fixed_preimage;19921993/*1994 * Adjust the common context lines in postimage. This can be1995 * done in-place when we are just doing whitespace fixing,1996 * which does not make the string grow, but needs a new buffer1997 * when ignoring whitespace causes the update, since in this case1998 * we could have e.g. tabs converted to multiple spaces.1999 * We trust the caller to tell us if the update can be done2000 * in place (postlen==0) or not.2001 */2002 old = postimage->buf;2003if(postlen)2004new= postimage->buf =xmalloc(postlen);2005else2006new= old;2007 fixed = preimage->buf;2008for(i = ctx =0; i < postimage->nr; i++) {2009size_t len = postimage->line[i].len;2010if(!(postimage->line[i].flag & LINE_COMMON)) {2011/* an added line -- no counterparts in preimage */2012memmove(new, old, len);2013 old += len;2014new+= len;2015continue;2016}20172018/* a common context -- skip it in the original postimage */2019 old += len;20202021/* and find the corresponding one in the fixed preimage */2022while(ctx < preimage->nr &&2023!(preimage->line[ctx].flag & LINE_COMMON)) {2024 fixed += preimage->line[ctx].len;2025 ctx++;2026}2027if(preimage->nr <= ctx)2028die("oops");20292030/* and copy it in, while fixing the line length */2031 len = preimage->line[ctx].len;2032memcpy(new, fixed, len);2033new+= len;2034 fixed += len;2035 postimage->line[i].len = len;2036 ctx++;2037}20382039/* Fix the length of the whole thing */2040 postimage->len =new- postimage->buf;2041}20422043static intmatch_fragment(struct image *img,2044struct image *preimage,2045struct image *postimage,2046unsigned longtry,2047int try_lno,2048unsigned ws_rule,2049int match_beginning,int match_end)2050{2051int i;2052char*fixed_buf, *buf, *orig, *target;2053struct strbuf fixed;2054size_t fixed_len;2055int preimage_limit;20562057if(preimage->nr + try_lno <= img->nr) {2058/*2059 * The hunk falls within the boundaries of img.2060 */2061 preimage_limit = preimage->nr;2062if(match_end && (preimage->nr + try_lno != img->nr))2063return0;2064}else if(ws_error_action == correct_ws_error &&2065(ws_rule & WS_BLANK_AT_EOF)) {2066/*2067 * This hunk extends beyond the end of img, and we are2068 * removing blank lines at the end of the file. This2069 * many lines from the beginning of the preimage must2070 * match with img, and the remainder of the preimage2071 * must be blank.2072 */2073 preimage_limit = img->nr - try_lno;2074}else{2075/*2076 * The hunk extends beyond the end of the img and2077 * we are not removing blanks at the end, so we2078 * should reject the hunk at this position.2079 */2080return0;2081}20822083if(match_beginning && try_lno)2084return0;20852086/* Quick hash check */2087for(i =0; i < preimage_limit; i++)2088if(preimage->line[i].hash != img->line[try_lno + i].hash)2089return0;20902091if(preimage_limit == preimage->nr) {2092/*2093 * Do we have an exact match? If we were told to match2094 * at the end, size must be exactly at try+fragsize,2095 * otherwise try+fragsize must be still within the preimage,2096 * and either case, the old piece should match the preimage2097 * exactly.2098 */2099if((match_end2100? (try+ preimage->len == img->len)2101: (try+ preimage->len <= img->len)) &&2102!memcmp(img->buf +try, preimage->buf, preimage->len))2103return1;2104}else{2105/*2106 * The preimage extends beyond the end of img, so2107 * there cannot be an exact match.2108 *2109 * There must be one non-blank context line that match2110 * a line before the end of img.2111 */2112char*buf_end;21132114 buf = preimage->buf;2115 buf_end = buf;2116for(i =0; i < preimage_limit; i++)2117 buf_end += preimage->line[i].len;21182119for( ; buf < buf_end; buf++)2120if(!isspace(*buf))2121break;2122if(buf == buf_end)2123return0;2124}21252126/*2127 * No exact match. If we are ignoring whitespace, run a line-by-line2128 * fuzzy matching. We collect all the line length information because2129 * we need it to adjust whitespace if we match.2130 */2131if(ws_ignore_action == ignore_ws_change) {2132size_t imgoff =0;2133size_t preoff =0;2134size_t postlen = postimage->len;2135size_t extra_chars;2136char*preimage_eof;2137char*preimage_end;2138for(i =0; i < preimage_limit; i++) {2139size_t prelen = preimage->line[i].len;2140size_t imglen = img->line[try_lno+i].len;21412142if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2143 preimage->buf + preoff, prelen))2144return0;2145if(preimage->line[i].flag & LINE_COMMON)2146 postlen += imglen - prelen;2147 imgoff += imglen;2148 preoff += prelen;2149}21502151/*2152 * Ok, the preimage matches with whitespace fuzz.2153 *2154 * imgoff now holds the true length of the target that2155 * matches the preimage before the end of the file.2156 *2157 * Count the number of characters in the preimage that fall2158 * beyond the end of the file and make sure that all of them2159 * are whitespace characters. (This can only happen if2160 * we are removing blank lines at the end of the file.)2161 */2162 buf = preimage_eof = preimage->buf + preoff;2163for( ; i < preimage->nr; i++)2164 preoff += preimage->line[i].len;2165 preimage_end = preimage->buf + preoff;2166for( ; buf < preimage_end; buf++)2167if(!isspace(*buf))2168return0;21692170/*2171 * Update the preimage and the common postimage context2172 * lines to use the same whitespace as the target.2173 * If whitespace is missing in the target (i.e.2174 * if the preimage extends beyond the end of the file),2175 * use the whitespace from the preimage.2176 */2177 extra_chars = preimage_end - preimage_eof;2178strbuf_init(&fixed, imgoff + extra_chars);2179strbuf_add(&fixed, img->buf +try, imgoff);2180strbuf_add(&fixed, preimage_eof, extra_chars);2181 fixed_buf =strbuf_detach(&fixed, &fixed_len);2182update_pre_post_images(preimage, postimage,2183 fixed_buf, fixed_len, postlen);2184return1;2185}21862187if(ws_error_action != correct_ws_error)2188return0;21892190/*2191 * The hunk does not apply byte-by-byte, but the hash says2192 * it might with whitespace fuzz. We haven't been asked to2193 * ignore whitespace, we were asked to correct whitespace2194 * errors, so let's try matching after whitespace correction.2195 *2196 * The preimage may extend beyond the end of the file,2197 * but in this loop we will only handle the part of the2198 * preimage that falls within the file.2199 */2200strbuf_init(&fixed, preimage->len +1);2201 orig = preimage->buf;2202 target = img->buf +try;2203for(i =0; i < preimage_limit; i++) {2204size_t oldlen = preimage->line[i].len;2205size_t tgtlen = img->line[try_lno + i].len;2206size_t fixstart = fixed.len;2207struct strbuf tgtfix;2208int match;22092210/* Try fixing the line in the preimage */2211ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);22122213/* Try fixing the line in the target */2214strbuf_init(&tgtfix, tgtlen);2215ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);22162217/*2218 * If they match, either the preimage was based on2219 * a version before our tree fixed whitespace breakage,2220 * or we are lacking a whitespace-fix patch the tree2221 * the preimage was based on already had (i.e. target2222 * has whitespace breakage, the preimage doesn't).2223 * In either case, we are fixing the whitespace breakages2224 * so we might as well take the fix together with their2225 * real change.2226 */2227 match = (tgtfix.len == fixed.len - fixstart &&2228!memcmp(tgtfix.buf, fixed.buf + fixstart,2229 fixed.len - fixstart));22302231strbuf_release(&tgtfix);2232if(!match)2233goto unmatch_exit;22342235 orig += oldlen;2236 target += tgtlen;2237}223822392240/*2241 * Now handle the lines in the preimage that falls beyond the2242 * end of the file (if any). They will only match if they are2243 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2244 * false).2245 */2246for( ; i < preimage->nr; i++) {2247size_t fixstart = fixed.len;/* start of the fixed preimage */2248size_t oldlen = preimage->line[i].len;2249int j;22502251/* Try fixing the line in the preimage */2252ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);22532254for(j = fixstart; j < fixed.len; j++)2255if(!isspace(fixed.buf[j]))2256goto unmatch_exit;22572258 orig += oldlen;2259}22602261/*2262 * Yes, the preimage is based on an older version that still2263 * has whitespace breakages unfixed, and fixing them makes the2264 * hunk match. Update the context lines in the postimage.2265 */2266 fixed_buf =strbuf_detach(&fixed, &fixed_len);2267update_pre_post_images(preimage, postimage,2268 fixed_buf, fixed_len,0);2269return1;22702271 unmatch_exit:2272strbuf_release(&fixed);2273return0;2274}22752276static intfind_pos(struct image *img,2277struct image *preimage,2278struct image *postimage,2279int line,2280unsigned ws_rule,2281int match_beginning,int match_end)2282{2283int i;2284unsigned long backwards, forwards,try;2285int backwards_lno, forwards_lno, try_lno;22862287/*2288 * If match_beginning or match_end is specified, there is no2289 * point starting from a wrong line that will never match and2290 * wander around and wait for a match at the specified end.2291 */2292if(match_beginning)2293 line =0;2294else if(match_end)2295 line = img->nr - preimage->nr;22962297/*2298 * Because the comparison is unsigned, the following test2299 * will also take care of a negative line number that can2300 * result when match_end and preimage is larger than the target.2301 */2302if((size_t) line > img->nr)2303 line = img->nr;23042305try=0;2306for(i =0; i < line; i++)2307try+= img->line[i].len;23082309/*2310 * There's probably some smart way to do this, but I'll leave2311 * that to the smart and beautiful people. I'm simple and stupid.2312 */2313 backwards =try;2314 backwards_lno = line;2315 forwards =try;2316 forwards_lno = line;2317 try_lno = line;23182319for(i =0; ; i++) {2320if(match_fragment(img, preimage, postimage,2321try, try_lno, ws_rule,2322 match_beginning, match_end))2323return try_lno;23242325 again:2326if(backwards_lno ==0&& forwards_lno == img->nr)2327break;23282329if(i &1) {2330if(backwards_lno ==0) {2331 i++;2332goto again;2333}2334 backwards_lno--;2335 backwards -= img->line[backwards_lno].len;2336try= backwards;2337 try_lno = backwards_lno;2338}else{2339if(forwards_lno == img->nr) {2340 i++;2341goto again;2342}2343 forwards += img->line[forwards_lno].len;2344 forwards_lno++;2345try= forwards;2346 try_lno = forwards_lno;2347}23482349}2350return-1;2351}23522353static voidremove_first_line(struct image *img)2354{2355 img->buf += img->line[0].len;2356 img->len -= img->line[0].len;2357 img->line++;2358 img->nr--;2359}23602361static voidremove_last_line(struct image *img)2362{2363 img->len -= img->line[--img->nr].len;2364}23652366static voidupdate_image(struct image *img,2367int applied_pos,2368struct image *preimage,2369struct image *postimage)2370{2371/*2372 * remove the copy of preimage at offset in img2373 * and replace it with postimage2374 */2375int i, nr;2376size_t remove_count, insert_count, applied_at =0;2377char*result;2378int preimage_limit;23792380/*2381 * If we are removing blank lines at the end of img,2382 * the preimage may extend beyond the end.2383 * If that is the case, we must be careful only to2384 * remove the part of the preimage that falls within2385 * the boundaries of img. Initialize preimage_limit2386 * to the number of lines in the preimage that falls2387 * within the boundaries.2388 */2389 preimage_limit = preimage->nr;2390if(preimage_limit > img->nr - applied_pos)2391 preimage_limit = img->nr - applied_pos;23922393for(i =0; i < applied_pos; i++)2394 applied_at += img->line[i].len;23952396 remove_count =0;2397for(i =0; i < preimage_limit; i++)2398 remove_count += img->line[applied_pos + i].len;2399 insert_count = postimage->len;24002401/* Adjust the contents */2402 result =xmalloc(img->len + insert_count - remove_count +1);2403memcpy(result, img->buf, applied_at);2404memcpy(result + applied_at, postimage->buf, postimage->len);2405memcpy(result + applied_at + postimage->len,2406 img->buf + (applied_at + remove_count),2407 img->len - (applied_at + remove_count));2408free(img->buf);2409 img->buf = result;2410 img->len += insert_count - remove_count;2411 result[img->len] ='\0';24122413/* Adjust the line table */2414 nr = img->nr + postimage->nr - preimage_limit;2415if(preimage_limit < postimage->nr) {2416/*2417 * NOTE: this knows that we never call remove_first_line()2418 * on anything other than pre/post image.2419 */2420 img->line =xrealloc(img->line, nr *sizeof(*img->line));2421 img->line_allocated = img->line;2422}2423if(preimage_limit != postimage->nr)2424memmove(img->line + applied_pos + postimage->nr,2425 img->line + applied_pos + preimage_limit,2426(img->nr - (applied_pos + preimage_limit)) *2427sizeof(*img->line));2428memcpy(img->line + applied_pos,2429 postimage->line,2430 postimage->nr *sizeof(*img->line));2431 img->nr = nr;2432}24332434static intapply_one_fragment(struct image *img,struct fragment *frag,2435int inaccurate_eof,unsigned ws_rule)2436{2437int match_beginning, match_end;2438const char*patch = frag->patch;2439int size = frag->size;2440char*old, *oldlines;2441struct strbuf newlines;2442int new_blank_lines_at_end =0;2443unsigned long leading, trailing;2444int pos, applied_pos;2445struct image preimage;2446struct image postimage;24472448memset(&preimage,0,sizeof(preimage));2449memset(&postimage,0,sizeof(postimage));2450 oldlines =xmalloc(size);2451strbuf_init(&newlines, size);24522453 old = oldlines;2454while(size >0) {2455char first;2456int len =linelen(patch, size);2457int plen;2458int added_blank_line =0;2459int is_blank_context =0;2460size_t start;24612462if(!len)2463break;24642465/*2466 * "plen" is how much of the line we should use for2467 * the actual patch data. Normally we just remove the2468 * first character on the line, but if the line is2469 * followed by "\ No newline", then we also remove the2470 * last one (which is the newline, of course).2471 */2472 plen = len -1;2473if(len < size && patch[len] =='\\')2474 plen--;2475 first = *patch;2476if(apply_in_reverse) {2477if(first =='-')2478 first ='+';2479else if(first =='+')2480 first ='-';2481}24822483switch(first) {2484case'\n':2485/* Newer GNU diff, empty context line */2486if(plen <0)2487/* ... followed by '\No newline'; nothing */2488break;2489*old++ ='\n';2490strbuf_addch(&newlines,'\n');2491add_line_info(&preimage,"\n",1, LINE_COMMON);2492add_line_info(&postimage,"\n",1, LINE_COMMON);2493 is_blank_context =1;2494break;2495case' ':2496if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2497ws_blank_line(patch +1, plen, ws_rule))2498 is_blank_context =1;2499case'-':2500memcpy(old, patch +1, plen);2501add_line_info(&preimage, old, plen,2502(first ==' '? LINE_COMMON :0));2503 old += plen;2504if(first =='-')2505break;2506/* Fall-through for ' ' */2507case'+':2508/* --no-add does not add new lines */2509if(first =='+'&& no_add)2510break;25112512 start = newlines.len;2513if(first !='+'||2514!whitespace_error ||2515 ws_error_action != correct_ws_error) {2516strbuf_add(&newlines, patch +1, plen);2517}2518else{2519ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2520}2521add_line_info(&postimage, newlines.buf + start, newlines.len - start,2522(first =='+'?0: LINE_COMMON));2523if(first =='+'&&2524(ws_rule & WS_BLANK_AT_EOF) &&2525ws_blank_line(patch +1, plen, ws_rule))2526 added_blank_line =1;2527break;2528case'@':case'\\':2529/* Ignore it, we already handled it */2530break;2531default:2532if(apply_verbosely)2533error("invalid start of line: '%c'", first);2534return-1;2535}2536if(added_blank_line)2537 new_blank_lines_at_end++;2538else if(is_blank_context)2539;2540else2541 new_blank_lines_at_end =0;2542 patch += len;2543 size -= len;2544}2545if(inaccurate_eof &&2546 old > oldlines && old[-1] =='\n'&&2547 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2548 old--;2549strbuf_setlen(&newlines, newlines.len -1);2550}25512552 leading = frag->leading;2553 trailing = frag->trailing;25542555/*2556 * A hunk to change lines at the beginning would begin with2557 * @@ -1,L +N,M @@2558 * but we need to be careful. -U0 that inserts before the second2559 * line also has this pattern.2560 *2561 * And a hunk to add to an empty file would begin with2562 * @@ -0,0 +N,M @@2563 *2564 * In other words, a hunk that is (frag->oldpos <= 1) with or2565 * without leading context must match at the beginning.2566 */2567 match_beginning = (!frag->oldpos ||2568(frag->oldpos ==1&& !unidiff_zero));25692570/*2571 * A hunk without trailing lines must match at the end.2572 * However, we simply cannot tell if a hunk must match end2573 * from the lack of trailing lines if the patch was generated2574 * with unidiff without any context.2575 */2576 match_end = !unidiff_zero && !trailing;25772578 pos = frag->newpos ? (frag->newpos -1) :0;2579 preimage.buf = oldlines;2580 preimage.len = old - oldlines;2581 postimage.buf = newlines.buf;2582 postimage.len = newlines.len;2583 preimage.line = preimage.line_allocated;2584 postimage.line = postimage.line_allocated;25852586for(;;) {25872588 applied_pos =find_pos(img, &preimage, &postimage, pos,2589 ws_rule, match_beginning, match_end);25902591if(applied_pos >=0)2592break;25932594/* Am I at my context limits? */2595if((leading <= p_context) && (trailing <= p_context))2596break;2597if(match_beginning || match_end) {2598 match_beginning = match_end =0;2599continue;2600}26012602/*2603 * Reduce the number of context lines; reduce both2604 * leading and trailing if they are equal otherwise2605 * just reduce the larger context.2606 */2607if(leading >= trailing) {2608remove_first_line(&preimage);2609remove_first_line(&postimage);2610 pos--;2611 leading--;2612}2613if(trailing > leading) {2614remove_last_line(&preimage);2615remove_last_line(&postimage);2616 trailing--;2617}2618}26192620if(applied_pos >=0) {2621if(new_blank_lines_at_end &&2622 preimage.nr + applied_pos >= img->nr &&2623(ws_rule & WS_BLANK_AT_EOF) &&2624 ws_error_action != nowarn_ws_error) {2625record_ws_error(WS_BLANK_AT_EOF,"+",1, frag->linenr);2626if(ws_error_action == correct_ws_error) {2627while(new_blank_lines_at_end--)2628remove_last_line(&postimage);2629}2630/*2631 * We would want to prevent write_out_results()2632 * from taking place in apply_patch() that follows2633 * the callchain led us here, which is:2634 * apply_patch->check_patch_list->check_patch->2635 * apply_data->apply_fragments->apply_one_fragment2636 */2637if(ws_error_action == die_on_ws_error)2638 apply =0;2639}26402641/*2642 * Warn if it was necessary to reduce the number2643 * of context lines.2644 */2645if((leading != frag->leading) ||2646(trailing != frag->trailing))2647fprintf(stderr,"Context reduced to (%ld/%ld)"2648" to apply fragment at%d\n",2649 leading, trailing, applied_pos+1);2650update_image(img, applied_pos, &preimage, &postimage);2651}else{2652if(apply_verbosely)2653error("while searching for:\n%.*s",2654(int)(old - oldlines), oldlines);2655}26562657free(oldlines);2658strbuf_release(&newlines);2659free(preimage.line_allocated);2660free(postimage.line_allocated);26612662return(applied_pos <0);2663}26642665static intapply_binary_fragment(struct image *img,struct patch *patch)2666{2667struct fragment *fragment = patch->fragments;2668unsigned long len;2669void*dst;26702671if(!fragment)2672returnerror("missing binary patch data for '%s'",2673 patch->new_name ?2674 patch->new_name :2675 patch->old_name);26762677/* Binary patch is irreversible without the optional second hunk */2678if(apply_in_reverse) {2679if(!fragment->next)2680returnerror("cannot reverse-apply a binary patch "2681"without the reverse hunk to '%s'",2682 patch->new_name2683? patch->new_name : patch->old_name);2684 fragment = fragment->next;2685}2686switch(fragment->binary_patch_method) {2687case BINARY_DELTA_DEFLATED:2688 dst =patch_delta(img->buf, img->len, fragment->patch,2689 fragment->size, &len);2690if(!dst)2691return-1;2692clear_image(img);2693 img->buf = dst;2694 img->len = len;2695return0;2696case BINARY_LITERAL_DEFLATED:2697clear_image(img);2698 img->len = fragment->size;2699 img->buf =xmalloc(img->len+1);2700memcpy(img->buf, fragment->patch, img->len);2701 img->buf[img->len] ='\0';2702return0;2703}2704return-1;2705}27062707static intapply_binary(struct image *img,struct patch *patch)2708{2709const char*name = patch->old_name ? patch->old_name : patch->new_name;2710unsigned char sha1[20];27112712/*2713 * For safety, we require patch index line to contain2714 * full 40-byte textual SHA1 for old and new, at least for now.2715 */2716if(strlen(patch->old_sha1_prefix) !=40||2717strlen(patch->new_sha1_prefix) !=40||2718get_sha1_hex(patch->old_sha1_prefix, sha1) ||2719get_sha1_hex(patch->new_sha1_prefix, sha1))2720returnerror("cannot apply binary patch to '%s' "2721"without full index line", name);27222723if(patch->old_name) {2724/*2725 * See if the old one matches what the patch2726 * applies to.2727 */2728hash_sha1_file(img->buf, img->len, blob_type, sha1);2729if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2730returnerror("the patch applies to '%s' (%s), "2731"which does not match the "2732"current contents.",2733 name,sha1_to_hex(sha1));2734}2735else{2736/* Otherwise, the old one must be empty. */2737if(img->len)2738returnerror("the patch applies to an empty "2739"'%s' but it is not empty", name);2740}27412742get_sha1_hex(patch->new_sha1_prefix, sha1);2743if(is_null_sha1(sha1)) {2744clear_image(img);2745return0;/* deletion patch */2746}27472748if(has_sha1_file(sha1)) {2749/* We already have the postimage */2750enum object_type type;2751unsigned long size;2752char*result;27532754 result =read_sha1_file(sha1, &type, &size);2755if(!result)2756returnerror("the necessary postimage%sfor "2757"'%s' cannot be read",2758 patch->new_sha1_prefix, name);2759clear_image(img);2760 img->buf = result;2761 img->len = size;2762}else{2763/*2764 * We have verified buf matches the preimage;2765 * apply the patch data to it, which is stored2766 * in the patch->fragments->{patch,size}.2767 */2768if(apply_binary_fragment(img, patch))2769returnerror("binary patch does not apply to '%s'",2770 name);27712772/* verify that the result matches */2773hash_sha1_file(img->buf, img->len, blob_type, sha1);2774if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2775returnerror("binary patch to '%s' creates incorrect result (expecting%s, got%s)",2776 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2777}27782779return0;2780}27812782static intapply_fragments(struct image *img,struct patch *patch)2783{2784struct fragment *frag = patch->fragments;2785const char*name = patch->old_name ? patch->old_name : patch->new_name;2786unsigned ws_rule = patch->ws_rule;2787unsigned inaccurate_eof = patch->inaccurate_eof;27882789if(patch->is_binary)2790returnapply_binary(img, patch);27912792while(frag) {2793if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule)) {2794error("patch failed:%s:%ld", name, frag->oldpos);2795if(!apply_with_reject)2796return-1;2797 frag->rejected =1;2798}2799 frag = frag->next;2800}2801return0;2802}28032804static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2805{2806if(!ce)2807return0;28082809if(S_ISGITLINK(ce->ce_mode)) {2810strbuf_grow(buf,100);2811strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2812}else{2813enum object_type type;2814unsigned long sz;2815char*result;28162817 result =read_sha1_file(ce->sha1, &type, &sz);2818if(!result)2819return-1;2820/* XXX read_sha1_file NUL-terminates */2821strbuf_attach(buf, result, sz, sz +1);2822}2823return0;2824}28252826static struct patch *in_fn_table(const char*name)2827{2828struct string_list_item *item;28292830if(name == NULL)2831return NULL;28322833 item =string_list_lookup(&fn_table, name);2834if(item != NULL)2835return(struct patch *)item->util;28362837return NULL;2838}28392840/*2841 * item->util in the filename table records the status of the path.2842 * Usually it points at a patch (whose result records the contents2843 * of it after applying it), but it could be PATH_WAS_DELETED for a2844 * path that a previously applied patch has already removed.2845 */2846#define PATH_TO_BE_DELETED ((struct patch *) -2)2847#define PATH_WAS_DELETED ((struct patch *) -1)28482849static intto_be_deleted(struct patch *patch)2850{2851return patch == PATH_TO_BE_DELETED;2852}28532854static intwas_deleted(struct patch *patch)2855{2856return patch == PATH_WAS_DELETED;2857}28582859static voidadd_to_fn_table(struct patch *patch)2860{2861struct string_list_item *item;28622863/*2864 * Always add new_name unless patch is a deletion2865 * This should cover the cases for normal diffs,2866 * file creations and copies2867 */2868if(patch->new_name != NULL) {2869 item =string_list_insert(&fn_table, patch->new_name);2870 item->util = patch;2871}28722873/*2874 * store a failure on rename/deletion cases because2875 * later chunks shouldn't patch old names2876 */2877if((patch->new_name == NULL) || (patch->is_rename)) {2878 item =string_list_insert(&fn_table, patch->old_name);2879 item->util = PATH_WAS_DELETED;2880}2881}28822883static voidprepare_fn_table(struct patch *patch)2884{2885/*2886 * store information about incoming file deletion2887 */2888while(patch) {2889if((patch->new_name == NULL) || (patch->is_rename)) {2890struct string_list_item *item;2891 item =string_list_insert(&fn_table, patch->old_name);2892 item->util = PATH_TO_BE_DELETED;2893}2894 patch = patch->next;2895}2896}28972898static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)2899{2900struct strbuf buf = STRBUF_INIT;2901struct image image;2902size_t len;2903char*img;2904struct patch *tpatch;29052906if(!(patch->is_copy || patch->is_rename) &&2907(tpatch =in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {2908if(was_deleted(tpatch)) {2909returnerror("patch%shas been renamed/deleted",2910 patch->old_name);2911}2912/* We have a patched copy in memory use that */2913strbuf_add(&buf, tpatch->result, tpatch->resultsize);2914}else if(cached) {2915if(read_file_or_gitlink(ce, &buf))2916returnerror("read of%sfailed", patch->old_name);2917}else if(patch->old_name) {2918if(S_ISGITLINK(patch->old_mode)) {2919if(ce) {2920read_file_or_gitlink(ce, &buf);2921}else{2922/*2923 * There is no way to apply subproject2924 * patch without looking at the index.2925 */2926 patch->fragments = NULL;2927}2928}else{2929if(read_old_data(st, patch->old_name, &buf))2930returnerror("read of%sfailed", patch->old_name);2931}2932}29332934 img =strbuf_detach(&buf, &len);2935prepare_image(&image, img, len, !patch->is_binary);29362937if(apply_fragments(&image, patch) <0)2938return-1;/* note with --reject this succeeds. */2939 patch->result = image.buf;2940 patch->resultsize = image.len;2941add_to_fn_table(patch);2942free(image.line_allocated);29432944if(0< patch->is_delete && patch->resultsize)2945returnerror("removal patch leaves file contents");29462947return0;2948}29492950static intcheck_to_create_blob(const char*new_name,int ok_if_exists)2951{2952struct stat nst;2953if(!lstat(new_name, &nst)) {2954if(S_ISDIR(nst.st_mode) || ok_if_exists)2955return0;2956/*2957 * A leading component of new_name might be a symlink2958 * that is going to be removed with this patch, but2959 * still pointing at somewhere that has the path.2960 * In such a case, path "new_name" does not exist as2961 * far as git is concerned.2962 */2963if(has_symlink_leading_path(new_name,strlen(new_name)))2964return0;29652966returnerror("%s: already exists in working directory", new_name);2967}2968else if((errno != ENOENT) && (errno != ENOTDIR))2969returnerror("%s:%s", new_name,strerror(errno));2970return0;2971}29722973static intverify_index_match(struct cache_entry *ce,struct stat *st)2974{2975if(S_ISGITLINK(ce->ce_mode)) {2976if(!S_ISDIR(st->st_mode))2977return-1;2978return0;2979}2980returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);2981}29822983static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)2984{2985const char*old_name = patch->old_name;2986struct patch *tpatch = NULL;2987int stat_ret =0;2988unsigned st_mode =0;29892990/*2991 * Make sure that we do not have local modifications from the2992 * index when we are looking at the index. Also make sure2993 * we have the preimage file to be patched in the work tree,2994 * unless --cached, which tells git to apply only in the index.2995 */2996if(!old_name)2997return0;29982999assert(patch->is_new <=0);30003001if(!(patch->is_copy || patch->is_rename) &&3002(tpatch =in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {3003if(was_deleted(tpatch))3004returnerror("%s: has been deleted/renamed", old_name);3005 st_mode = tpatch->new_mode;3006}else if(!cached) {3007 stat_ret =lstat(old_name, st);3008if(stat_ret && errno != ENOENT)3009returnerror("%s:%s", old_name,strerror(errno));3010}30113012if(to_be_deleted(tpatch))3013 tpatch = NULL;30143015if(check_index && !tpatch) {3016int pos =cache_name_pos(old_name,strlen(old_name));3017if(pos <0) {3018if(patch->is_new <0)3019goto is_new;3020returnerror("%s: does not exist in index", old_name);3021}3022*ce = active_cache[pos];3023if(stat_ret <0) {3024struct checkout costate;3025/* checkout */3026memset(&costate,0,sizeof(costate));3027 costate.base_dir ="";3028 costate.refresh_cache =1;3029if(checkout_entry(*ce, &costate, NULL) ||3030lstat(old_name, st))3031return-1;3032}3033if(!cached &&verify_index_match(*ce, st))3034returnerror("%s: does not match index", old_name);3035if(cached)3036 st_mode = (*ce)->ce_mode;3037}else if(stat_ret <0) {3038if(patch->is_new <0)3039goto is_new;3040returnerror("%s:%s", old_name,strerror(errno));3041}30423043if(!cached && !tpatch)3044 st_mode =ce_mode_from_stat(*ce, st->st_mode);30453046if(patch->is_new <0)3047 patch->is_new =0;3048if(!patch->old_mode)3049 patch->old_mode = st_mode;3050if((st_mode ^ patch->old_mode) & S_IFMT)3051returnerror("%s: wrong type", old_name);3052if(st_mode != patch->old_mode)3053warning("%shas type%o, expected%o",3054 old_name, st_mode, patch->old_mode);3055if(!patch->new_mode && !patch->is_delete)3056 patch->new_mode = st_mode;3057return0;30583059 is_new:3060 patch->is_new =1;3061 patch->is_delete =0;3062 patch->old_name = NULL;3063return0;3064}30653066static intcheck_patch(struct patch *patch)3067{3068struct stat st;3069const char*old_name = patch->old_name;3070const char*new_name = patch->new_name;3071const char*name = old_name ? old_name : new_name;3072struct cache_entry *ce = NULL;3073struct patch *tpatch;3074int ok_if_exists;3075int status;30763077 patch->rejected =1;/* we will drop this after we succeed */30783079 status =check_preimage(patch, &ce, &st);3080if(status)3081return status;3082 old_name = patch->old_name;30833084if((tpatch =in_fn_table(new_name)) &&3085(was_deleted(tpatch) ||to_be_deleted(tpatch)))3086/*3087 * A type-change diff is always split into a patch to3088 * delete old, immediately followed by a patch to3089 * create new (see diff.c::run_diff()); in such a case3090 * it is Ok that the entry to be deleted by the3091 * previous patch is still in the working tree and in3092 * the index.3093 */3094 ok_if_exists =1;3095else3096 ok_if_exists =0;30973098if(new_name &&3099((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {3100if(check_index &&3101cache_name_pos(new_name,strlen(new_name)) >=0&&3102!ok_if_exists)3103returnerror("%s: already exists in index", new_name);3104if(!cached) {3105int err =check_to_create_blob(new_name, ok_if_exists);3106if(err)3107return err;3108}3109if(!patch->new_mode) {3110if(0< patch->is_new)3111 patch->new_mode = S_IFREG |0644;3112else3113 patch->new_mode = patch->old_mode;3114}3115}31163117if(new_name && old_name) {3118int same = !strcmp(old_name, new_name);3119if(!patch->new_mode)3120 patch->new_mode = patch->old_mode;3121if((patch->old_mode ^ patch->new_mode) & S_IFMT)3122returnerror("new mode (%o) of%sdoes not match old mode (%o)%s%s",3123 patch->new_mode, new_name, patch->old_mode,3124 same ?"":" of ", same ?"": old_name);3125}31263127if(apply_data(patch, &st, ce) <0)3128returnerror("%s: patch does not apply", name);3129 patch->rejected =0;3130return0;3131}31323133static intcheck_patch_list(struct patch *patch)3134{3135int err =0;31363137prepare_fn_table(patch);3138while(patch) {3139if(apply_verbosely)3140say_patch_name(stderr,3141"Checking patch ", patch,"...\n");3142 err |=check_patch(patch);3143 patch = patch->next;3144}3145return err;3146}31473148/* This function tries to read the sha1 from the current index */3149static intget_current_sha1(const char*path,unsigned char*sha1)3150{3151int pos;31523153if(read_cache() <0)3154return-1;3155 pos =cache_name_pos(path,strlen(path));3156if(pos <0)3157return-1;3158hashcpy(sha1, active_cache[pos]->sha1);3159return0;3160}31613162/* Build an index that contains the just the files needed for a 3way merge */3163static voidbuild_fake_ancestor(struct patch *list,const char*filename)3164{3165struct patch *patch;3166struct index_state result = { NULL };3167int fd;31683169/* Once we start supporting the reverse patch, it may be3170 * worth showing the new sha1 prefix, but until then...3171 */3172for(patch = list; patch; patch = patch->next) {3173const unsigned char*sha1_ptr;3174unsigned char sha1[20];3175struct cache_entry *ce;3176const char*name;31773178 name = patch->old_name ? patch->old_name : patch->new_name;3179if(0< patch->is_new)3180continue;3181else if(get_sha1(patch->old_sha1_prefix, sha1))3182/* git diff has no index line for mode/type changes */3183if(!patch->lines_added && !patch->lines_deleted) {3184if(get_current_sha1(patch->old_name, sha1))3185die("mode change for%s, which is not "3186"in current HEAD", name);3187 sha1_ptr = sha1;3188}else3189die("sha1 information is lacking or useless "3190"(%s).", name);3191else3192 sha1_ptr = sha1;31933194 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);3195if(!ce)3196die("make_cache_entry failed for path '%s'", name);3197if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3198die("Could not add%sto temporary index", name);3199}32003201 fd =open(filename, O_WRONLY | O_CREAT,0666);3202if(fd <0||write_index(&result, fd) ||close(fd))3203die("Could not write temporary index to%s", filename);32043205discard_index(&result);3206}32073208static voidstat_patch_list(struct patch *patch)3209{3210int files, adds, dels;32113212for(files = adds = dels =0; patch ; patch = patch->next) {3213 files++;3214 adds += patch->lines_added;3215 dels += patch->lines_deleted;3216show_stats(patch);3217}32183219printf("%dfiles changed,%dinsertions(+),%ddeletions(-)\n", files, adds, dels);3220}32213222static voidnumstat_patch_list(struct patch *patch)3223{3224for( ; patch; patch = patch->next) {3225const char*name;3226 name = patch->new_name ? patch->new_name : patch->old_name;3227if(patch->is_binary)3228printf("-\t-\t");3229else3230printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3231write_name_quoted(name, stdout, line_termination);3232}3233}32343235static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3236{3237if(mode)3238printf("%smode%06o%s\n", newdelete, mode, name);3239else3240printf("%s %s\n", newdelete, name);3241}32423243static voidshow_mode_change(struct patch *p,int show_name)3244{3245if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3246if(show_name)3247printf(" mode change%06o =>%06o%s\n",3248 p->old_mode, p->new_mode, p->new_name);3249else3250printf(" mode change%06o =>%06o\n",3251 p->old_mode, p->new_mode);3252}3253}32543255static voidshow_rename_copy(struct patch *p)3256{3257const char*renamecopy = p->is_rename ?"rename":"copy";3258const char*old, *new;32593260/* Find common prefix */3261 old = p->old_name;3262new= p->new_name;3263while(1) {3264const char*slash_old, *slash_new;3265 slash_old =strchr(old,'/');3266 slash_new =strchr(new,'/');3267if(!slash_old ||3268!slash_new ||3269 slash_old - old != slash_new -new||3270memcmp(old,new, slash_new -new))3271break;3272 old = slash_old +1;3273new= slash_new +1;3274}3275/* p->old_name thru old is the common prefix, and old and new3276 * through the end of names are renames3277 */3278if(old != p->old_name)3279printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,3280(int)(old - p->old_name), p->old_name,3281 old,new, p->score);3282else3283printf("%s %s=>%s(%d%%)\n", renamecopy,3284 p->old_name, p->new_name, p->score);3285show_mode_change(p,0);3286}32873288static voidsummary_patch_list(struct patch *patch)3289{3290struct patch *p;32913292for(p = patch; p; p = p->next) {3293if(p->is_new)3294show_file_mode_name("create", p->new_mode, p->new_name);3295else if(p->is_delete)3296show_file_mode_name("delete", p->old_mode, p->old_name);3297else{3298if(p->is_rename || p->is_copy)3299show_rename_copy(p);3300else{3301if(p->score) {3302printf(" rewrite%s(%d%%)\n",3303 p->new_name, p->score);3304show_mode_change(p,0);3305}3306else3307show_mode_change(p,1);3308}3309}3310}3311}33123313static voidpatch_stats(struct patch *patch)3314{3315int lines = patch->lines_added + patch->lines_deleted;33163317if(lines > max_change)3318 max_change = lines;3319if(patch->old_name) {3320int len =quote_c_style(patch->old_name, NULL, NULL,0);3321if(!len)3322 len =strlen(patch->old_name);3323if(len > max_len)3324 max_len = len;3325}3326if(patch->new_name) {3327int len =quote_c_style(patch->new_name, NULL, NULL,0);3328if(!len)3329 len =strlen(patch->new_name);3330if(len > max_len)3331 max_len = len;3332}3333}33343335static voidremove_file(struct patch *patch,int rmdir_empty)3336{3337if(update_index) {3338if(remove_file_from_cache(patch->old_name) <0)3339die("unable to remove%sfrom index", patch->old_name);3340}3341if(!cached) {3342if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {3343remove_path(patch->old_name);3344}3345}3346}33473348static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)3349{3350struct stat st;3351struct cache_entry *ce;3352int namelen =strlen(path);3353unsigned ce_size =cache_entry_size(namelen);33543355if(!update_index)3356return;33573358 ce =xcalloc(1, ce_size);3359memcpy(ce->name, path, namelen);3360 ce->ce_mode =create_ce_mode(mode);3361 ce->ce_flags = namelen;3362if(S_ISGITLINK(mode)) {3363const char*s = buf;33643365if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))3366die("corrupt patch for subproject%s", path);3367}else{3368if(!cached) {3369if(lstat(path, &st) <0)3370die_errno("unable to stat newly created file '%s'",3371 path);3372fill_stat_cache_info(ce, &st);3373}3374if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)3375die("unable to create backing store for newly created file%s", path);3376}3377if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3378die("unable to add cache entry for%s", path);3379}33803381static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)3382{3383int fd;3384struct strbuf nbuf = STRBUF_INIT;33853386if(S_ISGITLINK(mode)) {3387struct stat st;3388if(!lstat(path, &st) &&S_ISDIR(st.st_mode))3389return0;3390returnmkdir(path,0777);3391}33923393if(has_symlinks &&S_ISLNK(mode))3394/* Although buf:size is counted string, it also is NUL3395 * terminated.3396 */3397returnsymlink(buf, path);33983399 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);3400if(fd <0)3401return-1;34023403if(convert_to_working_tree(path, buf, size, &nbuf)) {3404 size = nbuf.len;3405 buf = nbuf.buf;3406}3407write_or_die(fd, buf, size);3408strbuf_release(&nbuf);34093410if(close(fd) <0)3411die_errno("closing file '%s'", path);3412return0;3413}34143415/*3416 * We optimistically assume that the directories exist,3417 * which is true 99% of the time anyway. If they don't,3418 * we create them and try again.3419 */3420static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)3421{3422if(cached)3423return;3424if(!try_create_file(path, mode, buf, size))3425return;34263427if(errno == ENOENT) {3428if(safe_create_leading_directories(path))3429return;3430if(!try_create_file(path, mode, buf, size))3431return;3432}34333434if(errno == EEXIST || errno == EACCES) {3435/* We may be trying to create a file where a directory3436 * used to be.3437 */3438struct stat st;3439if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))3440 errno = EEXIST;3441}34423443if(errno == EEXIST) {3444unsigned int nr =getpid();34453446for(;;) {3447char newpath[PATH_MAX];3448mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);3449if(!try_create_file(newpath, mode, buf, size)) {3450if(!rename(newpath, path))3451return;3452unlink_or_warn(newpath);3453break;3454}3455if(errno != EEXIST)3456break;3457++nr;3458}3459}3460die_errno("unable to write file '%s' mode%o", path, mode);3461}34623463static voidcreate_file(struct patch *patch)3464{3465char*path = patch->new_name;3466unsigned mode = patch->new_mode;3467unsigned long size = patch->resultsize;3468char*buf = patch->result;34693470if(!mode)3471 mode = S_IFREG |0644;3472create_one_file(path, mode, buf, size);3473add_index_file(path, mode, buf, size);3474}34753476/* phase zero is to remove, phase one is to create */3477static voidwrite_out_one_result(struct patch *patch,int phase)3478{3479if(patch->is_delete >0) {3480if(phase ==0)3481remove_file(patch,1);3482return;3483}3484if(patch->is_new >0|| patch->is_copy) {3485if(phase ==1)3486create_file(patch);3487return;3488}3489/*3490 * Rename or modification boils down to the same3491 * thing: remove the old, write the new3492 */3493if(phase ==0)3494remove_file(patch, patch->is_rename);3495if(phase ==1)3496create_file(patch);3497}34983499static intwrite_out_one_reject(struct patch *patch)3500{3501FILE*rej;3502char namebuf[PATH_MAX];3503struct fragment *frag;3504int cnt =0;35053506for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {3507if(!frag->rejected)3508continue;3509 cnt++;3510}35113512if(!cnt) {3513if(apply_verbosely)3514say_patch_name(stderr,3515"Applied patch ", patch," cleanly.\n");3516return0;3517}35183519/* This should not happen, because a removal patch that leaves3520 * contents are marked "rejected" at the patch level.3521 */3522if(!patch->new_name)3523die("internal error");35243525/* Say this even without --verbose */3526say_patch_name(stderr,"Applying patch ", patch," with");3527fprintf(stderr,"%drejects...\n", cnt);35283529 cnt =strlen(patch->new_name);3530if(ARRAY_SIZE(namebuf) <= cnt +5) {3531 cnt =ARRAY_SIZE(namebuf) -5;3532warning("truncating .rej filename to %.*s.rej",3533 cnt -1, patch->new_name);3534}3535memcpy(namebuf, patch->new_name, cnt);3536memcpy(namebuf + cnt,".rej",5);35373538 rej =fopen(namebuf,"w");3539if(!rej)3540returnerror("cannot open%s:%s", namebuf,strerror(errno));35413542/* Normal git tools never deal with .rej, so do not pretend3543 * this is a git patch by saying --git nor give extended3544 * headers. While at it, maybe please "kompare" that wants3545 * the trailing TAB and some garbage at the end of line ;-).3546 */3547fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",3548 patch->new_name, patch->new_name);3549for(cnt =1, frag = patch->fragments;3550 frag;3551 cnt++, frag = frag->next) {3552if(!frag->rejected) {3553fprintf(stderr,"Hunk #%dapplied cleanly.\n", cnt);3554continue;3555}3556fprintf(stderr,"Rejected hunk #%d.\n", cnt);3557fprintf(rej,"%.*s", frag->size, frag->patch);3558if(frag->patch[frag->size-1] !='\n')3559fputc('\n', rej);3560}3561fclose(rej);3562return-1;3563}35643565static intwrite_out_results(struct patch *list,int skipped_patch)3566{3567int phase;3568int errs =0;3569struct patch *l;35703571if(!list && !skipped_patch)3572returnerror("No changes");35733574for(phase =0; phase <2; phase++) {3575 l = list;3576while(l) {3577if(l->rejected)3578 errs =1;3579else{3580write_out_one_result(l, phase);3581if(phase ==1&&write_out_one_reject(l))3582 errs =1;3583}3584 l = l->next;3585}3586}3587return errs;3588}35893590static struct lock_file lock_file;35913592static struct string_list limit_by_name;3593static int has_include;3594static voidadd_name_limit(const char*name,int exclude)3595{3596struct string_list_item *it;35973598 it =string_list_append(&limit_by_name, name);3599 it->util = exclude ? NULL : (void*)1;3600}36013602static intuse_patch(struct patch *p)3603{3604const char*pathname = p->new_name ? p->new_name : p->old_name;3605int i;36063607/* Paths outside are not touched regardless of "--include" */3608if(0< prefix_length) {3609int pathlen =strlen(pathname);3610if(pathlen <= prefix_length ||3611memcmp(prefix, pathname, prefix_length))3612return0;3613}36143615/* See if it matches any of exclude/include rule */3616for(i =0; i < limit_by_name.nr; i++) {3617struct string_list_item *it = &limit_by_name.items[i];3618if(!fnmatch(it->string, pathname,0))3619return(it->util != NULL);3620}36213622/*3623 * If we had any include, a path that does not match any rule is3624 * not used. Otherwise, we saw bunch of exclude rules (or none)3625 * and such a path is used.3626 */3627return!has_include;3628}362936303631static voidprefix_one(char**name)3632{3633char*old_name = *name;3634if(!old_name)3635return;3636*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3637free(old_name);3638}36393640static voidprefix_patches(struct patch *p)3641{3642if(!prefix || p->is_toplevel_relative)3643return;3644for( ; p; p = p->next) {3645if(p->new_name == p->old_name) {3646char*prefixed = p->new_name;3647prefix_one(&prefixed);3648 p->new_name = p->old_name = prefixed;3649}3650else{3651prefix_one(&p->new_name);3652prefix_one(&p->old_name);3653}3654}3655}36563657#define INACCURATE_EOF (1<<0)3658#define RECOUNT (1<<1)36593660static intapply_patch(int fd,const char*filename,int options)3661{3662size_t offset;3663struct strbuf buf = STRBUF_INIT;3664struct patch *list = NULL, **listp = &list;3665int skipped_patch =0;36663667/* FIXME - memory leak when using multiple patch files as inputs */3668memset(&fn_table,0,sizeof(struct string_list));3669 patch_input_file = filename;3670read_patch_file(&buf, fd);3671 offset =0;3672while(offset < buf.len) {3673struct patch *patch;3674int nr;36753676 patch =xcalloc(1,sizeof(*patch));3677 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3678 patch->recount = !!(options & RECOUNT);3679 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3680if(nr <0)3681break;3682if(apply_in_reverse)3683reverse_patches(patch);3684if(prefix)3685prefix_patches(patch);3686if(use_patch(patch)) {3687patch_stats(patch);3688*listp = patch;3689 listp = &patch->next;3690}3691else{3692/* perhaps free it a bit better? */3693free(patch);3694 skipped_patch++;3695}3696 offset += nr;3697}36983699if(whitespace_error && (ws_error_action == die_on_ws_error))3700 apply =0;37013702 update_index = check_index && apply;3703if(update_index && newfd <0)3704 newfd =hold_locked_index(&lock_file,1);37053706if(check_index) {3707if(read_cache() <0)3708die("unable to read index file");3709}37103711if((check || apply) &&3712check_patch_list(list) <0&&3713!apply_with_reject)3714exit(1);37153716if(apply &&write_out_results(list, skipped_patch))3717exit(1);37183719if(fake_ancestor)3720build_fake_ancestor(list, fake_ancestor);37213722if(diffstat)3723stat_patch_list(list);37243725if(numstat)3726numstat_patch_list(list);37273728if(summary)3729summary_patch_list(list);37303731strbuf_release(&buf);3732return0;3733}37343735static intgit_apply_config(const char*var,const char*value,void*cb)3736{3737if(!strcmp(var,"apply.whitespace"))3738returngit_config_string(&apply_default_whitespace, var, value);3739else if(!strcmp(var,"apply.ignorewhitespace"))3740returngit_config_string(&apply_default_ignorewhitespace, var, value);3741returngit_default_config(var, value, cb);3742}37433744static intoption_parse_exclude(const struct option *opt,3745const char*arg,int unset)3746{3747add_name_limit(arg,1);3748return0;3749}37503751static intoption_parse_include(const struct option *opt,3752const char*arg,int unset)3753{3754add_name_limit(arg,0);3755 has_include =1;3756return0;3757}37583759static intoption_parse_p(const struct option *opt,3760const char*arg,int unset)3761{3762 p_value =atoi(arg);3763 p_value_known =1;3764return0;3765}37663767static intoption_parse_z(const struct option *opt,3768const char*arg,int unset)3769{3770if(unset)3771 line_termination ='\n';3772else3773 line_termination =0;3774return0;3775}37763777static intoption_parse_space_change(const struct option *opt,3778const char*arg,int unset)3779{3780if(unset)3781 ws_ignore_action = ignore_ws_none;3782else3783 ws_ignore_action = ignore_ws_change;3784return0;3785}37863787static intoption_parse_whitespace(const struct option *opt,3788const char*arg,int unset)3789{3790const char**whitespace_option = opt->value;37913792*whitespace_option = arg;3793parse_whitespace_option(arg);3794return0;3795}37963797static intoption_parse_directory(const struct option *opt,3798const char*arg,int unset)3799{3800 root_len =strlen(arg);3801if(root_len && arg[root_len -1] !='/') {3802char*new_root;3803 root = new_root =xmalloc(root_len +2);3804strcpy(new_root, arg);3805strcpy(new_root + root_len++,"/");3806}else3807 root = arg;3808return0;3809}38103811intcmd_apply(int argc,const char**argv,const char*prefix_)3812{3813int i;3814int errs =0;3815int is_not_gitdir = !startup_info->have_repository;3816int binary;3817int force_apply =0;38183819const char*whitespace_option = NULL;38203821struct option builtin_apply_options[] = {3822{ OPTION_CALLBACK,0,"exclude", NULL,"path",3823"don't apply changes matching the given path",38240, option_parse_exclude },3825{ OPTION_CALLBACK,0,"include", NULL,"path",3826"apply changes matching the given path",38270, option_parse_include },3828{ OPTION_CALLBACK,'p', NULL, NULL,"num",3829"remove <num> leading slashes from traditional diff paths",38300, option_parse_p },3831OPT_BOOLEAN(0,"no-add", &no_add,3832"ignore additions made by the patch"),3833OPT_BOOLEAN(0,"stat", &diffstat,3834"instead of applying the patch, output diffstat for the input"),3835{ OPTION_BOOLEAN,0,"allow-binary-replacement", &binary,3836 NULL,"old option, now no-op",3837 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3838{ OPTION_BOOLEAN,0,"binary", &binary,3839 NULL,"old option, now no-op",3840 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3841OPT_BOOLEAN(0,"numstat", &numstat,3842"shows number of added and deleted lines in decimal notation"),3843OPT_BOOLEAN(0,"summary", &summary,3844"instead of applying the patch, output a summary for the input"),3845OPT_BOOLEAN(0,"check", &check,3846"instead of applying the patch, see if the patch is applicable"),3847OPT_BOOLEAN(0,"index", &check_index,3848"make sure the patch is applicable to the current index"),3849OPT_BOOLEAN(0,"cached", &cached,3850"apply a patch without touching the working tree"),3851OPT_BOOLEAN(0,"apply", &force_apply,3852"also apply the patch (use with --stat/--summary/--check)"),3853OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,3854"build a temporary index based on embedded index information"),3855{ OPTION_CALLBACK,'z', NULL, NULL, NULL,3856"paths are separated with NUL character",3857 PARSE_OPT_NOARG, option_parse_z },3858OPT_INTEGER('C', NULL, &p_context,3859"ensure at least <n> lines of context match"),3860{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,"action",3861"detect new or modified lines that have whitespace errors",38620, option_parse_whitespace },3863{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,3864"ignore changes in whitespace when finding context",3865 PARSE_OPT_NOARG, option_parse_space_change },3866{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,3867"ignore changes in whitespace when finding context",3868 PARSE_OPT_NOARG, option_parse_space_change },3869OPT_BOOLEAN('R',"reverse", &apply_in_reverse,3870"apply the patch in reverse"),3871OPT_BOOLEAN(0,"unidiff-zero", &unidiff_zero,3872"don't expect at least one line of context"),3873OPT_BOOLEAN(0,"reject", &apply_with_reject,3874"leave the rejected hunks in corresponding *.rej files"),3875OPT__VERBOSE(&apply_verbosely),3876OPT_BIT(0,"inaccurate-eof", &options,3877"tolerate incorrectly detected missing new-line at the end of file",3878 INACCURATE_EOF),3879OPT_BIT(0,"recount", &options,3880"do not trust the line counts in the hunk headers",3881 RECOUNT),3882{ OPTION_CALLBACK,0,"directory", NULL,"root",3883"prepend <root> to all filenames",38840, option_parse_directory },3885OPT_END()3886};38873888 prefix = prefix_;3889 prefix_length = prefix ?strlen(prefix) :0;3890git_config(git_apply_config, NULL);3891if(apply_default_whitespace)3892parse_whitespace_option(apply_default_whitespace);3893if(apply_default_ignorewhitespace)3894parse_ignorewhitespace_option(apply_default_ignorewhitespace);38953896 argc =parse_options(argc, argv, prefix, builtin_apply_options,3897 apply_usage,0);38983899if(apply_with_reject)3900 apply = apply_verbosely =1;3901if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))3902 apply =0;3903if(check_index && is_not_gitdir)3904die("--index outside a repository");3905if(cached) {3906if(is_not_gitdir)3907die("--cached outside a repository");3908 check_index =1;3909}3910for(i =0; i < argc; i++) {3911const char*arg = argv[i];3912int fd;39133914if(!strcmp(arg,"-")) {3915 errs |=apply_patch(0,"<stdin>", options);3916 read_stdin =0;3917continue;3918}else if(0< prefix_length)3919 arg =prefix_filename(prefix, prefix_length, arg);39203921 fd =open(arg, O_RDONLY);3922if(fd <0)3923die_errno("can't open patch '%s'", arg);3924 read_stdin =0;3925set_default_whitespace_mode(whitespace_option);3926 errs |=apply_patch(fd, arg, options);3927close(fd);3928}3929set_default_whitespace_mode(whitespace_option);3930if(read_stdin)3931 errs |=apply_patch(0,"<stdin>", options);3932if(whitespace_error) {3933if(squelch_whitespace_errors &&3934 squelch_whitespace_errors < whitespace_error) {3935int squelched =3936 whitespace_error - squelch_whitespace_errors;3937warning("squelched%d"3938"whitespace error%s",3939 squelched,3940 squelched ==1?"":"s");3941}3942if(ws_error_action == die_on_ws_error)3943die("%dline%sadd%swhitespace errors.",3944 whitespace_error,3945 whitespace_error ==1?"":"s",3946 whitespace_error ==1?"s":"");3947if(applied_after_fixing_ws && apply)3948warning("%dline%sapplied after"3949" fixing whitespace errors.",3950 applied_after_fixing_ws,3951 applied_after_fixing_ws ==1?"":"s");3952else if(whitespace_error)3953warning("%dline%sadd%swhitespace errors.",3954 whitespace_error,3955 whitespace_error ==1?"":"s",3956 whitespace_error ==1?"s":"");3957}39583959if(update_index) {3960if(write_cache(newfd, active_cache, active_nr) ||3961commit_locked_index(&lock_file))3962die("Unable to write new index file");3963}39643965return!!errs;3966}