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 int unsafe_paths; 55static const char*fake_ancestor; 56static int line_termination ='\n'; 57static unsigned int p_context = UINT_MAX; 58static const char*const apply_usage[] = { 59N_("git apply [<options>] [<patch>...]"), 60 NULL 61}; 62 63static enum ws_error_action { 64 nowarn_ws_error, 65 warn_on_ws_error, 66 die_on_ws_error, 67 correct_ws_error 68} ws_error_action = warn_on_ws_error; 69static int whitespace_error; 70static int squelch_whitespace_errors =5; 71static int applied_after_fixing_ws; 72 73static enum ws_ignore { 74 ignore_ws_none, 75 ignore_ws_change 76} ws_ignore_action = ignore_ws_none; 77 78 79static const char*patch_input_file; 80static struct strbuf root = STRBUF_INIT; 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 */ 210struct object_id threeway_stage[3]; 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.len) 497strbuf_insert(&name,0, root.buf, 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.len) { 700char*ret =xstrfmt("%s%.*s", root.buf, len, start); 701returnsquash_slash(ret); 702} 703 704returnsquash_slash(xmemdupz(start, len)); 705} 706 707static char*find_name(const char*line,char*def,int p_value,int terminate) 708{ 709if(*line =='"') { 710char*name =find_name_gnu(line, def, p_value); 711if(name) 712return name; 713} 714 715returnfind_name_common(line, def, p_value, NULL, terminate); 716} 717 718static char*find_name_traditional(const char*line,char*def,int p_value) 719{ 720size_t len; 721size_t date_len; 722 723if(*line =='"') { 724char*name =find_name_gnu(line, def, p_value); 725if(name) 726return name; 727} 728 729 len =strchrnul(line,'\n') - line; 730 date_len =diff_timestamp_len(line, len); 731if(!date_len) 732returnfind_name_common(line, def, p_value, NULL, TERM_TAB); 733 len -= date_len; 734 735returnfind_name_common(line, def, p_value, line + len,0); 736} 737 738static intcount_slashes(const char*cp) 739{ 740int cnt =0; 741char ch; 742 743while((ch = *cp++)) 744if(ch =='/') 745 cnt++; 746return cnt; 747} 748 749/* 750 * Given the string after "--- " or "+++ ", guess the appropriate 751 * p_value for the given patch. 752 */ 753static intguess_p_value(const char*nameline) 754{ 755char*name, *cp; 756int val = -1; 757 758if(is_dev_null(nameline)) 759return-1; 760 name =find_name_traditional(nameline, NULL,0); 761if(!name) 762return-1; 763 cp =strchr(name,'/'); 764if(!cp) 765 val =0; 766else if(prefix) { 767/* 768 * Does it begin with "a/$our-prefix" and such? Then this is 769 * very likely to apply to our directory. 770 */ 771if(!strncmp(name, prefix, prefix_length)) 772 val =count_slashes(prefix); 773else{ 774 cp++; 775if(!strncmp(cp, prefix, prefix_length)) 776 val =count_slashes(prefix) +1; 777} 778} 779free(name); 780return val; 781} 782 783/* 784 * Does the ---/+++ line have the POSIX timestamp after the last HT? 785 * GNU diff puts epoch there to signal a creation/deletion event. Is 786 * this such a timestamp? 787 */ 788static inthas_epoch_timestamp(const char*nameline) 789{ 790/* 791 * We are only interested in epoch timestamp; any non-zero 792 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 793 * For the same reason, the date must be either 1969-12-31 or 794 * 1970-01-01, and the seconds part must be "00". 795 */ 796const char stamp_regexp[] = 797"^(1969-12-31|1970-01-01)" 798" " 799"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 800" " 801"([-+][0-2][0-9]:?[0-5][0-9])\n"; 802const char*timestamp = NULL, *cp, *colon; 803static regex_t *stamp; 804 regmatch_t m[10]; 805int zoneoffset; 806int hourminute; 807int status; 808 809for(cp = nameline; *cp !='\n'; cp++) { 810if(*cp =='\t') 811 timestamp = cp +1; 812} 813if(!timestamp) 814return0; 815if(!stamp) { 816 stamp =xmalloc(sizeof(*stamp)); 817if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 818warning(_("Cannot prepare timestamp regexp%s"), 819 stamp_regexp); 820return0; 821} 822} 823 824 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 825if(status) { 826if(status != REG_NOMATCH) 827warning(_("regexec returned%dfor input:%s"), 828 status, timestamp); 829return0; 830} 831 832 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 833if(*colon ==':') 834 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 835else 836 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 837if(timestamp[m[3].rm_so] =='-') 838 zoneoffset = -zoneoffset; 839 840/* 841 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 842 * (west of GMT) or 1970-01-01 (east of GMT) 843 */ 844if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 845(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 846return0; 847 848 hourminute = (strtol(timestamp +11, NULL,10) *60+ 849strtol(timestamp +14, NULL,10) - 850 zoneoffset); 851 852return((zoneoffset <0&& hourminute ==1440) || 853(0<= zoneoffset && !hourminute)); 854} 855 856/* 857 * Get the name etc info from the ---/+++ lines of a traditional patch header 858 * 859 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 860 * files, we can happily check the index for a match, but for creating a 861 * new file we should try to match whatever "patch" does. I have no idea. 862 */ 863static voidparse_traditional_patch(const char*first,const char*second,struct patch *patch) 864{ 865char*name; 866 867 first +=4;/* skip "--- " */ 868 second +=4;/* skip "+++ " */ 869if(!p_value_known) { 870int p, q; 871 p =guess_p_value(first); 872 q =guess_p_value(second); 873if(p <0) p = q; 874if(0<= p && p == q) { 875 p_value = p; 876 p_value_known =1; 877} 878} 879if(is_dev_null(first)) { 880 patch->is_new =1; 881 patch->is_delete =0; 882 name =find_name_traditional(second, NULL, p_value); 883 patch->new_name = name; 884}else if(is_dev_null(second)) { 885 patch->is_new =0; 886 patch->is_delete =1; 887 name =find_name_traditional(first, NULL, p_value); 888 patch->old_name = name; 889}else{ 890char*first_name; 891 first_name =find_name_traditional(first, NULL, p_value); 892 name =find_name_traditional(second, first_name, p_value); 893free(first_name); 894if(has_epoch_timestamp(first)) { 895 patch->is_new =1; 896 patch->is_delete =0; 897 patch->new_name = name; 898}else if(has_epoch_timestamp(second)) { 899 patch->is_new =0; 900 patch->is_delete =1; 901 patch->old_name = name; 902}else{ 903 patch->old_name = name; 904 patch->new_name =xstrdup_or_null(name); 905} 906} 907if(!name) 908die(_("unable to find filename in patch at line%d"), linenr); 909} 910 911static intgitdiff_hdrend(const char*line,struct patch *patch) 912{ 913return-1; 914} 915 916/* 917 * We're anal about diff header consistency, to make 918 * sure that we don't end up having strange ambiguous 919 * patches floating around. 920 * 921 * As a result, gitdiff_{old|new}name() will check 922 * their names against any previous information, just 923 * to make sure.. 924 */ 925#define DIFF_OLD_NAME 0 926#define DIFF_NEW_NAME 1 927 928static char*gitdiff_verify_name(const char*line,int isnull,char*orig_name,int side) 929{ 930if(!orig_name && !isnull) 931returnfind_name(line, NULL, p_value, TERM_TAB); 932 933if(orig_name) { 934int len =strlen(orig_name); 935char*another; 936if(isnull) 937die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 938 orig_name, linenr); 939 another =find_name(line, NULL, p_value, TERM_TAB); 940if(!another ||memcmp(another, orig_name, len +1)) 941die((side == DIFF_NEW_NAME) ? 942_("git apply: bad git-diff - inconsistent new filename on line%d") : 943_("git apply: bad git-diff - inconsistent old filename on line%d"), linenr); 944free(another); 945return orig_name; 946}else{ 947/* expect "/dev/null" */ 948if(memcmp("/dev/null", line,9) || line[9] !='\n') 949die(_("git apply: bad git-diff - expected /dev/null on line%d"), linenr); 950return NULL; 951} 952} 953 954static intgitdiff_oldname(const char*line,struct patch *patch) 955{ 956 patch->old_name =gitdiff_verify_name(line, patch->is_new, patch->old_name, 957 DIFF_OLD_NAME); 958return0; 959} 960 961static intgitdiff_newname(const char*line,struct patch *patch) 962{ 963 patch->new_name =gitdiff_verify_name(line, patch->is_delete, patch->new_name, 964 DIFF_NEW_NAME); 965return0; 966} 967 968static intgitdiff_oldmode(const char*line,struct patch *patch) 969{ 970 patch->old_mode =strtoul(line, NULL,8); 971return0; 972} 973 974static intgitdiff_newmode(const char*line,struct patch *patch) 975{ 976 patch->new_mode =strtoul(line, NULL,8); 977return0; 978} 979 980static intgitdiff_delete(const char*line,struct patch *patch) 981{ 982 patch->is_delete =1; 983free(patch->old_name); 984 patch->old_name =xstrdup_or_null(patch->def_name); 985returngitdiff_oldmode(line, patch); 986} 987 988static intgitdiff_newfile(const char*line,struct patch *patch) 989{ 990 patch->is_new =1; 991free(patch->new_name); 992 patch->new_name =xstrdup_or_null(patch->def_name); 993returngitdiff_newmode(line, patch); 994} 995 996static intgitdiff_copysrc(const char*line,struct patch *patch) 997{ 998 patch->is_copy =1; 999free(patch->old_name);1000 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0);1001return0;1002}10031004static intgitdiff_copydst(const char*line,struct patch *patch)1005{1006 patch->is_copy =1;1007free(patch->new_name);1008 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0);1009return0;1010}10111012static intgitdiff_renamesrc(const char*line,struct patch *patch)1013{1014 patch->is_rename =1;1015free(patch->old_name);1016 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0);1017return0;1018}10191020static intgitdiff_renamedst(const char*line,struct patch *patch)1021{1022 patch->is_rename =1;1023free(patch->new_name);1024 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0);1025return0;1026}10271028static intgitdiff_similarity(const char*line,struct patch *patch)1029{1030unsigned long val =strtoul(line, NULL,10);1031if(val <=100)1032 patch->score = val;1033return0;1034}10351036static intgitdiff_dissimilarity(const char*line,struct patch *patch)1037{1038unsigned long val =strtoul(line, NULL,10);1039if(val <=100)1040 patch->score = val;1041return0;1042}10431044static intgitdiff_index(const char*line,struct patch *patch)1045{1046/*1047 * index line is N hexadecimal, "..", N hexadecimal,1048 * and optional space with octal mode.1049 */1050const char*ptr, *eol;1051int len;10521053 ptr =strchr(line,'.');1054if(!ptr || ptr[1] !='.'||40< ptr - line)1055return0;1056 len = ptr - line;1057memcpy(patch->old_sha1_prefix, line, len);1058 patch->old_sha1_prefix[len] =0;10591060 line = ptr +2;1061 ptr =strchr(line,' ');1062 eol =strchrnul(line,'\n');10631064if(!ptr || eol < ptr)1065 ptr = eol;1066 len = ptr - line;10671068if(40< len)1069return0;1070memcpy(patch->new_sha1_prefix, line, len);1071 patch->new_sha1_prefix[len] =0;1072if(*ptr ==' ')1073 patch->old_mode =strtoul(ptr+1, NULL,8);1074return0;1075}10761077/*1078 * This is normal for a diff that doesn't change anything: we'll fall through1079 * into the next diff. Tell the parser to break out.1080 */1081static intgitdiff_unrecognized(const char*line,struct patch *patch)1082{1083return-1;1084}10851086/*1087 * Skip p_value leading components from "line"; as we do not accept1088 * absolute paths, return NULL in that case.1089 */1090static const char*skip_tree_prefix(const char*line,int llen)1091{1092int nslash;1093int i;10941095if(!p_value)1096return(llen && line[0] =='/') ? NULL : line;10971098 nslash = p_value;1099for(i =0; i < llen; i++) {1100int ch = line[i];1101if(ch =='/'&& --nslash <=0)1102return(i ==0) ? NULL : &line[i +1];1103}1104return NULL;1105}11061107/*1108 * This is to extract the same name that appears on "diff --git"1109 * line. We do not find and return anything if it is a rename1110 * patch, and it is OK because we will find the name elsewhere.1111 * We need to reliably find name only when it is mode-change only,1112 * creation or deletion of an empty file. In any of these cases,1113 * both sides are the same name under a/ and b/ respectively.1114 */1115static char*git_header_name(const char*line,int llen)1116{1117const char*name;1118const char*second = NULL;1119size_t len, line_len;11201121 line +=strlen("diff --git ");1122 llen -=strlen("diff --git ");11231124if(*line =='"') {1125const char*cp;1126struct strbuf first = STRBUF_INIT;1127struct strbuf sp = STRBUF_INIT;11281129if(unquote_c_style(&first, line, &second))1130goto free_and_fail1;11311132/* strip the a/b prefix including trailing slash */1133 cp =skip_tree_prefix(first.buf, first.len);1134if(!cp)1135goto free_and_fail1;1136strbuf_remove(&first,0, cp - first.buf);11371138/*1139 * second points at one past closing dq of name.1140 * find the second name.1141 */1142while((second < line + llen) &&isspace(*second))1143 second++;11441145if(line + llen <= second)1146goto free_and_fail1;1147if(*second =='"') {1148if(unquote_c_style(&sp, second, NULL))1149goto free_and_fail1;1150 cp =skip_tree_prefix(sp.buf, sp.len);1151if(!cp)1152goto free_and_fail1;1153/* They must match, otherwise ignore */1154if(strcmp(cp, first.buf))1155goto free_and_fail1;1156strbuf_release(&sp);1157returnstrbuf_detach(&first, NULL);1158}11591160/* unquoted second */1161 cp =skip_tree_prefix(second, line + llen - second);1162if(!cp)1163goto free_and_fail1;1164if(line + llen - cp != first.len ||1165memcmp(first.buf, cp, first.len))1166goto free_and_fail1;1167returnstrbuf_detach(&first, NULL);11681169 free_and_fail1:1170strbuf_release(&first);1171strbuf_release(&sp);1172return NULL;1173}11741175/* unquoted first name */1176 name =skip_tree_prefix(line, llen);1177if(!name)1178return NULL;11791180/*1181 * since the first name is unquoted, a dq if exists must be1182 * the beginning of the second name.1183 */1184for(second = name; second < line + llen; second++) {1185if(*second =='"') {1186struct strbuf sp = STRBUF_INIT;1187const char*np;11881189if(unquote_c_style(&sp, second, NULL))1190goto free_and_fail2;11911192 np =skip_tree_prefix(sp.buf, sp.len);1193if(!np)1194goto free_and_fail2;11951196 len = sp.buf + sp.len - np;1197if(len < second - name &&1198!strncmp(np, name, len) &&1199isspace(name[len])) {1200/* Good */1201strbuf_remove(&sp,0, np - sp.buf);1202returnstrbuf_detach(&sp, NULL);1203}12041205 free_and_fail2:1206strbuf_release(&sp);1207return NULL;1208}1209}12101211/*1212 * Accept a name only if it shows up twice, exactly the same1213 * form.1214 */1215 second =strchr(name,'\n');1216if(!second)1217return NULL;1218 line_len = second - name;1219for(len =0; ; len++) {1220switch(name[len]) {1221default:1222continue;1223case'\n':1224return NULL;1225case'\t':case' ':1226/*1227 * Is this the separator between the preimage1228 * and the postimage pathname? Again, we are1229 * only interested in the case where there is1230 * no rename, as this is only to set def_name1231 * and a rename patch has the names elsewhere1232 * in an unambiguous form.1233 */1234if(!name[len +1])1235return NULL;/* no postimage name */1236 second =skip_tree_prefix(name + len +1,1237 line_len - (len +1));1238if(!second)1239return NULL;1240/*1241 * Does len bytes starting at "name" and "second"1242 * (that are separated by one HT or SP we just1243 * found) exactly match?1244 */1245if(second[len] =='\n'&& !strncmp(name, second, len))1246returnxmemdupz(name, len);1247}1248}1249}12501251/* Verify that we recognize the lines following a git header */1252static intparse_git_header(const char*line,int len,unsigned int size,struct patch *patch)1253{1254unsigned long offset;12551256/* A git diff has explicit new/delete information, so we don't guess */1257 patch->is_new =0;1258 patch->is_delete =0;12591260/*1261 * Some things may not have the old name in the1262 * rest of the headers anywhere (pure mode changes,1263 * or removing or adding empty files), so we get1264 * the default name from the header.1265 */1266 patch->def_name =git_header_name(line, len);1267if(patch->def_name && root.len) {1268char*s =xstrfmt("%s%s", root.buf, patch->def_name);1269free(patch->def_name);1270 patch->def_name = s;1271}12721273 line += len;1274 size -= len;1275 linenr++;1276for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) {1277static const struct opentry {1278const char*str;1279int(*fn)(const char*,struct patch *);1280} optable[] = {1281{"@@ -", gitdiff_hdrend },1282{"--- ", gitdiff_oldname },1283{"+++ ", gitdiff_newname },1284{"old mode ", gitdiff_oldmode },1285{"new mode ", gitdiff_newmode },1286{"deleted file mode ", gitdiff_delete },1287{"new file mode ", gitdiff_newfile },1288{"copy from ", gitdiff_copysrc },1289{"copy to ", gitdiff_copydst },1290{"rename old ", gitdiff_renamesrc },1291{"rename new ", gitdiff_renamedst },1292{"rename from ", gitdiff_renamesrc },1293{"rename to ", gitdiff_renamedst },1294{"similarity index ", gitdiff_similarity },1295{"dissimilarity index ", gitdiff_dissimilarity },1296{"index ", gitdiff_index },1297{"", gitdiff_unrecognized },1298};1299int i;13001301 len =linelen(line, size);1302if(!len || line[len-1] !='\n')1303break;1304for(i =0; i <ARRAY_SIZE(optable); i++) {1305const struct opentry *p = optable + i;1306int oplen =strlen(p->str);1307if(len < oplen ||memcmp(p->str, line, oplen))1308continue;1309if(p->fn(line + oplen, patch) <0)1310return offset;1311break;1312}1313}13141315return offset;1316}13171318static intparse_num(const char*line,unsigned long*p)1319{1320char*ptr;13211322if(!isdigit(*line))1323return0;1324*p =strtoul(line, &ptr,10);1325return ptr - line;1326}13271328static intparse_range(const char*line,int len,int offset,const char*expect,1329unsigned long*p1,unsigned long*p2)1330{1331int digits, ex;13321333if(offset <0|| offset >= len)1334return-1;1335 line += offset;1336 len -= offset;13371338 digits =parse_num(line, p1);1339if(!digits)1340return-1;13411342 offset += digits;1343 line += digits;1344 len -= digits;13451346*p2 =1;1347if(*line ==',') {1348 digits =parse_num(line+1, p2);1349if(!digits)1350return-1;13511352 offset += digits+1;1353 line += digits+1;1354 len -= digits+1;1355}13561357 ex =strlen(expect);1358if(ex > len)1359return-1;1360if(memcmp(line, expect, ex))1361return-1;13621363return offset + ex;1364}13651366static voidrecount_diff(const char*line,int size,struct fragment *fragment)1367{1368int oldlines =0, newlines =0, ret =0;13691370if(size <1) {1371warning("recount: ignore empty hunk");1372return;1373}13741375for(;;) {1376int len =linelen(line, size);1377 size -= len;1378 line += len;13791380if(size <1)1381break;13821383switch(*line) {1384case' ':case'\n':1385 newlines++;1386/* fall through */1387case'-':1388 oldlines++;1389continue;1390case'+':1391 newlines++;1392continue;1393case'\\':1394continue;1395case'@':1396 ret = size <3|| !starts_with(line,"@@ ");1397break;1398case'd':1399 ret = size <5|| !starts_with(line,"diff ");1400break;1401default:1402 ret = -1;1403break;1404}1405if(ret) {1406warning(_("recount: unexpected line: %.*s"),1407(int)linelen(line, size), line);1408return;1409}1410break;1411}1412 fragment->oldlines = oldlines;1413 fragment->newlines = newlines;1414}14151416/*1417 * Parse a unified diff fragment header of the1418 * form "@@ -a,b +c,d @@"1419 */1420static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1421{1422int offset;14231424if(!len || line[len-1] !='\n')1425return-1;14261427/* Figure out the number of lines in a fragment */1428 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1429 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14301431return offset;1432}14331434static intfind_header(const char*line,unsigned long size,int*hdrsize,struct patch *patch)1435{1436unsigned long offset, len;14371438 patch->is_toplevel_relative =0;1439 patch->is_rename = patch->is_copy =0;1440 patch->is_new = patch->is_delete = -1;1441 patch->old_mode = patch->new_mode =0;1442 patch->old_name = patch->new_name = NULL;1443for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) {1444unsigned long nextlen;14451446 len =linelen(line, size);1447if(!len)1448break;14491450/* Testing this early allows us to take a few shortcuts.. */1451if(len <6)1452continue;14531454/*1455 * Make sure we don't find any unconnected patch fragments.1456 * That's a sign that we didn't find a header, and that a1457 * patch has become corrupted/broken up.1458 */1459if(!memcmp("@@ -", line,4)) {1460struct fragment dummy;1461if(parse_fragment_header(line, len, &dummy) <0)1462continue;1463die(_("patch fragment without header at line%d: %.*s"),1464 linenr, (int)len-1, line);1465}14661467if(size < len +6)1468break;14691470/*1471 * Git patch? It might not have a real patch, just a rename1472 * or mode change, so we handle that specially1473 */1474if(!memcmp("diff --git ", line,11)) {1475int git_hdr_len =parse_git_header(line, len, size, patch);1476if(git_hdr_len <= len)1477continue;1478if(!patch->old_name && !patch->new_name) {1479if(!patch->def_name)1480die(Q_("git diff header lacks filename information when removing "1481"%dleading pathname component (line%d)",1482"git diff header lacks filename information when removing "1483"%dleading pathname components (line%d)",1484 p_value),1485 p_value, linenr);1486 patch->old_name =xstrdup(patch->def_name);1487 patch->new_name =xstrdup(patch->def_name);1488}1489if(!patch->is_delete && !patch->new_name)1490die("git diff header lacks filename information "1491"(line%d)", linenr);1492 patch->is_toplevel_relative =1;1493*hdrsize = git_hdr_len;1494return offset;1495}14961497/* --- followed by +++ ? */1498if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1499continue;15001501/*1502 * We only accept unified patches, so we want it to1503 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1504 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1505 */1506 nextlen =linelen(line + len, size - len);1507if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1508continue;15091510/* Ok, we'll consider it a patch */1511parse_traditional_patch(line, line+len, patch);1512*hdrsize = len + nextlen;1513 linenr +=2;1514return offset;1515}1516return-1;1517}15181519static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1520{1521char*err;15221523if(!result)1524return;15251526 whitespace_error++;1527if(squelch_whitespace_errors &&1528 squelch_whitespace_errors < whitespace_error)1529return;15301531 err =whitespace_error_string(result);1532fprintf(stderr,"%s:%d:%s.\n%.*s\n",1533 patch_input_file, linenr, err, len, line);1534free(err);1535}15361537static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1538{1539unsigned result =ws_check(line +1, len -1, ws_rule);15401541record_ws_error(result, line +1, len -2, linenr);1542}15431544/*1545 * Parse a unified diff. Note that this really needs to parse each1546 * fragment separately, since the only way to know the difference1547 * between a "---" that is part of a patch, and a "---" that starts1548 * the next patch is to look at the line counts..1549 */1550static intparse_fragment(const char*line,unsigned long size,1551struct patch *patch,struct fragment *fragment)1552{1553int added, deleted;1554int len =linelen(line, size), offset;1555unsigned long oldlines, newlines;1556unsigned long leading, trailing;15571558 offset =parse_fragment_header(line, len, fragment);1559if(offset <0)1560return-1;1561if(offset >0&& patch->recount)1562recount_diff(line + offset, size - offset, fragment);1563 oldlines = fragment->oldlines;1564 newlines = fragment->newlines;1565 leading =0;1566 trailing =0;15671568/* Parse the thing.. */1569 line += len;1570 size -= len;1571 linenr++;1572 added = deleted =0;1573for(offset = len;15740< size;1575 offset += len, size -= len, line += len, linenr++) {1576if(!oldlines && !newlines)1577break;1578 len =linelen(line, size);1579if(!len || line[len-1] !='\n')1580return-1;1581switch(*line) {1582default:1583return-1;1584case'\n':/* newer GNU diff, an empty context line */1585case' ':1586 oldlines--;1587 newlines--;1588if(!deleted && !added)1589 leading++;1590 trailing++;1591if(!apply_in_reverse &&1592 ws_error_action == correct_ws_error)1593check_whitespace(line, len, patch->ws_rule);1594break;1595case'-':1596if(apply_in_reverse &&1597 ws_error_action != nowarn_ws_error)1598check_whitespace(line, len, patch->ws_rule);1599 deleted++;1600 oldlines--;1601 trailing =0;1602break;1603case'+':1604if(!apply_in_reverse &&1605 ws_error_action != nowarn_ws_error)1606check_whitespace(line, len, patch->ws_rule);1607 added++;1608 newlines--;1609 trailing =0;1610break;16111612/*1613 * We allow "\ No newline at end of file". Depending1614 * on locale settings when the patch was produced we1615 * don't know what this line looks like. The only1616 * thing we do know is that it begins with "\ ".1617 * Checking for 12 is just for sanity check -- any1618 * l10n of "\ No newline..." is at least that long.1619 */1620case'\\':1621if(len <12||memcmp(line,"\\",2))1622return-1;1623break;1624}1625}1626if(oldlines || newlines)1627return-1;1628if(!deleted && !added)1629return-1;16301631 fragment->leading = leading;1632 fragment->trailing = trailing;16331634/*1635 * If a fragment ends with an incomplete line, we failed to include1636 * it in the above loop because we hit oldlines == newlines == 01637 * before seeing it.1638 */1639if(12< size && !memcmp(line,"\\",2))1640 offset +=linelen(line, size);16411642 patch->lines_added += added;1643 patch->lines_deleted += deleted;16441645if(0< patch->is_new && oldlines)1646returnerror(_("new file depends on old contents"));1647if(0< patch->is_delete && newlines)1648returnerror(_("deleted file still has contents"));1649return offset;1650}16511652/*1653 * We have seen "diff --git a/... b/..." header (or a traditional patch1654 * header). Read hunks that belong to this patch into fragments and hang1655 * them to the given patch structure.1656 *1657 * The (fragment->patch, fragment->size) pair points into the memory given1658 * by the caller, not a copy, when we return.1659 */1660static intparse_single_patch(const char*line,unsigned long size,struct patch *patch)1661{1662unsigned long offset =0;1663unsigned long oldlines =0, newlines =0, context =0;1664struct fragment **fragp = &patch->fragments;16651666while(size >4&& !memcmp(line,"@@ -",4)) {1667struct fragment *fragment;1668int len;16691670 fragment =xcalloc(1,sizeof(*fragment));1671 fragment->linenr = linenr;1672 len =parse_fragment(line, size, patch, fragment);1673if(len <=0)1674die(_("corrupt patch at line%d"), linenr);1675 fragment->patch = line;1676 fragment->size = len;1677 oldlines += fragment->oldlines;1678 newlines += fragment->newlines;1679 context += fragment->leading + fragment->trailing;16801681*fragp = fragment;1682 fragp = &fragment->next;16831684 offset += len;1685 line += len;1686 size -= len;1687}16881689/*1690 * If something was removed (i.e. we have old-lines) it cannot1691 * be creation, and if something was added it cannot be1692 * deletion. However, the reverse is not true; --unified=01693 * patches that only add are not necessarily creation even1694 * though they do not have any old lines, and ones that only1695 * delete are not necessarily deletion.1696 *1697 * Unfortunately, a real creation/deletion patch do _not_ have1698 * any context line by definition, so we cannot safely tell it1699 * apart with --unified=0 insanity. At least if the patch has1700 * more than one hunk it is not creation or deletion.1701 */1702if(patch->is_new <0&&1703(oldlines || (patch->fragments && patch->fragments->next)))1704 patch->is_new =0;1705if(patch->is_delete <0&&1706(newlines || (patch->fragments && patch->fragments->next)))1707 patch->is_delete =0;17081709if(0< patch->is_new && oldlines)1710die(_("new file%sdepends on old contents"), patch->new_name);1711if(0< patch->is_delete && newlines)1712die(_("deleted file%sstill has contents"), patch->old_name);1713if(!patch->is_delete && !newlines && context)1714fprintf_ln(stderr,1715_("** warning: "1716"file%sbecomes empty but is not deleted"),1717 patch->new_name);17181719return offset;1720}17211722staticinlineintmetadata_changes(struct patch *patch)1723{1724return patch->is_rename >0||1725 patch->is_copy >0||1726 patch->is_new >0||1727 patch->is_delete ||1728(patch->old_mode && patch->new_mode &&1729 patch->old_mode != patch->new_mode);1730}17311732static char*inflate_it(const void*data,unsigned long size,1733unsigned long inflated_size)1734{1735 git_zstream stream;1736void*out;1737int st;17381739memset(&stream,0,sizeof(stream));17401741 stream.next_in = (unsigned char*)data;1742 stream.avail_in = size;1743 stream.next_out = out =xmalloc(inflated_size);1744 stream.avail_out = inflated_size;1745git_inflate_init(&stream);1746 st =git_inflate(&stream, Z_FINISH);1747git_inflate_end(&stream);1748if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1749free(out);1750return NULL;1751}1752return out;1753}17541755/*1756 * Read a binary hunk and return a new fragment; fragment->patch1757 * points at an allocated memory that the caller must free, so1758 * it is marked as "->free_patch = 1".1759 */1760static struct fragment *parse_binary_hunk(char**buf_p,1761unsigned long*sz_p,1762int*status_p,1763int*used_p)1764{1765/*1766 * Expect a line that begins with binary patch method ("literal"1767 * or "delta"), followed by the length of data before deflating.1768 * a sequence of 'length-byte' followed by base-85 encoded data1769 * should follow, terminated by a newline.1770 *1771 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1772 * and we would limit the patch line to 66 characters,1773 * so one line can fit up to 13 groups that would decode1774 * to 52 bytes max. The length byte 'A'-'Z' corresponds1775 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1776 */1777int llen, used;1778unsigned long size = *sz_p;1779char*buffer = *buf_p;1780int patch_method;1781unsigned long origlen;1782char*data = NULL;1783int hunk_size =0;1784struct fragment *frag;17851786 llen =linelen(buffer, size);1787 used = llen;17881789*status_p =0;17901791if(starts_with(buffer,"delta ")) {1792 patch_method = BINARY_DELTA_DEFLATED;1793 origlen =strtoul(buffer +6, NULL,10);1794}1795else if(starts_with(buffer,"literal ")) {1796 patch_method = BINARY_LITERAL_DEFLATED;1797 origlen =strtoul(buffer +8, NULL,10);1798}1799else1800return NULL;18011802 linenr++;1803 buffer += llen;1804while(1) {1805int byte_length, max_byte_length, newsize;1806 llen =linelen(buffer, size);1807 used += llen;1808 linenr++;1809if(llen ==1) {1810/* consume the blank line */1811 buffer++;1812 size--;1813break;1814}1815/*1816 * Minimum line is "A00000\n" which is 7-byte long,1817 * and the line length must be multiple of 5 plus 2.1818 */1819if((llen <7) || (llen-2) %5)1820goto corrupt;1821 max_byte_length = (llen -2) /5*4;1822 byte_length = *buffer;1823if('A'<= byte_length && byte_length <='Z')1824 byte_length = byte_length -'A'+1;1825else if('a'<= byte_length && byte_length <='z')1826 byte_length = byte_length -'a'+27;1827else1828goto corrupt;1829/* if the input length was not multiple of 4, we would1830 * have filler at the end but the filler should never1831 * exceed 3 bytes1832 */1833if(max_byte_length < byte_length ||1834 byte_length <= max_byte_length -4)1835goto corrupt;1836 newsize = hunk_size + byte_length;1837 data =xrealloc(data, newsize);1838if(decode_85(data + hunk_size, buffer +1, byte_length))1839goto corrupt;1840 hunk_size = newsize;1841 buffer += llen;1842 size -= llen;1843}18441845 frag =xcalloc(1,sizeof(*frag));1846 frag->patch =inflate_it(data, hunk_size, origlen);1847 frag->free_patch =1;1848if(!frag->patch)1849goto corrupt;1850free(data);1851 frag->size = origlen;1852*buf_p = buffer;1853*sz_p = size;1854*used_p = used;1855 frag->binary_patch_method = patch_method;1856return frag;18571858 corrupt:1859free(data);1860*status_p = -1;1861error(_("corrupt binary patch at line%d: %.*s"),1862 linenr-1, llen-1, buffer);1863return NULL;1864}18651866/*1867 * Returns:1868 * -1 in case of error,1869 * the length of the parsed binary patch otherwise1870 */1871static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1872{1873/*1874 * We have read "GIT binary patch\n"; what follows is a line1875 * that says the patch method (currently, either "literal" or1876 * "delta") and the length of data before deflating; a1877 * sequence of 'length-byte' followed by base-85 encoded data1878 * follows.1879 *1880 * When a binary patch is reversible, there is another binary1881 * hunk in the same format, starting with patch method (either1882 * "literal" or "delta") with the length of data, and a sequence1883 * of length-byte + base-85 encoded data, terminated with another1884 * empty line. This data, when applied to the postimage, produces1885 * the preimage.1886 */1887struct fragment *forward;1888struct fragment *reverse;1889int status;1890int used, used_1;18911892 forward =parse_binary_hunk(&buffer, &size, &status, &used);1893if(!forward && !status)1894/* there has to be one hunk (forward hunk) */1895returnerror(_("unrecognized binary patch at line%d"), linenr-1);1896if(status)1897/* otherwise we already gave an error message */1898return status;18991900 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1901if(reverse)1902 used += used_1;1903else if(status) {1904/*1905 * Not having reverse hunk is not an error, but having1906 * a corrupt reverse hunk is.1907 */1908free((void*) forward->patch);1909free(forward);1910return status;1911}1912 forward->next = reverse;1913 patch->fragments = forward;1914 patch->is_binary =1;1915return used;1916}19171918static voidprefix_one(char**name)1919{1920char*old_name = *name;1921if(!old_name)1922return;1923*name =xstrdup(prefix_filename(prefix, prefix_length, *name));1924free(old_name);1925}19261927static voidprefix_patch(struct patch *p)1928{1929if(!prefix || p->is_toplevel_relative)1930return;1931prefix_one(&p->new_name);1932prefix_one(&p->old_name);1933}19341935/*1936 * include/exclude1937 */19381939static struct string_list limit_by_name;1940static int has_include;1941static voidadd_name_limit(const char*name,int exclude)1942{1943struct string_list_item *it;19441945 it =string_list_append(&limit_by_name, name);1946 it->util = exclude ? NULL : (void*)1;1947}19481949static intuse_patch(struct patch *p)1950{1951const char*pathname = p->new_name ? p->new_name : p->old_name;1952int i;19531954/* Paths outside are not touched regardless of "--include" */1955if(0< prefix_length) {1956int pathlen =strlen(pathname);1957if(pathlen <= prefix_length ||1958memcmp(prefix, pathname, prefix_length))1959return0;1960}19611962/* See if it matches any of exclude/include rule */1963for(i =0; i < limit_by_name.nr; i++) {1964struct string_list_item *it = &limit_by_name.items[i];1965if(!wildmatch(it->string, pathname,0, NULL))1966return(it->util != NULL);1967}19681969/*1970 * If we had any include, a path that does not match any rule is1971 * not used. Otherwise, we saw bunch of exclude rules (or none)1972 * and such a path is used.1973 */1974return!has_include;1975}197619771978/*1979 * Read the patch text in "buffer" that extends for "size" bytes; stop1980 * reading after seeing a single patch (i.e. changes to a single file).1981 * Create fragments (i.e. patch hunks) and hang them to the given patch.1982 * Return the number of bytes consumed, so that the caller can call us1983 * again for the next patch.1984 */1985static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1986{1987int hdrsize, patchsize;1988int offset =find_header(buffer, size, &hdrsize, patch);19891990if(offset <0)1991return offset;19921993prefix_patch(patch);19941995if(!use_patch(patch))1996 patch->ws_rule =0;1997else1998 patch->ws_rule =whitespace_rule(patch->new_name1999? patch->new_name2000: patch->old_name);20012002 patchsize =parse_single_patch(buffer + offset + hdrsize,2003 size - offset - hdrsize, patch);20042005if(!patchsize) {2006static const char git_binary[] ="GIT binary patch\n";2007int hd = hdrsize + offset;2008unsigned long llen =linelen(buffer + hd, size - hd);20092010if(llen ==sizeof(git_binary) -1&&2011!memcmp(git_binary, buffer + hd, llen)) {2012int used;2013 linenr++;2014 used =parse_binary(buffer + hd + llen,2015 size - hd - llen, patch);2016if(used <0)2017return-1;2018if(used)2019 patchsize = used + llen;2020else2021 patchsize =0;2022}2023else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2024static const char*binhdr[] = {2025"Binary files ",2026"Files ",2027 NULL,2028};2029int i;2030for(i =0; binhdr[i]; i++) {2031int len =strlen(binhdr[i]);2032if(len < size - hd &&2033!memcmp(binhdr[i], buffer + hd, len)) {2034 linenr++;2035 patch->is_binary =1;2036 patchsize = llen;2037break;2038}2039}2040}20412042/* Empty patch cannot be applied if it is a text patch2043 * without metadata change. A binary patch appears2044 * empty to us here.2045 */2046if((apply || check) &&2047(!patch->is_binary && !metadata_changes(patch)))2048die(_("patch with only garbage at line%d"), linenr);2049}20502051return offset + hdrsize + patchsize;2052}20532054#define swap(a,b) myswap((a),(b),sizeof(a))20552056#define myswap(a, b, size) do { \2057 unsigned char mytmp[size]; \2058 memcpy(mytmp, &a, size); \2059 memcpy(&a, &b, size); \2060 memcpy(&b, mytmp, size); \2061} while (0)20622063static voidreverse_patches(struct patch *p)2064{2065for(; p; p = p->next) {2066struct fragment *frag = p->fragments;20672068swap(p->new_name, p->old_name);2069swap(p->new_mode, p->old_mode);2070swap(p->is_new, p->is_delete);2071swap(p->lines_added, p->lines_deleted);2072swap(p->old_sha1_prefix, p->new_sha1_prefix);20732074for(; frag; frag = frag->next) {2075swap(frag->newpos, frag->oldpos);2076swap(frag->newlines, frag->oldlines);2077}2078}2079}20802081static const char pluses[] =2082"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2083static const char minuses[]=2084"----------------------------------------------------------------------";20852086static voidshow_stats(struct patch *patch)2087{2088struct strbuf qname = STRBUF_INIT;2089char*cp = patch->new_name ? patch->new_name : patch->old_name;2090int max, add, del;20912092quote_c_style(cp, &qname, NULL,0);20932094/*2095 * "scale" the filename2096 */2097 max = max_len;2098if(max >50)2099 max =50;21002101if(qname.len > max) {2102 cp =strchr(qname.buf + qname.len +3- max,'/');2103if(!cp)2104 cp = qname.buf + qname.len +3- max;2105strbuf_splice(&qname,0, cp - qname.buf,"...",3);2106}21072108if(patch->is_binary) {2109printf(" %-*s | Bin\n", max, qname.buf);2110strbuf_release(&qname);2111return;2112}21132114printf(" %-*s |", max, qname.buf);2115strbuf_release(&qname);21162117/*2118 * scale the add/delete2119 */2120 max = max + max_change >70?70- max : max_change;2121 add = patch->lines_added;2122 del = patch->lines_deleted;21232124if(max_change >0) {2125int total = ((add + del) * max + max_change /2) / max_change;2126 add = (add * max + max_change /2) / max_change;2127 del = total - add;2128}2129printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2130 add, pluses, del, minuses);2131}21322133static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2134{2135switch(st->st_mode & S_IFMT) {2136case S_IFLNK:2137if(strbuf_readlink(buf, path, st->st_size) <0)2138returnerror(_("unable to read symlink%s"), path);2139return0;2140case S_IFREG:2141if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2142returnerror(_("unable to open or read%s"), path);2143convert_to_git(path, buf->buf, buf->len, buf,0);2144return0;2145default:2146return-1;2147}2148}21492150/*2151 * Update the preimage, and the common lines in postimage,2152 * from buffer buf of length len. If postlen is 0 the postimage2153 * is updated in place, otherwise it's updated on a new buffer2154 * of length postlen2155 */21562157static voidupdate_pre_post_images(struct image *preimage,2158struct image *postimage,2159char*buf,2160size_t len,size_t postlen)2161{2162int i, ctx, reduced;2163char*new, *old, *fixed;2164struct image fixed_preimage;21652166/*2167 * Update the preimage with whitespace fixes. Note that we2168 * are not losing preimage->buf -- apply_one_fragment() will2169 * free "oldlines".2170 */2171prepare_image(&fixed_preimage, buf, len,1);2172assert(postlen2173? fixed_preimage.nr == preimage->nr2174: fixed_preimage.nr <= preimage->nr);2175for(i =0; i < fixed_preimage.nr; i++)2176 fixed_preimage.line[i].flag = preimage->line[i].flag;2177free(preimage->line_allocated);2178*preimage = fixed_preimage;21792180/*2181 * Adjust the common context lines in postimage. This can be2182 * done in-place when we are shrinking it with whitespace2183 * fixing, but needs a new buffer when ignoring whitespace or2184 * expanding leading tabs to spaces.2185 *2186 * We trust the caller to tell us if the update can be done2187 * in place (postlen==0) or not.2188 */2189 old = postimage->buf;2190if(postlen)2191new= postimage->buf =xmalloc(postlen);2192else2193new= old;2194 fixed = preimage->buf;21952196for(i = reduced = ctx =0; i < postimage->nr; i++) {2197size_t len = postimage->line[i].len;2198if(!(postimage->line[i].flag & LINE_COMMON)) {2199/* an added line -- no counterparts in preimage */2200memmove(new, old, len);2201 old += len;2202new+= len;2203continue;2204}22052206/* a common context -- skip it in the original postimage */2207 old += len;22082209/* and find the corresponding one in the fixed preimage */2210while(ctx < preimage->nr &&2211!(preimage->line[ctx].flag & LINE_COMMON)) {2212 fixed += preimage->line[ctx].len;2213 ctx++;2214}22152216/*2217 * preimage is expected to run out, if the caller2218 * fixed addition of trailing blank lines.2219 */2220if(preimage->nr <= ctx) {2221 reduced++;2222continue;2223}22242225/* and copy it in, while fixing the line length */2226 len = preimage->line[ctx].len;2227memcpy(new, fixed, len);2228new+= len;2229 fixed += len;2230 postimage->line[i].len = len;2231 ctx++;2232}22332234if(postlen2235? postlen <new- postimage->buf2236: postimage->len <new- postimage->buf)2237die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2238(int)postlen, (int) postimage->len, (int)(new- postimage->buf));22392240/* Fix the length of the whole thing */2241 postimage->len =new- postimage->buf;2242 postimage->nr -= reduced;2243}22442245static intmatch_fragment(struct image *img,2246struct image *preimage,2247struct image *postimage,2248unsigned longtry,2249int try_lno,2250unsigned ws_rule,2251int match_beginning,int match_end)2252{2253int i;2254char*fixed_buf, *buf, *orig, *target;2255struct strbuf fixed;2256size_t fixed_len, postlen;2257int preimage_limit;22582259if(preimage->nr + try_lno <= img->nr) {2260/*2261 * The hunk falls within the boundaries of img.2262 */2263 preimage_limit = preimage->nr;2264if(match_end && (preimage->nr + try_lno != img->nr))2265return0;2266}else if(ws_error_action == correct_ws_error &&2267(ws_rule & WS_BLANK_AT_EOF)) {2268/*2269 * This hunk extends beyond the end of img, and we are2270 * removing blank lines at the end of the file. This2271 * many lines from the beginning of the preimage must2272 * match with img, and the remainder of the preimage2273 * must be blank.2274 */2275 preimage_limit = img->nr - try_lno;2276}else{2277/*2278 * The hunk extends beyond the end of the img and2279 * we are not removing blanks at the end, so we2280 * should reject the hunk at this position.2281 */2282return0;2283}22842285if(match_beginning && try_lno)2286return0;22872288/* Quick hash check */2289for(i =0; i < preimage_limit; i++)2290if((img->line[try_lno + i].flag & LINE_PATCHED) ||2291(preimage->line[i].hash != img->line[try_lno + i].hash))2292return0;22932294if(preimage_limit == preimage->nr) {2295/*2296 * Do we have an exact match? If we were told to match2297 * at the end, size must be exactly at try+fragsize,2298 * otherwise try+fragsize must be still within the preimage,2299 * and either case, the old piece should match the preimage2300 * exactly.2301 */2302if((match_end2303? (try+ preimage->len == img->len)2304: (try+ preimage->len <= img->len)) &&2305!memcmp(img->buf +try, preimage->buf, preimage->len))2306return1;2307}else{2308/*2309 * The preimage extends beyond the end of img, so2310 * there cannot be an exact match.2311 *2312 * There must be one non-blank context line that match2313 * a line before the end of img.2314 */2315char*buf_end;23162317 buf = preimage->buf;2318 buf_end = buf;2319for(i =0; i < preimage_limit; i++)2320 buf_end += preimage->line[i].len;23212322for( ; buf < buf_end; buf++)2323if(!isspace(*buf))2324break;2325if(buf == buf_end)2326return0;2327}23282329/*2330 * No exact match. If we are ignoring whitespace, run a line-by-line2331 * fuzzy matching. We collect all the line length information because2332 * we need it to adjust whitespace if we match.2333 */2334if(ws_ignore_action == ignore_ws_change) {2335size_t imgoff =0;2336size_t preoff =0;2337size_t postlen = postimage->len;2338size_t extra_chars;2339char*preimage_eof;2340char*preimage_end;2341for(i =0; i < preimage_limit; i++) {2342size_t prelen = preimage->line[i].len;2343size_t imglen = img->line[try_lno+i].len;23442345if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2346 preimage->buf + preoff, prelen))2347return0;2348if(preimage->line[i].flag & LINE_COMMON)2349 postlen += imglen - prelen;2350 imgoff += imglen;2351 preoff += prelen;2352}23532354/*2355 * Ok, the preimage matches with whitespace fuzz.2356 *2357 * imgoff now holds the true length of the target that2358 * matches the preimage before the end of the file.2359 *2360 * Count the number of characters in the preimage that fall2361 * beyond the end of the file and make sure that all of them2362 * are whitespace characters. (This can only happen if2363 * we are removing blank lines at the end of the file.)2364 */2365 buf = preimage_eof = preimage->buf + preoff;2366for( ; i < preimage->nr; i++)2367 preoff += preimage->line[i].len;2368 preimage_end = preimage->buf + preoff;2369for( ; buf < preimage_end; buf++)2370if(!isspace(*buf))2371return0;23722373/*2374 * Update the preimage and the common postimage context2375 * lines to use the same whitespace as the target.2376 * If whitespace is missing in the target (i.e.2377 * if the preimage extends beyond the end of the file),2378 * use the whitespace from the preimage.2379 */2380 extra_chars = preimage_end - preimage_eof;2381strbuf_init(&fixed, imgoff + extra_chars);2382strbuf_add(&fixed, img->buf +try, imgoff);2383strbuf_add(&fixed, preimage_eof, extra_chars);2384 fixed_buf =strbuf_detach(&fixed, &fixed_len);2385update_pre_post_images(preimage, postimage,2386 fixed_buf, fixed_len, postlen);2387return1;2388}23892390if(ws_error_action != correct_ws_error)2391return0;23922393/*2394 * The hunk does not apply byte-by-byte, but the hash says2395 * it might with whitespace fuzz. We weren't asked to2396 * ignore whitespace, we were asked to correct whitespace2397 * errors, so let's try matching after whitespace correction.2398 *2399 * While checking the preimage against the target, whitespace2400 * errors in both fixed, we count how large the corresponding2401 * postimage needs to be. The postimage prepared by2402 * apply_one_fragment() has whitespace errors fixed on added2403 * lines already, but the common lines were propagated as-is,2404 * which may become longer when their whitespace errors are2405 * fixed.2406 */24072408/* First count added lines in postimage */2409 postlen =0;2410for(i =0; i < postimage->nr; i++) {2411if(!(postimage->line[i].flag & LINE_COMMON))2412 postlen += postimage->line[i].len;2413}24142415/*2416 * The preimage may extend beyond the end of the file,2417 * but in this loop we will only handle the part of the2418 * preimage that falls within the file.2419 */2420strbuf_init(&fixed, preimage->len +1);2421 orig = preimage->buf;2422 target = img->buf +try;2423for(i =0; i < preimage_limit; i++) {2424size_t oldlen = preimage->line[i].len;2425size_t tgtlen = img->line[try_lno + i].len;2426size_t fixstart = fixed.len;2427struct strbuf tgtfix;2428int match;24292430/* Try fixing the line in the preimage */2431ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24322433/* Try fixing the line in the target */2434strbuf_init(&tgtfix, tgtlen);2435ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);24362437/*2438 * If they match, either the preimage was based on2439 * a version before our tree fixed whitespace breakage,2440 * or we are lacking a whitespace-fix patch the tree2441 * the preimage was based on already had (i.e. target2442 * has whitespace breakage, the preimage doesn't).2443 * In either case, we are fixing the whitespace breakages2444 * so we might as well take the fix together with their2445 * real change.2446 */2447 match = (tgtfix.len == fixed.len - fixstart &&2448!memcmp(tgtfix.buf, fixed.buf + fixstart,2449 fixed.len - fixstart));24502451/* Add the length if this is common with the postimage */2452if(preimage->line[i].flag & LINE_COMMON)2453 postlen += tgtfix.len;24542455strbuf_release(&tgtfix);2456if(!match)2457goto unmatch_exit;24582459 orig += oldlen;2460 target += tgtlen;2461}246224632464/*2465 * Now handle the lines in the preimage that falls beyond the2466 * end of the file (if any). They will only match if they are2467 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2468 * false).2469 */2470for( ; i < preimage->nr; i++) {2471size_t fixstart = fixed.len;/* start of the fixed preimage */2472size_t oldlen = preimage->line[i].len;2473int j;24742475/* Try fixing the line in the preimage */2476ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24772478for(j = fixstart; j < fixed.len; j++)2479if(!isspace(fixed.buf[j]))2480goto unmatch_exit;24812482 orig += oldlen;2483}24842485/*2486 * Yes, the preimage is based on an older version that still2487 * has whitespace breakages unfixed, and fixing them makes the2488 * hunk match. Update the context lines in the postimage.2489 */2490 fixed_buf =strbuf_detach(&fixed, &fixed_len);2491if(postlen < postimage->len)2492 postlen =0;2493update_pre_post_images(preimage, postimage,2494 fixed_buf, fixed_len, postlen);2495return1;24962497 unmatch_exit:2498strbuf_release(&fixed);2499return0;2500}25012502static intfind_pos(struct image *img,2503struct image *preimage,2504struct image *postimage,2505int line,2506unsigned ws_rule,2507int match_beginning,int match_end)2508{2509int i;2510unsigned long backwards, forwards,try;2511int backwards_lno, forwards_lno, try_lno;25122513/*2514 * If match_beginning or match_end is specified, there is no2515 * point starting from a wrong line that will never match and2516 * wander around and wait for a match at the specified end.2517 */2518if(match_beginning)2519 line =0;2520else if(match_end)2521 line = img->nr - preimage->nr;25222523/*2524 * Because the comparison is unsigned, the following test2525 * will also take care of a negative line number that can2526 * result when match_end and preimage is larger than the target.2527 */2528if((size_t) line > img->nr)2529 line = img->nr;25302531try=0;2532for(i =0; i < line; i++)2533try+= img->line[i].len;25342535/*2536 * There's probably some smart way to do this, but I'll leave2537 * that to the smart and beautiful people. I'm simple and stupid.2538 */2539 backwards =try;2540 backwards_lno = line;2541 forwards =try;2542 forwards_lno = line;2543 try_lno = line;25442545for(i =0; ; i++) {2546if(match_fragment(img, preimage, postimage,2547try, try_lno, ws_rule,2548 match_beginning, match_end))2549return try_lno;25502551 again:2552if(backwards_lno ==0&& forwards_lno == img->nr)2553break;25542555if(i &1) {2556if(backwards_lno ==0) {2557 i++;2558goto again;2559}2560 backwards_lno--;2561 backwards -= img->line[backwards_lno].len;2562try= backwards;2563 try_lno = backwards_lno;2564}else{2565if(forwards_lno == img->nr) {2566 i++;2567goto again;2568}2569 forwards += img->line[forwards_lno].len;2570 forwards_lno++;2571try= forwards;2572 try_lno = forwards_lno;2573}25742575}2576return-1;2577}25782579static voidremove_first_line(struct image *img)2580{2581 img->buf += img->line[0].len;2582 img->len -= img->line[0].len;2583 img->line++;2584 img->nr--;2585}25862587static voidremove_last_line(struct image *img)2588{2589 img->len -= img->line[--img->nr].len;2590}25912592/*2593 * The change from "preimage" and "postimage" has been found to2594 * apply at applied_pos (counts in line numbers) in "img".2595 * Update "img" to remove "preimage" and replace it with "postimage".2596 */2597static voidupdate_image(struct image *img,2598int applied_pos,2599struct image *preimage,2600struct image *postimage)2601{2602/*2603 * remove the copy of preimage at offset in img2604 * and replace it with postimage2605 */2606int i, nr;2607size_t remove_count, insert_count, applied_at =0;2608char*result;2609int preimage_limit;26102611/*2612 * If we are removing blank lines at the end of img,2613 * the preimage may extend beyond the end.2614 * If that is the case, we must be careful only to2615 * remove the part of the preimage that falls within2616 * the boundaries of img. Initialize preimage_limit2617 * to the number of lines in the preimage that falls2618 * within the boundaries.2619 */2620 preimage_limit = preimage->nr;2621if(preimage_limit > img->nr - applied_pos)2622 preimage_limit = img->nr - applied_pos;26232624for(i =0; i < applied_pos; i++)2625 applied_at += img->line[i].len;26262627 remove_count =0;2628for(i =0; i < preimage_limit; i++)2629 remove_count += img->line[applied_pos + i].len;2630 insert_count = postimage->len;26312632/* Adjust the contents */2633 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2634memcpy(result, img->buf, applied_at);2635memcpy(result + applied_at, postimage->buf, postimage->len);2636memcpy(result + applied_at + postimage->len,2637 img->buf + (applied_at + remove_count),2638 img->len - (applied_at + remove_count));2639free(img->buf);2640 img->buf = result;2641 img->len += insert_count - remove_count;2642 result[img->len] ='\0';26432644/* Adjust the line table */2645 nr = img->nr + postimage->nr - preimage_limit;2646if(preimage_limit < postimage->nr) {2647/*2648 * NOTE: this knows that we never call remove_first_line()2649 * on anything other than pre/post image.2650 */2651REALLOC_ARRAY(img->line, nr);2652 img->line_allocated = img->line;2653}2654if(preimage_limit != postimage->nr)2655memmove(img->line + applied_pos + postimage->nr,2656 img->line + applied_pos + preimage_limit,2657(img->nr - (applied_pos + preimage_limit)) *2658sizeof(*img->line));2659memcpy(img->line + applied_pos,2660 postimage->line,2661 postimage->nr *sizeof(*img->line));2662if(!allow_overlap)2663for(i =0; i < postimage->nr; i++)2664 img->line[applied_pos + i].flag |= LINE_PATCHED;2665 img->nr = nr;2666}26672668/*2669 * Use the patch-hunk text in "frag" to prepare two images (preimage and2670 * postimage) for the hunk. Find lines that match "preimage" in "img" and2671 * replace the part of "img" with "postimage" text.2672 */2673static intapply_one_fragment(struct image *img,struct fragment *frag,2674int inaccurate_eof,unsigned ws_rule,2675int nth_fragment)2676{2677int match_beginning, match_end;2678const char*patch = frag->patch;2679int size = frag->size;2680char*old, *oldlines;2681struct strbuf newlines;2682int new_blank_lines_at_end =0;2683int found_new_blank_lines_at_end =0;2684int hunk_linenr = frag->linenr;2685unsigned long leading, trailing;2686int pos, applied_pos;2687struct image preimage;2688struct image postimage;26892690memset(&preimage,0,sizeof(preimage));2691memset(&postimage,0,sizeof(postimage));2692 oldlines =xmalloc(size);2693strbuf_init(&newlines, size);26942695 old = oldlines;2696while(size >0) {2697char first;2698int len =linelen(patch, size);2699int plen;2700int added_blank_line =0;2701int is_blank_context =0;2702size_t start;27032704if(!len)2705break;27062707/*2708 * "plen" is how much of the line we should use for2709 * the actual patch data. Normally we just remove the2710 * first character on the line, but if the line is2711 * followed by "\ No newline", then we also remove the2712 * last one (which is the newline, of course).2713 */2714 plen = len -1;2715if(len < size && patch[len] =='\\')2716 plen--;2717 first = *patch;2718if(apply_in_reverse) {2719if(first =='-')2720 first ='+';2721else if(first =='+')2722 first ='-';2723}27242725switch(first) {2726case'\n':2727/* Newer GNU diff, empty context line */2728if(plen <0)2729/* ... followed by '\No newline'; nothing */2730break;2731*old++ ='\n';2732strbuf_addch(&newlines,'\n');2733add_line_info(&preimage,"\n",1, LINE_COMMON);2734add_line_info(&postimage,"\n",1, LINE_COMMON);2735 is_blank_context =1;2736break;2737case' ':2738if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2739ws_blank_line(patch +1, plen, ws_rule))2740 is_blank_context =1;2741case'-':2742memcpy(old, patch +1, plen);2743add_line_info(&preimage, old, plen,2744(first ==' '? LINE_COMMON :0));2745 old += plen;2746if(first =='-')2747break;2748/* Fall-through for ' ' */2749case'+':2750/* --no-add does not add new lines */2751if(first =='+'&& no_add)2752break;27532754 start = newlines.len;2755if(first !='+'||2756!whitespace_error ||2757 ws_error_action != correct_ws_error) {2758strbuf_add(&newlines, patch +1, plen);2759}2760else{2761ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2762}2763add_line_info(&postimage, newlines.buf + start, newlines.len - start,2764(first =='+'?0: LINE_COMMON));2765if(first =='+'&&2766(ws_rule & WS_BLANK_AT_EOF) &&2767ws_blank_line(patch +1, plen, ws_rule))2768 added_blank_line =1;2769break;2770case'@':case'\\':2771/* Ignore it, we already handled it */2772break;2773default:2774if(apply_verbosely)2775error(_("invalid start of line: '%c'"), first);2776 applied_pos = -1;2777goto out;2778}2779if(added_blank_line) {2780if(!new_blank_lines_at_end)2781 found_new_blank_lines_at_end = hunk_linenr;2782 new_blank_lines_at_end++;2783}2784else if(is_blank_context)2785;2786else2787 new_blank_lines_at_end =0;2788 patch += len;2789 size -= len;2790 hunk_linenr++;2791}2792if(inaccurate_eof &&2793 old > oldlines && old[-1] =='\n'&&2794 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2795 old--;2796strbuf_setlen(&newlines, newlines.len -1);2797}27982799 leading = frag->leading;2800 trailing = frag->trailing;28012802/*2803 * A hunk to change lines at the beginning would begin with2804 * @@ -1,L +N,M @@2805 * but we need to be careful. -U0 that inserts before the second2806 * line also has this pattern.2807 *2808 * And a hunk to add to an empty file would begin with2809 * @@ -0,0 +N,M @@2810 *2811 * In other words, a hunk that is (frag->oldpos <= 1) with or2812 * without leading context must match at the beginning.2813 */2814 match_beginning = (!frag->oldpos ||2815(frag->oldpos ==1&& !unidiff_zero));28162817/*2818 * A hunk without trailing lines must match at the end.2819 * However, we simply cannot tell if a hunk must match end2820 * from the lack of trailing lines if the patch was generated2821 * with unidiff without any context.2822 */2823 match_end = !unidiff_zero && !trailing;28242825 pos = frag->newpos ? (frag->newpos -1) :0;2826 preimage.buf = oldlines;2827 preimage.len = old - oldlines;2828 postimage.buf = newlines.buf;2829 postimage.len = newlines.len;2830 preimage.line = preimage.line_allocated;2831 postimage.line = postimage.line_allocated;28322833for(;;) {28342835 applied_pos =find_pos(img, &preimage, &postimage, pos,2836 ws_rule, match_beginning, match_end);28372838if(applied_pos >=0)2839break;28402841/* Am I at my context limits? */2842if((leading <= p_context) && (trailing <= p_context))2843break;2844if(match_beginning || match_end) {2845 match_beginning = match_end =0;2846continue;2847}28482849/*2850 * Reduce the number of context lines; reduce both2851 * leading and trailing if they are equal otherwise2852 * just reduce the larger context.2853 */2854if(leading >= trailing) {2855remove_first_line(&preimage);2856remove_first_line(&postimage);2857 pos--;2858 leading--;2859}2860if(trailing > leading) {2861remove_last_line(&preimage);2862remove_last_line(&postimage);2863 trailing--;2864}2865}28662867if(applied_pos >=0) {2868if(new_blank_lines_at_end &&2869 preimage.nr + applied_pos >= img->nr &&2870(ws_rule & WS_BLANK_AT_EOF) &&2871 ws_error_action != nowarn_ws_error) {2872record_ws_error(WS_BLANK_AT_EOF,"+",1,2873 found_new_blank_lines_at_end);2874if(ws_error_action == correct_ws_error) {2875while(new_blank_lines_at_end--)2876remove_last_line(&postimage);2877}2878/*2879 * We would want to prevent write_out_results()2880 * from taking place in apply_patch() that follows2881 * the callchain led us here, which is:2882 * apply_patch->check_patch_list->check_patch->2883 * apply_data->apply_fragments->apply_one_fragment2884 */2885if(ws_error_action == die_on_ws_error)2886 apply =0;2887}28882889if(apply_verbosely && applied_pos != pos) {2890int offset = applied_pos - pos;2891if(apply_in_reverse)2892 offset =0- offset;2893fprintf_ln(stderr,2894Q_("Hunk #%dsucceeded at%d(offset%dline).",2895"Hunk #%dsucceeded at%d(offset%dlines).",2896 offset),2897 nth_fragment, applied_pos +1, offset);2898}28992900/*2901 * Warn if it was necessary to reduce the number2902 * of context lines.2903 */2904if((leading != frag->leading) ||2905(trailing != frag->trailing))2906fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2907" to apply fragment at%d"),2908 leading, trailing, applied_pos+1);2909update_image(img, applied_pos, &preimage, &postimage);2910}else{2911if(apply_verbosely)2912error(_("while searching for:\n%.*s"),2913(int)(old - oldlines), oldlines);2914}29152916out:2917free(oldlines);2918strbuf_release(&newlines);2919free(preimage.line_allocated);2920free(postimage.line_allocated);29212922return(applied_pos <0);2923}29242925static intapply_binary_fragment(struct image *img,struct patch *patch)2926{2927struct fragment *fragment = patch->fragments;2928unsigned long len;2929void*dst;29302931if(!fragment)2932returnerror(_("missing binary patch data for '%s'"),2933 patch->new_name ?2934 patch->new_name :2935 patch->old_name);29362937/* Binary patch is irreversible without the optional second hunk */2938if(apply_in_reverse) {2939if(!fragment->next)2940returnerror("cannot reverse-apply a binary patch "2941"without the reverse hunk to '%s'",2942 patch->new_name2943? patch->new_name : patch->old_name);2944 fragment = fragment->next;2945}2946switch(fragment->binary_patch_method) {2947case BINARY_DELTA_DEFLATED:2948 dst =patch_delta(img->buf, img->len, fragment->patch,2949 fragment->size, &len);2950if(!dst)2951return-1;2952clear_image(img);2953 img->buf = dst;2954 img->len = len;2955return0;2956case BINARY_LITERAL_DEFLATED:2957clear_image(img);2958 img->len = fragment->size;2959 img->buf =xmemdupz(fragment->patch, img->len);2960return0;2961}2962return-1;2963}29642965/*2966 * Replace "img" with the result of applying the binary patch.2967 * The binary patch data itself in patch->fragment is still kept2968 * but the preimage prepared by the caller in "img" is freed here2969 * or in the helper function apply_binary_fragment() this calls.2970 */2971static intapply_binary(struct image *img,struct patch *patch)2972{2973const char*name = patch->old_name ? patch->old_name : patch->new_name;2974unsigned char sha1[20];29752976/*2977 * For safety, we require patch index line to contain2978 * full 40-byte textual SHA1 for old and new, at least for now.2979 */2980if(strlen(patch->old_sha1_prefix) !=40||2981strlen(patch->new_sha1_prefix) !=40||2982get_sha1_hex(patch->old_sha1_prefix, sha1) ||2983get_sha1_hex(patch->new_sha1_prefix, sha1))2984returnerror("cannot apply binary patch to '%s' "2985"without full index line", name);29862987if(patch->old_name) {2988/*2989 * See if the old one matches what the patch2990 * applies to.2991 */2992hash_sha1_file(img->buf, img->len, blob_type, sha1);2993if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2994returnerror("the patch applies to '%s' (%s), "2995"which does not match the "2996"current contents.",2997 name,sha1_to_hex(sha1));2998}2999else{3000/* Otherwise, the old one must be empty. */3001if(img->len)3002returnerror("the patch applies to an empty "3003"'%s' but it is not empty", name);3004}30053006get_sha1_hex(patch->new_sha1_prefix, sha1);3007if(is_null_sha1(sha1)) {3008clear_image(img);3009return0;/* deletion patch */3010}30113012if(has_sha1_file(sha1)) {3013/* We already have the postimage */3014enum object_type type;3015unsigned long size;3016char*result;30173018 result =read_sha1_file(sha1, &type, &size);3019if(!result)3020returnerror("the necessary postimage%sfor "3021"'%s' cannot be read",3022 patch->new_sha1_prefix, name);3023clear_image(img);3024 img->buf = result;3025 img->len = size;3026}else{3027/*3028 * We have verified buf matches the preimage;3029 * apply the patch data to it, which is stored3030 * in the patch->fragments->{patch,size}.3031 */3032if(apply_binary_fragment(img, patch))3033returnerror(_("binary patch does not apply to '%s'"),3034 name);30353036/* verify that the result matches */3037hash_sha1_file(img->buf, img->len, blob_type, sha1);3038if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3039returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3040 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3041}30423043return0;3044}30453046static intapply_fragments(struct image *img,struct patch *patch)3047{3048struct fragment *frag = patch->fragments;3049const char*name = patch->old_name ? patch->old_name : patch->new_name;3050unsigned ws_rule = patch->ws_rule;3051unsigned inaccurate_eof = patch->inaccurate_eof;3052int nth =0;30533054if(patch->is_binary)3055returnapply_binary(img, patch);30563057while(frag) {3058 nth++;3059if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {3060error(_("patch failed:%s:%ld"), name, frag->oldpos);3061if(!apply_with_reject)3062return-1;3063 frag->rejected =1;3064}3065 frag = frag->next;3066}3067return0;3068}30693070static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3071{3072if(S_ISGITLINK(mode)) {3073strbuf_grow(buf,100);3074strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3075}else{3076enum object_type type;3077unsigned long sz;3078char*result;30793080 result =read_sha1_file(sha1, &type, &sz);3081if(!result)3082return-1;3083/* XXX read_sha1_file NUL-terminates */3084strbuf_attach(buf, result, sz, sz +1);3085}3086return0;3087}30883089static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3090{3091if(!ce)3092return0;3093returnread_blob_object(buf, ce->sha1, ce->ce_mode);3094}30953096static struct patch *in_fn_table(const char*name)3097{3098struct string_list_item *item;30993100if(name == NULL)3101return NULL;31023103 item =string_list_lookup(&fn_table, name);3104if(item != NULL)3105return(struct patch *)item->util;31063107return NULL;3108}31093110/*3111 * item->util in the filename table records the status of the path.3112 * Usually it points at a patch (whose result records the contents3113 * of it after applying it), but it could be PATH_WAS_DELETED for a3114 * path that a previously applied patch has already removed, or3115 * PATH_TO_BE_DELETED for a path that a later patch would remove.3116 *3117 * The latter is needed to deal with a case where two paths A and B3118 * are swapped by first renaming A to B and then renaming B to A;3119 * moving A to B should not be prevented due to presence of B as we3120 * will remove it in a later patch.3121 */3122#define PATH_TO_BE_DELETED ((struct patch *) -2)3123#define PATH_WAS_DELETED ((struct patch *) -1)31243125static intto_be_deleted(struct patch *patch)3126{3127return patch == PATH_TO_BE_DELETED;3128}31293130static intwas_deleted(struct patch *patch)3131{3132return patch == PATH_WAS_DELETED;3133}31343135static voidadd_to_fn_table(struct patch *patch)3136{3137struct string_list_item *item;31383139/*3140 * Always add new_name unless patch is a deletion3141 * This should cover the cases for normal diffs,3142 * file creations and copies3143 */3144if(patch->new_name != NULL) {3145 item =string_list_insert(&fn_table, patch->new_name);3146 item->util = patch;3147}31483149/*3150 * store a failure on rename/deletion cases because3151 * later chunks shouldn't patch old names3152 */3153if((patch->new_name == NULL) || (patch->is_rename)) {3154 item =string_list_insert(&fn_table, patch->old_name);3155 item->util = PATH_WAS_DELETED;3156}3157}31583159static voidprepare_fn_table(struct patch *patch)3160{3161/*3162 * store information about incoming file deletion3163 */3164while(patch) {3165if((patch->new_name == NULL) || (patch->is_rename)) {3166struct string_list_item *item;3167 item =string_list_insert(&fn_table, patch->old_name);3168 item->util = PATH_TO_BE_DELETED;3169}3170 patch = patch->next;3171}3172}31733174static intcheckout_target(struct index_state *istate,3175struct cache_entry *ce,struct stat *st)3176{3177struct checkout costate;31783179memset(&costate,0,sizeof(costate));3180 costate.base_dir ="";3181 costate.refresh_cache =1;3182 costate.istate = istate;3183if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3184returnerror(_("cannot checkout%s"), ce->name);3185return0;3186}31873188static struct patch *previous_patch(struct patch *patch,int*gone)3189{3190struct patch *previous;31913192*gone =0;3193if(patch->is_copy || patch->is_rename)3194return NULL;/* "git" patches do not depend on the order */31953196 previous =in_fn_table(patch->old_name);3197if(!previous)3198return NULL;31993200if(to_be_deleted(previous))3201return NULL;/* the deletion hasn't happened yet */32023203if(was_deleted(previous))3204*gone =1;32053206return previous;3207}32083209static intverify_index_match(const struct cache_entry *ce,struct stat *st)3210{3211if(S_ISGITLINK(ce->ce_mode)) {3212if(!S_ISDIR(st->st_mode))3213return-1;3214return0;3215}3216returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3217}32183219#define SUBMODULE_PATCH_WITHOUT_INDEX 132203221static intload_patch_target(struct strbuf *buf,3222const struct cache_entry *ce,3223struct stat *st,3224const char*name,3225unsigned expected_mode)3226{3227if(cached || check_index) {3228if(read_file_or_gitlink(ce, buf))3229returnerror(_("read of%sfailed"), name);3230}else if(name) {3231if(S_ISGITLINK(expected_mode)) {3232if(ce)3233returnread_file_or_gitlink(ce, buf);3234else3235return SUBMODULE_PATCH_WITHOUT_INDEX;3236}else if(has_symlink_leading_path(name,strlen(name))) {3237returnerror(_("reading from '%s' beyond a symbolic link"), name);3238}else{3239if(read_old_data(st, name, buf))3240returnerror(_("read of%sfailed"), name);3241}3242}3243return0;3244}32453246/*3247 * We are about to apply "patch"; populate the "image" with the3248 * current version we have, from the working tree or from the index,3249 * depending on the situation e.g. --cached/--index. If we are3250 * applying a non-git patch that incrementally updates the tree,3251 * we read from the result of a previous diff.3252 */3253static intload_preimage(struct image *image,3254struct patch *patch,struct stat *st,3255const struct cache_entry *ce)3256{3257struct strbuf buf = STRBUF_INIT;3258size_t len;3259char*img;3260struct patch *previous;3261int status;32623263 previous =previous_patch(patch, &status);3264if(status)3265returnerror(_("path%shas been renamed/deleted"),3266 patch->old_name);3267if(previous) {3268/* We have a patched copy in memory; use that. */3269strbuf_add(&buf, previous->result, previous->resultsize);3270}else{3271 status =load_patch_target(&buf, ce, st,3272 patch->old_name, patch->old_mode);3273if(status <0)3274return status;3275else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3276/*3277 * There is no way to apply subproject3278 * patch without looking at the index.3279 * NEEDSWORK: shouldn't this be flagged3280 * as an error???3281 */3282free_fragment_list(patch->fragments);3283 patch->fragments = NULL;3284}else if(status) {3285returnerror(_("read of%sfailed"), patch->old_name);3286}3287}32883289 img =strbuf_detach(&buf, &len);3290prepare_image(image, img, len, !patch->is_binary);3291return0;3292}32933294static intthree_way_merge(struct image *image,3295char*path,3296const unsigned char*base,3297const unsigned char*ours,3298const unsigned char*theirs)3299{3300 mmfile_t base_file, our_file, their_file;3301 mmbuffer_t result = { NULL };3302int status;33033304read_mmblob(&base_file, base);3305read_mmblob(&our_file, ours);3306read_mmblob(&their_file, theirs);3307 status =ll_merge(&result, path,3308&base_file,"base",3309&our_file,"ours",3310&their_file,"theirs", NULL);3311free(base_file.ptr);3312free(our_file.ptr);3313free(their_file.ptr);3314if(status <0|| !result.ptr) {3315free(result.ptr);3316return-1;3317}3318clear_image(image);3319 image->buf = result.ptr;3320 image->len = result.size;33213322return status;3323}33243325/*3326 * When directly falling back to add/add three-way merge, we read from3327 * the current contents of the new_name. In no cases other than that3328 * this function will be called.3329 */3330static intload_current(struct image *image,struct patch *patch)3331{3332struct strbuf buf = STRBUF_INIT;3333int status, pos;3334size_t len;3335char*img;3336struct stat st;3337struct cache_entry *ce;3338char*name = patch->new_name;3339unsigned mode = patch->new_mode;33403341if(!patch->is_new)3342die("BUG: patch to%sis not a creation", patch->old_name);33433344 pos =cache_name_pos(name,strlen(name));3345if(pos <0)3346returnerror(_("%s: does not exist in index"), name);3347 ce = active_cache[pos];3348if(lstat(name, &st)) {3349if(errno != ENOENT)3350returnerror(_("%s:%s"), name,strerror(errno));3351if(checkout_target(&the_index, ce, &st))3352return-1;3353}3354if(verify_index_match(ce, &st))3355returnerror(_("%s: does not match index"), name);33563357 status =load_patch_target(&buf, ce, &st, name, mode);3358if(status <0)3359return status;3360else if(status)3361return-1;3362 img =strbuf_detach(&buf, &len);3363prepare_image(image, img, len, !patch->is_binary);3364return0;3365}33663367static inttry_threeway(struct image *image,struct patch *patch,3368struct stat *st,const struct cache_entry *ce)3369{3370unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3371struct strbuf buf = STRBUF_INIT;3372size_t len;3373int status;3374char*img;3375struct image tmp_image;33763377/* No point falling back to 3-way merge in these cases */3378if(patch->is_delete ||3379S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3380return-1;33813382/* Preimage the patch was prepared for */3383if(patch->is_new)3384write_sha1_file("",0, blob_type, pre_sha1);3385else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3386read_blob_object(&buf, pre_sha1, patch->old_mode))3387returnerror("repository lacks the necessary blob to fall back on 3-way merge.");33883389fprintf(stderr,"Falling back to three-way merge...\n");33903391 img =strbuf_detach(&buf, &len);3392prepare_image(&tmp_image, img, len,1);3393/* Apply the patch to get the post image */3394if(apply_fragments(&tmp_image, patch) <0) {3395clear_image(&tmp_image);3396return-1;3397}3398/* post_sha1[] is theirs */3399write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3400clear_image(&tmp_image);34013402/* our_sha1[] is ours */3403if(patch->is_new) {3404if(load_current(&tmp_image, patch))3405returnerror("cannot read the current contents of '%s'",3406 patch->new_name);3407}else{3408if(load_preimage(&tmp_image, patch, st, ce))3409returnerror("cannot read the current contents of '%s'",3410 patch->old_name);3411}3412write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3413clear_image(&tmp_image);34143415/* in-core three-way merge between post and our using pre as base */3416 status =three_way_merge(image, patch->new_name,3417 pre_sha1, our_sha1, post_sha1);3418if(status <0) {3419fprintf(stderr,"Failed to fall back on three-way merge...\n");3420return status;3421}34223423if(status) {3424 patch->conflicted_threeway =1;3425if(patch->is_new)3426oidclr(&patch->threeway_stage[0]);3427else3428hashcpy(patch->threeway_stage[0].hash, pre_sha1);3429hashcpy(patch->threeway_stage[1].hash, our_sha1);3430hashcpy(patch->threeway_stage[2].hash, post_sha1);3431fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3432}else{3433fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3434}3435return0;3436}34373438static intapply_data(struct patch *patch,struct stat *st,const struct cache_entry *ce)3439{3440struct image image;34413442if(load_preimage(&image, patch, st, ce) <0)3443return-1;34443445if(patch->direct_to_threeway ||3446apply_fragments(&image, patch) <0) {3447/* Note: with --reject, apply_fragments() returns 0 */3448if(!threeway ||try_threeway(&image, patch, st, ce) <0)3449return-1;3450}3451 patch->result = image.buf;3452 patch->resultsize = image.len;3453add_to_fn_table(patch);3454free(image.line_allocated);34553456if(0< patch->is_delete && patch->resultsize)3457returnerror(_("removal patch leaves file contents"));34583459return0;3460}34613462/*3463 * If "patch" that we are looking at modifies or deletes what we have,3464 * we would want it not to lose any local modification we have, either3465 * in the working tree or in the index.3466 *3467 * This also decides if a non-git patch is a creation patch or a3468 * modification to an existing empty file. We do not check the state3469 * of the current tree for a creation patch in this function; the caller3470 * check_patch() separately makes sure (and errors out otherwise) that3471 * the path the patch creates does not exist in the current tree.3472 */3473static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)3474{3475const char*old_name = patch->old_name;3476struct patch *previous = NULL;3477int stat_ret =0, status;3478unsigned st_mode =0;34793480if(!old_name)3481return0;34823483assert(patch->is_new <=0);3484 previous =previous_patch(patch, &status);34853486if(status)3487returnerror(_("path%shas been renamed/deleted"), old_name);3488if(previous) {3489 st_mode = previous->new_mode;3490}else if(!cached) {3491 stat_ret =lstat(old_name, st);3492if(stat_ret && errno != ENOENT)3493returnerror(_("%s:%s"), old_name,strerror(errno));3494}34953496if(check_index && !previous) {3497int pos =cache_name_pos(old_name,strlen(old_name));3498if(pos <0) {3499if(patch->is_new <0)3500goto is_new;3501returnerror(_("%s: does not exist in index"), old_name);3502}3503*ce = active_cache[pos];3504if(stat_ret <0) {3505if(checkout_target(&the_index, *ce, st))3506return-1;3507}3508if(!cached &&verify_index_match(*ce, st))3509returnerror(_("%s: does not match index"), old_name);3510if(cached)3511 st_mode = (*ce)->ce_mode;3512}else if(stat_ret <0) {3513if(patch->is_new <0)3514goto is_new;3515returnerror(_("%s:%s"), old_name,strerror(errno));3516}35173518if(!cached && !previous)3519 st_mode =ce_mode_from_stat(*ce, st->st_mode);35203521if(patch->is_new <0)3522 patch->is_new =0;3523if(!patch->old_mode)3524 patch->old_mode = st_mode;3525if((st_mode ^ patch->old_mode) & S_IFMT)3526returnerror(_("%s: wrong type"), old_name);3527if(st_mode != patch->old_mode)3528warning(_("%shas type%o, expected%o"),3529 old_name, st_mode, patch->old_mode);3530if(!patch->new_mode && !patch->is_delete)3531 patch->new_mode = st_mode;3532return0;35333534 is_new:3535 patch->is_new =1;3536 patch->is_delete =0;3537free(patch->old_name);3538 patch->old_name = NULL;3539return0;3540}354135423543#define EXISTS_IN_INDEX 13544#define EXISTS_IN_WORKTREE 235453546static intcheck_to_create(const char*new_name,int ok_if_exists)3547{3548struct stat nst;35493550if(check_index &&3551cache_name_pos(new_name,strlen(new_name)) >=0&&3552!ok_if_exists)3553return EXISTS_IN_INDEX;3554if(cached)3555return0;35563557if(!lstat(new_name, &nst)) {3558if(S_ISDIR(nst.st_mode) || ok_if_exists)3559return0;3560/*3561 * A leading component of new_name might be a symlink3562 * that is going to be removed with this patch, but3563 * still pointing at somewhere that has the path.3564 * In such a case, path "new_name" does not exist as3565 * far as git is concerned.3566 */3567if(has_symlink_leading_path(new_name,strlen(new_name)))3568return0;35693570return EXISTS_IN_WORKTREE;3571}else if((errno != ENOENT) && (errno != ENOTDIR)) {3572returnerror("%s:%s", new_name,strerror(errno));3573}3574return0;3575}35763577/*3578 * We need to keep track of how symlinks in the preimage are3579 * manipulated by the patches. A patch to add a/b/c where a/b3580 * is a symlink should not be allowed to affect the directory3581 * the symlink points at, but if the same patch removes a/b,3582 * it is perfectly fine, as the patch removes a/b to make room3583 * to create a directory a/b so that a/b/c can be created.3584 */3585static struct string_list symlink_changes;3586#define SYMLINK_GOES_AWAY 013587#define SYMLINK_IN_RESULT 0235883589static uintptr_tregister_symlink_changes(const char*path,uintptr_t what)3590{3591struct string_list_item *ent;35923593 ent =string_list_lookup(&symlink_changes, path);3594if(!ent) {3595 ent =string_list_insert(&symlink_changes, path);3596 ent->util = (void*)0;3597}3598 ent->util = (void*)(what | ((uintptr_t)ent->util));3599return(uintptr_t)ent->util;3600}36013602static uintptr_tcheck_symlink_changes(const char*path)3603{3604struct string_list_item *ent;36053606 ent =string_list_lookup(&symlink_changes, path);3607if(!ent)3608return0;3609return(uintptr_t)ent->util;3610}36113612static voidprepare_symlink_changes(struct patch *patch)3613{3614for( ; patch; patch = patch->next) {3615if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3616(patch->is_rename || patch->is_delete))3617/* the symlink at patch->old_name is removed */3618register_symlink_changes(patch->old_name, SYMLINK_GOES_AWAY);36193620if(patch->new_name &&S_ISLNK(patch->new_mode))3621/* the symlink at patch->new_name is created or remains */3622register_symlink_changes(patch->new_name, SYMLINK_IN_RESULT);3623}3624}36253626static intpath_is_beyond_symlink_1(struct strbuf *name)3627{3628do{3629unsigned int change;36303631while(--name->len && name->buf[name->len] !='/')3632;/* scan backwards */3633if(!name->len)3634break;3635 name->buf[name->len] ='\0';3636 change =check_symlink_changes(name->buf);3637if(change & SYMLINK_IN_RESULT)3638return1;3639if(change & SYMLINK_GOES_AWAY)3640/*3641 * This cannot be "return 0", because we may3642 * see a new one created at a higher level.3643 */3644continue;36453646/* otherwise, check the preimage */3647if(check_index) {3648struct cache_entry *ce;36493650 ce =cache_file_exists(name->buf, name->len, ignore_case);3651if(ce &&S_ISLNK(ce->ce_mode))3652return1;3653}else{3654struct stat st;3655if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3656return1;3657}3658}while(1);3659return0;3660}36613662static intpath_is_beyond_symlink(const char*name_)3663{3664int ret;3665struct strbuf name = STRBUF_INIT;36663667assert(*name_ !='\0');3668strbuf_addstr(&name, name_);3669 ret =path_is_beyond_symlink_1(&name);3670strbuf_release(&name);36713672return ret;3673}36743675static voiddie_on_unsafe_path(struct patch *patch)3676{3677const char*old_name = NULL;3678const char*new_name = NULL;3679if(patch->is_delete)3680 old_name = patch->old_name;3681else if(!patch->is_new && !patch->is_copy)3682 old_name = patch->old_name;3683if(!patch->is_delete)3684 new_name = patch->new_name;36853686if(old_name && !verify_path(old_name))3687die(_("invalid path '%s'"), old_name);3688if(new_name && !verify_path(new_name))3689die(_("invalid path '%s'"), new_name);3690}36913692/*3693 * Check and apply the patch in-core; leave the result in patch->result3694 * for the caller to write it out to the final destination.3695 */3696static intcheck_patch(struct patch *patch)3697{3698struct stat st;3699const char*old_name = patch->old_name;3700const char*new_name = patch->new_name;3701const char*name = old_name ? old_name : new_name;3702struct cache_entry *ce = NULL;3703struct patch *tpatch;3704int ok_if_exists;3705int status;37063707 patch->rejected =1;/* we will drop this after we succeed */37083709 status =check_preimage(patch, &ce, &st);3710if(status)3711return status;3712 old_name = patch->old_name;37133714/*3715 * A type-change diff is always split into a patch to delete3716 * old, immediately followed by a patch to create new (see3717 * diff.c::run_diff()); in such a case it is Ok that the entry3718 * to be deleted by the previous patch is still in the working3719 * tree and in the index.3720 *3721 * A patch to swap-rename between A and B would first rename A3722 * to B and then rename B to A. While applying the first one,3723 * the presence of B should not stop A from getting renamed to3724 * B; ask to_be_deleted() about the later rename. Removal of3725 * B and rename from A to B is handled the same way by asking3726 * was_deleted().3727 */3728if((tpatch =in_fn_table(new_name)) &&3729(was_deleted(tpatch) ||to_be_deleted(tpatch)))3730 ok_if_exists =1;3731else3732 ok_if_exists =0;37333734if(new_name &&3735((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3736int err =check_to_create(new_name, ok_if_exists);37373738if(err && threeway) {3739 patch->direct_to_threeway =1;3740}else switch(err) {3741case0:3742break;/* happy */3743case EXISTS_IN_INDEX:3744returnerror(_("%s: already exists in index"), new_name);3745break;3746case EXISTS_IN_WORKTREE:3747returnerror(_("%s: already exists in working directory"),3748 new_name);3749default:3750return err;3751}37523753if(!patch->new_mode) {3754if(0< patch->is_new)3755 patch->new_mode = S_IFREG |0644;3756else3757 patch->new_mode = patch->old_mode;3758}3759}37603761if(new_name && old_name) {3762int same = !strcmp(old_name, new_name);3763if(!patch->new_mode)3764 patch->new_mode = patch->old_mode;3765if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3766if(same)3767returnerror(_("new mode (%o) of%sdoes not "3768"match old mode (%o)"),3769 patch->new_mode, new_name,3770 patch->old_mode);3771else3772returnerror(_("new mode (%o) of%sdoes not "3773"match old mode (%o) of%s"),3774 patch->new_mode, new_name,3775 patch->old_mode, old_name);3776}3777}37783779if(!unsafe_paths)3780die_on_unsafe_path(patch);37813782/*3783 * An attempt to read from or delete a path that is beyond a3784 * symbolic link will be prevented by load_patch_target() that3785 * is called at the beginning of apply_data() so we do not3786 * have to worry about a patch marked with "is_delete" bit3787 * here. We however need to make sure that the patch result3788 * is not deposited to a path that is beyond a symbolic link3789 * here.3790 */3791if(!patch->is_delete &&path_is_beyond_symlink(patch->new_name))3792returnerror(_("affected file '%s' is beyond a symbolic link"),3793 patch->new_name);37943795if(apply_data(patch, &st, ce) <0)3796returnerror(_("%s: patch does not apply"), name);3797 patch->rejected =0;3798return0;3799}38003801static intcheck_patch_list(struct patch *patch)3802{3803int err =0;38043805prepare_symlink_changes(patch);3806prepare_fn_table(patch);3807while(patch) {3808if(apply_verbosely)3809say_patch_name(stderr,3810_("Checking patch%s..."), patch);3811 err |=check_patch(patch);3812 patch = patch->next;3813}3814return err;3815}38163817/* This function tries to read the sha1 from the current index */3818static intget_current_sha1(const char*path,unsigned char*sha1)3819{3820int pos;38213822if(read_cache() <0)3823return-1;3824 pos =cache_name_pos(path,strlen(path));3825if(pos <0)3826return-1;3827hashcpy(sha1, active_cache[pos]->sha1);3828return0;3829}38303831static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3832{3833/*3834 * A usable gitlink patch has only one fragment (hunk) that looks like:3835 * @@ -1 +1 @@3836 * -Subproject commit <old sha1>3837 * +Subproject commit <new sha1>3838 * or3839 * @@ -1 +0,0 @@3840 * -Subproject commit <old sha1>3841 * for a removal patch.3842 */3843struct fragment *hunk = p->fragments;3844static const char heading[] ="-Subproject commit ";3845char*preimage;38463847if(/* does the patch have only one hunk? */3848 hunk && !hunk->next &&3849/* is its preimage one line? */3850 hunk->oldpos ==1&& hunk->oldlines ==1&&3851/* does preimage begin with the heading? */3852(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3853starts_with(++preimage, heading) &&3854/* does it record full SHA-1? */3855!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3856 preimage[sizeof(heading) +40-1] =='\n'&&3857/* does the abbreviated name on the index line agree with it? */3858starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3859return0;/* it all looks fine */38603861/* we may have full object name on the index line */3862returnget_sha1_hex(p->old_sha1_prefix, sha1);3863}38643865/* Build an index that contains the just the files needed for a 3way merge */3866static voidbuild_fake_ancestor(struct patch *list,const char*filename)3867{3868struct patch *patch;3869struct index_state result = { NULL };3870static struct lock_file lock;38713872/* Once we start supporting the reverse patch, it may be3873 * worth showing the new sha1 prefix, but until then...3874 */3875for(patch = list; patch; patch = patch->next) {3876unsigned char sha1[20];3877struct cache_entry *ce;3878const char*name;38793880 name = patch->old_name ? patch->old_name : patch->new_name;3881if(0< patch->is_new)3882continue;38833884if(S_ISGITLINK(patch->old_mode)) {3885if(!preimage_sha1_in_gitlink_patch(patch, sha1))3886;/* ok, the textual part looks sane */3887else3888die("sha1 information is lacking or useless for submodule%s",3889 name);3890}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {3891;/* ok */3892}else if(!patch->lines_added && !patch->lines_deleted) {3893/* mode-only change: update the current */3894if(get_current_sha1(patch->old_name, sha1))3895die("mode change for%s, which is not "3896"in current HEAD", name);3897}else3898die("sha1 information is lacking or useless "3899"(%s).", name);39003901 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);3902if(!ce)3903die(_("make_cache_entry failed for path '%s'"), name);3904if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3905die("Could not add%sto temporary index", name);3906}39073908hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);3909if(write_locked_index(&result, &lock, COMMIT_LOCK))3910die("Could not write temporary index to%s", filename);39113912discard_index(&result);3913}39143915static voidstat_patch_list(struct patch *patch)3916{3917int files, adds, dels;39183919for(files = adds = dels =0; patch ; patch = patch->next) {3920 files++;3921 adds += patch->lines_added;3922 dels += patch->lines_deleted;3923show_stats(patch);3924}39253926print_stat_summary(stdout, files, adds, dels);3927}39283929static voidnumstat_patch_list(struct patch *patch)3930{3931for( ; patch; patch = patch->next) {3932const char*name;3933 name = patch->new_name ? patch->new_name : patch->old_name;3934if(patch->is_binary)3935printf("-\t-\t");3936else3937printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3938write_name_quoted(name, stdout, line_termination);3939}3940}39413942static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3943{3944if(mode)3945printf("%smode%06o%s\n", newdelete, mode, name);3946else3947printf("%s %s\n", newdelete, name);3948}39493950static voidshow_mode_change(struct patch *p,int show_name)3951{3952if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3953if(show_name)3954printf(" mode change%06o =>%06o%s\n",3955 p->old_mode, p->new_mode, p->new_name);3956else3957printf(" mode change%06o =>%06o\n",3958 p->old_mode, p->new_mode);3959}3960}39613962static voidshow_rename_copy(struct patch *p)3963{3964const char*renamecopy = p->is_rename ?"rename":"copy";3965const char*old, *new;39663967/* Find common prefix */3968 old = p->old_name;3969new= p->new_name;3970while(1) {3971const char*slash_old, *slash_new;3972 slash_old =strchr(old,'/');3973 slash_new =strchr(new,'/');3974if(!slash_old ||3975!slash_new ||3976 slash_old - old != slash_new -new||3977memcmp(old,new, slash_new -new))3978break;3979 old = slash_old +1;3980new= slash_new +1;3981}3982/* p->old_name thru old is the common prefix, and old and new3983 * through the end of names are renames3984 */3985if(old != p->old_name)3986printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,3987(int)(old - p->old_name), p->old_name,3988 old,new, p->score);3989else3990printf("%s %s=>%s(%d%%)\n", renamecopy,3991 p->old_name, p->new_name, p->score);3992show_mode_change(p,0);3993}39943995static voidsummary_patch_list(struct patch *patch)3996{3997struct patch *p;39983999for(p = patch; p; p = p->next) {4000if(p->is_new)4001show_file_mode_name("create", p->new_mode, p->new_name);4002else if(p->is_delete)4003show_file_mode_name("delete", p->old_mode, p->old_name);4004else{4005if(p->is_rename || p->is_copy)4006show_rename_copy(p);4007else{4008if(p->score) {4009printf(" rewrite%s(%d%%)\n",4010 p->new_name, p->score);4011show_mode_change(p,0);4012}4013else4014show_mode_change(p,1);4015}4016}4017}4018}40194020static voidpatch_stats(struct patch *patch)4021{4022int lines = patch->lines_added + patch->lines_deleted;40234024if(lines > max_change)4025 max_change = lines;4026if(patch->old_name) {4027int len =quote_c_style(patch->old_name, NULL, NULL,0);4028if(!len)4029 len =strlen(patch->old_name);4030if(len > max_len)4031 max_len = len;4032}4033if(patch->new_name) {4034int len =quote_c_style(patch->new_name, NULL, NULL,0);4035if(!len)4036 len =strlen(patch->new_name);4037if(len > max_len)4038 max_len = len;4039}4040}40414042static voidremove_file(struct patch *patch,int rmdir_empty)4043{4044if(update_index) {4045if(remove_file_from_cache(patch->old_name) <0)4046die(_("unable to remove%sfrom index"), patch->old_name);4047}4048if(!cached) {4049if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4050remove_path(patch->old_name);4051}4052}4053}40544055static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)4056{4057struct stat st;4058struct cache_entry *ce;4059int namelen =strlen(path);4060unsigned ce_size =cache_entry_size(namelen);40614062if(!update_index)4063return;40644065 ce =xcalloc(1, ce_size);4066memcpy(ce->name, path, namelen);4067 ce->ce_mode =create_ce_mode(mode);4068 ce->ce_flags =create_ce_flags(0);4069 ce->ce_namelen = namelen;4070if(S_ISGITLINK(mode)) {4071const char*s;40724073if(!skip_prefix(buf,"Subproject commit ", &s) ||4074get_sha1_hex(s, ce->sha1))4075die(_("corrupt patch for submodule%s"), path);4076}else{4077if(!cached) {4078if(lstat(path, &st) <0)4079die_errno(_("unable to stat newly created file '%s'"),4080 path);4081fill_stat_cache_info(ce, &st);4082}4083if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4084die(_("unable to create backing store for newly created file%s"), path);4085}4086if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4087die(_("unable to add cache entry for%s"), path);4088}40894090static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4091{4092int fd;4093struct strbuf nbuf = STRBUF_INIT;40944095if(S_ISGITLINK(mode)) {4096struct stat st;4097if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4098return0;4099returnmkdir(path,0777);4100}41014102if(has_symlinks &&S_ISLNK(mode))4103/* Although buf:size is counted string, it also is NUL4104 * terminated.4105 */4106returnsymlink(buf, path);41074108 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4109if(fd <0)4110return-1;41114112if(convert_to_working_tree(path, buf, size, &nbuf)) {4113 size = nbuf.len;4114 buf = nbuf.buf;4115}4116write_or_die(fd, buf, size);4117strbuf_release(&nbuf);41184119if(close(fd) <0)4120die_errno(_("closing file '%s'"), path);4121return0;4122}41234124/*4125 * We optimistically assume that the directories exist,4126 * which is true 99% of the time anyway. If they don't,4127 * we create them and try again.4128 */4129static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)4130{4131if(cached)4132return;4133if(!try_create_file(path, mode, buf, size))4134return;41354136if(errno == ENOENT) {4137if(safe_create_leading_directories(path))4138return;4139if(!try_create_file(path, mode, buf, size))4140return;4141}41424143if(errno == EEXIST || errno == EACCES) {4144/* We may be trying to create a file where a directory4145 * used to be.4146 */4147struct stat st;4148if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4149 errno = EEXIST;4150}41514152if(errno == EEXIST) {4153unsigned int nr =getpid();41544155for(;;) {4156char newpath[PATH_MAX];4157mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4158if(!try_create_file(newpath, mode, buf, size)) {4159if(!rename(newpath, path))4160return;4161unlink_or_warn(newpath);4162break;4163}4164if(errno != EEXIST)4165break;4166++nr;4167}4168}4169die_errno(_("unable to write file '%s' mode%o"), path, mode);4170}41714172static voidadd_conflicted_stages_file(struct patch *patch)4173{4174int stage, namelen;4175unsigned ce_size, mode;4176struct cache_entry *ce;41774178if(!update_index)4179return;4180 namelen =strlen(patch->new_name);4181 ce_size =cache_entry_size(namelen);4182 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);41834184remove_file_from_cache(patch->new_name);4185for(stage =1; stage <4; stage++) {4186if(is_null_oid(&patch->threeway_stage[stage -1]))4187continue;4188 ce =xcalloc(1, ce_size);4189memcpy(ce->name, patch->new_name, namelen);4190 ce->ce_mode =create_ce_mode(mode);4191 ce->ce_flags =create_ce_flags(stage);4192 ce->ce_namelen = namelen;4193hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4194if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4195die(_("unable to add cache entry for%s"), patch->new_name);4196}4197}41984199static voidcreate_file(struct patch *patch)4200{4201char*path = patch->new_name;4202unsigned mode = patch->new_mode;4203unsigned long size = patch->resultsize;4204char*buf = patch->result;42054206if(!mode)4207 mode = S_IFREG |0644;4208create_one_file(path, mode, buf, size);42094210if(patch->conflicted_threeway)4211add_conflicted_stages_file(patch);4212else4213add_index_file(path, mode, buf, size);4214}42154216/* phase zero is to remove, phase one is to create */4217static voidwrite_out_one_result(struct patch *patch,int phase)4218{4219if(patch->is_delete >0) {4220if(phase ==0)4221remove_file(patch,1);4222return;4223}4224if(patch->is_new >0|| patch->is_copy) {4225if(phase ==1)4226create_file(patch);4227return;4228}4229/*4230 * Rename or modification boils down to the same4231 * thing: remove the old, write the new4232 */4233if(phase ==0)4234remove_file(patch, patch->is_rename);4235if(phase ==1)4236create_file(patch);4237}42384239static intwrite_out_one_reject(struct patch *patch)4240{4241FILE*rej;4242char namebuf[PATH_MAX];4243struct fragment *frag;4244int cnt =0;4245struct strbuf sb = STRBUF_INIT;42464247for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4248if(!frag->rejected)4249continue;4250 cnt++;4251}42524253if(!cnt) {4254if(apply_verbosely)4255say_patch_name(stderr,4256_("Applied patch%scleanly."), patch);4257return0;4258}42594260/* This should not happen, because a removal patch that leaves4261 * contents are marked "rejected" at the patch level.4262 */4263if(!patch->new_name)4264die(_("internal error"));42654266/* Say this even without --verbose */4267strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4268"Applying patch %%swith%drejects...",4269 cnt),4270 cnt);4271say_patch_name(stderr, sb.buf, patch);4272strbuf_release(&sb);42734274 cnt =strlen(patch->new_name);4275if(ARRAY_SIZE(namebuf) <= cnt +5) {4276 cnt =ARRAY_SIZE(namebuf) -5;4277warning(_("truncating .rej filename to %.*s.rej"),4278 cnt -1, patch->new_name);4279}4280memcpy(namebuf, patch->new_name, cnt);4281memcpy(namebuf + cnt,".rej",5);42824283 rej =fopen(namebuf,"w");4284if(!rej)4285returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));42864287/* Normal git tools never deal with .rej, so do not pretend4288 * this is a git patch by saying --git or giving extended4289 * headers. While at it, maybe please "kompare" that wants4290 * the trailing TAB and some garbage at the end of line ;-).4291 */4292fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4293 patch->new_name, patch->new_name);4294for(cnt =1, frag = patch->fragments;4295 frag;4296 cnt++, frag = frag->next) {4297if(!frag->rejected) {4298fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4299continue;4300}4301fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4302fprintf(rej,"%.*s", frag->size, frag->patch);4303if(frag->patch[frag->size-1] !='\n')4304fputc('\n', rej);4305}4306fclose(rej);4307return-1;4308}43094310static intwrite_out_results(struct patch *list)4311{4312int phase;4313int errs =0;4314struct patch *l;4315struct string_list cpath = STRING_LIST_INIT_DUP;43164317for(phase =0; phase <2; phase++) {4318 l = list;4319while(l) {4320if(l->rejected)4321 errs =1;4322else{4323write_out_one_result(l, phase);4324if(phase ==1) {4325if(write_out_one_reject(l))4326 errs =1;4327if(l->conflicted_threeway) {4328string_list_append(&cpath, l->new_name);4329 errs =1;4330}4331}4332}4333 l = l->next;4334}4335}43364337if(cpath.nr) {4338struct string_list_item *item;43394340string_list_sort(&cpath);4341for_each_string_list_item(item, &cpath)4342fprintf(stderr,"U%s\n", item->string);4343string_list_clear(&cpath,0);43444345rerere(0);4346}43474348return errs;4349}43504351static struct lock_file lock_file;43524353#define INACCURATE_EOF (1<<0)4354#define RECOUNT (1<<1)43554356static intapply_patch(int fd,const char*filename,int options)4357{4358size_t offset;4359struct strbuf buf = STRBUF_INIT;/* owns the patch text */4360struct patch *list = NULL, **listp = &list;4361int skipped_patch =0;43624363 patch_input_file = filename;4364read_patch_file(&buf, fd);4365 offset =0;4366while(offset < buf.len) {4367struct patch *patch;4368int nr;43694370 patch =xcalloc(1,sizeof(*patch));4371 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4372 patch->recount = !!(options & RECOUNT);4373 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);4374if(nr <0) {4375free_patch(patch);4376break;4377}4378if(apply_in_reverse)4379reverse_patches(patch);4380if(use_patch(patch)) {4381patch_stats(patch);4382*listp = patch;4383 listp = &patch->next;4384}4385else{4386if(apply_verbosely)4387say_patch_name(stderr,_("Skipped patch '%s'."), patch);4388free_patch(patch);4389 skipped_patch++;4390}4391 offset += nr;4392}43934394if(!list && !skipped_patch)4395die(_("unrecognized input"));43964397if(whitespace_error && (ws_error_action == die_on_ws_error))4398 apply =0;43994400 update_index = check_index && apply;4401if(update_index && newfd <0)4402 newfd =hold_locked_index(&lock_file,1);44034404if(check_index) {4405if(read_cache() <0)4406die(_("unable to read index file"));4407}44084409if((check || apply) &&4410check_patch_list(list) <0&&4411!apply_with_reject)4412exit(1);44134414if(apply &&write_out_results(list)) {4415if(apply_with_reject)4416exit(1);4417/* with --3way, we still need to write the index out */4418return1;4419}44204421if(fake_ancestor)4422build_fake_ancestor(list, fake_ancestor);44234424if(diffstat)4425stat_patch_list(list);44264427if(numstat)4428numstat_patch_list(list);44294430if(summary)4431summary_patch_list(list);44324433free_patch_list(list);4434strbuf_release(&buf);4435string_list_clear(&fn_table,0);4436return0;4437}44384439static voidgit_apply_config(void)4440{4441git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4442git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4443git_config(git_default_config, NULL);4444}44454446static intoption_parse_exclude(const struct option *opt,4447const char*arg,int unset)4448{4449add_name_limit(arg,1);4450return0;4451}44524453static intoption_parse_include(const struct option *opt,4454const char*arg,int unset)4455{4456add_name_limit(arg,0);4457 has_include =1;4458return0;4459}44604461static intoption_parse_p(const struct option *opt,4462const char*arg,int unset)4463{4464 p_value =atoi(arg);4465 p_value_known =1;4466return0;4467}44684469static intoption_parse_space_change(const struct option *opt,4470const char*arg,int unset)4471{4472if(unset)4473 ws_ignore_action = ignore_ws_none;4474else4475 ws_ignore_action = ignore_ws_change;4476return0;4477}44784479static intoption_parse_whitespace(const struct option *opt,4480const char*arg,int unset)4481{4482const char**whitespace_option = opt->value;44834484*whitespace_option = arg;4485parse_whitespace_option(arg);4486return0;4487}44884489static intoption_parse_directory(const struct option *opt,4490const char*arg,int unset)4491{4492strbuf_reset(&root);4493strbuf_addstr(&root, arg);4494strbuf_complete(&root,'/');4495return0;4496}44974498intcmd_apply(int argc,const char**argv,const char*prefix_)4499{4500int i;4501int errs =0;4502int is_not_gitdir = !startup_info->have_repository;4503int force_apply =0;45044505const char*whitespace_option = NULL;45064507struct option builtin_apply_options[] = {4508{ OPTION_CALLBACK,0,"exclude", NULL,N_("path"),4509N_("don't apply changes matching the given path"),45100, option_parse_exclude },4511{ OPTION_CALLBACK,0,"include", NULL,N_("path"),4512N_("apply changes matching the given path"),45130, option_parse_include },4514{ OPTION_CALLBACK,'p', NULL, NULL,N_("num"),4515N_("remove <num> leading slashes from traditional diff paths"),45160, option_parse_p },4517OPT_BOOL(0,"no-add", &no_add,4518N_("ignore additions made by the patch")),4519OPT_BOOL(0,"stat", &diffstat,4520N_("instead of applying the patch, output diffstat for the input")),4521OPT_NOOP_NOARG(0,"allow-binary-replacement"),4522OPT_NOOP_NOARG(0,"binary"),4523OPT_BOOL(0,"numstat", &numstat,4524N_("show number of added and deleted lines in decimal notation")),4525OPT_BOOL(0,"summary", &summary,4526N_("instead of applying the patch, output a summary for the input")),4527OPT_BOOL(0,"check", &check,4528N_("instead of applying the patch, see if the patch is applicable")),4529OPT_BOOL(0,"index", &check_index,4530N_("make sure the patch is applicable to the current index")),4531OPT_BOOL(0,"cached", &cached,4532N_("apply a patch without touching the working tree")),4533OPT_BOOL(0,"unsafe-paths", &unsafe_paths,4534N_("accept a patch that touches outside the working area")),4535OPT_BOOL(0,"apply", &force_apply,4536N_("also apply the patch (use with --stat/--summary/--check)")),4537OPT_BOOL('3',"3way", &threeway,4538N_("attempt three-way merge if a patch does not apply")),4539OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,4540N_("build a temporary index based on embedded index information")),4541/* Think twice before adding "--nul" synonym to this */4542OPT_SET_INT('z', NULL, &line_termination,4543N_("paths are separated with NUL character"),'\0'),4544OPT_INTEGER('C', NULL, &p_context,4545N_("ensure at least <n> lines of context match")),4546{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,N_("action"),4547N_("detect new or modified lines that have whitespace errors"),45480, option_parse_whitespace },4549{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,4550N_("ignore changes in whitespace when finding context"),4551 PARSE_OPT_NOARG, option_parse_space_change },4552{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,4553N_("ignore changes in whitespace when finding context"),4554 PARSE_OPT_NOARG, option_parse_space_change },4555OPT_BOOL('R',"reverse", &apply_in_reverse,4556N_("apply the patch in reverse")),4557OPT_BOOL(0,"unidiff-zero", &unidiff_zero,4558N_("don't expect at least one line of context")),4559OPT_BOOL(0,"reject", &apply_with_reject,4560N_("leave the rejected hunks in corresponding *.rej files")),4561OPT_BOOL(0,"allow-overlap", &allow_overlap,4562N_("allow overlapping hunks")),4563OPT__VERBOSE(&apply_verbosely,N_("be verbose")),4564OPT_BIT(0,"inaccurate-eof", &options,4565N_("tolerate incorrectly detected missing new-line at the end of file"),4566 INACCURATE_EOF),4567OPT_BIT(0,"recount", &options,4568N_("do not trust the line counts in the hunk headers"),4569 RECOUNT),4570{ OPTION_CALLBACK,0,"directory", NULL,N_("root"),4571N_("prepend <root> to all filenames"),45720, option_parse_directory },4573OPT_END()4574};45754576 prefix = prefix_;4577 prefix_length = prefix ?strlen(prefix) :0;4578git_apply_config();4579if(apply_default_whitespace)4580parse_whitespace_option(apply_default_whitespace);4581if(apply_default_ignorewhitespace)4582parse_ignorewhitespace_option(apply_default_ignorewhitespace);45834584 argc =parse_options(argc, argv, prefix, builtin_apply_options,4585 apply_usage,0);45864587if(apply_with_reject && threeway)4588die("--reject and --3way cannot be used together.");4589if(cached && threeway)4590die("--cached and --3way cannot be used together.");4591if(threeway) {4592if(is_not_gitdir)4593die(_("--3way outside a repository"));4594 check_index =1;4595}4596if(apply_with_reject)4597 apply = apply_verbosely =1;4598if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))4599 apply =0;4600if(check_index && is_not_gitdir)4601die(_("--index outside a repository"));4602if(cached) {4603if(is_not_gitdir)4604die(_("--cached outside a repository"));4605 check_index =1;4606}4607if(check_index)4608 unsafe_paths =0;46094610for(i =0; i < argc; i++) {4611const char*arg = argv[i];4612int fd;46134614if(!strcmp(arg,"-")) {4615 errs |=apply_patch(0,"<stdin>", options);4616 read_stdin =0;4617continue;4618}else if(0< prefix_length)4619 arg =prefix_filename(prefix, prefix_length, arg);46204621 fd =open(arg, O_RDONLY);4622if(fd <0)4623die_errno(_("can't open patch '%s'"), arg);4624 read_stdin =0;4625set_default_whitespace_mode(whitespace_option);4626 errs |=apply_patch(fd, arg, options);4627close(fd);4628}4629set_default_whitespace_mode(whitespace_option);4630if(read_stdin)4631 errs |=apply_patch(0,"<stdin>", options);4632if(whitespace_error) {4633if(squelch_whitespace_errors &&4634 squelch_whitespace_errors < whitespace_error) {4635int squelched =4636 whitespace_error - squelch_whitespace_errors;4637warning(Q_("squelched%dwhitespace error",4638"squelched%dwhitespace errors",4639 squelched),4640 squelched);4641}4642if(ws_error_action == die_on_ws_error)4643die(Q_("%dline adds whitespace errors.",4644"%dlines add whitespace errors.",4645 whitespace_error),4646 whitespace_error);4647if(applied_after_fixing_ws && apply)4648warning("%dline%sapplied after"4649" fixing whitespace errors.",4650 applied_after_fixing_ws,4651 applied_after_fixing_ws ==1?"":"s");4652else if(whitespace_error)4653warning(Q_("%dline adds whitespace errors.",4654"%dlines add whitespace errors.",4655 whitespace_error),4656 whitespace_error);4657}46584659if(update_index) {4660if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK))4661die(_("Unable to write new index file"));4662}46634664return!!errs;4665}