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}22322233if(postlen2234? postlen <new- postimage->buf2235: postimage->len <new- postimage->buf)2236die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2237(int)postlen, (int) postimage->len, (int)(new- postimage->buf));22382239/* Fix the length of the whole thing */2240 postimage->len =new- postimage->buf;2241 postimage->nr -= reduced;2242}22432244static intmatch_fragment(struct image *img,2245struct image *preimage,2246struct image *postimage,2247unsigned longtry,2248int try_lno,2249unsigned ws_rule,2250int match_beginning,int match_end)2251{2252int i;2253char*fixed_buf, *buf, *orig, *target;2254struct strbuf fixed;2255size_t fixed_len, postlen;2256int preimage_limit;22572258if(preimage->nr + try_lno <= img->nr) {2259/*2260 * The hunk falls within the boundaries of img.2261 */2262 preimage_limit = preimage->nr;2263if(match_end && (preimage->nr + try_lno != img->nr))2264return0;2265}else if(ws_error_action == correct_ws_error &&2266(ws_rule & WS_BLANK_AT_EOF)) {2267/*2268 * This hunk extends beyond the end of img, and we are2269 * removing blank lines at the end of the file. This2270 * many lines from the beginning of the preimage must2271 * match with img, and the remainder of the preimage2272 * must be blank.2273 */2274 preimage_limit = img->nr - try_lno;2275}else{2276/*2277 * The hunk extends beyond the end of the img and2278 * we are not removing blanks at the end, so we2279 * should reject the hunk at this position.2280 */2281return0;2282}22832284if(match_beginning && try_lno)2285return0;22862287/* Quick hash check */2288for(i =0; i < preimage_limit; i++)2289if((img->line[try_lno + i].flag & LINE_PATCHED) ||2290(preimage->line[i].hash != img->line[try_lno + i].hash))2291return0;22922293if(preimage_limit == preimage->nr) {2294/*2295 * Do we have an exact match? If we were told to match2296 * at the end, size must be exactly at try+fragsize,2297 * otherwise try+fragsize must be still within the preimage,2298 * and either case, the old piece should match the preimage2299 * exactly.2300 */2301if((match_end2302? (try+ preimage->len == img->len)2303: (try+ preimage->len <= img->len)) &&2304!memcmp(img->buf +try, preimage->buf, preimage->len))2305return1;2306}else{2307/*2308 * The preimage extends beyond the end of img, so2309 * there cannot be an exact match.2310 *2311 * There must be one non-blank context line that match2312 * a line before the end of img.2313 */2314char*buf_end;23152316 buf = preimage->buf;2317 buf_end = buf;2318for(i =0; i < preimage_limit; i++)2319 buf_end += preimage->line[i].len;23202321for( ; buf < buf_end; buf++)2322if(!isspace(*buf))2323break;2324if(buf == buf_end)2325return0;2326}23272328/*2329 * No exact match. If we are ignoring whitespace, run a line-by-line2330 * fuzzy matching. We collect all the line length information because2331 * we need it to adjust whitespace if we match.2332 */2333if(ws_ignore_action == ignore_ws_change) {2334size_t imgoff =0;2335size_t preoff =0;2336size_t postlen = postimage->len;2337size_t extra_chars;2338char*preimage_eof;2339char*preimage_end;2340for(i =0; i < preimage_limit; i++) {2341size_t prelen = preimage->line[i].len;2342size_t imglen = img->line[try_lno+i].len;23432344if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2345 preimage->buf + preoff, prelen))2346return0;2347if(preimage->line[i].flag & LINE_COMMON)2348 postlen += imglen - prelen;2349 imgoff += imglen;2350 preoff += prelen;2351}23522353/*2354 * Ok, the preimage matches with whitespace fuzz.2355 *2356 * imgoff now holds the true length of the target that2357 * matches the preimage before the end of the file.2358 *2359 * Count the number of characters in the preimage that fall2360 * beyond the end of the file and make sure that all of them2361 * are whitespace characters. (This can only happen if2362 * we are removing blank lines at the end of the file.)2363 */2364 buf = preimage_eof = preimage->buf + preoff;2365for( ; i < preimage->nr; i++)2366 preoff += preimage->line[i].len;2367 preimage_end = preimage->buf + preoff;2368for( ; buf < preimage_end; buf++)2369if(!isspace(*buf))2370return0;23712372/*2373 * Update the preimage and the common postimage context2374 * lines to use the same whitespace as the target.2375 * If whitespace is missing in the target (i.e.2376 * if the preimage extends beyond the end of the file),2377 * use the whitespace from the preimage.2378 */2379 extra_chars = preimage_end - preimage_eof;2380strbuf_init(&fixed, imgoff + extra_chars);2381strbuf_add(&fixed, img->buf +try, imgoff);2382strbuf_add(&fixed, preimage_eof, extra_chars);2383 fixed_buf =strbuf_detach(&fixed, &fixed_len);2384update_pre_post_images(preimage, postimage,2385 fixed_buf, fixed_len, postlen);2386return1;2387}23882389if(ws_error_action != correct_ws_error)2390return0;23912392/*2393 * The hunk does not apply byte-by-byte, but the hash says2394 * it might with whitespace fuzz. We weren't asked to2395 * ignore whitespace, we were asked to correct whitespace2396 * errors, so let's try matching after whitespace correction.2397 *2398 * While checking the preimage against the target, whitespace2399 * errors in both fixed, we count how large the corresponding2400 * postimage needs to be. The postimage prepared by2401 * apply_one_fragment() has whitespace errors fixed on added2402 * lines already, but the common lines were propagated as-is,2403 * which may become longer when their whitespace errors are2404 * fixed.2405 */24062407/* First count added lines in postimage */2408 postlen =0;2409for(i =0; i < postimage->nr; i++) {2410if(!(postimage->line[i].flag & LINE_COMMON))2411 postlen += postimage->line[i].len;2412}24132414/*2415 * The preimage may extend beyond the end of the file,2416 * but in this loop we will only handle the part of the2417 * preimage that falls within the file.2418 */2419strbuf_init(&fixed, preimage->len +1);2420 orig = preimage->buf;2421 target = img->buf +try;2422for(i =0; i < preimage_limit; i++) {2423size_t oldlen = preimage->line[i].len;2424size_t tgtlen = img->line[try_lno + i].len;2425size_t fixstart = fixed.len;2426struct strbuf tgtfix;2427int match;24282429/* Try fixing the line in the preimage */2430ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24312432/* Try fixing the line in the target */2433strbuf_init(&tgtfix, tgtlen);2434ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);24352436/*2437 * If they match, either the preimage was based on2438 * a version before our tree fixed whitespace breakage,2439 * or we are lacking a whitespace-fix patch the tree2440 * the preimage was based on already had (i.e. target2441 * has whitespace breakage, the preimage doesn't).2442 * In either case, we are fixing the whitespace breakages2443 * so we might as well take the fix together with their2444 * real change.2445 */2446 match = (tgtfix.len == fixed.len - fixstart &&2447!memcmp(tgtfix.buf, fixed.buf + fixstart,2448 fixed.len - fixstart));24492450/* Add the length if this is common with the postimage */2451if(preimage->line[i].flag & LINE_COMMON)2452 postlen += tgtfix.len;24532454strbuf_release(&tgtfix);2455if(!match)2456goto unmatch_exit;24572458 orig += oldlen;2459 target += tgtlen;2460}246124622463/*2464 * Now handle the lines in the preimage that falls beyond the2465 * end of the file (if any). They will only match if they are2466 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2467 * false).2468 */2469for( ; i < preimage->nr; i++) {2470size_t fixstart = fixed.len;/* start of the fixed preimage */2471size_t oldlen = preimage->line[i].len;2472int j;24732474/* Try fixing the line in the preimage */2475ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24762477for(j = fixstart; j < fixed.len; j++)2478if(!isspace(fixed.buf[j]))2479goto unmatch_exit;24802481 orig += oldlen;2482}24832484/*2485 * Yes, the preimage is based on an older version that still2486 * has whitespace breakages unfixed, and fixing them makes the2487 * hunk match. Update the context lines in the postimage.2488 */2489 fixed_buf =strbuf_detach(&fixed, &fixed_len);2490if(postlen < postimage->len)2491 postlen =0;2492update_pre_post_images(preimage, postimage,2493 fixed_buf, fixed_len, postlen);2494return1;24952496 unmatch_exit:2497strbuf_release(&fixed);2498return0;2499}25002501static intfind_pos(struct image *img,2502struct image *preimage,2503struct image *postimage,2504int line,2505unsigned ws_rule,2506int match_beginning,int match_end)2507{2508int i;2509unsigned long backwards, forwards,try;2510int backwards_lno, forwards_lno, try_lno;25112512/*2513 * If match_beginning or match_end is specified, there is no2514 * point starting from a wrong line that will never match and2515 * wander around and wait for a match at the specified end.2516 */2517if(match_beginning)2518 line =0;2519else if(match_end)2520 line = img->nr - preimage->nr;25212522/*2523 * Because the comparison is unsigned, the following test2524 * will also take care of a negative line number that can2525 * result when match_end and preimage is larger than the target.2526 */2527if((size_t) line > img->nr)2528 line = img->nr;25292530try=0;2531for(i =0; i < line; i++)2532try+= img->line[i].len;25332534/*2535 * There's probably some smart way to do this, but I'll leave2536 * that to the smart and beautiful people. I'm simple and stupid.2537 */2538 backwards =try;2539 backwards_lno = line;2540 forwards =try;2541 forwards_lno = line;2542 try_lno = line;25432544for(i =0; ; i++) {2545if(match_fragment(img, preimage, postimage,2546try, try_lno, ws_rule,2547 match_beginning, match_end))2548return try_lno;25492550 again:2551if(backwards_lno ==0&& forwards_lno == img->nr)2552break;25532554if(i &1) {2555if(backwards_lno ==0) {2556 i++;2557goto again;2558}2559 backwards_lno--;2560 backwards -= img->line[backwards_lno].len;2561try= backwards;2562 try_lno = backwards_lno;2563}else{2564if(forwards_lno == img->nr) {2565 i++;2566goto again;2567}2568 forwards += img->line[forwards_lno].len;2569 forwards_lno++;2570try= forwards;2571 try_lno = forwards_lno;2572}25732574}2575return-1;2576}25772578static voidremove_first_line(struct image *img)2579{2580 img->buf += img->line[0].len;2581 img->len -= img->line[0].len;2582 img->line++;2583 img->nr--;2584}25852586static voidremove_last_line(struct image *img)2587{2588 img->len -= img->line[--img->nr].len;2589}25902591/*2592 * The change from "preimage" and "postimage" has been found to2593 * apply at applied_pos (counts in line numbers) in "img".2594 * Update "img" to remove "preimage" and replace it with "postimage".2595 */2596static voidupdate_image(struct image *img,2597int applied_pos,2598struct image *preimage,2599struct image *postimage)2600{2601/*2602 * remove the copy of preimage at offset in img2603 * and replace it with postimage2604 */2605int i, nr;2606size_t remove_count, insert_count, applied_at =0;2607char*result;2608int preimage_limit;26092610/*2611 * If we are removing blank lines at the end of img,2612 * the preimage may extend beyond the end.2613 * If that is the case, we must be careful only to2614 * remove the part of the preimage that falls within2615 * the boundaries of img. Initialize preimage_limit2616 * to the number of lines in the preimage that falls2617 * within the boundaries.2618 */2619 preimage_limit = preimage->nr;2620if(preimage_limit > img->nr - applied_pos)2621 preimage_limit = img->nr - applied_pos;26222623for(i =0; i < applied_pos; i++)2624 applied_at += img->line[i].len;26252626 remove_count =0;2627for(i =0; i < preimage_limit; i++)2628 remove_count += img->line[applied_pos + i].len;2629 insert_count = postimage->len;26302631/* Adjust the contents */2632 result =xmalloc(img->len + insert_count - remove_count +1);2633memcpy(result, img->buf, applied_at);2634memcpy(result + applied_at, postimage->buf, postimage->len);2635memcpy(result + applied_at + postimage->len,2636 img->buf + (applied_at + remove_count),2637 img->len - (applied_at + remove_count));2638free(img->buf);2639 img->buf = result;2640 img->len += insert_count - remove_count;2641 result[img->len] ='\0';26422643/* Adjust the line table */2644 nr = img->nr + postimage->nr - preimage_limit;2645if(preimage_limit < postimage->nr) {2646/*2647 * NOTE: this knows that we never call remove_first_line()2648 * on anything other than pre/post image.2649 */2650REALLOC_ARRAY(img->line, nr);2651 img->line_allocated = img->line;2652}2653if(preimage_limit != postimage->nr)2654memmove(img->line + applied_pos + postimage->nr,2655 img->line + applied_pos + preimage_limit,2656(img->nr - (applied_pos + preimage_limit)) *2657sizeof(*img->line));2658memcpy(img->line + applied_pos,2659 postimage->line,2660 postimage->nr *sizeof(*img->line));2661if(!allow_overlap)2662for(i =0; i < postimage->nr; i++)2663 img->line[applied_pos + i].flag |= LINE_PATCHED;2664 img->nr = nr;2665}26662667/*2668 * Use the patch-hunk text in "frag" to prepare two images (preimage and2669 * postimage) for the hunk. Find lines that match "preimage" in "img" and2670 * replace the part of "img" with "postimage" text.2671 */2672static intapply_one_fragment(struct image *img,struct fragment *frag,2673int inaccurate_eof,unsigned ws_rule,2674int nth_fragment)2675{2676int match_beginning, match_end;2677const char*patch = frag->patch;2678int size = frag->size;2679char*old, *oldlines;2680struct strbuf newlines;2681int new_blank_lines_at_end =0;2682int found_new_blank_lines_at_end =0;2683int hunk_linenr = frag->linenr;2684unsigned long leading, trailing;2685int pos, applied_pos;2686struct image preimage;2687struct image postimage;26882689memset(&preimage,0,sizeof(preimage));2690memset(&postimage,0,sizeof(postimage));2691 oldlines =xmalloc(size);2692strbuf_init(&newlines, size);26932694 old = oldlines;2695while(size >0) {2696char first;2697int len =linelen(patch, size);2698int plen;2699int added_blank_line =0;2700int is_blank_context =0;2701size_t start;27022703if(!len)2704break;27052706/*2707 * "plen" is how much of the line we should use for2708 * the actual patch data. Normally we just remove the2709 * first character on the line, but if the line is2710 * followed by "\ No newline", then we also remove the2711 * last one (which is the newline, of course).2712 */2713 plen = len -1;2714if(len < size && patch[len] =='\\')2715 plen--;2716 first = *patch;2717if(apply_in_reverse) {2718if(first =='-')2719 first ='+';2720else if(first =='+')2721 first ='-';2722}27232724switch(first) {2725case'\n':2726/* Newer GNU diff, empty context line */2727if(plen <0)2728/* ... followed by '\No newline'; nothing */2729break;2730*old++ ='\n';2731strbuf_addch(&newlines,'\n');2732add_line_info(&preimage,"\n",1, LINE_COMMON);2733add_line_info(&postimage,"\n",1, LINE_COMMON);2734 is_blank_context =1;2735break;2736case' ':2737if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2738ws_blank_line(patch +1, plen, ws_rule))2739 is_blank_context =1;2740case'-':2741memcpy(old, patch +1, plen);2742add_line_info(&preimage, old, plen,2743(first ==' '? LINE_COMMON :0));2744 old += plen;2745if(first =='-')2746break;2747/* Fall-through for ' ' */2748case'+':2749/* --no-add does not add new lines */2750if(first =='+'&& no_add)2751break;27522753 start = newlines.len;2754if(first !='+'||2755!whitespace_error ||2756 ws_error_action != correct_ws_error) {2757strbuf_add(&newlines, patch +1, plen);2758}2759else{2760ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2761}2762add_line_info(&postimage, newlines.buf + start, newlines.len - start,2763(first =='+'?0: LINE_COMMON));2764if(first =='+'&&2765(ws_rule & WS_BLANK_AT_EOF) &&2766ws_blank_line(patch +1, plen, ws_rule))2767 added_blank_line =1;2768break;2769case'@':case'\\':2770/* Ignore it, we already handled it */2771break;2772default:2773if(apply_verbosely)2774error(_("invalid start of line: '%c'"), first);2775return-1;2776}2777if(added_blank_line) {2778if(!new_blank_lines_at_end)2779 found_new_blank_lines_at_end = hunk_linenr;2780 new_blank_lines_at_end++;2781}2782else if(is_blank_context)2783;2784else2785 new_blank_lines_at_end =0;2786 patch += len;2787 size -= len;2788 hunk_linenr++;2789}2790if(inaccurate_eof &&2791 old > oldlines && old[-1] =='\n'&&2792 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2793 old--;2794strbuf_setlen(&newlines, newlines.len -1);2795}27962797 leading = frag->leading;2798 trailing = frag->trailing;27992800/*2801 * A hunk to change lines at the beginning would begin with2802 * @@ -1,L +N,M @@2803 * but we need to be careful. -U0 that inserts before the second2804 * line also has this pattern.2805 *2806 * And a hunk to add to an empty file would begin with2807 * @@ -0,0 +N,M @@2808 *2809 * In other words, a hunk that is (frag->oldpos <= 1) with or2810 * without leading context must match at the beginning.2811 */2812 match_beginning = (!frag->oldpos ||2813(frag->oldpos ==1&& !unidiff_zero));28142815/*2816 * A hunk without trailing lines must match at the end.2817 * However, we simply cannot tell if a hunk must match end2818 * from the lack of trailing lines if the patch was generated2819 * with unidiff without any context.2820 */2821 match_end = !unidiff_zero && !trailing;28222823 pos = frag->newpos ? (frag->newpos -1) :0;2824 preimage.buf = oldlines;2825 preimage.len = old - oldlines;2826 postimage.buf = newlines.buf;2827 postimage.len = newlines.len;2828 preimage.line = preimage.line_allocated;2829 postimage.line = postimage.line_allocated;28302831for(;;) {28322833 applied_pos =find_pos(img, &preimage, &postimage, pos,2834 ws_rule, match_beginning, match_end);28352836if(applied_pos >=0)2837break;28382839/* Am I at my context limits? */2840if((leading <= p_context) && (trailing <= p_context))2841break;2842if(match_beginning || match_end) {2843 match_beginning = match_end =0;2844continue;2845}28462847/*2848 * Reduce the number of context lines; reduce both2849 * leading and trailing if they are equal otherwise2850 * just reduce the larger context.2851 */2852if(leading >= trailing) {2853remove_first_line(&preimage);2854remove_first_line(&postimage);2855 pos--;2856 leading--;2857}2858if(trailing > leading) {2859remove_last_line(&preimage);2860remove_last_line(&postimage);2861 trailing--;2862}2863}28642865if(applied_pos >=0) {2866if(new_blank_lines_at_end &&2867 preimage.nr + applied_pos >= img->nr &&2868(ws_rule & WS_BLANK_AT_EOF) &&2869 ws_error_action != nowarn_ws_error) {2870record_ws_error(WS_BLANK_AT_EOF,"+",1,2871 found_new_blank_lines_at_end);2872if(ws_error_action == correct_ws_error) {2873while(new_blank_lines_at_end--)2874remove_last_line(&postimage);2875}2876/*2877 * We would want to prevent write_out_results()2878 * from taking place in apply_patch() that follows2879 * the callchain led us here, which is:2880 * apply_patch->check_patch_list->check_patch->2881 * apply_data->apply_fragments->apply_one_fragment2882 */2883if(ws_error_action == die_on_ws_error)2884 apply =0;2885}28862887if(apply_verbosely && applied_pos != pos) {2888int offset = applied_pos - pos;2889if(apply_in_reverse)2890 offset =0- offset;2891fprintf_ln(stderr,2892Q_("Hunk #%dsucceeded at%d(offset%dline).",2893"Hunk #%dsucceeded at%d(offset%dlines).",2894 offset),2895 nth_fragment, applied_pos +1, offset);2896}28972898/*2899 * Warn if it was necessary to reduce the number2900 * of context lines.2901 */2902if((leading != frag->leading) ||2903(trailing != frag->trailing))2904fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2905" to apply fragment at%d"),2906 leading, trailing, applied_pos+1);2907update_image(img, applied_pos, &preimage, &postimage);2908}else{2909if(apply_verbosely)2910error(_("while searching for:\n%.*s"),2911(int)(old - oldlines), oldlines);2912}29132914free(oldlines);2915strbuf_release(&newlines);2916free(preimage.line_allocated);2917free(postimage.line_allocated);29182919return(applied_pos <0);2920}29212922static intapply_binary_fragment(struct image *img,struct patch *patch)2923{2924struct fragment *fragment = patch->fragments;2925unsigned long len;2926void*dst;29272928if(!fragment)2929returnerror(_("missing binary patch data for '%s'"),2930 patch->new_name ?2931 patch->new_name :2932 patch->old_name);29332934/* Binary patch is irreversible without the optional second hunk */2935if(apply_in_reverse) {2936if(!fragment->next)2937returnerror("cannot reverse-apply a binary patch "2938"without the reverse hunk to '%s'",2939 patch->new_name2940? patch->new_name : patch->old_name);2941 fragment = fragment->next;2942}2943switch(fragment->binary_patch_method) {2944case BINARY_DELTA_DEFLATED:2945 dst =patch_delta(img->buf, img->len, fragment->patch,2946 fragment->size, &len);2947if(!dst)2948return-1;2949clear_image(img);2950 img->buf = dst;2951 img->len = len;2952return0;2953case BINARY_LITERAL_DEFLATED:2954clear_image(img);2955 img->len = fragment->size;2956 img->buf =xmemdupz(fragment->patch, img->len);2957return0;2958}2959return-1;2960}29612962/*2963 * Replace "img" with the result of applying the binary patch.2964 * The binary patch data itself in patch->fragment is still kept2965 * but the preimage prepared by the caller in "img" is freed here2966 * or in the helper function apply_binary_fragment() this calls.2967 */2968static intapply_binary(struct image *img,struct patch *patch)2969{2970const char*name = patch->old_name ? patch->old_name : patch->new_name;2971unsigned char sha1[20];29722973/*2974 * For safety, we require patch index line to contain2975 * full 40-byte textual SHA1 for old and new, at least for now.2976 */2977if(strlen(patch->old_sha1_prefix) !=40||2978strlen(patch->new_sha1_prefix) !=40||2979get_sha1_hex(patch->old_sha1_prefix, sha1) ||2980get_sha1_hex(patch->new_sha1_prefix, sha1))2981returnerror("cannot apply binary patch to '%s' "2982"without full index line", name);29832984if(patch->old_name) {2985/*2986 * See if the old one matches what the patch2987 * applies to.2988 */2989hash_sha1_file(img->buf, img->len, blob_type, sha1);2990if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2991returnerror("the patch applies to '%s' (%s), "2992"which does not match the "2993"current contents.",2994 name,sha1_to_hex(sha1));2995}2996else{2997/* Otherwise, the old one must be empty. */2998if(img->len)2999returnerror("the patch applies to an empty "3000"'%s' but it is not empty", name);3001}30023003get_sha1_hex(patch->new_sha1_prefix, sha1);3004if(is_null_sha1(sha1)) {3005clear_image(img);3006return0;/* deletion patch */3007}30083009if(has_sha1_file(sha1)) {3010/* We already have the postimage */3011enum object_type type;3012unsigned long size;3013char*result;30143015 result =read_sha1_file(sha1, &type, &size);3016if(!result)3017returnerror("the necessary postimage%sfor "3018"'%s' cannot be read",3019 patch->new_sha1_prefix, name);3020clear_image(img);3021 img->buf = result;3022 img->len = size;3023}else{3024/*3025 * We have verified buf matches the preimage;3026 * apply the patch data to it, which is stored3027 * in the patch->fragments->{patch,size}.3028 */3029if(apply_binary_fragment(img, patch))3030returnerror(_("binary patch does not apply to '%s'"),3031 name);30323033/* verify that the result matches */3034hash_sha1_file(img->buf, img->len, blob_type, sha1);3035if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3036returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3037 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3038}30393040return0;3041}30423043static intapply_fragments(struct image *img,struct patch *patch)3044{3045struct fragment *frag = patch->fragments;3046const char*name = patch->old_name ? patch->old_name : patch->new_name;3047unsigned ws_rule = patch->ws_rule;3048unsigned inaccurate_eof = patch->inaccurate_eof;3049int nth =0;30503051if(patch->is_binary)3052returnapply_binary(img, patch);30533054while(frag) {3055 nth++;3056if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {3057error(_("patch failed:%s:%ld"), name, frag->oldpos);3058if(!apply_with_reject)3059return-1;3060 frag->rejected =1;3061}3062 frag = frag->next;3063}3064return0;3065}30663067static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3068{3069if(S_ISGITLINK(mode)) {3070strbuf_grow(buf,100);3071strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3072}else{3073enum object_type type;3074unsigned long sz;3075char*result;30763077 result =read_sha1_file(sha1, &type, &sz);3078if(!result)3079return-1;3080/* XXX read_sha1_file NUL-terminates */3081strbuf_attach(buf, result, sz, sz +1);3082}3083return0;3084}30853086static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3087{3088if(!ce)3089return0;3090returnread_blob_object(buf, ce->sha1, ce->ce_mode);3091}30923093static struct patch *in_fn_table(const char*name)3094{3095struct string_list_item *item;30963097if(name == NULL)3098return NULL;30993100 item =string_list_lookup(&fn_table, name);3101if(item != NULL)3102return(struct patch *)item->util;31033104return NULL;3105}31063107/*3108 * item->util in the filename table records the status of the path.3109 * Usually it points at a patch (whose result records the contents3110 * of it after applying it), but it could be PATH_WAS_DELETED for a3111 * path that a previously applied patch has already removed, or3112 * PATH_TO_BE_DELETED for a path that a later patch would remove.3113 *3114 * The latter is needed to deal with a case where two paths A and B3115 * are swapped by first renaming A to B and then renaming B to A;3116 * moving A to B should not be prevented due to presence of B as we3117 * will remove it in a later patch.3118 */3119#define PATH_TO_BE_DELETED ((struct patch *) -2)3120#define PATH_WAS_DELETED ((struct patch *) -1)31213122static intto_be_deleted(struct patch *patch)3123{3124return patch == PATH_TO_BE_DELETED;3125}31263127static intwas_deleted(struct patch *patch)3128{3129return patch == PATH_WAS_DELETED;3130}31313132static voidadd_to_fn_table(struct patch *patch)3133{3134struct string_list_item *item;31353136/*3137 * Always add new_name unless patch is a deletion3138 * This should cover the cases for normal diffs,3139 * file creations and copies3140 */3141if(patch->new_name != NULL) {3142 item =string_list_insert(&fn_table, patch->new_name);3143 item->util = patch;3144}31453146/*3147 * store a failure on rename/deletion cases because3148 * later chunks shouldn't patch old names3149 */3150if((patch->new_name == NULL) || (patch->is_rename)) {3151 item =string_list_insert(&fn_table, patch->old_name);3152 item->util = PATH_WAS_DELETED;3153}3154}31553156static voidprepare_fn_table(struct patch *patch)3157{3158/*3159 * store information about incoming file deletion3160 */3161while(patch) {3162if((patch->new_name == NULL) || (patch->is_rename)) {3163struct string_list_item *item;3164 item =string_list_insert(&fn_table, patch->old_name);3165 item->util = PATH_TO_BE_DELETED;3166}3167 patch = patch->next;3168}3169}31703171static intcheckout_target(struct index_state *istate,3172struct cache_entry *ce,struct stat *st)3173{3174struct checkout costate;31753176memset(&costate,0,sizeof(costate));3177 costate.base_dir ="";3178 costate.refresh_cache =1;3179 costate.istate = istate;3180if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3181returnerror(_("cannot checkout%s"), ce->name);3182return0;3183}31843185static struct patch *previous_patch(struct patch *patch,int*gone)3186{3187struct patch *previous;31883189*gone =0;3190if(patch->is_copy || patch->is_rename)3191return NULL;/* "git" patches do not depend on the order */31923193 previous =in_fn_table(patch->old_name);3194if(!previous)3195return NULL;31963197if(to_be_deleted(previous))3198return NULL;/* the deletion hasn't happened yet */31993200if(was_deleted(previous))3201*gone =1;32023203return previous;3204}32053206static intverify_index_match(const struct cache_entry *ce,struct stat *st)3207{3208if(S_ISGITLINK(ce->ce_mode)) {3209if(!S_ISDIR(st->st_mode))3210return-1;3211return0;3212}3213returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3214}32153216#define SUBMODULE_PATCH_WITHOUT_INDEX 132173218static intload_patch_target(struct strbuf *buf,3219const struct cache_entry *ce,3220struct stat *st,3221const char*name,3222unsigned expected_mode)3223{3224if(cached) {3225if(read_file_or_gitlink(ce, buf))3226returnerror(_("read of%sfailed"), name);3227}else if(name) {3228if(S_ISGITLINK(expected_mode)) {3229if(ce)3230returnread_file_or_gitlink(ce, buf);3231else3232return SUBMODULE_PATCH_WITHOUT_INDEX;3233}else{3234if(read_old_data(st, name, buf))3235returnerror(_("read of%sfailed"), name);3236}3237}3238return0;3239}32403241/*3242 * We are about to apply "patch"; populate the "image" with the3243 * current version we have, from the working tree or from the index,3244 * depending on the situation e.g. --cached/--index. If we are3245 * applying a non-git patch that incrementally updates the tree,3246 * we read from the result of a previous diff.3247 */3248static intload_preimage(struct image *image,3249struct patch *patch,struct stat *st,3250const struct cache_entry *ce)3251{3252struct strbuf buf = STRBUF_INIT;3253size_t len;3254char*img;3255struct patch *previous;3256int status;32573258 previous =previous_patch(patch, &status);3259if(status)3260returnerror(_("path%shas been renamed/deleted"),3261 patch->old_name);3262if(previous) {3263/* We have a patched copy in memory; use that. */3264strbuf_add(&buf, previous->result, previous->resultsize);3265}else{3266 status =load_patch_target(&buf, ce, st,3267 patch->old_name, patch->old_mode);3268if(status <0)3269return status;3270else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3271/*3272 * There is no way to apply subproject3273 * patch without looking at the index.3274 * NEEDSWORK: shouldn't this be flagged3275 * as an error???3276 */3277free_fragment_list(patch->fragments);3278 patch->fragments = NULL;3279}else if(status) {3280returnerror(_("read of%sfailed"), patch->old_name);3281}3282}32833284 img =strbuf_detach(&buf, &len);3285prepare_image(image, img, len, !patch->is_binary);3286return0;3287}32883289static intthree_way_merge(struct image *image,3290char*path,3291const unsigned char*base,3292const unsigned char*ours,3293const unsigned char*theirs)3294{3295 mmfile_t base_file, our_file, their_file;3296 mmbuffer_t result = { NULL };3297int status;32983299read_mmblob(&base_file, base);3300read_mmblob(&our_file, ours);3301read_mmblob(&their_file, theirs);3302 status =ll_merge(&result, path,3303&base_file,"base",3304&our_file,"ours",3305&their_file,"theirs", NULL);3306free(base_file.ptr);3307free(our_file.ptr);3308free(their_file.ptr);3309if(status <0|| !result.ptr) {3310free(result.ptr);3311return-1;3312}3313clear_image(image);3314 image->buf = result.ptr;3315 image->len = result.size;33163317return status;3318}33193320/*3321 * When directly falling back to add/add three-way merge, we read from3322 * the current contents of the new_name. In no cases other than that3323 * this function will be called.3324 */3325static intload_current(struct image *image,struct patch *patch)3326{3327struct strbuf buf = STRBUF_INIT;3328int status, pos;3329size_t len;3330char*img;3331struct stat st;3332struct cache_entry *ce;3333char*name = patch->new_name;3334unsigned mode = patch->new_mode;33353336if(!patch->is_new)3337die("BUG: patch to%sis not a creation", patch->old_name);33383339 pos =cache_name_pos(name,strlen(name));3340if(pos <0)3341returnerror(_("%s: does not exist in index"), name);3342 ce = active_cache[pos];3343if(lstat(name, &st)) {3344if(errno != ENOENT)3345returnerror(_("%s:%s"), name,strerror(errno));3346if(checkout_target(&the_index, ce, &st))3347return-1;3348}3349if(verify_index_match(ce, &st))3350returnerror(_("%s: does not match index"), name);33513352 status =load_patch_target(&buf, ce, &st, name, mode);3353if(status <0)3354return status;3355else if(status)3356return-1;3357 img =strbuf_detach(&buf, &len);3358prepare_image(image, img, len, !patch->is_binary);3359return0;3360}33613362static inttry_threeway(struct image *image,struct patch *patch,3363struct stat *st,const struct cache_entry *ce)3364{3365unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3366struct strbuf buf = STRBUF_INIT;3367size_t len;3368int status;3369char*img;3370struct image tmp_image;33713372/* No point falling back to 3-way merge in these cases */3373if(patch->is_delete ||3374S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3375return-1;33763377/* Preimage the patch was prepared for */3378if(patch->is_new)3379write_sha1_file("",0, blob_type, pre_sha1);3380else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3381read_blob_object(&buf, pre_sha1, patch->old_mode))3382returnerror("repository lacks the necessary blob to fall back on 3-way merge.");33833384fprintf(stderr,"Falling back to three-way merge...\n");33853386 img =strbuf_detach(&buf, &len);3387prepare_image(&tmp_image, img, len,1);3388/* Apply the patch to get the post image */3389if(apply_fragments(&tmp_image, patch) <0) {3390clear_image(&tmp_image);3391return-1;3392}3393/* post_sha1[] is theirs */3394write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3395clear_image(&tmp_image);33963397/* our_sha1[] is ours */3398if(patch->is_new) {3399if(load_current(&tmp_image, patch))3400returnerror("cannot read the current contents of '%s'",3401 patch->new_name);3402}else{3403if(load_preimage(&tmp_image, patch, st, ce))3404returnerror("cannot read the current contents of '%s'",3405 patch->old_name);3406}3407write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3408clear_image(&tmp_image);34093410/* in-core three-way merge between post and our using pre as base */3411 status =three_way_merge(image, patch->new_name,3412 pre_sha1, our_sha1, post_sha1);3413if(status <0) {3414fprintf(stderr,"Failed to fall back on three-way merge...\n");3415return status;3416}34173418if(status) {3419 patch->conflicted_threeway =1;3420if(patch->is_new)3421hashclr(patch->threeway_stage[0]);3422else3423hashcpy(patch->threeway_stage[0], pre_sha1);3424hashcpy(patch->threeway_stage[1], our_sha1);3425hashcpy(patch->threeway_stage[2], post_sha1);3426fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3427}else{3428fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3429}3430return0;3431}34323433static intapply_data(struct patch *patch,struct stat *st,const struct cache_entry *ce)3434{3435struct image image;34363437if(load_preimage(&image, patch, st, ce) <0)3438return-1;34393440if(patch->direct_to_threeway ||3441apply_fragments(&image, patch) <0) {3442/* Note: with --reject, apply_fragments() returns 0 */3443if(!threeway ||try_threeway(&image, patch, st, ce) <0)3444return-1;3445}3446 patch->result = image.buf;3447 patch->resultsize = image.len;3448add_to_fn_table(patch);3449free(image.line_allocated);34503451if(0< patch->is_delete && patch->resultsize)3452returnerror(_("removal patch leaves file contents"));34533454return0;3455}34563457/*3458 * If "patch" that we are looking at modifies or deletes what we have,3459 * we would want it not to lose any local modification we have, either3460 * in the working tree or in the index.3461 *3462 * This also decides if a non-git patch is a creation patch or a3463 * modification to an existing empty file. We do not check the state3464 * of the current tree for a creation patch in this function; the caller3465 * check_patch() separately makes sure (and errors out otherwise) that3466 * the path the patch creates does not exist in the current tree.3467 */3468static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)3469{3470const char*old_name = patch->old_name;3471struct patch *previous = NULL;3472int stat_ret =0, status;3473unsigned st_mode =0;34743475if(!old_name)3476return0;34773478assert(patch->is_new <=0);3479 previous =previous_patch(patch, &status);34803481if(status)3482returnerror(_("path%shas been renamed/deleted"), old_name);3483if(previous) {3484 st_mode = previous->new_mode;3485}else if(!cached) {3486 stat_ret =lstat(old_name, st);3487if(stat_ret && errno != ENOENT)3488returnerror(_("%s:%s"), old_name,strerror(errno));3489}34903491if(check_index && !previous) {3492int pos =cache_name_pos(old_name,strlen(old_name));3493if(pos <0) {3494if(patch->is_new <0)3495goto is_new;3496returnerror(_("%s: does not exist in index"), old_name);3497}3498*ce = active_cache[pos];3499if(stat_ret <0) {3500if(checkout_target(&the_index, *ce, st))3501return-1;3502}3503if(!cached &&verify_index_match(*ce, st))3504returnerror(_("%s: does not match index"), old_name);3505if(cached)3506 st_mode = (*ce)->ce_mode;3507}else if(stat_ret <0) {3508if(patch->is_new <0)3509goto is_new;3510returnerror(_("%s:%s"), old_name,strerror(errno));3511}35123513if(!cached && !previous)3514 st_mode =ce_mode_from_stat(*ce, st->st_mode);35153516if(patch->is_new <0)3517 patch->is_new =0;3518if(!patch->old_mode)3519 patch->old_mode = st_mode;3520if((st_mode ^ patch->old_mode) & S_IFMT)3521returnerror(_("%s: wrong type"), old_name);3522if(st_mode != patch->old_mode)3523warning(_("%shas type%o, expected%o"),3524 old_name, st_mode, patch->old_mode);3525if(!patch->new_mode && !patch->is_delete)3526 patch->new_mode = st_mode;3527return0;35283529 is_new:3530 patch->is_new =1;3531 patch->is_delete =0;3532free(patch->old_name);3533 patch->old_name = NULL;3534return0;3535}353635373538#define EXISTS_IN_INDEX 13539#define EXISTS_IN_WORKTREE 235403541static intcheck_to_create(const char*new_name,int ok_if_exists)3542{3543struct stat nst;35443545if(check_index &&3546cache_name_pos(new_name,strlen(new_name)) >=0&&3547!ok_if_exists)3548return EXISTS_IN_INDEX;3549if(cached)3550return0;35513552if(!lstat(new_name, &nst)) {3553if(S_ISDIR(nst.st_mode) || ok_if_exists)3554return0;3555/*3556 * A leading component of new_name might be a symlink3557 * that is going to be removed with this patch, but3558 * still pointing at somewhere that has the path.3559 * In such a case, path "new_name" does not exist as3560 * far as git is concerned.3561 */3562if(has_symlink_leading_path(new_name,strlen(new_name)))3563return0;35643565return EXISTS_IN_WORKTREE;3566}else if((errno != ENOENT) && (errno != ENOTDIR)) {3567returnerror("%s:%s", new_name,strerror(errno));3568}3569return0;3570}35713572/*3573 * Check and apply the patch in-core; leave the result in patch->result3574 * for the caller to write it out to the final destination.3575 */3576static intcheck_patch(struct patch *patch)3577{3578struct stat st;3579const char*old_name = patch->old_name;3580const char*new_name = patch->new_name;3581const char*name = old_name ? old_name : new_name;3582struct cache_entry *ce = NULL;3583struct patch *tpatch;3584int ok_if_exists;3585int status;35863587 patch->rejected =1;/* we will drop this after we succeed */35883589 status =check_preimage(patch, &ce, &st);3590if(status)3591return status;3592 old_name = patch->old_name;35933594/*3595 * A type-change diff is always split into a patch to delete3596 * old, immediately followed by a patch to create new (see3597 * diff.c::run_diff()); in such a case it is Ok that the entry3598 * to be deleted by the previous patch is still in the working3599 * tree and in the index.3600 *3601 * A patch to swap-rename between A and B would first rename A3602 * to B and then rename B to A. While applying the first one,3603 * the presence of B should not stop A from getting renamed to3604 * B; ask to_be_deleted() about the later rename. Removal of3605 * B and rename from A to B is handled the same way by asking3606 * was_deleted().3607 */3608if((tpatch =in_fn_table(new_name)) &&3609(was_deleted(tpatch) ||to_be_deleted(tpatch)))3610 ok_if_exists =1;3611else3612 ok_if_exists =0;36133614if(new_name &&3615((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3616int err =check_to_create(new_name, ok_if_exists);36173618if(err && threeway) {3619 patch->direct_to_threeway =1;3620}else switch(err) {3621case0:3622break;/* happy */3623case EXISTS_IN_INDEX:3624returnerror(_("%s: already exists in index"), new_name);3625break;3626case EXISTS_IN_WORKTREE:3627returnerror(_("%s: already exists in working directory"),3628 new_name);3629default:3630return err;3631}36323633if(!patch->new_mode) {3634if(0< patch->is_new)3635 patch->new_mode = S_IFREG |0644;3636else3637 patch->new_mode = patch->old_mode;3638}3639}36403641if(new_name && old_name) {3642int same = !strcmp(old_name, new_name);3643if(!patch->new_mode)3644 patch->new_mode = patch->old_mode;3645if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3646if(same)3647returnerror(_("new mode (%o) of%sdoes not "3648"match old mode (%o)"),3649 patch->new_mode, new_name,3650 patch->old_mode);3651else3652returnerror(_("new mode (%o) of%sdoes not "3653"match old mode (%o) of%s"),3654 patch->new_mode, new_name,3655 patch->old_mode, old_name);3656}3657}36583659if(apply_data(patch, &st, ce) <0)3660returnerror(_("%s: patch does not apply"), name);3661 patch->rejected =0;3662return0;3663}36643665static intcheck_patch_list(struct patch *patch)3666{3667int err =0;36683669prepare_fn_table(patch);3670while(patch) {3671if(apply_verbosely)3672say_patch_name(stderr,3673_("Checking patch%s..."), patch);3674 err |=check_patch(patch);3675 patch = patch->next;3676}3677return err;3678}36793680/* This function tries to read the sha1 from the current index */3681static intget_current_sha1(const char*path,unsigned char*sha1)3682{3683int pos;36843685if(read_cache() <0)3686return-1;3687 pos =cache_name_pos(path,strlen(path));3688if(pos <0)3689return-1;3690hashcpy(sha1, active_cache[pos]->sha1);3691return0;3692}36933694static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3695{3696/*3697 * A usable gitlink patch has only one fragment (hunk) that looks like:3698 * @@ -1 +1 @@3699 * -Subproject commit <old sha1>3700 * +Subproject commit <new sha1>3701 * or3702 * @@ -1 +0,0 @@3703 * -Subproject commit <old sha1>3704 * for a removal patch.3705 */3706struct fragment *hunk = p->fragments;3707static const char heading[] ="-Subproject commit ";3708char*preimage;37093710if(/* does the patch have only one hunk? */3711 hunk && !hunk->next &&3712/* is its preimage one line? */3713 hunk->oldpos ==1&& hunk->oldlines ==1&&3714/* does preimage begin with the heading? */3715(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3716starts_with(++preimage, heading) &&3717/* does it record full SHA-1? */3718!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3719 preimage[sizeof(heading) +40-1] =='\n'&&3720/* does the abbreviated name on the index line agree with it? */3721starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3722return0;/* it all looks fine */37233724/* we may have full object name on the index line */3725returnget_sha1_hex(p->old_sha1_prefix, sha1);3726}37273728/* Build an index that contains the just the files needed for a 3way merge */3729static voidbuild_fake_ancestor(struct patch *list,const char*filename)3730{3731struct patch *patch;3732struct index_state result = { NULL };3733static struct lock_file lock;37343735/* Once we start supporting the reverse patch, it may be3736 * worth showing the new sha1 prefix, but until then...3737 */3738for(patch = list; patch; patch = patch->next) {3739unsigned char sha1[20];3740struct cache_entry *ce;3741const char*name;37423743 name = patch->old_name ? patch->old_name : patch->new_name;3744if(0< patch->is_new)3745continue;37463747if(S_ISGITLINK(patch->old_mode)) {3748if(!preimage_sha1_in_gitlink_patch(patch, sha1))3749;/* ok, the textual part looks sane */3750else3751die("sha1 information is lacking or useless for submodule%s",3752 name);3753}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {3754;/* ok */3755}else if(!patch->lines_added && !patch->lines_deleted) {3756/* mode-only change: update the current */3757if(get_current_sha1(patch->old_name, sha1))3758die("mode change for%s, which is not "3759"in current HEAD", name);3760}else3761die("sha1 information is lacking or useless "3762"(%s).", name);37633764 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);3765if(!ce)3766die(_("make_cache_entry failed for path '%s'"), name);3767if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3768die("Could not add%sto temporary index", name);3769}37703771hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);3772if(write_locked_index(&result, &lock, COMMIT_LOCK))3773die("Could not write temporary index to%s", filename);37743775discard_index(&result);3776}37773778static voidstat_patch_list(struct patch *patch)3779{3780int files, adds, dels;37813782for(files = adds = dels =0; patch ; patch = patch->next) {3783 files++;3784 adds += patch->lines_added;3785 dels += patch->lines_deleted;3786show_stats(patch);3787}37883789print_stat_summary(stdout, files, adds, dels);3790}37913792static voidnumstat_patch_list(struct patch *patch)3793{3794for( ; patch; patch = patch->next) {3795const char*name;3796 name = patch->new_name ? patch->new_name : patch->old_name;3797if(patch->is_binary)3798printf("-\t-\t");3799else3800printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3801write_name_quoted(name, stdout, line_termination);3802}3803}38043805static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3806{3807if(mode)3808printf("%smode%06o%s\n", newdelete, mode, name);3809else3810printf("%s %s\n", newdelete, name);3811}38123813static voidshow_mode_change(struct patch *p,int show_name)3814{3815if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3816if(show_name)3817printf(" mode change%06o =>%06o%s\n",3818 p->old_mode, p->new_mode, p->new_name);3819else3820printf(" mode change%06o =>%06o\n",3821 p->old_mode, p->new_mode);3822}3823}38243825static voidshow_rename_copy(struct patch *p)3826{3827const char*renamecopy = p->is_rename ?"rename":"copy";3828const char*old, *new;38293830/* Find common prefix */3831 old = p->old_name;3832new= p->new_name;3833while(1) {3834const char*slash_old, *slash_new;3835 slash_old =strchr(old,'/');3836 slash_new =strchr(new,'/');3837if(!slash_old ||3838!slash_new ||3839 slash_old - old != slash_new -new||3840memcmp(old,new, slash_new -new))3841break;3842 old = slash_old +1;3843new= slash_new +1;3844}3845/* p->old_name thru old is the common prefix, and old and new3846 * through the end of names are renames3847 */3848if(old != p->old_name)3849printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,3850(int)(old - p->old_name), p->old_name,3851 old,new, p->score);3852else3853printf("%s %s=>%s(%d%%)\n", renamecopy,3854 p->old_name, p->new_name, p->score);3855show_mode_change(p,0);3856}38573858static voidsummary_patch_list(struct patch *patch)3859{3860struct patch *p;38613862for(p = patch; p; p = p->next) {3863if(p->is_new)3864show_file_mode_name("create", p->new_mode, p->new_name);3865else if(p->is_delete)3866show_file_mode_name("delete", p->old_mode, p->old_name);3867else{3868if(p->is_rename || p->is_copy)3869show_rename_copy(p);3870else{3871if(p->score) {3872printf(" rewrite%s(%d%%)\n",3873 p->new_name, p->score);3874show_mode_change(p,0);3875}3876else3877show_mode_change(p,1);3878}3879}3880}3881}38823883static voidpatch_stats(struct patch *patch)3884{3885int lines = patch->lines_added + patch->lines_deleted;38863887if(lines > max_change)3888 max_change = lines;3889if(patch->old_name) {3890int len =quote_c_style(patch->old_name, NULL, NULL,0);3891if(!len)3892 len =strlen(patch->old_name);3893if(len > max_len)3894 max_len = len;3895}3896if(patch->new_name) {3897int len =quote_c_style(patch->new_name, NULL, NULL,0);3898if(!len)3899 len =strlen(patch->new_name);3900if(len > max_len)3901 max_len = len;3902}3903}39043905static voidremove_file(struct patch *patch,int rmdir_empty)3906{3907if(update_index) {3908if(remove_file_from_cache(patch->old_name) <0)3909die(_("unable to remove%sfrom index"), patch->old_name);3910}3911if(!cached) {3912if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {3913remove_path(patch->old_name);3914}3915}3916}39173918static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)3919{3920struct stat st;3921struct cache_entry *ce;3922int namelen =strlen(path);3923unsigned ce_size =cache_entry_size(namelen);39243925if(!update_index)3926return;39273928 ce =xcalloc(1, ce_size);3929memcpy(ce->name, path, namelen);3930 ce->ce_mode =create_ce_mode(mode);3931 ce->ce_flags =create_ce_flags(0);3932 ce->ce_namelen = namelen;3933if(S_ISGITLINK(mode)) {3934const char*s;39353936if(!skip_prefix(buf,"Subproject commit ", &s) ||3937get_sha1_hex(s, ce->sha1))3938die(_("corrupt patch for submodule%s"), path);3939}else{3940if(!cached) {3941if(lstat(path, &st) <0)3942die_errno(_("unable to stat newly created file '%s'"),3943 path);3944fill_stat_cache_info(ce, &st);3945}3946if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)3947die(_("unable to create backing store for newly created file%s"), path);3948}3949if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3950die(_("unable to add cache entry for%s"), path);3951}39523953static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)3954{3955int fd;3956struct strbuf nbuf = STRBUF_INIT;39573958if(S_ISGITLINK(mode)) {3959struct stat st;3960if(!lstat(path, &st) &&S_ISDIR(st.st_mode))3961return0;3962returnmkdir(path,0777);3963}39643965if(has_symlinks &&S_ISLNK(mode))3966/* Although buf:size is counted string, it also is NUL3967 * terminated.3968 */3969returnsymlink(buf, path);39703971 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);3972if(fd <0)3973return-1;39743975if(convert_to_working_tree(path, buf, size, &nbuf)) {3976 size = nbuf.len;3977 buf = nbuf.buf;3978}3979write_or_die(fd, buf, size);3980strbuf_release(&nbuf);39813982if(close(fd) <0)3983die_errno(_("closing file '%s'"), path);3984return0;3985}39863987/*3988 * We optimistically assume that the directories exist,3989 * which is true 99% of the time anyway. If they don't,3990 * we create them and try again.3991 */3992static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)3993{3994if(cached)3995return;3996if(!try_create_file(path, mode, buf, size))3997return;39983999if(errno == ENOENT) {4000if(safe_create_leading_directories(path))4001return;4002if(!try_create_file(path, mode, buf, size))4003return;4004}40054006if(errno == EEXIST || errno == EACCES) {4007/* We may be trying to create a file where a directory4008 * used to be.4009 */4010struct stat st;4011if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4012 errno = EEXIST;4013}40144015if(errno == EEXIST) {4016unsigned int nr =getpid();40174018for(;;) {4019char newpath[PATH_MAX];4020mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4021if(!try_create_file(newpath, mode, buf, size)) {4022if(!rename(newpath, path))4023return;4024unlink_or_warn(newpath);4025break;4026}4027if(errno != EEXIST)4028break;4029++nr;4030}4031}4032die_errno(_("unable to write file '%s' mode%o"), path, mode);4033}40344035static voidadd_conflicted_stages_file(struct patch *patch)4036{4037int stage, namelen;4038unsigned ce_size, mode;4039struct cache_entry *ce;40404041if(!update_index)4042return;4043 namelen =strlen(patch->new_name);4044 ce_size =cache_entry_size(namelen);4045 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);40464047remove_file_from_cache(patch->new_name);4048for(stage =1; stage <4; stage++) {4049if(is_null_sha1(patch->threeway_stage[stage -1]))4050continue;4051 ce =xcalloc(1, ce_size);4052memcpy(ce->name, patch->new_name, namelen);4053 ce->ce_mode =create_ce_mode(mode);4054 ce->ce_flags =create_ce_flags(stage);4055 ce->ce_namelen = namelen;4056hashcpy(ce->sha1, patch->threeway_stage[stage -1]);4057if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4058die(_("unable to add cache entry for%s"), patch->new_name);4059}4060}40614062static voidcreate_file(struct patch *patch)4063{4064char*path = patch->new_name;4065unsigned mode = patch->new_mode;4066unsigned long size = patch->resultsize;4067char*buf = patch->result;40684069if(!mode)4070 mode = S_IFREG |0644;4071create_one_file(path, mode, buf, size);40724073if(patch->conflicted_threeway)4074add_conflicted_stages_file(patch);4075else4076add_index_file(path, mode, buf, size);4077}40784079/* phase zero is to remove, phase one is to create */4080static voidwrite_out_one_result(struct patch *patch,int phase)4081{4082if(patch->is_delete >0) {4083if(phase ==0)4084remove_file(patch,1);4085return;4086}4087if(patch->is_new >0|| patch->is_copy) {4088if(phase ==1)4089create_file(patch);4090return;4091}4092/*4093 * Rename or modification boils down to the same4094 * thing: remove the old, write the new4095 */4096if(phase ==0)4097remove_file(patch, patch->is_rename);4098if(phase ==1)4099create_file(patch);4100}41014102static intwrite_out_one_reject(struct patch *patch)4103{4104FILE*rej;4105char namebuf[PATH_MAX];4106struct fragment *frag;4107int cnt =0;4108struct strbuf sb = STRBUF_INIT;41094110for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4111if(!frag->rejected)4112continue;4113 cnt++;4114}41154116if(!cnt) {4117if(apply_verbosely)4118say_patch_name(stderr,4119_("Applied patch%scleanly."), patch);4120return0;4121}41224123/* This should not happen, because a removal patch that leaves4124 * contents are marked "rejected" at the patch level.4125 */4126if(!patch->new_name)4127die(_("internal error"));41284129/* Say this even without --verbose */4130strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4131"Applying patch %%swith%drejects...",4132 cnt),4133 cnt);4134say_patch_name(stderr, sb.buf, patch);4135strbuf_release(&sb);41364137 cnt =strlen(patch->new_name);4138if(ARRAY_SIZE(namebuf) <= cnt +5) {4139 cnt =ARRAY_SIZE(namebuf) -5;4140warning(_("truncating .rej filename to %.*s.rej"),4141 cnt -1, patch->new_name);4142}4143memcpy(namebuf, patch->new_name, cnt);4144memcpy(namebuf + cnt,".rej",5);41454146 rej =fopen(namebuf,"w");4147if(!rej)4148returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));41494150/* Normal git tools never deal with .rej, so do not pretend4151 * this is a git patch by saying --git or giving extended4152 * headers. While at it, maybe please "kompare" that wants4153 * the trailing TAB and some garbage at the end of line ;-).4154 */4155fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4156 patch->new_name, patch->new_name);4157for(cnt =1, frag = patch->fragments;4158 frag;4159 cnt++, frag = frag->next) {4160if(!frag->rejected) {4161fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4162continue;4163}4164fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4165fprintf(rej,"%.*s", frag->size, frag->patch);4166if(frag->patch[frag->size-1] !='\n')4167fputc('\n', rej);4168}4169fclose(rej);4170return-1;4171}41724173static intwrite_out_results(struct patch *list)4174{4175int phase;4176int errs =0;4177struct patch *l;4178struct string_list cpath = STRING_LIST_INIT_DUP;41794180for(phase =0; phase <2; phase++) {4181 l = list;4182while(l) {4183if(l->rejected)4184 errs =1;4185else{4186write_out_one_result(l, phase);4187if(phase ==1) {4188if(write_out_one_reject(l))4189 errs =1;4190if(l->conflicted_threeway) {4191string_list_append(&cpath, l->new_name);4192 errs =1;4193}4194}4195}4196 l = l->next;4197}4198}41994200if(cpath.nr) {4201struct string_list_item *item;42024203string_list_sort(&cpath);4204for_each_string_list_item(item, &cpath)4205fprintf(stderr,"U%s\n", item->string);4206string_list_clear(&cpath,0);42074208rerere(0);4209}42104211return errs;4212}42134214static struct lock_file lock_file;42154216#define INACCURATE_EOF (1<<0)4217#define RECOUNT (1<<1)42184219static intapply_patch(int fd,const char*filename,int options)4220{4221size_t offset;4222struct strbuf buf = STRBUF_INIT;/* owns the patch text */4223struct patch *list = NULL, **listp = &list;4224int skipped_patch =0;42254226 patch_input_file = filename;4227read_patch_file(&buf, fd);4228 offset =0;4229while(offset < buf.len) {4230struct patch *patch;4231int nr;42324233 patch =xcalloc(1,sizeof(*patch));4234 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4235 patch->recount = !!(options & RECOUNT);4236 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);4237if(nr <0)4238break;4239if(apply_in_reverse)4240reverse_patches(patch);4241if(use_patch(patch)) {4242patch_stats(patch);4243*listp = patch;4244 listp = &patch->next;4245}4246else{4247free_patch(patch);4248 skipped_patch++;4249}4250 offset += nr;4251}42524253if(!list && !skipped_patch)4254die(_("unrecognized input"));42554256if(whitespace_error && (ws_error_action == die_on_ws_error))4257 apply =0;42584259 update_index = check_index && apply;4260if(update_index && newfd <0)4261 newfd =hold_locked_index(&lock_file,1);42624263if(check_index) {4264if(read_cache() <0)4265die(_("unable to read index file"));4266}42674268if((check || apply) &&4269check_patch_list(list) <0&&4270!apply_with_reject)4271exit(1);42724273if(apply &&write_out_results(list)) {4274if(apply_with_reject)4275exit(1);4276/* with --3way, we still need to write the index out */4277return1;4278}42794280if(fake_ancestor)4281build_fake_ancestor(list, fake_ancestor);42824283if(diffstat)4284stat_patch_list(list);42854286if(numstat)4287numstat_patch_list(list);42884289if(summary)4290summary_patch_list(list);42914292free_patch_list(list);4293strbuf_release(&buf);4294string_list_clear(&fn_table,0);4295return0;4296}42974298static voidgit_apply_config(void)4299{4300git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4301git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4302git_config(git_default_config, NULL);4303}43044305static intoption_parse_exclude(const struct option *opt,4306const char*arg,int unset)4307{4308add_name_limit(arg,1);4309return0;4310}43114312static intoption_parse_include(const struct option *opt,4313const char*arg,int unset)4314{4315add_name_limit(arg,0);4316 has_include =1;4317return0;4318}43194320static intoption_parse_p(const struct option *opt,4321const char*arg,int unset)4322{4323 p_value =atoi(arg);4324 p_value_known =1;4325return0;4326}43274328static intoption_parse_z(const struct option *opt,4329const char*arg,int unset)4330{4331if(unset)4332 line_termination ='\n';4333else4334 line_termination =0;4335return0;4336}43374338static intoption_parse_space_change(const struct option *opt,4339const char*arg,int unset)4340{4341if(unset)4342 ws_ignore_action = ignore_ws_none;4343else4344 ws_ignore_action = ignore_ws_change;4345return0;4346}43474348static intoption_parse_whitespace(const struct option *opt,4349const char*arg,int unset)4350{4351const char**whitespace_option = opt->value;43524353*whitespace_option = arg;4354parse_whitespace_option(arg);4355return0;4356}43574358static intoption_parse_directory(const struct option *opt,4359const char*arg,int unset)4360{4361 root_len =strlen(arg);4362if(root_len && arg[root_len -1] !='/') {4363char*new_root;4364 root = new_root =xmalloc(root_len +2);4365strcpy(new_root, arg);4366strcpy(new_root + root_len++,"/");4367}else4368 root = arg;4369return0;4370}43714372intcmd_apply(int argc,const char**argv,const char*prefix_)4373{4374int i;4375int errs =0;4376int is_not_gitdir = !startup_info->have_repository;4377int force_apply =0;43784379const char*whitespace_option = NULL;43804381struct option builtin_apply_options[] = {4382{ OPTION_CALLBACK,0,"exclude", NULL,N_("path"),4383N_("don't apply changes matching the given path"),43840, option_parse_exclude },4385{ OPTION_CALLBACK,0,"include", NULL,N_("path"),4386N_("apply changes matching the given path"),43870, option_parse_include },4388{ OPTION_CALLBACK,'p', NULL, NULL,N_("num"),4389N_("remove <num> leading slashes from traditional diff paths"),43900, option_parse_p },4391OPT_BOOL(0,"no-add", &no_add,4392N_("ignore additions made by the patch")),4393OPT_BOOL(0,"stat", &diffstat,4394N_("instead of applying the patch, output diffstat for the input")),4395OPT_NOOP_NOARG(0,"allow-binary-replacement"),4396OPT_NOOP_NOARG(0,"binary"),4397OPT_BOOL(0,"numstat", &numstat,4398N_("show number of added and deleted lines in decimal notation")),4399OPT_BOOL(0,"summary", &summary,4400N_("instead of applying the patch, output a summary for the input")),4401OPT_BOOL(0,"check", &check,4402N_("instead of applying the patch, see if the patch is applicable")),4403OPT_BOOL(0,"index", &check_index,4404N_("make sure the patch is applicable to the current index")),4405OPT_BOOL(0,"cached", &cached,4406N_("apply a patch without touching the working tree")),4407OPT_BOOL(0,"apply", &force_apply,4408N_("also apply the patch (use with --stat/--summary/--check)")),4409OPT_BOOL('3',"3way", &threeway,4410N_("attempt three-way merge if a patch does not apply")),4411OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,4412N_("build a temporary index based on embedded index information")),4413{ OPTION_CALLBACK,'z', NULL, NULL, NULL,4414N_("paths are separated with NUL character"),4415 PARSE_OPT_NOARG, option_parse_z },4416OPT_INTEGER('C', NULL, &p_context,4417N_("ensure at least <n> lines of context match")),4418{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,N_("action"),4419N_("detect new or modified lines that have whitespace errors"),44200, option_parse_whitespace },4421{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,4422N_("ignore changes in whitespace when finding context"),4423 PARSE_OPT_NOARG, option_parse_space_change },4424{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,4425N_("ignore changes in whitespace when finding context"),4426 PARSE_OPT_NOARG, option_parse_space_change },4427OPT_BOOL('R',"reverse", &apply_in_reverse,4428N_("apply the patch in reverse")),4429OPT_BOOL(0,"unidiff-zero", &unidiff_zero,4430N_("don't expect at least one line of context")),4431OPT_BOOL(0,"reject", &apply_with_reject,4432N_("leave the rejected hunks in corresponding *.rej files")),4433OPT_BOOL(0,"allow-overlap", &allow_overlap,4434N_("allow overlapping hunks")),4435OPT__VERBOSE(&apply_verbosely,N_("be verbose")),4436OPT_BIT(0,"inaccurate-eof", &options,4437N_("tolerate incorrectly detected missing new-line at the end of file"),4438 INACCURATE_EOF),4439OPT_BIT(0,"recount", &options,4440N_("do not trust the line counts in the hunk headers"),4441 RECOUNT),4442{ OPTION_CALLBACK,0,"directory", NULL,N_("root"),4443N_("prepend <root> to all filenames"),44440, option_parse_directory },4445OPT_END()4446};44474448 prefix = prefix_;4449 prefix_length = prefix ?strlen(prefix) :0;4450git_apply_config();4451if(apply_default_whitespace)4452parse_whitespace_option(apply_default_whitespace);4453if(apply_default_ignorewhitespace)4454parse_ignorewhitespace_option(apply_default_ignorewhitespace);44554456 argc =parse_options(argc, argv, prefix, builtin_apply_options,4457 apply_usage,0);44584459if(apply_with_reject && threeway)4460die("--reject and --3way cannot be used together.");4461if(cached && threeway)4462die("--cached and --3way cannot be used together.");4463if(threeway) {4464if(is_not_gitdir)4465die(_("--3way outside a repository"));4466 check_index =1;4467}4468if(apply_with_reject)4469 apply = apply_verbosely =1;4470if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))4471 apply =0;4472if(check_index && is_not_gitdir)4473die(_("--index outside a repository"));4474if(cached) {4475if(is_not_gitdir)4476die(_("--cached outside a repository"));4477 check_index =1;4478}4479for(i =0; i < argc; i++) {4480const char*arg = argv[i];4481int fd;44824483if(!strcmp(arg,"-")) {4484 errs |=apply_patch(0,"<stdin>", options);4485 read_stdin =0;4486continue;4487}else if(0< prefix_length)4488 arg =prefix_filename(prefix, prefix_length, arg);44894490 fd =open(arg, O_RDONLY);4491if(fd <0)4492die_errno(_("can't open patch '%s'"), arg);4493 read_stdin =0;4494set_default_whitespace_mode(whitespace_option);4495 errs |=apply_patch(fd, arg, options);4496close(fd);4497}4498set_default_whitespace_mode(whitespace_option);4499if(read_stdin)4500 errs |=apply_patch(0,"<stdin>", options);4501if(whitespace_error) {4502if(squelch_whitespace_errors &&4503 squelch_whitespace_errors < whitespace_error) {4504int squelched =4505 whitespace_error - squelch_whitespace_errors;4506warning(Q_("squelched%dwhitespace error",4507"squelched%dwhitespace errors",4508 squelched),4509 squelched);4510}4511if(ws_error_action == die_on_ws_error)4512die(Q_("%dline adds whitespace errors.",4513"%dlines add whitespace errors.",4514 whitespace_error),4515 whitespace_error);4516if(applied_after_fixing_ws && apply)4517warning("%dline%sapplied after"4518" fixing whitespace errors.",4519 applied_after_fixing_ws,4520 applied_after_fixing_ws ==1?"":"s");4521else if(whitespace_error)4522warning(Q_("%dline adds whitespace errors.",4523"%dlines add whitespace errors.",4524 whitespace_error),4525 whitespace_error);4526}45274528if(update_index) {4529if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK))4530die(_("Unable to write new index file"));4531}45324533return!!errs;4534}