1/* 2 * apply.c 3 * 4 * Copyright (C) Linus Torvalds, 2005 5 * 6 * This applies patches on top of some (arbitrary) version of the SCM. 7 * 8 */ 9#include"cache.h" 10#include"lockfile.h" 11#include"cache-tree.h" 12#include"quote.h" 13#include"blob.h" 14#include"delta.h" 15#include"builtin.h" 16#include"string-list.h" 17#include"dir.h" 18#include"diff.h" 19#include"parse-options.h" 20#include"xdiff-interface.h" 21#include"ll-merge.h" 22#include"rerere.h" 23 24/* 25 * --check turns on checking that the working tree matches the 26 * files that are being modified, but doesn't apply the patch 27 * --stat does just a diffstat, and doesn't actually apply 28 * --numstat does numeric diffstat, and doesn't actually apply 29 * --index-info shows the old and new index info for paths if available. 30 * --index updates the cache as well. 31 * --cached updates only the cache without ever touching the working tree. 32 */ 33static const char*prefix; 34static int prefix_length = -1; 35static int newfd = -1; 36 37static int unidiff_zero; 38static int p_value =1; 39static int p_value_known; 40static int check_index; 41static int update_index; 42static int cached; 43static int diffstat; 44static int numstat; 45static int summary; 46static int check; 47static int apply =1; 48static int apply_in_reverse; 49static int apply_with_reject; 50static int apply_verbosely; 51static int allow_overlap; 52static int no_add; 53static int threeway; 54static int unsafe_paths; 55static const char*fake_ancestor; 56static int line_termination ='\n'; 57static unsigned int p_context = UINT_MAX; 58static const char*const apply_usage[] = { 59N_("git apply [<options>] [<patch>...]"), 60 NULL 61}; 62 63static enum ws_error_action { 64 nowarn_ws_error, 65 warn_on_ws_error, 66 die_on_ws_error, 67 correct_ws_error 68} ws_error_action = warn_on_ws_error; 69static int whitespace_error; 70static int squelch_whitespace_errors =5; 71static int applied_after_fixing_ws; 72 73static enum ws_ignore { 74 ignore_ws_none, 75 ignore_ws_change 76} ws_ignore_action = ignore_ws_none; 77 78 79static const char*patch_input_file; 80static struct strbuf root = STRBUF_INIT; 81static int read_stdin =1; 82static int options; 83 84static voidparse_whitespace_option(const char*option) 85{ 86if(!option) { 87 ws_error_action = warn_on_ws_error; 88return; 89} 90if(!strcmp(option,"warn")) { 91 ws_error_action = warn_on_ws_error; 92return; 93} 94if(!strcmp(option,"nowarn")) { 95 ws_error_action = nowarn_ws_error; 96return; 97} 98if(!strcmp(option,"error")) { 99 ws_error_action = die_on_ws_error; 100return; 101} 102if(!strcmp(option,"error-all")) { 103 ws_error_action = die_on_ws_error; 104 squelch_whitespace_errors =0; 105return; 106} 107if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 108 ws_error_action = correct_ws_error; 109return; 110} 111die(_("unrecognized whitespace option '%s'"), option); 112} 113 114static voidparse_ignorewhitespace_option(const char*option) 115{ 116if(!option || !strcmp(option,"no") || 117!strcmp(option,"false") || !strcmp(option,"never") || 118!strcmp(option,"none")) { 119 ws_ignore_action = ignore_ws_none; 120return; 121} 122if(!strcmp(option,"change")) { 123 ws_ignore_action = ignore_ws_change; 124return; 125} 126die(_("unrecognized whitespace ignore option '%s'"), option); 127} 128 129static voidset_default_whitespace_mode(const char*whitespace_option) 130{ 131if(!whitespace_option && !apply_default_whitespace) 132 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 133} 134 135/* 136 * For "diff-stat" like behaviour, we keep track of the biggest change 137 * we've seen, and the longest filename. That allows us to do simple 138 * scaling. 139 */ 140static int max_change, max_len; 141 142/* 143 * Various "current state", notably line numbers and what 144 * file (and how) we're patching right now.. The "is_xxxx" 145 * things are flags, where -1 means "don't know yet". 146 */ 147static int linenr =1; 148 149/* 150 * This represents one "hunk" from a patch, starting with 151 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 152 * patch text is pointed at by patch, and its byte length 153 * is stored in size. leading and trailing are the number 154 * of context lines. 155 */ 156struct fragment { 157unsigned long leading, trailing; 158unsigned long oldpos, oldlines; 159unsigned long newpos, newlines; 160/* 161 * 'patch' is usually borrowed from buf in apply_patch(), 162 * but some codepaths store an allocated buffer. 163 */ 164const char*patch; 165unsigned free_patch:1, 166 rejected:1; 167int size; 168int linenr; 169struct fragment *next; 170}; 171 172/* 173 * When dealing with a binary patch, we reuse "leading" field 174 * to store the type of the binary hunk, either deflated "delta" 175 * or deflated "literal". 176 */ 177#define binary_patch_method leading 178#define BINARY_DELTA_DEFLATED 1 179#define BINARY_LITERAL_DEFLATED 2 180 181/* 182 * This represents a "patch" to a file, both metainfo changes 183 * such as creation/deletion, filemode and content changes represented 184 * as a series of fragments. 185 */ 186struct patch { 187char*new_name, *old_name, *def_name; 188unsigned int old_mode, new_mode; 189int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 190int rejected; 191unsigned ws_rule; 192int lines_added, lines_deleted; 193int score; 194unsigned int is_toplevel_relative:1; 195unsigned int inaccurate_eof:1; 196unsigned int is_binary:1; 197unsigned int is_copy:1; 198unsigned int is_rename:1; 199unsigned int recount:1; 200unsigned int conflicted_threeway:1; 201unsigned int direct_to_threeway:1; 202struct fragment *fragments; 203char*result; 204size_t resultsize; 205char old_sha1_prefix[41]; 206char new_sha1_prefix[41]; 207struct patch *next; 208 209/* three-way fallback result */ 210struct object_id threeway_stage[3]; 211}; 212 213static voidfree_fragment_list(struct fragment *list) 214{ 215while(list) { 216struct fragment *next = list->next; 217if(list->free_patch) 218free((char*)list->patch); 219free(list); 220 list = next; 221} 222} 223 224static voidfree_patch(struct patch *patch) 225{ 226free_fragment_list(patch->fragments); 227free(patch->def_name); 228free(patch->old_name); 229free(patch->new_name); 230free(patch->result); 231free(patch); 232} 233 234static voidfree_patch_list(struct patch *list) 235{ 236while(list) { 237struct patch *next = list->next; 238free_patch(list); 239 list = next; 240} 241} 242 243/* 244 * A line in a file, len-bytes long (includes the terminating LF, 245 * except for an incomplete line at the end if the file ends with 246 * one), and its contents hashes to 'hash'. 247 */ 248struct line { 249size_t len; 250unsigned hash :24; 251unsigned flag :8; 252#define LINE_COMMON 1 253#define LINE_PATCHED 2 254}; 255 256/* 257 * This represents a "file", which is an array of "lines". 258 */ 259struct image { 260char*buf; 261size_t len; 262size_t nr; 263size_t alloc; 264struct line *line_allocated; 265struct line *line; 266}; 267 268/* 269 * Records filenames that have been touched, in order to handle 270 * the case where more than one patches touch the same file. 271 */ 272 273static struct string_list fn_table; 274 275static uint32_thash_line(const char*cp,size_t len) 276{ 277size_t i; 278uint32_t h; 279for(i =0, h =0; i < len; i++) { 280if(!isspace(cp[i])) { 281 h = h *3+ (cp[i] &0xff); 282} 283} 284return h; 285} 286 287/* 288 * Compare lines s1 of length n1 and s2 of length n2, ignoring 289 * whitespace difference. Returns 1 if they match, 0 otherwise 290 */ 291static intfuzzy_matchlines(const char*s1,size_t n1, 292const char*s2,size_t n2) 293{ 294const char*last1 = s1 + n1 -1; 295const char*last2 = s2 + n2 -1; 296int result =0; 297 298/* ignore line endings */ 299while((*last1 =='\r') || (*last1 =='\n')) 300 last1--; 301while((*last2 =='\r') || (*last2 =='\n')) 302 last2--; 303 304/* skip leading whitespaces, if both begin with whitespace */ 305if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 306while(isspace(*s1) && (s1 <= last1)) 307 s1++; 308while(isspace(*s2) && (s2 <= last2)) 309 s2++; 310} 311/* early return if both lines are empty */ 312if((s1 > last1) && (s2 > last2)) 313return1; 314while(!result) { 315 result = *s1++ - *s2++; 316/* 317 * Skip whitespace inside. We check for whitespace on 318 * both buffers because we don't want "a b" to match 319 * "ab" 320 */ 321if(isspace(*s1) &&isspace(*s2)) { 322while(isspace(*s1) && s1 <= last1) 323 s1++; 324while(isspace(*s2) && s2 <= last2) 325 s2++; 326} 327/* 328 * If we reached the end on one side only, 329 * lines don't match 330 */ 331if( 332((s2 > last2) && (s1 <= last1)) || 333((s1 > last1) && (s2 <= last2))) 334return0; 335if((s1 > last1) && (s2 > last2)) 336break; 337} 338 339return!result; 340} 341 342static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 343{ 344ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 345 img->line_allocated[img->nr].len = len; 346 img->line_allocated[img->nr].hash =hash_line(bol, len); 347 img->line_allocated[img->nr].flag = flag; 348 img->nr++; 349} 350 351/* 352 * "buf" has the file contents to be patched (read from various sources). 353 * attach it to "image" and add line-based index to it. 354 * "image" now owns the "buf". 355 */ 356static voidprepare_image(struct image *image,char*buf,size_t len, 357int prepare_linetable) 358{ 359const char*cp, *ep; 360 361memset(image,0,sizeof(*image)); 362 image->buf = buf; 363 image->len = len; 364 365if(!prepare_linetable) 366return; 367 368 ep = image->buf + image->len; 369 cp = image->buf; 370while(cp < ep) { 371const char*next; 372for(next = cp; next < ep && *next !='\n'; next++) 373; 374if(next < ep) 375 next++; 376add_line_info(image, cp, next - cp,0); 377 cp = next; 378} 379 image->line = image->line_allocated; 380} 381 382static voidclear_image(struct image *image) 383{ 384free(image->buf); 385free(image->line_allocated); 386memset(image,0,sizeof(*image)); 387} 388 389/* fmt must contain _one_ %s and no other substitution */ 390static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 391{ 392struct strbuf sb = STRBUF_INIT; 393 394if(patch->old_name && patch->new_name && 395strcmp(patch->old_name, patch->new_name)) { 396quote_c_style(patch->old_name, &sb, NULL,0); 397strbuf_addstr(&sb," => "); 398quote_c_style(patch->new_name, &sb, NULL,0); 399}else{ 400const char*n = patch->new_name; 401if(!n) 402 n = patch->old_name; 403quote_c_style(n, &sb, NULL,0); 404} 405fprintf(output, fmt, sb.buf); 406fputc('\n', output); 407strbuf_release(&sb); 408} 409 410#define SLOP (16) 411 412static voidread_patch_file(struct strbuf *sb,int fd) 413{ 414if(strbuf_read(sb, fd,0) <0) 415die_errno("git apply: failed to read"); 416 417/* 418 * Make sure that we have some slop in the buffer 419 * so that we can do speculative "memcmp" etc, and 420 * see to it that it is NUL-filled. 421 */ 422strbuf_grow(sb, SLOP); 423memset(sb->buf + sb->len,0, SLOP); 424} 425 426static unsigned longlinelen(const char*buffer,unsigned long size) 427{ 428unsigned long len =0; 429while(size--) { 430 len++; 431if(*buffer++ =='\n') 432break; 433} 434return len; 435} 436 437static intis_dev_null(const char*str) 438{ 439returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 440} 441 442#define TERM_SPACE 1 443#define TERM_TAB 2 444 445static intname_terminate(const char*name,int namelen,int c,int terminate) 446{ 447if(c ==' '&& !(terminate & TERM_SPACE)) 448return0; 449if(c =='\t'&& !(terminate & TERM_TAB)) 450return0; 451 452return1; 453} 454 455/* remove double slashes to make --index work with such filenames */ 456static char*squash_slash(char*name) 457{ 458int i =0, j =0; 459 460if(!name) 461return NULL; 462 463while(name[i]) { 464if((name[j++] = name[i++]) =='/') 465while(name[i] =='/') 466 i++; 467} 468 name[j] ='\0'; 469return name; 470} 471 472static char*find_name_gnu(const char*line,const char*def,int p_value) 473{ 474struct strbuf name = STRBUF_INIT; 475char*cp; 476 477/* 478 * Proposed "new-style" GNU patch/diff format; see 479 * http://marc.info/?l=git&m=112927316408690&w=2 480 */ 481if(unquote_c_style(&name, line, NULL)) { 482strbuf_release(&name); 483return NULL; 484} 485 486for(cp = name.buf; p_value; p_value--) { 487 cp =strchr(cp,'/'); 488if(!cp) { 489strbuf_release(&name); 490return NULL; 491} 492 cp++; 493} 494 495strbuf_remove(&name,0, cp - name.buf); 496if(root.len) 497strbuf_insert(&name,0, root.buf, root.len); 498returnsquash_slash(strbuf_detach(&name, NULL)); 499} 500 501static size_tsane_tz_len(const char*line,size_t len) 502{ 503const char*tz, *p; 504 505if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 506return0; 507 tz = line + len -strlen(" +0500"); 508 509if(tz[1] !='+'&& tz[1] !='-') 510return0; 511 512for(p = tz +2; p != line + len; p++) 513if(!isdigit(*p)) 514return0; 515 516return line + len - tz; 517} 518 519static size_ttz_with_colon_len(const char*line,size_t len) 520{ 521const char*tz, *p; 522 523if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 524return0; 525 tz = line + len -strlen(" +08:00"); 526 527if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 528return0; 529 p = tz +2; 530if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 531!isdigit(*p++) || !isdigit(*p++)) 532return0; 533 534return line + len - tz; 535} 536 537static size_tdate_len(const char*line,size_t len) 538{ 539const char*date, *p; 540 541if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 542return0; 543 p = date = line + len -strlen("72-02-05"); 544 545if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 546!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 547!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 548return0; 549 550if(date - line >=strlen("19") && 551isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 552 date -=strlen("19"); 553 554return line + len - date; 555} 556 557static size_tshort_time_len(const char*line,size_t len) 558{ 559const char*time, *p; 560 561if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 562return0; 563 p = time = line + len -strlen(" 07:01:32"); 564 565/* Permit 1-digit hours? */ 566if(*p++ !=' '|| 567!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 568!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 569!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 570return0; 571 572return line + len - time; 573} 574 575static size_tfractional_time_len(const char*line,size_t len) 576{ 577const char*p; 578size_t n; 579 580/* Expected format: 19:41:17.620000023 */ 581if(!len || !isdigit(line[len -1])) 582return0; 583 p = line + len -1; 584 585/* Fractional seconds. */ 586while(p > line &&isdigit(*p)) 587 p--; 588if(*p !='.') 589return0; 590 591/* Hours, minutes, and whole seconds. */ 592 n =short_time_len(line, p - line); 593if(!n) 594return0; 595 596return line + len - p + n; 597} 598 599static size_ttrailing_spaces_len(const char*line,size_t len) 600{ 601const char*p; 602 603/* Expected format: ' ' x (1 or more) */ 604if(!len || line[len -1] !=' ') 605return0; 606 607 p = line + len; 608while(p != line) { 609 p--; 610if(*p !=' ') 611return line + len - (p +1); 612} 613 614/* All spaces! */ 615return len; 616} 617 618static size_tdiff_timestamp_len(const char*line,size_t len) 619{ 620const char*end = line + len; 621size_t n; 622 623/* 624 * Posix: 2010-07-05 19:41:17 625 * GNU: 2010-07-05 19:41:17.620000023 -0500 626 */ 627 628if(!isdigit(end[-1])) 629return0; 630 631 n =sane_tz_len(line, end - line); 632if(!n) 633 n =tz_with_colon_len(line, end - line); 634 end -= n; 635 636 n =short_time_len(line, end - line); 637if(!n) 638 n =fractional_time_len(line, end - line); 639 end -= n; 640 641 n =date_len(line, end - line); 642if(!n)/* No date. Too bad. */ 643return0; 644 end -= n; 645 646if(end == line)/* No space before date. */ 647return0; 648if(end[-1] =='\t') {/* Success! */ 649 end--; 650return line + len - end; 651} 652if(end[-1] !=' ')/* No space before date. */ 653return0; 654 655/* Whitespace damage. */ 656 end -=trailing_spaces_len(line, end - line); 657return line + len - end; 658} 659 660static char*find_name_common(const char*line,const char*def, 661int p_value,const char*end,int terminate) 662{ 663int len; 664const char*start = NULL; 665 666if(p_value ==0) 667 start = line; 668while(line != end) { 669char c = *line; 670 671if(!end &&isspace(c)) { 672if(c =='\n') 673break; 674if(name_terminate(start, line-start, c, terminate)) 675break; 676} 677 line++; 678if(c =='/'&& !--p_value) 679 start = line; 680} 681if(!start) 682returnsquash_slash(xstrdup_or_null(def)); 683 len = line - start; 684if(!len) 685returnsquash_slash(xstrdup_or_null(def)); 686 687/* 688 * Generally we prefer the shorter name, especially 689 * if the other one is just a variation of that with 690 * something else tacked on to the end (ie "file.orig" 691 * or "file~"). 692 */ 693if(def) { 694int deflen =strlen(def); 695if(deflen < len && !strncmp(start, def, deflen)) 696returnsquash_slash(xstrdup(def)); 697} 698 699if(root.len) { 700char*ret =xstrfmt("%s%.*s", root.buf, len, start); 701returnsquash_slash(ret); 702} 703 704returnsquash_slash(xmemdupz(start, len)); 705} 706 707static char*find_name(const char*line,char*def,int p_value,int terminate) 708{ 709if(*line =='"') { 710char*name =find_name_gnu(line, def, p_value); 711if(name) 712return name; 713} 714 715returnfind_name_common(line, def, p_value, NULL, terminate); 716} 717 718static char*find_name_traditional(const char*line,char*def,int p_value) 719{ 720size_t len; 721size_t date_len; 722 723if(*line =='"') { 724char*name =find_name_gnu(line, def, p_value); 725if(name) 726return name; 727} 728 729 len =strchrnul(line,'\n') - line; 730 date_len =diff_timestamp_len(line, len); 731if(!date_len) 732returnfind_name_common(line, def, p_value, NULL, TERM_TAB); 733 len -= date_len; 734 735returnfind_name_common(line, def, p_value, line + len,0); 736} 737 738static intcount_slashes(const char*cp) 739{ 740int cnt =0; 741char ch; 742 743while((ch = *cp++)) 744if(ch =='/') 745 cnt++; 746return cnt; 747} 748 749/* 750 * Given the string after "--- " or "+++ ", guess the appropriate 751 * p_value for the given patch. 752 */ 753static intguess_p_value(const char*nameline) 754{ 755char*name, *cp; 756int val = -1; 757 758if(is_dev_null(nameline)) 759return-1; 760 name =find_name_traditional(nameline, NULL,0); 761if(!name) 762return-1; 763 cp =strchr(name,'/'); 764if(!cp) 765 val =0; 766else if(prefix) { 767/* 768 * Does it begin with "a/$our-prefix" and such? Then this is 769 * very likely to apply to our directory. 770 */ 771if(!strncmp(name, prefix, prefix_length)) 772 val =count_slashes(prefix); 773else{ 774 cp++; 775if(!strncmp(cp, prefix, prefix_length)) 776 val =count_slashes(prefix) +1; 777} 778} 779free(name); 780return val; 781} 782 783/* 784 * Does the ---/+++ line have the POSIX timestamp after the last HT? 785 * GNU diff puts epoch there to signal a creation/deletion event. Is 786 * this such a timestamp? 787 */ 788static inthas_epoch_timestamp(const char*nameline) 789{ 790/* 791 * We are only interested in epoch timestamp; any non-zero 792 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 793 * For the same reason, the date must be either 1969-12-31 or 794 * 1970-01-01, and the seconds part must be "00". 795 */ 796const char stamp_regexp[] = 797"^(1969-12-31|1970-01-01)" 798" " 799"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 800" " 801"([-+][0-2][0-9]:?[0-5][0-9])\n"; 802const char*timestamp = NULL, *cp, *colon; 803static regex_t *stamp; 804 regmatch_t m[10]; 805int zoneoffset; 806int hourminute; 807int status; 808 809for(cp = nameline; *cp !='\n'; cp++) { 810if(*cp =='\t') 811 timestamp = cp +1; 812} 813if(!timestamp) 814return0; 815if(!stamp) { 816 stamp =xmalloc(sizeof(*stamp)); 817if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 818warning(_("Cannot prepare timestamp regexp%s"), 819 stamp_regexp); 820return0; 821} 822} 823 824 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 825if(status) { 826if(status != REG_NOMATCH) 827warning(_("regexec returned%dfor input:%s"), 828 status, timestamp); 829return0; 830} 831 832 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 833if(*colon ==':') 834 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 835else 836 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 837if(timestamp[m[3].rm_so] =='-') 838 zoneoffset = -zoneoffset; 839 840/* 841 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 842 * (west of GMT) or 1970-01-01 (east of GMT) 843 */ 844if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 845(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 846return0; 847 848 hourminute = (strtol(timestamp +11, NULL,10) *60+ 849strtol(timestamp +14, NULL,10) - 850 zoneoffset); 851 852return((zoneoffset <0&& hourminute ==1440) || 853(0<= zoneoffset && !hourminute)); 854} 855 856/* 857 * Get the name etc info from the ---/+++ lines of a traditional patch header 858 * 859 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 860 * files, we can happily check the index for a match, but for creating a 861 * new file we should try to match whatever "patch" does. I have no idea. 862 */ 863static voidparse_traditional_patch(const char*first,const char*second,struct patch *patch) 864{ 865char*name; 866 867 first +=4;/* skip "--- " */ 868 second +=4;/* skip "+++ " */ 869if(!p_value_known) { 870int p, q; 871 p =guess_p_value(first); 872 q =guess_p_value(second); 873if(p <0) p = q; 874if(0<= p && p == q) { 875 p_value = p; 876 p_value_known =1; 877} 878} 879if(is_dev_null(first)) { 880 patch->is_new =1; 881 patch->is_delete =0; 882 name =find_name_traditional(second, NULL, p_value); 883 patch->new_name = name; 884}else if(is_dev_null(second)) { 885 patch->is_new =0; 886 patch->is_delete =1; 887 name =find_name_traditional(first, NULL, p_value); 888 patch->old_name = name; 889}else{ 890char*first_name; 891 first_name =find_name_traditional(first, NULL, p_value); 892 name =find_name_traditional(second, first_name, p_value); 893free(first_name); 894if(has_epoch_timestamp(first)) { 895 patch->is_new =1; 896 patch->is_delete =0; 897 patch->new_name = name; 898}else if(has_epoch_timestamp(second)) { 899 patch->is_new =0; 900 patch->is_delete =1; 901 patch->old_name = name; 902}else{ 903 patch->old_name = name; 904 patch->new_name =xstrdup_or_null(name); 905} 906} 907if(!name) 908die(_("unable to find filename in patch at line%d"), linenr); 909} 910 911static intgitdiff_hdrend(const char*line,struct patch *patch) 912{ 913return-1; 914} 915 916/* 917 * We're anal about diff header consistency, to make 918 * sure that we don't end up having strange ambiguous 919 * patches floating around. 920 * 921 * As a result, gitdiff_{old|new}name() will check 922 * their names against any previous information, just 923 * to make sure.. 924 */ 925#define DIFF_OLD_NAME 0 926#define DIFF_NEW_NAME 1 927 928static char*gitdiff_verify_name(const char*line,int isnull,char*orig_name,int side) 929{ 930if(!orig_name && !isnull) 931returnfind_name(line, NULL, p_value, TERM_TAB); 932 933if(orig_name) { 934int len =strlen(orig_name); 935char*another; 936if(isnull) 937die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 938 orig_name, linenr); 939 another =find_name(line, NULL, p_value, TERM_TAB); 940if(!another ||memcmp(another, orig_name, len +1)) 941die((side == DIFF_NEW_NAME) ? 942_("git apply: bad git-diff - inconsistent new filename on line%d") : 943_("git apply: bad git-diff - inconsistent old filename on line%d"), linenr); 944free(another); 945return orig_name; 946}else{ 947/* expect "/dev/null" */ 948if(memcmp("/dev/null", line,9) || line[9] !='\n') 949die(_("git apply: bad git-diff - expected /dev/null on line%d"), linenr); 950return NULL; 951} 952} 953 954static intgitdiff_oldname(const char*line,struct patch *patch) 955{ 956char*orig = patch->old_name; 957 patch->old_name =gitdiff_verify_name(line, patch->is_new, patch->old_name, 958 DIFF_OLD_NAME); 959if(orig != patch->old_name) 960free(orig); 961return0; 962} 963 964static intgitdiff_newname(const char*line,struct patch *patch) 965{ 966char*orig = patch->new_name; 967 patch->new_name =gitdiff_verify_name(line, patch->is_delete, patch->new_name, 968 DIFF_NEW_NAME); 969if(orig != patch->new_name) 970free(orig); 971return0; 972} 973 974static intgitdiff_oldmode(const char*line,struct patch *patch) 975{ 976 patch->old_mode =strtoul(line, NULL,8); 977return0; 978} 979 980static intgitdiff_newmode(const char*line,struct patch *patch) 981{ 982 patch->new_mode =strtoul(line, NULL,8); 983return0; 984} 985 986static intgitdiff_delete(const char*line,struct patch *patch) 987{ 988 patch->is_delete =1; 989free(patch->old_name); 990 patch->old_name =xstrdup_or_null(patch->def_name); 991returngitdiff_oldmode(line, patch); 992} 993 994static intgitdiff_newfile(const char*line,struct patch *patch) 995{ 996 patch->is_new =1; 997free(patch->new_name); 998 patch->new_name =xstrdup_or_null(patch->def_name); 999returngitdiff_newmode(line, patch);1000}10011002static intgitdiff_copysrc(const char*line,struct patch *patch)1003{1004 patch->is_copy =1;1005free(patch->old_name);1006 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0);1007return0;1008}10091010static intgitdiff_copydst(const char*line,struct patch *patch)1011{1012 patch->is_copy =1;1013free(patch->new_name);1014 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0);1015return0;1016}10171018static intgitdiff_renamesrc(const char*line,struct patch *patch)1019{1020 patch->is_rename =1;1021free(patch->old_name);1022 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0);1023return0;1024}10251026static intgitdiff_renamedst(const char*line,struct patch *patch)1027{1028 patch->is_rename =1;1029free(patch->new_name);1030 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0);1031return0;1032}10331034static intgitdiff_similarity(const char*line,struct patch *patch)1035{1036unsigned long val =strtoul(line, NULL,10);1037if(val <=100)1038 patch->score = val;1039return0;1040}10411042static intgitdiff_dissimilarity(const char*line,struct patch *patch)1043{1044unsigned long val =strtoul(line, NULL,10);1045if(val <=100)1046 patch->score = val;1047return0;1048}10491050static intgitdiff_index(const char*line,struct patch *patch)1051{1052/*1053 * index line is N hexadecimal, "..", N hexadecimal,1054 * and optional space with octal mode.1055 */1056const char*ptr, *eol;1057int len;10581059 ptr =strchr(line,'.');1060if(!ptr || ptr[1] !='.'||40< ptr - line)1061return0;1062 len = ptr - line;1063memcpy(patch->old_sha1_prefix, line, len);1064 patch->old_sha1_prefix[len] =0;10651066 line = ptr +2;1067 ptr =strchr(line,' ');1068 eol =strchrnul(line,'\n');10691070if(!ptr || eol < ptr)1071 ptr = eol;1072 len = ptr - line;10731074if(40< len)1075return0;1076memcpy(patch->new_sha1_prefix, line, len);1077 patch->new_sha1_prefix[len] =0;1078if(*ptr ==' ')1079 patch->old_mode =strtoul(ptr+1, NULL,8);1080return0;1081}10821083/*1084 * This is normal for a diff that doesn't change anything: we'll fall through1085 * into the next diff. Tell the parser to break out.1086 */1087static intgitdiff_unrecognized(const char*line,struct patch *patch)1088{1089return-1;1090}10911092/*1093 * Skip p_value leading components from "line"; as we do not accept1094 * absolute paths, return NULL in that case.1095 */1096static const char*skip_tree_prefix(const char*line,int llen)1097{1098int nslash;1099int i;11001101if(!p_value)1102return(llen && line[0] =='/') ? NULL : line;11031104 nslash = p_value;1105for(i =0; i < llen; i++) {1106int ch = line[i];1107if(ch =='/'&& --nslash <=0)1108return(i ==0) ? NULL : &line[i +1];1109}1110return NULL;1111}11121113/*1114 * This is to extract the same name that appears on "diff --git"1115 * line. We do not find and return anything if it is a rename1116 * patch, and it is OK because we will find the name elsewhere.1117 * We need to reliably find name only when it is mode-change only,1118 * creation or deletion of an empty file. In any of these cases,1119 * both sides are the same name under a/ and b/ respectively.1120 */1121static char*git_header_name(const char*line,int llen)1122{1123const char*name;1124const char*second = NULL;1125size_t len, line_len;11261127 line +=strlen("diff --git ");1128 llen -=strlen("diff --git ");11291130if(*line =='"') {1131const char*cp;1132struct strbuf first = STRBUF_INIT;1133struct strbuf sp = STRBUF_INIT;11341135if(unquote_c_style(&first, line, &second))1136goto free_and_fail1;11371138/* strip the a/b prefix including trailing slash */1139 cp =skip_tree_prefix(first.buf, first.len);1140if(!cp)1141goto free_and_fail1;1142strbuf_remove(&first,0, cp - first.buf);11431144/*1145 * second points at one past closing dq of name.1146 * find the second name.1147 */1148while((second < line + llen) &&isspace(*second))1149 second++;11501151if(line + llen <= second)1152goto free_and_fail1;1153if(*second =='"') {1154if(unquote_c_style(&sp, second, NULL))1155goto free_and_fail1;1156 cp =skip_tree_prefix(sp.buf, sp.len);1157if(!cp)1158goto free_and_fail1;1159/* They must match, otherwise ignore */1160if(strcmp(cp, first.buf))1161goto free_and_fail1;1162strbuf_release(&sp);1163returnstrbuf_detach(&first, NULL);1164}11651166/* unquoted second */1167 cp =skip_tree_prefix(second, line + llen - second);1168if(!cp)1169goto free_and_fail1;1170if(line + llen - cp != first.len ||1171memcmp(first.buf, cp, first.len))1172goto free_and_fail1;1173returnstrbuf_detach(&first, NULL);11741175 free_and_fail1:1176strbuf_release(&first);1177strbuf_release(&sp);1178return NULL;1179}11801181/* unquoted first name */1182 name =skip_tree_prefix(line, llen);1183if(!name)1184return NULL;11851186/*1187 * since the first name is unquoted, a dq if exists must be1188 * the beginning of the second name.1189 */1190for(second = name; second < line + llen; second++) {1191if(*second =='"') {1192struct strbuf sp = STRBUF_INIT;1193const char*np;11941195if(unquote_c_style(&sp, second, NULL))1196goto free_and_fail2;11971198 np =skip_tree_prefix(sp.buf, sp.len);1199if(!np)1200goto free_and_fail2;12011202 len = sp.buf + sp.len - np;1203if(len < second - name &&1204!strncmp(np, name, len) &&1205isspace(name[len])) {1206/* Good */1207strbuf_remove(&sp,0, np - sp.buf);1208returnstrbuf_detach(&sp, NULL);1209}12101211 free_and_fail2:1212strbuf_release(&sp);1213return NULL;1214}1215}12161217/*1218 * Accept a name only if it shows up twice, exactly the same1219 * form.1220 */1221 second =strchr(name,'\n');1222if(!second)1223return NULL;1224 line_len = second - name;1225for(len =0; ; len++) {1226switch(name[len]) {1227default:1228continue;1229case'\n':1230return NULL;1231case'\t':case' ':1232/*1233 * Is this the separator between the preimage1234 * and the postimage pathname? Again, we are1235 * only interested in the case where there is1236 * no rename, as this is only to set def_name1237 * and a rename patch has the names elsewhere1238 * in an unambiguous form.1239 */1240if(!name[len +1])1241return NULL;/* no postimage name */1242 second =skip_tree_prefix(name + len +1,1243 line_len - (len +1));1244if(!second)1245return NULL;1246/*1247 * Does len bytes starting at "name" and "second"1248 * (that are separated by one HT or SP we just1249 * found) exactly match?1250 */1251if(second[len] =='\n'&& !strncmp(name, second, len))1252returnxmemdupz(name, len);1253}1254}1255}12561257/* Verify that we recognize the lines following a git header */1258static intparse_git_header(const char*line,int len,unsigned int size,struct patch *patch)1259{1260unsigned long offset;12611262/* A git diff has explicit new/delete information, so we don't guess */1263 patch->is_new =0;1264 patch->is_delete =0;12651266/*1267 * Some things may not have the old name in the1268 * rest of the headers anywhere (pure mode changes,1269 * or removing or adding empty files), so we get1270 * the default name from the header.1271 */1272 patch->def_name =git_header_name(line, len);1273if(patch->def_name && root.len) {1274char*s =xstrfmt("%s%s", root.buf, patch->def_name);1275free(patch->def_name);1276 patch->def_name = s;1277}12781279 line += len;1280 size -= len;1281 linenr++;1282for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) {1283static const struct opentry {1284const char*str;1285int(*fn)(const char*,struct patch *);1286} optable[] = {1287{"@@ -", gitdiff_hdrend },1288{"--- ", gitdiff_oldname },1289{"+++ ", gitdiff_newname },1290{"old mode ", gitdiff_oldmode },1291{"new mode ", gitdiff_newmode },1292{"deleted file mode ", gitdiff_delete },1293{"new file mode ", gitdiff_newfile },1294{"copy from ", gitdiff_copysrc },1295{"copy to ", gitdiff_copydst },1296{"rename old ", gitdiff_renamesrc },1297{"rename new ", gitdiff_renamedst },1298{"rename from ", gitdiff_renamesrc },1299{"rename to ", gitdiff_renamedst },1300{"similarity index ", gitdiff_similarity },1301{"dissimilarity index ", gitdiff_dissimilarity },1302{"index ", gitdiff_index },1303{"", gitdiff_unrecognized },1304};1305int i;13061307 len =linelen(line, size);1308if(!len || line[len-1] !='\n')1309break;1310for(i =0; i <ARRAY_SIZE(optable); i++) {1311const struct opentry *p = optable + i;1312int oplen =strlen(p->str);1313if(len < oplen ||memcmp(p->str, line, oplen))1314continue;1315if(p->fn(line + oplen, patch) <0)1316return offset;1317break;1318}1319}13201321return offset;1322}13231324static intparse_num(const char*line,unsigned long*p)1325{1326char*ptr;13271328if(!isdigit(*line))1329return0;1330*p =strtoul(line, &ptr,10);1331return ptr - line;1332}13331334static intparse_range(const char*line,int len,int offset,const char*expect,1335unsigned long*p1,unsigned long*p2)1336{1337int digits, ex;13381339if(offset <0|| offset >= len)1340return-1;1341 line += offset;1342 len -= offset;13431344 digits =parse_num(line, p1);1345if(!digits)1346return-1;13471348 offset += digits;1349 line += digits;1350 len -= digits;13511352*p2 =1;1353if(*line ==',') {1354 digits =parse_num(line+1, p2);1355if(!digits)1356return-1;13571358 offset += digits+1;1359 line += digits+1;1360 len -= digits+1;1361}13621363 ex =strlen(expect);1364if(ex > len)1365return-1;1366if(memcmp(line, expect, ex))1367return-1;13681369return offset + ex;1370}13711372static voidrecount_diff(const char*line,int size,struct fragment *fragment)1373{1374int oldlines =0, newlines =0, ret =0;13751376if(size <1) {1377warning("recount: ignore empty hunk");1378return;1379}13801381for(;;) {1382int len =linelen(line, size);1383 size -= len;1384 line += len;13851386if(size <1)1387break;13881389switch(*line) {1390case' ':case'\n':1391 newlines++;1392/* fall through */1393case'-':1394 oldlines++;1395continue;1396case'+':1397 newlines++;1398continue;1399case'\\':1400continue;1401case'@':1402 ret = size <3|| !starts_with(line,"@@ ");1403break;1404case'd':1405 ret = size <5|| !starts_with(line,"diff ");1406break;1407default:1408 ret = -1;1409break;1410}1411if(ret) {1412warning(_("recount: unexpected line: %.*s"),1413(int)linelen(line, size), line);1414return;1415}1416break;1417}1418 fragment->oldlines = oldlines;1419 fragment->newlines = newlines;1420}14211422/*1423 * Parse a unified diff fragment header of the1424 * form "@@ -a,b +c,d @@"1425 */1426static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1427{1428int offset;14291430if(!len || line[len-1] !='\n')1431return-1;14321433/* Figure out the number of lines in a fragment */1434 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1435 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14361437return offset;1438}14391440static intfind_header(const char*line,unsigned long size,int*hdrsize,struct patch *patch)1441{1442unsigned long offset, len;14431444 patch->is_toplevel_relative =0;1445 patch->is_rename = patch->is_copy =0;1446 patch->is_new = patch->is_delete = -1;1447 patch->old_mode = patch->new_mode =0;1448 patch->old_name = patch->new_name = NULL;1449for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) {1450unsigned long nextlen;14511452 len =linelen(line, size);1453if(!len)1454break;14551456/* Testing this early allows us to take a few shortcuts.. */1457if(len <6)1458continue;14591460/*1461 * Make sure we don't find any unconnected patch fragments.1462 * That's a sign that we didn't find a header, and that a1463 * patch has become corrupted/broken up.1464 */1465if(!memcmp("@@ -", line,4)) {1466struct fragment dummy;1467if(parse_fragment_header(line, len, &dummy) <0)1468continue;1469die(_("patch fragment without header at line%d: %.*s"),1470 linenr, (int)len-1, line);1471}14721473if(size < len +6)1474break;14751476/*1477 * Git patch? It might not have a real patch, just a rename1478 * or mode change, so we handle that specially1479 */1480if(!memcmp("diff --git ", line,11)) {1481int git_hdr_len =parse_git_header(line, len, size, patch);1482if(git_hdr_len <= len)1483continue;1484if(!patch->old_name && !patch->new_name) {1485if(!patch->def_name)1486die(Q_("git diff header lacks filename information when removing "1487"%dleading pathname component (line%d)",1488"git diff header lacks filename information when removing "1489"%dleading pathname components (line%d)",1490 p_value),1491 p_value, linenr);1492 patch->old_name =xstrdup(patch->def_name);1493 patch->new_name =xstrdup(patch->def_name);1494}1495if(!patch->is_delete && !patch->new_name)1496die("git diff header lacks filename information "1497"(line%d)", linenr);1498 patch->is_toplevel_relative =1;1499*hdrsize = git_hdr_len;1500return offset;1501}15021503/* --- followed by +++ ? */1504if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1505continue;15061507/*1508 * We only accept unified patches, so we want it to1509 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1510 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1511 */1512 nextlen =linelen(line + len, size - len);1513if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1514continue;15151516/* Ok, we'll consider it a patch */1517parse_traditional_patch(line, line+len, patch);1518*hdrsize = len + nextlen;1519 linenr +=2;1520return offset;1521}1522return-1;1523}15241525static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1526{1527char*err;15281529if(!result)1530return;15311532 whitespace_error++;1533if(squelch_whitespace_errors &&1534 squelch_whitespace_errors < whitespace_error)1535return;15361537 err =whitespace_error_string(result);1538fprintf(stderr,"%s:%d:%s.\n%.*s\n",1539 patch_input_file, linenr, err, len, line);1540free(err);1541}15421543static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1544{1545unsigned result =ws_check(line +1, len -1, ws_rule);15461547record_ws_error(result, line +1, len -2, linenr);1548}15491550/*1551 * Parse a unified diff. Note that this really needs to parse each1552 * fragment separately, since the only way to know the difference1553 * between a "---" that is part of a patch, and a "---" that starts1554 * the next patch is to look at the line counts..1555 */1556static intparse_fragment(const char*line,unsigned long size,1557struct patch *patch,struct fragment *fragment)1558{1559int added, deleted;1560int len =linelen(line, size), offset;1561unsigned long oldlines, newlines;1562unsigned long leading, trailing;15631564 offset =parse_fragment_header(line, len, fragment);1565if(offset <0)1566return-1;1567if(offset >0&& patch->recount)1568recount_diff(line + offset, size - offset, fragment);1569 oldlines = fragment->oldlines;1570 newlines = fragment->newlines;1571 leading =0;1572 trailing =0;15731574/* Parse the thing.. */1575 line += len;1576 size -= len;1577 linenr++;1578 added = deleted =0;1579for(offset = len;15800< size;1581 offset += len, size -= len, line += len, linenr++) {1582if(!oldlines && !newlines)1583break;1584 len =linelen(line, size);1585if(!len || line[len-1] !='\n')1586return-1;1587switch(*line) {1588default:1589return-1;1590case'\n':/* newer GNU diff, an empty context line */1591case' ':1592 oldlines--;1593 newlines--;1594if(!deleted && !added)1595 leading++;1596 trailing++;1597if(!apply_in_reverse &&1598 ws_error_action == correct_ws_error)1599check_whitespace(line, len, patch->ws_rule);1600break;1601case'-':1602if(apply_in_reverse &&1603 ws_error_action != nowarn_ws_error)1604check_whitespace(line, len, patch->ws_rule);1605 deleted++;1606 oldlines--;1607 trailing =0;1608break;1609case'+':1610if(!apply_in_reverse &&1611 ws_error_action != nowarn_ws_error)1612check_whitespace(line, len, patch->ws_rule);1613 added++;1614 newlines--;1615 trailing =0;1616break;16171618/*1619 * We allow "\ No newline at end of file". Depending1620 * on locale settings when the patch was produced we1621 * don't know what this line looks like. The only1622 * thing we do know is that it begins with "\ ".1623 * Checking for 12 is just for sanity check -- any1624 * l10n of "\ No newline..." is at least that long.1625 */1626case'\\':1627if(len <12||memcmp(line,"\\",2))1628return-1;1629break;1630}1631}1632if(oldlines || newlines)1633return-1;1634if(!deleted && !added)1635return-1;16361637 fragment->leading = leading;1638 fragment->trailing = trailing;16391640/*1641 * If a fragment ends with an incomplete line, we failed to include1642 * it in the above loop because we hit oldlines == newlines == 01643 * before seeing it.1644 */1645if(12< size && !memcmp(line,"\\",2))1646 offset +=linelen(line, size);16471648 patch->lines_added += added;1649 patch->lines_deleted += deleted;16501651if(0< patch->is_new && oldlines)1652returnerror(_("new file depends on old contents"));1653if(0< patch->is_delete && newlines)1654returnerror(_("deleted file still has contents"));1655return offset;1656}16571658/*1659 * We have seen "diff --git a/... b/..." header (or a traditional patch1660 * header). Read hunks that belong to this patch into fragments and hang1661 * them to the given patch structure.1662 *1663 * The (fragment->patch, fragment->size) pair points into the memory given1664 * by the caller, not a copy, when we return.1665 */1666static intparse_single_patch(const char*line,unsigned long size,struct patch *patch)1667{1668unsigned long offset =0;1669unsigned long oldlines =0, newlines =0, context =0;1670struct fragment **fragp = &patch->fragments;16711672while(size >4&& !memcmp(line,"@@ -",4)) {1673struct fragment *fragment;1674int len;16751676 fragment =xcalloc(1,sizeof(*fragment));1677 fragment->linenr = linenr;1678 len =parse_fragment(line, size, patch, fragment);1679if(len <=0)1680die(_("corrupt patch at line%d"), linenr);1681 fragment->patch = line;1682 fragment->size = len;1683 oldlines += fragment->oldlines;1684 newlines += fragment->newlines;1685 context += fragment->leading + fragment->trailing;16861687*fragp = fragment;1688 fragp = &fragment->next;16891690 offset += len;1691 line += len;1692 size -= len;1693}16941695/*1696 * If something was removed (i.e. we have old-lines) it cannot1697 * be creation, and if something was added it cannot be1698 * deletion. However, the reverse is not true; --unified=01699 * patches that only add are not necessarily creation even1700 * though they do not have any old lines, and ones that only1701 * delete are not necessarily deletion.1702 *1703 * Unfortunately, a real creation/deletion patch do _not_ have1704 * any context line by definition, so we cannot safely tell it1705 * apart with --unified=0 insanity. At least if the patch has1706 * more than one hunk it is not creation or deletion.1707 */1708if(patch->is_new <0&&1709(oldlines || (patch->fragments && patch->fragments->next)))1710 patch->is_new =0;1711if(patch->is_delete <0&&1712(newlines || (patch->fragments && patch->fragments->next)))1713 patch->is_delete =0;17141715if(0< patch->is_new && oldlines)1716die(_("new file%sdepends on old contents"), patch->new_name);1717if(0< patch->is_delete && newlines)1718die(_("deleted file%sstill has contents"), patch->old_name);1719if(!patch->is_delete && !newlines && context)1720fprintf_ln(stderr,1721_("** warning: "1722"file%sbecomes empty but is not deleted"),1723 patch->new_name);17241725return offset;1726}17271728staticinlineintmetadata_changes(struct patch *patch)1729{1730return patch->is_rename >0||1731 patch->is_copy >0||1732 patch->is_new >0||1733 patch->is_delete ||1734(patch->old_mode && patch->new_mode &&1735 patch->old_mode != patch->new_mode);1736}17371738static char*inflate_it(const void*data,unsigned long size,1739unsigned long inflated_size)1740{1741 git_zstream stream;1742void*out;1743int st;17441745memset(&stream,0,sizeof(stream));17461747 stream.next_in = (unsigned char*)data;1748 stream.avail_in = size;1749 stream.next_out = out =xmalloc(inflated_size);1750 stream.avail_out = inflated_size;1751git_inflate_init(&stream);1752 st =git_inflate(&stream, Z_FINISH);1753git_inflate_end(&stream);1754if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1755free(out);1756return NULL;1757}1758return out;1759}17601761/*1762 * Read a binary hunk and return a new fragment; fragment->patch1763 * points at an allocated memory that the caller must free, so1764 * it is marked as "->free_patch = 1".1765 */1766static struct fragment *parse_binary_hunk(char**buf_p,1767unsigned long*sz_p,1768int*status_p,1769int*used_p)1770{1771/*1772 * Expect a line that begins with binary patch method ("literal"1773 * or "delta"), followed by the length of data before deflating.1774 * a sequence of 'length-byte' followed by base-85 encoded data1775 * should follow, terminated by a newline.1776 *1777 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1778 * and we would limit the patch line to 66 characters,1779 * so one line can fit up to 13 groups that would decode1780 * to 52 bytes max. The length byte 'A'-'Z' corresponds1781 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1782 */1783int llen, used;1784unsigned long size = *sz_p;1785char*buffer = *buf_p;1786int patch_method;1787unsigned long origlen;1788char*data = NULL;1789int hunk_size =0;1790struct fragment *frag;17911792 llen =linelen(buffer, size);1793 used = llen;17941795*status_p =0;17961797if(starts_with(buffer,"delta ")) {1798 patch_method = BINARY_DELTA_DEFLATED;1799 origlen =strtoul(buffer +6, NULL,10);1800}1801else if(starts_with(buffer,"literal ")) {1802 patch_method = BINARY_LITERAL_DEFLATED;1803 origlen =strtoul(buffer +8, NULL,10);1804}1805else1806return NULL;18071808 linenr++;1809 buffer += llen;1810while(1) {1811int byte_length, max_byte_length, newsize;1812 llen =linelen(buffer, size);1813 used += llen;1814 linenr++;1815if(llen ==1) {1816/* consume the blank line */1817 buffer++;1818 size--;1819break;1820}1821/*1822 * Minimum line is "A00000\n" which is 7-byte long,1823 * and the line length must be multiple of 5 plus 2.1824 */1825if((llen <7) || (llen-2) %5)1826goto corrupt;1827 max_byte_length = (llen -2) /5*4;1828 byte_length = *buffer;1829if('A'<= byte_length && byte_length <='Z')1830 byte_length = byte_length -'A'+1;1831else if('a'<= byte_length && byte_length <='z')1832 byte_length = byte_length -'a'+27;1833else1834goto corrupt;1835/* if the input length was not multiple of 4, we would1836 * have filler at the end but the filler should never1837 * exceed 3 bytes1838 */1839if(max_byte_length < byte_length ||1840 byte_length <= max_byte_length -4)1841goto corrupt;1842 newsize = hunk_size + byte_length;1843 data =xrealloc(data, newsize);1844if(decode_85(data + hunk_size, buffer +1, byte_length))1845goto corrupt;1846 hunk_size = newsize;1847 buffer += llen;1848 size -= llen;1849}18501851 frag =xcalloc(1,sizeof(*frag));1852 frag->patch =inflate_it(data, hunk_size, origlen);1853 frag->free_patch =1;1854if(!frag->patch)1855goto corrupt;1856free(data);1857 frag->size = origlen;1858*buf_p = buffer;1859*sz_p = size;1860*used_p = used;1861 frag->binary_patch_method = patch_method;1862return frag;18631864 corrupt:1865free(data);1866*status_p = -1;1867error(_("corrupt binary patch at line%d: %.*s"),1868 linenr-1, llen-1, buffer);1869return NULL;1870}18711872static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1873{1874/*1875 * We have read "GIT binary patch\n"; what follows is a line1876 * that says the patch method (currently, either "literal" or1877 * "delta") and the length of data before deflating; a1878 * sequence of 'length-byte' followed by base-85 encoded data1879 * follows.1880 *1881 * When a binary patch is reversible, there is another binary1882 * hunk in the same format, starting with patch method (either1883 * "literal" or "delta") with the length of data, and a sequence1884 * of length-byte + base-85 encoded data, terminated with another1885 * empty line. This data, when applied to the postimage, produces1886 * the preimage.1887 */1888struct fragment *forward;1889struct fragment *reverse;1890int status;1891int used, used_1;18921893 forward =parse_binary_hunk(&buffer, &size, &status, &used);1894if(!forward && !status)1895/* there has to be one hunk (forward hunk) */1896returnerror(_("unrecognized binary patch at line%d"), linenr-1);1897if(status)1898/* otherwise we already gave an error message */1899return status;19001901 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1902if(reverse)1903 used += used_1;1904else if(status) {1905/*1906 * Not having reverse hunk is not an error, but having1907 * a corrupt reverse hunk is.1908 */1909free((void*) forward->patch);1910free(forward);1911return status;1912}1913 forward->next = reverse;1914 patch->fragments = forward;1915 patch->is_binary =1;1916return used;1917}19181919static voidprefix_one(char**name)1920{1921char*old_name = *name;1922if(!old_name)1923return;1924*name =xstrdup(prefix_filename(prefix, prefix_length, *name));1925free(old_name);1926}19271928static voidprefix_patch(struct patch *p)1929{1930if(!prefix || p->is_toplevel_relative)1931return;1932prefix_one(&p->new_name);1933prefix_one(&p->old_name);1934}19351936/*1937 * include/exclude1938 */19391940static struct string_list limit_by_name;1941static int has_include;1942static voidadd_name_limit(const char*name,int exclude)1943{1944struct string_list_item *it;19451946 it =string_list_append(&limit_by_name, name);1947 it->util = exclude ? NULL : (void*)1;1948}19491950static intuse_patch(struct patch *p)1951{1952const char*pathname = p->new_name ? p->new_name : p->old_name;1953int i;19541955/* Paths outside are not touched regardless of "--include" */1956if(0< prefix_length) {1957int pathlen =strlen(pathname);1958if(pathlen <= prefix_length ||1959memcmp(prefix, pathname, prefix_length))1960return0;1961}19621963/* See if it matches any of exclude/include rule */1964for(i =0; i < limit_by_name.nr; i++) {1965struct string_list_item *it = &limit_by_name.items[i];1966if(!wildmatch(it->string, pathname,0, NULL))1967return(it->util != NULL);1968}19691970/*1971 * If we had any include, a path that does not match any rule is1972 * not used. Otherwise, we saw bunch of exclude rules (or none)1973 * and such a path is used.1974 */1975return!has_include;1976}197719781979/*1980 * Read the patch text in "buffer" that extends for "size" bytes; stop1981 * reading after seeing a single patch (i.e. changes to a single file).1982 * Create fragments (i.e. patch hunks) and hang them to the given patch.1983 * Return the number of bytes consumed, so that the caller can call us1984 * again for the next patch.1985 */1986static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1987{1988int hdrsize, patchsize;1989int offset =find_header(buffer, size, &hdrsize, patch);19901991if(offset <0)1992return offset;19931994prefix_patch(patch);19951996if(!use_patch(patch))1997 patch->ws_rule =0;1998else1999 patch->ws_rule =whitespace_rule(patch->new_name2000? patch->new_name2001: patch->old_name);20022003 patchsize =parse_single_patch(buffer + offset + hdrsize,2004 size - offset - hdrsize, patch);20052006if(!patchsize) {2007static const char git_binary[] ="GIT binary patch\n";2008int hd = hdrsize + offset;2009unsigned long llen =linelen(buffer + hd, size - hd);20102011if(llen ==sizeof(git_binary) -1&&2012!memcmp(git_binary, buffer + hd, llen)) {2013int used;2014 linenr++;2015 used =parse_binary(buffer + hd + llen,2016 size - hd - llen, patch);2017if(used)2018 patchsize = used + llen;2019else2020 patchsize =0;2021}2022else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2023static const char*binhdr[] = {2024"Binary files ",2025"Files ",2026 NULL,2027};2028int i;2029for(i =0; binhdr[i]; i++) {2030int len =strlen(binhdr[i]);2031if(len < size - hd &&2032!memcmp(binhdr[i], buffer + hd, len)) {2033 linenr++;2034 patch->is_binary =1;2035 patchsize = llen;2036break;2037}2038}2039}20402041/* Empty patch cannot be applied if it is a text patch2042 * without metadata change. A binary patch appears2043 * empty to us here.2044 */2045if((apply || check) &&2046(!patch->is_binary && !metadata_changes(patch)))2047die(_("patch with only garbage at line%d"), linenr);2048}20492050return offset + hdrsize + patchsize;2051}20522053#define swap(a,b) myswap((a),(b),sizeof(a))20542055#define myswap(a, b, size) do { \2056 unsigned char mytmp[size]; \2057 memcpy(mytmp, &a, size); \2058 memcpy(&a, &b, size); \2059 memcpy(&b, mytmp, size); \2060} while (0)20612062static voidreverse_patches(struct patch *p)2063{2064for(; p; p = p->next) {2065struct fragment *frag = p->fragments;20662067swap(p->new_name, p->old_name);2068swap(p->new_mode, p->old_mode);2069swap(p->is_new, p->is_delete);2070swap(p->lines_added, p->lines_deleted);2071swap(p->old_sha1_prefix, p->new_sha1_prefix);20722073for(; frag; frag = frag->next) {2074swap(frag->newpos, frag->oldpos);2075swap(frag->newlines, frag->oldlines);2076}2077}2078}20792080static const char pluses[] =2081"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2082static const char minuses[]=2083"----------------------------------------------------------------------";20842085static voidshow_stats(struct patch *patch)2086{2087struct strbuf qname = STRBUF_INIT;2088char*cp = patch->new_name ? patch->new_name : patch->old_name;2089int max, add, del;20902091quote_c_style(cp, &qname, NULL,0);20922093/*2094 * "scale" the filename2095 */2096 max = max_len;2097if(max >50)2098 max =50;20992100if(qname.len > max) {2101 cp =strchr(qname.buf + qname.len +3- max,'/');2102if(!cp)2103 cp = qname.buf + qname.len +3- max;2104strbuf_splice(&qname,0, cp - qname.buf,"...",3);2105}21062107if(patch->is_binary) {2108printf(" %-*s | Bin\n", max, qname.buf);2109strbuf_release(&qname);2110return;2111}21122113printf(" %-*s |", max, qname.buf);2114strbuf_release(&qname);21152116/*2117 * scale the add/delete2118 */2119 max = max + max_change >70?70- max : max_change;2120 add = patch->lines_added;2121 del = patch->lines_deleted;21222123if(max_change >0) {2124int total = ((add + del) * max + max_change /2) / max_change;2125 add = (add * max + max_change /2) / max_change;2126 del = total - add;2127}2128printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2129 add, pluses, del, minuses);2130}21312132static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2133{2134switch(st->st_mode & S_IFMT) {2135case S_IFLNK:2136if(strbuf_readlink(buf, path, st->st_size) <0)2137returnerror(_("unable to read symlink%s"), path);2138return0;2139case S_IFREG:2140if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2141returnerror(_("unable to open or read%s"), path);2142convert_to_git(path, buf->buf, buf->len, buf,0);2143return0;2144default:2145return-1;2146}2147}21482149/*2150 * Update the preimage, and the common lines in postimage,2151 * from buffer buf of length len. If postlen is 0 the postimage2152 * is updated in place, otherwise it's updated on a new buffer2153 * of length postlen2154 */21552156static voidupdate_pre_post_images(struct image *preimage,2157struct image *postimage,2158char*buf,2159size_t len,size_t postlen)2160{2161int i, ctx, reduced;2162char*new, *old, *fixed;2163struct image fixed_preimage;21642165/*2166 * Update the preimage with whitespace fixes. Note that we2167 * are not losing preimage->buf -- apply_one_fragment() will2168 * free "oldlines".2169 */2170prepare_image(&fixed_preimage, buf, len,1);2171assert(postlen2172? fixed_preimage.nr == preimage->nr2173: fixed_preimage.nr <= preimage->nr);2174for(i =0; i < fixed_preimage.nr; i++)2175 fixed_preimage.line[i].flag = preimage->line[i].flag;2176free(preimage->line_allocated);2177*preimage = fixed_preimage;21782179/*2180 * Adjust the common context lines in postimage. This can be2181 * done in-place when we are shrinking it with whitespace2182 * fixing, but needs a new buffer when ignoring whitespace or2183 * expanding leading tabs to spaces.2184 *2185 * We trust the caller to tell us if the update can be done2186 * in place (postlen==0) or not.2187 */2188 old = postimage->buf;2189if(postlen)2190new= postimage->buf =xmalloc(postlen);2191else2192new= old;2193 fixed = preimage->buf;21942195for(i = reduced = ctx =0; i < postimage->nr; i++) {2196size_t len = postimage->line[i].len;2197if(!(postimage->line[i].flag & LINE_COMMON)) {2198/* an added line -- no counterparts in preimage */2199memmove(new, old, len);2200 old += len;2201new+= len;2202continue;2203}22042205/* a common context -- skip it in the original postimage */2206 old += len;22072208/* and find the corresponding one in the fixed preimage */2209while(ctx < preimage->nr &&2210!(preimage->line[ctx].flag & LINE_COMMON)) {2211 fixed += preimage->line[ctx].len;2212 ctx++;2213}22142215/*2216 * preimage is expected to run out, if the caller2217 * fixed addition of trailing blank lines.2218 */2219if(preimage->nr <= ctx) {2220 reduced++;2221continue;2222}22232224/* and copy it in, while fixing the line length */2225 len = preimage->line[ctx].len;2226memcpy(new, fixed, len);2227new+= len;2228 fixed += len;2229 postimage->line[i].len = len;2230 ctx++;2231}22322233if(postlen2234? postlen <new- postimage->buf2235: postimage->len <new- postimage->buf)2236die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2237(int)postlen, (int) postimage->len, (int)(new- postimage->buf));22382239/* Fix the length of the whole thing */2240 postimage->len =new- postimage->buf;2241 postimage->nr -= reduced;2242}22432244static intmatch_fragment(struct image *img,2245struct image *preimage,2246struct image *postimage,2247unsigned longtry,2248int try_lno,2249unsigned ws_rule,2250int match_beginning,int match_end)2251{2252int i;2253char*fixed_buf, *buf, *orig, *target;2254struct strbuf fixed;2255size_t fixed_len, postlen;2256int preimage_limit;22572258if(preimage->nr + try_lno <= img->nr) {2259/*2260 * The hunk falls within the boundaries of img.2261 */2262 preimage_limit = preimage->nr;2263if(match_end && (preimage->nr + try_lno != img->nr))2264return0;2265}else if(ws_error_action == correct_ws_error &&2266(ws_rule & WS_BLANK_AT_EOF)) {2267/*2268 * This hunk extends beyond the end of img, and we are2269 * removing blank lines at the end of the file. This2270 * many lines from the beginning of the preimage must2271 * match with img, and the remainder of the preimage2272 * must be blank.2273 */2274 preimage_limit = img->nr - try_lno;2275}else{2276/*2277 * The hunk extends beyond the end of the img and2278 * we are not removing blanks at the end, so we2279 * should reject the hunk at this position.2280 */2281return0;2282}22832284if(match_beginning && try_lno)2285return0;22862287/* Quick hash check */2288for(i =0; i < preimage_limit; i++)2289if((img->line[try_lno + i].flag & LINE_PATCHED) ||2290(preimage->line[i].hash != img->line[try_lno + i].hash))2291return0;22922293if(preimage_limit == preimage->nr) {2294/*2295 * Do we have an exact match? If we were told to match2296 * at the end, size must be exactly at try+fragsize,2297 * otherwise try+fragsize must be still within the preimage,2298 * and either case, the old piece should match the preimage2299 * exactly.2300 */2301if((match_end2302? (try+ preimage->len == img->len)2303: (try+ preimage->len <= img->len)) &&2304!memcmp(img->buf +try, preimage->buf, preimage->len))2305return1;2306}else{2307/*2308 * The preimage extends beyond the end of img, so2309 * there cannot be an exact match.2310 *2311 * There must be one non-blank context line that match2312 * a line before the end of img.2313 */2314char*buf_end;23152316 buf = preimage->buf;2317 buf_end = buf;2318for(i =0; i < preimage_limit; i++)2319 buf_end += preimage->line[i].len;23202321for( ; buf < buf_end; buf++)2322if(!isspace(*buf))2323break;2324if(buf == buf_end)2325return0;2326}23272328/*2329 * No exact match. If we are ignoring whitespace, run a line-by-line2330 * fuzzy matching. We collect all the line length information because2331 * we need it to adjust whitespace if we match.2332 */2333if(ws_ignore_action == ignore_ws_change) {2334size_t imgoff =0;2335size_t preoff =0;2336size_t postlen = postimage->len;2337size_t extra_chars;2338char*preimage_eof;2339char*preimage_end;2340for(i =0; i < preimage_limit; i++) {2341size_t prelen = preimage->line[i].len;2342size_t imglen = img->line[try_lno+i].len;23432344if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2345 preimage->buf + preoff, prelen))2346return0;2347if(preimage->line[i].flag & LINE_COMMON)2348 postlen += imglen - prelen;2349 imgoff += imglen;2350 preoff += prelen;2351}23522353/*2354 * Ok, the preimage matches with whitespace fuzz.2355 *2356 * imgoff now holds the true length of the target that2357 * matches the preimage before the end of the file.2358 *2359 * Count the number of characters in the preimage that fall2360 * beyond the end of the file and make sure that all of them2361 * are whitespace characters. (This can only happen if2362 * we are removing blank lines at the end of the file.)2363 */2364 buf = preimage_eof = preimage->buf + preoff;2365for( ; i < preimage->nr; i++)2366 preoff += preimage->line[i].len;2367 preimage_end = preimage->buf + preoff;2368for( ; buf < preimage_end; buf++)2369if(!isspace(*buf))2370return0;23712372/*2373 * Update the preimage and the common postimage context2374 * lines to use the same whitespace as the target.2375 * If whitespace is missing in the target (i.e.2376 * if the preimage extends beyond the end of the file),2377 * use the whitespace from the preimage.2378 */2379 extra_chars = preimage_end - preimage_eof;2380strbuf_init(&fixed, imgoff + extra_chars);2381strbuf_add(&fixed, img->buf +try, imgoff);2382strbuf_add(&fixed, preimage_eof, extra_chars);2383 fixed_buf =strbuf_detach(&fixed, &fixed_len);2384update_pre_post_images(preimage, postimage,2385 fixed_buf, fixed_len, postlen);2386return1;2387}23882389if(ws_error_action != correct_ws_error)2390return0;23912392/*2393 * The hunk does not apply byte-by-byte, but the hash says2394 * it might with whitespace fuzz. We weren't asked to2395 * ignore whitespace, we were asked to correct whitespace2396 * errors, so let's try matching after whitespace correction.2397 *2398 * While checking the preimage against the target, whitespace2399 * errors in both fixed, we count how large the corresponding2400 * postimage needs to be. The postimage prepared by2401 * apply_one_fragment() has whitespace errors fixed on added2402 * lines already, but the common lines were propagated as-is,2403 * which may become longer when their whitespace errors are2404 * fixed.2405 */24062407/* First count added lines in postimage */2408 postlen =0;2409for(i =0; i < postimage->nr; i++) {2410if(!(postimage->line[i].flag & LINE_COMMON))2411 postlen += postimage->line[i].len;2412}24132414/*2415 * The preimage may extend beyond the end of the file,2416 * but in this loop we will only handle the part of the2417 * preimage that falls within the file.2418 */2419strbuf_init(&fixed, preimage->len +1);2420 orig = preimage->buf;2421 target = img->buf +try;2422for(i =0; i < preimage_limit; i++) {2423size_t oldlen = preimage->line[i].len;2424size_t tgtlen = img->line[try_lno + i].len;2425size_t fixstart = fixed.len;2426struct strbuf tgtfix;2427int match;24282429/* Try fixing the line in the preimage */2430ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24312432/* Try fixing the line in the target */2433strbuf_init(&tgtfix, tgtlen);2434ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);24352436/*2437 * If they match, either the preimage was based on2438 * a version before our tree fixed whitespace breakage,2439 * or we are lacking a whitespace-fix patch the tree2440 * the preimage was based on already had (i.e. target2441 * has whitespace breakage, the preimage doesn't).2442 * In either case, we are fixing the whitespace breakages2443 * so we might as well take the fix together with their2444 * real change.2445 */2446 match = (tgtfix.len == fixed.len - fixstart &&2447!memcmp(tgtfix.buf, fixed.buf + fixstart,2448 fixed.len - fixstart));24492450/* Add the length if this is common with the postimage */2451if(preimage->line[i].flag & LINE_COMMON)2452 postlen += tgtfix.len;24532454strbuf_release(&tgtfix);2455if(!match)2456goto unmatch_exit;24572458 orig += oldlen;2459 target += tgtlen;2460}246124622463/*2464 * Now handle the lines in the preimage that falls beyond the2465 * end of the file (if any). They will only match if they are2466 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2467 * false).2468 */2469for( ; i < preimage->nr; i++) {2470size_t fixstart = fixed.len;/* start of the fixed preimage */2471size_t oldlen = preimage->line[i].len;2472int j;24732474/* Try fixing the line in the preimage */2475ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24762477for(j = fixstart; j < fixed.len; j++)2478if(!isspace(fixed.buf[j]))2479goto unmatch_exit;24802481 orig += oldlen;2482}24832484/*2485 * Yes, the preimage is based on an older version that still2486 * has whitespace breakages unfixed, and fixing them makes the2487 * hunk match. Update the context lines in the postimage.2488 */2489 fixed_buf =strbuf_detach(&fixed, &fixed_len);2490if(postlen < postimage->len)2491 postlen =0;2492update_pre_post_images(preimage, postimage,2493 fixed_buf, fixed_len, postlen);2494return1;24952496 unmatch_exit:2497strbuf_release(&fixed);2498return0;2499}25002501static intfind_pos(struct image *img,2502struct image *preimage,2503struct image *postimage,2504int line,2505unsigned ws_rule,2506int match_beginning,int match_end)2507{2508int i;2509unsigned long backwards, forwards,try;2510int backwards_lno, forwards_lno, try_lno;25112512/*2513 * If match_beginning or match_end is specified, there is no2514 * point starting from a wrong line that will never match and2515 * wander around and wait for a match at the specified end.2516 */2517if(match_beginning)2518 line =0;2519else if(match_end)2520 line = img->nr - preimage->nr;25212522/*2523 * Because the comparison is unsigned, the following test2524 * will also take care of a negative line number that can2525 * result when match_end and preimage is larger than the target.2526 */2527if((size_t) line > img->nr)2528 line = img->nr;25292530try=0;2531for(i =0; i < line; i++)2532try+= img->line[i].len;25332534/*2535 * There's probably some smart way to do this, but I'll leave2536 * that to the smart and beautiful people. I'm simple and stupid.2537 */2538 backwards =try;2539 backwards_lno = line;2540 forwards =try;2541 forwards_lno = line;2542 try_lno = line;25432544for(i =0; ; i++) {2545if(match_fragment(img, preimage, postimage,2546try, try_lno, ws_rule,2547 match_beginning, match_end))2548return try_lno;25492550 again:2551if(backwards_lno ==0&& forwards_lno == img->nr)2552break;25532554if(i &1) {2555if(backwards_lno ==0) {2556 i++;2557goto again;2558}2559 backwards_lno--;2560 backwards -= img->line[backwards_lno].len;2561try= backwards;2562 try_lno = backwards_lno;2563}else{2564if(forwards_lno == img->nr) {2565 i++;2566goto again;2567}2568 forwards += img->line[forwards_lno].len;2569 forwards_lno++;2570try= forwards;2571 try_lno = forwards_lno;2572}25732574}2575return-1;2576}25772578static voidremove_first_line(struct image *img)2579{2580 img->buf += img->line[0].len;2581 img->len -= img->line[0].len;2582 img->line++;2583 img->nr--;2584}25852586static voidremove_last_line(struct image *img)2587{2588 img->len -= img->line[--img->nr].len;2589}25902591/*2592 * The change from "preimage" and "postimage" has been found to2593 * apply at applied_pos (counts in line numbers) in "img".2594 * Update "img" to remove "preimage" and replace it with "postimage".2595 */2596static voidupdate_image(struct image *img,2597int applied_pos,2598struct image *preimage,2599struct image *postimage)2600{2601/*2602 * remove the copy of preimage at offset in img2603 * and replace it with postimage2604 */2605int i, nr;2606size_t remove_count, insert_count, applied_at =0;2607char*result;2608int preimage_limit;26092610/*2611 * If we are removing blank lines at the end of img,2612 * the preimage may extend beyond the end.2613 * If that is the case, we must be careful only to2614 * remove the part of the preimage that falls within2615 * the boundaries of img. Initialize preimage_limit2616 * to the number of lines in the preimage that falls2617 * within the boundaries.2618 */2619 preimage_limit = preimage->nr;2620if(preimage_limit > img->nr - applied_pos)2621 preimage_limit = img->nr - applied_pos;26222623for(i =0; i < applied_pos; i++)2624 applied_at += img->line[i].len;26252626 remove_count =0;2627for(i =0; i < preimage_limit; i++)2628 remove_count += img->line[applied_pos + i].len;2629 insert_count = postimage->len;26302631/* Adjust the contents */2632 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2633memcpy(result, img->buf, applied_at);2634memcpy(result + applied_at, postimage->buf, postimage->len);2635memcpy(result + applied_at + postimage->len,2636 img->buf + (applied_at + remove_count),2637 img->len - (applied_at + remove_count));2638free(img->buf);2639 img->buf = result;2640 img->len += insert_count - remove_count;2641 result[img->len] ='\0';26422643/* Adjust the line table */2644 nr = img->nr + postimage->nr - preimage_limit;2645if(preimage_limit < postimage->nr) {2646/*2647 * NOTE: this knows that we never call remove_first_line()2648 * on anything other than pre/post image.2649 */2650REALLOC_ARRAY(img->line, nr);2651 img->line_allocated = img->line;2652}2653if(preimage_limit != postimage->nr)2654memmove(img->line + applied_pos + postimage->nr,2655 img->line + applied_pos + preimage_limit,2656(img->nr - (applied_pos + preimage_limit)) *2657sizeof(*img->line));2658memcpy(img->line + applied_pos,2659 postimage->line,2660 postimage->nr *sizeof(*img->line));2661if(!allow_overlap)2662for(i =0; i < postimage->nr; i++)2663 img->line[applied_pos + i].flag |= LINE_PATCHED;2664 img->nr = nr;2665}26662667/*2668 * Use the patch-hunk text in "frag" to prepare two images (preimage and2669 * postimage) for the hunk. Find lines that match "preimage" in "img" and2670 * replace the part of "img" with "postimage" text.2671 */2672static intapply_one_fragment(struct image *img,struct fragment *frag,2673int inaccurate_eof,unsigned ws_rule,2674int nth_fragment)2675{2676int match_beginning, match_end;2677const char*patch = frag->patch;2678int size = frag->size;2679char*old, *oldlines;2680struct strbuf newlines;2681int new_blank_lines_at_end =0;2682int found_new_blank_lines_at_end =0;2683int hunk_linenr = frag->linenr;2684unsigned long leading, trailing;2685int pos, applied_pos;2686struct image preimage;2687struct image postimage;26882689memset(&preimage,0,sizeof(preimage));2690memset(&postimage,0,sizeof(postimage));2691 oldlines =xmalloc(size);2692strbuf_init(&newlines, size);26932694 old = oldlines;2695while(size >0) {2696char first;2697int len =linelen(patch, size);2698int plen;2699int added_blank_line =0;2700int is_blank_context =0;2701size_t start;27022703if(!len)2704break;27052706/*2707 * "plen" is how much of the line we should use for2708 * the actual patch data. Normally we just remove the2709 * first character on the line, but if the line is2710 * followed by "\ No newline", then we also remove the2711 * last one (which is the newline, of course).2712 */2713 plen = len -1;2714if(len < size && patch[len] =='\\')2715 plen--;2716 first = *patch;2717if(apply_in_reverse) {2718if(first =='-')2719 first ='+';2720else if(first =='+')2721 first ='-';2722}27232724switch(first) {2725case'\n':2726/* Newer GNU diff, empty context line */2727if(plen <0)2728/* ... followed by '\No newline'; nothing */2729break;2730*old++ ='\n';2731strbuf_addch(&newlines,'\n');2732add_line_info(&preimage,"\n",1, LINE_COMMON);2733add_line_info(&postimage,"\n",1, LINE_COMMON);2734 is_blank_context =1;2735break;2736case' ':2737if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2738ws_blank_line(patch +1, plen, ws_rule))2739 is_blank_context =1;2740case'-':2741memcpy(old, patch +1, plen);2742add_line_info(&preimage, old, plen,2743(first ==' '? LINE_COMMON :0));2744 old += plen;2745if(first =='-')2746break;2747/* Fall-through for ' ' */2748case'+':2749/* --no-add does not add new lines */2750if(first =='+'&& no_add)2751break;27522753 start = newlines.len;2754if(first !='+'||2755!whitespace_error ||2756 ws_error_action != correct_ws_error) {2757strbuf_add(&newlines, patch +1, plen);2758}2759else{2760ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2761}2762add_line_info(&postimage, newlines.buf + start, newlines.len - start,2763(first =='+'?0: LINE_COMMON));2764if(first =='+'&&2765(ws_rule & WS_BLANK_AT_EOF) &&2766ws_blank_line(patch +1, plen, ws_rule))2767 added_blank_line =1;2768break;2769case'@':case'\\':2770/* Ignore it, we already handled it */2771break;2772default:2773if(apply_verbosely)2774error(_("invalid start of line: '%c'"), first);2775 applied_pos = -1;2776goto out;2777}2778if(added_blank_line) {2779if(!new_blank_lines_at_end)2780 found_new_blank_lines_at_end = hunk_linenr;2781 new_blank_lines_at_end++;2782}2783else if(is_blank_context)2784;2785else2786 new_blank_lines_at_end =0;2787 patch += len;2788 size -= len;2789 hunk_linenr++;2790}2791if(inaccurate_eof &&2792 old > oldlines && old[-1] =='\n'&&2793 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2794 old--;2795strbuf_setlen(&newlines, newlines.len -1);2796}27972798 leading = frag->leading;2799 trailing = frag->trailing;28002801/*2802 * A hunk to change lines at the beginning would begin with2803 * @@ -1,L +N,M @@2804 * but we need to be careful. -U0 that inserts before the second2805 * line also has this pattern.2806 *2807 * And a hunk to add to an empty file would begin with2808 * @@ -0,0 +N,M @@2809 *2810 * In other words, a hunk that is (frag->oldpos <= 1) with or2811 * without leading context must match at the beginning.2812 */2813 match_beginning = (!frag->oldpos ||2814(frag->oldpos ==1&& !unidiff_zero));28152816/*2817 * A hunk without trailing lines must match at the end.2818 * However, we simply cannot tell if a hunk must match end2819 * from the lack of trailing lines if the patch was generated2820 * with unidiff without any context.2821 */2822 match_end = !unidiff_zero && !trailing;28232824 pos = frag->newpos ? (frag->newpos -1) :0;2825 preimage.buf = oldlines;2826 preimage.len = old - oldlines;2827 postimage.buf = newlines.buf;2828 postimage.len = newlines.len;2829 preimage.line = preimage.line_allocated;2830 postimage.line = postimage.line_allocated;28312832for(;;) {28332834 applied_pos =find_pos(img, &preimage, &postimage, pos,2835 ws_rule, match_beginning, match_end);28362837if(applied_pos >=0)2838break;28392840/* Am I at my context limits? */2841if((leading <= p_context) && (trailing <= p_context))2842break;2843if(match_beginning || match_end) {2844 match_beginning = match_end =0;2845continue;2846}28472848/*2849 * Reduce the number of context lines; reduce both2850 * leading and trailing if they are equal otherwise2851 * just reduce the larger context.2852 */2853if(leading >= trailing) {2854remove_first_line(&preimage);2855remove_first_line(&postimage);2856 pos--;2857 leading--;2858}2859if(trailing > leading) {2860remove_last_line(&preimage);2861remove_last_line(&postimage);2862 trailing--;2863}2864}28652866if(applied_pos >=0) {2867if(new_blank_lines_at_end &&2868 preimage.nr + applied_pos >= img->nr &&2869(ws_rule & WS_BLANK_AT_EOF) &&2870 ws_error_action != nowarn_ws_error) {2871record_ws_error(WS_BLANK_AT_EOF,"+",1,2872 found_new_blank_lines_at_end);2873if(ws_error_action == correct_ws_error) {2874while(new_blank_lines_at_end--)2875remove_last_line(&postimage);2876}2877/*2878 * We would want to prevent write_out_results()2879 * from taking place in apply_patch() that follows2880 * the callchain led us here, which is:2881 * apply_patch->check_patch_list->check_patch->2882 * apply_data->apply_fragments->apply_one_fragment2883 */2884if(ws_error_action == die_on_ws_error)2885 apply =0;2886}28872888if(apply_verbosely && applied_pos != pos) {2889int offset = applied_pos - pos;2890if(apply_in_reverse)2891 offset =0- offset;2892fprintf_ln(stderr,2893Q_("Hunk #%dsucceeded at%d(offset%dline).",2894"Hunk #%dsucceeded at%d(offset%dlines).",2895 offset),2896 nth_fragment, applied_pos +1, offset);2897}28982899/*2900 * Warn if it was necessary to reduce the number2901 * of context lines.2902 */2903if((leading != frag->leading) ||2904(trailing != frag->trailing))2905fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2906" to apply fragment at%d"),2907 leading, trailing, applied_pos+1);2908update_image(img, applied_pos, &preimage, &postimage);2909}else{2910if(apply_verbosely)2911error(_("while searching for:\n%.*s"),2912(int)(old - oldlines), oldlines);2913}29142915out:2916free(oldlines);2917strbuf_release(&newlines);2918free(preimage.line_allocated);2919free(postimage.line_allocated);29202921return(applied_pos <0);2922}29232924static intapply_binary_fragment(struct image *img,struct patch *patch)2925{2926struct fragment *fragment = patch->fragments;2927unsigned long len;2928void*dst;29292930if(!fragment)2931returnerror(_("missing binary patch data for '%s'"),2932 patch->new_name ?2933 patch->new_name :2934 patch->old_name);29352936/* Binary patch is irreversible without the optional second hunk */2937if(apply_in_reverse) {2938if(!fragment->next)2939returnerror("cannot reverse-apply a binary patch "2940"without the reverse hunk to '%s'",2941 patch->new_name2942? patch->new_name : patch->old_name);2943 fragment = fragment->next;2944}2945switch(fragment->binary_patch_method) {2946case BINARY_DELTA_DEFLATED:2947 dst =patch_delta(img->buf, img->len, fragment->patch,2948 fragment->size, &len);2949if(!dst)2950return-1;2951clear_image(img);2952 img->buf = dst;2953 img->len = len;2954return0;2955case BINARY_LITERAL_DEFLATED:2956clear_image(img);2957 img->len = fragment->size;2958 img->buf =xmemdupz(fragment->patch, img->len);2959return0;2960}2961return-1;2962}29632964/*2965 * Replace "img" with the result of applying the binary patch.2966 * The binary patch data itself in patch->fragment is still kept2967 * but the preimage prepared by the caller in "img" is freed here2968 * or in the helper function apply_binary_fragment() this calls.2969 */2970static intapply_binary(struct image *img,struct patch *patch)2971{2972const char*name = patch->old_name ? patch->old_name : patch->new_name;2973unsigned char sha1[20];29742975/*2976 * For safety, we require patch index line to contain2977 * full 40-byte textual SHA1 for old and new, at least for now.2978 */2979if(strlen(patch->old_sha1_prefix) !=40||2980strlen(patch->new_sha1_prefix) !=40||2981get_sha1_hex(patch->old_sha1_prefix, sha1) ||2982get_sha1_hex(patch->new_sha1_prefix, sha1))2983returnerror("cannot apply binary patch to '%s' "2984"without full index line", name);29852986if(patch->old_name) {2987/*2988 * See if the old one matches what the patch2989 * applies to.2990 */2991hash_sha1_file(img->buf, img->len, blob_type, sha1);2992if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2993returnerror("the patch applies to '%s' (%s), "2994"which does not match the "2995"current contents.",2996 name,sha1_to_hex(sha1));2997}2998else{2999/* Otherwise, the old one must be empty. */3000if(img->len)3001returnerror("the patch applies to an empty "3002"'%s' but it is not empty", name);3003}30043005get_sha1_hex(patch->new_sha1_prefix, sha1);3006if(is_null_sha1(sha1)) {3007clear_image(img);3008return0;/* deletion patch */3009}30103011if(has_sha1_file(sha1)) {3012/* We already have the postimage */3013enum object_type type;3014unsigned long size;3015char*result;30163017 result =read_sha1_file(sha1, &type, &size);3018if(!result)3019returnerror("the necessary postimage%sfor "3020"'%s' cannot be read",3021 patch->new_sha1_prefix, name);3022clear_image(img);3023 img->buf = result;3024 img->len = size;3025}else{3026/*3027 * We have verified buf matches the preimage;3028 * apply the patch data to it, which is stored3029 * in the patch->fragments->{patch,size}.3030 */3031if(apply_binary_fragment(img, patch))3032returnerror(_("binary patch does not apply to '%s'"),3033 name);30343035/* verify that the result matches */3036hash_sha1_file(img->buf, img->len, blob_type, sha1);3037if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3038returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3039 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3040}30413042return0;3043}30443045static intapply_fragments(struct image *img,struct patch *patch)3046{3047struct fragment *frag = patch->fragments;3048const char*name = patch->old_name ? patch->old_name : patch->new_name;3049unsigned ws_rule = patch->ws_rule;3050unsigned inaccurate_eof = patch->inaccurate_eof;3051int nth =0;30523053if(patch->is_binary)3054returnapply_binary(img, patch);30553056while(frag) {3057 nth++;3058if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {3059error(_("patch failed:%s:%ld"), name, frag->oldpos);3060if(!apply_with_reject)3061return-1;3062 frag->rejected =1;3063}3064 frag = frag->next;3065}3066return0;3067}30683069static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3070{3071if(S_ISGITLINK(mode)) {3072strbuf_grow(buf,100);3073strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3074}else{3075enum object_type type;3076unsigned long sz;3077char*result;30783079 result =read_sha1_file(sha1, &type, &sz);3080if(!result)3081return-1;3082/* XXX read_sha1_file NUL-terminates */3083strbuf_attach(buf, result, sz, sz +1);3084}3085return0;3086}30873088static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3089{3090if(!ce)3091return0;3092returnread_blob_object(buf, ce->sha1, ce->ce_mode);3093}30943095static struct patch *in_fn_table(const char*name)3096{3097struct string_list_item *item;30983099if(name == NULL)3100return NULL;31013102 item =string_list_lookup(&fn_table, name);3103if(item != NULL)3104return(struct patch *)item->util;31053106return NULL;3107}31083109/*3110 * item->util in the filename table records the status of the path.3111 * Usually it points at a patch (whose result records the contents3112 * of it after applying it), but it could be PATH_WAS_DELETED for a3113 * path that a previously applied patch has already removed, or3114 * PATH_TO_BE_DELETED for a path that a later patch would remove.3115 *3116 * The latter is needed to deal with a case where two paths A and B3117 * are swapped by first renaming A to B and then renaming B to A;3118 * moving A to B should not be prevented due to presence of B as we3119 * will remove it in a later patch.3120 */3121#define PATH_TO_BE_DELETED ((struct patch *) -2)3122#define PATH_WAS_DELETED ((struct patch *) -1)31233124static intto_be_deleted(struct patch *patch)3125{3126return patch == PATH_TO_BE_DELETED;3127}31283129static intwas_deleted(struct patch *patch)3130{3131return patch == PATH_WAS_DELETED;3132}31333134static voidadd_to_fn_table(struct patch *patch)3135{3136struct string_list_item *item;31373138/*3139 * Always add new_name unless patch is a deletion3140 * This should cover the cases for normal diffs,3141 * file creations and copies3142 */3143if(patch->new_name != NULL) {3144 item =string_list_insert(&fn_table, patch->new_name);3145 item->util = patch;3146}31473148/*3149 * store a failure on rename/deletion cases because3150 * later chunks shouldn't patch old names3151 */3152if((patch->new_name == NULL) || (patch->is_rename)) {3153 item =string_list_insert(&fn_table, patch->old_name);3154 item->util = PATH_WAS_DELETED;3155}3156}31573158static voidprepare_fn_table(struct patch *patch)3159{3160/*3161 * store information about incoming file deletion3162 */3163while(patch) {3164if((patch->new_name == NULL) || (patch->is_rename)) {3165struct string_list_item *item;3166 item =string_list_insert(&fn_table, patch->old_name);3167 item->util = PATH_TO_BE_DELETED;3168}3169 patch = patch->next;3170}3171}31723173static intcheckout_target(struct index_state *istate,3174struct cache_entry *ce,struct stat *st)3175{3176struct checkout costate;31773178memset(&costate,0,sizeof(costate));3179 costate.base_dir ="";3180 costate.refresh_cache =1;3181 costate.istate = istate;3182if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3183returnerror(_("cannot checkout%s"), ce->name);3184return0;3185}31863187static struct patch *previous_patch(struct patch *patch,int*gone)3188{3189struct patch *previous;31903191*gone =0;3192if(patch->is_copy || patch->is_rename)3193return NULL;/* "git" patches do not depend on the order */31943195 previous =in_fn_table(patch->old_name);3196if(!previous)3197return NULL;31983199if(to_be_deleted(previous))3200return NULL;/* the deletion hasn't happened yet */32013202if(was_deleted(previous))3203*gone =1;32043205return previous;3206}32073208static intverify_index_match(const struct cache_entry *ce,struct stat *st)3209{3210if(S_ISGITLINK(ce->ce_mode)) {3211if(!S_ISDIR(st->st_mode))3212return-1;3213return0;3214}3215returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3216}32173218#define SUBMODULE_PATCH_WITHOUT_INDEX 132193220static intload_patch_target(struct strbuf *buf,3221const struct cache_entry *ce,3222struct stat *st,3223const char*name,3224unsigned expected_mode)3225{3226if(cached || check_index) {3227if(read_file_or_gitlink(ce, buf))3228returnerror(_("read of%sfailed"), name);3229}else if(name) {3230if(S_ISGITLINK(expected_mode)) {3231if(ce)3232returnread_file_or_gitlink(ce, buf);3233else3234return SUBMODULE_PATCH_WITHOUT_INDEX;3235}else if(has_symlink_leading_path(name,strlen(name))) {3236returnerror(_("reading from '%s' beyond a symbolic link"), name);3237}else{3238if(read_old_data(st, name, buf))3239returnerror(_("read of%sfailed"), name);3240}3241}3242return0;3243}32443245/*3246 * We are about to apply "patch"; populate the "image" with the3247 * current version we have, from the working tree or from the index,3248 * depending on the situation e.g. --cached/--index. If we are3249 * applying a non-git patch that incrementally updates the tree,3250 * we read from the result of a previous diff.3251 */3252static intload_preimage(struct image *image,3253struct patch *patch,struct stat *st,3254const struct cache_entry *ce)3255{3256struct strbuf buf = STRBUF_INIT;3257size_t len;3258char*img;3259struct patch *previous;3260int status;32613262 previous =previous_patch(patch, &status);3263if(status)3264returnerror(_("path%shas been renamed/deleted"),3265 patch->old_name);3266if(previous) {3267/* We have a patched copy in memory; use that. */3268strbuf_add(&buf, previous->result, previous->resultsize);3269}else{3270 status =load_patch_target(&buf, ce, st,3271 patch->old_name, patch->old_mode);3272if(status <0)3273return status;3274else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3275/*3276 * There is no way to apply subproject3277 * patch without looking at the index.3278 * NEEDSWORK: shouldn't this be flagged3279 * as an error???3280 */3281free_fragment_list(patch->fragments);3282 patch->fragments = NULL;3283}else if(status) {3284returnerror(_("read of%sfailed"), patch->old_name);3285}3286}32873288 img =strbuf_detach(&buf, &len);3289prepare_image(image, img, len, !patch->is_binary);3290return0;3291}32923293static intthree_way_merge(struct image *image,3294char*path,3295const unsigned char*base,3296const unsigned char*ours,3297const unsigned char*theirs)3298{3299 mmfile_t base_file, our_file, their_file;3300 mmbuffer_t result = { NULL };3301int status;33023303read_mmblob(&base_file, base);3304read_mmblob(&our_file, ours);3305read_mmblob(&their_file, theirs);3306 status =ll_merge(&result, path,3307&base_file,"base",3308&our_file,"ours",3309&their_file,"theirs", NULL);3310free(base_file.ptr);3311free(our_file.ptr);3312free(their_file.ptr);3313if(status <0|| !result.ptr) {3314free(result.ptr);3315return-1;3316}3317clear_image(image);3318 image->buf = result.ptr;3319 image->len = result.size;33203321return status;3322}33233324/*3325 * When directly falling back to add/add three-way merge, we read from3326 * the current contents of the new_name. In no cases other than that3327 * this function will be called.3328 */3329static intload_current(struct image *image,struct patch *patch)3330{3331struct strbuf buf = STRBUF_INIT;3332int status, pos;3333size_t len;3334char*img;3335struct stat st;3336struct cache_entry *ce;3337char*name = patch->new_name;3338unsigned mode = patch->new_mode;33393340if(!patch->is_new)3341die("BUG: patch to%sis not a creation", patch->old_name);33423343 pos =cache_name_pos(name,strlen(name));3344if(pos <0)3345returnerror(_("%s: does not exist in index"), name);3346 ce = active_cache[pos];3347if(lstat(name, &st)) {3348if(errno != ENOENT)3349returnerror(_("%s:%s"), name,strerror(errno));3350if(checkout_target(&the_index, ce, &st))3351return-1;3352}3353if(verify_index_match(ce, &st))3354returnerror(_("%s: does not match index"), name);33553356 status =load_patch_target(&buf, ce, &st, name, mode);3357if(status <0)3358return status;3359else if(status)3360return-1;3361 img =strbuf_detach(&buf, &len);3362prepare_image(image, img, len, !patch->is_binary);3363return0;3364}33653366static inttry_threeway(struct image *image,struct patch *patch,3367struct stat *st,const struct cache_entry *ce)3368{3369unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3370struct strbuf buf = STRBUF_INIT;3371size_t len;3372int status;3373char*img;3374struct image tmp_image;33753376/* No point falling back to 3-way merge in these cases */3377if(patch->is_delete ||3378S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3379return-1;33803381/* Preimage the patch was prepared for */3382if(patch->is_new)3383write_sha1_file("",0, blob_type, pre_sha1);3384else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3385read_blob_object(&buf, pre_sha1, patch->old_mode))3386returnerror("repository lacks the necessary blob to fall back on 3-way merge.");33873388fprintf(stderr,"Falling back to three-way merge...\n");33893390 img =strbuf_detach(&buf, &len);3391prepare_image(&tmp_image, img, len,1);3392/* Apply the patch to get the post image */3393if(apply_fragments(&tmp_image, patch) <0) {3394clear_image(&tmp_image);3395return-1;3396}3397/* post_sha1[] is theirs */3398write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3399clear_image(&tmp_image);34003401/* our_sha1[] is ours */3402if(patch->is_new) {3403if(load_current(&tmp_image, patch))3404returnerror("cannot read the current contents of '%s'",3405 patch->new_name);3406}else{3407if(load_preimage(&tmp_image, patch, st, ce))3408returnerror("cannot read the current contents of '%s'",3409 patch->old_name);3410}3411write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3412clear_image(&tmp_image);34133414/* in-core three-way merge between post and our using pre as base */3415 status =three_way_merge(image, patch->new_name,3416 pre_sha1, our_sha1, post_sha1);3417if(status <0) {3418fprintf(stderr,"Failed to fall back on three-way merge...\n");3419return status;3420}34213422if(status) {3423 patch->conflicted_threeway =1;3424if(patch->is_new)3425oidclr(&patch->threeway_stage[0]);3426else3427hashcpy(patch->threeway_stage[0].hash, pre_sha1);3428hashcpy(patch->threeway_stage[1].hash, our_sha1);3429hashcpy(patch->threeway_stage[2].hash, post_sha1);3430fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3431}else{3432fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3433}3434return0;3435}34363437static intapply_data(struct patch *patch,struct stat *st,const struct cache_entry *ce)3438{3439struct image image;34403441if(load_preimage(&image, patch, st, ce) <0)3442return-1;34433444if(patch->direct_to_threeway ||3445apply_fragments(&image, patch) <0) {3446/* Note: with --reject, apply_fragments() returns 0 */3447if(!threeway ||try_threeway(&image, patch, st, ce) <0)3448return-1;3449}3450 patch->result = image.buf;3451 patch->resultsize = image.len;3452add_to_fn_table(patch);3453free(image.line_allocated);34543455if(0< patch->is_delete && patch->resultsize)3456returnerror(_("removal patch leaves file contents"));34573458return0;3459}34603461/*3462 * If "patch" that we are looking at modifies or deletes what we have,3463 * we would want it not to lose any local modification we have, either3464 * in the working tree or in the index.3465 *3466 * This also decides if a non-git patch is a creation patch or a3467 * modification to an existing empty file. We do not check the state3468 * of the current tree for a creation patch in this function; the caller3469 * check_patch() separately makes sure (and errors out otherwise) that3470 * the path the patch creates does not exist in the current tree.3471 */3472static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)3473{3474const char*old_name = patch->old_name;3475struct patch *previous = NULL;3476int stat_ret =0, status;3477unsigned st_mode =0;34783479if(!old_name)3480return0;34813482assert(patch->is_new <=0);3483 previous =previous_patch(patch, &status);34843485if(status)3486returnerror(_("path%shas been renamed/deleted"), old_name);3487if(previous) {3488 st_mode = previous->new_mode;3489}else if(!cached) {3490 stat_ret =lstat(old_name, st);3491if(stat_ret && errno != ENOENT)3492returnerror(_("%s:%s"), old_name,strerror(errno));3493}34943495if(check_index && !previous) {3496int pos =cache_name_pos(old_name,strlen(old_name));3497if(pos <0) {3498if(patch->is_new <0)3499goto is_new;3500returnerror(_("%s: does not exist in index"), old_name);3501}3502*ce = active_cache[pos];3503if(stat_ret <0) {3504if(checkout_target(&the_index, *ce, st))3505return-1;3506}3507if(!cached &&verify_index_match(*ce, st))3508returnerror(_("%s: does not match index"), old_name);3509if(cached)3510 st_mode = (*ce)->ce_mode;3511}else if(stat_ret <0) {3512if(patch->is_new <0)3513goto is_new;3514returnerror(_("%s:%s"), old_name,strerror(errno));3515}35163517if(!cached && !previous)3518 st_mode =ce_mode_from_stat(*ce, st->st_mode);35193520if(patch->is_new <0)3521 patch->is_new =0;3522if(!patch->old_mode)3523 patch->old_mode = st_mode;3524if((st_mode ^ patch->old_mode) & S_IFMT)3525returnerror(_("%s: wrong type"), old_name);3526if(st_mode != patch->old_mode)3527warning(_("%shas type%o, expected%o"),3528 old_name, st_mode, patch->old_mode);3529if(!patch->new_mode && !patch->is_delete)3530 patch->new_mode = st_mode;3531return0;35323533 is_new:3534 patch->is_new =1;3535 patch->is_delete =0;3536free(patch->old_name);3537 patch->old_name = NULL;3538return0;3539}354035413542#define EXISTS_IN_INDEX 13543#define EXISTS_IN_WORKTREE 235443545static intcheck_to_create(const char*new_name,int ok_if_exists)3546{3547struct stat nst;35483549if(check_index &&3550cache_name_pos(new_name,strlen(new_name)) >=0&&3551!ok_if_exists)3552return EXISTS_IN_INDEX;3553if(cached)3554return0;35553556if(!lstat(new_name, &nst)) {3557if(S_ISDIR(nst.st_mode) || ok_if_exists)3558return0;3559/*3560 * A leading component of new_name might be a symlink3561 * that is going to be removed with this patch, but3562 * still pointing at somewhere that has the path.3563 * In such a case, path "new_name" does not exist as3564 * far as git is concerned.3565 */3566if(has_symlink_leading_path(new_name,strlen(new_name)))3567return0;35683569return EXISTS_IN_WORKTREE;3570}else if((errno != ENOENT) && (errno != ENOTDIR)) {3571returnerror("%s:%s", new_name,strerror(errno));3572}3573return0;3574}35753576/*3577 * We need to keep track of how symlinks in the preimage are3578 * manipulated by the patches. A patch to add a/b/c where a/b3579 * is a symlink should not be allowed to affect the directory3580 * the symlink points at, but if the same patch removes a/b,3581 * it is perfectly fine, as the patch removes a/b to make room3582 * to create a directory a/b so that a/b/c can be created.3583 */3584static struct string_list symlink_changes;3585#define SYMLINK_GOES_AWAY 013586#define SYMLINK_IN_RESULT 0235873588static uintptr_tregister_symlink_changes(const char*path,uintptr_t what)3589{3590struct string_list_item *ent;35913592 ent =string_list_lookup(&symlink_changes, path);3593if(!ent) {3594 ent =string_list_insert(&symlink_changes, path);3595 ent->util = (void*)0;3596}3597 ent->util = (void*)(what | ((uintptr_t)ent->util));3598return(uintptr_t)ent->util;3599}36003601static uintptr_tcheck_symlink_changes(const char*path)3602{3603struct string_list_item *ent;36043605 ent =string_list_lookup(&symlink_changes, path);3606if(!ent)3607return0;3608return(uintptr_t)ent->util;3609}36103611static voidprepare_symlink_changes(struct patch *patch)3612{3613for( ; patch; patch = patch->next) {3614if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3615(patch->is_rename || patch->is_delete))3616/* the symlink at patch->old_name is removed */3617register_symlink_changes(patch->old_name, SYMLINK_GOES_AWAY);36183619if(patch->new_name &&S_ISLNK(patch->new_mode))3620/* the symlink at patch->new_name is created or remains */3621register_symlink_changes(patch->new_name, SYMLINK_IN_RESULT);3622}3623}36243625static intpath_is_beyond_symlink_1(struct strbuf *name)3626{3627do{3628unsigned int change;36293630while(--name->len && name->buf[name->len] !='/')3631;/* scan backwards */3632if(!name->len)3633break;3634 name->buf[name->len] ='\0';3635 change =check_symlink_changes(name->buf);3636if(change & SYMLINK_IN_RESULT)3637return1;3638if(change & SYMLINK_GOES_AWAY)3639/*3640 * This cannot be "return 0", because we may3641 * see a new one created at a higher level.3642 */3643continue;36443645/* otherwise, check the preimage */3646if(check_index) {3647struct cache_entry *ce;36483649 ce =cache_file_exists(name->buf, name->len, ignore_case);3650if(ce &&S_ISLNK(ce->ce_mode))3651return1;3652}else{3653struct stat st;3654if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3655return1;3656}3657}while(1);3658return0;3659}36603661static intpath_is_beyond_symlink(const char*name_)3662{3663int ret;3664struct strbuf name = STRBUF_INIT;36653666assert(*name_ !='\0');3667strbuf_addstr(&name, name_);3668 ret =path_is_beyond_symlink_1(&name);3669strbuf_release(&name);36703671return ret;3672}36733674static voiddie_on_unsafe_path(struct patch *patch)3675{3676const char*old_name = NULL;3677const char*new_name = NULL;3678if(patch->is_delete)3679 old_name = patch->old_name;3680else if(!patch->is_new && !patch->is_copy)3681 old_name = patch->old_name;3682if(!patch->is_delete)3683 new_name = patch->new_name;36843685if(old_name && !verify_path(old_name))3686die(_("invalid path '%s'"), old_name);3687if(new_name && !verify_path(new_name))3688die(_("invalid path '%s'"), new_name);3689}36903691/*3692 * Check and apply the patch in-core; leave the result in patch->result3693 * for the caller to write it out to the final destination.3694 */3695static intcheck_patch(struct patch *patch)3696{3697struct stat st;3698const char*old_name = patch->old_name;3699const char*new_name = patch->new_name;3700const char*name = old_name ? old_name : new_name;3701struct cache_entry *ce = NULL;3702struct patch *tpatch;3703int ok_if_exists;3704int status;37053706 patch->rejected =1;/* we will drop this after we succeed */37073708 status =check_preimage(patch, &ce, &st);3709if(status)3710return status;3711 old_name = patch->old_name;37123713/*3714 * A type-change diff is always split into a patch to delete3715 * old, immediately followed by a patch to create new (see3716 * diff.c::run_diff()); in such a case it is Ok that the entry3717 * to be deleted by the previous patch is still in the working3718 * tree and in the index.3719 *3720 * A patch to swap-rename between A and B would first rename A3721 * to B and then rename B to A. While applying the first one,3722 * the presence of B should not stop A from getting renamed to3723 * B; ask to_be_deleted() about the later rename. Removal of3724 * B and rename from A to B is handled the same way by asking3725 * was_deleted().3726 */3727if((tpatch =in_fn_table(new_name)) &&3728(was_deleted(tpatch) ||to_be_deleted(tpatch)))3729 ok_if_exists =1;3730else3731 ok_if_exists =0;37323733if(new_name &&3734((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3735int err =check_to_create(new_name, ok_if_exists);37363737if(err && threeway) {3738 patch->direct_to_threeway =1;3739}else switch(err) {3740case0:3741break;/* happy */3742case EXISTS_IN_INDEX:3743returnerror(_("%s: already exists in index"), new_name);3744break;3745case EXISTS_IN_WORKTREE:3746returnerror(_("%s: already exists in working directory"),3747 new_name);3748default:3749return err;3750}37513752if(!patch->new_mode) {3753if(0< patch->is_new)3754 patch->new_mode = S_IFREG |0644;3755else3756 patch->new_mode = patch->old_mode;3757}3758}37593760if(new_name && old_name) {3761int same = !strcmp(old_name, new_name);3762if(!patch->new_mode)3763 patch->new_mode = patch->old_mode;3764if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3765if(same)3766returnerror(_("new mode (%o) of%sdoes not "3767"match old mode (%o)"),3768 patch->new_mode, new_name,3769 patch->old_mode);3770else3771returnerror(_("new mode (%o) of%sdoes not "3772"match old mode (%o) of%s"),3773 patch->new_mode, new_name,3774 patch->old_mode, old_name);3775}3776}37773778if(!unsafe_paths)3779die_on_unsafe_path(patch);37803781/*3782 * An attempt to read from or delete a path that is beyond a3783 * symbolic link will be prevented by load_patch_target() that3784 * is called at the beginning of apply_data() so we do not3785 * have to worry about a patch marked with "is_delete" bit3786 * here. We however need to make sure that the patch result3787 * is not deposited to a path that is beyond a symbolic link3788 * here.3789 */3790if(!patch->is_delete &&path_is_beyond_symlink(patch->new_name))3791returnerror(_("affected file '%s' is beyond a symbolic link"),3792 patch->new_name);37933794if(apply_data(patch, &st, ce) <0)3795returnerror(_("%s: patch does not apply"), name);3796 patch->rejected =0;3797return0;3798}37993800static intcheck_patch_list(struct patch *patch)3801{3802int err =0;38033804prepare_symlink_changes(patch);3805prepare_fn_table(patch);3806while(patch) {3807if(apply_verbosely)3808say_patch_name(stderr,3809_("Checking patch%s..."), patch);3810 err |=check_patch(patch);3811 patch = patch->next;3812}3813return err;3814}38153816/* This function tries to read the sha1 from the current index */3817static intget_current_sha1(const char*path,unsigned char*sha1)3818{3819int pos;38203821if(read_cache() <0)3822return-1;3823 pos =cache_name_pos(path,strlen(path));3824if(pos <0)3825return-1;3826hashcpy(sha1, active_cache[pos]->sha1);3827return0;3828}38293830static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3831{3832/*3833 * A usable gitlink patch has only one fragment (hunk) that looks like:3834 * @@ -1 +1 @@3835 * -Subproject commit <old sha1>3836 * +Subproject commit <new sha1>3837 * or3838 * @@ -1 +0,0 @@3839 * -Subproject commit <old sha1>3840 * for a removal patch.3841 */3842struct fragment *hunk = p->fragments;3843static const char heading[] ="-Subproject commit ";3844char*preimage;38453846if(/* does the patch have only one hunk? */3847 hunk && !hunk->next &&3848/* is its preimage one line? */3849 hunk->oldpos ==1&& hunk->oldlines ==1&&3850/* does preimage begin with the heading? */3851(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3852starts_with(++preimage, heading) &&3853/* does it record full SHA-1? */3854!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3855 preimage[sizeof(heading) +40-1] =='\n'&&3856/* does the abbreviated name on the index line agree with it? */3857starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3858return0;/* it all looks fine */38593860/* we may have full object name on the index line */3861returnget_sha1_hex(p->old_sha1_prefix, sha1);3862}38633864/* Build an index that contains the just the files needed for a 3way merge */3865static voidbuild_fake_ancestor(struct patch *list,const char*filename)3866{3867struct patch *patch;3868struct index_state result = { NULL };3869static struct lock_file lock;38703871/* Once we start supporting the reverse patch, it may be3872 * worth showing the new sha1 prefix, but until then...3873 */3874for(patch = list; patch; patch = patch->next) {3875unsigned char sha1[20];3876struct cache_entry *ce;3877const char*name;38783879 name = patch->old_name ? patch->old_name : patch->new_name;3880if(0< patch->is_new)3881continue;38823883if(S_ISGITLINK(patch->old_mode)) {3884if(!preimage_sha1_in_gitlink_patch(patch, sha1))3885;/* ok, the textual part looks sane */3886else3887die("sha1 information is lacking or useless for submodule%s",3888 name);3889}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {3890;/* ok */3891}else if(!patch->lines_added && !patch->lines_deleted) {3892/* mode-only change: update the current */3893if(get_current_sha1(patch->old_name, sha1))3894die("mode change for%s, which is not "3895"in current HEAD", name);3896}else3897die("sha1 information is lacking or useless "3898"(%s).", name);38993900 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);3901if(!ce)3902die(_("make_cache_entry failed for path '%s'"), name);3903if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3904die("Could not add%sto temporary index", name);3905}39063907hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);3908if(write_locked_index(&result, &lock, COMMIT_LOCK))3909die("Could not write temporary index to%s", filename);39103911discard_index(&result);3912}39133914static voidstat_patch_list(struct patch *patch)3915{3916int files, adds, dels;39173918for(files = adds = dels =0; patch ; patch = patch->next) {3919 files++;3920 adds += patch->lines_added;3921 dels += patch->lines_deleted;3922show_stats(patch);3923}39243925print_stat_summary(stdout, files, adds, dels);3926}39273928static voidnumstat_patch_list(struct patch *patch)3929{3930for( ; patch; patch = patch->next) {3931const char*name;3932 name = patch->new_name ? patch->new_name : patch->old_name;3933if(patch->is_binary)3934printf("-\t-\t");3935else3936printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3937write_name_quoted(name, stdout, line_termination);3938}3939}39403941static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3942{3943if(mode)3944printf("%smode%06o%s\n", newdelete, mode, name);3945else3946printf("%s %s\n", newdelete, name);3947}39483949static voidshow_mode_change(struct patch *p,int show_name)3950{3951if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3952if(show_name)3953printf(" mode change%06o =>%06o%s\n",3954 p->old_mode, p->new_mode, p->new_name);3955else3956printf(" mode change%06o =>%06o\n",3957 p->old_mode, p->new_mode);3958}3959}39603961static voidshow_rename_copy(struct patch *p)3962{3963const char*renamecopy = p->is_rename ?"rename":"copy";3964const char*old, *new;39653966/* Find common prefix */3967 old = p->old_name;3968new= p->new_name;3969while(1) {3970const char*slash_old, *slash_new;3971 slash_old =strchr(old,'/');3972 slash_new =strchr(new,'/');3973if(!slash_old ||3974!slash_new ||3975 slash_old - old != slash_new -new||3976memcmp(old,new, slash_new -new))3977break;3978 old = slash_old +1;3979new= slash_new +1;3980}3981/* p->old_name thru old is the common prefix, and old and new3982 * through the end of names are renames3983 */3984if(old != p->old_name)3985printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,3986(int)(old - p->old_name), p->old_name,3987 old,new, p->score);3988else3989printf("%s %s=>%s(%d%%)\n", renamecopy,3990 p->old_name, p->new_name, p->score);3991show_mode_change(p,0);3992}39933994static voidsummary_patch_list(struct patch *patch)3995{3996struct patch *p;39973998for(p = patch; p; p = p->next) {3999if(p->is_new)4000show_file_mode_name("create", p->new_mode, p->new_name);4001else if(p->is_delete)4002show_file_mode_name("delete", p->old_mode, p->old_name);4003else{4004if(p->is_rename || p->is_copy)4005show_rename_copy(p);4006else{4007if(p->score) {4008printf(" rewrite%s(%d%%)\n",4009 p->new_name, p->score);4010show_mode_change(p,0);4011}4012else4013show_mode_change(p,1);4014}4015}4016}4017}40184019static voidpatch_stats(struct patch *patch)4020{4021int lines = patch->lines_added + patch->lines_deleted;40224023if(lines > max_change)4024 max_change = lines;4025if(patch->old_name) {4026int len =quote_c_style(patch->old_name, NULL, NULL,0);4027if(!len)4028 len =strlen(patch->old_name);4029if(len > max_len)4030 max_len = len;4031}4032if(patch->new_name) {4033int len =quote_c_style(patch->new_name, NULL, NULL,0);4034if(!len)4035 len =strlen(patch->new_name);4036if(len > max_len)4037 max_len = len;4038}4039}40404041static voidremove_file(struct patch *patch,int rmdir_empty)4042{4043if(update_index) {4044if(remove_file_from_cache(patch->old_name) <0)4045die(_("unable to remove%sfrom index"), patch->old_name);4046}4047if(!cached) {4048if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4049remove_path(patch->old_name);4050}4051}4052}40534054static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)4055{4056struct stat st;4057struct cache_entry *ce;4058int namelen =strlen(path);4059unsigned ce_size =cache_entry_size(namelen);40604061if(!update_index)4062return;40634064 ce =xcalloc(1, ce_size);4065memcpy(ce->name, path, namelen);4066 ce->ce_mode =create_ce_mode(mode);4067 ce->ce_flags =create_ce_flags(0);4068 ce->ce_namelen = namelen;4069if(S_ISGITLINK(mode)) {4070const char*s;40714072if(!skip_prefix(buf,"Subproject commit ", &s) ||4073get_sha1_hex(s, ce->sha1))4074die(_("corrupt patch for submodule%s"), path);4075}else{4076if(!cached) {4077if(lstat(path, &st) <0)4078die_errno(_("unable to stat newly created file '%s'"),4079 path);4080fill_stat_cache_info(ce, &st);4081}4082if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4083die(_("unable to create backing store for newly created file%s"), path);4084}4085if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4086die(_("unable to add cache entry for%s"), path);4087}40884089static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4090{4091int fd;4092struct strbuf nbuf = STRBUF_INIT;40934094if(S_ISGITLINK(mode)) {4095struct stat st;4096if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4097return0;4098returnmkdir(path,0777);4099}41004101if(has_symlinks &&S_ISLNK(mode))4102/* Although buf:size is counted string, it also is NUL4103 * terminated.4104 */4105returnsymlink(buf, path);41064107 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4108if(fd <0)4109return-1;41104111if(convert_to_working_tree(path, buf, size, &nbuf)) {4112 size = nbuf.len;4113 buf = nbuf.buf;4114}4115write_or_die(fd, buf, size);4116strbuf_release(&nbuf);41174118if(close(fd) <0)4119die_errno(_("closing file '%s'"), path);4120return0;4121}41224123/*4124 * We optimistically assume that the directories exist,4125 * which is true 99% of the time anyway. If they don't,4126 * we create them and try again.4127 */4128static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)4129{4130if(cached)4131return;4132if(!try_create_file(path, mode, buf, size))4133return;41344135if(errno == ENOENT) {4136if(safe_create_leading_directories(path))4137return;4138if(!try_create_file(path, mode, buf, size))4139return;4140}41414142if(errno == EEXIST || errno == EACCES) {4143/* We may be trying to create a file where a directory4144 * used to be.4145 */4146struct stat st;4147if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4148 errno = EEXIST;4149}41504151if(errno == EEXIST) {4152unsigned int nr =getpid();41534154for(;;) {4155char newpath[PATH_MAX];4156mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4157if(!try_create_file(newpath, mode, buf, size)) {4158if(!rename(newpath, path))4159return;4160unlink_or_warn(newpath);4161break;4162}4163if(errno != EEXIST)4164break;4165++nr;4166}4167}4168die_errno(_("unable to write file '%s' mode%o"), path, mode);4169}41704171static voidadd_conflicted_stages_file(struct patch *patch)4172{4173int stage, namelen;4174unsigned ce_size, mode;4175struct cache_entry *ce;41764177if(!update_index)4178return;4179 namelen =strlen(patch->new_name);4180 ce_size =cache_entry_size(namelen);4181 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);41824183remove_file_from_cache(patch->new_name);4184for(stage =1; stage <4; stage++) {4185if(is_null_oid(&patch->threeway_stage[stage -1]))4186continue;4187 ce =xcalloc(1, ce_size);4188memcpy(ce->name, patch->new_name, namelen);4189 ce->ce_mode =create_ce_mode(mode);4190 ce->ce_flags =create_ce_flags(stage);4191 ce->ce_namelen = namelen;4192hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4193if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4194die(_("unable to add cache entry for%s"), patch->new_name);4195}4196}41974198static voidcreate_file(struct patch *patch)4199{4200char*path = patch->new_name;4201unsigned mode = patch->new_mode;4202unsigned long size = patch->resultsize;4203char*buf = patch->result;42044205if(!mode)4206 mode = S_IFREG |0644;4207create_one_file(path, mode, buf, size);42084209if(patch->conflicted_threeway)4210add_conflicted_stages_file(patch);4211else4212add_index_file(path, mode, buf, size);4213}42144215/* phase zero is to remove, phase one is to create */4216static voidwrite_out_one_result(struct patch *patch,int phase)4217{4218if(patch->is_delete >0) {4219if(phase ==0)4220remove_file(patch,1);4221return;4222}4223if(patch->is_new >0|| patch->is_copy) {4224if(phase ==1)4225create_file(patch);4226return;4227}4228/*4229 * Rename or modification boils down to the same4230 * thing: remove the old, write the new4231 */4232if(phase ==0)4233remove_file(patch, patch->is_rename);4234if(phase ==1)4235create_file(patch);4236}42374238static intwrite_out_one_reject(struct patch *patch)4239{4240FILE*rej;4241char namebuf[PATH_MAX];4242struct fragment *frag;4243int cnt =0;4244struct strbuf sb = STRBUF_INIT;42454246for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4247if(!frag->rejected)4248continue;4249 cnt++;4250}42514252if(!cnt) {4253if(apply_verbosely)4254say_patch_name(stderr,4255_("Applied patch%scleanly."), patch);4256return0;4257}42584259/* This should not happen, because a removal patch that leaves4260 * contents are marked "rejected" at the patch level.4261 */4262if(!patch->new_name)4263die(_("internal error"));42644265/* Say this even without --verbose */4266strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4267"Applying patch %%swith%drejects...",4268 cnt),4269 cnt);4270say_patch_name(stderr, sb.buf, patch);4271strbuf_release(&sb);42724273 cnt =strlen(patch->new_name);4274if(ARRAY_SIZE(namebuf) <= cnt +5) {4275 cnt =ARRAY_SIZE(namebuf) -5;4276warning(_("truncating .rej filename to %.*s.rej"),4277 cnt -1, patch->new_name);4278}4279memcpy(namebuf, patch->new_name, cnt);4280memcpy(namebuf + cnt,".rej",5);42814282 rej =fopen(namebuf,"w");4283if(!rej)4284returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));42854286/* Normal git tools never deal with .rej, so do not pretend4287 * this is a git patch by saying --git or giving extended4288 * headers. While at it, maybe please "kompare" that wants4289 * the trailing TAB and some garbage at the end of line ;-).4290 */4291fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4292 patch->new_name, patch->new_name);4293for(cnt =1, frag = patch->fragments;4294 frag;4295 cnt++, frag = frag->next) {4296if(!frag->rejected) {4297fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4298continue;4299}4300fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4301fprintf(rej,"%.*s", frag->size, frag->patch);4302if(frag->patch[frag->size-1] !='\n')4303fputc('\n', rej);4304}4305fclose(rej);4306return-1;4307}43084309static intwrite_out_results(struct patch *list)4310{4311int phase;4312int errs =0;4313struct patch *l;4314struct string_list cpath = STRING_LIST_INIT_DUP;43154316for(phase =0; phase <2; phase++) {4317 l = list;4318while(l) {4319if(l->rejected)4320 errs =1;4321else{4322write_out_one_result(l, phase);4323if(phase ==1) {4324if(write_out_one_reject(l))4325 errs =1;4326if(l->conflicted_threeway) {4327string_list_append(&cpath, l->new_name);4328 errs =1;4329}4330}4331}4332 l = l->next;4333}4334}43354336if(cpath.nr) {4337struct string_list_item *item;43384339string_list_sort(&cpath);4340for_each_string_list_item(item, &cpath)4341fprintf(stderr,"U%s\n", item->string);4342string_list_clear(&cpath,0);43434344rerere(0);4345}43464347return errs;4348}43494350static struct lock_file lock_file;43514352#define INACCURATE_EOF (1<<0)4353#define RECOUNT (1<<1)43544355static intapply_patch(int fd,const char*filename,int options)4356{4357size_t offset;4358struct strbuf buf = STRBUF_INIT;/* owns the patch text */4359struct patch *list = NULL, **listp = &list;4360int skipped_patch =0;43614362 patch_input_file = filename;4363read_patch_file(&buf, fd);4364 offset =0;4365while(offset < buf.len) {4366struct patch *patch;4367int nr;43684369 patch =xcalloc(1,sizeof(*patch));4370 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4371 patch->recount = !!(options & RECOUNT);4372 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);4373if(nr <0)4374break;4375if(apply_in_reverse)4376reverse_patches(patch);4377if(use_patch(patch)) {4378patch_stats(patch);4379*listp = patch;4380 listp = &patch->next;4381}4382else{4383free_patch(patch);4384 skipped_patch++;4385}4386 offset += nr;4387}43884389if(!list && !skipped_patch)4390die(_("unrecognized input"));43914392if(whitespace_error && (ws_error_action == die_on_ws_error))4393 apply =0;43944395 update_index = check_index && apply;4396if(update_index && newfd <0)4397 newfd =hold_locked_index(&lock_file,1);43984399if(check_index) {4400if(read_cache() <0)4401die(_("unable to read index file"));4402}44034404if((check || apply) &&4405check_patch_list(list) <0&&4406!apply_with_reject)4407exit(1);44084409if(apply &&write_out_results(list)) {4410if(apply_with_reject)4411exit(1);4412/* with --3way, we still need to write the index out */4413return1;4414}44154416if(fake_ancestor)4417build_fake_ancestor(list, fake_ancestor);44184419if(diffstat)4420stat_patch_list(list);44214422if(numstat)4423numstat_patch_list(list);44244425if(summary)4426summary_patch_list(list);44274428free_patch_list(list);4429strbuf_release(&buf);4430string_list_clear(&fn_table,0);4431return0;4432}44334434static voidgit_apply_config(void)4435{4436git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4437git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4438git_config(git_default_config, NULL);4439}44404441static intoption_parse_exclude(const struct option *opt,4442const char*arg,int unset)4443{4444add_name_limit(arg,1);4445return0;4446}44474448static intoption_parse_include(const struct option *opt,4449const char*arg,int unset)4450{4451add_name_limit(arg,0);4452 has_include =1;4453return0;4454}44554456static intoption_parse_p(const struct option *opt,4457const char*arg,int unset)4458{4459 p_value =atoi(arg);4460 p_value_known =1;4461return0;4462}44634464static intoption_parse_space_change(const struct option *opt,4465const char*arg,int unset)4466{4467if(unset)4468 ws_ignore_action = ignore_ws_none;4469else4470 ws_ignore_action = ignore_ws_change;4471return0;4472}44734474static intoption_parse_whitespace(const struct option *opt,4475const char*arg,int unset)4476{4477const char**whitespace_option = opt->value;44784479*whitespace_option = arg;4480parse_whitespace_option(arg);4481return0;4482}44834484static intoption_parse_directory(const struct option *opt,4485const char*arg,int unset)4486{4487strbuf_reset(&root);4488strbuf_addstr(&root, arg);4489strbuf_complete(&root,'/');4490return0;4491}44924493intcmd_apply(int argc,const char**argv,const char*prefix_)4494{4495int i;4496int errs =0;4497int is_not_gitdir = !startup_info->have_repository;4498int force_apply =0;44994500const char*whitespace_option = NULL;45014502struct option builtin_apply_options[] = {4503{ OPTION_CALLBACK,0,"exclude", NULL,N_("path"),4504N_("don't apply changes matching the given path"),45050, option_parse_exclude },4506{ OPTION_CALLBACK,0,"include", NULL,N_("path"),4507N_("apply changes matching the given path"),45080, option_parse_include },4509{ OPTION_CALLBACK,'p', NULL, NULL,N_("num"),4510N_("remove <num> leading slashes from traditional diff paths"),45110, option_parse_p },4512OPT_BOOL(0,"no-add", &no_add,4513N_("ignore additions made by the patch")),4514OPT_BOOL(0,"stat", &diffstat,4515N_("instead of applying the patch, output diffstat for the input")),4516OPT_NOOP_NOARG(0,"allow-binary-replacement"),4517OPT_NOOP_NOARG(0,"binary"),4518OPT_BOOL(0,"numstat", &numstat,4519N_("show number of added and deleted lines in decimal notation")),4520OPT_BOOL(0,"summary", &summary,4521N_("instead of applying the patch, output a summary for the input")),4522OPT_BOOL(0,"check", &check,4523N_("instead of applying the patch, see if the patch is applicable")),4524OPT_BOOL(0,"index", &check_index,4525N_("make sure the patch is applicable to the current index")),4526OPT_BOOL(0,"cached", &cached,4527N_("apply a patch without touching the working tree")),4528OPT_BOOL(0,"unsafe-paths", &unsafe_paths,4529N_("accept a patch that touches outside the working area")),4530OPT_BOOL(0,"apply", &force_apply,4531N_("also apply the patch (use with --stat/--summary/--check)")),4532OPT_BOOL('3',"3way", &threeway,4533N_("attempt three-way merge if a patch does not apply")),4534OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,4535N_("build a temporary index based on embedded index information")),4536/* Think twice before adding "--nul" synonym to this */4537OPT_SET_INT('z', NULL, &line_termination,4538N_("paths are separated with NUL character"),'\0'),4539OPT_INTEGER('C', NULL, &p_context,4540N_("ensure at least <n> lines of context match")),4541{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,N_("action"),4542N_("detect new or modified lines that have whitespace errors"),45430, option_parse_whitespace },4544{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,4545N_("ignore changes in whitespace when finding context"),4546 PARSE_OPT_NOARG, option_parse_space_change },4547{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,4548N_("ignore changes in whitespace when finding context"),4549 PARSE_OPT_NOARG, option_parse_space_change },4550OPT_BOOL('R',"reverse", &apply_in_reverse,4551N_("apply the patch in reverse")),4552OPT_BOOL(0,"unidiff-zero", &unidiff_zero,4553N_("don't expect at least one line of context")),4554OPT_BOOL(0,"reject", &apply_with_reject,4555N_("leave the rejected hunks in corresponding *.rej files")),4556OPT_BOOL(0,"allow-overlap", &allow_overlap,4557N_("allow overlapping hunks")),4558OPT__VERBOSE(&apply_verbosely,N_("be verbose")),4559OPT_BIT(0,"inaccurate-eof", &options,4560N_("tolerate incorrectly detected missing new-line at the end of file"),4561 INACCURATE_EOF),4562OPT_BIT(0,"recount", &options,4563N_("do not trust the line counts in the hunk headers"),4564 RECOUNT),4565{ OPTION_CALLBACK,0,"directory", NULL,N_("root"),4566N_("prepend <root> to all filenames"),45670, option_parse_directory },4568OPT_END()4569};45704571 prefix = prefix_;4572 prefix_length = prefix ?strlen(prefix) :0;4573git_apply_config();4574if(apply_default_whitespace)4575parse_whitespace_option(apply_default_whitespace);4576if(apply_default_ignorewhitespace)4577parse_ignorewhitespace_option(apply_default_ignorewhitespace);45784579 argc =parse_options(argc, argv, prefix, builtin_apply_options,4580 apply_usage,0);45814582if(apply_with_reject && threeway)4583die("--reject and --3way cannot be used together.");4584if(cached && threeway)4585die("--cached and --3way cannot be used together.");4586if(threeway) {4587if(is_not_gitdir)4588die(_("--3way outside a repository"));4589 check_index =1;4590}4591if(apply_with_reject)4592 apply = apply_verbosely =1;4593if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))4594 apply =0;4595if(check_index && is_not_gitdir)4596die(_("--index outside a repository"));4597if(cached) {4598if(is_not_gitdir)4599die(_("--cached outside a repository"));4600 check_index =1;4601}4602if(check_index)4603 unsafe_paths =0;46044605for(i =0; i < argc; i++) {4606const char*arg = argv[i];4607int fd;46084609if(!strcmp(arg,"-")) {4610 errs |=apply_patch(0,"<stdin>", options);4611 read_stdin =0;4612continue;4613}else if(0< prefix_length)4614 arg =prefix_filename(prefix, prefix_length, arg);46154616 fd =open(arg, O_RDONLY);4617if(fd <0)4618die_errno(_("can't open patch '%s'"), arg);4619 read_stdin =0;4620set_default_whitespace_mode(whitespace_option);4621 errs |=apply_patch(fd, arg, options);4622close(fd);4623}4624set_default_whitespace_mode(whitespace_option);4625if(read_stdin)4626 errs |=apply_patch(0,"<stdin>", options);4627if(whitespace_error) {4628if(squelch_whitespace_errors &&4629 squelch_whitespace_errors < whitespace_error) {4630int squelched =4631 whitespace_error - squelch_whitespace_errors;4632warning(Q_("squelched%dwhitespace error",4633"squelched%dwhitespace errors",4634 squelched),4635 squelched);4636}4637if(ws_error_action == die_on_ws_error)4638die(Q_("%dline adds whitespace errors.",4639"%dlines add whitespace errors.",4640 whitespace_error),4641 whitespace_error);4642if(applied_after_fixing_ws && apply)4643warning("%dline%sapplied after"4644" fixing whitespace errors.",4645 applied_after_fixing_ws,4646 applied_after_fixing_ws ==1?"":"s");4647else if(whitespace_error)4648warning(Q_("%dline adds whitespace errors.",4649"%dlines add whitespace errors.",4650 whitespace_error),4651 whitespace_error);4652}46534654if(update_index) {4655if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK))4656die(_("Unable to write new index file"));4657}46584659return!!errs;4660}