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#define LINE_PATCHED 2 208}; 209 210/* 211 * This represents a "file", which is an array of "lines". 212 */ 213struct image { 214char*buf; 215size_t len; 216size_t nr; 217size_t alloc; 218struct line *line_allocated; 219struct line *line; 220}; 221 222/* 223 * Records filenames that have been touched, in order to handle 224 * the case where more than one patches touch the same file. 225 */ 226 227static struct string_list fn_table; 228 229static uint32_thash_line(const char*cp,size_t len) 230{ 231size_t i; 232uint32_t h; 233for(i =0, h =0; i < len; i++) { 234if(!isspace(cp[i])) { 235 h = h *3+ (cp[i] &0xff); 236} 237} 238return h; 239} 240 241/* 242 * Compare lines s1 of length n1 and s2 of length n2, ignoring 243 * whitespace difference. Returns 1 if they match, 0 otherwise 244 */ 245static intfuzzy_matchlines(const char*s1,size_t n1, 246const char*s2,size_t n2) 247{ 248const char*last1 = s1 + n1 -1; 249const char*last2 = s2 + n2 -1; 250int result =0; 251 252if(n1 <0|| n2 <0) 253return0; 254 255/* ignore line endings */ 256while((*last1 =='\r') || (*last1 =='\n')) 257 last1--; 258while((*last2 =='\r') || (*last2 =='\n')) 259 last2--; 260 261/* skip leading whitespace */ 262while(isspace(*s1) && (s1 <= last1)) 263 s1++; 264while(isspace(*s2) && (s2 <= last2)) 265 s2++; 266/* early return if both lines are empty */ 267if((s1 > last1) && (s2 > last2)) 268return1; 269while(!result) { 270 result = *s1++ - *s2++; 271/* 272 * Skip whitespace inside. We check for whitespace on 273 * both buffers because we don't want "a b" to match 274 * "ab" 275 */ 276if(isspace(*s1) &&isspace(*s2)) { 277while(isspace(*s1) && s1 <= last1) 278 s1++; 279while(isspace(*s2) && s2 <= last2) 280 s2++; 281} 282/* 283 * If we reached the end on one side only, 284 * lines don't match 285 */ 286if( 287((s2 > last2) && (s1 <= last1)) || 288((s1 > last1) && (s2 <= last2))) 289return0; 290if((s1 > last1) && (s2 > last2)) 291break; 292} 293 294return!result; 295} 296 297static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 298{ 299ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 300 img->line_allocated[img->nr].len = len; 301 img->line_allocated[img->nr].hash =hash_line(bol, len); 302 img->line_allocated[img->nr].flag = flag; 303 img->nr++; 304} 305 306static voidprepare_image(struct image *image,char*buf,size_t len, 307int prepare_linetable) 308{ 309const char*cp, *ep; 310 311memset(image,0,sizeof(*image)); 312 image->buf = buf; 313 image->len = len; 314 315if(!prepare_linetable) 316return; 317 318 ep = image->buf + image->len; 319 cp = image->buf; 320while(cp < ep) { 321const char*next; 322for(next = cp; next < ep && *next !='\n'; next++) 323; 324if(next < ep) 325 next++; 326add_line_info(image, cp, next - cp,0); 327 cp = next; 328} 329 image->line = image->line_allocated; 330} 331 332static voidclear_image(struct image *image) 333{ 334free(image->buf); 335 image->buf = NULL; 336 image->len =0; 337} 338 339static voidsay_patch_name(FILE*output,const char*pre, 340struct patch *patch,const char*post) 341{ 342fputs(pre, output); 343if(patch->old_name && patch->new_name && 344strcmp(patch->old_name, patch->new_name)) { 345quote_c_style(patch->old_name, NULL, output,0); 346fputs(" => ", output); 347quote_c_style(patch->new_name, NULL, output,0); 348}else{ 349const char*n = patch->new_name; 350if(!n) 351 n = patch->old_name; 352quote_c_style(n, NULL, output,0); 353} 354fputs(post, output); 355} 356 357#define CHUNKSIZE (8192) 358#define SLOP (16) 359 360static voidread_patch_file(struct strbuf *sb,int fd) 361{ 362if(strbuf_read(sb, fd,0) <0) 363die_errno("git apply: failed to read"); 364 365/* 366 * Make sure that we have some slop in the buffer 367 * so that we can do speculative "memcmp" etc, and 368 * see to it that it is NUL-filled. 369 */ 370strbuf_grow(sb, SLOP); 371memset(sb->buf + sb->len,0, SLOP); 372} 373 374static unsigned longlinelen(const char*buffer,unsigned long size) 375{ 376unsigned long len =0; 377while(size--) { 378 len++; 379if(*buffer++ =='\n') 380break; 381} 382return len; 383} 384 385static intis_dev_null(const char*str) 386{ 387return!memcmp("/dev/null", str,9) &&isspace(str[9]); 388} 389 390#define TERM_SPACE 1 391#define TERM_TAB 2 392 393static intname_terminate(const char*name,int namelen,int c,int terminate) 394{ 395if(c ==' '&& !(terminate & TERM_SPACE)) 396return0; 397if(c =='\t'&& !(terminate & TERM_TAB)) 398return0; 399 400return1; 401} 402 403/* remove double slashes to make --index work with such filenames */ 404static char*squash_slash(char*name) 405{ 406int i =0, j =0; 407 408if(!name) 409return NULL; 410 411while(name[i]) { 412if((name[j++] = name[i++]) =='/') 413while(name[i] =='/') 414 i++; 415} 416 name[j] ='\0'; 417return name; 418} 419 420static char*find_name_gnu(const char*line,char*def,int p_value) 421{ 422struct strbuf name = STRBUF_INIT; 423char*cp; 424 425/* 426 * Proposed "new-style" GNU patch/diff format; see 427 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2 428 */ 429if(unquote_c_style(&name, line, NULL)) { 430strbuf_release(&name); 431return NULL; 432} 433 434for(cp = name.buf; p_value; p_value--) { 435 cp =strchr(cp,'/'); 436if(!cp) { 437strbuf_release(&name); 438return NULL; 439} 440 cp++; 441} 442 443/* name can later be freed, so we need 444 * to memmove, not just return cp 445 */ 446strbuf_remove(&name,0, cp - name.buf); 447free(def); 448if(root) 449strbuf_insert(&name,0, root, root_len); 450returnsquash_slash(strbuf_detach(&name, NULL)); 451} 452 453static size_tsane_tz_len(const char*line,size_t len) 454{ 455const char*tz, *p; 456 457if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 458return0; 459 tz = line + len -strlen(" +0500"); 460 461if(tz[1] !='+'&& tz[1] !='-') 462return0; 463 464for(p = tz +2; p != line + len; p++) 465if(!isdigit(*p)) 466return0; 467 468return line + len - tz; 469} 470 471static size_ttz_with_colon_len(const char*line,size_t len) 472{ 473const char*tz, *p; 474 475if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 476return0; 477 tz = line + len -strlen(" +08:00"); 478 479if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 480return0; 481 p = tz +2; 482if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 483!isdigit(*p++) || !isdigit(*p++)) 484return0; 485 486return line + len - tz; 487} 488 489static size_tdate_len(const char*line,size_t len) 490{ 491const char*date, *p; 492 493if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 494return0; 495 p = date = line + len -strlen("72-02-05"); 496 497if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 498!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 499!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 500return0; 501 502if(date - line >=strlen("19") && 503isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 504 date -=strlen("19"); 505 506return line + len - date; 507} 508 509static size_tshort_time_len(const char*line,size_t len) 510{ 511const char*time, *p; 512 513if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 514return0; 515 p = time = line + len -strlen(" 07:01:32"); 516 517/* Permit 1-digit hours? */ 518if(*p++ !=' '|| 519!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 520!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 521!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 522return0; 523 524return line + len - time; 525} 526 527static size_tfractional_time_len(const char*line,size_t len) 528{ 529const char*p; 530size_t n; 531 532/* Expected format: 19:41:17.620000023 */ 533if(!len || !isdigit(line[len -1])) 534return0; 535 p = line + len -1; 536 537/* Fractional seconds. */ 538while(p > line &&isdigit(*p)) 539 p--; 540if(*p !='.') 541return0; 542 543/* Hours, minutes, and whole seconds. */ 544 n =short_time_len(line, p - line); 545if(!n) 546return0; 547 548return line + len - p + n; 549} 550 551static size_ttrailing_spaces_len(const char*line,size_t len) 552{ 553const char*p; 554 555/* Expected format: ' ' x (1 or more) */ 556if(!len || line[len -1] !=' ') 557return0; 558 559 p = line + len; 560while(p != line) { 561 p--; 562if(*p !=' ') 563return line + len - (p +1); 564} 565 566/* All spaces! */ 567return len; 568} 569 570static size_tdiff_timestamp_len(const char*line,size_t len) 571{ 572const char*end = line + len; 573size_t n; 574 575/* 576 * Posix: 2010-07-05 19:41:17 577 * GNU: 2010-07-05 19:41:17.620000023 -0500 578 */ 579 580if(!isdigit(end[-1])) 581return0; 582 583 n =sane_tz_len(line, end - line); 584if(!n) 585 n =tz_with_colon_len(line, end - line); 586 end -= n; 587 588 n =short_time_len(line, end - line); 589if(!n) 590 n =fractional_time_len(line, end - line); 591 end -= n; 592 593 n =date_len(line, end - line); 594if(!n)/* No date. Too bad. */ 595return0; 596 end -= n; 597 598if(end == line)/* No space before date. */ 599return0; 600if(end[-1] =='\t') {/* Success! */ 601 end--; 602return line + len - end; 603} 604if(end[-1] !=' ')/* No space before date. */ 605return0; 606 607/* Whitespace damage. */ 608 end -=trailing_spaces_len(line, end - line); 609return line + len - end; 610} 611 612static char*find_name_common(const char*line,char*def,int p_value, 613const char*end,int terminate) 614{ 615int len; 616const char*start = NULL; 617 618if(p_value ==0) 619 start = line; 620while(line != end) { 621char c = *line; 622 623if(!end &&isspace(c)) { 624if(c =='\n') 625break; 626if(name_terminate(start, line-start, c, terminate)) 627break; 628} 629 line++; 630if(c =='/'&& !--p_value) 631 start = line; 632} 633if(!start) 634returnsquash_slash(def); 635 len = line - start; 636if(!len) 637returnsquash_slash(def); 638 639/* 640 * Generally we prefer the shorter name, especially 641 * if the other one is just a variation of that with 642 * something else tacked on to the end (ie "file.orig" 643 * or "file~"). 644 */ 645if(def) { 646int deflen =strlen(def); 647if(deflen < len && !strncmp(start, def, deflen)) 648returnsquash_slash(def); 649free(def); 650} 651 652if(root) { 653char*ret =xmalloc(root_len + len +1); 654strcpy(ret, root); 655memcpy(ret + root_len, start, len); 656 ret[root_len + len] ='\0'; 657returnsquash_slash(ret); 658} 659 660returnsquash_slash(xmemdupz(start, len)); 661} 662 663static char*find_name(const char*line,char*def,int p_value,int terminate) 664{ 665if(*line =='"') { 666char*name =find_name_gnu(line, def, p_value); 667if(name) 668return name; 669} 670 671returnfind_name_common(line, def, p_value, NULL, terminate); 672} 673 674static char*find_name_traditional(const char*line,char*def,int p_value) 675{ 676size_t len =strlen(line); 677size_t date_len; 678 679if(*line =='"') { 680char*name =find_name_gnu(line, def, p_value); 681if(name) 682return name; 683} 684 685 len =strchrnul(line,'\n') - line; 686 date_len =diff_timestamp_len(line, len); 687if(!date_len) 688returnfind_name_common(line, def, p_value, NULL, TERM_TAB); 689 len -= date_len; 690 691returnfind_name_common(line, def, p_value, line + len,0); 692} 693 694static intcount_slashes(const char*cp) 695{ 696int cnt =0; 697char ch; 698 699while((ch = *cp++)) 700if(ch =='/') 701 cnt++; 702return cnt; 703} 704 705/* 706 * Given the string after "--- " or "+++ ", guess the appropriate 707 * p_value for the given patch. 708 */ 709static intguess_p_value(const char*nameline) 710{ 711char*name, *cp; 712int val = -1; 713 714if(is_dev_null(nameline)) 715return-1; 716 name =find_name_traditional(nameline, NULL,0); 717if(!name) 718return-1; 719 cp =strchr(name,'/'); 720if(!cp) 721 val =0; 722else if(prefix) { 723/* 724 * Does it begin with "a/$our-prefix" and such? Then this is 725 * very likely to apply to our directory. 726 */ 727if(!strncmp(name, prefix, prefix_length)) 728 val =count_slashes(prefix); 729else{ 730 cp++; 731if(!strncmp(cp, prefix, prefix_length)) 732 val =count_slashes(prefix) +1; 733} 734} 735free(name); 736return val; 737} 738 739/* 740 * Does the ---/+++ line has the POSIX timestamp after the last HT? 741 * GNU diff puts epoch there to signal a creation/deletion event. Is 742 * this such a timestamp? 743 */ 744static inthas_epoch_timestamp(const char*nameline) 745{ 746/* 747 * We are only interested in epoch timestamp; any non-zero 748 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 749 * For the same reason, the date must be either 1969-12-31 or 750 * 1970-01-01, and the seconds part must be "00". 751 */ 752const char stamp_regexp[] = 753"^(1969-12-31|1970-01-01)" 754" " 755"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 756" " 757"([-+][0-2][0-9]:?[0-5][0-9])\n"; 758const char*timestamp = NULL, *cp, *colon; 759static regex_t *stamp; 760 regmatch_t m[10]; 761int zoneoffset; 762int hourminute; 763int status; 764 765for(cp = nameline; *cp !='\n'; cp++) { 766if(*cp =='\t') 767 timestamp = cp +1; 768} 769if(!timestamp) 770return0; 771if(!stamp) { 772 stamp =xmalloc(sizeof(*stamp)); 773if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 774warning("Cannot prepare timestamp regexp%s", 775 stamp_regexp); 776return0; 777} 778} 779 780 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 781if(status) { 782if(status != REG_NOMATCH) 783warning("regexec returned%dfor input:%s", 784 status, timestamp); 785return0; 786} 787 788 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 789if(*colon ==':') 790 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 791else 792 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 793if(timestamp[m[3].rm_so] =='-') 794 zoneoffset = -zoneoffset; 795 796/* 797 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 798 * (west of GMT) or 1970-01-01 (east of GMT) 799 */ 800if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 801(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 802return0; 803 804 hourminute = (strtol(timestamp +11, NULL,10) *60+ 805strtol(timestamp +14, NULL,10) - 806 zoneoffset); 807 808return((zoneoffset <0&& hourminute ==1440) || 809(0<= zoneoffset && !hourminute)); 810} 811 812/* 813 * Get the name etc info from the ---/+++ lines of a traditional patch header 814 * 815 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 816 * files, we can happily check the index for a match, but for creating a 817 * new file we should try to match whatever "patch" does. I have no idea. 818 */ 819static voidparse_traditional_patch(const char*first,const char*second,struct patch *patch) 820{ 821char*name; 822 823 first +=4;/* skip "--- " */ 824 second +=4;/* skip "+++ " */ 825if(!p_value_known) { 826int p, q; 827 p =guess_p_value(first); 828 q =guess_p_value(second); 829if(p <0) p = q; 830if(0<= p && p == q) { 831 p_value = p; 832 p_value_known =1; 833} 834} 835if(is_dev_null(first)) { 836 patch->is_new =1; 837 patch->is_delete =0; 838 name =find_name_traditional(second, NULL, p_value); 839 patch->new_name = name; 840}else if(is_dev_null(second)) { 841 patch->is_new =0; 842 patch->is_delete =1; 843 name =find_name_traditional(first, NULL, p_value); 844 patch->old_name = name; 845}else{ 846 name =find_name_traditional(first, NULL, p_value); 847 name =find_name_traditional(second, name, p_value); 848if(has_epoch_timestamp(first)) { 849 patch->is_new =1; 850 patch->is_delete =0; 851 patch->new_name = name; 852}else if(has_epoch_timestamp(second)) { 853 patch->is_new =0; 854 patch->is_delete =1; 855 patch->old_name = name; 856}else{ 857 patch->old_name = patch->new_name = name; 858} 859} 860if(!name) 861die("unable to find filename in patch at line%d", linenr); 862} 863 864static intgitdiff_hdrend(const char*line,struct patch *patch) 865{ 866return-1; 867} 868 869/* 870 * We're anal about diff header consistency, to make 871 * sure that we don't end up having strange ambiguous 872 * patches floating around. 873 * 874 * As a result, gitdiff_{old|new}name() will check 875 * their names against any previous information, just 876 * to make sure.. 877 */ 878static char*gitdiff_verify_name(const char*line,int isnull,char*orig_name,const char*oldnew) 879{ 880if(!orig_name && !isnull) 881returnfind_name(line, NULL, p_value, TERM_TAB); 882 883if(orig_name) { 884int len; 885const char*name; 886char*another; 887 name = orig_name; 888 len =strlen(name); 889if(isnull) 890die("git apply: bad git-diff - expected /dev/null, got%son line%d", name, linenr); 891 another =find_name(line, NULL, p_value, TERM_TAB); 892if(!another ||memcmp(another, name, len +1)) 893die("git apply: bad git-diff - inconsistent%sfilename on line%d", oldnew, linenr); 894free(another); 895return orig_name; 896} 897else{ 898/* expect "/dev/null" */ 899if(memcmp("/dev/null", line,9) || line[9] !='\n') 900die("git apply: bad git-diff - expected /dev/null on line%d", linenr); 901return NULL; 902} 903} 904 905static intgitdiff_oldname(const char*line,struct patch *patch) 906{ 907 patch->old_name =gitdiff_verify_name(line, patch->is_new, patch->old_name,"old"); 908return0; 909} 910 911static intgitdiff_newname(const char*line,struct patch *patch) 912{ 913 patch->new_name =gitdiff_verify_name(line, patch->is_delete, patch->new_name,"new"); 914return0; 915} 916 917static intgitdiff_oldmode(const char*line,struct patch *patch) 918{ 919 patch->old_mode =strtoul(line, NULL,8); 920return0; 921} 922 923static intgitdiff_newmode(const char*line,struct patch *patch) 924{ 925 patch->new_mode =strtoul(line, NULL,8); 926return0; 927} 928 929static intgitdiff_delete(const char*line,struct patch *patch) 930{ 931 patch->is_delete =1; 932 patch->old_name = patch->def_name; 933returngitdiff_oldmode(line, patch); 934} 935 936static intgitdiff_newfile(const char*line,struct patch *patch) 937{ 938 patch->is_new =1; 939 patch->new_name = patch->def_name; 940returngitdiff_newmode(line, patch); 941} 942 943static intgitdiff_copysrc(const char*line,struct patch *patch) 944{ 945 patch->is_copy =1; 946 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0); 947return0; 948} 949 950static intgitdiff_copydst(const char*line,struct patch *patch) 951{ 952 patch->is_copy =1; 953 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0); 954return0; 955} 956 957static intgitdiff_renamesrc(const char*line,struct patch *patch) 958{ 959 patch->is_rename =1; 960 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0); 961return0; 962} 963 964static intgitdiff_renamedst(const char*line,struct patch *patch) 965{ 966 patch->is_rename =1; 967 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0); 968return0; 969} 970 971static intgitdiff_similarity(const char*line,struct patch *patch) 972{ 973if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 974 patch->score =0; 975return0; 976} 977 978static intgitdiff_dissimilarity(const char*line,struct patch *patch) 979{ 980if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 981 patch->score =0; 982return0; 983} 984 985static intgitdiff_index(const char*line,struct patch *patch) 986{ 987/* 988 * index line is N hexadecimal, "..", N hexadecimal, 989 * and optional space with octal mode. 990 */ 991const char*ptr, *eol; 992int len; 993 994 ptr =strchr(line,'.'); 995if(!ptr || ptr[1] !='.'||40< ptr - line) 996return0; 997 len = ptr - line; 998memcpy(patch->old_sha1_prefix, line, len); 999 patch->old_sha1_prefix[len] =0;10001001 line = ptr +2;1002 ptr =strchr(line,' ');1003 eol =strchr(line,'\n');10041005if(!ptr || eol < ptr)1006 ptr = eol;1007 len = ptr - line;10081009if(40< len)1010return0;1011memcpy(patch->new_sha1_prefix, line, len);1012 patch->new_sha1_prefix[len] =0;1013if(*ptr ==' ')1014 patch->old_mode =strtoul(ptr+1, NULL,8);1015return0;1016}10171018/*1019 * This is normal for a diff that doesn't change anything: we'll fall through1020 * into the next diff. Tell the parser to break out.1021 */1022static intgitdiff_unrecognized(const char*line,struct patch *patch)1023{1024return-1;1025}10261027static const char*stop_at_slash(const char*line,int llen)1028{1029int nslash = p_value;1030int i;10311032for(i =0; i < llen; i++) {1033int ch = line[i];1034if(ch =='/'&& --nslash <=0)1035return&line[i];1036}1037return NULL;1038}10391040/*1041 * This is to extract the same name that appears on "diff --git"1042 * line. We do not find and return anything if it is a rename1043 * patch, and it is OK because we will find the name elsewhere.1044 * We need to reliably find name only when it is mode-change only,1045 * creation or deletion of an empty file. In any of these cases,1046 * both sides are the same name under a/ and b/ respectively.1047 */1048static char*git_header_name(char*line,int llen)1049{1050const char*name;1051const char*second = NULL;1052size_t len, line_len;10531054 line +=strlen("diff --git ");1055 llen -=strlen("diff --git ");10561057if(*line =='"') {1058const char*cp;1059struct strbuf first = STRBUF_INIT;1060struct strbuf sp = STRBUF_INIT;10611062if(unquote_c_style(&first, line, &second))1063goto free_and_fail1;10641065/* advance to the first slash */1066 cp =stop_at_slash(first.buf, first.len);1067/* we do not accept absolute paths */1068if(!cp || cp == first.buf)1069goto free_and_fail1;1070strbuf_remove(&first,0, cp +1- first.buf);10711072/*1073 * second points at one past closing dq of name.1074 * find the second name.1075 */1076while((second < line + llen) &&isspace(*second))1077 second++;10781079if(line + llen <= second)1080goto free_and_fail1;1081if(*second =='"') {1082if(unquote_c_style(&sp, second, NULL))1083goto free_and_fail1;1084 cp =stop_at_slash(sp.buf, sp.len);1085if(!cp || cp == sp.buf)1086goto free_and_fail1;1087/* They must match, otherwise ignore */1088if(strcmp(cp +1, first.buf))1089goto free_and_fail1;1090strbuf_release(&sp);1091returnstrbuf_detach(&first, NULL);1092}10931094/* unquoted second */1095 cp =stop_at_slash(second, line + llen - second);1096if(!cp || cp == second)1097goto free_and_fail1;1098 cp++;1099if(line + llen - cp != first.len +1||1100memcmp(first.buf, cp, first.len))1101goto free_and_fail1;1102returnstrbuf_detach(&first, NULL);11031104 free_and_fail1:1105strbuf_release(&first);1106strbuf_release(&sp);1107return NULL;1108}11091110/* unquoted first name */1111 name =stop_at_slash(line, llen);1112if(!name || name == line)1113return NULL;1114 name++;11151116/*1117 * since the first name is unquoted, a dq if exists must be1118 * the beginning of the second name.1119 */1120for(second = name; second < line + llen; second++) {1121if(*second =='"') {1122struct strbuf sp = STRBUF_INIT;1123const char*np;11241125if(unquote_c_style(&sp, second, NULL))1126goto free_and_fail2;11271128 np =stop_at_slash(sp.buf, sp.len);1129if(!np || np == sp.buf)1130goto free_and_fail2;1131 np++;11321133 len = sp.buf + sp.len - np;1134if(len < second - name &&1135!strncmp(np, name, len) &&1136isspace(name[len])) {1137/* Good */1138strbuf_remove(&sp,0, np - sp.buf);1139returnstrbuf_detach(&sp, NULL);1140}11411142 free_and_fail2:1143strbuf_release(&sp);1144return NULL;1145}1146}11471148/*1149 * Accept a name only if it shows up twice, exactly the same1150 * form.1151 */1152 second =strchr(name,'\n');1153if(!second)1154return NULL;1155 line_len = second - name;1156for(len =0; ; len++) {1157switch(name[len]) {1158default:1159continue;1160case'\n':1161return NULL;1162case'\t':case' ':1163 second =stop_at_slash(name + len, line_len - len);1164if(!second)1165return NULL;1166 second++;1167if(second[len] =='\n'&& !strncmp(name, second, len)) {1168returnxmemdupz(name, len);1169}1170}1171}1172}11731174/* Verify that we recognize the lines following a git header */1175static intparse_git_header(char*line,int len,unsigned int size,struct patch *patch)1176{1177unsigned long offset;11781179/* A git diff has explicit new/delete information, so we don't guess */1180 patch->is_new =0;1181 patch->is_delete =0;11821183/*1184 * Some things may not have the old name in the1185 * rest of the headers anywhere (pure mode changes,1186 * or removing or adding empty files), so we get1187 * the default name from the header.1188 */1189 patch->def_name =git_header_name(line, len);1190if(patch->def_name && root) {1191char*s =xmalloc(root_len +strlen(patch->def_name) +1);1192strcpy(s, root);1193strcpy(s + root_len, patch->def_name);1194free(patch->def_name);1195 patch->def_name = s;1196}11971198 line += len;1199 size -= len;1200 linenr++;1201for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) {1202static const struct opentry {1203const char*str;1204int(*fn)(const char*,struct patch *);1205} optable[] = {1206{"@@ -", gitdiff_hdrend },1207{"--- ", gitdiff_oldname },1208{"+++ ", gitdiff_newname },1209{"old mode ", gitdiff_oldmode },1210{"new mode ", gitdiff_newmode },1211{"deleted file mode ", gitdiff_delete },1212{"new file mode ", gitdiff_newfile },1213{"copy from ", gitdiff_copysrc },1214{"copy to ", gitdiff_copydst },1215{"rename old ", gitdiff_renamesrc },1216{"rename new ", gitdiff_renamedst },1217{"rename from ", gitdiff_renamesrc },1218{"rename to ", gitdiff_renamedst },1219{"similarity index ", gitdiff_similarity },1220{"dissimilarity index ", gitdiff_dissimilarity },1221{"index ", gitdiff_index },1222{"", gitdiff_unrecognized },1223};1224int i;12251226 len =linelen(line, size);1227if(!len || line[len-1] !='\n')1228break;1229for(i =0; i <ARRAY_SIZE(optable); i++) {1230const struct opentry *p = optable + i;1231int oplen =strlen(p->str);1232if(len < oplen ||memcmp(p->str, line, oplen))1233continue;1234if(p->fn(line + oplen, patch) <0)1235return offset;1236break;1237}1238}12391240return offset;1241}12421243static intparse_num(const char*line,unsigned long*p)1244{1245char*ptr;12461247if(!isdigit(*line))1248return0;1249*p =strtoul(line, &ptr,10);1250return ptr - line;1251}12521253static intparse_range(const char*line,int len,int offset,const char*expect,1254unsigned long*p1,unsigned long*p2)1255{1256int digits, ex;12571258if(offset <0|| offset >= len)1259return-1;1260 line += offset;1261 len -= offset;12621263 digits =parse_num(line, p1);1264if(!digits)1265return-1;12661267 offset += digits;1268 line += digits;1269 len -= digits;12701271*p2 =1;1272if(*line ==',') {1273 digits =parse_num(line+1, p2);1274if(!digits)1275return-1;12761277 offset += digits+1;1278 line += digits+1;1279 len -= digits+1;1280}12811282 ex =strlen(expect);1283if(ex > len)1284return-1;1285if(memcmp(line, expect, ex))1286return-1;12871288return offset + ex;1289}12901291static voidrecount_diff(char*line,int size,struct fragment *fragment)1292{1293int oldlines =0, newlines =0, ret =0;12941295if(size <1) {1296warning("recount: ignore empty hunk");1297return;1298}12991300for(;;) {1301int len =linelen(line, size);1302 size -= len;1303 line += len;13041305if(size <1)1306break;13071308switch(*line) {1309case' ':case'\n':1310 newlines++;1311/* fall through */1312case'-':1313 oldlines++;1314continue;1315case'+':1316 newlines++;1317continue;1318case'\\':1319continue;1320case'@':1321 ret = size <3||prefixcmp(line,"@@ ");1322break;1323case'd':1324 ret = size <5||prefixcmp(line,"diff ");1325break;1326default:1327 ret = -1;1328break;1329}1330if(ret) {1331warning("recount: unexpected line: %.*s",1332(int)linelen(line, size), line);1333return;1334}1335break;1336}1337 fragment->oldlines = oldlines;1338 fragment->newlines = newlines;1339}13401341/*1342 * Parse a unified diff fragment header of the1343 * form "@@ -a,b +c,d @@"1344 */1345static intparse_fragment_header(char*line,int len,struct fragment *fragment)1346{1347int offset;13481349if(!len || line[len-1] !='\n')1350return-1;13511352/* Figure out the number of lines in a fragment */1353 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1354 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);13551356return offset;1357}13581359static intfind_header(char*line,unsigned long size,int*hdrsize,struct patch *patch)1360{1361unsigned long offset, len;13621363 patch->is_toplevel_relative =0;1364 patch->is_rename = patch->is_copy =0;1365 patch->is_new = patch->is_delete = -1;1366 patch->old_mode = patch->new_mode =0;1367 patch->old_name = patch->new_name = NULL;1368for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) {1369unsigned long nextlen;13701371 len =linelen(line, size);1372if(!len)1373break;13741375/* Testing this early allows us to take a few shortcuts.. */1376if(len <6)1377continue;13781379/*1380 * Make sure we don't find any unconnected patch fragments.1381 * That's a sign that we didn't find a header, and that a1382 * patch has become corrupted/broken up.1383 */1384if(!memcmp("@@ -", line,4)) {1385struct fragment dummy;1386if(parse_fragment_header(line, len, &dummy) <0)1387continue;1388die("patch fragment without header at line%d: %.*s",1389 linenr, (int)len-1, line);1390}13911392if(size < len +6)1393break;13941395/*1396 * Git patch? It might not have a real patch, just a rename1397 * or mode change, so we handle that specially1398 */1399if(!memcmp("diff --git ", line,11)) {1400int git_hdr_len =parse_git_header(line, len, size, patch);1401if(git_hdr_len <= len)1402continue;1403if(!patch->old_name && !patch->new_name) {1404if(!patch->def_name)1405die("git diff header lacks filename information when removing "1406"%dleading pathname components (line%d)", p_value, linenr);1407 patch->old_name = patch->new_name = patch->def_name;1408}1409 patch->is_toplevel_relative =1;1410*hdrsize = git_hdr_len;1411return offset;1412}14131414/* --- followed by +++ ? */1415if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1416continue;14171418/*1419 * We only accept unified patches, so we want it to1420 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1421 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1422 */1423 nextlen =linelen(line + len, size - len);1424if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1425continue;14261427/* Ok, we'll consider it a patch */1428parse_traditional_patch(line, line+len, patch);1429*hdrsize = len + nextlen;1430 linenr +=2;1431return offset;1432}1433return-1;1434}14351436static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1437{1438char*err;14391440if(!result)1441return;14421443 whitespace_error++;1444if(squelch_whitespace_errors &&1445 squelch_whitespace_errors < whitespace_error)1446return;14471448 err =whitespace_error_string(result);1449fprintf(stderr,"%s:%d:%s.\n%.*s\n",1450 patch_input_file, linenr, err, len, line);1451free(err);1452}14531454static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1455{1456unsigned result =ws_check(line +1, len -1, ws_rule);14571458record_ws_error(result, line +1, len -2, linenr);1459}14601461/*1462 * Parse a unified diff. Note that this really needs to parse each1463 * fragment separately, since the only way to know the difference1464 * between a "---" that is part of a patch, and a "---" that starts1465 * the next patch is to look at the line counts..1466 */1467static intparse_fragment(char*line,unsigned long size,1468struct patch *patch,struct fragment *fragment)1469{1470int added, deleted;1471int len =linelen(line, size), offset;1472unsigned long oldlines, newlines;1473unsigned long leading, trailing;14741475 offset =parse_fragment_header(line, len, fragment);1476if(offset <0)1477return-1;1478if(offset >0&& patch->recount)1479recount_diff(line + offset, size - offset, fragment);1480 oldlines = fragment->oldlines;1481 newlines = fragment->newlines;1482 leading =0;1483 trailing =0;14841485/* Parse the thing.. */1486 line += len;1487 size -= len;1488 linenr++;1489 added = deleted =0;1490for(offset = len;14910< size;1492 offset += len, size -= len, line += len, linenr++) {1493if(!oldlines && !newlines)1494break;1495 len =linelen(line, size);1496if(!len || line[len-1] !='\n')1497return-1;1498switch(*line) {1499default:1500return-1;1501case'\n':/* newer GNU diff, an empty context line */1502case' ':1503 oldlines--;1504 newlines--;1505if(!deleted && !added)1506 leading++;1507 trailing++;1508break;1509case'-':1510if(apply_in_reverse &&1511 ws_error_action != nowarn_ws_error)1512check_whitespace(line, len, patch->ws_rule);1513 deleted++;1514 oldlines--;1515 trailing =0;1516break;1517case'+':1518if(!apply_in_reverse &&1519 ws_error_action != nowarn_ws_error)1520check_whitespace(line, len, patch->ws_rule);1521 added++;1522 newlines--;1523 trailing =0;1524break;15251526/*1527 * We allow "\ No newline at end of file". Depending1528 * on locale settings when the patch was produced we1529 * don't know what this line looks like. The only1530 * thing we do know is that it begins with "\ ".1531 * Checking for 12 is just for sanity check -- any1532 * l10n of "\ No newline..." is at least that long.1533 */1534case'\\':1535if(len <12||memcmp(line,"\\",2))1536return-1;1537break;1538}1539}1540if(oldlines || newlines)1541return-1;1542 fragment->leading = leading;1543 fragment->trailing = trailing;15441545/*1546 * If a fragment ends with an incomplete line, we failed to include1547 * it in the above loop because we hit oldlines == newlines == 01548 * before seeing it.1549 */1550if(12< size && !memcmp(line,"\\",2))1551 offset +=linelen(line, size);15521553 patch->lines_added += added;1554 patch->lines_deleted += deleted;15551556if(0< patch->is_new && oldlines)1557returnerror("new file depends on old contents");1558if(0< patch->is_delete && newlines)1559returnerror("deleted file still has contents");1560return offset;1561}15621563static intparse_single_patch(char*line,unsigned long size,struct patch *patch)1564{1565unsigned long offset =0;1566unsigned long oldlines =0, newlines =0, context =0;1567struct fragment **fragp = &patch->fragments;15681569while(size >4&& !memcmp(line,"@@ -",4)) {1570struct fragment *fragment;1571int len;15721573 fragment =xcalloc(1,sizeof(*fragment));1574 fragment->linenr = linenr;1575 len =parse_fragment(line, size, patch, fragment);1576if(len <=0)1577die("corrupt patch at line%d", linenr);1578 fragment->patch = line;1579 fragment->size = len;1580 oldlines += fragment->oldlines;1581 newlines += fragment->newlines;1582 context += fragment->leading + fragment->trailing;15831584*fragp = fragment;1585 fragp = &fragment->next;15861587 offset += len;1588 line += len;1589 size -= len;1590}15911592/*1593 * If something was removed (i.e. we have old-lines) it cannot1594 * be creation, and if something was added it cannot be1595 * deletion. However, the reverse is not true; --unified=01596 * patches that only add are not necessarily creation even1597 * though they do not have any old lines, and ones that only1598 * delete are not necessarily deletion.1599 *1600 * Unfortunately, a real creation/deletion patch do _not_ have1601 * any context line by definition, so we cannot safely tell it1602 * apart with --unified=0 insanity. At least if the patch has1603 * more than one hunk it is not creation or deletion.1604 */1605if(patch->is_new <0&&1606(oldlines || (patch->fragments && patch->fragments->next)))1607 patch->is_new =0;1608if(patch->is_delete <0&&1609(newlines || (patch->fragments && patch->fragments->next)))1610 patch->is_delete =0;16111612if(0< patch->is_new && oldlines)1613die("new file%sdepends on old contents", patch->new_name);1614if(0< patch->is_delete && newlines)1615die("deleted file%sstill has contents", patch->old_name);1616if(!patch->is_delete && !newlines && context)1617fprintf(stderr,"** warning: file%sbecomes empty but "1618"is not deleted\n", patch->new_name);16191620return offset;1621}16221623staticinlineintmetadata_changes(struct patch *patch)1624{1625return patch->is_rename >0||1626 patch->is_copy >0||1627 patch->is_new >0||1628 patch->is_delete ||1629(patch->old_mode && patch->new_mode &&1630 patch->old_mode != patch->new_mode);1631}16321633static char*inflate_it(const void*data,unsigned long size,1634unsigned long inflated_size)1635{1636 z_stream stream;1637void*out;1638int st;16391640memset(&stream,0,sizeof(stream));16411642 stream.next_in = (unsigned char*)data;1643 stream.avail_in = size;1644 stream.next_out = out =xmalloc(inflated_size);1645 stream.avail_out = inflated_size;1646git_inflate_init(&stream);1647 st =git_inflate(&stream, Z_FINISH);1648git_inflate_end(&stream);1649if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1650free(out);1651return NULL;1652}1653return out;1654}16551656static struct fragment *parse_binary_hunk(char**buf_p,1657unsigned long*sz_p,1658int*status_p,1659int*used_p)1660{1661/*1662 * Expect a line that begins with binary patch method ("literal"1663 * or "delta"), followed by the length of data before deflating.1664 * a sequence of 'length-byte' followed by base-85 encoded data1665 * should follow, terminated by a newline.1666 *1667 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1668 * and we would limit the patch line to 66 characters,1669 * so one line can fit up to 13 groups that would decode1670 * to 52 bytes max. The length byte 'A'-'Z' corresponds1671 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1672 */1673int llen, used;1674unsigned long size = *sz_p;1675char*buffer = *buf_p;1676int patch_method;1677unsigned long origlen;1678char*data = NULL;1679int hunk_size =0;1680struct fragment *frag;16811682 llen =linelen(buffer, size);1683 used = llen;16841685*status_p =0;16861687if(!prefixcmp(buffer,"delta ")) {1688 patch_method = BINARY_DELTA_DEFLATED;1689 origlen =strtoul(buffer +6, NULL,10);1690}1691else if(!prefixcmp(buffer,"literal ")) {1692 patch_method = BINARY_LITERAL_DEFLATED;1693 origlen =strtoul(buffer +8, NULL,10);1694}1695else1696return NULL;16971698 linenr++;1699 buffer += llen;1700while(1) {1701int byte_length, max_byte_length, newsize;1702 llen =linelen(buffer, size);1703 used += llen;1704 linenr++;1705if(llen ==1) {1706/* consume the blank line */1707 buffer++;1708 size--;1709break;1710}1711/*1712 * Minimum line is "A00000\n" which is 7-byte long,1713 * and the line length must be multiple of 5 plus 2.1714 */1715if((llen <7) || (llen-2) %5)1716goto corrupt;1717 max_byte_length = (llen -2) /5*4;1718 byte_length = *buffer;1719if('A'<= byte_length && byte_length <='Z')1720 byte_length = byte_length -'A'+1;1721else if('a'<= byte_length && byte_length <='z')1722 byte_length = byte_length -'a'+27;1723else1724goto corrupt;1725/* if the input length was not multiple of 4, we would1726 * have filler at the end but the filler should never1727 * exceed 3 bytes1728 */1729if(max_byte_length < byte_length ||1730 byte_length <= max_byte_length -4)1731goto corrupt;1732 newsize = hunk_size + byte_length;1733 data =xrealloc(data, newsize);1734if(decode_85(data + hunk_size, buffer +1, byte_length))1735goto corrupt;1736 hunk_size = newsize;1737 buffer += llen;1738 size -= llen;1739}17401741 frag =xcalloc(1,sizeof(*frag));1742 frag->patch =inflate_it(data, hunk_size, origlen);1743if(!frag->patch)1744goto corrupt;1745free(data);1746 frag->size = origlen;1747*buf_p = buffer;1748*sz_p = size;1749*used_p = used;1750 frag->binary_patch_method = patch_method;1751return frag;17521753 corrupt:1754free(data);1755*status_p = -1;1756error("corrupt binary patch at line%d: %.*s",1757 linenr-1, llen-1, buffer);1758return NULL;1759}17601761static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1762{1763/*1764 * We have read "GIT binary patch\n"; what follows is a line1765 * that says the patch method (currently, either "literal" or1766 * "delta") and the length of data before deflating; a1767 * sequence of 'length-byte' followed by base-85 encoded data1768 * follows.1769 *1770 * When a binary patch is reversible, there is another binary1771 * hunk in the same format, starting with patch method (either1772 * "literal" or "delta") with the length of data, and a sequence1773 * of length-byte + base-85 encoded data, terminated with another1774 * empty line. This data, when applied to the postimage, produces1775 * the preimage.1776 */1777struct fragment *forward;1778struct fragment *reverse;1779int status;1780int used, used_1;17811782 forward =parse_binary_hunk(&buffer, &size, &status, &used);1783if(!forward && !status)1784/* there has to be one hunk (forward hunk) */1785returnerror("unrecognized binary patch at line%d", linenr-1);1786if(status)1787/* otherwise we already gave an error message */1788return status;17891790 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1791if(reverse)1792 used += used_1;1793else if(status) {1794/*1795 * Not having reverse hunk is not an error, but having1796 * a corrupt reverse hunk is.1797 */1798free((void*) forward->patch);1799free(forward);1800return status;1801}1802 forward->next = reverse;1803 patch->fragments = forward;1804 patch->is_binary =1;1805return used;1806}18071808static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1809{1810int hdrsize, patchsize;1811int offset =find_header(buffer, size, &hdrsize, patch);18121813if(offset <0)1814return offset;18151816 patch->ws_rule =whitespace_rule(patch->new_name1817? patch->new_name1818: patch->old_name);18191820 patchsize =parse_single_patch(buffer + offset + hdrsize,1821 size - offset - hdrsize, patch);18221823if(!patchsize) {1824static const char*binhdr[] = {1825"Binary files ",1826"Files ",1827 NULL,1828};1829static const char git_binary[] ="GIT binary patch\n";1830int i;1831int hd = hdrsize + offset;1832unsigned long llen =linelen(buffer + hd, size - hd);18331834if(llen ==sizeof(git_binary) -1&&1835!memcmp(git_binary, buffer + hd, llen)) {1836int used;1837 linenr++;1838 used =parse_binary(buffer + hd + llen,1839 size - hd - llen, patch);1840if(used)1841 patchsize = used + llen;1842else1843 patchsize =0;1844}1845else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1846for(i =0; binhdr[i]; i++) {1847int len =strlen(binhdr[i]);1848if(len < size - hd &&1849!memcmp(binhdr[i], buffer + hd, len)) {1850 linenr++;1851 patch->is_binary =1;1852 patchsize = llen;1853break;1854}1855}1856}18571858/* Empty patch cannot be applied if it is a text patch1859 * without metadata change. A binary patch appears1860 * empty to us here.1861 */1862if((apply || check) &&1863(!patch->is_binary && !metadata_changes(patch)))1864die("patch with only garbage at line%d", linenr);1865}18661867return offset + hdrsize + patchsize;1868}18691870#define swap(a,b) myswap((a),(b),sizeof(a))18711872#define myswap(a, b, size) do { \1873 unsigned char mytmp[size]; \1874 memcpy(mytmp, &a, size); \1875 memcpy(&a, &b, size); \1876 memcpy(&b, mytmp, size); \1877} while (0)18781879static voidreverse_patches(struct patch *p)1880{1881for(; p; p = p->next) {1882struct fragment *frag = p->fragments;18831884swap(p->new_name, p->old_name);1885swap(p->new_mode, p->old_mode);1886swap(p->is_new, p->is_delete);1887swap(p->lines_added, p->lines_deleted);1888swap(p->old_sha1_prefix, p->new_sha1_prefix);18891890for(; frag; frag = frag->next) {1891swap(frag->newpos, frag->oldpos);1892swap(frag->newlines, frag->oldlines);1893}1894}1895}18961897static const char pluses[] =1898"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";1899static const char minuses[]=1900"----------------------------------------------------------------------";19011902static voidshow_stats(struct patch *patch)1903{1904struct strbuf qname = STRBUF_INIT;1905char*cp = patch->new_name ? patch->new_name : patch->old_name;1906int max, add, del;19071908quote_c_style(cp, &qname, NULL,0);19091910/*1911 * "scale" the filename1912 */1913 max = max_len;1914if(max >50)1915 max =50;19161917if(qname.len > max) {1918 cp =strchr(qname.buf + qname.len +3- max,'/');1919if(!cp)1920 cp = qname.buf + qname.len +3- max;1921strbuf_splice(&qname,0, cp - qname.buf,"...",3);1922}19231924if(patch->is_binary) {1925printf(" %-*s | Bin\n", max, qname.buf);1926strbuf_release(&qname);1927return;1928}19291930printf(" %-*s |", max, qname.buf);1931strbuf_release(&qname);19321933/*1934 * scale the add/delete1935 */1936 max = max + max_change >70?70- max : max_change;1937 add = patch->lines_added;1938 del = patch->lines_deleted;19391940if(max_change >0) {1941int total = ((add + del) * max + max_change /2) / max_change;1942 add = (add * max + max_change /2) / max_change;1943 del = total - add;1944}1945printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,1946 add, pluses, del, minuses);1947}19481949static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)1950{1951switch(st->st_mode & S_IFMT) {1952case S_IFLNK:1953if(strbuf_readlink(buf, path, st->st_size) <0)1954returnerror("unable to read symlink%s", path);1955return0;1956case S_IFREG:1957if(strbuf_read_file(buf, path, st->st_size) != st->st_size)1958returnerror("unable to open or read%s", path);1959convert_to_git(path, buf->buf, buf->len, buf,0);1960return0;1961default:1962return-1;1963}1964}19651966/*1967 * Update the preimage, and the common lines in postimage,1968 * from buffer buf of length len. If postlen is 0 the postimage1969 * is updated in place, otherwise it's updated on a new buffer1970 * of length postlen1971 */19721973static voidupdate_pre_post_images(struct image *preimage,1974struct image *postimage,1975char*buf,1976size_t len,size_t postlen)1977{1978int i, ctx;1979char*new, *old, *fixed;1980struct image fixed_preimage;19811982/*1983 * Update the preimage with whitespace fixes. Note that we1984 * are not losing preimage->buf -- apply_one_fragment() will1985 * free "oldlines".1986 */1987prepare_image(&fixed_preimage, buf, len,1);1988assert(fixed_preimage.nr == preimage->nr);1989for(i =0; i < preimage->nr; i++)1990 fixed_preimage.line[i].flag = preimage->line[i].flag;1991free(preimage->line_allocated);1992*preimage = fixed_preimage;19931994/*1995 * Adjust the common context lines in postimage. This can be1996 * done in-place when we are just doing whitespace fixing,1997 * which does not make the string grow, but needs a new buffer1998 * when ignoring whitespace causes the update, since in this case1999 * we could have e.g. tabs converted to multiple spaces.2000 * We trust the caller to tell us if the update can be done2001 * in place (postlen==0) or not.2002 */2003 old = postimage->buf;2004if(postlen)2005new= postimage->buf =xmalloc(postlen);2006else2007new= old;2008 fixed = preimage->buf;2009for(i = ctx =0; i < postimage->nr; i++) {2010size_t len = postimage->line[i].len;2011if(!(postimage->line[i].flag & LINE_COMMON)) {2012/* an added line -- no counterparts in preimage */2013memmove(new, old, len);2014 old += len;2015new+= len;2016continue;2017}20182019/* a common context -- skip it in the original postimage */2020 old += len;20212022/* and find the corresponding one in the fixed preimage */2023while(ctx < preimage->nr &&2024!(preimage->line[ctx].flag & LINE_COMMON)) {2025 fixed += preimage->line[ctx].len;2026 ctx++;2027}2028if(preimage->nr <= ctx)2029die("oops");20302031/* and copy it in, while fixing the line length */2032 len = preimage->line[ctx].len;2033memcpy(new, fixed, len);2034new+= len;2035 fixed += len;2036 postimage->line[i].len = len;2037 ctx++;2038}20392040/* Fix the length of the whole thing */2041 postimage->len =new- postimage->buf;2042}20432044static intmatch_fragment(struct image *img,2045struct image *preimage,2046struct image *postimage,2047unsigned longtry,2048int try_lno,2049unsigned ws_rule,2050int match_beginning,int match_end)2051{2052int i;2053char*fixed_buf, *buf, *orig, *target;2054struct strbuf fixed;2055size_t fixed_len;2056int preimage_limit;20572058if(preimage->nr + try_lno <= img->nr) {2059/*2060 * The hunk falls within the boundaries of img.2061 */2062 preimage_limit = preimage->nr;2063if(match_end && (preimage->nr + try_lno != img->nr))2064return0;2065}else if(ws_error_action == correct_ws_error &&2066(ws_rule & WS_BLANK_AT_EOF)) {2067/*2068 * This hunk extends beyond the end of img, and we are2069 * removing blank lines at the end of the file. This2070 * many lines from the beginning of the preimage must2071 * match with img, and the remainder of the preimage2072 * must be blank.2073 */2074 preimage_limit = img->nr - try_lno;2075}else{2076/*2077 * The hunk extends beyond the end of the img and2078 * we are not removing blanks at the end, so we2079 * should reject the hunk at this position.2080 */2081return0;2082}20832084if(match_beginning && try_lno)2085return0;20862087/* Quick hash check */2088for(i =0; i < preimage_limit; i++)2089if((img->line[try_lno + i].flag & LINE_PATCHED) ||2090(preimage->line[i].hash != img->line[try_lno + i].hash))2091return0;20922093if(preimage_limit == preimage->nr) {2094/*2095 * Do we have an exact match? If we were told to match2096 * at the end, size must be exactly at try+fragsize,2097 * otherwise try+fragsize must be still within the preimage,2098 * and either case, the old piece should match the preimage2099 * exactly.2100 */2101if((match_end2102? (try+ preimage->len == img->len)2103: (try+ preimage->len <= img->len)) &&2104!memcmp(img->buf +try, preimage->buf, preimage->len))2105return1;2106}else{2107/*2108 * The preimage extends beyond the end of img, so2109 * there cannot be an exact match.2110 *2111 * There must be one non-blank context line that match2112 * a line before the end of img.2113 */2114char*buf_end;21152116 buf = preimage->buf;2117 buf_end = buf;2118for(i =0; i < preimage_limit; i++)2119 buf_end += preimage->line[i].len;21202121for( ; buf < buf_end; buf++)2122if(!isspace(*buf))2123break;2124if(buf == buf_end)2125return0;2126}21272128/*2129 * No exact match. If we are ignoring whitespace, run a line-by-line2130 * fuzzy matching. We collect all the line length information because2131 * we need it to adjust whitespace if we match.2132 */2133if(ws_ignore_action == ignore_ws_change) {2134size_t imgoff =0;2135size_t preoff =0;2136size_t postlen = postimage->len;2137size_t extra_chars;2138char*preimage_eof;2139char*preimage_end;2140for(i =0; i < preimage_limit; i++) {2141size_t prelen = preimage->line[i].len;2142size_t imglen = img->line[try_lno+i].len;21432144if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2145 preimage->buf + preoff, prelen))2146return0;2147if(preimage->line[i].flag & LINE_COMMON)2148 postlen += imglen - prelen;2149 imgoff += imglen;2150 preoff += prelen;2151}21522153/*2154 * Ok, the preimage matches with whitespace fuzz.2155 *2156 * imgoff now holds the true length of the target that2157 * matches the preimage before the end of the file.2158 *2159 * Count the number of characters in the preimage that fall2160 * beyond the end of the file and make sure that all of them2161 * are whitespace characters. (This can only happen if2162 * we are removing blank lines at the end of the file.)2163 */2164 buf = preimage_eof = preimage->buf + preoff;2165for( ; i < preimage->nr; i++)2166 preoff += preimage->line[i].len;2167 preimage_end = preimage->buf + preoff;2168for( ; buf < preimage_end; buf++)2169if(!isspace(*buf))2170return0;21712172/*2173 * Update the preimage and the common postimage context2174 * lines to use the same whitespace as the target.2175 * If whitespace is missing in the target (i.e.2176 * if the preimage extends beyond the end of the file),2177 * use the whitespace from the preimage.2178 */2179 extra_chars = preimage_end - preimage_eof;2180strbuf_init(&fixed, imgoff + extra_chars);2181strbuf_add(&fixed, img->buf +try, imgoff);2182strbuf_add(&fixed, preimage_eof, extra_chars);2183 fixed_buf =strbuf_detach(&fixed, &fixed_len);2184update_pre_post_images(preimage, postimage,2185 fixed_buf, fixed_len, postlen);2186return1;2187}21882189if(ws_error_action != correct_ws_error)2190return0;21912192/*2193 * The hunk does not apply byte-by-byte, but the hash says2194 * it might with whitespace fuzz. We haven't been asked to2195 * ignore whitespace, we were asked to correct whitespace2196 * errors, so let's try matching after whitespace correction.2197 *2198 * The preimage may extend beyond the end of the file,2199 * but in this loop we will only handle the part of the2200 * preimage that falls within the file.2201 */2202strbuf_init(&fixed, preimage->len +1);2203 orig = preimage->buf;2204 target = img->buf +try;2205for(i =0; i < preimage_limit; i++) {2206size_t oldlen = preimage->line[i].len;2207size_t tgtlen = img->line[try_lno + i].len;2208size_t fixstart = fixed.len;2209struct strbuf tgtfix;2210int match;22112212/* Try fixing the line in the preimage */2213ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);22142215/* Try fixing the line in the target */2216strbuf_init(&tgtfix, tgtlen);2217ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);22182219/*2220 * If they match, either the preimage was based on2221 * a version before our tree fixed whitespace breakage,2222 * or we are lacking a whitespace-fix patch the tree2223 * the preimage was based on already had (i.e. target2224 * has whitespace breakage, the preimage doesn't).2225 * In either case, we are fixing the whitespace breakages2226 * so we might as well take the fix together with their2227 * real change.2228 */2229 match = (tgtfix.len == fixed.len - fixstart &&2230!memcmp(tgtfix.buf, fixed.buf + fixstart,2231 fixed.len - fixstart));22322233strbuf_release(&tgtfix);2234if(!match)2235goto unmatch_exit;22362237 orig += oldlen;2238 target += tgtlen;2239}224022412242/*2243 * Now handle the lines in the preimage that falls beyond the2244 * end of the file (if any). They will only match if they are2245 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2246 * false).2247 */2248for( ; i < preimage->nr; i++) {2249size_t fixstart = fixed.len;/* start of the fixed preimage */2250size_t oldlen = preimage->line[i].len;2251int j;22522253/* Try fixing the line in the preimage */2254ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);22552256for(j = fixstart; j < fixed.len; j++)2257if(!isspace(fixed.buf[j]))2258goto unmatch_exit;22592260 orig += oldlen;2261}22622263/*2264 * Yes, the preimage is based on an older version that still2265 * has whitespace breakages unfixed, and fixing them makes the2266 * hunk match. Update the context lines in the postimage.2267 */2268 fixed_buf =strbuf_detach(&fixed, &fixed_len);2269update_pre_post_images(preimage, postimage,2270 fixed_buf, fixed_len,0);2271return1;22722273 unmatch_exit:2274strbuf_release(&fixed);2275return0;2276}22772278static intfind_pos(struct image *img,2279struct image *preimage,2280struct image *postimage,2281int line,2282unsigned ws_rule,2283int match_beginning,int match_end)2284{2285int i;2286unsigned long backwards, forwards,try;2287int backwards_lno, forwards_lno, try_lno;22882289/*2290 * If match_beginning or match_end is specified, there is no2291 * point starting from a wrong line that will never match and2292 * wander around and wait for a match at the specified end.2293 */2294if(match_beginning)2295 line =0;2296else if(match_end)2297 line = img->nr - preimage->nr;22982299/*2300 * Because the comparison is unsigned, the following test2301 * will also take care of a negative line number that can2302 * result when match_end and preimage is larger than the target.2303 */2304if((size_t) line > img->nr)2305 line = img->nr;23062307try=0;2308for(i =0; i < line; i++)2309try+= img->line[i].len;23102311/*2312 * There's probably some smart way to do this, but I'll leave2313 * that to the smart and beautiful people. I'm simple and stupid.2314 */2315 backwards =try;2316 backwards_lno = line;2317 forwards =try;2318 forwards_lno = line;2319 try_lno = line;23202321for(i =0; ; i++) {2322if(match_fragment(img, preimage, postimage,2323try, try_lno, ws_rule,2324 match_beginning, match_end))2325return try_lno;23262327 again:2328if(backwards_lno ==0&& forwards_lno == img->nr)2329break;23302331if(i &1) {2332if(backwards_lno ==0) {2333 i++;2334goto again;2335}2336 backwards_lno--;2337 backwards -= img->line[backwards_lno].len;2338try= backwards;2339 try_lno = backwards_lno;2340}else{2341if(forwards_lno == img->nr) {2342 i++;2343goto again;2344}2345 forwards += img->line[forwards_lno].len;2346 forwards_lno++;2347try= forwards;2348 try_lno = forwards_lno;2349}23502351}2352return-1;2353}23542355static voidremove_first_line(struct image *img)2356{2357 img->buf += img->line[0].len;2358 img->len -= img->line[0].len;2359 img->line++;2360 img->nr--;2361}23622363static voidremove_last_line(struct image *img)2364{2365 img->len -= img->line[--img->nr].len;2366}23672368static voidupdate_image(struct image *img,2369int applied_pos,2370struct image *preimage,2371struct image *postimage)2372{2373/*2374 * remove the copy of preimage at offset in img2375 * and replace it with postimage2376 */2377int i, nr;2378size_t remove_count, insert_count, applied_at =0;2379char*result;2380int preimage_limit;23812382/*2383 * If we are removing blank lines at the end of img,2384 * the preimage may extend beyond the end.2385 * If that is the case, we must be careful only to2386 * remove the part of the preimage that falls within2387 * the boundaries of img. Initialize preimage_limit2388 * to the number of lines in the preimage that falls2389 * within the boundaries.2390 */2391 preimage_limit = preimage->nr;2392if(preimage_limit > img->nr - applied_pos)2393 preimage_limit = img->nr - applied_pos;23942395for(i =0; i < applied_pos; i++)2396 applied_at += img->line[i].len;23972398 remove_count =0;2399for(i =0; i < preimage_limit; i++)2400 remove_count += img->line[applied_pos + i].len;2401 insert_count = postimage->len;24022403/* Adjust the contents */2404 result =xmalloc(img->len + insert_count - remove_count +1);2405memcpy(result, img->buf, applied_at);2406memcpy(result + applied_at, postimage->buf, postimage->len);2407memcpy(result + applied_at + postimage->len,2408 img->buf + (applied_at + remove_count),2409 img->len - (applied_at + remove_count));2410free(img->buf);2411 img->buf = result;2412 img->len += insert_count - remove_count;2413 result[img->len] ='\0';24142415/* Adjust the line table */2416 nr = img->nr + postimage->nr - preimage_limit;2417if(preimage_limit < postimage->nr) {2418/*2419 * NOTE: this knows that we never call remove_first_line()2420 * on anything other than pre/post image.2421 */2422 img->line =xrealloc(img->line, nr *sizeof(*img->line));2423 img->line_allocated = img->line;2424}2425if(preimage_limit != postimage->nr)2426memmove(img->line + applied_pos + postimage->nr,2427 img->line + applied_pos + preimage_limit,2428(img->nr - (applied_pos + preimage_limit)) *2429sizeof(*img->line));2430memcpy(img->line + applied_pos,2431 postimage->line,2432 postimage->nr *sizeof(*img->line));2433for(i =0; i < postimage->nr; i++)2434 img->line[applied_pos + i].flag |= LINE_PATCHED;24352436 img->nr = nr;2437}24382439static intapply_one_fragment(struct image *img,struct fragment *frag,2440int inaccurate_eof,unsigned ws_rule,2441int nth_fragment)2442{2443int match_beginning, match_end;2444const char*patch = frag->patch;2445int size = frag->size;2446char*old, *oldlines;2447struct strbuf newlines;2448int new_blank_lines_at_end =0;2449unsigned long leading, trailing;2450int pos, applied_pos;2451struct image preimage;2452struct image postimage;24532454memset(&preimage,0,sizeof(preimage));2455memset(&postimage,0,sizeof(postimage));2456 oldlines =xmalloc(size);2457strbuf_init(&newlines, size);24582459 old = oldlines;2460while(size >0) {2461char first;2462int len =linelen(patch, size);2463int plen;2464int added_blank_line =0;2465int is_blank_context =0;2466size_t start;24672468if(!len)2469break;24702471/*2472 * "plen" is how much of the line we should use for2473 * the actual patch data. Normally we just remove the2474 * first character on the line, but if the line is2475 * followed by "\ No newline", then we also remove the2476 * last one (which is the newline, of course).2477 */2478 plen = len -1;2479if(len < size && patch[len] =='\\')2480 plen--;2481 first = *patch;2482if(apply_in_reverse) {2483if(first =='-')2484 first ='+';2485else if(first =='+')2486 first ='-';2487}24882489switch(first) {2490case'\n':2491/* Newer GNU diff, empty context line */2492if(plen <0)2493/* ... followed by '\No newline'; nothing */2494break;2495*old++ ='\n';2496strbuf_addch(&newlines,'\n');2497add_line_info(&preimage,"\n",1, LINE_COMMON);2498add_line_info(&postimage,"\n",1, LINE_COMMON);2499 is_blank_context =1;2500break;2501case' ':2502if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2503ws_blank_line(patch +1, plen, ws_rule))2504 is_blank_context =1;2505case'-':2506memcpy(old, patch +1, plen);2507add_line_info(&preimage, old, plen,2508(first ==' '? LINE_COMMON :0));2509 old += plen;2510if(first =='-')2511break;2512/* Fall-through for ' ' */2513case'+':2514/* --no-add does not add new lines */2515if(first =='+'&& no_add)2516break;25172518 start = newlines.len;2519if(first !='+'||2520!whitespace_error ||2521 ws_error_action != correct_ws_error) {2522strbuf_add(&newlines, patch +1, plen);2523}2524else{2525ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2526}2527add_line_info(&postimage, newlines.buf + start, newlines.len - start,2528(first =='+'?0: LINE_COMMON));2529if(first =='+'&&2530(ws_rule & WS_BLANK_AT_EOF) &&2531ws_blank_line(patch +1, plen, ws_rule))2532 added_blank_line =1;2533break;2534case'@':case'\\':2535/* Ignore it, we already handled it */2536break;2537default:2538if(apply_verbosely)2539error("invalid start of line: '%c'", first);2540return-1;2541}2542if(added_blank_line)2543 new_blank_lines_at_end++;2544else if(is_blank_context)2545;2546else2547 new_blank_lines_at_end =0;2548 patch += len;2549 size -= len;2550}2551if(inaccurate_eof &&2552 old > oldlines && old[-1] =='\n'&&2553 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2554 old--;2555strbuf_setlen(&newlines, newlines.len -1);2556}25572558 leading = frag->leading;2559 trailing = frag->trailing;25602561/*2562 * A hunk to change lines at the beginning would begin with2563 * @@ -1,L +N,M @@2564 * but we need to be careful. -U0 that inserts before the second2565 * line also has this pattern.2566 *2567 * And a hunk to add to an empty file would begin with2568 * @@ -0,0 +N,M @@2569 *2570 * In other words, a hunk that is (frag->oldpos <= 1) with or2571 * without leading context must match at the beginning.2572 */2573 match_beginning = (!frag->oldpos ||2574(frag->oldpos ==1&& !unidiff_zero));25752576/*2577 * A hunk without trailing lines must match at the end.2578 * However, we simply cannot tell if a hunk must match end2579 * from the lack of trailing lines if the patch was generated2580 * with unidiff without any context.2581 */2582 match_end = !unidiff_zero && !trailing;25832584 pos = frag->newpos ? (frag->newpos -1) :0;2585 preimage.buf = oldlines;2586 preimage.len = old - oldlines;2587 postimage.buf = newlines.buf;2588 postimage.len = newlines.len;2589 preimage.line = preimage.line_allocated;2590 postimage.line = postimage.line_allocated;25912592for(;;) {25932594 applied_pos =find_pos(img, &preimage, &postimage, pos,2595 ws_rule, match_beginning, match_end);25962597if(applied_pos >=0)2598break;25992600/* Am I at my context limits? */2601if((leading <= p_context) && (trailing <= p_context))2602break;2603if(match_beginning || match_end) {2604 match_beginning = match_end =0;2605continue;2606}26072608/*2609 * Reduce the number of context lines; reduce both2610 * leading and trailing if they are equal otherwise2611 * just reduce the larger context.2612 */2613if(leading >= trailing) {2614remove_first_line(&preimage);2615remove_first_line(&postimage);2616 pos--;2617 leading--;2618}2619if(trailing > leading) {2620remove_last_line(&preimage);2621remove_last_line(&postimage);2622 trailing--;2623}2624}26252626if(applied_pos >=0) {2627if(new_blank_lines_at_end &&2628 preimage.nr + applied_pos >= img->nr &&2629(ws_rule & WS_BLANK_AT_EOF) &&2630 ws_error_action != nowarn_ws_error) {2631record_ws_error(WS_BLANK_AT_EOF,"+",1, frag->linenr);2632if(ws_error_action == correct_ws_error) {2633while(new_blank_lines_at_end--)2634remove_last_line(&postimage);2635}2636/*2637 * We would want to prevent write_out_results()2638 * from taking place in apply_patch() that follows2639 * the callchain led us here, which is:2640 * apply_patch->check_patch_list->check_patch->2641 * apply_data->apply_fragments->apply_one_fragment2642 */2643if(ws_error_action == die_on_ws_error)2644 apply =0;2645}26462647if(apply_verbosely && applied_pos != pos) {2648int offset = applied_pos - pos;2649if(apply_in_reverse)2650 offset =0- offset;2651fprintf(stderr,2652"Hunk #%dsucceeded at%d(offset%dlines).\n",2653 nth_fragment, applied_pos +1, offset);2654}26552656/*2657 * Warn if it was necessary to reduce the number2658 * of context lines.2659 */2660if((leading != frag->leading) ||2661(trailing != frag->trailing))2662fprintf(stderr,"Context reduced to (%ld/%ld)"2663" to apply fragment at%d\n",2664 leading, trailing, applied_pos+1);2665update_image(img, applied_pos, &preimage, &postimage);2666}else{2667if(apply_verbosely)2668error("while searching for:\n%.*s",2669(int)(old - oldlines), oldlines);2670}26712672free(oldlines);2673strbuf_release(&newlines);2674free(preimage.line_allocated);2675free(postimage.line_allocated);26762677return(applied_pos <0);2678}26792680static intapply_binary_fragment(struct image *img,struct patch *patch)2681{2682struct fragment *fragment = patch->fragments;2683unsigned long len;2684void*dst;26852686if(!fragment)2687returnerror("missing binary patch data for '%s'",2688 patch->new_name ?2689 patch->new_name :2690 patch->old_name);26912692/* Binary patch is irreversible without the optional second hunk */2693if(apply_in_reverse) {2694if(!fragment->next)2695returnerror("cannot reverse-apply a binary patch "2696"without the reverse hunk to '%s'",2697 patch->new_name2698? patch->new_name : patch->old_name);2699 fragment = fragment->next;2700}2701switch(fragment->binary_patch_method) {2702case BINARY_DELTA_DEFLATED:2703 dst =patch_delta(img->buf, img->len, fragment->patch,2704 fragment->size, &len);2705if(!dst)2706return-1;2707clear_image(img);2708 img->buf = dst;2709 img->len = len;2710return0;2711case BINARY_LITERAL_DEFLATED:2712clear_image(img);2713 img->len = fragment->size;2714 img->buf =xmalloc(img->len+1);2715memcpy(img->buf, fragment->patch, img->len);2716 img->buf[img->len] ='\0';2717return0;2718}2719return-1;2720}27212722static intapply_binary(struct image *img,struct patch *patch)2723{2724const char*name = patch->old_name ? patch->old_name : patch->new_name;2725unsigned char sha1[20];27262727/*2728 * For safety, we require patch index line to contain2729 * full 40-byte textual SHA1 for old and new, at least for now.2730 */2731if(strlen(patch->old_sha1_prefix) !=40||2732strlen(patch->new_sha1_prefix) !=40||2733get_sha1_hex(patch->old_sha1_prefix, sha1) ||2734get_sha1_hex(patch->new_sha1_prefix, sha1))2735returnerror("cannot apply binary patch to '%s' "2736"without full index line", name);27372738if(patch->old_name) {2739/*2740 * See if the old one matches what the patch2741 * applies to.2742 */2743hash_sha1_file(img->buf, img->len, blob_type, sha1);2744if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2745returnerror("the patch applies to '%s' (%s), "2746"which does not match the "2747"current contents.",2748 name,sha1_to_hex(sha1));2749}2750else{2751/* Otherwise, the old one must be empty. */2752if(img->len)2753returnerror("the patch applies to an empty "2754"'%s' but it is not empty", name);2755}27562757get_sha1_hex(patch->new_sha1_prefix, sha1);2758if(is_null_sha1(sha1)) {2759clear_image(img);2760return0;/* deletion patch */2761}27622763if(has_sha1_file(sha1)) {2764/* We already have the postimage */2765enum object_type type;2766unsigned long size;2767char*result;27682769 result =read_sha1_file(sha1, &type, &size);2770if(!result)2771returnerror("the necessary postimage%sfor "2772"'%s' cannot be read",2773 patch->new_sha1_prefix, name);2774clear_image(img);2775 img->buf = result;2776 img->len = size;2777}else{2778/*2779 * We have verified buf matches the preimage;2780 * apply the patch data to it, which is stored2781 * in the patch->fragments->{patch,size}.2782 */2783if(apply_binary_fragment(img, patch))2784returnerror("binary patch does not apply to '%s'",2785 name);27862787/* verify that the result matches */2788hash_sha1_file(img->buf, img->len, blob_type, sha1);2789if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2790returnerror("binary patch to '%s' creates incorrect result (expecting%s, got%s)",2791 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2792}27932794return0;2795}27962797static intapply_fragments(struct image *img,struct patch *patch)2798{2799struct fragment *frag = patch->fragments;2800const char*name = patch->old_name ? patch->old_name : patch->new_name;2801unsigned ws_rule = patch->ws_rule;2802unsigned inaccurate_eof = patch->inaccurate_eof;2803int nth =0;28042805if(patch->is_binary)2806returnapply_binary(img, patch);28072808while(frag) {2809 nth++;2810if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {2811error("patch failed:%s:%ld", name, frag->oldpos);2812if(!apply_with_reject)2813return-1;2814 frag->rejected =1;2815}2816 frag = frag->next;2817}2818return0;2819}28202821static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2822{2823if(!ce)2824return0;28252826if(S_ISGITLINK(ce->ce_mode)) {2827strbuf_grow(buf,100);2828strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2829}else{2830enum object_type type;2831unsigned long sz;2832char*result;28332834 result =read_sha1_file(ce->sha1, &type, &sz);2835if(!result)2836return-1;2837/* XXX read_sha1_file NUL-terminates */2838strbuf_attach(buf, result, sz, sz +1);2839}2840return0;2841}28422843static struct patch *in_fn_table(const char*name)2844{2845struct string_list_item *item;28462847if(name == NULL)2848return NULL;28492850 item =string_list_lookup(&fn_table, name);2851if(item != NULL)2852return(struct patch *)item->util;28532854return NULL;2855}28562857/*2858 * item->util in the filename table records the status of the path.2859 * Usually it points at a patch (whose result records the contents2860 * of it after applying it), but it could be PATH_WAS_DELETED for a2861 * path that a previously applied patch has already removed.2862 */2863#define PATH_TO_BE_DELETED ((struct patch *) -2)2864#define PATH_WAS_DELETED ((struct patch *) -1)28652866static intto_be_deleted(struct patch *patch)2867{2868return patch == PATH_TO_BE_DELETED;2869}28702871static intwas_deleted(struct patch *patch)2872{2873return patch == PATH_WAS_DELETED;2874}28752876static voidadd_to_fn_table(struct patch *patch)2877{2878struct string_list_item *item;28792880/*2881 * Always add new_name unless patch is a deletion2882 * This should cover the cases for normal diffs,2883 * file creations and copies2884 */2885if(patch->new_name != NULL) {2886 item =string_list_insert(&fn_table, patch->new_name);2887 item->util = patch;2888}28892890/*2891 * store a failure on rename/deletion cases because2892 * later chunks shouldn't patch old names2893 */2894if((patch->new_name == NULL) || (patch->is_rename)) {2895 item =string_list_insert(&fn_table, patch->old_name);2896 item->util = PATH_WAS_DELETED;2897}2898}28992900static voidprepare_fn_table(struct patch *patch)2901{2902/*2903 * store information about incoming file deletion2904 */2905while(patch) {2906if((patch->new_name == NULL) || (patch->is_rename)) {2907struct string_list_item *item;2908 item =string_list_insert(&fn_table, patch->old_name);2909 item->util = PATH_TO_BE_DELETED;2910}2911 patch = patch->next;2912}2913}29142915static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)2916{2917struct strbuf buf = STRBUF_INIT;2918struct image image;2919size_t len;2920char*img;2921struct patch *tpatch;29222923if(!(patch->is_copy || patch->is_rename) &&2924(tpatch =in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {2925if(was_deleted(tpatch)) {2926returnerror("patch%shas been renamed/deleted",2927 patch->old_name);2928}2929/* We have a patched copy in memory use that */2930strbuf_add(&buf, tpatch->result, tpatch->resultsize);2931}else if(cached) {2932if(read_file_or_gitlink(ce, &buf))2933returnerror("read of%sfailed", patch->old_name);2934}else if(patch->old_name) {2935if(S_ISGITLINK(patch->old_mode)) {2936if(ce) {2937read_file_or_gitlink(ce, &buf);2938}else{2939/*2940 * There is no way to apply subproject2941 * patch without looking at the index.2942 */2943 patch->fragments = NULL;2944}2945}else{2946if(read_old_data(st, patch->old_name, &buf))2947returnerror("read of%sfailed", patch->old_name);2948}2949}29502951 img =strbuf_detach(&buf, &len);2952prepare_image(&image, img, len, !patch->is_binary);29532954if(apply_fragments(&image, patch) <0)2955return-1;/* note with --reject this succeeds. */2956 patch->result = image.buf;2957 patch->resultsize = image.len;2958add_to_fn_table(patch);2959free(image.line_allocated);29602961if(0< patch->is_delete && patch->resultsize)2962returnerror("removal patch leaves file contents");29632964return0;2965}29662967static intcheck_to_create_blob(const char*new_name,int ok_if_exists)2968{2969struct stat nst;2970if(!lstat(new_name, &nst)) {2971if(S_ISDIR(nst.st_mode) || ok_if_exists)2972return0;2973/*2974 * A leading component of new_name might be a symlink2975 * that is going to be removed with this patch, but2976 * still pointing at somewhere that has the path.2977 * In such a case, path "new_name" does not exist as2978 * far as git is concerned.2979 */2980if(has_symlink_leading_path(new_name,strlen(new_name)))2981return0;29822983returnerror("%s: already exists in working directory", new_name);2984}2985else if((errno != ENOENT) && (errno != ENOTDIR))2986returnerror("%s:%s", new_name,strerror(errno));2987return0;2988}29892990static intverify_index_match(struct cache_entry *ce,struct stat *st)2991{2992if(S_ISGITLINK(ce->ce_mode)) {2993if(!S_ISDIR(st->st_mode))2994return-1;2995return0;2996}2997returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);2998}29993000static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)3001{3002const char*old_name = patch->old_name;3003struct patch *tpatch = NULL;3004int stat_ret =0;3005unsigned st_mode =0;30063007/*3008 * Make sure that we do not have local modifications from the3009 * index when we are looking at the index. Also make sure3010 * we have the preimage file to be patched in the work tree,3011 * unless --cached, which tells git to apply only in the index.3012 */3013if(!old_name)3014return0;30153016assert(patch->is_new <=0);30173018if(!(patch->is_copy || patch->is_rename) &&3019(tpatch =in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {3020if(was_deleted(tpatch))3021returnerror("%s: has been deleted/renamed", old_name);3022 st_mode = tpatch->new_mode;3023}else if(!cached) {3024 stat_ret =lstat(old_name, st);3025if(stat_ret && errno != ENOENT)3026returnerror("%s:%s", old_name,strerror(errno));3027}30283029if(to_be_deleted(tpatch))3030 tpatch = NULL;30313032if(check_index && !tpatch) {3033int pos =cache_name_pos(old_name,strlen(old_name));3034if(pos <0) {3035if(patch->is_new <0)3036goto is_new;3037returnerror("%s: does not exist in index", old_name);3038}3039*ce = active_cache[pos];3040if(stat_ret <0) {3041struct checkout costate;3042/* checkout */3043memset(&costate,0,sizeof(costate));3044 costate.base_dir ="";3045 costate.refresh_cache =1;3046if(checkout_entry(*ce, &costate, NULL) ||3047lstat(old_name, st))3048return-1;3049}3050if(!cached &&verify_index_match(*ce, st))3051returnerror("%s: does not match index", old_name);3052if(cached)3053 st_mode = (*ce)->ce_mode;3054}else if(stat_ret <0) {3055if(patch->is_new <0)3056goto is_new;3057returnerror("%s:%s", old_name,strerror(errno));3058}30593060if(!cached && !tpatch)3061 st_mode =ce_mode_from_stat(*ce, st->st_mode);30623063if(patch->is_new <0)3064 patch->is_new =0;3065if(!patch->old_mode)3066 patch->old_mode = st_mode;3067if((st_mode ^ patch->old_mode) & S_IFMT)3068returnerror("%s: wrong type", old_name);3069if(st_mode != patch->old_mode)3070warning("%shas type%o, expected%o",3071 old_name, st_mode, patch->old_mode);3072if(!patch->new_mode && !patch->is_delete)3073 patch->new_mode = st_mode;3074return0;30753076 is_new:3077 patch->is_new =1;3078 patch->is_delete =0;3079 patch->old_name = NULL;3080return0;3081}30823083static intcheck_patch(struct patch *patch)3084{3085struct stat st;3086const char*old_name = patch->old_name;3087const char*new_name = patch->new_name;3088const char*name = old_name ? old_name : new_name;3089struct cache_entry *ce = NULL;3090struct patch *tpatch;3091int ok_if_exists;3092int status;30933094 patch->rejected =1;/* we will drop this after we succeed */30953096 status =check_preimage(patch, &ce, &st);3097if(status)3098return status;3099 old_name = patch->old_name;31003101if((tpatch =in_fn_table(new_name)) &&3102(was_deleted(tpatch) ||to_be_deleted(tpatch)))3103/*3104 * A type-change diff is always split into a patch to3105 * delete old, immediately followed by a patch to3106 * create new (see diff.c::run_diff()); in such a case3107 * it is Ok that the entry to be deleted by the3108 * previous patch is still in the working tree and in3109 * the index.3110 */3111 ok_if_exists =1;3112else3113 ok_if_exists =0;31143115if(new_name &&3116((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {3117if(check_index &&3118cache_name_pos(new_name,strlen(new_name)) >=0&&3119!ok_if_exists)3120returnerror("%s: already exists in index", new_name);3121if(!cached) {3122int err =check_to_create_blob(new_name, ok_if_exists);3123if(err)3124return err;3125}3126if(!patch->new_mode) {3127if(0< patch->is_new)3128 patch->new_mode = S_IFREG |0644;3129else3130 patch->new_mode = patch->old_mode;3131}3132}31333134if(new_name && old_name) {3135int same = !strcmp(old_name, new_name);3136if(!patch->new_mode)3137 patch->new_mode = patch->old_mode;3138if((patch->old_mode ^ patch->new_mode) & S_IFMT)3139returnerror("new mode (%o) of%sdoes not match old mode (%o)%s%s",3140 patch->new_mode, new_name, patch->old_mode,3141 same ?"":" of ", same ?"": old_name);3142}31433144if(apply_data(patch, &st, ce) <0)3145returnerror("%s: patch does not apply", name);3146 patch->rejected =0;3147return0;3148}31493150static intcheck_patch_list(struct patch *patch)3151{3152int err =0;31533154prepare_fn_table(patch);3155while(patch) {3156if(apply_verbosely)3157say_patch_name(stderr,3158"Checking patch ", patch,"...\n");3159 err |=check_patch(patch);3160 patch = patch->next;3161}3162return err;3163}31643165/* This function tries to read the sha1 from the current index */3166static intget_current_sha1(const char*path,unsigned char*sha1)3167{3168int pos;31693170if(read_cache() <0)3171return-1;3172 pos =cache_name_pos(path,strlen(path));3173if(pos <0)3174return-1;3175hashcpy(sha1, active_cache[pos]->sha1);3176return0;3177}31783179/* Build an index that contains the just the files needed for a 3way merge */3180static voidbuild_fake_ancestor(struct patch *list,const char*filename)3181{3182struct patch *patch;3183struct index_state result = { NULL };3184int fd;31853186/* Once we start supporting the reverse patch, it may be3187 * worth showing the new sha1 prefix, but until then...3188 */3189for(patch = list; patch; patch = patch->next) {3190const unsigned char*sha1_ptr;3191unsigned char sha1[20];3192struct cache_entry *ce;3193const char*name;31943195 name = patch->old_name ? patch->old_name : patch->new_name;3196if(0< patch->is_new)3197continue;3198else if(get_sha1(patch->old_sha1_prefix, sha1))3199/* git diff has no index line for mode/type changes */3200if(!patch->lines_added && !patch->lines_deleted) {3201if(get_current_sha1(patch->old_name, sha1))3202die("mode change for%s, which is not "3203"in current HEAD", name);3204 sha1_ptr = sha1;3205}else3206die("sha1 information is lacking or useless "3207"(%s).", name);3208else3209 sha1_ptr = sha1;32103211 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);3212if(!ce)3213die("make_cache_entry failed for path '%s'", name);3214if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3215die("Could not add%sto temporary index", name);3216}32173218 fd =open(filename, O_WRONLY | O_CREAT,0666);3219if(fd <0||write_index(&result, fd) ||close(fd))3220die("Could not write temporary index to%s", filename);32213222discard_index(&result);3223}32243225static voidstat_patch_list(struct patch *patch)3226{3227int files, adds, dels;32283229for(files = adds = dels =0; patch ; patch = patch->next) {3230 files++;3231 adds += patch->lines_added;3232 dels += patch->lines_deleted;3233show_stats(patch);3234}32353236printf("%dfiles changed,%dinsertions(+),%ddeletions(-)\n", files, adds, dels);3237}32383239static voidnumstat_patch_list(struct patch *patch)3240{3241for( ; patch; patch = patch->next) {3242const char*name;3243 name = patch->new_name ? patch->new_name : patch->old_name;3244if(patch->is_binary)3245printf("-\t-\t");3246else3247printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3248write_name_quoted(name, stdout, line_termination);3249}3250}32513252static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3253{3254if(mode)3255printf("%smode%06o%s\n", newdelete, mode, name);3256else3257printf("%s %s\n", newdelete, name);3258}32593260static voidshow_mode_change(struct patch *p,int show_name)3261{3262if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3263if(show_name)3264printf(" mode change%06o =>%06o%s\n",3265 p->old_mode, p->new_mode, p->new_name);3266else3267printf(" mode change%06o =>%06o\n",3268 p->old_mode, p->new_mode);3269}3270}32713272static voidshow_rename_copy(struct patch *p)3273{3274const char*renamecopy = p->is_rename ?"rename":"copy";3275const char*old, *new;32763277/* Find common prefix */3278 old = p->old_name;3279new= p->new_name;3280while(1) {3281const char*slash_old, *slash_new;3282 slash_old =strchr(old,'/');3283 slash_new =strchr(new,'/');3284if(!slash_old ||3285!slash_new ||3286 slash_old - old != slash_new -new||3287memcmp(old,new, slash_new -new))3288break;3289 old = slash_old +1;3290new= slash_new +1;3291}3292/* p->old_name thru old is the common prefix, and old and new3293 * through the end of names are renames3294 */3295if(old != p->old_name)3296printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,3297(int)(old - p->old_name), p->old_name,3298 old,new, p->score);3299else3300printf("%s %s=>%s(%d%%)\n", renamecopy,3301 p->old_name, p->new_name, p->score);3302show_mode_change(p,0);3303}33043305static voidsummary_patch_list(struct patch *patch)3306{3307struct patch *p;33083309for(p = patch; p; p = p->next) {3310if(p->is_new)3311show_file_mode_name("create", p->new_mode, p->new_name);3312else if(p->is_delete)3313show_file_mode_name("delete", p->old_mode, p->old_name);3314else{3315if(p->is_rename || p->is_copy)3316show_rename_copy(p);3317else{3318if(p->score) {3319printf(" rewrite%s(%d%%)\n",3320 p->new_name, p->score);3321show_mode_change(p,0);3322}3323else3324show_mode_change(p,1);3325}3326}3327}3328}33293330static voidpatch_stats(struct patch *patch)3331{3332int lines = patch->lines_added + patch->lines_deleted;33333334if(lines > max_change)3335 max_change = lines;3336if(patch->old_name) {3337int len =quote_c_style(patch->old_name, NULL, NULL,0);3338if(!len)3339 len =strlen(patch->old_name);3340if(len > max_len)3341 max_len = len;3342}3343if(patch->new_name) {3344int len =quote_c_style(patch->new_name, NULL, NULL,0);3345if(!len)3346 len =strlen(patch->new_name);3347if(len > max_len)3348 max_len = len;3349}3350}33513352static voidremove_file(struct patch *patch,int rmdir_empty)3353{3354if(update_index) {3355if(remove_file_from_cache(patch->old_name) <0)3356die("unable to remove%sfrom index", patch->old_name);3357}3358if(!cached) {3359if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {3360remove_path(patch->old_name);3361}3362}3363}33643365static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)3366{3367struct stat st;3368struct cache_entry *ce;3369int namelen =strlen(path);3370unsigned ce_size =cache_entry_size(namelen);33713372if(!update_index)3373return;33743375 ce =xcalloc(1, ce_size);3376memcpy(ce->name, path, namelen);3377 ce->ce_mode =create_ce_mode(mode);3378 ce->ce_flags = namelen;3379if(S_ISGITLINK(mode)) {3380const char*s = buf;33813382if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))3383die("corrupt patch for subproject%s", path);3384}else{3385if(!cached) {3386if(lstat(path, &st) <0)3387die_errno("unable to stat newly created file '%s'",3388 path);3389fill_stat_cache_info(ce, &st);3390}3391if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)3392die("unable to create backing store for newly created file%s", path);3393}3394if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3395die("unable to add cache entry for%s", path);3396}33973398static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)3399{3400int fd;3401struct strbuf nbuf = STRBUF_INIT;34023403if(S_ISGITLINK(mode)) {3404struct stat st;3405if(!lstat(path, &st) &&S_ISDIR(st.st_mode))3406return0;3407returnmkdir(path,0777);3408}34093410if(has_symlinks &&S_ISLNK(mode))3411/* Although buf:size is counted string, it also is NUL3412 * terminated.3413 */3414returnsymlink(buf, path);34153416 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);3417if(fd <0)3418return-1;34193420if(convert_to_working_tree(path, buf, size, &nbuf)) {3421 size = nbuf.len;3422 buf = nbuf.buf;3423}3424write_or_die(fd, buf, size);3425strbuf_release(&nbuf);34263427if(close(fd) <0)3428die_errno("closing file '%s'", path);3429return0;3430}34313432/*3433 * We optimistically assume that the directories exist,3434 * which is true 99% of the time anyway. If they don't,3435 * we create them and try again.3436 */3437static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)3438{3439if(cached)3440return;3441if(!try_create_file(path, mode, buf, size))3442return;34433444if(errno == ENOENT) {3445if(safe_create_leading_directories(path))3446return;3447if(!try_create_file(path, mode, buf, size))3448return;3449}34503451if(errno == EEXIST || errno == EACCES) {3452/* We may be trying to create a file where a directory3453 * used to be.3454 */3455struct stat st;3456if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))3457 errno = EEXIST;3458}34593460if(errno == EEXIST) {3461unsigned int nr =getpid();34623463for(;;) {3464char newpath[PATH_MAX];3465mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);3466if(!try_create_file(newpath, mode, buf, size)) {3467if(!rename(newpath, path))3468return;3469unlink_or_warn(newpath);3470break;3471}3472if(errno != EEXIST)3473break;3474++nr;3475}3476}3477die_errno("unable to write file '%s' mode%o", path, mode);3478}34793480static voidcreate_file(struct patch *patch)3481{3482char*path = patch->new_name;3483unsigned mode = patch->new_mode;3484unsigned long size = patch->resultsize;3485char*buf = patch->result;34863487if(!mode)3488 mode = S_IFREG |0644;3489create_one_file(path, mode, buf, size);3490add_index_file(path, mode, buf, size);3491}34923493/* phase zero is to remove, phase one is to create */3494static voidwrite_out_one_result(struct patch *patch,int phase)3495{3496if(patch->is_delete >0) {3497if(phase ==0)3498remove_file(patch,1);3499return;3500}3501if(patch->is_new >0|| patch->is_copy) {3502if(phase ==1)3503create_file(patch);3504return;3505}3506/*3507 * Rename or modification boils down to the same3508 * thing: remove the old, write the new3509 */3510if(phase ==0)3511remove_file(patch, patch->is_rename);3512if(phase ==1)3513create_file(patch);3514}35153516static intwrite_out_one_reject(struct patch *patch)3517{3518FILE*rej;3519char namebuf[PATH_MAX];3520struct fragment *frag;3521int cnt =0;35223523for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {3524if(!frag->rejected)3525continue;3526 cnt++;3527}35283529if(!cnt) {3530if(apply_verbosely)3531say_patch_name(stderr,3532"Applied patch ", patch," cleanly.\n");3533return0;3534}35353536/* This should not happen, because a removal patch that leaves3537 * contents are marked "rejected" at the patch level.3538 */3539if(!patch->new_name)3540die("internal error");35413542/* Say this even without --verbose */3543say_patch_name(stderr,"Applying patch ", patch," with");3544fprintf(stderr,"%drejects...\n", cnt);35453546 cnt =strlen(patch->new_name);3547if(ARRAY_SIZE(namebuf) <= cnt +5) {3548 cnt =ARRAY_SIZE(namebuf) -5;3549warning("truncating .rej filename to %.*s.rej",3550 cnt -1, patch->new_name);3551}3552memcpy(namebuf, patch->new_name, cnt);3553memcpy(namebuf + cnt,".rej",5);35543555 rej =fopen(namebuf,"w");3556if(!rej)3557returnerror("cannot open%s:%s", namebuf,strerror(errno));35583559/* Normal git tools never deal with .rej, so do not pretend3560 * this is a git patch by saying --git nor give extended3561 * headers. While at it, maybe please "kompare" that wants3562 * the trailing TAB and some garbage at the end of line ;-).3563 */3564fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",3565 patch->new_name, patch->new_name);3566for(cnt =1, frag = patch->fragments;3567 frag;3568 cnt++, frag = frag->next) {3569if(!frag->rejected) {3570fprintf(stderr,"Hunk #%dapplied cleanly.\n", cnt);3571continue;3572}3573fprintf(stderr,"Rejected hunk #%d.\n", cnt);3574fprintf(rej,"%.*s", frag->size, frag->patch);3575if(frag->patch[frag->size-1] !='\n')3576fputc('\n', rej);3577}3578fclose(rej);3579return-1;3580}35813582static intwrite_out_results(struct patch *list,int skipped_patch)3583{3584int phase;3585int errs =0;3586struct patch *l;35873588if(!list && !skipped_patch)3589returnerror("No changes");35903591for(phase =0; phase <2; phase++) {3592 l = list;3593while(l) {3594if(l->rejected)3595 errs =1;3596else{3597write_out_one_result(l, phase);3598if(phase ==1&&write_out_one_reject(l))3599 errs =1;3600}3601 l = l->next;3602}3603}3604return errs;3605}36063607static struct lock_file lock_file;36083609static struct string_list limit_by_name;3610static int has_include;3611static voidadd_name_limit(const char*name,int exclude)3612{3613struct string_list_item *it;36143615 it =string_list_append(&limit_by_name, name);3616 it->util = exclude ? NULL : (void*)1;3617}36183619static intuse_patch(struct patch *p)3620{3621const char*pathname = p->new_name ? p->new_name : p->old_name;3622int i;36233624/* Paths outside are not touched regardless of "--include" */3625if(0< prefix_length) {3626int pathlen =strlen(pathname);3627if(pathlen <= prefix_length ||3628memcmp(prefix, pathname, prefix_length))3629return0;3630}36313632/* See if it matches any of exclude/include rule */3633for(i =0; i < limit_by_name.nr; i++) {3634struct string_list_item *it = &limit_by_name.items[i];3635if(!fnmatch(it->string, pathname,0))3636return(it->util != NULL);3637}36383639/*3640 * If we had any include, a path that does not match any rule is3641 * not used. Otherwise, we saw bunch of exclude rules (or none)3642 * and such a path is used.3643 */3644return!has_include;3645}364636473648static voidprefix_one(char**name)3649{3650char*old_name = *name;3651if(!old_name)3652return;3653*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3654free(old_name);3655}36563657static voidprefix_patches(struct patch *p)3658{3659if(!prefix || p->is_toplevel_relative)3660return;3661for( ; p; p = p->next) {3662if(p->new_name == p->old_name) {3663char*prefixed = p->new_name;3664prefix_one(&prefixed);3665 p->new_name = p->old_name = prefixed;3666}3667else{3668prefix_one(&p->new_name);3669prefix_one(&p->old_name);3670}3671}3672}36733674#define INACCURATE_EOF (1<<0)3675#define RECOUNT (1<<1)36763677static intapply_patch(int fd,const char*filename,int options)3678{3679size_t offset;3680struct strbuf buf = STRBUF_INIT;3681struct patch *list = NULL, **listp = &list;3682int skipped_patch =0;36833684/* FIXME - memory leak when using multiple patch files as inputs */3685memset(&fn_table,0,sizeof(struct string_list));3686 patch_input_file = filename;3687read_patch_file(&buf, fd);3688 offset =0;3689while(offset < buf.len) {3690struct patch *patch;3691int nr;36923693 patch =xcalloc(1,sizeof(*patch));3694 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3695 patch->recount = !!(options & RECOUNT);3696 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3697if(nr <0)3698break;3699if(apply_in_reverse)3700reverse_patches(patch);3701if(prefix)3702prefix_patches(patch);3703if(use_patch(patch)) {3704patch_stats(patch);3705*listp = patch;3706 listp = &patch->next;3707}3708else{3709/* perhaps free it a bit better? */3710free(patch);3711 skipped_patch++;3712}3713 offset += nr;3714}37153716if(whitespace_error && (ws_error_action == die_on_ws_error))3717 apply =0;37183719 update_index = check_index && apply;3720if(update_index && newfd <0)3721 newfd =hold_locked_index(&lock_file,1);37223723if(check_index) {3724if(read_cache() <0)3725die("unable to read index file");3726}37273728if((check || apply) &&3729check_patch_list(list) <0&&3730!apply_with_reject)3731exit(1);37323733if(apply &&write_out_results(list, skipped_patch))3734exit(1);37353736if(fake_ancestor)3737build_fake_ancestor(list, fake_ancestor);37383739if(diffstat)3740stat_patch_list(list);37413742if(numstat)3743numstat_patch_list(list);37443745if(summary)3746summary_patch_list(list);37473748strbuf_release(&buf);3749return0;3750}37513752static intgit_apply_config(const char*var,const char*value,void*cb)3753{3754if(!strcmp(var,"apply.whitespace"))3755returngit_config_string(&apply_default_whitespace, var, value);3756else if(!strcmp(var,"apply.ignorewhitespace"))3757returngit_config_string(&apply_default_ignorewhitespace, var, value);3758returngit_default_config(var, value, cb);3759}37603761static intoption_parse_exclude(const struct option *opt,3762const char*arg,int unset)3763{3764add_name_limit(arg,1);3765return0;3766}37673768static intoption_parse_include(const struct option *opt,3769const char*arg,int unset)3770{3771add_name_limit(arg,0);3772 has_include =1;3773return0;3774}37753776static intoption_parse_p(const struct option *opt,3777const char*arg,int unset)3778{3779 p_value =atoi(arg);3780 p_value_known =1;3781return0;3782}37833784static intoption_parse_z(const struct option *opt,3785const char*arg,int unset)3786{3787if(unset)3788 line_termination ='\n';3789else3790 line_termination =0;3791return0;3792}37933794static intoption_parse_space_change(const struct option *opt,3795const char*arg,int unset)3796{3797if(unset)3798 ws_ignore_action = ignore_ws_none;3799else3800 ws_ignore_action = ignore_ws_change;3801return0;3802}38033804static intoption_parse_whitespace(const struct option *opt,3805const char*arg,int unset)3806{3807const char**whitespace_option = opt->value;38083809*whitespace_option = arg;3810parse_whitespace_option(arg);3811return0;3812}38133814static intoption_parse_directory(const struct option *opt,3815const char*arg,int unset)3816{3817 root_len =strlen(arg);3818if(root_len && arg[root_len -1] !='/') {3819char*new_root;3820 root = new_root =xmalloc(root_len +2);3821strcpy(new_root, arg);3822strcpy(new_root + root_len++,"/");3823}else3824 root = arg;3825return0;3826}38273828intcmd_apply(int argc,const char**argv,const char*prefix_)3829{3830int i;3831int errs =0;3832int is_not_gitdir = !startup_info->have_repository;3833int binary;3834int force_apply =0;38353836const char*whitespace_option = NULL;38373838struct option builtin_apply_options[] = {3839{ OPTION_CALLBACK,0,"exclude", NULL,"path",3840"don't apply changes matching the given path",38410, option_parse_exclude },3842{ OPTION_CALLBACK,0,"include", NULL,"path",3843"apply changes matching the given path",38440, option_parse_include },3845{ OPTION_CALLBACK,'p', NULL, NULL,"num",3846"remove <num> leading slashes from traditional diff paths",38470, option_parse_p },3848OPT_BOOLEAN(0,"no-add", &no_add,3849"ignore additions made by the patch"),3850OPT_BOOLEAN(0,"stat", &diffstat,3851"instead of applying the patch, output diffstat for the input"),3852{ OPTION_BOOLEAN,0,"allow-binary-replacement", &binary,3853 NULL,"old option, now no-op",3854 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3855{ OPTION_BOOLEAN,0,"binary", &binary,3856 NULL,"old option, now no-op",3857 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3858OPT_BOOLEAN(0,"numstat", &numstat,3859"shows number of added and deleted lines in decimal notation"),3860OPT_BOOLEAN(0,"summary", &summary,3861"instead of applying the patch, output a summary for the input"),3862OPT_BOOLEAN(0,"check", &check,3863"instead of applying the patch, see if the patch is applicable"),3864OPT_BOOLEAN(0,"index", &check_index,3865"make sure the patch is applicable to the current index"),3866OPT_BOOLEAN(0,"cached", &cached,3867"apply a patch without touching the working tree"),3868OPT_BOOLEAN(0,"apply", &force_apply,3869"also apply the patch (use with --stat/--summary/--check)"),3870OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,3871"build a temporary index based on embedded index information"),3872{ OPTION_CALLBACK,'z', NULL, NULL, NULL,3873"paths are separated with NUL character",3874 PARSE_OPT_NOARG, option_parse_z },3875OPT_INTEGER('C', NULL, &p_context,3876"ensure at least <n> lines of context match"),3877{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,"action",3878"detect new or modified lines that have whitespace errors",38790, option_parse_whitespace },3880{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,3881"ignore changes in whitespace when finding context",3882 PARSE_OPT_NOARG, option_parse_space_change },3883{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,3884"ignore changes in whitespace when finding context",3885 PARSE_OPT_NOARG, option_parse_space_change },3886OPT_BOOLEAN('R',"reverse", &apply_in_reverse,3887"apply the patch in reverse"),3888OPT_BOOLEAN(0,"unidiff-zero", &unidiff_zero,3889"don't expect at least one line of context"),3890OPT_BOOLEAN(0,"reject", &apply_with_reject,3891"leave the rejected hunks in corresponding *.rej files"),3892OPT__VERBOSE(&apply_verbosely,"be verbose"),3893OPT_BIT(0,"inaccurate-eof", &options,3894"tolerate incorrectly detected missing new-line at the end of file",3895 INACCURATE_EOF),3896OPT_BIT(0,"recount", &options,3897"do not trust the line counts in the hunk headers",3898 RECOUNT),3899{ OPTION_CALLBACK,0,"directory", NULL,"root",3900"prepend <root> to all filenames",39010, option_parse_directory },3902OPT_END()3903};39043905 prefix = prefix_;3906 prefix_length = prefix ?strlen(prefix) :0;3907git_config(git_apply_config, NULL);3908if(apply_default_whitespace)3909parse_whitespace_option(apply_default_whitespace);3910if(apply_default_ignorewhitespace)3911parse_ignorewhitespace_option(apply_default_ignorewhitespace);39123913 argc =parse_options(argc, argv, prefix, builtin_apply_options,3914 apply_usage,0);39153916if(apply_with_reject)3917 apply = apply_verbosely =1;3918if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))3919 apply =0;3920if(check_index && is_not_gitdir)3921die("--index outside a repository");3922if(cached) {3923if(is_not_gitdir)3924die("--cached outside a repository");3925 check_index =1;3926}3927for(i =0; i < argc; i++) {3928const char*arg = argv[i];3929int fd;39303931if(!strcmp(arg,"-")) {3932 errs |=apply_patch(0,"<stdin>", options);3933 read_stdin =0;3934continue;3935}else if(0< prefix_length)3936 arg =prefix_filename(prefix, prefix_length, arg);39373938 fd =open(arg, O_RDONLY);3939if(fd <0)3940die_errno("can't open patch '%s'", arg);3941 read_stdin =0;3942set_default_whitespace_mode(whitespace_option);3943 errs |=apply_patch(fd, arg, options);3944close(fd);3945}3946set_default_whitespace_mode(whitespace_option);3947if(read_stdin)3948 errs |=apply_patch(0,"<stdin>", options);3949if(whitespace_error) {3950if(squelch_whitespace_errors &&3951 squelch_whitespace_errors < whitespace_error) {3952int squelched =3953 whitespace_error - squelch_whitespace_errors;3954warning("squelched%d"3955"whitespace error%s",3956 squelched,3957 squelched ==1?"":"s");3958}3959if(ws_error_action == die_on_ws_error)3960die("%dline%sadd%swhitespace errors.",3961 whitespace_error,3962 whitespace_error ==1?"":"s",3963 whitespace_error ==1?"s":"");3964if(applied_after_fixing_ws && apply)3965warning("%dline%sapplied after"3966" fixing whitespace errors.",3967 applied_after_fixing_ws,3968 applied_after_fixing_ws ==1?"":"s");3969else if(whitespace_error)3970warning("%dline%sadd%swhitespace errors.",3971 whitespace_error,3972 whitespace_error ==1?"":"s",3973 whitespace_error ==1?"s":"");3974}39753976if(update_index) {3977if(write_cache(newfd, active_cache, active_nr) ||3978commit_locked_index(&lock_file))3979die("Unable to write new index file");3980}39813982return!!errs;3983}