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 state_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 state_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 state_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, state_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, state_p_value); 888 patch->old_name = name; 889}else{ 890char*first_name; 891 first_name =find_name_traditional(first, NULL, state_p_value); 892 name =find_name_traditional(second, first_name, state_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"), state_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 voidgitdiff_verify_name(const char*line,int isnull,char**name,int side) 929{ 930if(!*name && !isnull) { 931*name =find_name(line, NULL, state_p_value, TERM_TAB); 932return; 933} 934 935if(*name) { 936int len =strlen(*name); 937char*another; 938if(isnull) 939die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 940*name, state_linenr); 941 another =find_name(line, NULL, state_p_value, TERM_TAB); 942if(!another ||memcmp(another, *name, len +1)) 943die((side == DIFF_NEW_NAME) ? 944_("git apply: bad git-diff - inconsistent new filename on line%d") : 945_("git apply: bad git-diff - inconsistent old filename on line%d"), state_linenr); 946free(another); 947}else{ 948/* expect "/dev/null" */ 949if(memcmp("/dev/null", line,9) || line[9] !='\n') 950die(_("git apply: bad git-diff - expected /dev/null on line%d"), state_linenr); 951} 952} 953 954static intgitdiff_oldname(const char*line,struct patch *patch) 955{ 956gitdiff_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{ 963gitdiff_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, state_p_value ? state_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, state_p_value ? state_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, state_p_value ? state_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, state_p_value ? state_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(!state_p_value)1096return(llen && line[0] =='/') ? NULL : line;10971098 nslash = state_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 state_linenr++;1276for(offset = len ; size >0; offset += len, size -= len, line += len, state_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, state_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 state_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 state_p_value),1485 state_p_value, state_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)", state_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 state_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, state_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 state_linenr++;1572 added = deleted =0;1573for(offset = len;15740< size;1575 offset += len, size -= len, line += len, state_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 = state_linenr;1672 len =parse_fragment(line, size, patch, fragment);1673if(len <=0)1674die(_("corrupt patch at line%d"), state_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 state_linenr++;1803 buffer += llen;1804while(1) {1805int byte_length, max_byte_length, newsize;1806 llen =linelen(buffer, size);1807 used += llen;1808 state_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 state_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"), state_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 state_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 state_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"), state_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 l_len = postimage->line[i].len;2198if(!(postimage->line[i].flag & LINE_COMMON)) {2199/* an added line -- no counterparts in preimage */2200memmove(new, old, l_len);2201 old += l_len;2202new+= l_len;2203continue;2204}22052206/* a common context -- skip it in the original postimage */2207 old += l_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 l_len = preimage->line[ctx].len;2227memcpy(new, fixed, l_len);2228new+= l_len;2229 fixed += l_len;2230 postimage->line[i].len = l_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 intline_by_line_fuzzy_match(struct image *img,2246struct image *preimage,2247struct image *postimage,2248unsigned longtry,2249int try_lno,2250int preimage_limit)2251{2252int i;2253size_t imgoff =0;2254size_t preoff =0;2255size_t postlen = postimage->len;2256size_t extra_chars;2257char*buf;2258char*preimage_eof;2259char*preimage_end;2260struct strbuf fixed;2261char*fixed_buf;2262size_t fixed_len;22632264for(i =0; i < preimage_limit; i++) {2265size_t prelen = preimage->line[i].len;2266size_t imglen = img->line[try_lno+i].len;22672268if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2269 preimage->buf + preoff, prelen))2270return0;2271if(preimage->line[i].flag & LINE_COMMON)2272 postlen += imglen - prelen;2273 imgoff += imglen;2274 preoff += prelen;2275}22762277/*2278 * Ok, the preimage matches with whitespace fuzz.2279 *2280 * imgoff now holds the true length of the target that2281 * matches the preimage before the end of the file.2282 *2283 * Count the number of characters in the preimage that fall2284 * beyond the end of the file and make sure that all of them2285 * are whitespace characters. (This can only happen if2286 * we are removing blank lines at the end of the file.)2287 */2288 buf = preimage_eof = preimage->buf + preoff;2289for( ; i < preimage->nr; i++)2290 preoff += preimage->line[i].len;2291 preimage_end = preimage->buf + preoff;2292for( ; buf < preimage_end; buf++)2293if(!isspace(*buf))2294return0;22952296/*2297 * Update the preimage and the common postimage context2298 * lines to use the same whitespace as the target.2299 * If whitespace is missing in the target (i.e.2300 * if the preimage extends beyond the end of the file),2301 * use the whitespace from the preimage.2302 */2303 extra_chars = preimage_end - preimage_eof;2304strbuf_init(&fixed, imgoff + extra_chars);2305strbuf_add(&fixed, img->buf +try, imgoff);2306strbuf_add(&fixed, preimage_eof, extra_chars);2307 fixed_buf =strbuf_detach(&fixed, &fixed_len);2308update_pre_post_images(preimage, postimage,2309 fixed_buf, fixed_len, postlen);2310return1;2311}23122313static intmatch_fragment(struct image *img,2314struct image *preimage,2315struct image *postimage,2316unsigned longtry,2317int try_lno,2318unsigned ws_rule,2319int match_beginning,int match_end)2320{2321int i;2322char*fixed_buf, *buf, *orig, *target;2323struct strbuf fixed;2324size_t fixed_len, postlen;2325int preimage_limit;23262327if(preimage->nr + try_lno <= img->nr) {2328/*2329 * The hunk falls within the boundaries of img.2330 */2331 preimage_limit = preimage->nr;2332if(match_end && (preimage->nr + try_lno != img->nr))2333return0;2334}else if(ws_error_action == correct_ws_error &&2335(ws_rule & WS_BLANK_AT_EOF)) {2336/*2337 * This hunk extends beyond the end of img, and we are2338 * removing blank lines at the end of the file. This2339 * many lines from the beginning of the preimage must2340 * match with img, and the remainder of the preimage2341 * must be blank.2342 */2343 preimage_limit = img->nr - try_lno;2344}else{2345/*2346 * The hunk extends beyond the end of the img and2347 * we are not removing blanks at the end, so we2348 * should reject the hunk at this position.2349 */2350return0;2351}23522353if(match_beginning && try_lno)2354return0;23552356/* Quick hash check */2357for(i =0; i < preimage_limit; i++)2358if((img->line[try_lno + i].flag & LINE_PATCHED) ||2359(preimage->line[i].hash != img->line[try_lno + i].hash))2360return0;23612362if(preimage_limit == preimage->nr) {2363/*2364 * Do we have an exact match? If we were told to match2365 * at the end, size must be exactly at try+fragsize,2366 * otherwise try+fragsize must be still within the preimage,2367 * and either case, the old piece should match the preimage2368 * exactly.2369 */2370if((match_end2371? (try+ preimage->len == img->len)2372: (try+ preimage->len <= img->len)) &&2373!memcmp(img->buf +try, preimage->buf, preimage->len))2374return1;2375}else{2376/*2377 * The preimage extends beyond the end of img, so2378 * there cannot be an exact match.2379 *2380 * There must be one non-blank context line that match2381 * a line before the end of img.2382 */2383char*buf_end;23842385 buf = preimage->buf;2386 buf_end = buf;2387for(i =0; i < preimage_limit; i++)2388 buf_end += preimage->line[i].len;23892390for( ; buf < buf_end; buf++)2391if(!isspace(*buf))2392break;2393if(buf == buf_end)2394return0;2395}23962397/*2398 * No exact match. If we are ignoring whitespace, run a line-by-line2399 * fuzzy matching. We collect all the line length information because2400 * we need it to adjust whitespace if we match.2401 */2402if(ws_ignore_action == ignore_ws_change)2403returnline_by_line_fuzzy_match(img, preimage, postimage,2404try, try_lno, preimage_limit);24052406if(ws_error_action != correct_ws_error)2407return0;24082409/*2410 * The hunk does not apply byte-by-byte, but the hash says2411 * it might with whitespace fuzz. We weren't asked to2412 * ignore whitespace, we were asked to correct whitespace2413 * errors, so let's try matching after whitespace correction.2414 *2415 * While checking the preimage against the target, whitespace2416 * errors in both fixed, we count how large the corresponding2417 * postimage needs to be. The postimage prepared by2418 * apply_one_fragment() has whitespace errors fixed on added2419 * lines already, but the common lines were propagated as-is,2420 * which may become longer when their whitespace errors are2421 * fixed.2422 */24232424/* First count added lines in postimage */2425 postlen =0;2426for(i =0; i < postimage->nr; i++) {2427if(!(postimage->line[i].flag & LINE_COMMON))2428 postlen += postimage->line[i].len;2429}24302431/*2432 * The preimage may extend beyond the end of the file,2433 * but in this loop we will only handle the part of the2434 * preimage that falls within the file.2435 */2436strbuf_init(&fixed, preimage->len +1);2437 orig = preimage->buf;2438 target = img->buf +try;2439for(i =0; i < preimage_limit; i++) {2440size_t oldlen = preimage->line[i].len;2441size_t tgtlen = img->line[try_lno + i].len;2442size_t fixstart = fixed.len;2443struct strbuf tgtfix;2444int match;24452446/* Try fixing the line in the preimage */2447ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24482449/* Try fixing the line in the target */2450strbuf_init(&tgtfix, tgtlen);2451ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);24522453/*2454 * If they match, either the preimage was based on2455 * a version before our tree fixed whitespace breakage,2456 * or we are lacking a whitespace-fix patch the tree2457 * the preimage was based on already had (i.e. target2458 * has whitespace breakage, the preimage doesn't).2459 * In either case, we are fixing the whitespace breakages2460 * so we might as well take the fix together with their2461 * real change.2462 */2463 match = (tgtfix.len == fixed.len - fixstart &&2464!memcmp(tgtfix.buf, fixed.buf + fixstart,2465 fixed.len - fixstart));24662467/* Add the length if this is common with the postimage */2468if(preimage->line[i].flag & LINE_COMMON)2469 postlen += tgtfix.len;24702471strbuf_release(&tgtfix);2472if(!match)2473goto unmatch_exit;24742475 orig += oldlen;2476 target += tgtlen;2477}247824792480/*2481 * Now handle the lines in the preimage that falls beyond the2482 * end of the file (if any). They will only match if they are2483 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2484 * false).2485 */2486for( ; i < preimage->nr; i++) {2487size_t fixstart = fixed.len;/* start of the fixed preimage */2488size_t oldlen = preimage->line[i].len;2489int j;24902491/* Try fixing the line in the preimage */2492ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24932494for(j = fixstart; j < fixed.len; j++)2495if(!isspace(fixed.buf[j]))2496goto unmatch_exit;24972498 orig += oldlen;2499}25002501/*2502 * Yes, the preimage is based on an older version that still2503 * has whitespace breakages unfixed, and fixing them makes the2504 * hunk match. Update the context lines in the postimage.2505 */2506 fixed_buf =strbuf_detach(&fixed, &fixed_len);2507if(postlen < postimage->len)2508 postlen =0;2509update_pre_post_images(preimage, postimage,2510 fixed_buf, fixed_len, postlen);2511return1;25122513 unmatch_exit:2514strbuf_release(&fixed);2515return0;2516}25172518static intfind_pos(struct image *img,2519struct image *preimage,2520struct image *postimage,2521int line,2522unsigned ws_rule,2523int match_beginning,int match_end)2524{2525int i;2526unsigned long backwards, forwards,try;2527int backwards_lno, forwards_lno, try_lno;25282529/*2530 * If match_beginning or match_end is specified, there is no2531 * point starting from a wrong line that will never match and2532 * wander around and wait for a match at the specified end.2533 */2534if(match_beginning)2535 line =0;2536else if(match_end)2537 line = img->nr - preimage->nr;25382539/*2540 * Because the comparison is unsigned, the following test2541 * will also take care of a negative line number that can2542 * result when match_end and preimage is larger than the target.2543 */2544if((size_t) line > img->nr)2545 line = img->nr;25462547try=0;2548for(i =0; i < line; i++)2549try+= img->line[i].len;25502551/*2552 * There's probably some smart way to do this, but I'll leave2553 * that to the smart and beautiful people. I'm simple and stupid.2554 */2555 backwards =try;2556 backwards_lno = line;2557 forwards =try;2558 forwards_lno = line;2559 try_lno = line;25602561for(i =0; ; i++) {2562if(match_fragment(img, preimage, postimage,2563try, try_lno, ws_rule,2564 match_beginning, match_end))2565return try_lno;25662567 again:2568if(backwards_lno ==0&& forwards_lno == img->nr)2569break;25702571if(i &1) {2572if(backwards_lno ==0) {2573 i++;2574goto again;2575}2576 backwards_lno--;2577 backwards -= img->line[backwards_lno].len;2578try= backwards;2579 try_lno = backwards_lno;2580}else{2581if(forwards_lno == img->nr) {2582 i++;2583goto again;2584}2585 forwards += img->line[forwards_lno].len;2586 forwards_lno++;2587try= forwards;2588 try_lno = forwards_lno;2589}25902591}2592return-1;2593}25942595static voidremove_first_line(struct image *img)2596{2597 img->buf += img->line[0].len;2598 img->len -= img->line[0].len;2599 img->line++;2600 img->nr--;2601}26022603static voidremove_last_line(struct image *img)2604{2605 img->len -= img->line[--img->nr].len;2606}26072608/*2609 * The change from "preimage" and "postimage" has been found to2610 * apply at applied_pos (counts in line numbers) in "img".2611 * Update "img" to remove "preimage" and replace it with "postimage".2612 */2613static voidupdate_image(struct image *img,2614int applied_pos,2615struct image *preimage,2616struct image *postimage)2617{2618/*2619 * remove the copy of preimage at offset in img2620 * and replace it with postimage2621 */2622int i, nr;2623size_t remove_count, insert_count, applied_at =0;2624char*result;2625int preimage_limit;26262627/*2628 * If we are removing blank lines at the end of img,2629 * the preimage may extend beyond the end.2630 * If that is the case, we must be careful only to2631 * remove the part of the preimage that falls within2632 * the boundaries of img. Initialize preimage_limit2633 * to the number of lines in the preimage that falls2634 * within the boundaries.2635 */2636 preimage_limit = preimage->nr;2637if(preimage_limit > img->nr - applied_pos)2638 preimage_limit = img->nr - applied_pos;26392640for(i =0; i < applied_pos; i++)2641 applied_at += img->line[i].len;26422643 remove_count =0;2644for(i =0; i < preimage_limit; i++)2645 remove_count += img->line[applied_pos + i].len;2646 insert_count = postimage->len;26472648/* Adjust the contents */2649 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2650memcpy(result, img->buf, applied_at);2651memcpy(result + applied_at, postimage->buf, postimage->len);2652memcpy(result + applied_at + postimage->len,2653 img->buf + (applied_at + remove_count),2654 img->len - (applied_at + remove_count));2655free(img->buf);2656 img->buf = result;2657 img->len += insert_count - remove_count;2658 result[img->len] ='\0';26592660/* Adjust the line table */2661 nr = img->nr + postimage->nr - preimage_limit;2662if(preimage_limit < postimage->nr) {2663/*2664 * NOTE: this knows that we never call remove_first_line()2665 * on anything other than pre/post image.2666 */2667REALLOC_ARRAY(img->line, nr);2668 img->line_allocated = img->line;2669}2670if(preimage_limit != postimage->nr)2671memmove(img->line + applied_pos + postimage->nr,2672 img->line + applied_pos + preimage_limit,2673(img->nr - (applied_pos + preimage_limit)) *2674sizeof(*img->line));2675memcpy(img->line + applied_pos,2676 postimage->line,2677 postimage->nr *sizeof(*img->line));2678if(!allow_overlap)2679for(i =0; i < postimage->nr; i++)2680 img->line[applied_pos + i].flag |= LINE_PATCHED;2681 img->nr = nr;2682}26832684/*2685 * Use the patch-hunk text in "frag" to prepare two images (preimage and2686 * postimage) for the hunk. Find lines that match "preimage" in "img" and2687 * replace the part of "img" with "postimage" text.2688 */2689static intapply_one_fragment(struct image *img,struct fragment *frag,2690int inaccurate_eof,unsigned ws_rule,2691int nth_fragment)2692{2693int match_beginning, match_end;2694const char*patch = frag->patch;2695int size = frag->size;2696char*old, *oldlines;2697struct strbuf newlines;2698int new_blank_lines_at_end =0;2699int found_new_blank_lines_at_end =0;2700int hunk_linenr = frag->linenr;2701unsigned long leading, trailing;2702int pos, applied_pos;2703struct image preimage;2704struct image postimage;27052706memset(&preimage,0,sizeof(preimage));2707memset(&postimage,0,sizeof(postimage));2708 oldlines =xmalloc(size);2709strbuf_init(&newlines, size);27102711 old = oldlines;2712while(size >0) {2713char first;2714int len =linelen(patch, size);2715int plen;2716int added_blank_line =0;2717int is_blank_context =0;2718size_t start;27192720if(!len)2721break;27222723/*2724 * "plen" is how much of the line we should use for2725 * the actual patch data. Normally we just remove the2726 * first character on the line, but if the line is2727 * followed by "\ No newline", then we also remove the2728 * last one (which is the newline, of course).2729 */2730 plen = len -1;2731if(len < size && patch[len] =='\\')2732 plen--;2733 first = *patch;2734if(apply_in_reverse) {2735if(first =='-')2736 first ='+';2737else if(first =='+')2738 first ='-';2739}27402741switch(first) {2742case'\n':2743/* Newer GNU diff, empty context line */2744if(plen <0)2745/* ... followed by '\No newline'; nothing */2746break;2747*old++ ='\n';2748strbuf_addch(&newlines,'\n');2749add_line_info(&preimage,"\n",1, LINE_COMMON);2750add_line_info(&postimage,"\n",1, LINE_COMMON);2751 is_blank_context =1;2752break;2753case' ':2754if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2755ws_blank_line(patch +1, plen, ws_rule))2756 is_blank_context =1;2757case'-':2758memcpy(old, patch +1, plen);2759add_line_info(&preimage, old, plen,2760(first ==' '? LINE_COMMON :0));2761 old += plen;2762if(first =='-')2763break;2764/* Fall-through for ' ' */2765case'+':2766/* --no-add does not add new lines */2767if(first =='+'&& no_add)2768break;27692770 start = newlines.len;2771if(first !='+'||2772!whitespace_error ||2773 ws_error_action != correct_ws_error) {2774strbuf_add(&newlines, patch +1, plen);2775}2776else{2777ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2778}2779add_line_info(&postimage, newlines.buf + start, newlines.len - start,2780(first =='+'?0: LINE_COMMON));2781if(first =='+'&&2782(ws_rule & WS_BLANK_AT_EOF) &&2783ws_blank_line(patch +1, plen, ws_rule))2784 added_blank_line =1;2785break;2786case'@':case'\\':2787/* Ignore it, we already handled it */2788break;2789default:2790if(apply_verbosely)2791error(_("invalid start of line: '%c'"), first);2792 applied_pos = -1;2793goto out;2794}2795if(added_blank_line) {2796if(!new_blank_lines_at_end)2797 found_new_blank_lines_at_end = hunk_linenr;2798 new_blank_lines_at_end++;2799}2800else if(is_blank_context)2801;2802else2803 new_blank_lines_at_end =0;2804 patch += len;2805 size -= len;2806 hunk_linenr++;2807}2808if(inaccurate_eof &&2809 old > oldlines && old[-1] =='\n'&&2810 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2811 old--;2812strbuf_setlen(&newlines, newlines.len -1);2813}28142815 leading = frag->leading;2816 trailing = frag->trailing;28172818/*2819 * A hunk to change lines at the beginning would begin with2820 * @@ -1,L +N,M @@2821 * but we need to be careful. -U0 that inserts before the second2822 * line also has this pattern.2823 *2824 * And a hunk to add to an empty file would begin with2825 * @@ -0,0 +N,M @@2826 *2827 * In other words, a hunk that is (frag->oldpos <= 1) with or2828 * without leading context must match at the beginning.2829 */2830 match_beginning = (!frag->oldpos ||2831(frag->oldpos ==1&& !unidiff_zero));28322833/*2834 * A hunk without trailing lines must match at the end.2835 * However, we simply cannot tell if a hunk must match end2836 * from the lack of trailing lines if the patch was generated2837 * with unidiff without any context.2838 */2839 match_end = !unidiff_zero && !trailing;28402841 pos = frag->newpos ? (frag->newpos -1) :0;2842 preimage.buf = oldlines;2843 preimage.len = old - oldlines;2844 postimage.buf = newlines.buf;2845 postimage.len = newlines.len;2846 preimage.line = preimage.line_allocated;2847 postimage.line = postimage.line_allocated;28482849for(;;) {28502851 applied_pos =find_pos(img, &preimage, &postimage, pos,2852 ws_rule, match_beginning, match_end);28532854if(applied_pos >=0)2855break;28562857/* Am I at my context limits? */2858if((leading <= p_context) && (trailing <= p_context))2859break;2860if(match_beginning || match_end) {2861 match_beginning = match_end =0;2862continue;2863}28642865/*2866 * Reduce the number of context lines; reduce both2867 * leading and trailing if they are equal otherwise2868 * just reduce the larger context.2869 */2870if(leading >= trailing) {2871remove_first_line(&preimage);2872remove_first_line(&postimage);2873 pos--;2874 leading--;2875}2876if(trailing > leading) {2877remove_last_line(&preimage);2878remove_last_line(&postimage);2879 trailing--;2880}2881}28822883if(applied_pos >=0) {2884if(new_blank_lines_at_end &&2885 preimage.nr + applied_pos >= img->nr &&2886(ws_rule & WS_BLANK_AT_EOF) &&2887 ws_error_action != nowarn_ws_error) {2888record_ws_error(WS_BLANK_AT_EOF,"+",1,2889 found_new_blank_lines_at_end);2890if(ws_error_action == correct_ws_error) {2891while(new_blank_lines_at_end--)2892remove_last_line(&postimage);2893}2894/*2895 * We would want to prevent write_out_results()2896 * from taking place in apply_patch() that follows2897 * the callchain led us here, which is:2898 * apply_patch->check_patch_list->check_patch->2899 * apply_data->apply_fragments->apply_one_fragment2900 */2901if(ws_error_action == die_on_ws_error)2902 apply =0;2903}29042905if(apply_verbosely && applied_pos != pos) {2906int offset = applied_pos - pos;2907if(apply_in_reverse)2908 offset =0- offset;2909fprintf_ln(stderr,2910Q_("Hunk #%dsucceeded at%d(offset%dline).",2911"Hunk #%dsucceeded at%d(offset%dlines).",2912 offset),2913 nth_fragment, applied_pos +1, offset);2914}29152916/*2917 * Warn if it was necessary to reduce the number2918 * of context lines.2919 */2920if((leading != frag->leading) ||2921(trailing != frag->trailing))2922fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2923" to apply fragment at%d"),2924 leading, trailing, applied_pos+1);2925update_image(img, applied_pos, &preimage, &postimage);2926}else{2927if(apply_verbosely)2928error(_("while searching for:\n%.*s"),2929(int)(old - oldlines), oldlines);2930}29312932out:2933free(oldlines);2934strbuf_release(&newlines);2935free(preimage.line_allocated);2936free(postimage.line_allocated);29372938return(applied_pos <0);2939}29402941static intapply_binary_fragment(struct image *img,struct patch *patch)2942{2943struct fragment *fragment = patch->fragments;2944unsigned long len;2945void*dst;29462947if(!fragment)2948returnerror(_("missing binary patch data for '%s'"),2949 patch->new_name ?2950 patch->new_name :2951 patch->old_name);29522953/* Binary patch is irreversible without the optional second hunk */2954if(apply_in_reverse) {2955if(!fragment->next)2956returnerror("cannot reverse-apply a binary patch "2957"without the reverse hunk to '%s'",2958 patch->new_name2959? patch->new_name : patch->old_name);2960 fragment = fragment->next;2961}2962switch(fragment->binary_patch_method) {2963case BINARY_DELTA_DEFLATED:2964 dst =patch_delta(img->buf, img->len, fragment->patch,2965 fragment->size, &len);2966if(!dst)2967return-1;2968clear_image(img);2969 img->buf = dst;2970 img->len = len;2971return0;2972case BINARY_LITERAL_DEFLATED:2973clear_image(img);2974 img->len = fragment->size;2975 img->buf =xmemdupz(fragment->patch, img->len);2976return0;2977}2978return-1;2979}29802981/*2982 * Replace "img" with the result of applying the binary patch.2983 * The binary patch data itself in patch->fragment is still kept2984 * but the preimage prepared by the caller in "img" is freed here2985 * or in the helper function apply_binary_fragment() this calls.2986 */2987static intapply_binary(struct image *img,struct patch *patch)2988{2989const char*name = patch->old_name ? patch->old_name : patch->new_name;2990unsigned char sha1[20];29912992/*2993 * For safety, we require patch index line to contain2994 * full 40-byte textual SHA1 for old and new, at least for now.2995 */2996if(strlen(patch->old_sha1_prefix) !=40||2997strlen(patch->new_sha1_prefix) !=40||2998get_sha1_hex(patch->old_sha1_prefix, sha1) ||2999get_sha1_hex(patch->new_sha1_prefix, sha1))3000returnerror("cannot apply binary patch to '%s' "3001"without full index line", name);30023003if(patch->old_name) {3004/*3005 * See if the old one matches what the patch3006 * applies to.3007 */3008hash_sha1_file(img->buf, img->len, blob_type, sha1);3009if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3010returnerror("the patch applies to '%s' (%s), "3011"which does not match the "3012"current contents.",3013 name,sha1_to_hex(sha1));3014}3015else{3016/* Otherwise, the old one must be empty. */3017if(img->len)3018returnerror("the patch applies to an empty "3019"'%s' but it is not empty", name);3020}30213022get_sha1_hex(patch->new_sha1_prefix, sha1);3023if(is_null_sha1(sha1)) {3024clear_image(img);3025return0;/* deletion patch */3026}30273028if(has_sha1_file(sha1)) {3029/* We already have the postimage */3030enum object_type type;3031unsigned long size;3032char*result;30333034 result =read_sha1_file(sha1, &type, &size);3035if(!result)3036returnerror("the necessary postimage%sfor "3037"'%s' cannot be read",3038 patch->new_sha1_prefix, name);3039clear_image(img);3040 img->buf = result;3041 img->len = size;3042}else{3043/*3044 * We have verified buf matches the preimage;3045 * apply the patch data to it, which is stored3046 * in the patch->fragments->{patch,size}.3047 */3048if(apply_binary_fragment(img, patch))3049returnerror(_("binary patch does not apply to '%s'"),3050 name);30513052/* verify that the result matches */3053hash_sha1_file(img->buf, img->len, blob_type, sha1);3054if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3055returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3056 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3057}30583059return0;3060}30613062static intapply_fragments(struct image *img,struct patch *patch)3063{3064struct fragment *frag = patch->fragments;3065const char*name = patch->old_name ? patch->old_name : patch->new_name;3066unsigned ws_rule = patch->ws_rule;3067unsigned inaccurate_eof = patch->inaccurate_eof;3068int nth =0;30693070if(patch->is_binary)3071returnapply_binary(img, patch);30723073while(frag) {3074 nth++;3075if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {3076error(_("patch failed:%s:%ld"), name, frag->oldpos);3077if(!apply_with_reject)3078return-1;3079 frag->rejected =1;3080}3081 frag = frag->next;3082}3083return0;3084}30853086static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3087{3088if(S_ISGITLINK(mode)) {3089strbuf_grow(buf,100);3090strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3091}else{3092enum object_type type;3093unsigned long sz;3094char*result;30953096 result =read_sha1_file(sha1, &type, &sz);3097if(!result)3098return-1;3099/* XXX read_sha1_file NUL-terminates */3100strbuf_attach(buf, result, sz, sz +1);3101}3102return0;3103}31043105static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3106{3107if(!ce)3108return0;3109returnread_blob_object(buf, ce->sha1, ce->ce_mode);3110}31113112static struct patch *in_fn_table(const char*name)3113{3114struct string_list_item *item;31153116if(name == NULL)3117return NULL;31183119 item =string_list_lookup(&fn_table, name);3120if(item != NULL)3121return(struct patch *)item->util;31223123return NULL;3124}31253126/*3127 * item->util in the filename table records the status of the path.3128 * Usually it points at a patch (whose result records the contents3129 * of it after applying it), but it could be PATH_WAS_DELETED for a3130 * path that a previously applied patch has already removed, or3131 * PATH_TO_BE_DELETED for a path that a later patch would remove.3132 *3133 * The latter is needed to deal with a case where two paths A and B3134 * are swapped by first renaming A to B and then renaming B to A;3135 * moving A to B should not be prevented due to presence of B as we3136 * will remove it in a later patch.3137 */3138#define PATH_TO_BE_DELETED ((struct patch *) -2)3139#define PATH_WAS_DELETED ((struct patch *) -1)31403141static intto_be_deleted(struct patch *patch)3142{3143return patch == PATH_TO_BE_DELETED;3144}31453146static intwas_deleted(struct patch *patch)3147{3148return patch == PATH_WAS_DELETED;3149}31503151static voidadd_to_fn_table(struct patch *patch)3152{3153struct string_list_item *item;31543155/*3156 * Always add new_name unless patch is a deletion3157 * This should cover the cases for normal diffs,3158 * file creations and copies3159 */3160if(patch->new_name != NULL) {3161 item =string_list_insert(&fn_table, patch->new_name);3162 item->util = patch;3163}31643165/*3166 * store a failure on rename/deletion cases because3167 * later chunks shouldn't patch old names3168 */3169if((patch->new_name == NULL) || (patch->is_rename)) {3170 item =string_list_insert(&fn_table, patch->old_name);3171 item->util = PATH_WAS_DELETED;3172}3173}31743175static voidprepare_fn_table(struct patch *patch)3176{3177/*3178 * store information about incoming file deletion3179 */3180while(patch) {3181if((patch->new_name == NULL) || (patch->is_rename)) {3182struct string_list_item *item;3183 item =string_list_insert(&fn_table, patch->old_name);3184 item->util = PATH_TO_BE_DELETED;3185}3186 patch = patch->next;3187}3188}31893190static intcheckout_target(struct index_state *istate,3191struct cache_entry *ce,struct stat *st)3192{3193struct checkout costate;31943195memset(&costate,0,sizeof(costate));3196 costate.base_dir ="";3197 costate.refresh_cache =1;3198 costate.istate = istate;3199if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3200returnerror(_("cannot checkout%s"), ce->name);3201return0;3202}32033204static struct patch *previous_patch(struct patch *patch,int*gone)3205{3206struct patch *previous;32073208*gone =0;3209if(patch->is_copy || patch->is_rename)3210return NULL;/* "git" patches do not depend on the order */32113212 previous =in_fn_table(patch->old_name);3213if(!previous)3214return NULL;32153216if(to_be_deleted(previous))3217return NULL;/* the deletion hasn't happened yet */32183219if(was_deleted(previous))3220*gone =1;32213222return previous;3223}32243225static intverify_index_match(const struct cache_entry *ce,struct stat *st)3226{3227if(S_ISGITLINK(ce->ce_mode)) {3228if(!S_ISDIR(st->st_mode))3229return-1;3230return0;3231}3232returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3233}32343235#define SUBMODULE_PATCH_WITHOUT_INDEX 132363237static intload_patch_target(struct strbuf *buf,3238const struct cache_entry *ce,3239struct stat *st,3240const char*name,3241unsigned expected_mode)3242{3243if(cached || check_index) {3244if(read_file_or_gitlink(ce, buf))3245returnerror(_("read of%sfailed"), name);3246}else if(name) {3247if(S_ISGITLINK(expected_mode)) {3248if(ce)3249returnread_file_or_gitlink(ce, buf);3250else3251return SUBMODULE_PATCH_WITHOUT_INDEX;3252}else if(has_symlink_leading_path(name,strlen(name))) {3253returnerror(_("reading from '%s' beyond a symbolic link"), name);3254}else{3255if(read_old_data(st, name, buf))3256returnerror(_("read of%sfailed"), name);3257}3258}3259return0;3260}32613262/*3263 * We are about to apply "patch"; populate the "image" with the3264 * current version we have, from the working tree or from the index,3265 * depending on the situation e.g. --cached/--index. If we are3266 * applying a non-git patch that incrementally updates the tree,3267 * we read from the result of a previous diff.3268 */3269static intload_preimage(struct image *image,3270struct patch *patch,struct stat *st,3271const struct cache_entry *ce)3272{3273struct strbuf buf = STRBUF_INIT;3274size_t len;3275char*img;3276struct patch *previous;3277int status;32783279 previous =previous_patch(patch, &status);3280if(status)3281returnerror(_("path%shas been renamed/deleted"),3282 patch->old_name);3283if(previous) {3284/* We have a patched copy in memory; use that. */3285strbuf_add(&buf, previous->result, previous->resultsize);3286}else{3287 status =load_patch_target(&buf, ce, st,3288 patch->old_name, patch->old_mode);3289if(status <0)3290return status;3291else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3292/*3293 * There is no way to apply subproject3294 * patch without looking at the index.3295 * NEEDSWORK: shouldn't this be flagged3296 * as an error???3297 */3298free_fragment_list(patch->fragments);3299 patch->fragments = NULL;3300}else if(status) {3301returnerror(_("read of%sfailed"), patch->old_name);3302}3303}33043305 img =strbuf_detach(&buf, &len);3306prepare_image(image, img, len, !patch->is_binary);3307return0;3308}33093310static intthree_way_merge(struct image *image,3311char*path,3312const unsigned char*base,3313const unsigned char*ours,3314const unsigned char*theirs)3315{3316 mmfile_t base_file, our_file, their_file;3317 mmbuffer_t result = { NULL };3318int status;33193320read_mmblob(&base_file, base);3321read_mmblob(&our_file, ours);3322read_mmblob(&their_file, theirs);3323 status =ll_merge(&result, path,3324&base_file,"base",3325&our_file,"ours",3326&their_file,"theirs", NULL);3327free(base_file.ptr);3328free(our_file.ptr);3329free(their_file.ptr);3330if(status <0|| !result.ptr) {3331free(result.ptr);3332return-1;3333}3334clear_image(image);3335 image->buf = result.ptr;3336 image->len = result.size;33373338return status;3339}33403341/*3342 * When directly falling back to add/add three-way merge, we read from3343 * the current contents of the new_name. In no cases other than that3344 * this function will be called.3345 */3346static intload_current(struct image *image,struct patch *patch)3347{3348struct strbuf buf = STRBUF_INIT;3349int status, pos;3350size_t len;3351char*img;3352struct stat st;3353struct cache_entry *ce;3354char*name = patch->new_name;3355unsigned mode = patch->new_mode;33563357if(!patch->is_new)3358die("BUG: patch to%sis not a creation", patch->old_name);33593360 pos =cache_name_pos(name,strlen(name));3361if(pos <0)3362returnerror(_("%s: does not exist in index"), name);3363 ce = active_cache[pos];3364if(lstat(name, &st)) {3365if(errno != ENOENT)3366returnerror(_("%s:%s"), name,strerror(errno));3367if(checkout_target(&the_index, ce, &st))3368return-1;3369}3370if(verify_index_match(ce, &st))3371returnerror(_("%s: does not match index"), name);33723373 status =load_patch_target(&buf, ce, &st, name, mode);3374if(status <0)3375return status;3376else if(status)3377return-1;3378 img =strbuf_detach(&buf, &len);3379prepare_image(image, img, len, !patch->is_binary);3380return0;3381}33823383static inttry_threeway(struct image *image,struct patch *patch,3384struct stat *st,const struct cache_entry *ce)3385{3386unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3387struct strbuf buf = STRBUF_INIT;3388size_t len;3389int status;3390char*img;3391struct image tmp_image;33923393/* No point falling back to 3-way merge in these cases */3394if(patch->is_delete ||3395S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3396return-1;33973398/* Preimage the patch was prepared for */3399if(patch->is_new)3400write_sha1_file("",0, blob_type, pre_sha1);3401else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3402read_blob_object(&buf, pre_sha1, patch->old_mode))3403returnerror("repository lacks the necessary blob to fall back on 3-way merge.");34043405fprintf(stderr,"Falling back to three-way merge...\n");34063407 img =strbuf_detach(&buf, &len);3408prepare_image(&tmp_image, img, len,1);3409/* Apply the patch to get the post image */3410if(apply_fragments(&tmp_image, patch) <0) {3411clear_image(&tmp_image);3412return-1;3413}3414/* post_sha1[] is theirs */3415write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3416clear_image(&tmp_image);34173418/* our_sha1[] is ours */3419if(patch->is_new) {3420if(load_current(&tmp_image, patch))3421returnerror("cannot read the current contents of '%s'",3422 patch->new_name);3423}else{3424if(load_preimage(&tmp_image, patch, st, ce))3425returnerror("cannot read the current contents of '%s'",3426 patch->old_name);3427}3428write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3429clear_image(&tmp_image);34303431/* in-core three-way merge between post and our using pre as base */3432 status =three_way_merge(image, patch->new_name,3433 pre_sha1, our_sha1, post_sha1);3434if(status <0) {3435fprintf(stderr,"Failed to fall back on three-way merge...\n");3436return status;3437}34383439if(status) {3440 patch->conflicted_threeway =1;3441if(patch->is_new)3442oidclr(&patch->threeway_stage[0]);3443else3444hashcpy(patch->threeway_stage[0].hash, pre_sha1);3445hashcpy(patch->threeway_stage[1].hash, our_sha1);3446hashcpy(patch->threeway_stage[2].hash, post_sha1);3447fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3448}else{3449fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3450}3451return0;3452}34533454static intapply_data(struct patch *patch,struct stat *st,const struct cache_entry *ce)3455{3456struct image image;34573458if(load_preimage(&image, patch, st, ce) <0)3459return-1;34603461if(patch->direct_to_threeway ||3462apply_fragments(&image, patch) <0) {3463/* Note: with --reject, apply_fragments() returns 0 */3464if(!threeway ||try_threeway(&image, patch, st, ce) <0)3465return-1;3466}3467 patch->result = image.buf;3468 patch->resultsize = image.len;3469add_to_fn_table(patch);3470free(image.line_allocated);34713472if(0< patch->is_delete && patch->resultsize)3473returnerror(_("removal patch leaves file contents"));34743475return0;3476}34773478/*3479 * If "patch" that we are looking at modifies or deletes what we have,3480 * we would want it not to lose any local modification we have, either3481 * in the working tree or in the index.3482 *3483 * This also decides if a non-git patch is a creation patch or a3484 * modification to an existing empty file. We do not check the state3485 * of the current tree for a creation patch in this function; the caller3486 * check_patch() separately makes sure (and errors out otherwise) that3487 * the path the patch creates does not exist in the current tree.3488 */3489static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)3490{3491const char*old_name = patch->old_name;3492struct patch *previous = NULL;3493int stat_ret =0, status;3494unsigned st_mode =0;34953496if(!old_name)3497return0;34983499assert(patch->is_new <=0);3500 previous =previous_patch(patch, &status);35013502if(status)3503returnerror(_("path%shas been renamed/deleted"), old_name);3504if(previous) {3505 st_mode = previous->new_mode;3506}else if(!cached) {3507 stat_ret =lstat(old_name, st);3508if(stat_ret && errno != ENOENT)3509returnerror(_("%s:%s"), old_name,strerror(errno));3510}35113512if(check_index && !previous) {3513int pos =cache_name_pos(old_name,strlen(old_name));3514if(pos <0) {3515if(patch->is_new <0)3516goto is_new;3517returnerror(_("%s: does not exist in index"), old_name);3518}3519*ce = active_cache[pos];3520if(stat_ret <0) {3521if(checkout_target(&the_index, *ce, st))3522return-1;3523}3524if(!cached &&verify_index_match(*ce, st))3525returnerror(_("%s: does not match index"), old_name);3526if(cached)3527 st_mode = (*ce)->ce_mode;3528}else if(stat_ret <0) {3529if(patch->is_new <0)3530goto is_new;3531returnerror(_("%s:%s"), old_name,strerror(errno));3532}35333534if(!cached && !previous)3535 st_mode =ce_mode_from_stat(*ce, st->st_mode);35363537if(patch->is_new <0)3538 patch->is_new =0;3539if(!patch->old_mode)3540 patch->old_mode = st_mode;3541if((st_mode ^ patch->old_mode) & S_IFMT)3542returnerror(_("%s: wrong type"), old_name);3543if(st_mode != patch->old_mode)3544warning(_("%shas type%o, expected%o"),3545 old_name, st_mode, patch->old_mode);3546if(!patch->new_mode && !patch->is_delete)3547 patch->new_mode = st_mode;3548return0;35493550 is_new:3551 patch->is_new =1;3552 patch->is_delete =0;3553free(patch->old_name);3554 patch->old_name = NULL;3555return0;3556}355735583559#define EXISTS_IN_INDEX 13560#define EXISTS_IN_WORKTREE 235613562static intcheck_to_create(const char*new_name,int ok_if_exists)3563{3564struct stat nst;35653566if(check_index &&3567cache_name_pos(new_name,strlen(new_name)) >=0&&3568!ok_if_exists)3569return EXISTS_IN_INDEX;3570if(cached)3571return0;35723573if(!lstat(new_name, &nst)) {3574if(S_ISDIR(nst.st_mode) || ok_if_exists)3575return0;3576/*3577 * A leading component of new_name might be a symlink3578 * that is going to be removed with this patch, but3579 * still pointing at somewhere that has the path.3580 * In such a case, path "new_name" does not exist as3581 * far as git is concerned.3582 */3583if(has_symlink_leading_path(new_name,strlen(new_name)))3584return0;35853586return EXISTS_IN_WORKTREE;3587}else if((errno != ENOENT) && (errno != ENOTDIR)) {3588returnerror("%s:%s", new_name,strerror(errno));3589}3590return0;3591}35923593/*3594 * We need to keep track of how symlinks in the preimage are3595 * manipulated by the patches. A patch to add a/b/c where a/b3596 * is a symlink should not be allowed to affect the directory3597 * the symlink points at, but if the same patch removes a/b,3598 * it is perfectly fine, as the patch removes a/b to make room3599 * to create a directory a/b so that a/b/c can be created.3600 */3601static struct string_list symlink_changes;3602#define SYMLINK_GOES_AWAY 013603#define SYMLINK_IN_RESULT 0236043605static uintptr_tregister_symlink_changes(const char*path,uintptr_t what)3606{3607struct string_list_item *ent;36083609 ent =string_list_lookup(&symlink_changes, path);3610if(!ent) {3611 ent =string_list_insert(&symlink_changes, path);3612 ent->util = (void*)0;3613}3614 ent->util = (void*)(what | ((uintptr_t)ent->util));3615return(uintptr_t)ent->util;3616}36173618static uintptr_tcheck_symlink_changes(const char*path)3619{3620struct string_list_item *ent;36213622 ent =string_list_lookup(&symlink_changes, path);3623if(!ent)3624return0;3625return(uintptr_t)ent->util;3626}36273628static voidprepare_symlink_changes(struct patch *patch)3629{3630for( ; patch; patch = patch->next) {3631if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3632(patch->is_rename || patch->is_delete))3633/* the symlink at patch->old_name is removed */3634register_symlink_changes(patch->old_name, SYMLINK_GOES_AWAY);36353636if(patch->new_name &&S_ISLNK(patch->new_mode))3637/* the symlink at patch->new_name is created or remains */3638register_symlink_changes(patch->new_name, SYMLINK_IN_RESULT);3639}3640}36413642static intpath_is_beyond_symlink_1(struct strbuf *name)3643{3644do{3645unsigned int change;36463647while(--name->len && name->buf[name->len] !='/')3648;/* scan backwards */3649if(!name->len)3650break;3651 name->buf[name->len] ='\0';3652 change =check_symlink_changes(name->buf);3653if(change & SYMLINK_IN_RESULT)3654return1;3655if(change & SYMLINK_GOES_AWAY)3656/*3657 * This cannot be "return 0", because we may3658 * see a new one created at a higher level.3659 */3660continue;36613662/* otherwise, check the preimage */3663if(check_index) {3664struct cache_entry *ce;36653666 ce =cache_file_exists(name->buf, name->len, ignore_case);3667if(ce &&S_ISLNK(ce->ce_mode))3668return1;3669}else{3670struct stat st;3671if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3672return1;3673}3674}while(1);3675return0;3676}36773678static intpath_is_beyond_symlink(const char*name_)3679{3680int ret;3681struct strbuf name = STRBUF_INIT;36823683assert(*name_ !='\0');3684strbuf_addstr(&name, name_);3685 ret =path_is_beyond_symlink_1(&name);3686strbuf_release(&name);36873688return ret;3689}36903691static voiddie_on_unsafe_path(struct patch *patch)3692{3693const char*old_name = NULL;3694const char*new_name = NULL;3695if(patch->is_delete)3696 old_name = patch->old_name;3697else if(!patch->is_new && !patch->is_copy)3698 old_name = patch->old_name;3699if(!patch->is_delete)3700 new_name = patch->new_name;37013702if(old_name && !verify_path(old_name))3703die(_("invalid path '%s'"), old_name);3704if(new_name && !verify_path(new_name))3705die(_("invalid path '%s'"), new_name);3706}37073708/*3709 * Check and apply the patch in-core; leave the result in patch->result3710 * for the caller to write it out to the final destination.3711 */3712static intcheck_patch(struct patch *patch)3713{3714struct stat st;3715const char*old_name = patch->old_name;3716const char*new_name = patch->new_name;3717const char*name = old_name ? old_name : new_name;3718struct cache_entry *ce = NULL;3719struct patch *tpatch;3720int ok_if_exists;3721int status;37223723 patch->rejected =1;/* we will drop this after we succeed */37243725 status =check_preimage(patch, &ce, &st);3726if(status)3727return status;3728 old_name = patch->old_name;37293730/*3731 * A type-change diff is always split into a patch to delete3732 * old, immediately followed by a patch to create new (see3733 * diff.c::run_diff()); in such a case it is Ok that the entry3734 * to be deleted by the previous patch is still in the working3735 * tree and in the index.3736 *3737 * A patch to swap-rename between A and B would first rename A3738 * to B and then rename B to A. While applying the first one,3739 * the presence of B should not stop A from getting renamed to3740 * B; ask to_be_deleted() about the later rename. Removal of3741 * B and rename from A to B is handled the same way by asking3742 * was_deleted().3743 */3744if((tpatch =in_fn_table(new_name)) &&3745(was_deleted(tpatch) ||to_be_deleted(tpatch)))3746 ok_if_exists =1;3747else3748 ok_if_exists =0;37493750if(new_name &&3751((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3752int err =check_to_create(new_name, ok_if_exists);37533754if(err && threeway) {3755 patch->direct_to_threeway =1;3756}else switch(err) {3757case0:3758break;/* happy */3759case EXISTS_IN_INDEX:3760returnerror(_("%s: already exists in index"), new_name);3761break;3762case EXISTS_IN_WORKTREE:3763returnerror(_("%s: already exists in working directory"),3764 new_name);3765default:3766return err;3767}37683769if(!patch->new_mode) {3770if(0< patch->is_new)3771 patch->new_mode = S_IFREG |0644;3772else3773 patch->new_mode = patch->old_mode;3774}3775}37763777if(new_name && old_name) {3778int same = !strcmp(old_name, new_name);3779if(!patch->new_mode)3780 patch->new_mode = patch->old_mode;3781if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3782if(same)3783returnerror(_("new mode (%o) of%sdoes not "3784"match old mode (%o)"),3785 patch->new_mode, new_name,3786 patch->old_mode);3787else3788returnerror(_("new mode (%o) of%sdoes not "3789"match old mode (%o) of%s"),3790 patch->new_mode, new_name,3791 patch->old_mode, old_name);3792}3793}37943795if(!unsafe_paths)3796die_on_unsafe_path(patch);37973798/*3799 * An attempt to read from or delete a path that is beyond a3800 * symbolic link will be prevented by load_patch_target() that3801 * is called at the beginning of apply_data() so we do not3802 * have to worry about a patch marked with "is_delete" bit3803 * here. We however need to make sure that the patch result3804 * is not deposited to a path that is beyond a symbolic link3805 * here.3806 */3807if(!patch->is_delete &&path_is_beyond_symlink(patch->new_name))3808returnerror(_("affected file '%s' is beyond a symbolic link"),3809 patch->new_name);38103811if(apply_data(patch, &st, ce) <0)3812returnerror(_("%s: patch does not apply"), name);3813 patch->rejected =0;3814return0;3815}38163817static intcheck_patch_list(struct patch *patch)3818{3819int err =0;38203821prepare_symlink_changes(patch);3822prepare_fn_table(patch);3823while(patch) {3824if(apply_verbosely)3825say_patch_name(stderr,3826_("Checking patch%s..."), patch);3827 err |=check_patch(patch);3828 patch = patch->next;3829}3830return err;3831}38323833/* This function tries to read the sha1 from the current index */3834static intget_current_sha1(const char*path,unsigned char*sha1)3835{3836int pos;38373838if(read_cache() <0)3839return-1;3840 pos =cache_name_pos(path,strlen(path));3841if(pos <0)3842return-1;3843hashcpy(sha1, active_cache[pos]->sha1);3844return0;3845}38463847static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3848{3849/*3850 * A usable gitlink patch has only one fragment (hunk) that looks like:3851 * @@ -1 +1 @@3852 * -Subproject commit <old sha1>3853 * +Subproject commit <new sha1>3854 * or3855 * @@ -1 +0,0 @@3856 * -Subproject commit <old sha1>3857 * for a removal patch.3858 */3859struct fragment *hunk = p->fragments;3860static const char heading[] ="-Subproject commit ";3861char*preimage;38623863if(/* does the patch have only one hunk? */3864 hunk && !hunk->next &&3865/* is its preimage one line? */3866 hunk->oldpos ==1&& hunk->oldlines ==1&&3867/* does preimage begin with the heading? */3868(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3869starts_with(++preimage, heading) &&3870/* does it record full SHA-1? */3871!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3872 preimage[sizeof(heading) +40-1] =='\n'&&3873/* does the abbreviated name on the index line agree with it? */3874starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3875return0;/* it all looks fine */38763877/* we may have full object name on the index line */3878returnget_sha1_hex(p->old_sha1_prefix, sha1);3879}38803881/* Build an index that contains the just the files needed for a 3way merge */3882static voidbuild_fake_ancestor(struct patch *list,const char*filename)3883{3884struct patch *patch;3885struct index_state result = { NULL };3886static struct lock_file lock;38873888/* Once we start supporting the reverse patch, it may be3889 * worth showing the new sha1 prefix, but until then...3890 */3891for(patch = list; patch; patch = patch->next) {3892unsigned char sha1[20];3893struct cache_entry *ce;3894const char*name;38953896 name = patch->old_name ? patch->old_name : patch->new_name;3897if(0< patch->is_new)3898continue;38993900if(S_ISGITLINK(patch->old_mode)) {3901if(!preimage_sha1_in_gitlink_patch(patch, sha1))3902;/* ok, the textual part looks sane */3903else3904die("sha1 information is lacking or useless for submodule%s",3905 name);3906}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {3907;/* ok */3908}else if(!patch->lines_added && !patch->lines_deleted) {3909/* mode-only change: update the current */3910if(get_current_sha1(patch->old_name, sha1))3911die("mode change for%s, which is not "3912"in current HEAD", name);3913}else3914die("sha1 information is lacking or useless "3915"(%s).", name);39163917 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);3918if(!ce)3919die(_("make_cache_entry failed for path '%s'"), name);3920if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3921die("Could not add%sto temporary index", name);3922}39233924hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);3925if(write_locked_index(&result, &lock, COMMIT_LOCK))3926die("Could not write temporary index to%s", filename);39273928discard_index(&result);3929}39303931static voidstat_patch_list(struct patch *patch)3932{3933int files, adds, dels;39343935for(files = adds = dels =0; patch ; patch = patch->next) {3936 files++;3937 adds += patch->lines_added;3938 dels += patch->lines_deleted;3939show_stats(patch);3940}39413942print_stat_summary(stdout, files, adds, dels);3943}39443945static voidnumstat_patch_list(struct patch *patch)3946{3947for( ; patch; patch = patch->next) {3948const char*name;3949 name = patch->new_name ? patch->new_name : patch->old_name;3950if(patch->is_binary)3951printf("-\t-\t");3952else3953printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3954write_name_quoted(name, stdout, line_termination);3955}3956}39573958static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3959{3960if(mode)3961printf("%smode%06o%s\n", newdelete, mode, name);3962else3963printf("%s %s\n", newdelete, name);3964}39653966static voidshow_mode_change(struct patch *p,int show_name)3967{3968if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3969if(show_name)3970printf(" mode change%06o =>%06o%s\n",3971 p->old_mode, p->new_mode, p->new_name);3972else3973printf(" mode change%06o =>%06o\n",3974 p->old_mode, p->new_mode);3975}3976}39773978static voidshow_rename_copy(struct patch *p)3979{3980const char*renamecopy = p->is_rename ?"rename":"copy";3981const char*old, *new;39823983/* Find common prefix */3984 old = p->old_name;3985new= p->new_name;3986while(1) {3987const char*slash_old, *slash_new;3988 slash_old =strchr(old,'/');3989 slash_new =strchr(new,'/');3990if(!slash_old ||3991!slash_new ||3992 slash_old - old != slash_new -new||3993memcmp(old,new, slash_new -new))3994break;3995 old = slash_old +1;3996new= slash_new +1;3997}3998/* p->old_name thru old is the common prefix, and old and new3999 * through the end of names are renames4000 */4001if(old != p->old_name)4002printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4003(int)(old - p->old_name), p->old_name,4004 old,new, p->score);4005else4006printf("%s %s=>%s(%d%%)\n", renamecopy,4007 p->old_name, p->new_name, p->score);4008show_mode_change(p,0);4009}40104011static voidsummary_patch_list(struct patch *patch)4012{4013struct patch *p;40144015for(p = patch; p; p = p->next) {4016if(p->is_new)4017show_file_mode_name("create", p->new_mode, p->new_name);4018else if(p->is_delete)4019show_file_mode_name("delete", p->old_mode, p->old_name);4020else{4021if(p->is_rename || p->is_copy)4022show_rename_copy(p);4023else{4024if(p->score) {4025printf(" rewrite%s(%d%%)\n",4026 p->new_name, p->score);4027show_mode_change(p,0);4028}4029else4030show_mode_change(p,1);4031}4032}4033}4034}40354036static voidpatch_stats(struct patch *patch)4037{4038int lines = patch->lines_added + patch->lines_deleted;40394040if(lines > max_change)4041 max_change = lines;4042if(patch->old_name) {4043int len =quote_c_style(patch->old_name, NULL, NULL,0);4044if(!len)4045 len =strlen(patch->old_name);4046if(len > max_len)4047 max_len = len;4048}4049if(patch->new_name) {4050int len =quote_c_style(patch->new_name, NULL, NULL,0);4051if(!len)4052 len =strlen(patch->new_name);4053if(len > max_len)4054 max_len = len;4055}4056}40574058static voidremove_file(struct patch *patch,int rmdir_empty)4059{4060if(update_index) {4061if(remove_file_from_cache(patch->old_name) <0)4062die(_("unable to remove%sfrom index"), patch->old_name);4063}4064if(!cached) {4065if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4066remove_path(patch->old_name);4067}4068}4069}40704071static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)4072{4073struct stat st;4074struct cache_entry *ce;4075int namelen =strlen(path);4076unsigned ce_size =cache_entry_size(namelen);40774078if(!update_index)4079return;40804081 ce =xcalloc(1, ce_size);4082memcpy(ce->name, path, namelen);4083 ce->ce_mode =create_ce_mode(mode);4084 ce->ce_flags =create_ce_flags(0);4085 ce->ce_namelen = namelen;4086if(S_ISGITLINK(mode)) {4087const char*s;40884089if(!skip_prefix(buf,"Subproject commit ", &s) ||4090get_sha1_hex(s, ce->sha1))4091die(_("corrupt patch for submodule%s"), path);4092}else{4093if(!cached) {4094if(lstat(path, &st) <0)4095die_errno(_("unable to stat newly created file '%s'"),4096 path);4097fill_stat_cache_info(ce, &st);4098}4099if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4100die(_("unable to create backing store for newly created file%s"), path);4101}4102if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4103die(_("unable to add cache entry for%s"), path);4104}41054106static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4107{4108int fd;4109struct strbuf nbuf = STRBUF_INIT;41104111if(S_ISGITLINK(mode)) {4112struct stat st;4113if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4114return0;4115returnmkdir(path,0777);4116}41174118if(has_symlinks &&S_ISLNK(mode))4119/* Although buf:size is counted string, it also is NUL4120 * terminated.4121 */4122returnsymlink(buf, path);41234124 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4125if(fd <0)4126return-1;41274128if(convert_to_working_tree(path, buf, size, &nbuf)) {4129 size = nbuf.len;4130 buf = nbuf.buf;4131}4132write_or_die(fd, buf, size);4133strbuf_release(&nbuf);41344135if(close(fd) <0)4136die_errno(_("closing file '%s'"), path);4137return0;4138}41394140/*4141 * We optimistically assume that the directories exist,4142 * which is true 99% of the time anyway. If they don't,4143 * we create them and try again.4144 */4145static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)4146{4147if(cached)4148return;4149if(!try_create_file(path, mode, buf, size))4150return;41514152if(errno == ENOENT) {4153if(safe_create_leading_directories(path))4154return;4155if(!try_create_file(path, mode, buf, size))4156return;4157}41584159if(errno == EEXIST || errno == EACCES) {4160/* We may be trying to create a file where a directory4161 * used to be.4162 */4163struct stat st;4164if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4165 errno = EEXIST;4166}41674168if(errno == EEXIST) {4169unsigned int nr =getpid();41704171for(;;) {4172char newpath[PATH_MAX];4173mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4174if(!try_create_file(newpath, mode, buf, size)) {4175if(!rename(newpath, path))4176return;4177unlink_or_warn(newpath);4178break;4179}4180if(errno != EEXIST)4181break;4182++nr;4183}4184}4185die_errno(_("unable to write file '%s' mode%o"), path, mode);4186}41874188static voidadd_conflicted_stages_file(struct patch *patch)4189{4190int stage, namelen;4191unsigned ce_size, mode;4192struct cache_entry *ce;41934194if(!update_index)4195return;4196 namelen =strlen(patch->new_name);4197 ce_size =cache_entry_size(namelen);4198 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);41994200remove_file_from_cache(patch->new_name);4201for(stage =1; stage <4; stage++) {4202if(is_null_oid(&patch->threeway_stage[stage -1]))4203continue;4204 ce =xcalloc(1, ce_size);4205memcpy(ce->name, patch->new_name, namelen);4206 ce->ce_mode =create_ce_mode(mode);4207 ce->ce_flags =create_ce_flags(stage);4208 ce->ce_namelen = namelen;4209hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4210if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4211die(_("unable to add cache entry for%s"), patch->new_name);4212}4213}42144215static voidcreate_file(struct patch *patch)4216{4217char*path = patch->new_name;4218unsigned mode = patch->new_mode;4219unsigned long size = patch->resultsize;4220char*buf = patch->result;42214222if(!mode)4223 mode = S_IFREG |0644;4224create_one_file(path, mode, buf, size);42254226if(patch->conflicted_threeway)4227add_conflicted_stages_file(patch);4228else4229add_index_file(path, mode, buf, size);4230}42314232/* phase zero is to remove, phase one is to create */4233static voidwrite_out_one_result(struct patch *patch,int phase)4234{4235if(patch->is_delete >0) {4236if(phase ==0)4237remove_file(patch,1);4238return;4239}4240if(patch->is_new >0|| patch->is_copy) {4241if(phase ==1)4242create_file(patch);4243return;4244}4245/*4246 * Rename or modification boils down to the same4247 * thing: remove the old, write the new4248 */4249if(phase ==0)4250remove_file(patch, patch->is_rename);4251if(phase ==1)4252create_file(patch);4253}42544255static intwrite_out_one_reject(struct patch *patch)4256{4257FILE*rej;4258char namebuf[PATH_MAX];4259struct fragment *frag;4260int cnt =0;4261struct strbuf sb = STRBUF_INIT;42624263for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4264if(!frag->rejected)4265continue;4266 cnt++;4267}42684269if(!cnt) {4270if(apply_verbosely)4271say_patch_name(stderr,4272_("Applied patch%scleanly."), patch);4273return0;4274}42754276/* This should not happen, because a removal patch that leaves4277 * contents are marked "rejected" at the patch level.4278 */4279if(!patch->new_name)4280die(_("internal error"));42814282/* Say this even without --verbose */4283strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4284"Applying patch %%swith%drejects...",4285 cnt),4286 cnt);4287say_patch_name(stderr, sb.buf, patch);4288strbuf_release(&sb);42894290 cnt =strlen(patch->new_name);4291if(ARRAY_SIZE(namebuf) <= cnt +5) {4292 cnt =ARRAY_SIZE(namebuf) -5;4293warning(_("truncating .rej filename to %.*s.rej"),4294 cnt -1, patch->new_name);4295}4296memcpy(namebuf, patch->new_name, cnt);4297memcpy(namebuf + cnt,".rej",5);42984299 rej =fopen(namebuf,"w");4300if(!rej)4301returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));43024303/* Normal git tools never deal with .rej, so do not pretend4304 * this is a git patch by saying --git or giving extended4305 * headers. While at it, maybe please "kompare" that wants4306 * the trailing TAB and some garbage at the end of line ;-).4307 */4308fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4309 patch->new_name, patch->new_name);4310for(cnt =1, frag = patch->fragments;4311 frag;4312 cnt++, frag = frag->next) {4313if(!frag->rejected) {4314fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4315continue;4316}4317fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4318fprintf(rej,"%.*s", frag->size, frag->patch);4319if(frag->patch[frag->size-1] !='\n')4320fputc('\n', rej);4321}4322fclose(rej);4323return-1;4324}43254326static intwrite_out_results(struct patch *list)4327{4328int phase;4329int errs =0;4330struct patch *l;4331struct string_list cpath = STRING_LIST_INIT_DUP;43324333for(phase =0; phase <2; phase++) {4334 l = list;4335while(l) {4336if(l->rejected)4337 errs =1;4338else{4339write_out_one_result(l, phase);4340if(phase ==1) {4341if(write_out_one_reject(l))4342 errs =1;4343if(l->conflicted_threeway) {4344string_list_append(&cpath, l->new_name);4345 errs =1;4346}4347}4348}4349 l = l->next;4350}4351}43524353if(cpath.nr) {4354struct string_list_item *item;43554356string_list_sort(&cpath);4357for_each_string_list_item(item, &cpath)4358fprintf(stderr,"U%s\n", item->string);4359string_list_clear(&cpath,0);43604361rerere(0);4362}43634364return errs;4365}43664367static struct lock_file lock_file;43684369#define INACCURATE_EOF (1<<0)4370#define RECOUNT (1<<1)43714372static intapply_patch(int fd,const char*filename,int options)4373{4374size_t offset;4375struct strbuf buf = STRBUF_INIT;/* owns the patch text */4376struct patch *list = NULL, **listp = &list;4377int skipped_patch =0;43784379 patch_input_file = filename;4380read_patch_file(&buf, fd);4381 offset =0;4382while(offset < buf.len) {4383struct patch *patch;4384int nr;43854386 patch =xcalloc(1,sizeof(*patch));4387 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4388 patch->recount = !!(options & RECOUNT);4389 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);4390if(nr <0) {4391free_patch(patch);4392break;4393}4394if(apply_in_reverse)4395reverse_patches(patch);4396if(use_patch(patch)) {4397patch_stats(patch);4398*listp = patch;4399 listp = &patch->next;4400}4401else{4402if(apply_verbosely)4403say_patch_name(stderr,_("Skipped patch '%s'."), patch);4404free_patch(patch);4405 skipped_patch++;4406}4407 offset += nr;4408}44094410if(!list && !skipped_patch)4411die(_("unrecognized input"));44124413if(whitespace_error && (ws_error_action == die_on_ws_error))4414 apply =0;44154416 update_index = check_index && apply;4417if(update_index && newfd <0)4418 newfd =hold_locked_index(&lock_file,1);44194420if(check_index) {4421if(read_cache() <0)4422die(_("unable to read index file"));4423}44244425if((check || apply) &&4426check_patch_list(list) <0&&4427!apply_with_reject)4428exit(1);44294430if(apply &&write_out_results(list)) {4431if(apply_with_reject)4432exit(1);4433/* with --3way, we still need to write the index out */4434return1;4435}44364437if(fake_ancestor)4438build_fake_ancestor(list, fake_ancestor);44394440if(diffstat)4441stat_patch_list(list);44424443if(numstat)4444numstat_patch_list(list);44454446if(summary)4447summary_patch_list(list);44484449free_patch_list(list);4450strbuf_release(&buf);4451string_list_clear(&fn_table,0);4452return0;4453}44544455static voidgit_apply_config(void)4456{4457git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4458git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4459git_config(git_default_config, NULL);4460}44614462static intoption_parse_exclude(const struct option *opt,4463const char*arg,int unset)4464{4465add_name_limit(arg,1);4466return0;4467}44684469static intoption_parse_include(const struct option *opt,4470const char*arg,int unset)4471{4472add_name_limit(arg,0);4473 has_include =1;4474return0;4475}44764477static intoption_parse_p(const struct option *opt,4478const char*arg,int unset)4479{4480 state_p_value =atoi(arg);4481 p_value_known =1;4482return0;4483}44844485static intoption_parse_space_change(const struct option *opt,4486const char*arg,int unset)4487{4488if(unset)4489 ws_ignore_action = ignore_ws_none;4490else4491 ws_ignore_action = ignore_ws_change;4492return0;4493}44944495static intoption_parse_whitespace(const struct option *opt,4496const char*arg,int unset)4497{4498const char**whitespace_option = opt->value;44994500*whitespace_option = arg;4501parse_whitespace_option(arg);4502return0;4503}45044505static intoption_parse_directory(const struct option *opt,4506const char*arg,int unset)4507{4508strbuf_reset(&root);4509strbuf_addstr(&root, arg);4510strbuf_complete(&root,'/');4511return0;4512}45134514intcmd_apply(int argc,const char**argv,const char*prefix_)4515{4516int i;4517int errs =0;4518int is_not_gitdir = !startup_info->have_repository;4519int force_apply =0;45204521const char*whitespace_option = NULL;45224523struct option builtin_apply_options[] = {4524{ OPTION_CALLBACK,0,"exclude", NULL,N_("path"),4525N_("don't apply changes matching the given path"),45260, option_parse_exclude },4527{ OPTION_CALLBACK,0,"include", NULL,N_("path"),4528N_("apply changes matching the given path"),45290, option_parse_include },4530{ OPTION_CALLBACK,'p', NULL, NULL,N_("num"),4531N_("remove <num> leading slashes from traditional diff paths"),45320, option_parse_p },4533OPT_BOOL(0,"no-add", &no_add,4534N_("ignore additions made by the patch")),4535OPT_BOOL(0,"stat", &diffstat,4536N_("instead of applying the patch, output diffstat for the input")),4537OPT_NOOP_NOARG(0,"allow-binary-replacement"),4538OPT_NOOP_NOARG(0,"binary"),4539OPT_BOOL(0,"numstat", &numstat,4540N_("show number of added and deleted lines in decimal notation")),4541OPT_BOOL(0,"summary", &summary,4542N_("instead of applying the patch, output a summary for the input")),4543OPT_BOOL(0,"check", &check,4544N_("instead of applying the patch, see if the patch is applicable")),4545OPT_BOOL(0,"index", &check_index,4546N_("make sure the patch is applicable to the current index")),4547OPT_BOOL(0,"cached", &cached,4548N_("apply a patch without touching the working tree")),4549OPT_BOOL(0,"unsafe-paths", &unsafe_paths,4550N_("accept a patch that touches outside the working area")),4551OPT_BOOL(0,"apply", &force_apply,4552N_("also apply the patch (use with --stat/--summary/--check)")),4553OPT_BOOL('3',"3way", &threeway,4554N_("attempt three-way merge if a patch does not apply")),4555OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,4556N_("build a temporary index based on embedded index information")),4557/* Think twice before adding "--nul" synonym to this */4558OPT_SET_INT('z', NULL, &line_termination,4559N_("paths are separated with NUL character"),'\0'),4560OPT_INTEGER('C', NULL, &p_context,4561N_("ensure at least <n> lines of context match")),4562{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,N_("action"),4563N_("detect new or modified lines that have whitespace errors"),45640, option_parse_whitespace },4565{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,4566N_("ignore changes in whitespace when finding context"),4567 PARSE_OPT_NOARG, option_parse_space_change },4568{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,4569N_("ignore changes in whitespace when finding context"),4570 PARSE_OPT_NOARG, option_parse_space_change },4571OPT_BOOL('R',"reverse", &apply_in_reverse,4572N_("apply the patch in reverse")),4573OPT_BOOL(0,"unidiff-zero", &unidiff_zero,4574N_("don't expect at least one line of context")),4575OPT_BOOL(0,"reject", &apply_with_reject,4576N_("leave the rejected hunks in corresponding *.rej files")),4577OPT_BOOL(0,"allow-overlap", &allow_overlap,4578N_("allow overlapping hunks")),4579OPT__VERBOSE(&apply_verbosely,N_("be verbose")),4580OPT_BIT(0,"inaccurate-eof", &options,4581N_("tolerate incorrectly detected missing new-line at the end of file"),4582 INACCURATE_EOF),4583OPT_BIT(0,"recount", &options,4584N_("do not trust the line counts in the hunk headers"),4585 RECOUNT),4586{ OPTION_CALLBACK,0,"directory", NULL,N_("root"),4587N_("prepend <root> to all filenames"),45880, option_parse_directory },4589OPT_END()4590};45914592 prefix = prefix_;4593 prefix_length = prefix ?strlen(prefix) :0;4594git_apply_config();4595if(apply_default_whitespace)4596parse_whitespace_option(apply_default_whitespace);4597if(apply_default_ignorewhitespace)4598parse_ignorewhitespace_option(apply_default_ignorewhitespace);45994600 argc =parse_options(argc, argv, prefix, builtin_apply_options,4601 apply_usage,0);46024603if(apply_with_reject && threeway)4604die("--reject and --3way cannot be used together.");4605if(cached && threeway)4606die("--cached and --3way cannot be used together.");4607if(threeway) {4608if(is_not_gitdir)4609die(_("--3way outside a repository"));4610 check_index =1;4611}4612if(apply_with_reject)4613 apply = apply_verbosely =1;4614if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))4615 apply =0;4616if(check_index && is_not_gitdir)4617die(_("--index outside a repository"));4618if(cached) {4619if(is_not_gitdir)4620die(_("--cached outside a repository"));4621 check_index =1;4622}4623if(check_index)4624 unsafe_paths =0;46254626for(i =0; i < argc; i++) {4627const char*arg = argv[i];4628int fd;46294630if(!strcmp(arg,"-")) {4631 errs |=apply_patch(0,"<stdin>", options);4632 read_stdin =0;4633continue;4634}else if(0< prefix_length)4635 arg =prefix_filename(prefix, prefix_length, arg);46364637 fd =open(arg, O_RDONLY);4638if(fd <0)4639die_errno(_("can't open patch '%s'"), arg);4640 read_stdin =0;4641set_default_whitespace_mode(whitespace_option);4642 errs |=apply_patch(fd, arg, options);4643close(fd);4644}4645set_default_whitespace_mode(whitespace_option);4646if(read_stdin)4647 errs |=apply_patch(0,"<stdin>", options);4648if(whitespace_error) {4649if(squelch_whitespace_errors &&4650 squelch_whitespace_errors < whitespace_error) {4651int squelched =4652 whitespace_error - squelch_whitespace_errors;4653warning(Q_("squelched%dwhitespace error",4654"squelched%dwhitespace errors",4655 squelched),4656 squelched);4657}4658if(ws_error_action == die_on_ws_error)4659die(Q_("%dline adds whitespace errors.",4660"%dlines add whitespace errors.",4661 whitespace_error),4662 whitespace_error);4663if(applied_after_fixing_ws && apply)4664warning("%dline%sapplied after"4665" fixing whitespace errors.",4666 applied_after_fixing_ws,4667 applied_after_fixing_ws ==1?"":"s");4668else if(whitespace_error)4669warning(Q_("%dline adds whitespace errors.",4670"%dlines add whitespace errors.",4671 whitespace_error),4672 whitespace_error);4673}46744675if(update_index) {4676if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK))4677die(_("Unable to write new index file"));4678}46794680return!!errs;4681}