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,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,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,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,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;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 */1151for(len =0; ; len++) {1152switch(name[len]) {1153default:1154continue;1155case'\n':1156return NULL;1157case'\t':case' ':1158 second = name+len;1159for(;;) {1160char c = *second++;1161if(c =='\n')1162return NULL;1163if(c =='/')1164break;1165}1166if(second[len] =='\n'&& !memcmp(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;26702671/* Binary patch is irreversible without the optional second hunk */2672if(apply_in_reverse) {2673if(!fragment->next)2674returnerror("cannot reverse-apply a binary patch "2675"without the reverse hunk to '%s'",2676 patch->new_name2677? patch->new_name : patch->old_name);2678 fragment = fragment->next;2679}2680switch(fragment->binary_patch_method) {2681case BINARY_DELTA_DEFLATED:2682 dst =patch_delta(img->buf, img->len, fragment->patch,2683 fragment->size, &len);2684if(!dst)2685return-1;2686clear_image(img);2687 img->buf = dst;2688 img->len = len;2689return0;2690case BINARY_LITERAL_DEFLATED:2691clear_image(img);2692 img->len = fragment->size;2693 img->buf =xmalloc(img->len+1);2694memcpy(img->buf, fragment->patch, img->len);2695 img->buf[img->len] ='\0';2696return0;2697}2698return-1;2699}27002701static intapply_binary(struct image *img,struct patch *patch)2702{2703const char*name = patch->old_name ? patch->old_name : patch->new_name;2704unsigned char sha1[20];27052706/*2707 * For safety, we require patch index line to contain2708 * full 40-byte textual SHA1 for old and new, at least for now.2709 */2710if(strlen(patch->old_sha1_prefix) !=40||2711strlen(patch->new_sha1_prefix) !=40||2712get_sha1_hex(patch->old_sha1_prefix, sha1) ||2713get_sha1_hex(patch->new_sha1_prefix, sha1))2714returnerror("cannot apply binary patch to '%s' "2715"without full index line", name);27162717if(patch->old_name) {2718/*2719 * See if the old one matches what the patch2720 * applies to.2721 */2722hash_sha1_file(img->buf, img->len, blob_type, sha1);2723if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2724returnerror("the patch applies to '%s' (%s), "2725"which does not match the "2726"current contents.",2727 name,sha1_to_hex(sha1));2728}2729else{2730/* Otherwise, the old one must be empty. */2731if(img->len)2732returnerror("the patch applies to an empty "2733"'%s' but it is not empty", name);2734}27352736get_sha1_hex(patch->new_sha1_prefix, sha1);2737if(is_null_sha1(sha1)) {2738clear_image(img);2739return0;/* deletion patch */2740}27412742if(has_sha1_file(sha1)) {2743/* We already have the postimage */2744enum object_type type;2745unsigned long size;2746char*result;27472748 result =read_sha1_file(sha1, &type, &size);2749if(!result)2750returnerror("the necessary postimage%sfor "2751"'%s' cannot be read",2752 patch->new_sha1_prefix, name);2753clear_image(img);2754 img->buf = result;2755 img->len = size;2756}else{2757/*2758 * We have verified buf matches the preimage;2759 * apply the patch data to it, which is stored2760 * in the patch->fragments->{patch,size}.2761 */2762if(apply_binary_fragment(img, patch))2763returnerror("binary patch does not apply to '%s'",2764 name);27652766/* verify that the result matches */2767hash_sha1_file(img->buf, img->len, blob_type, sha1);2768if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2769returnerror("binary patch to '%s' creates incorrect result (expecting%s, got%s)",2770 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2771}27722773return0;2774}27752776static intapply_fragments(struct image *img,struct patch *patch)2777{2778struct fragment *frag = patch->fragments;2779const char*name = patch->old_name ? patch->old_name : patch->new_name;2780unsigned ws_rule = patch->ws_rule;2781unsigned inaccurate_eof = patch->inaccurate_eof;27822783if(patch->is_binary)2784returnapply_binary(img, patch);27852786while(frag) {2787if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule)) {2788error("patch failed:%s:%ld", name, frag->oldpos);2789if(!apply_with_reject)2790return-1;2791 frag->rejected =1;2792}2793 frag = frag->next;2794}2795return0;2796}27972798static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2799{2800if(!ce)2801return0;28022803if(S_ISGITLINK(ce->ce_mode)) {2804strbuf_grow(buf,100);2805strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2806}else{2807enum object_type type;2808unsigned long sz;2809char*result;28102811 result =read_sha1_file(ce->sha1, &type, &sz);2812if(!result)2813return-1;2814/* XXX read_sha1_file NUL-terminates */2815strbuf_attach(buf, result, sz, sz +1);2816}2817return0;2818}28192820static struct patch *in_fn_table(const char*name)2821{2822struct string_list_item *item;28232824if(name == NULL)2825return NULL;28262827 item =string_list_lookup(&fn_table, name);2828if(item != NULL)2829return(struct patch *)item->util;28302831return NULL;2832}28332834/*2835 * item->util in the filename table records the status of the path.2836 * Usually it points at a patch (whose result records the contents2837 * of it after applying it), but it could be PATH_WAS_DELETED for a2838 * path that a previously applied patch has already removed.2839 */2840#define PATH_TO_BE_DELETED ((struct patch *) -2)2841#define PATH_WAS_DELETED ((struct patch *) -1)28422843static intto_be_deleted(struct patch *patch)2844{2845return patch == PATH_TO_BE_DELETED;2846}28472848static intwas_deleted(struct patch *patch)2849{2850return patch == PATH_WAS_DELETED;2851}28522853static voidadd_to_fn_table(struct patch *patch)2854{2855struct string_list_item *item;28562857/*2858 * Always add new_name unless patch is a deletion2859 * This should cover the cases for normal diffs,2860 * file creations and copies2861 */2862if(patch->new_name != NULL) {2863 item =string_list_insert(&fn_table, patch->new_name);2864 item->util = patch;2865}28662867/*2868 * store a failure on rename/deletion cases because2869 * later chunks shouldn't patch old names2870 */2871if((patch->new_name == NULL) || (patch->is_rename)) {2872 item =string_list_insert(&fn_table, patch->old_name);2873 item->util = PATH_WAS_DELETED;2874}2875}28762877static voidprepare_fn_table(struct patch *patch)2878{2879/*2880 * store information about incoming file deletion2881 */2882while(patch) {2883if((patch->new_name == NULL) || (patch->is_rename)) {2884struct string_list_item *item;2885 item =string_list_insert(&fn_table, patch->old_name);2886 item->util = PATH_TO_BE_DELETED;2887}2888 patch = patch->next;2889}2890}28912892static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)2893{2894struct strbuf buf = STRBUF_INIT;2895struct image image;2896size_t len;2897char*img;2898struct patch *tpatch;28992900if(!(patch->is_copy || patch->is_rename) &&2901(tpatch =in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {2902if(was_deleted(tpatch)) {2903returnerror("patch%shas been renamed/deleted",2904 patch->old_name);2905}2906/* We have a patched copy in memory use that */2907strbuf_add(&buf, tpatch->result, tpatch->resultsize);2908}else if(cached) {2909if(read_file_or_gitlink(ce, &buf))2910returnerror("read of%sfailed", patch->old_name);2911}else if(patch->old_name) {2912if(S_ISGITLINK(patch->old_mode)) {2913if(ce) {2914read_file_or_gitlink(ce, &buf);2915}else{2916/*2917 * There is no way to apply subproject2918 * patch without looking at the index.2919 */2920 patch->fragments = NULL;2921}2922}else{2923if(read_old_data(st, patch->old_name, &buf))2924returnerror("read of%sfailed", patch->old_name);2925}2926}29272928 img =strbuf_detach(&buf, &len);2929prepare_image(&image, img, len, !patch->is_binary);29302931if(apply_fragments(&image, patch) <0)2932return-1;/* note with --reject this succeeds. */2933 patch->result = image.buf;2934 patch->resultsize = image.len;2935add_to_fn_table(patch);2936free(image.line_allocated);29372938if(0< patch->is_delete && patch->resultsize)2939returnerror("removal patch leaves file contents");29402941return0;2942}29432944static intcheck_to_create_blob(const char*new_name,int ok_if_exists)2945{2946struct stat nst;2947if(!lstat(new_name, &nst)) {2948if(S_ISDIR(nst.st_mode) || ok_if_exists)2949return0;2950/*2951 * A leading component of new_name might be a symlink2952 * that is going to be removed with this patch, but2953 * still pointing at somewhere that has the path.2954 * In such a case, path "new_name" does not exist as2955 * far as git is concerned.2956 */2957if(has_symlink_leading_path(new_name,strlen(new_name)))2958return0;29592960returnerror("%s: already exists in working directory", new_name);2961}2962else if((errno != ENOENT) && (errno != ENOTDIR))2963returnerror("%s:%s", new_name,strerror(errno));2964return0;2965}29662967static intverify_index_match(struct cache_entry *ce,struct stat *st)2968{2969if(S_ISGITLINK(ce->ce_mode)) {2970if(!S_ISDIR(st->st_mode))2971return-1;2972return0;2973}2974returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);2975}29762977static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)2978{2979const char*old_name = patch->old_name;2980struct patch *tpatch = NULL;2981int stat_ret =0;2982unsigned st_mode =0;29832984/*2985 * Make sure that we do not have local modifications from the2986 * index when we are looking at the index. Also make sure2987 * we have the preimage file to be patched in the work tree,2988 * unless --cached, which tells git to apply only in the index.2989 */2990if(!old_name)2991return0;29922993assert(patch->is_new <=0);29942995if(!(patch->is_copy || patch->is_rename) &&2996(tpatch =in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {2997if(was_deleted(tpatch))2998returnerror("%s: has been deleted/renamed", old_name);2999 st_mode = tpatch->new_mode;3000}else if(!cached) {3001 stat_ret =lstat(old_name, st);3002if(stat_ret && errno != ENOENT)3003returnerror("%s:%s", old_name,strerror(errno));3004}30053006if(to_be_deleted(tpatch))3007 tpatch = NULL;30083009if(check_index && !tpatch) {3010int pos =cache_name_pos(old_name,strlen(old_name));3011if(pos <0) {3012if(patch->is_new <0)3013goto is_new;3014returnerror("%s: does not exist in index", old_name);3015}3016*ce = active_cache[pos];3017if(stat_ret <0) {3018struct checkout costate;3019/* checkout */3020memset(&costate,0,sizeof(costate));3021 costate.base_dir ="";3022 costate.refresh_cache =1;3023if(checkout_entry(*ce, &costate, NULL) ||3024lstat(old_name, st))3025return-1;3026}3027if(!cached &&verify_index_match(*ce, st))3028returnerror("%s: does not match index", old_name);3029if(cached)3030 st_mode = (*ce)->ce_mode;3031}else if(stat_ret <0) {3032if(patch->is_new <0)3033goto is_new;3034returnerror("%s:%s", old_name,strerror(errno));3035}30363037if(!cached && !tpatch)3038 st_mode =ce_mode_from_stat(*ce, st->st_mode);30393040if(patch->is_new <0)3041 patch->is_new =0;3042if(!patch->old_mode)3043 patch->old_mode = st_mode;3044if((st_mode ^ patch->old_mode) & S_IFMT)3045returnerror("%s: wrong type", old_name);3046if(st_mode != patch->old_mode)3047warning("%shas type%o, expected%o",3048 old_name, st_mode, patch->old_mode);3049if(!patch->new_mode && !patch->is_delete)3050 patch->new_mode = st_mode;3051return0;30523053 is_new:3054 patch->is_new =1;3055 patch->is_delete =0;3056 patch->old_name = NULL;3057return0;3058}30593060static intcheck_patch(struct patch *patch)3061{3062struct stat st;3063const char*old_name = patch->old_name;3064const char*new_name = patch->new_name;3065const char*name = old_name ? old_name : new_name;3066struct cache_entry *ce = NULL;3067struct patch *tpatch;3068int ok_if_exists;3069int status;30703071 patch->rejected =1;/* we will drop this after we succeed */30723073 status =check_preimage(patch, &ce, &st);3074if(status)3075return status;3076 old_name = patch->old_name;30773078if((tpatch =in_fn_table(new_name)) &&3079(was_deleted(tpatch) ||to_be_deleted(tpatch)))3080/*3081 * A type-change diff is always split into a patch to3082 * delete old, immediately followed by a patch to3083 * create new (see diff.c::run_diff()); in such a case3084 * it is Ok that the entry to be deleted by the3085 * previous patch is still in the working tree and in3086 * the index.3087 */3088 ok_if_exists =1;3089else3090 ok_if_exists =0;30913092if(new_name &&3093((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {3094if(check_index &&3095cache_name_pos(new_name,strlen(new_name)) >=0&&3096!ok_if_exists)3097returnerror("%s: already exists in index", new_name);3098if(!cached) {3099int err =check_to_create_blob(new_name, ok_if_exists);3100if(err)3101return err;3102}3103if(!patch->new_mode) {3104if(0< patch->is_new)3105 patch->new_mode = S_IFREG |0644;3106else3107 patch->new_mode = patch->old_mode;3108}3109}31103111if(new_name && old_name) {3112int same = !strcmp(old_name, new_name);3113if(!patch->new_mode)3114 patch->new_mode = patch->old_mode;3115if((patch->old_mode ^ patch->new_mode) & S_IFMT)3116returnerror("new mode (%o) of%sdoes not match old mode (%o)%s%s",3117 patch->new_mode, new_name, patch->old_mode,3118 same ?"":" of ", same ?"": old_name);3119}31203121if(apply_data(patch, &st, ce) <0)3122returnerror("%s: patch does not apply", name);3123 patch->rejected =0;3124return0;3125}31263127static intcheck_patch_list(struct patch *patch)3128{3129int err =0;31303131prepare_fn_table(patch);3132while(patch) {3133if(apply_verbosely)3134say_patch_name(stderr,3135"Checking patch ", patch,"...\n");3136 err |=check_patch(patch);3137 patch = patch->next;3138}3139return err;3140}31413142/* This function tries to read the sha1 from the current index */3143static intget_current_sha1(const char*path,unsigned char*sha1)3144{3145int pos;31463147if(read_cache() <0)3148return-1;3149 pos =cache_name_pos(path,strlen(path));3150if(pos <0)3151return-1;3152hashcpy(sha1, active_cache[pos]->sha1);3153return0;3154}31553156/* Build an index that contains the just the files needed for a 3way merge */3157static voidbuild_fake_ancestor(struct patch *list,const char*filename)3158{3159struct patch *patch;3160struct index_state result = { NULL };3161int fd;31623163/* Once we start supporting the reverse patch, it may be3164 * worth showing the new sha1 prefix, but until then...3165 */3166for(patch = list; patch; patch = patch->next) {3167const unsigned char*sha1_ptr;3168unsigned char sha1[20];3169struct cache_entry *ce;3170const char*name;31713172 name = patch->old_name ? patch->old_name : patch->new_name;3173if(0< patch->is_new)3174continue;3175else if(get_sha1(patch->old_sha1_prefix, sha1))3176/* git diff has no index line for mode/type changes */3177if(!patch->lines_added && !patch->lines_deleted) {3178if(get_current_sha1(patch->old_name, sha1))3179die("mode change for%s, which is not "3180"in current HEAD", name);3181 sha1_ptr = sha1;3182}else3183die("sha1 information is lacking or useless "3184"(%s).", name);3185else3186 sha1_ptr = sha1;31873188 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);3189if(!ce)3190die("make_cache_entry failed for path '%s'", name);3191if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3192die("Could not add%sto temporary index", name);3193}31943195 fd =open(filename, O_WRONLY | O_CREAT,0666);3196if(fd <0||write_index(&result, fd) ||close(fd))3197die("Could not write temporary index to%s", filename);31983199discard_index(&result);3200}32013202static voidstat_patch_list(struct patch *patch)3203{3204int files, adds, dels;32053206for(files = adds = dels =0; patch ; patch = patch->next) {3207 files++;3208 adds += patch->lines_added;3209 dels += patch->lines_deleted;3210show_stats(patch);3211}32123213printf("%dfiles changed,%dinsertions(+),%ddeletions(-)\n", files, adds, dels);3214}32153216static voidnumstat_patch_list(struct patch *patch)3217{3218for( ; patch; patch = patch->next) {3219const char*name;3220 name = patch->new_name ? patch->new_name : patch->old_name;3221if(patch->is_binary)3222printf("-\t-\t");3223else3224printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3225write_name_quoted(name, stdout, line_termination);3226}3227}32283229static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3230{3231if(mode)3232printf("%smode%06o%s\n", newdelete, mode, name);3233else3234printf("%s %s\n", newdelete, name);3235}32363237static voidshow_mode_change(struct patch *p,int show_name)3238{3239if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3240if(show_name)3241printf(" mode change%06o =>%06o%s\n",3242 p->old_mode, p->new_mode, p->new_name);3243else3244printf(" mode change%06o =>%06o\n",3245 p->old_mode, p->new_mode);3246}3247}32483249static voidshow_rename_copy(struct patch *p)3250{3251const char*renamecopy = p->is_rename ?"rename":"copy";3252const char*old, *new;32533254/* Find common prefix */3255 old = p->old_name;3256new= p->new_name;3257while(1) {3258const char*slash_old, *slash_new;3259 slash_old =strchr(old,'/');3260 slash_new =strchr(new,'/');3261if(!slash_old ||3262!slash_new ||3263 slash_old - old != slash_new -new||3264memcmp(old,new, slash_new -new))3265break;3266 old = slash_old +1;3267new= slash_new +1;3268}3269/* p->old_name thru old is the common prefix, and old and new3270 * through the end of names are renames3271 */3272if(old != p->old_name)3273printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,3274(int)(old - p->old_name), p->old_name,3275 old,new, p->score);3276else3277printf("%s %s=>%s(%d%%)\n", renamecopy,3278 p->old_name, p->new_name, p->score);3279show_mode_change(p,0);3280}32813282static voidsummary_patch_list(struct patch *patch)3283{3284struct patch *p;32853286for(p = patch; p; p = p->next) {3287if(p->is_new)3288show_file_mode_name("create", p->new_mode, p->new_name);3289else if(p->is_delete)3290show_file_mode_name("delete", p->old_mode, p->old_name);3291else{3292if(p->is_rename || p->is_copy)3293show_rename_copy(p);3294else{3295if(p->score) {3296printf(" rewrite%s(%d%%)\n",3297 p->new_name, p->score);3298show_mode_change(p,0);3299}3300else3301show_mode_change(p,1);3302}3303}3304}3305}33063307static voidpatch_stats(struct patch *patch)3308{3309int lines = patch->lines_added + patch->lines_deleted;33103311if(lines > max_change)3312 max_change = lines;3313if(patch->old_name) {3314int len =quote_c_style(patch->old_name, NULL, NULL,0);3315if(!len)3316 len =strlen(patch->old_name);3317if(len > max_len)3318 max_len = len;3319}3320if(patch->new_name) {3321int len =quote_c_style(patch->new_name, NULL, NULL,0);3322if(!len)3323 len =strlen(patch->new_name);3324if(len > max_len)3325 max_len = len;3326}3327}33283329static voidremove_file(struct patch *patch,int rmdir_empty)3330{3331if(update_index) {3332if(remove_file_from_cache(patch->old_name) <0)3333die("unable to remove%sfrom index", patch->old_name);3334}3335if(!cached) {3336if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {3337remove_path(patch->old_name);3338}3339}3340}33413342static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)3343{3344struct stat st;3345struct cache_entry *ce;3346int namelen =strlen(path);3347unsigned ce_size =cache_entry_size(namelen);33483349if(!update_index)3350return;33513352 ce =xcalloc(1, ce_size);3353memcpy(ce->name, path, namelen);3354 ce->ce_mode =create_ce_mode(mode);3355 ce->ce_flags = namelen;3356if(S_ISGITLINK(mode)) {3357const char*s = buf;33583359if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))3360die("corrupt patch for subproject%s", path);3361}else{3362if(!cached) {3363if(lstat(path, &st) <0)3364die_errno("unable to stat newly created file '%s'",3365 path);3366fill_stat_cache_info(ce, &st);3367}3368if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)3369die("unable to create backing store for newly created file%s", path);3370}3371if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3372die("unable to add cache entry for%s", path);3373}33743375static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)3376{3377int fd;3378struct strbuf nbuf = STRBUF_INIT;33793380if(S_ISGITLINK(mode)) {3381struct stat st;3382if(!lstat(path, &st) &&S_ISDIR(st.st_mode))3383return0;3384returnmkdir(path,0777);3385}33863387if(has_symlinks &&S_ISLNK(mode))3388/* Although buf:size is counted string, it also is NUL3389 * terminated.3390 */3391returnsymlink(buf, path);33923393 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);3394if(fd <0)3395return-1;33963397if(convert_to_working_tree(path, buf, size, &nbuf)) {3398 size = nbuf.len;3399 buf = nbuf.buf;3400}3401write_or_die(fd, buf, size);3402strbuf_release(&nbuf);34033404if(close(fd) <0)3405die_errno("closing file '%s'", path);3406return0;3407}34083409/*3410 * We optimistically assume that the directories exist,3411 * which is true 99% of the time anyway. If they don't,3412 * we create them and try again.3413 */3414static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)3415{3416if(cached)3417return;3418if(!try_create_file(path, mode, buf, size))3419return;34203421if(errno == ENOENT) {3422if(safe_create_leading_directories(path))3423return;3424if(!try_create_file(path, mode, buf, size))3425return;3426}34273428if(errno == EEXIST || errno == EACCES) {3429/* We may be trying to create a file where a directory3430 * used to be.3431 */3432struct stat st;3433if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))3434 errno = EEXIST;3435}34363437if(errno == EEXIST) {3438unsigned int nr =getpid();34393440for(;;) {3441char newpath[PATH_MAX];3442mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);3443if(!try_create_file(newpath, mode, buf, size)) {3444if(!rename(newpath, path))3445return;3446unlink_or_warn(newpath);3447break;3448}3449if(errno != EEXIST)3450break;3451++nr;3452}3453}3454die_errno("unable to write file '%s' mode%o", path, mode);3455}34563457static voidcreate_file(struct patch *patch)3458{3459char*path = patch->new_name;3460unsigned mode = patch->new_mode;3461unsigned long size = patch->resultsize;3462char*buf = patch->result;34633464if(!mode)3465 mode = S_IFREG |0644;3466create_one_file(path, mode, buf, size);3467add_index_file(path, mode, buf, size);3468}34693470/* phase zero is to remove, phase one is to create */3471static voidwrite_out_one_result(struct patch *patch,int phase)3472{3473if(patch->is_delete >0) {3474if(phase ==0)3475remove_file(patch,1);3476return;3477}3478if(patch->is_new >0|| patch->is_copy) {3479if(phase ==1)3480create_file(patch);3481return;3482}3483/*3484 * Rename or modification boils down to the same3485 * thing: remove the old, write the new3486 */3487if(phase ==0)3488remove_file(patch, patch->is_rename);3489if(phase ==1)3490create_file(patch);3491}34923493static intwrite_out_one_reject(struct patch *patch)3494{3495FILE*rej;3496char namebuf[PATH_MAX];3497struct fragment *frag;3498int cnt =0;34993500for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {3501if(!frag->rejected)3502continue;3503 cnt++;3504}35053506if(!cnt) {3507if(apply_verbosely)3508say_patch_name(stderr,3509"Applied patch ", patch," cleanly.\n");3510return0;3511}35123513/* This should not happen, because a removal patch that leaves3514 * contents are marked "rejected" at the patch level.3515 */3516if(!patch->new_name)3517die("internal error");35183519/* Say this even without --verbose */3520say_patch_name(stderr,"Applying patch ", patch," with");3521fprintf(stderr,"%drejects...\n", cnt);35223523 cnt =strlen(patch->new_name);3524if(ARRAY_SIZE(namebuf) <= cnt +5) {3525 cnt =ARRAY_SIZE(namebuf) -5;3526warning("truncating .rej filename to %.*s.rej",3527 cnt -1, patch->new_name);3528}3529memcpy(namebuf, patch->new_name, cnt);3530memcpy(namebuf + cnt,".rej",5);35313532 rej =fopen(namebuf,"w");3533if(!rej)3534returnerror("cannot open%s:%s", namebuf,strerror(errno));35353536/* Normal git tools never deal with .rej, so do not pretend3537 * this is a git patch by saying --git nor give extended3538 * headers. While at it, maybe please "kompare" that wants3539 * the trailing TAB and some garbage at the end of line ;-).3540 */3541fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",3542 patch->new_name, patch->new_name);3543for(cnt =1, frag = patch->fragments;3544 frag;3545 cnt++, frag = frag->next) {3546if(!frag->rejected) {3547fprintf(stderr,"Hunk #%dapplied cleanly.\n", cnt);3548continue;3549}3550fprintf(stderr,"Rejected hunk #%d.\n", cnt);3551fprintf(rej,"%.*s", frag->size, frag->patch);3552if(frag->patch[frag->size-1] !='\n')3553fputc('\n', rej);3554}3555fclose(rej);3556return-1;3557}35583559static intwrite_out_results(struct patch *list,int skipped_patch)3560{3561int phase;3562int errs =0;3563struct patch *l;35643565if(!list && !skipped_patch)3566returnerror("No changes");35673568for(phase =0; phase <2; phase++) {3569 l = list;3570while(l) {3571if(l->rejected)3572 errs =1;3573else{3574write_out_one_result(l, phase);3575if(phase ==1&&write_out_one_reject(l))3576 errs =1;3577}3578 l = l->next;3579}3580}3581return errs;3582}35833584static struct lock_file lock_file;35853586static struct string_list limit_by_name;3587static int has_include;3588static voidadd_name_limit(const char*name,int exclude)3589{3590struct string_list_item *it;35913592 it =string_list_append(&limit_by_name, name);3593 it->util = exclude ? NULL : (void*)1;3594}35953596static intuse_patch(struct patch *p)3597{3598const char*pathname = p->new_name ? p->new_name : p->old_name;3599int i;36003601/* Paths outside are not touched regardless of "--include" */3602if(0< prefix_length) {3603int pathlen =strlen(pathname);3604if(pathlen <= prefix_length ||3605memcmp(prefix, pathname, prefix_length))3606return0;3607}36083609/* See if it matches any of exclude/include rule */3610for(i =0; i < limit_by_name.nr; i++) {3611struct string_list_item *it = &limit_by_name.items[i];3612if(!fnmatch(it->string, pathname,0))3613return(it->util != NULL);3614}36153616/*3617 * If we had any include, a path that does not match any rule is3618 * not used. Otherwise, we saw bunch of exclude rules (or none)3619 * and such a path is used.3620 */3621return!has_include;3622}362336243625static voidprefix_one(char**name)3626{3627char*old_name = *name;3628if(!old_name)3629return;3630*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3631free(old_name);3632}36333634static voidprefix_patches(struct patch *p)3635{3636if(!prefix || p->is_toplevel_relative)3637return;3638for( ; p; p = p->next) {3639if(p->new_name == p->old_name) {3640char*prefixed = p->new_name;3641prefix_one(&prefixed);3642 p->new_name = p->old_name = prefixed;3643}3644else{3645prefix_one(&p->new_name);3646prefix_one(&p->old_name);3647}3648}3649}36503651#define INACCURATE_EOF (1<<0)3652#define RECOUNT (1<<1)36533654static intapply_patch(int fd,const char*filename,int options)3655{3656size_t offset;3657struct strbuf buf = STRBUF_INIT;3658struct patch *list = NULL, **listp = &list;3659int skipped_patch =0;36603661/* FIXME - memory leak when using multiple patch files as inputs */3662memset(&fn_table,0,sizeof(struct string_list));3663 patch_input_file = filename;3664read_patch_file(&buf, fd);3665 offset =0;3666while(offset < buf.len) {3667struct patch *patch;3668int nr;36693670 patch =xcalloc(1,sizeof(*patch));3671 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3672 patch->recount = !!(options & RECOUNT);3673 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3674if(nr <0)3675break;3676if(apply_in_reverse)3677reverse_patches(patch);3678if(prefix)3679prefix_patches(patch);3680if(use_patch(patch)) {3681patch_stats(patch);3682*listp = patch;3683 listp = &patch->next;3684}3685else{3686/* perhaps free it a bit better? */3687free(patch);3688 skipped_patch++;3689}3690 offset += nr;3691}36923693if(whitespace_error && (ws_error_action == die_on_ws_error))3694 apply =0;36953696 update_index = check_index && apply;3697if(update_index && newfd <0)3698 newfd =hold_locked_index(&lock_file,1);36993700if(check_index) {3701if(read_cache() <0)3702die("unable to read index file");3703}37043705if((check || apply) &&3706check_patch_list(list) <0&&3707!apply_with_reject)3708exit(1);37093710if(apply &&write_out_results(list, skipped_patch))3711exit(1);37123713if(fake_ancestor)3714build_fake_ancestor(list, fake_ancestor);37153716if(diffstat)3717stat_patch_list(list);37183719if(numstat)3720numstat_patch_list(list);37213722if(summary)3723summary_patch_list(list);37243725strbuf_release(&buf);3726return0;3727}37283729static intgit_apply_config(const char*var,const char*value,void*cb)3730{3731if(!strcmp(var,"apply.whitespace"))3732returngit_config_string(&apply_default_whitespace, var, value);3733else if(!strcmp(var,"apply.ignorewhitespace"))3734returngit_config_string(&apply_default_ignorewhitespace, var, value);3735returngit_default_config(var, value, cb);3736}37373738static intoption_parse_exclude(const struct option *opt,3739const char*arg,int unset)3740{3741add_name_limit(arg,1);3742return0;3743}37443745static intoption_parse_include(const struct option *opt,3746const char*arg,int unset)3747{3748add_name_limit(arg,0);3749 has_include =1;3750return0;3751}37523753static intoption_parse_p(const struct option *opt,3754const char*arg,int unset)3755{3756 p_value =atoi(arg);3757 p_value_known =1;3758return0;3759}37603761static intoption_parse_z(const struct option *opt,3762const char*arg,int unset)3763{3764if(unset)3765 line_termination ='\n';3766else3767 line_termination =0;3768return0;3769}37703771static intoption_parse_space_change(const struct option *opt,3772const char*arg,int unset)3773{3774if(unset)3775 ws_ignore_action = ignore_ws_none;3776else3777 ws_ignore_action = ignore_ws_change;3778return0;3779}37803781static intoption_parse_whitespace(const struct option *opt,3782const char*arg,int unset)3783{3784const char**whitespace_option = opt->value;37853786*whitespace_option = arg;3787parse_whitespace_option(arg);3788return0;3789}37903791static intoption_parse_directory(const struct option *opt,3792const char*arg,int unset)3793{3794 root_len =strlen(arg);3795if(root_len && arg[root_len -1] !='/') {3796char*new_root;3797 root = new_root =xmalloc(root_len +2);3798strcpy(new_root, arg);3799strcpy(new_root + root_len++,"/");3800}else3801 root = arg;3802return0;3803}38043805intcmd_apply(int argc,const char**argv,const char*prefix_)3806{3807int i;3808int errs =0;3809int is_not_gitdir = !startup_info->have_repository;3810int binary;3811int force_apply =0;38123813const char*whitespace_option = NULL;38143815struct option builtin_apply_options[] = {3816{ OPTION_CALLBACK,0,"exclude", NULL,"path",3817"don't apply changes matching the given path",38180, option_parse_exclude },3819{ OPTION_CALLBACK,0,"include", NULL,"path",3820"apply changes matching the given path",38210, option_parse_include },3822{ OPTION_CALLBACK,'p', NULL, NULL,"num",3823"remove <num> leading slashes from traditional diff paths",38240, option_parse_p },3825OPT_BOOLEAN(0,"no-add", &no_add,3826"ignore additions made by the patch"),3827OPT_BOOLEAN(0,"stat", &diffstat,3828"instead of applying the patch, output diffstat for the input"),3829{ OPTION_BOOLEAN,0,"allow-binary-replacement", &binary,3830 NULL,"old option, now no-op",3831 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3832{ OPTION_BOOLEAN,0,"binary", &binary,3833 NULL,"old option, now no-op",3834 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3835OPT_BOOLEAN(0,"numstat", &numstat,3836"shows number of added and deleted lines in decimal notation"),3837OPT_BOOLEAN(0,"summary", &summary,3838"instead of applying the patch, output a summary for the input"),3839OPT_BOOLEAN(0,"check", &check,3840"instead of applying the patch, see if the patch is applicable"),3841OPT_BOOLEAN(0,"index", &check_index,3842"make sure the patch is applicable to the current index"),3843OPT_BOOLEAN(0,"cached", &cached,3844"apply a patch without touching the working tree"),3845OPT_BOOLEAN(0,"apply", &force_apply,3846"also apply the patch (use with --stat/--summary/--check)"),3847OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,3848"build a temporary index based on embedded index information"),3849{ OPTION_CALLBACK,'z', NULL, NULL, NULL,3850"paths are separated with NUL character",3851 PARSE_OPT_NOARG, option_parse_z },3852OPT_INTEGER('C', NULL, &p_context,3853"ensure at least <n> lines of context match"),3854{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,"action",3855"detect new or modified lines that have whitespace errors",38560, option_parse_whitespace },3857{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,3858"ignore changes in whitespace when finding context",3859 PARSE_OPT_NOARG, option_parse_space_change },3860{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,3861"ignore changes in whitespace when finding context",3862 PARSE_OPT_NOARG, option_parse_space_change },3863OPT_BOOLEAN('R',"reverse", &apply_in_reverse,3864"apply the patch in reverse"),3865OPT_BOOLEAN(0,"unidiff-zero", &unidiff_zero,3866"don't expect at least one line of context"),3867OPT_BOOLEAN(0,"reject", &apply_with_reject,3868"leave the rejected hunks in corresponding *.rej files"),3869OPT__VERBOSE(&apply_verbosely),3870OPT_BIT(0,"inaccurate-eof", &options,3871"tolerate incorrectly detected missing new-line at the end of file",3872 INACCURATE_EOF),3873OPT_BIT(0,"recount", &options,3874"do not trust the line counts in the hunk headers",3875 RECOUNT),3876{ OPTION_CALLBACK,0,"directory", NULL,"root",3877"prepend <root> to all filenames",38780, option_parse_directory },3879OPT_END()3880};38813882 prefix = prefix_;3883 prefix_length = prefix ?strlen(prefix) :0;3884git_config(git_apply_config, NULL);3885if(apply_default_whitespace)3886parse_whitespace_option(apply_default_whitespace);3887if(apply_default_ignorewhitespace)3888parse_ignorewhitespace_option(apply_default_ignorewhitespace);38893890 argc =parse_options(argc, argv, prefix, builtin_apply_options,3891 apply_usage,0);38923893if(apply_with_reject)3894 apply = apply_verbosely =1;3895if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))3896 apply =0;3897if(check_index && is_not_gitdir)3898die("--index outside a repository");3899if(cached) {3900if(is_not_gitdir)3901die("--cached outside a repository");3902 check_index =1;3903}3904for(i =0; i < argc; i++) {3905const char*arg = argv[i];3906int fd;39073908if(!strcmp(arg,"-")) {3909 errs |=apply_patch(0,"<stdin>", options);3910 read_stdin =0;3911continue;3912}else if(0< prefix_length)3913 arg =prefix_filename(prefix, prefix_length, arg);39143915 fd =open(arg, O_RDONLY);3916if(fd <0)3917die_errno("can't open patch '%s'", arg);3918 read_stdin =0;3919set_default_whitespace_mode(whitespace_option);3920 errs |=apply_patch(fd, arg, options);3921close(fd);3922}3923set_default_whitespace_mode(whitespace_option);3924if(read_stdin)3925 errs |=apply_patch(0,"<stdin>", options);3926if(whitespace_error) {3927if(squelch_whitespace_errors &&3928 squelch_whitespace_errors < whitespace_error) {3929int squelched =3930 whitespace_error - squelch_whitespace_errors;3931warning("squelched%d"3932"whitespace error%s",3933 squelched,3934 squelched ==1?"":"s");3935}3936if(ws_error_action == die_on_ws_error)3937die("%dline%sadd%swhitespace errors.",3938 whitespace_error,3939 whitespace_error ==1?"":"s",3940 whitespace_error ==1?"s":"");3941if(applied_after_fixing_ws && apply)3942warning("%dline%sapplied after"3943" fixing whitespace errors.",3944 applied_after_fixing_ws,3945 applied_after_fixing_ws ==1?"":"s");3946else if(whitespace_error)3947warning("%dline%sadd%swhitespace errors.",3948 whitespace_error,3949 whitespace_error ==1?"":"s",3950 whitespace_error ==1?"s":"");3951}39523953if(update_index) {3954if(write_cache(newfd, active_cache, active_nr) ||3955commit_locked_index(&lock_file))3956die("Unable to write new index file");3957}39583959return!!errs;3960}