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"lockfile.h" 11#include"cache-tree.h" 12#include"quote.h" 13#include"blob.h" 14#include"delta.h" 15#include"builtin.h" 16#include"string-list.h" 17#include"dir.h" 18#include"diff.h" 19#include"parse-options.h" 20#include"xdiff-interface.h" 21#include"ll-merge.h" 22#include"rerere.h" 23 24/* 25 * --check turns on checking that the working tree matches the 26 * files that are being modified, but doesn't apply the patch 27 * --stat does just a diffstat, and doesn't actually apply 28 * --numstat does numeric diffstat, and doesn't actually apply 29 * --index-info shows the old and new index info for paths if available. 30 * --index updates the cache as well. 31 * --cached updates only the cache without ever touching the working tree. 32 */ 33static const char*prefix; 34static int prefix_length = -1; 35static int newfd = -1; 36 37static int unidiff_zero; 38static int p_value =1; 39static int p_value_known; 40static int check_index; 41static int update_index; 42static int cached; 43static int diffstat; 44static int numstat; 45static int summary; 46static int check; 47static int apply =1; 48static int apply_in_reverse; 49static int apply_with_reject; 50static int apply_verbosely; 51static int allow_overlap; 52static int no_add; 53static int threeway; 54static const char*fake_ancestor; 55static int line_termination ='\n'; 56static unsigned int p_context = UINT_MAX; 57static const char*const apply_usage[] = { 58N_("git apply [options] [<patch>...]"), 59 NULL 60}; 61 62static enum ws_error_action { 63 nowarn_ws_error, 64 warn_on_ws_error, 65 die_on_ws_error, 66 correct_ws_error 67} ws_error_action = warn_on_ws_error; 68static int whitespace_error; 69static int squelch_whitespace_errors =5; 70static int applied_after_fixing_ws; 71 72static enum ws_ignore { 73 ignore_ws_none, 74 ignore_ws_change 75} ws_ignore_action = ignore_ws_none; 76 77 78static const char*patch_input_file; 79static const char*root; 80static int root_len; 81static int read_stdin =1; 82static int options; 83 84static voidparse_whitespace_option(const char*option) 85{ 86if(!option) { 87 ws_error_action = warn_on_ws_error; 88return; 89} 90if(!strcmp(option,"warn")) { 91 ws_error_action = warn_on_ws_error; 92return; 93} 94if(!strcmp(option,"nowarn")) { 95 ws_error_action = nowarn_ws_error; 96return; 97} 98if(!strcmp(option,"error")) { 99 ws_error_action = die_on_ws_error; 100return; 101} 102if(!strcmp(option,"error-all")) { 103 ws_error_action = die_on_ws_error; 104 squelch_whitespace_errors =0; 105return; 106} 107if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 108 ws_error_action = correct_ws_error; 109return; 110} 111die(_("unrecognized whitespace option '%s'"), option); 112} 113 114static voidparse_ignorewhitespace_option(const char*option) 115{ 116if(!option || !strcmp(option,"no") || 117!strcmp(option,"false") || !strcmp(option,"never") || 118!strcmp(option,"none")) { 119 ws_ignore_action = ignore_ws_none; 120return; 121} 122if(!strcmp(option,"change")) { 123 ws_ignore_action = ignore_ws_change; 124return; 125} 126die(_("unrecognized whitespace ignore option '%s'"), option); 127} 128 129static voidset_default_whitespace_mode(const char*whitespace_option) 130{ 131if(!whitespace_option && !apply_default_whitespace) 132 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 133} 134 135/* 136 * For "diff-stat" like behaviour, we keep track of the biggest change 137 * we've seen, and the longest filename. That allows us to do simple 138 * scaling. 139 */ 140static int max_change, max_len; 141 142/* 143 * Various "current state", notably line numbers and what 144 * file (and how) we're patching right now.. The "is_xxxx" 145 * things are flags, where -1 means "don't know yet". 146 */ 147static int linenr =1; 148 149/* 150 * This represents one "hunk" from a patch, starting with 151 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 152 * patch text is pointed at by patch, and its byte length 153 * is stored in size. leading and trailing are the number 154 * of context lines. 155 */ 156struct fragment { 157unsigned long leading, trailing; 158unsigned long oldpos, oldlines; 159unsigned long newpos, newlines; 160/* 161 * 'patch' is usually borrowed from buf in apply_patch(), 162 * but some codepaths store an allocated buffer. 163 */ 164const char*patch; 165unsigned free_patch:1, 166 rejected:1; 167int size; 168int linenr; 169struct fragment *next; 170}; 171 172/* 173 * When dealing with a binary patch, we reuse "leading" field 174 * to store the type of the binary hunk, either deflated "delta" 175 * or deflated "literal". 176 */ 177#define binary_patch_method leading 178#define BINARY_DELTA_DEFLATED 1 179#define BINARY_LITERAL_DEFLATED 2 180 181/* 182 * This represents a "patch" to a file, both metainfo changes 183 * such as creation/deletion, filemode and content changes represented 184 * as a series of fragments. 185 */ 186struct patch { 187char*new_name, *old_name, *def_name; 188unsigned int old_mode, new_mode; 189int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 190int rejected; 191unsigned ws_rule; 192int lines_added, lines_deleted; 193int score; 194unsigned int is_toplevel_relative:1; 195unsigned int inaccurate_eof:1; 196unsigned int is_binary:1; 197unsigned int is_copy:1; 198unsigned int is_rename:1; 199unsigned int recount:1; 200unsigned int conflicted_threeway:1; 201unsigned int direct_to_threeway:1; 202struct fragment *fragments; 203char*result; 204size_t resultsize; 205char old_sha1_prefix[41]; 206char new_sha1_prefix[41]; 207struct patch *next; 208 209/* three-way fallback result */ 210unsigned char threeway_stage[3][20]; 211}; 212 213static voidfree_fragment_list(struct fragment *list) 214{ 215while(list) { 216struct fragment *next = list->next; 217if(list->free_patch) 218free((char*)list->patch); 219free(list); 220 list = next; 221} 222} 223 224static voidfree_patch(struct patch *patch) 225{ 226free_fragment_list(patch->fragments); 227free(patch->def_name); 228free(patch->old_name); 229free(patch->new_name); 230free(patch->result); 231free(patch); 232} 233 234static voidfree_patch_list(struct patch *list) 235{ 236while(list) { 237struct patch *next = list->next; 238free_patch(list); 239 list = next; 240} 241} 242 243/* 244 * A line in a file, len-bytes long (includes the terminating LF, 245 * except for an incomplete line at the end if the file ends with 246 * one), and its contents hashes to 'hash'. 247 */ 248struct line { 249size_t len; 250unsigned hash :24; 251unsigned flag :8; 252#define LINE_COMMON 1 253#define LINE_PATCHED 2 254}; 255 256/* 257 * This represents a "file", which is an array of "lines". 258 */ 259struct image { 260char*buf; 261size_t len; 262size_t nr; 263size_t alloc; 264struct line *line_allocated; 265struct line *line; 266}; 267 268/* 269 * Records filenames that have been touched, in order to handle 270 * the case where more than one patches touch the same file. 271 */ 272 273static struct string_list fn_table; 274 275static uint32_thash_line(const char*cp,size_t len) 276{ 277size_t i; 278uint32_t h; 279for(i =0, h =0; i < len; i++) { 280if(!isspace(cp[i])) { 281 h = h *3+ (cp[i] &0xff); 282} 283} 284return h; 285} 286 287/* 288 * Compare lines s1 of length n1 and s2 of length n2, ignoring 289 * whitespace difference. Returns 1 if they match, 0 otherwise 290 */ 291static intfuzzy_matchlines(const char*s1,size_t n1, 292const char*s2,size_t n2) 293{ 294const char*last1 = s1 + n1 -1; 295const char*last2 = s2 + n2 -1; 296int result =0; 297 298/* ignore line endings */ 299while((*last1 =='\r') || (*last1 =='\n')) 300 last1--; 301while((*last2 =='\r') || (*last2 =='\n')) 302 last2--; 303 304/* skip leading whitespaces, if both begin with whitespace */ 305if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 306while(isspace(*s1) && (s1 <= last1)) 307 s1++; 308while(isspace(*s2) && (s2 <= last2)) 309 s2++; 310} 311/* early return if both lines are empty */ 312if((s1 > last1) && (s2 > last2)) 313return1; 314while(!result) { 315 result = *s1++ - *s2++; 316/* 317 * Skip whitespace inside. We check for whitespace on 318 * both buffers because we don't want "a b" to match 319 * "ab" 320 */ 321if(isspace(*s1) &&isspace(*s2)) { 322while(isspace(*s1) && s1 <= last1) 323 s1++; 324while(isspace(*s2) && s2 <= last2) 325 s2++; 326} 327/* 328 * If we reached the end on one side only, 329 * lines don't match 330 */ 331if( 332((s2 > last2) && (s1 <= last1)) || 333((s1 > last1) && (s2 <= last2))) 334return0; 335if((s1 > last1) && (s2 > last2)) 336break; 337} 338 339return!result; 340} 341 342static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 343{ 344ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 345 img->line_allocated[img->nr].len = len; 346 img->line_allocated[img->nr].hash =hash_line(bol, len); 347 img->line_allocated[img->nr].flag = flag; 348 img->nr++; 349} 350 351/* 352 * "buf" has the file contents to be patched (read from various sources). 353 * attach it to "image" and add line-based index to it. 354 * "image" now owns the "buf". 355 */ 356static voidprepare_image(struct image *image,char*buf,size_t len, 357int prepare_linetable) 358{ 359const char*cp, *ep; 360 361memset(image,0,sizeof(*image)); 362 image->buf = buf; 363 image->len = len; 364 365if(!prepare_linetable) 366return; 367 368 ep = image->buf + image->len; 369 cp = image->buf; 370while(cp < ep) { 371const char*next; 372for(next = cp; next < ep && *next !='\n'; next++) 373; 374if(next < ep) 375 next++; 376add_line_info(image, cp, next - cp,0); 377 cp = next; 378} 379 image->line = image->line_allocated; 380} 381 382static voidclear_image(struct image *image) 383{ 384free(image->buf); 385free(image->line_allocated); 386memset(image,0,sizeof(*image)); 387} 388 389/* fmt must contain _one_ %s and no other substitution */ 390static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 391{ 392struct strbuf sb = STRBUF_INIT; 393 394if(patch->old_name && patch->new_name && 395strcmp(patch->old_name, patch->new_name)) { 396quote_c_style(patch->old_name, &sb, NULL,0); 397strbuf_addstr(&sb," => "); 398quote_c_style(patch->new_name, &sb, NULL,0); 399}else{ 400const char*n = patch->new_name; 401if(!n) 402 n = patch->old_name; 403quote_c_style(n, &sb, NULL,0); 404} 405fprintf(output, fmt, sb.buf); 406fputc('\n', output); 407strbuf_release(&sb); 408} 409 410#define SLOP (16) 411 412static voidread_patch_file(struct strbuf *sb,int fd) 413{ 414if(strbuf_read(sb, fd,0) <0) 415die_errno("git apply: failed to read"); 416 417/* 418 * Make sure that we have some slop in the buffer 419 * so that we can do speculative "memcmp" etc, and 420 * see to it that it is NUL-filled. 421 */ 422strbuf_grow(sb, SLOP); 423memset(sb->buf + sb->len,0, SLOP); 424} 425 426static unsigned longlinelen(const char*buffer,unsigned long size) 427{ 428unsigned long len =0; 429while(size--) { 430 len++; 431if(*buffer++ =='\n') 432break; 433} 434return len; 435} 436 437static intis_dev_null(const char*str) 438{ 439returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 440} 441 442#define TERM_SPACE 1 443#define TERM_TAB 2 444 445static intname_terminate(const char*name,int namelen,int c,int terminate) 446{ 447if(c ==' '&& !(terminate & TERM_SPACE)) 448return0; 449if(c =='\t'&& !(terminate & TERM_TAB)) 450return0; 451 452return1; 453} 454 455/* remove double slashes to make --index work with such filenames */ 456static char*squash_slash(char*name) 457{ 458int i =0, j =0; 459 460if(!name) 461return NULL; 462 463while(name[i]) { 464if((name[j++] = name[i++]) =='/') 465while(name[i] =='/') 466 i++; 467} 468 name[j] ='\0'; 469return name; 470} 471 472static char*find_name_gnu(const char*line,const char*def,int p_value) 473{ 474struct strbuf name = STRBUF_INIT; 475char*cp; 476 477/* 478 * Proposed "new-style" GNU patch/diff format; see 479 * http://marc.info/?l=git&m=112927316408690&w=2 480 */ 481if(unquote_c_style(&name, line, NULL)) { 482strbuf_release(&name); 483return NULL; 484} 485 486for(cp = name.buf; p_value; p_value--) { 487 cp =strchr(cp,'/'); 488if(!cp) { 489strbuf_release(&name); 490return NULL; 491} 492 cp++; 493} 494 495strbuf_remove(&name,0, cp - name.buf); 496if(root) 497strbuf_insert(&name,0, root, root_len); 498returnsquash_slash(strbuf_detach(&name, NULL)); 499} 500 501static size_tsane_tz_len(const char*line,size_t len) 502{ 503const char*tz, *p; 504 505if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 506return0; 507 tz = line + len -strlen(" +0500"); 508 509if(tz[1] !='+'&& tz[1] !='-') 510return0; 511 512for(p = tz +2; p != line + len; p++) 513if(!isdigit(*p)) 514return0; 515 516return line + len - tz; 517} 518 519static size_ttz_with_colon_len(const char*line,size_t len) 520{ 521const char*tz, *p; 522 523if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 524return0; 525 tz = line + len -strlen(" +08:00"); 526 527if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 528return0; 529 p = tz +2; 530if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 531!isdigit(*p++) || !isdigit(*p++)) 532return0; 533 534return line + len - tz; 535} 536 537static size_tdate_len(const char*line,size_t len) 538{ 539const char*date, *p; 540 541if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 542return0; 543 p = date = line + len -strlen("72-02-05"); 544 545if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 546!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 547!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 548return0; 549 550if(date - line >=strlen("19") && 551isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 552 date -=strlen("19"); 553 554return line + len - date; 555} 556 557static size_tshort_time_len(const char*line,size_t len) 558{ 559const char*time, *p; 560 561if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 562return0; 563 p = time = line + len -strlen(" 07:01:32"); 564 565/* Permit 1-digit hours? */ 566if(*p++ !=' '|| 567!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 568!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 569!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 570return0; 571 572return line + len - time; 573} 574 575static size_tfractional_time_len(const char*line,size_t len) 576{ 577const char*p; 578size_t n; 579 580/* Expected format: 19:41:17.620000023 */ 581if(!len || !isdigit(line[len -1])) 582return0; 583 p = line + len -1; 584 585/* Fractional seconds. */ 586while(p > line &&isdigit(*p)) 587 p--; 588if(*p !='.') 589return0; 590 591/* Hours, minutes, and whole seconds. */ 592 n =short_time_len(line, p - line); 593if(!n) 594return0; 595 596return line + len - p + n; 597} 598 599static size_ttrailing_spaces_len(const char*line,size_t len) 600{ 601const char*p; 602 603/* Expected format: ' ' x (1 or more) */ 604if(!len || line[len -1] !=' ') 605return0; 606 607 p = line + len; 608while(p != line) { 609 p--; 610if(*p !=' ') 611return line + len - (p +1); 612} 613 614/* All spaces! */ 615return len; 616} 617 618static size_tdiff_timestamp_len(const char*line,size_t len) 619{ 620const char*end = line + len; 621size_t n; 622 623/* 624 * Posix: 2010-07-05 19:41:17 625 * GNU: 2010-07-05 19:41:17.620000023 -0500 626 */ 627 628if(!isdigit(end[-1])) 629return0; 630 631 n =sane_tz_len(line, end - line); 632if(!n) 633 n =tz_with_colon_len(line, end - line); 634 end -= n; 635 636 n =short_time_len(line, end - line); 637if(!n) 638 n =fractional_time_len(line, end - line); 639 end -= n; 640 641 n =date_len(line, end - line); 642if(!n)/* No date. Too bad. */ 643return0; 644 end -= n; 645 646if(end == line)/* No space before date. */ 647return0; 648if(end[-1] =='\t') {/* Success! */ 649 end--; 650return line + len - end; 651} 652if(end[-1] !=' ')/* No space before date. */ 653return0; 654 655/* Whitespace damage. */ 656 end -=trailing_spaces_len(line, end - line); 657return line + len - end; 658} 659 660static char*find_name_common(const char*line,const char*def, 661int p_value,const char*end,int terminate) 662{ 663int len; 664const char*start = NULL; 665 666if(p_value ==0) 667 start = line; 668while(line != end) { 669char c = *line; 670 671if(!end &&isspace(c)) { 672if(c =='\n') 673break; 674if(name_terminate(start, line-start, c, terminate)) 675break; 676} 677 line++; 678if(c =='/'&& !--p_value) 679 start = line; 680} 681if(!start) 682returnsquash_slash(xstrdup_or_null(def)); 683 len = line - start; 684if(!len) 685returnsquash_slash(xstrdup_or_null(def)); 686 687/* 688 * Generally we prefer the shorter name, especially 689 * if the other one is just a variation of that with 690 * something else tacked on to the end (ie "file.orig" 691 * or "file~"). 692 */ 693if(def) { 694int deflen =strlen(def); 695if(deflen < len && !strncmp(start, def, deflen)) 696returnsquash_slash(xstrdup(def)); 697} 698 699if(root) { 700char*ret =xmalloc(root_len + len +1); 701strcpy(ret, root); 702memcpy(ret + root_len, start, len); 703 ret[root_len + len] ='\0'; 704returnsquash_slash(ret); 705} 706 707returnsquash_slash(xmemdupz(start, len)); 708} 709 710static char*find_name(const char*line,char*def,int p_value,int terminate) 711{ 712if(*line =='"') { 713char*name =find_name_gnu(line, def, p_value); 714if(name) 715return name; 716} 717 718returnfind_name_common(line, def, p_value, NULL, terminate); 719} 720 721static char*find_name_traditional(const char*line,char*def,int p_value) 722{ 723size_t len; 724size_t date_len; 725 726if(*line =='"') { 727char*name =find_name_gnu(line, def, p_value); 728if(name) 729return name; 730} 731 732 len =strchrnul(line,'\n') - line; 733 date_len =diff_timestamp_len(line, len); 734if(!date_len) 735returnfind_name_common(line, def, p_value, NULL, TERM_TAB); 736 len -= date_len; 737 738returnfind_name_common(line, def, p_value, line + len,0); 739} 740 741static intcount_slashes(const char*cp) 742{ 743int cnt =0; 744char ch; 745 746while((ch = *cp++)) 747if(ch =='/') 748 cnt++; 749return cnt; 750} 751 752/* 753 * Given the string after "--- " or "+++ ", guess the appropriate 754 * p_value for the given patch. 755 */ 756static intguess_p_value(const char*nameline) 757{ 758char*name, *cp; 759int val = -1; 760 761if(is_dev_null(nameline)) 762return-1; 763 name =find_name_traditional(nameline, NULL,0); 764if(!name) 765return-1; 766 cp =strchr(name,'/'); 767if(!cp) 768 val =0; 769else if(prefix) { 770/* 771 * Does it begin with "a/$our-prefix" and such? Then this is 772 * very likely to apply to our directory. 773 */ 774if(!strncmp(name, prefix, prefix_length)) 775 val =count_slashes(prefix); 776else{ 777 cp++; 778if(!strncmp(cp, prefix, prefix_length)) 779 val =count_slashes(prefix) +1; 780} 781} 782free(name); 783return val; 784} 785 786/* 787 * Does the ---/+++ line has the POSIX timestamp after the last HT? 788 * GNU diff puts epoch there to signal a creation/deletion event. Is 789 * this such a timestamp? 790 */ 791static inthas_epoch_timestamp(const char*nameline) 792{ 793/* 794 * We are only interested in epoch timestamp; any non-zero 795 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 796 * For the same reason, the date must be either 1969-12-31 or 797 * 1970-01-01, and the seconds part must be "00". 798 */ 799const char stamp_regexp[] = 800"^(1969-12-31|1970-01-01)" 801" " 802"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 803" " 804"([-+][0-2][0-9]:?[0-5][0-9])\n"; 805const char*timestamp = NULL, *cp, *colon; 806static regex_t *stamp; 807 regmatch_t m[10]; 808int zoneoffset; 809int hourminute; 810int status; 811 812for(cp = nameline; *cp !='\n'; cp++) { 813if(*cp =='\t') 814 timestamp = cp +1; 815} 816if(!timestamp) 817return0; 818if(!stamp) { 819 stamp =xmalloc(sizeof(*stamp)); 820if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 821warning(_("Cannot prepare timestamp regexp%s"), 822 stamp_regexp); 823return0; 824} 825} 826 827 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 828if(status) { 829if(status != REG_NOMATCH) 830warning(_("regexec returned%dfor input:%s"), 831 status, timestamp); 832return0; 833} 834 835 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 836if(*colon ==':') 837 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 838else 839 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 840if(timestamp[m[3].rm_so] =='-') 841 zoneoffset = -zoneoffset; 842 843/* 844 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 845 * (west of GMT) or 1970-01-01 (east of GMT) 846 */ 847if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 848(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 849return0; 850 851 hourminute = (strtol(timestamp +11, NULL,10) *60+ 852strtol(timestamp +14, NULL,10) - 853 zoneoffset); 854 855return((zoneoffset <0&& hourminute ==1440) || 856(0<= zoneoffset && !hourminute)); 857} 858 859/* 860 * Get the name etc info from the ---/+++ lines of a traditional patch header 861 * 862 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 863 * files, we can happily check the index for a match, but for creating a 864 * new file we should try to match whatever "patch" does. I have no idea. 865 */ 866static voidparse_traditional_patch(const char*first,const char*second,struct patch *patch) 867{ 868char*name; 869 870 first +=4;/* skip "--- " */ 871 second +=4;/* skip "+++ " */ 872if(!p_value_known) { 873int p, q; 874 p =guess_p_value(first); 875 q =guess_p_value(second); 876if(p <0) p = q; 877if(0<= p && p == q) { 878 p_value = p; 879 p_value_known =1; 880} 881} 882if(is_dev_null(first)) { 883 patch->is_new =1; 884 patch->is_delete =0; 885 name =find_name_traditional(second, NULL, p_value); 886 patch->new_name = name; 887}else if(is_dev_null(second)) { 888 patch->is_new =0; 889 patch->is_delete =1; 890 name =find_name_traditional(first, NULL, p_value); 891 patch->old_name = name; 892}else{ 893char*first_name; 894 first_name =find_name_traditional(first, NULL, p_value); 895 name =find_name_traditional(second, first_name, p_value); 896free(first_name); 897if(has_epoch_timestamp(first)) { 898 patch->is_new =1; 899 patch->is_delete =0; 900 patch->new_name = name; 901}else if(has_epoch_timestamp(second)) { 902 patch->is_new =0; 903 patch->is_delete =1; 904 patch->old_name = name; 905}else{ 906 patch->old_name = name; 907 patch->new_name =xstrdup_or_null(name); 908} 909} 910if(!name) 911die(_("unable to find filename in patch at line%d"), linenr); 912} 913 914static intgitdiff_hdrend(const char*line,struct patch *patch) 915{ 916return-1; 917} 918 919/* 920 * We're anal about diff header consistency, to make 921 * sure that we don't end up having strange ambiguous 922 * patches floating around. 923 * 924 * As a result, gitdiff_{old|new}name() will check 925 * their names against any previous information, just 926 * to make sure.. 927 */ 928#define DIFF_OLD_NAME 0 929#define DIFF_NEW_NAME 1 930 931static char*gitdiff_verify_name(const char*line,int isnull,char*orig_name,int side) 932{ 933if(!orig_name && !isnull) 934returnfind_name(line, NULL, p_value, TERM_TAB); 935 936if(orig_name) { 937int len; 938const char*name; 939char*another; 940 name = orig_name; 941 len =strlen(name); 942if(isnull) 943die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), name, linenr); 944 another =find_name(line, NULL, p_value, TERM_TAB); 945if(!another ||memcmp(another, name, len +1)) 946die((side == DIFF_NEW_NAME) ? 947_("git apply: bad git-diff - inconsistent new filename on line%d") : 948_("git apply: bad git-diff - inconsistent old filename on line%d"), linenr); 949free(another); 950return orig_name; 951} 952else{ 953/* expect "/dev/null" */ 954if(memcmp("/dev/null", line,9) || line[9] !='\n') 955die(_("git apply: bad git-diff - expected /dev/null on line%d"), linenr); 956return NULL; 957} 958} 959 960static intgitdiff_oldname(const char*line,struct patch *patch) 961{ 962char*orig = patch->old_name; 963 patch->old_name =gitdiff_verify_name(line, patch->is_new, patch->old_name, 964 DIFF_OLD_NAME); 965if(orig != patch->old_name) 966free(orig); 967return0; 968} 969 970static intgitdiff_newname(const char*line,struct patch *patch) 971{ 972char*orig = patch->new_name; 973 patch->new_name =gitdiff_verify_name(line, patch->is_delete, patch->new_name, 974 DIFF_NEW_NAME); 975if(orig != patch->new_name) 976free(orig); 977return0; 978} 979 980static intgitdiff_oldmode(const char*line,struct patch *patch) 981{ 982 patch->old_mode =strtoul(line, NULL,8); 983return0; 984} 985 986static intgitdiff_newmode(const char*line,struct patch *patch) 987{ 988 patch->new_mode =strtoul(line, NULL,8); 989return0; 990} 991 992static intgitdiff_delete(const char*line,struct patch *patch) 993{ 994 patch->is_delete =1; 995free(patch->old_name); 996 patch->old_name =xstrdup_or_null(patch->def_name); 997returngitdiff_oldmode(line, patch); 998} 9991000static intgitdiff_newfile(const char*line,struct patch *patch)1001{1002 patch->is_new =1;1003free(patch->new_name);1004 patch->new_name =xstrdup_or_null(patch->def_name);1005returngitdiff_newmode(line, patch);1006}10071008static intgitdiff_copysrc(const char*line,struct patch *patch)1009{1010 patch->is_copy =1;1011free(patch->old_name);1012 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0);1013return0;1014}10151016static intgitdiff_copydst(const char*line,struct patch *patch)1017{1018 patch->is_copy =1;1019free(patch->new_name);1020 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0);1021return0;1022}10231024static intgitdiff_renamesrc(const char*line,struct patch *patch)1025{1026 patch->is_rename =1;1027free(patch->old_name);1028 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0);1029return0;1030}10311032static intgitdiff_renamedst(const char*line,struct patch *patch)1033{1034 patch->is_rename =1;1035free(patch->new_name);1036 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0);1037return0;1038}10391040static intgitdiff_similarity(const char*line,struct patch *patch)1041{1042unsigned long val =strtoul(line, NULL,10);1043if(val <=100)1044 patch->score = val;1045return0;1046}10471048static intgitdiff_dissimilarity(const char*line,struct patch *patch)1049{1050unsigned long val =strtoul(line, NULL,10);1051if(val <=100)1052 patch->score = val;1053return0;1054}10551056static intgitdiff_index(const char*line,struct patch *patch)1057{1058/*1059 * index line is N hexadecimal, "..", N hexadecimal,1060 * and optional space with octal mode.1061 */1062const char*ptr, *eol;1063int len;10641065 ptr =strchr(line,'.');1066if(!ptr || ptr[1] !='.'||40< ptr - line)1067return0;1068 len = ptr - line;1069memcpy(patch->old_sha1_prefix, line, len);1070 patch->old_sha1_prefix[len] =0;10711072 line = ptr +2;1073 ptr =strchr(line,' ');1074 eol =strchrnul(line,'\n');10751076if(!ptr || eol < ptr)1077 ptr = eol;1078 len = ptr - line;10791080if(40< len)1081return0;1082memcpy(patch->new_sha1_prefix, line, len);1083 patch->new_sha1_prefix[len] =0;1084if(*ptr ==' ')1085 patch->old_mode =strtoul(ptr+1, NULL,8);1086return0;1087}10881089/*1090 * This is normal for a diff that doesn't change anything: we'll fall through1091 * into the next diff. Tell the parser to break out.1092 */1093static intgitdiff_unrecognized(const char*line,struct patch *patch)1094{1095return-1;1096}10971098/*1099 * Skip p_value leading components from "line"; as we do not accept1100 * absolute paths, return NULL in that case.1101 */1102static const char*skip_tree_prefix(const char*line,int llen)1103{1104int nslash;1105int i;11061107if(!p_value)1108return(llen && line[0] =='/') ? NULL : line;11091110 nslash = p_value;1111for(i =0; i < llen; i++) {1112int ch = line[i];1113if(ch =='/'&& --nslash <=0)1114return(i ==0) ? NULL : &line[i +1];1115}1116return NULL;1117}11181119/*1120 * This is to extract the same name that appears on "diff --git"1121 * line. We do not find and return anything if it is a rename1122 * patch, and it is OK because we will find the name elsewhere.1123 * We need to reliably find name only when it is mode-change only,1124 * creation or deletion of an empty file. In any of these cases,1125 * both sides are the same name under a/ and b/ respectively.1126 */1127static char*git_header_name(const char*line,int llen)1128{1129const char*name;1130const char*second = NULL;1131size_t len, line_len;11321133 line +=strlen("diff --git ");1134 llen -=strlen("diff --git ");11351136if(*line =='"') {1137const char*cp;1138struct strbuf first = STRBUF_INIT;1139struct strbuf sp = STRBUF_INIT;11401141if(unquote_c_style(&first, line, &second))1142goto free_and_fail1;11431144/* strip the a/b prefix including trailing slash */1145 cp =skip_tree_prefix(first.buf, first.len);1146if(!cp)1147goto free_and_fail1;1148strbuf_remove(&first,0, cp - first.buf);11491150/*1151 * second points at one past closing dq of name.1152 * find the second name.1153 */1154while((second < line + llen) &&isspace(*second))1155 second++;11561157if(line + llen <= second)1158goto free_and_fail1;1159if(*second =='"') {1160if(unquote_c_style(&sp, second, NULL))1161goto free_and_fail1;1162 cp =skip_tree_prefix(sp.buf, sp.len);1163if(!cp)1164goto free_and_fail1;1165/* They must match, otherwise ignore */1166if(strcmp(cp, first.buf))1167goto free_and_fail1;1168strbuf_release(&sp);1169returnstrbuf_detach(&first, NULL);1170}11711172/* unquoted second */1173 cp =skip_tree_prefix(second, line + llen - second);1174if(!cp)1175goto free_and_fail1;1176if(line + llen - cp != first.len ||1177memcmp(first.buf, cp, first.len))1178goto free_and_fail1;1179returnstrbuf_detach(&first, NULL);11801181 free_and_fail1:1182strbuf_release(&first);1183strbuf_release(&sp);1184return NULL;1185}11861187/* unquoted first name */1188 name =skip_tree_prefix(line, llen);1189if(!name)1190return NULL;11911192/*1193 * since the first name is unquoted, a dq if exists must be1194 * the beginning of the second name.1195 */1196for(second = name; second < line + llen; second++) {1197if(*second =='"') {1198struct strbuf sp = STRBUF_INIT;1199const char*np;12001201if(unquote_c_style(&sp, second, NULL))1202goto free_and_fail2;12031204 np =skip_tree_prefix(sp.buf, sp.len);1205if(!np)1206goto free_and_fail2;12071208 len = sp.buf + sp.len - np;1209if(len < second - name &&1210!strncmp(np, name, len) &&1211isspace(name[len])) {1212/* Good */1213strbuf_remove(&sp,0, np - sp.buf);1214returnstrbuf_detach(&sp, NULL);1215}12161217 free_and_fail2:1218strbuf_release(&sp);1219return NULL;1220}1221}12221223/*1224 * Accept a name only if it shows up twice, exactly the same1225 * form.1226 */1227 second =strchr(name,'\n');1228if(!second)1229return NULL;1230 line_len = second - name;1231for(len =0; ; len++) {1232switch(name[len]) {1233default:1234continue;1235case'\n':1236return NULL;1237case'\t':case' ':1238/*1239 * Is this the separator between the preimage1240 * and the postimage pathname? Again, we are1241 * only interested in the case where there is1242 * no rename, as this is only to set def_name1243 * and a rename patch has the names elsewhere1244 * in an unambiguous form.1245 */1246if(!name[len +1])1247return NULL;/* no postimage name */1248 second =skip_tree_prefix(name + len +1,1249 line_len - (len +1));1250if(!second)1251return NULL;1252/*1253 * Does len bytes starting at "name" and "second"1254 * (that are separated by one HT or SP we just1255 * found) exactly match?1256 */1257if(second[len] =='\n'&& !strncmp(name, second, len))1258returnxmemdupz(name, len);1259}1260}1261}12621263/* Verify that we recognize the lines following a git header */1264static intparse_git_header(const char*line,int len,unsigned int size,struct patch *patch)1265{1266unsigned long offset;12671268/* A git diff has explicit new/delete information, so we don't guess */1269 patch->is_new =0;1270 patch->is_delete =0;12711272/*1273 * Some things may not have the old name in the1274 * rest of the headers anywhere (pure mode changes,1275 * or removing or adding empty files), so we get1276 * the default name from the header.1277 */1278 patch->def_name =git_header_name(line, len);1279if(patch->def_name && root) {1280char*s =xstrfmt("%s%s", root, patch->def_name);1281free(patch->def_name);1282 patch->def_name = s;1283}12841285 line += len;1286 size -= len;1287 linenr++;1288for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) {1289static const struct opentry {1290const char*str;1291int(*fn)(const char*,struct patch *);1292} optable[] = {1293{"@@ -", gitdiff_hdrend },1294{"--- ", gitdiff_oldname },1295{"+++ ", gitdiff_newname },1296{"old mode ", gitdiff_oldmode },1297{"new mode ", gitdiff_newmode },1298{"deleted file mode ", gitdiff_delete },1299{"new file mode ", gitdiff_newfile },1300{"copy from ", gitdiff_copysrc },1301{"copy to ", gitdiff_copydst },1302{"rename old ", gitdiff_renamesrc },1303{"rename new ", gitdiff_renamedst },1304{"rename from ", gitdiff_renamesrc },1305{"rename to ", gitdiff_renamedst },1306{"similarity index ", gitdiff_similarity },1307{"dissimilarity index ", gitdiff_dissimilarity },1308{"index ", gitdiff_index },1309{"", gitdiff_unrecognized },1310};1311int i;13121313 len =linelen(line, size);1314if(!len || line[len-1] !='\n')1315break;1316for(i =0; i <ARRAY_SIZE(optable); i++) {1317const struct opentry *p = optable + i;1318int oplen =strlen(p->str);1319if(len < oplen ||memcmp(p->str, line, oplen))1320continue;1321if(p->fn(line + oplen, patch) <0)1322return offset;1323break;1324}1325}13261327return offset;1328}13291330static intparse_num(const char*line,unsigned long*p)1331{1332char*ptr;13331334if(!isdigit(*line))1335return0;1336*p =strtoul(line, &ptr,10);1337return ptr - line;1338}13391340static intparse_range(const char*line,int len,int offset,const char*expect,1341unsigned long*p1,unsigned long*p2)1342{1343int digits, ex;13441345if(offset <0|| offset >= len)1346return-1;1347 line += offset;1348 len -= offset;13491350 digits =parse_num(line, p1);1351if(!digits)1352return-1;13531354 offset += digits;1355 line += digits;1356 len -= digits;13571358*p2 =1;1359if(*line ==',') {1360 digits =parse_num(line+1, p2);1361if(!digits)1362return-1;13631364 offset += digits+1;1365 line += digits+1;1366 len -= digits+1;1367}13681369 ex =strlen(expect);1370if(ex > len)1371return-1;1372if(memcmp(line, expect, ex))1373return-1;13741375return offset + ex;1376}13771378static voidrecount_diff(const char*line,int size,struct fragment *fragment)1379{1380int oldlines =0, newlines =0, ret =0;13811382if(size <1) {1383warning("recount: ignore empty hunk");1384return;1385}13861387for(;;) {1388int len =linelen(line, size);1389 size -= len;1390 line += len;13911392if(size <1)1393break;13941395switch(*line) {1396case' ':case'\n':1397 newlines++;1398/* fall through */1399case'-':1400 oldlines++;1401continue;1402case'+':1403 newlines++;1404continue;1405case'\\':1406continue;1407case'@':1408 ret = size <3|| !starts_with(line,"@@ ");1409break;1410case'd':1411 ret = size <5|| !starts_with(line,"diff ");1412break;1413default:1414 ret = -1;1415break;1416}1417if(ret) {1418warning(_("recount: unexpected line: %.*s"),1419(int)linelen(line, size), line);1420return;1421}1422break;1423}1424 fragment->oldlines = oldlines;1425 fragment->newlines = newlines;1426}14271428/*1429 * Parse a unified diff fragment header of the1430 * form "@@ -a,b +c,d @@"1431 */1432static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1433{1434int offset;14351436if(!len || line[len-1] !='\n')1437return-1;14381439/* Figure out the number of lines in a fragment */1440 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1441 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14421443return offset;1444}14451446static intfind_header(const char*line,unsigned long size,int*hdrsize,struct patch *patch)1447{1448unsigned long offset, len;14491450 patch->is_toplevel_relative =0;1451 patch->is_rename = patch->is_copy =0;1452 patch->is_new = patch->is_delete = -1;1453 patch->old_mode = patch->new_mode =0;1454 patch->old_name = patch->new_name = NULL;1455for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) {1456unsigned long nextlen;14571458 len =linelen(line, size);1459if(!len)1460break;14611462/* Testing this early allows us to take a few shortcuts.. */1463if(len <6)1464continue;14651466/*1467 * Make sure we don't find any unconnected patch fragments.1468 * That's a sign that we didn't find a header, and that a1469 * patch has become corrupted/broken up.1470 */1471if(!memcmp("@@ -", line,4)) {1472struct fragment dummy;1473if(parse_fragment_header(line, len, &dummy) <0)1474continue;1475die(_("patch fragment without header at line%d: %.*s"),1476 linenr, (int)len-1, line);1477}14781479if(size < len +6)1480break;14811482/*1483 * Git patch? It might not have a real patch, just a rename1484 * or mode change, so we handle that specially1485 */1486if(!memcmp("diff --git ", line,11)) {1487int git_hdr_len =parse_git_header(line, len, size, patch);1488if(git_hdr_len <= len)1489continue;1490if(!patch->old_name && !patch->new_name) {1491if(!patch->def_name)1492die(Q_("git diff header lacks filename information when removing "1493"%dleading pathname component (line%d)",1494"git diff header lacks filename information when removing "1495"%dleading pathname components (line%d)",1496 p_value),1497 p_value, linenr);1498 patch->old_name =xstrdup(patch->def_name);1499 patch->new_name =xstrdup(patch->def_name);1500}1501if(!patch->is_delete && !patch->new_name)1502die("git diff header lacks filename information "1503"(line%d)", linenr);1504 patch->is_toplevel_relative =1;1505*hdrsize = git_hdr_len;1506return offset;1507}15081509/* --- followed by +++ ? */1510if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1511continue;15121513/*1514 * We only accept unified patches, so we want it to1515 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1516 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1517 */1518 nextlen =linelen(line + len, size - len);1519if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1520continue;15211522/* Ok, we'll consider it a patch */1523parse_traditional_patch(line, line+len, patch);1524*hdrsize = len + nextlen;1525 linenr +=2;1526return offset;1527}1528return-1;1529}15301531static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1532{1533char*err;15341535if(!result)1536return;15371538 whitespace_error++;1539if(squelch_whitespace_errors &&1540 squelch_whitespace_errors < whitespace_error)1541return;15421543 err =whitespace_error_string(result);1544fprintf(stderr,"%s:%d:%s.\n%.*s\n",1545 patch_input_file, linenr, err, len, line);1546free(err);1547}15481549static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1550{1551unsigned result =ws_check(line +1, len -1, ws_rule);15521553record_ws_error(result, line +1, len -2, linenr);1554}15551556/*1557 * Parse a unified diff. Note that this really needs to parse each1558 * fragment separately, since the only way to know the difference1559 * between a "---" that is part of a patch, and a "---" that starts1560 * the next patch is to look at the line counts..1561 */1562static intparse_fragment(const char*line,unsigned long size,1563struct patch *patch,struct fragment *fragment)1564{1565int added, deleted;1566int len =linelen(line, size), offset;1567unsigned long oldlines, newlines;1568unsigned long leading, trailing;15691570 offset =parse_fragment_header(line, len, fragment);1571if(offset <0)1572return-1;1573if(offset >0&& patch->recount)1574recount_diff(line + offset, size - offset, fragment);1575 oldlines = fragment->oldlines;1576 newlines = fragment->newlines;1577 leading =0;1578 trailing =0;15791580/* Parse the thing.. */1581 line += len;1582 size -= len;1583 linenr++;1584 added = deleted =0;1585for(offset = len;15860< size;1587 offset += len, size -= len, line += len, linenr++) {1588if(!oldlines && !newlines)1589break;1590 len =linelen(line, size);1591if(!len || line[len-1] !='\n')1592return-1;1593switch(*line) {1594default:1595return-1;1596case'\n':/* newer GNU diff, an empty context line */1597case' ':1598 oldlines--;1599 newlines--;1600if(!deleted && !added)1601 leading++;1602 trailing++;1603break;1604case'-':1605if(apply_in_reverse &&1606 ws_error_action != nowarn_ws_error)1607check_whitespace(line, len, patch->ws_rule);1608 deleted++;1609 oldlines--;1610 trailing =0;1611break;1612case'+':1613if(!apply_in_reverse &&1614 ws_error_action != nowarn_ws_error)1615check_whitespace(line, len, patch->ws_rule);1616 added++;1617 newlines--;1618 trailing =0;1619break;16201621/*1622 * We allow "\ No newline at end of file". Depending1623 * on locale settings when the patch was produced we1624 * don't know what this line looks like. The only1625 * thing we do know is that it begins with "\ ".1626 * Checking for 12 is just for sanity check -- any1627 * l10n of "\ No newline..." is at least that long.1628 */1629case'\\':1630if(len <12||memcmp(line,"\\",2))1631return-1;1632break;1633}1634}1635if(oldlines || newlines)1636return-1;1637 fragment->leading = leading;1638 fragment->trailing = trailing;16391640/*1641 * If a fragment ends with an incomplete line, we failed to include1642 * it in the above loop because we hit oldlines == newlines == 01643 * before seeing it.1644 */1645if(12< size && !memcmp(line,"\\",2))1646 offset +=linelen(line, size);16471648 patch->lines_added += added;1649 patch->lines_deleted += deleted;16501651if(0< patch->is_new && oldlines)1652returnerror(_("new file depends on old contents"));1653if(0< patch->is_delete && newlines)1654returnerror(_("deleted file still has contents"));1655return offset;1656}16571658/*1659 * We have seen "diff --git a/... b/..." header (or a traditional patch1660 * header). Read hunks that belong to this patch into fragments and hang1661 * them to the given patch structure.1662 *1663 * The (fragment->patch, fragment->size) pair points into the memory given1664 * by the caller, not a copy, when we return.1665 */1666static intparse_single_patch(const char*line,unsigned long size,struct patch *patch)1667{1668unsigned long offset =0;1669unsigned long oldlines =0, newlines =0, context =0;1670struct fragment **fragp = &patch->fragments;16711672while(size >4&& !memcmp(line,"@@ -",4)) {1673struct fragment *fragment;1674int len;16751676 fragment =xcalloc(1,sizeof(*fragment));1677 fragment->linenr = linenr;1678 len =parse_fragment(line, size, patch, fragment);1679if(len <=0)1680die(_("corrupt patch at line%d"), linenr);1681 fragment->patch = line;1682 fragment->size = len;1683 oldlines += fragment->oldlines;1684 newlines += fragment->newlines;1685 context += fragment->leading + fragment->trailing;16861687*fragp = fragment;1688 fragp = &fragment->next;16891690 offset += len;1691 line += len;1692 size -= len;1693}16941695/*1696 * If something was removed (i.e. we have old-lines) it cannot1697 * be creation, and if something was added it cannot be1698 * deletion. However, the reverse is not true; --unified=01699 * patches that only add are not necessarily creation even1700 * though they do not have any old lines, and ones that only1701 * delete are not necessarily deletion.1702 *1703 * Unfortunately, a real creation/deletion patch do _not_ have1704 * any context line by definition, so we cannot safely tell it1705 * apart with --unified=0 insanity. At least if the patch has1706 * more than one hunk it is not creation or deletion.1707 */1708if(patch->is_new <0&&1709(oldlines || (patch->fragments && patch->fragments->next)))1710 patch->is_new =0;1711if(patch->is_delete <0&&1712(newlines || (patch->fragments && patch->fragments->next)))1713 patch->is_delete =0;17141715if(0< patch->is_new && oldlines)1716die(_("new file%sdepends on old contents"), patch->new_name);1717if(0< patch->is_delete && newlines)1718die(_("deleted file%sstill has contents"), patch->old_name);1719if(!patch->is_delete && !newlines && context)1720fprintf_ln(stderr,1721_("** warning: "1722"file%sbecomes empty but is not deleted"),1723 patch->new_name);17241725return offset;1726}17271728staticinlineintmetadata_changes(struct patch *patch)1729{1730return patch->is_rename >0||1731 patch->is_copy >0||1732 patch->is_new >0||1733 patch->is_delete ||1734(patch->old_mode && patch->new_mode &&1735 patch->old_mode != patch->new_mode);1736}17371738static char*inflate_it(const void*data,unsigned long size,1739unsigned long inflated_size)1740{1741 git_zstream stream;1742void*out;1743int st;17441745memset(&stream,0,sizeof(stream));17461747 stream.next_in = (unsigned char*)data;1748 stream.avail_in = size;1749 stream.next_out = out =xmalloc(inflated_size);1750 stream.avail_out = inflated_size;1751git_inflate_init(&stream);1752 st =git_inflate(&stream, Z_FINISH);1753git_inflate_end(&stream);1754if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1755free(out);1756return NULL;1757}1758return out;1759}17601761/*1762 * Read a binary hunk and return a new fragment; fragment->patch1763 * points at an allocated memory that the caller must free, so1764 * it is marked as "->free_patch = 1".1765 */1766static struct fragment *parse_binary_hunk(char**buf_p,1767unsigned long*sz_p,1768int*status_p,1769int*used_p)1770{1771/*1772 * Expect a line that begins with binary patch method ("literal"1773 * or "delta"), followed by the length of data before deflating.1774 * a sequence of 'length-byte' followed by base-85 encoded data1775 * should follow, terminated by a newline.1776 *1777 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1778 * and we would limit the patch line to 66 characters,1779 * so one line can fit up to 13 groups that would decode1780 * to 52 bytes max. The length byte 'A'-'Z' corresponds1781 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1782 */1783int llen, used;1784unsigned long size = *sz_p;1785char*buffer = *buf_p;1786int patch_method;1787unsigned long origlen;1788char*data = NULL;1789int hunk_size =0;1790struct fragment *frag;17911792 llen =linelen(buffer, size);1793 used = llen;17941795*status_p =0;17961797if(starts_with(buffer,"delta ")) {1798 patch_method = BINARY_DELTA_DEFLATED;1799 origlen =strtoul(buffer +6, NULL,10);1800}1801else if(starts_with(buffer,"literal ")) {1802 patch_method = BINARY_LITERAL_DEFLATED;1803 origlen =strtoul(buffer +8, NULL,10);1804}1805else1806return NULL;18071808 linenr++;1809 buffer += llen;1810while(1) {1811int byte_length, max_byte_length, newsize;1812 llen =linelen(buffer, size);1813 used += llen;1814 linenr++;1815if(llen ==1) {1816/* consume the blank line */1817 buffer++;1818 size--;1819break;1820}1821/*1822 * Minimum line is "A00000\n" which is 7-byte long,1823 * and the line length must be multiple of 5 plus 2.1824 */1825if((llen <7) || (llen-2) %5)1826goto corrupt;1827 max_byte_length = (llen -2) /5*4;1828 byte_length = *buffer;1829if('A'<= byte_length && byte_length <='Z')1830 byte_length = byte_length -'A'+1;1831else if('a'<= byte_length && byte_length <='z')1832 byte_length = byte_length -'a'+27;1833else1834goto corrupt;1835/* if the input length was not multiple of 4, we would1836 * have filler at the end but the filler should never1837 * exceed 3 bytes1838 */1839if(max_byte_length < byte_length ||1840 byte_length <= max_byte_length -4)1841goto corrupt;1842 newsize = hunk_size + byte_length;1843 data =xrealloc(data, newsize);1844if(decode_85(data + hunk_size, buffer +1, byte_length))1845goto corrupt;1846 hunk_size = newsize;1847 buffer += llen;1848 size -= llen;1849}18501851 frag =xcalloc(1,sizeof(*frag));1852 frag->patch =inflate_it(data, hunk_size, origlen);1853 frag->free_patch =1;1854if(!frag->patch)1855goto corrupt;1856free(data);1857 frag->size = origlen;1858*buf_p = buffer;1859*sz_p = size;1860*used_p = used;1861 frag->binary_patch_method = patch_method;1862return frag;18631864 corrupt:1865free(data);1866*status_p = -1;1867error(_("corrupt binary patch at line%d: %.*s"),1868 linenr-1, llen-1, buffer);1869return NULL;1870}18711872static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1873{1874/*1875 * We have read "GIT binary patch\n"; what follows is a line1876 * that says the patch method (currently, either "literal" or1877 * "delta") and the length of data before deflating; a1878 * sequence of 'length-byte' followed by base-85 encoded data1879 * follows.1880 *1881 * When a binary patch is reversible, there is another binary1882 * hunk in the same format, starting with patch method (either1883 * "literal" or "delta") with the length of data, and a sequence1884 * of length-byte + base-85 encoded data, terminated with another1885 * empty line. This data, when applied to the postimage, produces1886 * the preimage.1887 */1888struct fragment *forward;1889struct fragment *reverse;1890int status;1891int used, used_1;18921893 forward =parse_binary_hunk(&buffer, &size, &status, &used);1894if(!forward && !status)1895/* there has to be one hunk (forward hunk) */1896returnerror(_("unrecognized binary patch at line%d"), linenr-1);1897if(status)1898/* otherwise we already gave an error message */1899return status;19001901 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1902if(reverse)1903 used += used_1;1904else if(status) {1905/*1906 * Not having reverse hunk is not an error, but having1907 * a corrupt reverse hunk is.1908 */1909free((void*) forward->patch);1910free(forward);1911return status;1912}1913 forward->next = reverse;1914 patch->fragments = forward;1915 patch->is_binary =1;1916return used;1917}19181919static voidprefix_one(char**name)1920{1921char*old_name = *name;1922if(!old_name)1923return;1924*name =xstrdup(prefix_filename(prefix, prefix_length, *name));1925free(old_name);1926}19271928static voidprefix_patch(struct patch *p)1929{1930if(!prefix || p->is_toplevel_relative)1931return;1932prefix_one(&p->new_name);1933prefix_one(&p->old_name);1934}19351936/*1937 * include/exclude1938 */19391940static struct string_list limit_by_name;1941static int has_include;1942static voidadd_name_limit(const char*name,int exclude)1943{1944struct string_list_item *it;19451946 it =string_list_append(&limit_by_name, name);1947 it->util = exclude ? NULL : (void*)1;1948}19491950static intuse_patch(struct patch *p)1951{1952const char*pathname = p->new_name ? p->new_name : p->old_name;1953int i;19541955/* Paths outside are not touched regardless of "--include" */1956if(0< prefix_length) {1957int pathlen =strlen(pathname);1958if(pathlen <= prefix_length ||1959memcmp(prefix, pathname, prefix_length))1960return0;1961}19621963/* See if it matches any of exclude/include rule */1964for(i =0; i < limit_by_name.nr; i++) {1965struct string_list_item *it = &limit_by_name.items[i];1966if(!wildmatch(it->string, pathname,0, NULL))1967return(it->util != NULL);1968}19691970/*1971 * If we had any include, a path that does not match any rule is1972 * not used. Otherwise, we saw bunch of exclude rules (or none)1973 * and such a path is used.1974 */1975return!has_include;1976}197719781979/*1980 * Read the patch text in "buffer" that extends for "size" bytes; stop1981 * reading after seeing a single patch (i.e. changes to a single file).1982 * Create fragments (i.e. patch hunks) and hang them to the given patch.1983 * Return the number of bytes consumed, so that the caller can call us1984 * again for the next patch.1985 */1986static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1987{1988int hdrsize, patchsize;1989int offset =find_header(buffer, size, &hdrsize, patch);19901991if(offset <0)1992return offset;19931994prefix_patch(patch);19951996if(!use_patch(patch))1997 patch->ws_rule =0;1998else1999 patch->ws_rule =whitespace_rule(patch->new_name2000? patch->new_name2001: patch->old_name);20022003 patchsize =parse_single_patch(buffer + offset + hdrsize,2004 size - offset - hdrsize, patch);20052006if(!patchsize) {2007static const char git_binary[] ="GIT binary patch\n";2008int hd = hdrsize + offset;2009unsigned long llen =linelen(buffer + hd, size - hd);20102011if(llen ==sizeof(git_binary) -1&&2012!memcmp(git_binary, buffer + hd, llen)) {2013int used;2014 linenr++;2015 used =parse_binary(buffer + hd + llen,2016 size - hd - llen, patch);2017if(used)2018 patchsize = used + llen;2019else2020 patchsize =0;2021}2022else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2023static const char*binhdr[] = {2024"Binary files ",2025"Files ",2026 NULL,2027};2028int i;2029for(i =0; binhdr[i]; i++) {2030int len =strlen(binhdr[i]);2031if(len < size - hd &&2032!memcmp(binhdr[i], buffer + hd, len)) {2033 linenr++;2034 patch->is_binary =1;2035 patchsize = llen;2036break;2037}2038}2039}20402041/* Empty patch cannot be applied if it is a text patch2042 * without metadata change. A binary patch appears2043 * empty to us here.2044 */2045if((apply || check) &&2046(!patch->is_binary && !metadata_changes(patch)))2047die(_("patch with only garbage at line%d"), linenr);2048}20492050return offset + hdrsize + patchsize;2051}20522053#define swap(a,b) myswap((a),(b),sizeof(a))20542055#define myswap(a, b, size) do { \2056 unsigned char mytmp[size]; \2057 memcpy(mytmp, &a, size); \2058 memcpy(&a, &b, size); \2059 memcpy(&b, mytmp, size); \2060} while (0)20612062static voidreverse_patches(struct patch *p)2063{2064for(; p; p = p->next) {2065struct fragment *frag = p->fragments;20662067swap(p->new_name, p->old_name);2068swap(p->new_mode, p->old_mode);2069swap(p->is_new, p->is_delete);2070swap(p->lines_added, p->lines_deleted);2071swap(p->old_sha1_prefix, p->new_sha1_prefix);20722073for(; frag; frag = frag->next) {2074swap(frag->newpos, frag->oldpos);2075swap(frag->newlines, frag->oldlines);2076}2077}2078}20792080static const char pluses[] =2081"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2082static const char minuses[]=2083"----------------------------------------------------------------------";20842085static voidshow_stats(struct patch *patch)2086{2087struct strbuf qname = STRBUF_INIT;2088char*cp = patch->new_name ? patch->new_name : patch->old_name;2089int max, add, del;20902091quote_c_style(cp, &qname, NULL,0);20922093/*2094 * "scale" the filename2095 */2096 max = max_len;2097if(max >50)2098 max =50;20992100if(qname.len > max) {2101 cp =strchr(qname.buf + qname.len +3- max,'/');2102if(!cp)2103 cp = qname.buf + qname.len +3- max;2104strbuf_splice(&qname,0, cp - qname.buf,"...",3);2105}21062107if(patch->is_binary) {2108printf(" %-*s | Bin\n", max, qname.buf);2109strbuf_release(&qname);2110return;2111}21122113printf(" %-*s |", max, qname.buf);2114strbuf_release(&qname);21152116/*2117 * scale the add/delete2118 */2119 max = max + max_change >70?70- max : max_change;2120 add = patch->lines_added;2121 del = patch->lines_deleted;21222123if(max_change >0) {2124int total = ((add + del) * max + max_change /2) / max_change;2125 add = (add * max + max_change /2) / max_change;2126 del = total - add;2127}2128printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2129 add, pluses, del, minuses);2130}21312132static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2133{2134switch(st->st_mode & S_IFMT) {2135case S_IFLNK:2136if(strbuf_readlink(buf, path, st->st_size) <0)2137returnerror(_("unable to read symlink%s"), path);2138return0;2139case S_IFREG:2140if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2141returnerror(_("unable to open or read%s"), path);2142convert_to_git(path, buf->buf, buf->len, buf,0);2143return0;2144default:2145return-1;2146}2147}21482149/*2150 * Update the preimage, and the common lines in postimage,2151 * from buffer buf of length len. If postlen is 0 the postimage2152 * is updated in place, otherwise it's updated on a new buffer2153 * of length postlen2154 */21552156static voidupdate_pre_post_images(struct image *preimage,2157struct image *postimage,2158char*buf,2159size_t len,size_t postlen)2160{2161int i, ctx, reduced;2162char*new, *old, *fixed;2163struct image fixed_preimage;21642165/*2166 * Update the preimage with whitespace fixes. Note that we2167 * are not losing preimage->buf -- apply_one_fragment() will2168 * free "oldlines".2169 */2170prepare_image(&fixed_preimage, buf, len,1);2171assert(postlen2172? fixed_preimage.nr == preimage->nr2173: fixed_preimage.nr <= preimage->nr);2174for(i =0; i < fixed_preimage.nr; i++)2175 fixed_preimage.line[i].flag = preimage->line[i].flag;2176free(preimage->line_allocated);2177*preimage = fixed_preimage;21782179/*2180 * Adjust the common context lines in postimage. This can be2181 * done in-place when we are shrinking it with whitespace2182 * fixing, but needs a new buffer when ignoring whitespace or2183 * expanding leading tabs to spaces.2184 *2185 * We trust the caller to tell us if the update can be done2186 * in place (postlen==0) or not.2187 */2188 old = postimage->buf;2189if(postlen)2190new= postimage->buf =xmalloc(postlen);2191else2192new= old;2193 fixed = preimage->buf;21942195for(i = reduced = ctx =0; i < postimage->nr; i++) {2196size_t len = postimage->line[i].len;2197if(!(postimage->line[i].flag & LINE_COMMON)) {2198/* an added line -- no counterparts in preimage */2199memmove(new, old, len);2200 old += len;2201new+= len;2202continue;2203}22042205/* a common context -- skip it in the original postimage */2206 old += len;22072208/* and find the corresponding one in the fixed preimage */2209while(ctx < preimage->nr &&2210!(preimage->line[ctx].flag & LINE_COMMON)) {2211 fixed += preimage->line[ctx].len;2212 ctx++;2213}22142215/*2216 * preimage is expected to run out, if the caller2217 * fixed addition of trailing blank lines.2218 */2219if(preimage->nr <= ctx) {2220 reduced++;2221continue;2222}22232224/* and copy it in, while fixing the line length */2225 len = preimage->line[ctx].len;2226memcpy(new, fixed, len);2227new+= len;2228 fixed += len;2229 postimage->line[i].len = len;2230 ctx++;2231}22322233/* Fix the length of the whole thing */2234 postimage->len =new- postimage->buf;2235 postimage->nr -= reduced;2236}22372238static intmatch_fragment(struct image *img,2239struct image *preimage,2240struct image *postimage,2241unsigned longtry,2242int try_lno,2243unsigned ws_rule,2244int match_beginning,int match_end)2245{2246int i;2247char*fixed_buf, *buf, *orig, *target;2248struct strbuf fixed;2249size_t fixed_len, postlen;2250int preimage_limit;22512252if(preimage->nr + try_lno <= img->nr) {2253/*2254 * The hunk falls within the boundaries of img.2255 */2256 preimage_limit = preimage->nr;2257if(match_end && (preimage->nr + try_lno != img->nr))2258return0;2259}else if(ws_error_action == correct_ws_error &&2260(ws_rule & WS_BLANK_AT_EOF)) {2261/*2262 * This hunk extends beyond the end of img, and we are2263 * removing blank lines at the end of the file. This2264 * many lines from the beginning of the preimage must2265 * match with img, and the remainder of the preimage2266 * must be blank.2267 */2268 preimage_limit = img->nr - try_lno;2269}else{2270/*2271 * The hunk extends beyond the end of the img and2272 * we are not removing blanks at the end, so we2273 * should reject the hunk at this position.2274 */2275return0;2276}22772278if(match_beginning && try_lno)2279return0;22802281/* Quick hash check */2282for(i =0; i < preimage_limit; i++)2283if((img->line[try_lno + i].flag & LINE_PATCHED) ||2284(preimage->line[i].hash != img->line[try_lno + i].hash))2285return0;22862287if(preimage_limit == preimage->nr) {2288/*2289 * Do we have an exact match? If we were told to match2290 * at the end, size must be exactly at try+fragsize,2291 * otherwise try+fragsize must be still within the preimage,2292 * and either case, the old piece should match the preimage2293 * exactly.2294 */2295if((match_end2296? (try+ preimage->len == img->len)2297: (try+ preimage->len <= img->len)) &&2298!memcmp(img->buf +try, preimage->buf, preimage->len))2299return1;2300}else{2301/*2302 * The preimage extends beyond the end of img, so2303 * there cannot be an exact match.2304 *2305 * There must be one non-blank context line that match2306 * a line before the end of img.2307 */2308char*buf_end;23092310 buf = preimage->buf;2311 buf_end = buf;2312for(i =0; i < preimage_limit; i++)2313 buf_end += preimage->line[i].len;23142315for( ; buf < buf_end; buf++)2316if(!isspace(*buf))2317break;2318if(buf == buf_end)2319return0;2320}23212322/*2323 * No exact match. If we are ignoring whitespace, run a line-by-line2324 * fuzzy matching. We collect all the line length information because2325 * we need it to adjust whitespace if we match.2326 */2327if(ws_ignore_action == ignore_ws_change) {2328size_t imgoff =0;2329size_t preoff =0;2330size_t postlen = postimage->len;2331size_t extra_chars;2332char*preimage_eof;2333char*preimage_end;2334for(i =0; i < preimage_limit; i++) {2335size_t prelen = preimage->line[i].len;2336size_t imglen = img->line[try_lno+i].len;23372338if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2339 preimage->buf + preoff, prelen))2340return0;2341if(preimage->line[i].flag & LINE_COMMON)2342 postlen += imglen - prelen;2343 imgoff += imglen;2344 preoff += prelen;2345}23462347/*2348 * Ok, the preimage matches with whitespace fuzz.2349 *2350 * imgoff now holds the true length of the target that2351 * matches the preimage before the end of the file.2352 *2353 * Count the number of characters in the preimage that fall2354 * beyond the end of the file and make sure that all of them2355 * are whitespace characters. (This can only happen if2356 * we are removing blank lines at the end of the file.)2357 */2358 buf = preimage_eof = preimage->buf + preoff;2359for( ; i < preimage->nr; i++)2360 preoff += preimage->line[i].len;2361 preimage_end = preimage->buf + preoff;2362for( ; buf < preimage_end; buf++)2363if(!isspace(*buf))2364return0;23652366/*2367 * Update the preimage and the common postimage context2368 * lines to use the same whitespace as the target.2369 * If whitespace is missing in the target (i.e.2370 * if the preimage extends beyond the end of the file),2371 * use the whitespace from the preimage.2372 */2373 extra_chars = preimage_end - preimage_eof;2374strbuf_init(&fixed, imgoff + extra_chars);2375strbuf_add(&fixed, img->buf +try, imgoff);2376strbuf_add(&fixed, preimage_eof, extra_chars);2377 fixed_buf =strbuf_detach(&fixed, &fixed_len);2378update_pre_post_images(preimage, postimage,2379 fixed_buf, fixed_len, postlen);2380return1;2381}23822383if(ws_error_action != correct_ws_error)2384return0;23852386/*2387 * The hunk does not apply byte-by-byte, but the hash says2388 * it might with whitespace fuzz. We haven't been asked to2389 * ignore whitespace, we were asked to correct whitespace2390 * errors, so let's try matching after whitespace correction.2391 *2392 * The preimage may extend beyond the end of the file,2393 * but in this loop we will only handle the part of the2394 * preimage that falls within the file.2395 */2396strbuf_init(&fixed, preimage->len +1);2397 orig = preimage->buf;2398 target = img->buf +try;2399 postlen =0;2400for(i =0; i < preimage_limit; i++) {2401size_t oldlen = preimage->line[i].len;2402size_t tgtlen = img->line[try_lno + i].len;2403size_t fixstart = fixed.len;2404struct strbuf tgtfix;2405int match;24062407/* Try fixing the line in the preimage */2408ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24092410/* Try fixing the line in the target */2411strbuf_init(&tgtfix, tgtlen);2412ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);24132414/*2415 * If they match, either the preimage was based on2416 * a version before our tree fixed whitespace breakage,2417 * or we are lacking a whitespace-fix patch the tree2418 * the preimage was based on already had (i.e. target2419 * has whitespace breakage, the preimage doesn't).2420 * In either case, we are fixing the whitespace breakages2421 * so we might as well take the fix together with their2422 * real change.2423 */2424 match = (tgtfix.len == fixed.len - fixstart &&2425!memcmp(tgtfix.buf, fixed.buf + fixstart,2426 fixed.len - fixstart));2427 postlen += tgtfix.len;24282429strbuf_release(&tgtfix);2430if(!match)2431goto unmatch_exit;24322433 orig += oldlen;2434 target += tgtlen;2435}243624372438/*2439 * Now handle the lines in the preimage that falls beyond the2440 * end of the file (if any). They will only match if they are2441 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2442 * false).2443 */2444for( ; i < preimage->nr; i++) {2445size_t fixstart = fixed.len;/* start of the fixed preimage */2446size_t oldlen = preimage->line[i].len;2447int j;24482449/* Try fixing the line in the preimage */2450ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24512452for(j = fixstart; j < fixed.len; j++)2453if(!isspace(fixed.buf[j]))2454goto unmatch_exit;24552456 orig += oldlen;2457}24582459/*2460 * Yes, the preimage is based on an older version that still2461 * has whitespace breakages unfixed, and fixing them makes the2462 * hunk match. Update the context lines in the postimage.2463 */2464 fixed_buf =strbuf_detach(&fixed, &fixed_len);2465if(postlen < postimage->len)2466 postlen =0;2467update_pre_post_images(preimage, postimage,2468 fixed_buf, fixed_len, postlen);2469return1;24702471 unmatch_exit:2472strbuf_release(&fixed);2473return0;2474}24752476static intfind_pos(struct image *img,2477struct image *preimage,2478struct image *postimage,2479int line,2480unsigned ws_rule,2481int match_beginning,int match_end)2482{2483int i;2484unsigned long backwards, forwards,try;2485int backwards_lno, forwards_lno, try_lno;24862487/*2488 * If match_beginning or match_end is specified, there is no2489 * point starting from a wrong line that will never match and2490 * wander around and wait for a match at the specified end.2491 */2492if(match_beginning)2493 line =0;2494else if(match_end)2495 line = img->nr - preimage->nr;24962497/*2498 * Because the comparison is unsigned, the following test2499 * will also take care of a negative line number that can2500 * result when match_end and preimage is larger than the target.2501 */2502if((size_t) line > img->nr)2503 line = img->nr;25042505try=0;2506for(i =0; i < line; i++)2507try+= img->line[i].len;25082509/*2510 * There's probably some smart way to do this, but I'll leave2511 * that to the smart and beautiful people. I'm simple and stupid.2512 */2513 backwards =try;2514 backwards_lno = line;2515 forwards =try;2516 forwards_lno = line;2517 try_lno = line;25182519for(i =0; ; i++) {2520if(match_fragment(img, preimage, postimage,2521try, try_lno, ws_rule,2522 match_beginning, match_end))2523return try_lno;25242525 again:2526if(backwards_lno ==0&& forwards_lno == img->nr)2527break;25282529if(i &1) {2530if(backwards_lno ==0) {2531 i++;2532goto again;2533}2534 backwards_lno--;2535 backwards -= img->line[backwards_lno].len;2536try= backwards;2537 try_lno = backwards_lno;2538}else{2539if(forwards_lno == img->nr) {2540 i++;2541goto again;2542}2543 forwards += img->line[forwards_lno].len;2544 forwards_lno++;2545try= forwards;2546 try_lno = forwards_lno;2547}25482549}2550return-1;2551}25522553static voidremove_first_line(struct image *img)2554{2555 img->buf += img->line[0].len;2556 img->len -= img->line[0].len;2557 img->line++;2558 img->nr--;2559}25602561static voidremove_last_line(struct image *img)2562{2563 img->len -= img->line[--img->nr].len;2564}25652566/*2567 * The change from "preimage" and "postimage" has been found to2568 * apply at applied_pos (counts in line numbers) in "img".2569 * Update "img" to remove "preimage" and replace it with "postimage".2570 */2571static voidupdate_image(struct image *img,2572int applied_pos,2573struct image *preimage,2574struct image *postimage)2575{2576/*2577 * remove the copy of preimage at offset in img2578 * and replace it with postimage2579 */2580int i, nr;2581size_t remove_count, insert_count, applied_at =0;2582char*result;2583int preimage_limit;25842585/*2586 * If we are removing blank lines at the end of img,2587 * the preimage may extend beyond the end.2588 * If that is the case, we must be careful only to2589 * remove the part of the preimage that falls within2590 * the boundaries of img. Initialize preimage_limit2591 * to the number of lines in the preimage that falls2592 * within the boundaries.2593 */2594 preimage_limit = preimage->nr;2595if(preimage_limit > img->nr - applied_pos)2596 preimage_limit = img->nr - applied_pos;25972598for(i =0; i < applied_pos; i++)2599 applied_at += img->line[i].len;26002601 remove_count =0;2602for(i =0; i < preimage_limit; i++)2603 remove_count += img->line[applied_pos + i].len;2604 insert_count = postimage->len;26052606/* Adjust the contents */2607 result =xmalloc(img->len + insert_count - remove_count +1);2608memcpy(result, img->buf, applied_at);2609memcpy(result + applied_at, postimage->buf, postimage->len);2610memcpy(result + applied_at + postimage->len,2611 img->buf + (applied_at + remove_count),2612 img->len - (applied_at + remove_count));2613free(img->buf);2614 img->buf = result;2615 img->len += insert_count - remove_count;2616 result[img->len] ='\0';26172618/* Adjust the line table */2619 nr = img->nr + postimage->nr - preimage_limit;2620if(preimage_limit < postimage->nr) {2621/*2622 * NOTE: this knows that we never call remove_first_line()2623 * on anything other than pre/post image.2624 */2625REALLOC_ARRAY(img->line, nr);2626 img->line_allocated = img->line;2627}2628if(preimage_limit != postimage->nr)2629memmove(img->line + applied_pos + postimage->nr,2630 img->line + applied_pos + preimage_limit,2631(img->nr - (applied_pos + preimage_limit)) *2632sizeof(*img->line));2633memcpy(img->line + applied_pos,2634 postimage->line,2635 postimage->nr *sizeof(*img->line));2636if(!allow_overlap)2637for(i =0; i < postimage->nr; i++)2638 img->line[applied_pos + i].flag |= LINE_PATCHED;2639 img->nr = nr;2640}26412642/*2643 * Use the patch-hunk text in "frag" to prepare two images (preimage and2644 * postimage) for the hunk. Find lines that match "preimage" in "img" and2645 * replace the part of "img" with "postimage" text.2646 */2647static intapply_one_fragment(struct image *img,struct fragment *frag,2648int inaccurate_eof,unsigned ws_rule,2649int nth_fragment)2650{2651int match_beginning, match_end;2652const char*patch = frag->patch;2653int size = frag->size;2654char*old, *oldlines;2655struct strbuf newlines;2656int new_blank_lines_at_end =0;2657int found_new_blank_lines_at_end =0;2658int hunk_linenr = frag->linenr;2659unsigned long leading, trailing;2660int pos, applied_pos;2661struct image preimage;2662struct image postimage;26632664memset(&preimage,0,sizeof(preimage));2665memset(&postimage,0,sizeof(postimage));2666 oldlines =xmalloc(size);2667strbuf_init(&newlines, size);26682669 old = oldlines;2670while(size >0) {2671char first;2672int len =linelen(patch, size);2673int plen;2674int added_blank_line =0;2675int is_blank_context =0;2676size_t start;26772678if(!len)2679break;26802681/*2682 * "plen" is how much of the line we should use for2683 * the actual patch data. Normally we just remove the2684 * first character on the line, but if the line is2685 * followed by "\ No newline", then we also remove the2686 * last one (which is the newline, of course).2687 */2688 plen = len -1;2689if(len < size && patch[len] =='\\')2690 plen--;2691 first = *patch;2692if(apply_in_reverse) {2693if(first =='-')2694 first ='+';2695else if(first =='+')2696 first ='-';2697}26982699switch(first) {2700case'\n':2701/* Newer GNU diff, empty context line */2702if(plen <0)2703/* ... followed by '\No newline'; nothing */2704break;2705*old++ ='\n';2706strbuf_addch(&newlines,'\n');2707add_line_info(&preimage,"\n",1, LINE_COMMON);2708add_line_info(&postimage,"\n",1, LINE_COMMON);2709 is_blank_context =1;2710break;2711case' ':2712if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2713ws_blank_line(patch +1, plen, ws_rule))2714 is_blank_context =1;2715case'-':2716memcpy(old, patch +1, plen);2717add_line_info(&preimage, old, plen,2718(first ==' '? LINE_COMMON :0));2719 old += plen;2720if(first =='-')2721break;2722/* Fall-through for ' ' */2723case'+':2724/* --no-add does not add new lines */2725if(first =='+'&& no_add)2726break;27272728 start = newlines.len;2729if(first !='+'||2730!whitespace_error ||2731 ws_error_action != correct_ws_error) {2732strbuf_add(&newlines, patch +1, plen);2733}2734else{2735ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2736}2737add_line_info(&postimage, newlines.buf + start, newlines.len - start,2738(first =='+'?0: LINE_COMMON));2739if(first =='+'&&2740(ws_rule & WS_BLANK_AT_EOF) &&2741ws_blank_line(patch +1, plen, ws_rule))2742 added_blank_line =1;2743break;2744case'@':case'\\':2745/* Ignore it, we already handled it */2746break;2747default:2748if(apply_verbosely)2749error(_("invalid start of line: '%c'"), first);2750return-1;2751}2752if(added_blank_line) {2753if(!new_blank_lines_at_end)2754 found_new_blank_lines_at_end = hunk_linenr;2755 new_blank_lines_at_end++;2756}2757else if(is_blank_context)2758;2759else2760 new_blank_lines_at_end =0;2761 patch += len;2762 size -= len;2763 hunk_linenr++;2764}2765if(inaccurate_eof &&2766 old > oldlines && old[-1] =='\n'&&2767 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2768 old--;2769strbuf_setlen(&newlines, newlines.len -1);2770}27712772 leading = frag->leading;2773 trailing = frag->trailing;27742775/*2776 * A hunk to change lines at the beginning would begin with2777 * @@ -1,L +N,M @@2778 * but we need to be careful. -U0 that inserts before the second2779 * line also has this pattern.2780 *2781 * And a hunk to add to an empty file would begin with2782 * @@ -0,0 +N,M @@2783 *2784 * In other words, a hunk that is (frag->oldpos <= 1) with or2785 * without leading context must match at the beginning.2786 */2787 match_beginning = (!frag->oldpos ||2788(frag->oldpos ==1&& !unidiff_zero));27892790/*2791 * A hunk without trailing lines must match at the end.2792 * However, we simply cannot tell if a hunk must match end2793 * from the lack of trailing lines if the patch was generated2794 * with unidiff without any context.2795 */2796 match_end = !unidiff_zero && !trailing;27972798 pos = frag->newpos ? (frag->newpos -1) :0;2799 preimage.buf = oldlines;2800 preimage.len = old - oldlines;2801 postimage.buf = newlines.buf;2802 postimage.len = newlines.len;2803 preimage.line = preimage.line_allocated;2804 postimage.line = postimage.line_allocated;28052806for(;;) {28072808 applied_pos =find_pos(img, &preimage, &postimage, pos,2809 ws_rule, match_beginning, match_end);28102811if(applied_pos >=0)2812break;28132814/* Am I at my context limits? */2815if((leading <= p_context) && (trailing <= p_context))2816break;2817if(match_beginning || match_end) {2818 match_beginning = match_end =0;2819continue;2820}28212822/*2823 * Reduce the number of context lines; reduce both2824 * leading and trailing if they are equal otherwise2825 * just reduce the larger context.2826 */2827if(leading >= trailing) {2828remove_first_line(&preimage);2829remove_first_line(&postimage);2830 pos--;2831 leading--;2832}2833if(trailing > leading) {2834remove_last_line(&preimage);2835remove_last_line(&postimage);2836 trailing--;2837}2838}28392840if(applied_pos >=0) {2841if(new_blank_lines_at_end &&2842 preimage.nr + applied_pos >= img->nr &&2843(ws_rule & WS_BLANK_AT_EOF) &&2844 ws_error_action != nowarn_ws_error) {2845record_ws_error(WS_BLANK_AT_EOF,"+",1,2846 found_new_blank_lines_at_end);2847if(ws_error_action == correct_ws_error) {2848while(new_blank_lines_at_end--)2849remove_last_line(&postimage);2850}2851/*2852 * We would want to prevent write_out_results()2853 * from taking place in apply_patch() that follows2854 * the callchain led us here, which is:2855 * apply_patch->check_patch_list->check_patch->2856 * apply_data->apply_fragments->apply_one_fragment2857 */2858if(ws_error_action == die_on_ws_error)2859 apply =0;2860}28612862if(apply_verbosely && applied_pos != pos) {2863int offset = applied_pos - pos;2864if(apply_in_reverse)2865 offset =0- offset;2866fprintf_ln(stderr,2867Q_("Hunk #%dsucceeded at%d(offset%dline).",2868"Hunk #%dsucceeded at%d(offset%dlines).",2869 offset),2870 nth_fragment, applied_pos +1, offset);2871}28722873/*2874 * Warn if it was necessary to reduce the number2875 * of context lines.2876 */2877if((leading != frag->leading) ||2878(trailing != frag->trailing))2879fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2880" to apply fragment at%d"),2881 leading, trailing, applied_pos+1);2882update_image(img, applied_pos, &preimage, &postimage);2883}else{2884if(apply_verbosely)2885error(_("while searching for:\n%.*s"),2886(int)(old - oldlines), oldlines);2887}28882889free(oldlines);2890strbuf_release(&newlines);2891free(preimage.line_allocated);2892free(postimage.line_allocated);28932894return(applied_pos <0);2895}28962897static intapply_binary_fragment(struct image *img,struct patch *patch)2898{2899struct fragment *fragment = patch->fragments;2900unsigned long len;2901void*dst;29022903if(!fragment)2904returnerror(_("missing binary patch data for '%s'"),2905 patch->new_name ?2906 patch->new_name :2907 patch->old_name);29082909/* Binary patch is irreversible without the optional second hunk */2910if(apply_in_reverse) {2911if(!fragment->next)2912returnerror("cannot reverse-apply a binary patch "2913"without the reverse hunk to '%s'",2914 patch->new_name2915? patch->new_name : patch->old_name);2916 fragment = fragment->next;2917}2918switch(fragment->binary_patch_method) {2919case BINARY_DELTA_DEFLATED:2920 dst =patch_delta(img->buf, img->len, fragment->patch,2921 fragment->size, &len);2922if(!dst)2923return-1;2924clear_image(img);2925 img->buf = dst;2926 img->len = len;2927return0;2928case BINARY_LITERAL_DEFLATED:2929clear_image(img);2930 img->len = fragment->size;2931 img->buf =xmemdupz(fragment->patch, img->len);2932return0;2933}2934return-1;2935}29362937/*2938 * Replace "img" with the result of applying the binary patch.2939 * The binary patch data itself in patch->fragment is still kept2940 * but the preimage prepared by the caller in "img" is freed here2941 * or in the helper function apply_binary_fragment() this calls.2942 */2943static intapply_binary(struct image *img,struct patch *patch)2944{2945const char*name = patch->old_name ? patch->old_name : patch->new_name;2946unsigned char sha1[20];29472948/*2949 * For safety, we require patch index line to contain2950 * full 40-byte textual SHA1 for old and new, at least for now.2951 */2952if(strlen(patch->old_sha1_prefix) !=40||2953strlen(patch->new_sha1_prefix) !=40||2954get_sha1_hex(patch->old_sha1_prefix, sha1) ||2955get_sha1_hex(patch->new_sha1_prefix, sha1))2956returnerror("cannot apply binary patch to '%s' "2957"without full index line", name);29582959if(patch->old_name) {2960/*2961 * See if the old one matches what the patch2962 * applies to.2963 */2964hash_sha1_file(img->buf, img->len, blob_type, sha1);2965if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2966returnerror("the patch applies to '%s' (%s), "2967"which does not match the "2968"current contents.",2969 name,sha1_to_hex(sha1));2970}2971else{2972/* Otherwise, the old one must be empty. */2973if(img->len)2974returnerror("the patch applies to an empty "2975"'%s' but it is not empty", name);2976}29772978get_sha1_hex(patch->new_sha1_prefix, sha1);2979if(is_null_sha1(sha1)) {2980clear_image(img);2981return0;/* deletion patch */2982}29832984if(has_sha1_file(sha1)) {2985/* We already have the postimage */2986enum object_type type;2987unsigned long size;2988char*result;29892990 result =read_sha1_file(sha1, &type, &size);2991if(!result)2992returnerror("the necessary postimage%sfor "2993"'%s' cannot be read",2994 patch->new_sha1_prefix, name);2995clear_image(img);2996 img->buf = result;2997 img->len = size;2998}else{2999/*3000 * We have verified buf matches the preimage;3001 * apply the patch data to it, which is stored3002 * in the patch->fragments->{patch,size}.3003 */3004if(apply_binary_fragment(img, patch))3005returnerror(_("binary patch does not apply to '%s'"),3006 name);30073008/* verify that the result matches */3009hash_sha1_file(img->buf, img->len, blob_type, sha1);3010if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3011returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3012 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3013}30143015return0;3016}30173018static intapply_fragments(struct image *img,struct patch *patch)3019{3020struct fragment *frag = patch->fragments;3021const char*name = patch->old_name ? patch->old_name : patch->new_name;3022unsigned ws_rule = patch->ws_rule;3023unsigned inaccurate_eof = patch->inaccurate_eof;3024int nth =0;30253026if(patch->is_binary)3027returnapply_binary(img, patch);30283029while(frag) {3030 nth++;3031if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {3032error(_("patch failed:%s:%ld"), name, frag->oldpos);3033if(!apply_with_reject)3034return-1;3035 frag->rejected =1;3036}3037 frag = frag->next;3038}3039return0;3040}30413042static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3043{3044if(S_ISGITLINK(mode)) {3045strbuf_grow(buf,100);3046strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3047}else{3048enum object_type type;3049unsigned long sz;3050char*result;30513052 result =read_sha1_file(sha1, &type, &sz);3053if(!result)3054return-1;3055/* XXX read_sha1_file NUL-terminates */3056strbuf_attach(buf, result, sz, sz +1);3057}3058return0;3059}30603061static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3062{3063if(!ce)3064return0;3065returnread_blob_object(buf, ce->sha1, ce->ce_mode);3066}30673068static struct patch *in_fn_table(const char*name)3069{3070struct string_list_item *item;30713072if(name == NULL)3073return NULL;30743075 item =string_list_lookup(&fn_table, name);3076if(item != NULL)3077return(struct patch *)item->util;30783079return NULL;3080}30813082/*3083 * item->util in the filename table records the status of the path.3084 * Usually it points at a patch (whose result records the contents3085 * of it after applying it), but it could be PATH_WAS_DELETED for a3086 * path that a previously applied patch has already removed, or3087 * PATH_TO_BE_DELETED for a path that a later patch would remove.3088 *3089 * The latter is needed to deal with a case where two paths A and B3090 * are swapped by first renaming A to B and then renaming B to A;3091 * moving A to B should not be prevented due to presence of B as we3092 * will remove it in a later patch.3093 */3094#define PATH_TO_BE_DELETED ((struct patch *) -2)3095#define PATH_WAS_DELETED ((struct patch *) -1)30963097static intto_be_deleted(struct patch *patch)3098{3099return patch == PATH_TO_BE_DELETED;3100}31013102static intwas_deleted(struct patch *patch)3103{3104return patch == PATH_WAS_DELETED;3105}31063107static voidadd_to_fn_table(struct patch *patch)3108{3109struct string_list_item *item;31103111/*3112 * Always add new_name unless patch is a deletion3113 * This should cover the cases for normal diffs,3114 * file creations and copies3115 */3116if(patch->new_name != NULL) {3117 item =string_list_insert(&fn_table, patch->new_name);3118 item->util = patch;3119}31203121/*3122 * store a failure on rename/deletion cases because3123 * later chunks shouldn't patch old names3124 */3125if((patch->new_name == NULL) || (patch->is_rename)) {3126 item =string_list_insert(&fn_table, patch->old_name);3127 item->util = PATH_WAS_DELETED;3128}3129}31303131static voidprepare_fn_table(struct patch *patch)3132{3133/*3134 * store information about incoming file deletion3135 */3136while(patch) {3137if((patch->new_name == NULL) || (patch->is_rename)) {3138struct string_list_item *item;3139 item =string_list_insert(&fn_table, patch->old_name);3140 item->util = PATH_TO_BE_DELETED;3141}3142 patch = patch->next;3143}3144}31453146static intcheckout_target(struct index_state *istate,3147struct cache_entry *ce,struct stat *st)3148{3149struct checkout costate;31503151memset(&costate,0,sizeof(costate));3152 costate.base_dir ="";3153 costate.refresh_cache =1;3154 costate.istate = istate;3155if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3156returnerror(_("cannot checkout%s"), ce->name);3157return0;3158}31593160static struct patch *previous_patch(struct patch *patch,int*gone)3161{3162struct patch *previous;31633164*gone =0;3165if(patch->is_copy || patch->is_rename)3166return NULL;/* "git" patches do not depend on the order */31673168 previous =in_fn_table(patch->old_name);3169if(!previous)3170return NULL;31713172if(to_be_deleted(previous))3173return NULL;/* the deletion hasn't happened yet */31743175if(was_deleted(previous))3176*gone =1;31773178return previous;3179}31803181static intverify_index_match(const struct cache_entry *ce,struct stat *st)3182{3183if(S_ISGITLINK(ce->ce_mode)) {3184if(!S_ISDIR(st->st_mode))3185return-1;3186return0;3187}3188returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3189}31903191#define SUBMODULE_PATCH_WITHOUT_INDEX 131923193static intload_patch_target(struct strbuf *buf,3194const struct cache_entry *ce,3195struct stat *st,3196const char*name,3197unsigned expected_mode)3198{3199if(cached) {3200if(read_file_or_gitlink(ce, buf))3201returnerror(_("read of%sfailed"), name);3202}else if(name) {3203if(S_ISGITLINK(expected_mode)) {3204if(ce)3205returnread_file_or_gitlink(ce, buf);3206else3207return SUBMODULE_PATCH_WITHOUT_INDEX;3208}else{3209if(read_old_data(st, name, buf))3210returnerror(_("read of%sfailed"), name);3211}3212}3213return0;3214}32153216/*3217 * We are about to apply "patch"; populate the "image" with the3218 * current version we have, from the working tree or from the index,3219 * depending on the situation e.g. --cached/--index. If we are3220 * applying a non-git patch that incrementally updates the tree,3221 * we read from the result of a previous diff.3222 */3223static intload_preimage(struct image *image,3224struct patch *patch,struct stat *st,3225const struct cache_entry *ce)3226{3227struct strbuf buf = STRBUF_INIT;3228size_t len;3229char*img;3230struct patch *previous;3231int status;32323233 previous =previous_patch(patch, &status);3234if(status)3235returnerror(_("path%shas been renamed/deleted"),3236 patch->old_name);3237if(previous) {3238/* We have a patched copy in memory; use that. */3239strbuf_add(&buf, previous->result, previous->resultsize);3240}else{3241 status =load_patch_target(&buf, ce, st,3242 patch->old_name, patch->old_mode);3243if(status <0)3244return status;3245else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3246/*3247 * There is no way to apply subproject3248 * patch without looking at the index.3249 * NEEDSWORK: shouldn't this be flagged3250 * as an error???3251 */3252free_fragment_list(patch->fragments);3253 patch->fragments = NULL;3254}else if(status) {3255returnerror(_("read of%sfailed"), patch->old_name);3256}3257}32583259 img =strbuf_detach(&buf, &len);3260prepare_image(image, img, len, !patch->is_binary);3261return0;3262}32633264static intthree_way_merge(struct image *image,3265char*path,3266const unsigned char*base,3267const unsigned char*ours,3268const unsigned char*theirs)3269{3270 mmfile_t base_file, our_file, their_file;3271 mmbuffer_t result = { NULL };3272int status;32733274read_mmblob(&base_file, base);3275read_mmblob(&our_file, ours);3276read_mmblob(&their_file, theirs);3277 status =ll_merge(&result, path,3278&base_file,"base",3279&our_file,"ours",3280&their_file,"theirs", NULL);3281free(base_file.ptr);3282free(our_file.ptr);3283free(their_file.ptr);3284if(status <0|| !result.ptr) {3285free(result.ptr);3286return-1;3287}3288clear_image(image);3289 image->buf = result.ptr;3290 image->len = result.size;32913292return status;3293}32943295/*3296 * When directly falling back to add/add three-way merge, we read from3297 * the current contents of the new_name. In no cases other than that3298 * this function will be called.3299 */3300static intload_current(struct image *image,struct patch *patch)3301{3302struct strbuf buf = STRBUF_INIT;3303int status, pos;3304size_t len;3305char*img;3306struct stat st;3307struct cache_entry *ce;3308char*name = patch->new_name;3309unsigned mode = patch->new_mode;33103311if(!patch->is_new)3312die("BUG: patch to%sis not a creation", patch->old_name);33133314 pos =cache_name_pos(name,strlen(name));3315if(pos <0)3316returnerror(_("%s: does not exist in index"), name);3317 ce = active_cache[pos];3318if(lstat(name, &st)) {3319if(errno != ENOENT)3320returnerror(_("%s:%s"), name,strerror(errno));3321if(checkout_target(&the_index, ce, &st))3322return-1;3323}3324if(verify_index_match(ce, &st))3325returnerror(_("%s: does not match index"), name);33263327 status =load_patch_target(&buf, ce, &st, name, mode);3328if(status <0)3329return status;3330else if(status)3331return-1;3332 img =strbuf_detach(&buf, &len);3333prepare_image(image, img, len, !patch->is_binary);3334return0;3335}33363337static inttry_threeway(struct image *image,struct patch *patch,3338struct stat *st,const struct cache_entry *ce)3339{3340unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3341struct strbuf buf = STRBUF_INIT;3342size_t len;3343int status;3344char*img;3345struct image tmp_image;33463347/* No point falling back to 3-way merge in these cases */3348if(patch->is_delete ||3349S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3350return-1;33513352/* Preimage the patch was prepared for */3353if(patch->is_new)3354write_sha1_file("",0, blob_type, pre_sha1);3355else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3356read_blob_object(&buf, pre_sha1, patch->old_mode))3357returnerror("repository lacks the necessary blob to fall back on 3-way merge.");33583359fprintf(stderr,"Falling back to three-way merge...\n");33603361 img =strbuf_detach(&buf, &len);3362prepare_image(&tmp_image, img, len,1);3363/* Apply the patch to get the post image */3364if(apply_fragments(&tmp_image, patch) <0) {3365clear_image(&tmp_image);3366return-1;3367}3368/* post_sha1[] is theirs */3369write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3370clear_image(&tmp_image);33713372/* our_sha1[] is ours */3373if(patch->is_new) {3374if(load_current(&tmp_image, patch))3375returnerror("cannot read the current contents of '%s'",3376 patch->new_name);3377}else{3378if(load_preimage(&tmp_image, patch, st, ce))3379returnerror("cannot read the current contents of '%s'",3380 patch->old_name);3381}3382write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3383clear_image(&tmp_image);33843385/* in-core three-way merge between post and our using pre as base */3386 status =three_way_merge(image, patch->new_name,3387 pre_sha1, our_sha1, post_sha1);3388if(status <0) {3389fprintf(stderr,"Failed to fall back on three-way merge...\n");3390return status;3391}33923393if(status) {3394 patch->conflicted_threeway =1;3395if(patch->is_new)3396hashclr(patch->threeway_stage[0]);3397else3398hashcpy(patch->threeway_stage[0], pre_sha1);3399hashcpy(patch->threeway_stage[1], our_sha1);3400hashcpy(patch->threeway_stage[2], post_sha1);3401fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3402}else{3403fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3404}3405return0;3406}34073408static intapply_data(struct patch *patch,struct stat *st,const struct cache_entry *ce)3409{3410struct image image;34113412if(load_preimage(&image, patch, st, ce) <0)3413return-1;34143415if(patch->direct_to_threeway ||3416apply_fragments(&image, patch) <0) {3417/* Note: with --reject, apply_fragments() returns 0 */3418if(!threeway ||try_threeway(&image, patch, st, ce) <0)3419return-1;3420}3421 patch->result = image.buf;3422 patch->resultsize = image.len;3423add_to_fn_table(patch);3424free(image.line_allocated);34253426if(0< patch->is_delete && patch->resultsize)3427returnerror(_("removal patch leaves file contents"));34283429return0;3430}34313432/*3433 * If "patch" that we are looking at modifies or deletes what we have,3434 * we would want it not to lose any local modification we have, either3435 * in the working tree or in the index.3436 *3437 * This also decides if a non-git patch is a creation patch or a3438 * modification to an existing empty file. We do not check the state3439 * of the current tree for a creation patch in this function; the caller3440 * check_patch() separately makes sure (and errors out otherwise) that3441 * the path the patch creates does not exist in the current tree.3442 */3443static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)3444{3445const char*old_name = patch->old_name;3446struct patch *previous = NULL;3447int stat_ret =0, status;3448unsigned st_mode =0;34493450if(!old_name)3451return0;34523453assert(patch->is_new <=0);3454 previous =previous_patch(patch, &status);34553456if(status)3457returnerror(_("path%shas been renamed/deleted"), old_name);3458if(previous) {3459 st_mode = previous->new_mode;3460}else if(!cached) {3461 stat_ret =lstat(old_name, st);3462if(stat_ret && errno != ENOENT)3463returnerror(_("%s:%s"), old_name,strerror(errno));3464}34653466if(check_index && !previous) {3467int pos =cache_name_pos(old_name,strlen(old_name));3468if(pos <0) {3469if(patch->is_new <0)3470goto is_new;3471returnerror(_("%s: does not exist in index"), old_name);3472}3473*ce = active_cache[pos];3474if(stat_ret <0) {3475if(checkout_target(&the_index, *ce, st))3476return-1;3477}3478if(!cached &&verify_index_match(*ce, st))3479returnerror(_("%s: does not match index"), old_name);3480if(cached)3481 st_mode = (*ce)->ce_mode;3482}else if(stat_ret <0) {3483if(patch->is_new <0)3484goto is_new;3485returnerror(_("%s:%s"), old_name,strerror(errno));3486}34873488if(!cached && !previous)3489 st_mode =ce_mode_from_stat(*ce, st->st_mode);34903491if(patch->is_new <0)3492 patch->is_new =0;3493if(!patch->old_mode)3494 patch->old_mode = st_mode;3495if((st_mode ^ patch->old_mode) & S_IFMT)3496returnerror(_("%s: wrong type"), old_name);3497if(st_mode != patch->old_mode)3498warning(_("%shas type%o, expected%o"),3499 old_name, st_mode, patch->old_mode);3500if(!patch->new_mode && !patch->is_delete)3501 patch->new_mode = st_mode;3502return0;35033504 is_new:3505 patch->is_new =1;3506 patch->is_delete =0;3507free(patch->old_name);3508 patch->old_name = NULL;3509return0;3510}351135123513#define EXISTS_IN_INDEX 13514#define EXISTS_IN_WORKTREE 235153516static intcheck_to_create(const char*new_name,int ok_if_exists)3517{3518struct stat nst;35193520if(check_index &&3521cache_name_pos(new_name,strlen(new_name)) >=0&&3522!ok_if_exists)3523return EXISTS_IN_INDEX;3524if(cached)3525return0;35263527if(!lstat(new_name, &nst)) {3528if(S_ISDIR(nst.st_mode) || ok_if_exists)3529return0;3530/*3531 * A leading component of new_name might be a symlink3532 * that is going to be removed with this patch, but3533 * still pointing at somewhere that has the path.3534 * In such a case, path "new_name" does not exist as3535 * far as git is concerned.3536 */3537if(has_symlink_leading_path(new_name,strlen(new_name)))3538return0;35393540return EXISTS_IN_WORKTREE;3541}else if((errno != ENOENT) && (errno != ENOTDIR)) {3542returnerror("%s:%s", new_name,strerror(errno));3543}3544return0;3545}35463547/*3548 * Check and apply the patch in-core; leave the result in patch->result3549 * for the caller to write it out to the final destination.3550 */3551static intcheck_patch(struct patch *patch)3552{3553struct stat st;3554const char*old_name = patch->old_name;3555const char*new_name = patch->new_name;3556const char*name = old_name ? old_name : new_name;3557struct cache_entry *ce = NULL;3558struct patch *tpatch;3559int ok_if_exists;3560int status;35613562 patch->rejected =1;/* we will drop this after we succeed */35633564 status =check_preimage(patch, &ce, &st);3565if(status)3566return status;3567 old_name = patch->old_name;35683569/*3570 * A type-change diff is always split into a patch to delete3571 * old, immediately followed by a patch to create new (see3572 * diff.c::run_diff()); in such a case it is Ok that the entry3573 * to be deleted by the previous patch is still in the working3574 * tree and in the index.3575 *3576 * A patch to swap-rename between A and B would first rename A3577 * to B and then rename B to A. While applying the first one,3578 * the presence of B should not stop A from getting renamed to3579 * B; ask to_be_deleted() about the later rename. Removal of3580 * B and rename from A to B is handled the same way by asking3581 * was_deleted().3582 */3583if((tpatch =in_fn_table(new_name)) &&3584(was_deleted(tpatch) ||to_be_deleted(tpatch)))3585 ok_if_exists =1;3586else3587 ok_if_exists =0;35883589if(new_name &&3590((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3591int err =check_to_create(new_name, ok_if_exists);35923593if(err && threeway) {3594 patch->direct_to_threeway =1;3595}else switch(err) {3596case0:3597break;/* happy */3598case EXISTS_IN_INDEX:3599returnerror(_("%s: already exists in index"), new_name);3600break;3601case EXISTS_IN_WORKTREE:3602returnerror(_("%s: already exists in working directory"),3603 new_name);3604default:3605return err;3606}36073608if(!patch->new_mode) {3609if(0< patch->is_new)3610 patch->new_mode = S_IFREG |0644;3611else3612 patch->new_mode = patch->old_mode;3613}3614}36153616if(new_name && old_name) {3617int same = !strcmp(old_name, new_name);3618if(!patch->new_mode)3619 patch->new_mode = patch->old_mode;3620if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3621if(same)3622returnerror(_("new mode (%o) of%sdoes not "3623"match old mode (%o)"),3624 patch->new_mode, new_name,3625 patch->old_mode);3626else3627returnerror(_("new mode (%o) of%sdoes not "3628"match old mode (%o) of%s"),3629 patch->new_mode, new_name,3630 patch->old_mode, old_name);3631}3632}36333634if(apply_data(patch, &st, ce) <0)3635returnerror(_("%s: patch does not apply"), name);3636 patch->rejected =0;3637return0;3638}36393640static intcheck_patch_list(struct patch *patch)3641{3642int err =0;36433644prepare_fn_table(patch);3645while(patch) {3646if(apply_verbosely)3647say_patch_name(stderr,3648_("Checking patch%s..."), patch);3649 err |=check_patch(patch);3650 patch = patch->next;3651}3652return err;3653}36543655/* This function tries to read the sha1 from the current index */3656static intget_current_sha1(const char*path,unsigned char*sha1)3657{3658int pos;36593660if(read_cache() <0)3661return-1;3662 pos =cache_name_pos(path,strlen(path));3663if(pos <0)3664return-1;3665hashcpy(sha1, active_cache[pos]->sha1);3666return0;3667}36683669static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3670{3671/*3672 * A usable gitlink patch has only one fragment (hunk) that looks like:3673 * @@ -1 +1 @@3674 * -Subproject commit <old sha1>3675 * +Subproject commit <new sha1>3676 * or3677 * @@ -1 +0,0 @@3678 * -Subproject commit <old sha1>3679 * for a removal patch.3680 */3681struct fragment *hunk = p->fragments;3682static const char heading[] ="-Subproject commit ";3683char*preimage;36843685if(/* does the patch have only one hunk? */3686 hunk && !hunk->next &&3687/* is its preimage one line? */3688 hunk->oldpos ==1&& hunk->oldlines ==1&&3689/* does preimage begin with the heading? */3690(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3691starts_with(++preimage, heading) &&3692/* does it record full SHA-1? */3693!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3694 preimage[sizeof(heading) +40-1] =='\n'&&3695/* does the abbreviated name on the index line agree with it? */3696starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3697return0;/* it all looks fine */36983699/* we may have full object name on the index line */3700returnget_sha1_hex(p->old_sha1_prefix, sha1);3701}37023703/* Build an index that contains the just the files needed for a 3way merge */3704static voidbuild_fake_ancestor(struct patch *list,const char*filename)3705{3706struct patch *patch;3707struct index_state result = { NULL };3708static struct lock_file lock;37093710/* Once we start supporting the reverse patch, it may be3711 * worth showing the new sha1 prefix, but until then...3712 */3713for(patch = list; patch; patch = patch->next) {3714unsigned char sha1[20];3715struct cache_entry *ce;3716const char*name;37173718 name = patch->old_name ? patch->old_name : patch->new_name;3719if(0< patch->is_new)3720continue;37213722if(S_ISGITLINK(patch->old_mode)) {3723if(!preimage_sha1_in_gitlink_patch(patch, sha1))3724;/* ok, the textual part looks sane */3725else3726die("sha1 information is lacking or useless for submodule%s",3727 name);3728}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {3729;/* ok */3730}else if(!patch->lines_added && !patch->lines_deleted) {3731/* mode-only change: update the current */3732if(get_current_sha1(patch->old_name, sha1))3733die("mode change for%s, which is not "3734"in current HEAD", name);3735}else3736die("sha1 information is lacking or useless "3737"(%s).", name);37383739 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);3740if(!ce)3741die(_("make_cache_entry failed for path '%s'"), name);3742if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3743die("Could not add%sto temporary index", name);3744}37453746hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);3747if(write_locked_index(&result, &lock, COMMIT_LOCK))3748die("Could not write temporary index to%s", filename);37493750discard_index(&result);3751}37523753static voidstat_patch_list(struct patch *patch)3754{3755int files, adds, dels;37563757for(files = adds = dels =0; patch ; patch = patch->next) {3758 files++;3759 adds += patch->lines_added;3760 dels += patch->lines_deleted;3761show_stats(patch);3762}37633764print_stat_summary(stdout, files, adds, dels);3765}37663767static voidnumstat_patch_list(struct patch *patch)3768{3769for( ; patch; patch = patch->next) {3770const char*name;3771 name = patch->new_name ? patch->new_name : patch->old_name;3772if(patch->is_binary)3773printf("-\t-\t");3774else3775printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3776write_name_quoted(name, stdout, line_termination);3777}3778}37793780static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3781{3782if(mode)3783printf("%smode%06o%s\n", newdelete, mode, name);3784else3785printf("%s %s\n", newdelete, name);3786}37873788static voidshow_mode_change(struct patch *p,int show_name)3789{3790if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3791if(show_name)3792printf(" mode change%06o =>%06o%s\n",3793 p->old_mode, p->new_mode, p->new_name);3794else3795printf(" mode change%06o =>%06o\n",3796 p->old_mode, p->new_mode);3797}3798}37993800static voidshow_rename_copy(struct patch *p)3801{3802const char*renamecopy = p->is_rename ?"rename":"copy";3803const char*old, *new;38043805/* Find common prefix */3806 old = p->old_name;3807new= p->new_name;3808while(1) {3809const char*slash_old, *slash_new;3810 slash_old =strchr(old,'/');3811 slash_new =strchr(new,'/');3812if(!slash_old ||3813!slash_new ||3814 slash_old - old != slash_new -new||3815memcmp(old,new, slash_new -new))3816break;3817 old = slash_old +1;3818new= slash_new +1;3819}3820/* p->old_name thru old is the common prefix, and old and new3821 * through the end of names are renames3822 */3823if(old != p->old_name)3824printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,3825(int)(old - p->old_name), p->old_name,3826 old,new, p->score);3827else3828printf("%s %s=>%s(%d%%)\n", renamecopy,3829 p->old_name, p->new_name, p->score);3830show_mode_change(p,0);3831}38323833static voidsummary_patch_list(struct patch *patch)3834{3835struct patch *p;38363837for(p = patch; p; p = p->next) {3838if(p->is_new)3839show_file_mode_name("create", p->new_mode, p->new_name);3840else if(p->is_delete)3841show_file_mode_name("delete", p->old_mode, p->old_name);3842else{3843if(p->is_rename || p->is_copy)3844show_rename_copy(p);3845else{3846if(p->score) {3847printf(" rewrite%s(%d%%)\n",3848 p->new_name, p->score);3849show_mode_change(p,0);3850}3851else3852show_mode_change(p,1);3853}3854}3855}3856}38573858static voidpatch_stats(struct patch *patch)3859{3860int lines = patch->lines_added + patch->lines_deleted;38613862if(lines > max_change)3863 max_change = lines;3864if(patch->old_name) {3865int len =quote_c_style(patch->old_name, NULL, NULL,0);3866if(!len)3867 len =strlen(patch->old_name);3868if(len > max_len)3869 max_len = len;3870}3871if(patch->new_name) {3872int len =quote_c_style(patch->new_name, NULL, NULL,0);3873if(!len)3874 len =strlen(patch->new_name);3875if(len > max_len)3876 max_len = len;3877}3878}38793880static voidremove_file(struct patch *patch,int rmdir_empty)3881{3882if(update_index) {3883if(remove_file_from_cache(patch->old_name) <0)3884die(_("unable to remove%sfrom index"), patch->old_name);3885}3886if(!cached) {3887if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {3888remove_path(patch->old_name);3889}3890}3891}38923893static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)3894{3895struct stat st;3896struct cache_entry *ce;3897int namelen =strlen(path);3898unsigned ce_size =cache_entry_size(namelen);38993900if(!update_index)3901return;39023903 ce =xcalloc(1, ce_size);3904memcpy(ce->name, path, namelen);3905 ce->ce_mode =create_ce_mode(mode);3906 ce->ce_flags =create_ce_flags(0);3907 ce->ce_namelen = namelen;3908if(S_ISGITLINK(mode)) {3909const char*s;39103911if(!skip_prefix(buf,"Subproject commit ", &s) ||3912get_sha1_hex(s, ce->sha1))3913die(_("corrupt patch for submodule%s"), path);3914}else{3915if(!cached) {3916if(lstat(path, &st) <0)3917die_errno(_("unable to stat newly created file '%s'"),3918 path);3919fill_stat_cache_info(ce, &st);3920}3921if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)3922die(_("unable to create backing store for newly created file%s"), path);3923}3924if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3925die(_("unable to add cache entry for%s"), path);3926}39273928static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)3929{3930int fd;3931struct strbuf nbuf = STRBUF_INIT;39323933if(S_ISGITLINK(mode)) {3934struct stat st;3935if(!lstat(path, &st) &&S_ISDIR(st.st_mode))3936return0;3937returnmkdir(path,0777);3938}39393940if(has_symlinks &&S_ISLNK(mode))3941/* Although buf:size is counted string, it also is NUL3942 * terminated.3943 */3944returnsymlink(buf, path);39453946 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);3947if(fd <0)3948return-1;39493950if(convert_to_working_tree(path, buf, size, &nbuf)) {3951 size = nbuf.len;3952 buf = nbuf.buf;3953}3954write_or_die(fd, buf, size);3955strbuf_release(&nbuf);39563957if(close(fd) <0)3958die_errno(_("closing file '%s'"), path);3959return0;3960}39613962/*3963 * We optimistically assume that the directories exist,3964 * which is true 99% of the time anyway. If they don't,3965 * we create them and try again.3966 */3967static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)3968{3969if(cached)3970return;3971if(!try_create_file(path, mode, buf, size))3972return;39733974if(errno == ENOENT) {3975if(safe_create_leading_directories(path))3976return;3977if(!try_create_file(path, mode, buf, size))3978return;3979}39803981if(errno == EEXIST || errno == EACCES) {3982/* We may be trying to create a file where a directory3983 * used to be.3984 */3985struct stat st;3986if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))3987 errno = EEXIST;3988}39893990if(errno == EEXIST) {3991unsigned int nr =getpid();39923993for(;;) {3994char newpath[PATH_MAX];3995mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);3996if(!try_create_file(newpath, mode, buf, size)) {3997if(!rename(newpath, path))3998return;3999unlink_or_warn(newpath);4000break;4001}4002if(errno != EEXIST)4003break;4004++nr;4005}4006}4007die_errno(_("unable to write file '%s' mode%o"), path, mode);4008}40094010static voidadd_conflicted_stages_file(struct patch *patch)4011{4012int stage, namelen;4013unsigned ce_size, mode;4014struct cache_entry *ce;40154016if(!update_index)4017return;4018 namelen =strlen(patch->new_name);4019 ce_size =cache_entry_size(namelen);4020 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);40214022remove_file_from_cache(patch->new_name);4023for(stage =1; stage <4; stage++) {4024if(is_null_sha1(patch->threeway_stage[stage -1]))4025continue;4026 ce =xcalloc(1, ce_size);4027memcpy(ce->name, patch->new_name, namelen);4028 ce->ce_mode =create_ce_mode(mode);4029 ce->ce_flags =create_ce_flags(stage);4030 ce->ce_namelen = namelen;4031hashcpy(ce->sha1, patch->threeway_stage[stage -1]);4032if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4033die(_("unable to add cache entry for%s"), patch->new_name);4034}4035}40364037static voidcreate_file(struct patch *patch)4038{4039char*path = patch->new_name;4040unsigned mode = patch->new_mode;4041unsigned long size = patch->resultsize;4042char*buf = patch->result;40434044if(!mode)4045 mode = S_IFREG |0644;4046create_one_file(path, mode, buf, size);40474048if(patch->conflicted_threeway)4049add_conflicted_stages_file(patch);4050else4051add_index_file(path, mode, buf, size);4052}40534054/* phase zero is to remove, phase one is to create */4055static voidwrite_out_one_result(struct patch *patch,int phase)4056{4057if(patch->is_delete >0) {4058if(phase ==0)4059remove_file(patch,1);4060return;4061}4062if(patch->is_new >0|| patch->is_copy) {4063if(phase ==1)4064create_file(patch);4065return;4066}4067/*4068 * Rename or modification boils down to the same4069 * thing: remove the old, write the new4070 */4071if(phase ==0)4072remove_file(patch, patch->is_rename);4073if(phase ==1)4074create_file(patch);4075}40764077static intwrite_out_one_reject(struct patch *patch)4078{4079FILE*rej;4080char namebuf[PATH_MAX];4081struct fragment *frag;4082int cnt =0;4083struct strbuf sb = STRBUF_INIT;40844085for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4086if(!frag->rejected)4087continue;4088 cnt++;4089}40904091if(!cnt) {4092if(apply_verbosely)4093say_patch_name(stderr,4094_("Applied patch%scleanly."), patch);4095return0;4096}40974098/* This should not happen, because a removal patch that leaves4099 * contents are marked "rejected" at the patch level.4100 */4101if(!patch->new_name)4102die(_("internal error"));41034104/* Say this even without --verbose */4105strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4106"Applying patch %%swith%drejects...",4107 cnt),4108 cnt);4109say_patch_name(stderr, sb.buf, patch);4110strbuf_release(&sb);41114112 cnt =strlen(patch->new_name);4113if(ARRAY_SIZE(namebuf) <= cnt +5) {4114 cnt =ARRAY_SIZE(namebuf) -5;4115warning(_("truncating .rej filename to %.*s.rej"),4116 cnt -1, patch->new_name);4117}4118memcpy(namebuf, patch->new_name, cnt);4119memcpy(namebuf + cnt,".rej",5);41204121 rej =fopen(namebuf,"w");4122if(!rej)4123returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));41244125/* Normal git tools never deal with .rej, so do not pretend4126 * this is a git patch by saying --git or giving extended4127 * headers. While at it, maybe please "kompare" that wants4128 * the trailing TAB and some garbage at the end of line ;-).4129 */4130fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4131 patch->new_name, patch->new_name);4132for(cnt =1, frag = patch->fragments;4133 frag;4134 cnt++, frag = frag->next) {4135if(!frag->rejected) {4136fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4137continue;4138}4139fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4140fprintf(rej,"%.*s", frag->size, frag->patch);4141if(frag->patch[frag->size-1] !='\n')4142fputc('\n', rej);4143}4144fclose(rej);4145return-1;4146}41474148static intwrite_out_results(struct patch *list)4149{4150int phase;4151int errs =0;4152struct patch *l;4153struct string_list cpath = STRING_LIST_INIT_DUP;41544155for(phase =0; phase <2; phase++) {4156 l = list;4157while(l) {4158if(l->rejected)4159 errs =1;4160else{4161write_out_one_result(l, phase);4162if(phase ==1) {4163if(write_out_one_reject(l))4164 errs =1;4165if(l->conflicted_threeway) {4166string_list_append(&cpath, l->new_name);4167 errs =1;4168}4169}4170}4171 l = l->next;4172}4173}41744175if(cpath.nr) {4176struct string_list_item *item;41774178string_list_sort(&cpath);4179for_each_string_list_item(item, &cpath)4180fprintf(stderr,"U%s\n", item->string);4181string_list_clear(&cpath,0);41824183rerere(0);4184}41854186return errs;4187}41884189static struct lock_file lock_file;41904191#define INACCURATE_EOF (1<<0)4192#define RECOUNT (1<<1)41934194static intapply_patch(int fd,const char*filename,int options)4195{4196size_t offset;4197struct strbuf buf = STRBUF_INIT;/* owns the patch text */4198struct patch *list = NULL, **listp = &list;4199int skipped_patch =0;42004201 patch_input_file = filename;4202read_patch_file(&buf, fd);4203 offset =0;4204while(offset < buf.len) {4205struct patch *patch;4206int nr;42074208 patch =xcalloc(1,sizeof(*patch));4209 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4210 patch->recount = !!(options & RECOUNT);4211 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);4212if(nr <0)4213break;4214if(apply_in_reverse)4215reverse_patches(patch);4216if(use_patch(patch)) {4217patch_stats(patch);4218*listp = patch;4219 listp = &patch->next;4220}4221else{4222free_patch(patch);4223 skipped_patch++;4224}4225 offset += nr;4226}42274228if(!list && !skipped_patch)4229die(_("unrecognized input"));42304231if(whitespace_error && (ws_error_action == die_on_ws_error))4232 apply =0;42334234 update_index = check_index && apply;4235if(update_index && newfd <0)4236 newfd =hold_locked_index(&lock_file,1);42374238if(check_index) {4239if(read_cache() <0)4240die(_("unable to read index file"));4241}42424243if((check || apply) &&4244check_patch_list(list) <0&&4245!apply_with_reject)4246exit(1);42474248if(apply &&write_out_results(list)) {4249if(apply_with_reject)4250exit(1);4251/* with --3way, we still need to write the index out */4252return1;4253}42544255if(fake_ancestor)4256build_fake_ancestor(list, fake_ancestor);42574258if(diffstat)4259stat_patch_list(list);42604261if(numstat)4262numstat_patch_list(list);42634264if(summary)4265summary_patch_list(list);42664267free_patch_list(list);4268strbuf_release(&buf);4269string_list_clear(&fn_table,0);4270return0;4271}42724273static voidgit_apply_config(void)4274{4275git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4276git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4277git_config(git_default_config, NULL);4278}42794280static intoption_parse_exclude(const struct option *opt,4281const char*arg,int unset)4282{4283add_name_limit(arg,1);4284return0;4285}42864287static intoption_parse_include(const struct option *opt,4288const char*arg,int unset)4289{4290add_name_limit(arg,0);4291 has_include =1;4292return0;4293}42944295static intoption_parse_p(const struct option *opt,4296const char*arg,int unset)4297{4298 p_value =atoi(arg);4299 p_value_known =1;4300return0;4301}43024303static intoption_parse_z(const struct option *opt,4304const char*arg,int unset)4305{4306if(unset)4307 line_termination ='\n';4308else4309 line_termination =0;4310return0;4311}43124313static intoption_parse_space_change(const struct option *opt,4314const char*arg,int unset)4315{4316if(unset)4317 ws_ignore_action = ignore_ws_none;4318else4319 ws_ignore_action = ignore_ws_change;4320return0;4321}43224323static intoption_parse_whitespace(const struct option *opt,4324const char*arg,int unset)4325{4326const char**whitespace_option = opt->value;43274328*whitespace_option = arg;4329parse_whitespace_option(arg);4330return0;4331}43324333static intoption_parse_directory(const struct option *opt,4334const char*arg,int unset)4335{4336 root_len =strlen(arg);4337if(root_len && arg[root_len -1] !='/') {4338char*new_root;4339 root = new_root =xmalloc(root_len +2);4340strcpy(new_root, arg);4341strcpy(new_root + root_len++,"/");4342}else4343 root = arg;4344return0;4345}43464347intcmd_apply(int argc,const char**argv,const char*prefix_)4348{4349int i;4350int errs =0;4351int is_not_gitdir = !startup_info->have_repository;4352int force_apply =0;43534354const char*whitespace_option = NULL;43554356struct option builtin_apply_options[] = {4357{ OPTION_CALLBACK,0,"exclude", NULL,N_("path"),4358N_("don't apply changes matching the given path"),43590, option_parse_exclude },4360{ OPTION_CALLBACK,0,"include", NULL,N_("path"),4361N_("apply changes matching the given path"),43620, option_parse_include },4363{ OPTION_CALLBACK,'p', NULL, NULL,N_("num"),4364N_("remove <num> leading slashes from traditional diff paths"),43650, option_parse_p },4366OPT_BOOL(0,"no-add", &no_add,4367N_("ignore additions made by the patch")),4368OPT_BOOL(0,"stat", &diffstat,4369N_("instead of applying the patch, output diffstat for the input")),4370OPT_NOOP_NOARG(0,"allow-binary-replacement"),4371OPT_NOOP_NOARG(0,"binary"),4372OPT_BOOL(0,"numstat", &numstat,4373N_("show number of added and deleted lines in decimal notation")),4374OPT_BOOL(0,"summary", &summary,4375N_("instead of applying the patch, output a summary for the input")),4376OPT_BOOL(0,"check", &check,4377N_("instead of applying the patch, see if the patch is applicable")),4378OPT_BOOL(0,"index", &check_index,4379N_("make sure the patch is applicable to the current index")),4380OPT_BOOL(0,"cached", &cached,4381N_("apply a patch without touching the working tree")),4382OPT_BOOL(0,"apply", &force_apply,4383N_("also apply the patch (use with --stat/--summary/--check)")),4384OPT_BOOL('3',"3way", &threeway,4385N_("attempt three-way merge if a patch does not apply")),4386OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,4387N_("build a temporary index based on embedded index information")),4388{ OPTION_CALLBACK,'z', NULL, NULL, NULL,4389N_("paths are separated with NUL character"),4390 PARSE_OPT_NOARG, option_parse_z },4391OPT_INTEGER('C', NULL, &p_context,4392N_("ensure at least <n> lines of context match")),4393{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,N_("action"),4394N_("detect new or modified lines that have whitespace errors"),43950, option_parse_whitespace },4396{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,4397N_("ignore changes in whitespace when finding context"),4398 PARSE_OPT_NOARG, option_parse_space_change },4399{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,4400N_("ignore changes in whitespace when finding context"),4401 PARSE_OPT_NOARG, option_parse_space_change },4402OPT_BOOL('R',"reverse", &apply_in_reverse,4403N_("apply the patch in reverse")),4404OPT_BOOL(0,"unidiff-zero", &unidiff_zero,4405N_("don't expect at least one line of context")),4406OPT_BOOL(0,"reject", &apply_with_reject,4407N_("leave the rejected hunks in corresponding *.rej files")),4408OPT_BOOL(0,"allow-overlap", &allow_overlap,4409N_("allow overlapping hunks")),4410OPT__VERBOSE(&apply_verbosely,N_("be verbose")),4411OPT_BIT(0,"inaccurate-eof", &options,4412N_("tolerate incorrectly detected missing new-line at the end of file"),4413 INACCURATE_EOF),4414OPT_BIT(0,"recount", &options,4415N_("do not trust the line counts in the hunk headers"),4416 RECOUNT),4417{ OPTION_CALLBACK,0,"directory", NULL,N_("root"),4418N_("prepend <root> to all filenames"),44190, option_parse_directory },4420OPT_END()4421};44224423 prefix = prefix_;4424 prefix_length = prefix ?strlen(prefix) :0;4425git_apply_config();4426if(apply_default_whitespace)4427parse_whitespace_option(apply_default_whitespace);4428if(apply_default_ignorewhitespace)4429parse_ignorewhitespace_option(apply_default_ignorewhitespace);44304431 argc =parse_options(argc, argv, prefix, builtin_apply_options,4432 apply_usage,0);44334434if(apply_with_reject && threeway)4435die("--reject and --3way cannot be used together.");4436if(cached && threeway)4437die("--cached and --3way cannot be used together.");4438if(threeway) {4439if(is_not_gitdir)4440die(_("--3way outside a repository"));4441 check_index =1;4442}4443if(apply_with_reject)4444 apply = apply_verbosely =1;4445if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))4446 apply =0;4447if(check_index && is_not_gitdir)4448die(_("--index outside a repository"));4449if(cached) {4450if(is_not_gitdir)4451die(_("--cached outside a repository"));4452 check_index =1;4453}4454for(i =0; i < argc; i++) {4455const char*arg = argv[i];4456int fd;44574458if(!strcmp(arg,"-")) {4459 errs |=apply_patch(0,"<stdin>", options);4460 read_stdin =0;4461continue;4462}else if(0< prefix_length)4463 arg =prefix_filename(prefix, prefix_length, arg);44644465 fd =open(arg, O_RDONLY);4466if(fd <0)4467die_errno(_("can't open patch '%s'"), arg);4468 read_stdin =0;4469set_default_whitespace_mode(whitespace_option);4470 errs |=apply_patch(fd, arg, options);4471close(fd);4472}4473set_default_whitespace_mode(whitespace_option);4474if(read_stdin)4475 errs |=apply_patch(0,"<stdin>", options);4476if(whitespace_error) {4477if(squelch_whitespace_errors &&4478 squelch_whitespace_errors < whitespace_error) {4479int squelched =4480 whitespace_error - squelch_whitespace_errors;4481warning(Q_("squelched%dwhitespace error",4482"squelched%dwhitespace errors",4483 squelched),4484 squelched);4485}4486if(ws_error_action == die_on_ws_error)4487die(Q_("%dline adds whitespace errors.",4488"%dlines add whitespace errors.",4489 whitespace_error),4490 whitespace_error);4491if(applied_after_fixing_ws && apply)4492warning("%dline%sapplied after"4493" fixing whitespace errors.",4494 applied_after_fixing_ws,4495 applied_after_fixing_ws ==1?"":"s");4496else if(whitespace_error)4497warning(Q_("%dline adds whitespace errors.",4498"%dlines add whitespace errors.",4499 whitespace_error),4500 whitespace_error);4501}45024503if(update_index) {4504if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK))4505die(_("Unable to write new index file"));4506}45074508return!!errs;4509}