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 24struct apply_state { 25const char*prefix; 26int prefix_length; 27 28/* These control what gets looked at and modified */ 29int cached;/* apply to the index only */ 30int check;/* preimage must match working tree, don't actually apply */ 31int check_index;/* preimage must match the indexed version */ 32int update_index;/* check_index && apply */ 33 34/* These control cosmetic aspect of the output */ 35int diffstat;/* just show a diffstat, and don't actually apply */ 36int numstat;/* just show a numeric diffstat, and don't actually apply */ 37int summary;/* just report creation, deletion, etc, and don't actually apply */ 38 39/* These boolean parameters control how the apply is done */ 40int allow_overlap; 41int apply_in_reverse; 42int apply_with_reject; 43int apply_verbosely; 44int no_add; 45int threeway; 46int unidiff_zero; 47int unsafe_paths; 48 49/* Other non boolean parameters */ 50const char*fake_ancestor; 51int line_termination; 52unsigned int p_context; 53}; 54 55static int newfd = -1; 56 57static int state_p_value =1; 58static int p_value_known; 59static int apply =1; 60static const char*const apply_usage[] = { 61N_("git apply [<options>] [<patch>...]"), 62 NULL 63}; 64 65static enum ws_error_action { 66 nowarn_ws_error, 67 warn_on_ws_error, 68 die_on_ws_error, 69 correct_ws_error 70} ws_error_action = warn_on_ws_error; 71static int whitespace_error; 72static int squelch_whitespace_errors =5; 73static int applied_after_fixing_ws; 74 75static enum ws_ignore { 76 ignore_ws_none, 77 ignore_ws_change 78} ws_ignore_action = ignore_ws_none; 79 80 81static const char*patch_input_file; 82static struct strbuf root = STRBUF_INIT; 83 84static voidparse_whitespace_option(const char*option) 85{ 86if(!option) { 87 ws_error_action = warn_on_ws_error; 88return; 89} 90if(!strcmp(option,"warn")) { 91 ws_error_action = warn_on_ws_error; 92return; 93} 94if(!strcmp(option,"nowarn")) { 95 ws_error_action = nowarn_ws_error; 96return; 97} 98if(!strcmp(option,"error")) { 99 ws_error_action = die_on_ws_error; 100return; 101} 102if(!strcmp(option,"error-all")) { 103 ws_error_action = die_on_ws_error; 104 squelch_whitespace_errors =0; 105return; 106} 107if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 108 ws_error_action = correct_ws_error; 109return; 110} 111die(_("unrecognized whitespace option '%s'"), option); 112} 113 114static voidparse_ignorewhitespace_option(const char*option) 115{ 116if(!option || !strcmp(option,"no") || 117!strcmp(option,"false") || !strcmp(option,"never") || 118!strcmp(option,"none")) { 119 ws_ignore_action = ignore_ws_none; 120return; 121} 122if(!strcmp(option,"change")) { 123 ws_ignore_action = ignore_ws_change; 124return; 125} 126die(_("unrecognized whitespace ignore option '%s'"), option); 127} 128 129static voidset_default_whitespace_mode(const char*whitespace_option) 130{ 131if(!whitespace_option && !apply_default_whitespace) 132 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 133} 134 135/* 136 * For "diff-stat" like behaviour, we keep track of the biggest change 137 * we've seen, and the longest filename. That allows us to do simple 138 * scaling. 139 */ 140static int max_change, max_len; 141 142/* 143 * Various "current state", notably line numbers and what 144 * file (and how) we're patching right now.. The "is_xxxx" 145 * things are flags, where -1 means "don't know yet". 146 */ 147static int state_linenr =1; 148 149/* 150 * This represents one "hunk" from a patch, starting with 151 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 152 * patch text is pointed at by patch, and its byte length 153 * is stored in size. leading and trailing are the number 154 * of context lines. 155 */ 156struct fragment { 157unsigned long leading, trailing; 158unsigned long oldpos, oldlines; 159unsigned long newpos, newlines; 160/* 161 * 'patch' is usually borrowed from buf in apply_patch(), 162 * but some codepaths store an allocated buffer. 163 */ 164const char*patch; 165unsigned free_patch:1, 166 rejected:1; 167int size; 168int linenr; 169struct fragment *next; 170}; 171 172/* 173 * When dealing with a binary patch, we reuse "leading" field 174 * to store the type of the binary hunk, either deflated "delta" 175 * or deflated "literal". 176 */ 177#define binary_patch_method leading 178#define BINARY_DELTA_DEFLATED 1 179#define BINARY_LITERAL_DEFLATED 2 180 181/* 182 * This represents a "patch" to a file, both metainfo changes 183 * such as creation/deletion, filemode and content changes represented 184 * as a series of fragments. 185 */ 186struct patch { 187char*new_name, *old_name, *def_name; 188unsigned int old_mode, new_mode; 189int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 190int rejected; 191unsigned ws_rule; 192int lines_added, lines_deleted; 193int score; 194unsigned int is_toplevel_relative:1; 195unsigned int inaccurate_eof:1; 196unsigned int is_binary:1; 197unsigned int is_copy:1; 198unsigned int is_rename:1; 199unsigned int recount:1; 200unsigned int conflicted_threeway:1; 201unsigned int direct_to_threeway:1; 202struct fragment *fragments; 203char*result; 204size_t resultsize; 205char old_sha1_prefix[41]; 206char new_sha1_prefix[41]; 207struct patch *next; 208 209/* three-way fallback result */ 210struct object_id threeway_stage[3]; 211}; 212 213static voidfree_fragment_list(struct fragment *list) 214{ 215while(list) { 216struct fragment *next = list->next; 217if(list->free_patch) 218free((char*)list->patch); 219free(list); 220 list = next; 221} 222} 223 224static voidfree_patch(struct patch *patch) 225{ 226free_fragment_list(patch->fragments); 227free(patch->def_name); 228free(patch->old_name); 229free(patch->new_name); 230free(patch->result); 231free(patch); 232} 233 234static voidfree_patch_list(struct patch *list) 235{ 236while(list) { 237struct patch *next = list->next; 238free_patch(list); 239 list = next; 240} 241} 242 243/* 244 * A line in a file, len-bytes long (includes the terminating LF, 245 * except for an incomplete line at the end if the file ends with 246 * one), and its contents hashes to 'hash'. 247 */ 248struct line { 249size_t len; 250unsigned hash :24; 251unsigned flag :8; 252#define LINE_COMMON 1 253#define LINE_PATCHED 2 254}; 255 256/* 257 * This represents a "file", which is an array of "lines". 258 */ 259struct image { 260char*buf; 261size_t len; 262size_t nr; 263size_t alloc; 264struct line *line_allocated; 265struct line *line; 266}; 267 268/* 269 * Records filenames that have been touched, in order to handle 270 * the case where more than one patches touch the same file. 271 */ 272 273static struct string_list fn_table; 274 275static uint32_thash_line(const char*cp,size_t len) 276{ 277size_t i; 278uint32_t h; 279for(i =0, h =0; i < len; i++) { 280if(!isspace(cp[i])) { 281 h = h *3+ (cp[i] &0xff); 282} 283} 284return h; 285} 286 287/* 288 * Compare lines s1 of length n1 and s2 of length n2, ignoring 289 * whitespace difference. Returns 1 if they match, 0 otherwise 290 */ 291static intfuzzy_matchlines(const char*s1,size_t n1, 292const char*s2,size_t n2) 293{ 294const char*last1 = s1 + n1 -1; 295const char*last2 = s2 + n2 -1; 296int result =0; 297 298/* ignore line endings */ 299while((*last1 =='\r') || (*last1 =='\n')) 300 last1--; 301while((*last2 =='\r') || (*last2 =='\n')) 302 last2--; 303 304/* skip leading whitespaces, if both begin with whitespace */ 305if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 306while(isspace(*s1) && (s1 <= last1)) 307 s1++; 308while(isspace(*s2) && (s2 <= last2)) 309 s2++; 310} 311/* early return if both lines are empty */ 312if((s1 > last1) && (s2 > last2)) 313return1; 314while(!result) { 315 result = *s1++ - *s2++; 316/* 317 * Skip whitespace inside. We check for whitespace on 318 * both buffers because we don't want "a b" to match 319 * "ab" 320 */ 321if(isspace(*s1) &&isspace(*s2)) { 322while(isspace(*s1) && s1 <= last1) 323 s1++; 324while(isspace(*s2) && s2 <= last2) 325 s2++; 326} 327/* 328 * If we reached the end on one side only, 329 * lines don't match 330 */ 331if( 332((s2 > last2) && (s1 <= last1)) || 333((s1 > last1) && (s2 <= last2))) 334return0; 335if((s1 > last1) && (s2 > last2)) 336break; 337} 338 339return!result; 340} 341 342static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 343{ 344ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 345 img->line_allocated[img->nr].len = len; 346 img->line_allocated[img->nr].hash =hash_line(bol, len); 347 img->line_allocated[img->nr].flag = flag; 348 img->nr++; 349} 350 351/* 352 * "buf" has the file contents to be patched (read from various sources). 353 * attach it to "image" and add line-based index to it. 354 * "image" now owns the "buf". 355 */ 356static voidprepare_image(struct image *image,char*buf,size_t len, 357int prepare_linetable) 358{ 359const char*cp, *ep; 360 361memset(image,0,sizeof(*image)); 362 image->buf = buf; 363 image->len = len; 364 365if(!prepare_linetable) 366return; 367 368 ep = image->buf + image->len; 369 cp = image->buf; 370while(cp < ep) { 371const char*next; 372for(next = cp; next < ep && *next !='\n'; next++) 373; 374if(next < ep) 375 next++; 376add_line_info(image, cp, next - cp,0); 377 cp = next; 378} 379 image->line = image->line_allocated; 380} 381 382static voidclear_image(struct image *image) 383{ 384free(image->buf); 385free(image->line_allocated); 386memset(image,0,sizeof(*image)); 387} 388 389/* fmt must contain _one_ %s and no other substitution */ 390static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 391{ 392struct strbuf sb = STRBUF_INIT; 393 394if(patch->old_name && patch->new_name && 395strcmp(patch->old_name, patch->new_name)) { 396quote_c_style(patch->old_name, &sb, NULL,0); 397strbuf_addstr(&sb," => "); 398quote_c_style(patch->new_name, &sb, NULL,0); 399}else{ 400const char*n = patch->new_name; 401if(!n) 402 n = patch->old_name; 403quote_c_style(n, &sb, NULL,0); 404} 405fprintf(output, fmt, sb.buf); 406fputc('\n', output); 407strbuf_release(&sb); 408} 409 410#define SLOP (16) 411 412static voidread_patch_file(struct strbuf *sb,int fd) 413{ 414if(strbuf_read(sb, fd,0) <0) 415die_errno("git apply: failed to read"); 416 417/* 418 * Make sure that we have some slop in the buffer 419 * so that we can do speculative "memcmp" etc, and 420 * see to it that it is NUL-filled. 421 */ 422strbuf_grow(sb, SLOP); 423memset(sb->buf + sb->len,0, SLOP); 424} 425 426static unsigned longlinelen(const char*buffer,unsigned long size) 427{ 428unsigned long len =0; 429while(size--) { 430 len++; 431if(*buffer++ =='\n') 432break; 433} 434return len; 435} 436 437static intis_dev_null(const char*str) 438{ 439returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 440} 441 442#define TERM_SPACE 1 443#define TERM_TAB 2 444 445static intname_terminate(const char*name,int namelen,int c,int terminate) 446{ 447if(c ==' '&& !(terminate & TERM_SPACE)) 448return0; 449if(c =='\t'&& !(terminate & TERM_TAB)) 450return0; 451 452return1; 453} 454 455/* remove double slashes to make --index work with such filenames */ 456static char*squash_slash(char*name) 457{ 458int i =0, j =0; 459 460if(!name) 461return NULL; 462 463while(name[i]) { 464if((name[j++] = name[i++]) =='/') 465while(name[i] =='/') 466 i++; 467} 468 name[j] ='\0'; 469return name; 470} 471 472static char*find_name_gnu(const char*line,const char*def,int p_value) 473{ 474struct strbuf name = STRBUF_INIT; 475char*cp; 476 477/* 478 * Proposed "new-style" GNU patch/diff format; see 479 * http://marc.info/?l=git&m=112927316408690&w=2 480 */ 481if(unquote_c_style(&name, line, NULL)) { 482strbuf_release(&name); 483return NULL; 484} 485 486for(cp = name.buf; p_value; p_value--) { 487 cp =strchr(cp,'/'); 488if(!cp) { 489strbuf_release(&name); 490return NULL; 491} 492 cp++; 493} 494 495strbuf_remove(&name,0, cp - name.buf); 496if(root.len) 497strbuf_insert(&name,0, root.buf, root.len); 498returnsquash_slash(strbuf_detach(&name, NULL)); 499} 500 501static size_tsane_tz_len(const char*line,size_t len) 502{ 503const char*tz, *p; 504 505if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 506return0; 507 tz = line + len -strlen(" +0500"); 508 509if(tz[1] !='+'&& tz[1] !='-') 510return0; 511 512for(p = tz +2; p != line + len; p++) 513if(!isdigit(*p)) 514return0; 515 516return line + len - tz; 517} 518 519static size_ttz_with_colon_len(const char*line,size_t len) 520{ 521const char*tz, *p; 522 523if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 524return0; 525 tz = line + len -strlen(" +08:00"); 526 527if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 528return0; 529 p = tz +2; 530if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 531!isdigit(*p++) || !isdigit(*p++)) 532return0; 533 534return line + len - tz; 535} 536 537static size_tdate_len(const char*line,size_t len) 538{ 539const char*date, *p; 540 541if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 542return0; 543 p = date = line + len -strlen("72-02-05"); 544 545if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 546!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 547!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 548return0; 549 550if(date - line >=strlen("19") && 551isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 552 date -=strlen("19"); 553 554return line + len - date; 555} 556 557static size_tshort_time_len(const char*line,size_t len) 558{ 559const char*time, *p; 560 561if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 562return0; 563 p = time = line + len -strlen(" 07:01:32"); 564 565/* Permit 1-digit hours? */ 566if(*p++ !=' '|| 567!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 568!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 569!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 570return0; 571 572return line + len - time; 573} 574 575static size_tfractional_time_len(const char*line,size_t len) 576{ 577const char*p; 578size_t n; 579 580/* Expected format: 19:41:17.620000023 */ 581if(!len || !isdigit(line[len -1])) 582return0; 583 p = line + len -1; 584 585/* Fractional seconds. */ 586while(p > line &&isdigit(*p)) 587 p--; 588if(*p !='.') 589return0; 590 591/* Hours, minutes, and whole seconds. */ 592 n =short_time_len(line, p - line); 593if(!n) 594return0; 595 596return line + len - p + n; 597} 598 599static size_ttrailing_spaces_len(const char*line,size_t len) 600{ 601const char*p; 602 603/* Expected format: ' ' x (1 or more) */ 604if(!len || line[len -1] !=' ') 605return0; 606 607 p = line + len; 608while(p != line) { 609 p--; 610if(*p !=' ') 611return line + len - (p +1); 612} 613 614/* All spaces! */ 615return len; 616} 617 618static size_tdiff_timestamp_len(const char*line,size_t len) 619{ 620const char*end = line + len; 621size_t n; 622 623/* 624 * Posix: 2010-07-05 19:41:17 625 * GNU: 2010-07-05 19:41:17.620000023 -0500 626 */ 627 628if(!isdigit(end[-1])) 629return0; 630 631 n =sane_tz_len(line, end - line); 632if(!n) 633 n =tz_with_colon_len(line, end - line); 634 end -= n; 635 636 n =short_time_len(line, end - line); 637if(!n) 638 n =fractional_time_len(line, end - line); 639 end -= n; 640 641 n =date_len(line, end - line); 642if(!n)/* No date. Too bad. */ 643return0; 644 end -= n; 645 646if(end == line)/* No space before date. */ 647return0; 648if(end[-1] =='\t') {/* Success! */ 649 end--; 650return line + len - end; 651} 652if(end[-1] !=' ')/* No space before date. */ 653return0; 654 655/* Whitespace damage. */ 656 end -=trailing_spaces_len(line, end - line); 657return line + len - end; 658} 659 660static char*find_name_common(const char*line,const char*def, 661int p_value,const char*end,int terminate) 662{ 663int len; 664const char*start = NULL; 665 666if(p_value ==0) 667 start = line; 668while(line != end) { 669char c = *line; 670 671if(!end &&isspace(c)) { 672if(c =='\n') 673break; 674if(name_terminate(start, line-start, c, terminate)) 675break; 676} 677 line++; 678if(c =='/'&& !--p_value) 679 start = line; 680} 681if(!start) 682returnsquash_slash(xstrdup_or_null(def)); 683 len = line - start; 684if(!len) 685returnsquash_slash(xstrdup_or_null(def)); 686 687/* 688 * Generally we prefer the shorter name, especially 689 * if the other one is just a variation of that with 690 * something else tacked on to the end (ie "file.orig" 691 * or "file~"). 692 */ 693if(def) { 694int deflen =strlen(def); 695if(deflen < len && !strncmp(start, def, deflen)) 696returnsquash_slash(xstrdup(def)); 697} 698 699if(root.len) { 700char*ret =xstrfmt("%s%.*s", root.buf, len, start); 701returnsquash_slash(ret); 702} 703 704returnsquash_slash(xmemdupz(start, len)); 705} 706 707static char*find_name(const char*line,char*def,int p_value,int terminate) 708{ 709if(*line =='"') { 710char*name =find_name_gnu(line, def, p_value); 711if(name) 712return name; 713} 714 715returnfind_name_common(line, def, p_value, NULL, terminate); 716} 717 718static char*find_name_traditional(const char*line,char*def,int p_value) 719{ 720size_t len; 721size_t date_len; 722 723if(*line =='"') { 724char*name =find_name_gnu(line, def, p_value); 725if(name) 726return name; 727} 728 729 len =strchrnul(line,'\n') - line; 730 date_len =diff_timestamp_len(line, len); 731if(!date_len) 732returnfind_name_common(line, def, p_value, NULL, TERM_TAB); 733 len -= date_len; 734 735returnfind_name_common(line, def, p_value, line + len,0); 736} 737 738static intcount_slashes(const char*cp) 739{ 740int cnt =0; 741char ch; 742 743while((ch = *cp++)) 744if(ch =='/') 745 cnt++; 746return cnt; 747} 748 749/* 750 * Given the string after "--- " or "+++ ", guess the appropriate 751 * p_value for the given patch. 752 */ 753static intguess_p_value(struct apply_state *state,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(state->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, state->prefix, state->prefix_length)) 772 val =count_slashes(state->prefix); 773else{ 774 cp++; 775if(!strncmp(cp, state->prefix, state->prefix_length)) 776 val =count_slashes(state->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(struct apply_state *state, 864const char*first, 865const char*second, 866struct patch *patch) 867{ 868char*name; 869 870 first +=4;/* skip "--- " */ 871 second +=4;/* skip "+++ " */ 872if(!p_value_known) { 873int p, q; 874 p =guess_p_value(state, first); 875 q =guess_p_value(state, second); 876if(p <0) p = q; 877if(0<= p && p == q) { 878 state_p_value = p; 879 p_value_known =1; 880} 881} 882if(is_dev_null(first)) { 883 patch->is_new =1; 884 patch->is_delete =0; 885 name =find_name_traditional(second, NULL, state_p_value); 886 patch->new_name = name; 887}else if(is_dev_null(second)) { 888 patch->is_new =0; 889 patch->is_delete =1; 890 name =find_name_traditional(first, NULL, state_p_value); 891 patch->old_name = name; 892}else{ 893char*first_name; 894 first_name =find_name_traditional(first, NULL, state_p_value); 895 name =find_name_traditional(second, first_name, state_p_value); 896free(first_name); 897if(has_epoch_timestamp(first)) { 898 patch->is_new =1; 899 patch->is_delete =0; 900 patch->new_name = name; 901}else if(has_epoch_timestamp(second)) { 902 patch->is_new =0; 903 patch->is_delete =1; 904 patch->old_name = name; 905}else{ 906 patch->old_name = name; 907 patch->new_name =xstrdup_or_null(name); 908} 909} 910if(!name) 911die(_("unable to find filename in patch at line%d"), state_linenr); 912} 913 914static intgitdiff_hdrend(const char*line,struct patch *patch) 915{ 916return-1; 917} 918 919/* 920 * We're anal about diff header consistency, to make 921 * sure that we don't end up having strange ambiguous 922 * patches floating around. 923 * 924 * As a result, gitdiff_{old|new}name() will check 925 * their names against any previous information, just 926 * to make sure.. 927 */ 928#define DIFF_OLD_NAME 0 929#define DIFF_NEW_NAME 1 930 931static voidgitdiff_verify_name(const char*line,int isnull,char**name,int side) 932{ 933if(!*name && !isnull) { 934*name =find_name(line, NULL, state_p_value, TERM_TAB); 935return; 936} 937 938if(*name) { 939int len =strlen(*name); 940char*another; 941if(isnull) 942die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 943*name, state_linenr); 944 another =find_name(line, NULL, state_p_value, TERM_TAB); 945if(!another ||memcmp(another, *name, len +1)) 946die((side == DIFF_NEW_NAME) ? 947_("git apply: bad git-diff - inconsistent new filename on line%d") : 948_("git apply: bad git-diff - inconsistent old filename on line%d"), state_linenr); 949free(another); 950}else{ 951/* expect "/dev/null" */ 952if(memcmp("/dev/null", line,9) || line[9] !='\n') 953die(_("git apply: bad git-diff - expected /dev/null on line%d"), state_linenr); 954} 955} 956 957static intgitdiff_oldname(const char*line,struct patch *patch) 958{ 959gitdiff_verify_name(line, patch->is_new, &patch->old_name, 960 DIFF_OLD_NAME); 961return0; 962} 963 964static intgitdiff_newname(const char*line,struct patch *patch) 965{ 966gitdiff_verify_name(line, patch->is_delete, &patch->new_name, 967 DIFF_NEW_NAME); 968return0; 969} 970 971static intgitdiff_oldmode(const char*line,struct patch *patch) 972{ 973 patch->old_mode =strtoul(line, NULL,8); 974return0; 975} 976 977static intgitdiff_newmode(const char*line,struct patch *patch) 978{ 979 patch->new_mode =strtoul(line, NULL,8); 980return0; 981} 982 983static intgitdiff_delete(const char*line,struct patch *patch) 984{ 985 patch->is_delete =1; 986free(patch->old_name); 987 patch->old_name =xstrdup_or_null(patch->def_name); 988returngitdiff_oldmode(line, patch); 989} 990 991static intgitdiff_newfile(const char*line,struct patch *patch) 992{ 993 patch->is_new =1; 994free(patch->new_name); 995 patch->new_name =xstrdup_or_null(patch->def_name); 996returngitdiff_newmode(line, patch); 997} 998 999static intgitdiff_copysrc(const char*line,struct patch *patch)1000{1001 patch->is_copy =1;1002free(patch->old_name);1003 patch->old_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1004return0;1005}10061007static intgitdiff_copydst(const char*line,struct patch *patch)1008{1009 patch->is_copy =1;1010free(patch->new_name);1011 patch->new_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1012return0;1013}10141015static intgitdiff_renamesrc(const char*line,struct patch *patch)1016{1017 patch->is_rename =1;1018free(patch->old_name);1019 patch->old_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1020return0;1021}10221023static intgitdiff_renamedst(const char*line,struct patch *patch)1024{1025 patch->is_rename =1;1026free(patch->new_name);1027 patch->new_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1028return0;1029}10301031static intgitdiff_similarity(const char*line,struct patch *patch)1032{1033unsigned long val =strtoul(line, NULL,10);1034if(val <=100)1035 patch->score = val;1036return0;1037}10381039static intgitdiff_dissimilarity(const char*line,struct patch *patch)1040{1041unsigned long val =strtoul(line, NULL,10);1042if(val <=100)1043 patch->score = val;1044return0;1045}10461047static intgitdiff_index(const char*line,struct patch *patch)1048{1049/*1050 * index line is N hexadecimal, "..", N hexadecimal,1051 * and optional space with octal mode.1052 */1053const char*ptr, *eol;1054int len;10551056 ptr =strchr(line,'.');1057if(!ptr || ptr[1] !='.'||40< ptr - line)1058return0;1059 len = ptr - line;1060memcpy(patch->old_sha1_prefix, line, len);1061 patch->old_sha1_prefix[len] =0;10621063 line = ptr +2;1064 ptr =strchr(line,' ');1065 eol =strchrnul(line,'\n');10661067if(!ptr || eol < ptr)1068 ptr = eol;1069 len = ptr - line;10701071if(40< len)1072return0;1073memcpy(patch->new_sha1_prefix, line, len);1074 patch->new_sha1_prefix[len] =0;1075if(*ptr ==' ')1076 patch->old_mode =strtoul(ptr+1, NULL,8);1077return0;1078}10791080/*1081 * This is normal for a diff that doesn't change anything: we'll fall through1082 * into the next diff. Tell the parser to break out.1083 */1084static intgitdiff_unrecognized(const char*line,struct patch *patch)1085{1086return-1;1087}10881089/*1090 * Skip p_value leading components from "line"; as we do not accept1091 * absolute paths, return NULL in that case.1092 */1093static const char*skip_tree_prefix(const char*line,int llen)1094{1095int nslash;1096int i;10971098if(!state_p_value)1099return(llen && line[0] =='/') ? NULL : line;11001101 nslash = state_p_value;1102for(i =0; i < llen; i++) {1103int ch = line[i];1104if(ch =='/'&& --nslash <=0)1105return(i ==0) ? NULL : &line[i +1];1106}1107return NULL;1108}11091110/*1111 * This is to extract the same name that appears on "diff --git"1112 * line. We do not find and return anything if it is a rename1113 * patch, and it is OK because we will find the name elsewhere.1114 * We need to reliably find name only when it is mode-change only,1115 * creation or deletion of an empty file. In any of these cases,1116 * both sides are the same name under a/ and b/ respectively.1117 */1118static char*git_header_name(const char*line,int llen)1119{1120const char*name;1121const char*second = NULL;1122size_t len, line_len;11231124 line +=strlen("diff --git ");1125 llen -=strlen("diff --git ");11261127if(*line =='"') {1128const char*cp;1129struct strbuf first = STRBUF_INIT;1130struct strbuf sp = STRBUF_INIT;11311132if(unquote_c_style(&first, line, &second))1133goto free_and_fail1;11341135/* strip the a/b prefix including trailing slash */1136 cp =skip_tree_prefix(first.buf, first.len);1137if(!cp)1138goto free_and_fail1;1139strbuf_remove(&first,0, cp - first.buf);11401141/*1142 * second points at one past closing dq of name.1143 * find the second name.1144 */1145while((second < line + llen) &&isspace(*second))1146 second++;11471148if(line + llen <= second)1149goto free_and_fail1;1150if(*second =='"') {1151if(unquote_c_style(&sp, second, NULL))1152goto free_and_fail1;1153 cp =skip_tree_prefix(sp.buf, sp.len);1154if(!cp)1155goto free_and_fail1;1156/* They must match, otherwise ignore */1157if(strcmp(cp, first.buf))1158goto free_and_fail1;1159strbuf_release(&sp);1160returnstrbuf_detach(&first, NULL);1161}11621163/* unquoted second */1164 cp =skip_tree_prefix(second, line + llen - second);1165if(!cp)1166goto free_and_fail1;1167if(line + llen - cp != first.len ||1168memcmp(first.buf, cp, first.len))1169goto free_and_fail1;1170returnstrbuf_detach(&first, NULL);11711172 free_and_fail1:1173strbuf_release(&first);1174strbuf_release(&sp);1175return NULL;1176}11771178/* unquoted first name */1179 name =skip_tree_prefix(line, llen);1180if(!name)1181return NULL;11821183/*1184 * since the first name is unquoted, a dq if exists must be1185 * the beginning of the second name.1186 */1187for(second = name; second < line + llen; second++) {1188if(*second =='"') {1189struct strbuf sp = STRBUF_INIT;1190const char*np;11911192if(unquote_c_style(&sp, second, NULL))1193goto free_and_fail2;11941195 np =skip_tree_prefix(sp.buf, sp.len);1196if(!np)1197goto free_and_fail2;11981199 len = sp.buf + sp.len - np;1200if(len < second - name &&1201!strncmp(np, name, len) &&1202isspace(name[len])) {1203/* Good */1204strbuf_remove(&sp,0, np - sp.buf);1205returnstrbuf_detach(&sp, NULL);1206}12071208 free_and_fail2:1209strbuf_release(&sp);1210return NULL;1211}1212}12131214/*1215 * Accept a name only if it shows up twice, exactly the same1216 * form.1217 */1218 second =strchr(name,'\n');1219if(!second)1220return NULL;1221 line_len = second - name;1222for(len =0; ; len++) {1223switch(name[len]) {1224default:1225continue;1226case'\n':1227return NULL;1228case'\t':case' ':1229/*1230 * Is this the separator between the preimage1231 * and the postimage pathname? Again, we are1232 * only interested in the case where there is1233 * no rename, as this is only to set def_name1234 * and a rename patch has the names elsewhere1235 * in an unambiguous form.1236 */1237if(!name[len +1])1238return NULL;/* no postimage name */1239 second =skip_tree_prefix(name + len +1,1240 line_len - (len +1));1241if(!second)1242return NULL;1243/*1244 * Does len bytes starting at "name" and "second"1245 * (that are separated by one HT or SP we just1246 * found) exactly match?1247 */1248if(second[len] =='\n'&& !strncmp(name, second, len))1249returnxmemdupz(name, len);1250}1251}1252}12531254/* Verify that we recognize the lines following a git header */1255static intparse_git_header(const char*line,int len,unsigned int size,struct patch *patch)1256{1257unsigned long offset;12581259/* A git diff has explicit new/delete information, so we don't guess */1260 patch->is_new =0;1261 patch->is_delete =0;12621263/*1264 * Some things may not have the old name in the1265 * rest of the headers anywhere (pure mode changes,1266 * or removing or adding empty files), so we get1267 * the default name from the header.1268 */1269 patch->def_name =git_header_name(line, len);1270if(patch->def_name && root.len) {1271char*s =xstrfmt("%s%s", root.buf, patch->def_name);1272free(patch->def_name);1273 patch->def_name = s;1274}12751276 line += len;1277 size -= len;1278 state_linenr++;1279for(offset = len ; size >0; offset += len, size -= len, line += len, state_linenr++) {1280static const struct opentry {1281const char*str;1282int(*fn)(const char*,struct patch *);1283} optable[] = {1284{"@@ -", gitdiff_hdrend },1285{"--- ", gitdiff_oldname },1286{"+++ ", gitdiff_newname },1287{"old mode ", gitdiff_oldmode },1288{"new mode ", gitdiff_newmode },1289{"deleted file mode ", gitdiff_delete },1290{"new file mode ", gitdiff_newfile },1291{"copy from ", gitdiff_copysrc },1292{"copy to ", gitdiff_copydst },1293{"rename old ", gitdiff_renamesrc },1294{"rename new ", gitdiff_renamedst },1295{"rename from ", gitdiff_renamesrc },1296{"rename to ", gitdiff_renamedst },1297{"similarity index ", gitdiff_similarity },1298{"dissimilarity index ", gitdiff_dissimilarity },1299{"index ", gitdiff_index },1300{"", gitdiff_unrecognized },1301};1302int i;13031304 len =linelen(line, size);1305if(!len || line[len-1] !='\n')1306break;1307for(i =0; i <ARRAY_SIZE(optable); i++) {1308const struct opentry *p = optable + i;1309int oplen =strlen(p->str);1310if(len < oplen ||memcmp(p->str, line, oplen))1311continue;1312if(p->fn(line + oplen, patch) <0)1313return offset;1314break;1315}1316}13171318return offset;1319}13201321static intparse_num(const char*line,unsigned long*p)1322{1323char*ptr;13241325if(!isdigit(*line))1326return0;1327*p =strtoul(line, &ptr,10);1328return ptr - line;1329}13301331static intparse_range(const char*line,int len,int offset,const char*expect,1332unsigned long*p1,unsigned long*p2)1333{1334int digits, ex;13351336if(offset <0|| offset >= len)1337return-1;1338 line += offset;1339 len -= offset;13401341 digits =parse_num(line, p1);1342if(!digits)1343return-1;13441345 offset += digits;1346 line += digits;1347 len -= digits;13481349*p2 =1;1350if(*line ==',') {1351 digits =parse_num(line+1, p2);1352if(!digits)1353return-1;13541355 offset += digits+1;1356 line += digits+1;1357 len -= digits+1;1358}13591360 ex =strlen(expect);1361if(ex > len)1362return-1;1363if(memcmp(line, expect, ex))1364return-1;13651366return offset + ex;1367}13681369static voidrecount_diff(const char*line,int size,struct fragment *fragment)1370{1371int oldlines =0, newlines =0, ret =0;13721373if(size <1) {1374warning("recount: ignore empty hunk");1375return;1376}13771378for(;;) {1379int len =linelen(line, size);1380 size -= len;1381 line += len;13821383if(size <1)1384break;13851386switch(*line) {1387case' ':case'\n':1388 newlines++;1389/* fall through */1390case'-':1391 oldlines++;1392continue;1393case'+':1394 newlines++;1395continue;1396case'\\':1397continue;1398case'@':1399 ret = size <3|| !starts_with(line,"@@ ");1400break;1401case'd':1402 ret = size <5|| !starts_with(line,"diff ");1403break;1404default:1405 ret = -1;1406break;1407}1408if(ret) {1409warning(_("recount: unexpected line: %.*s"),1410(int)linelen(line, size), line);1411return;1412}1413break;1414}1415 fragment->oldlines = oldlines;1416 fragment->newlines = newlines;1417}14181419/*1420 * Parse a unified diff fragment header of the1421 * form "@@ -a,b +c,d @@"1422 */1423static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1424{1425int offset;14261427if(!len || line[len-1] !='\n')1428return-1;14291430/* Figure out the number of lines in a fragment */1431 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1432 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14331434return offset;1435}14361437static intfind_header(struct apply_state *state,1438const char*line,1439unsigned long size,1440int*hdrsize,1441struct patch *patch)1442{1443unsigned long offset, len;14441445 patch->is_toplevel_relative =0;1446 patch->is_rename = patch->is_copy =0;1447 patch->is_new = patch->is_delete = -1;1448 patch->old_mode = patch->new_mode =0;1449 patch->old_name = patch->new_name = NULL;1450for(offset =0; size >0; offset += len, size -= len, line += len, state_linenr++) {1451unsigned long nextlen;14521453 len =linelen(line, size);1454if(!len)1455break;14561457/* Testing this early allows us to take a few shortcuts.. */1458if(len <6)1459continue;14601461/*1462 * Make sure we don't find any unconnected patch fragments.1463 * That's a sign that we didn't find a header, and that a1464 * patch has become corrupted/broken up.1465 */1466if(!memcmp("@@ -", line,4)) {1467struct fragment dummy;1468if(parse_fragment_header(line, len, &dummy) <0)1469continue;1470die(_("patch fragment without header at line%d: %.*s"),1471 state_linenr, (int)len-1, line);1472}14731474if(size < len +6)1475break;14761477/*1478 * Git patch? It might not have a real patch, just a rename1479 * or mode change, so we handle that specially1480 */1481if(!memcmp("diff --git ", line,11)) {1482int git_hdr_len =parse_git_header(line, len, size, patch);1483if(git_hdr_len <= len)1484continue;1485if(!patch->old_name && !patch->new_name) {1486if(!patch->def_name)1487die(Q_("git diff header lacks filename information when removing "1488"%dleading pathname component (line%d)",1489"git diff header lacks filename information when removing "1490"%dleading pathname components (line%d)",1491 state_p_value),1492 state_p_value, state_linenr);1493 patch->old_name =xstrdup(patch->def_name);1494 patch->new_name =xstrdup(patch->def_name);1495}1496if(!patch->is_delete && !patch->new_name)1497die("git diff header lacks filename information "1498"(line%d)", state_linenr);1499 patch->is_toplevel_relative =1;1500*hdrsize = git_hdr_len;1501return offset;1502}15031504/* --- followed by +++ ? */1505if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1506continue;15071508/*1509 * We only accept unified patches, so we want it to1510 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1511 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1512 */1513 nextlen =linelen(line + len, size - len);1514if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1515continue;15161517/* Ok, we'll consider it a patch */1518parse_traditional_patch(state, line, line+len, patch);1519*hdrsize = len + nextlen;1520 state_linenr +=2;1521return offset;1522}1523return-1;1524}15251526static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1527{1528char*err;15291530if(!result)1531return;15321533 whitespace_error++;1534if(squelch_whitespace_errors &&1535 squelch_whitespace_errors < whitespace_error)1536return;15371538 err =whitespace_error_string(result);1539fprintf(stderr,"%s:%d:%s.\n%.*s\n",1540 patch_input_file, linenr, err, len, line);1541free(err);1542}15431544static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1545{1546unsigned result =ws_check(line +1, len -1, ws_rule);15471548record_ws_error(result, line +1, len -2, state_linenr);1549}15501551/*1552 * Parse a unified diff. Note that this really needs to parse each1553 * fragment separately, since the only way to know the difference1554 * between a "---" that is part of a patch, and a "---" that starts1555 * the next patch is to look at the line counts..1556 */1557static intparse_fragment(struct apply_state *state,1558const char*line,1559unsigned long size,1560struct patch *patch,1561struct fragment *fragment)1562{1563int added, deleted;1564int len =linelen(line, size), offset;1565unsigned long oldlines, newlines;1566unsigned long leading, trailing;15671568 offset =parse_fragment_header(line, len, fragment);1569if(offset <0)1570return-1;1571if(offset >0&& patch->recount)1572recount_diff(line + offset, size - offset, fragment);1573 oldlines = fragment->oldlines;1574 newlines = fragment->newlines;1575 leading =0;1576 trailing =0;15771578/* Parse the thing.. */1579 line += len;1580 size -= len;1581 state_linenr++;1582 added = deleted =0;1583for(offset = len;15840< size;1585 offset += len, size -= len, line += len, state_linenr++) {1586if(!oldlines && !newlines)1587break;1588 len =linelen(line, size);1589if(!len || line[len-1] !='\n')1590return-1;1591switch(*line) {1592default:1593return-1;1594case'\n':/* newer GNU diff, an empty context line */1595case' ':1596 oldlines--;1597 newlines--;1598if(!deleted && !added)1599 leading++;1600 trailing++;1601if(!state->apply_in_reverse &&1602 ws_error_action == correct_ws_error)1603check_whitespace(line, len, patch->ws_rule);1604break;1605case'-':1606if(state->apply_in_reverse &&1607 ws_error_action != nowarn_ws_error)1608check_whitespace(line, len, patch->ws_rule);1609 deleted++;1610 oldlines--;1611 trailing =0;1612break;1613case'+':1614if(!state->apply_in_reverse &&1615 ws_error_action != nowarn_ws_error)1616check_whitespace(line, len, patch->ws_rule);1617 added++;1618 newlines--;1619 trailing =0;1620break;16211622/*1623 * We allow "\ No newline at end of file". Depending1624 * on locale settings when the patch was produced we1625 * don't know what this line looks like. The only1626 * thing we do know is that it begins with "\ ".1627 * Checking for 12 is just for sanity check -- any1628 * l10n of "\ No newline..." is at least that long.1629 */1630case'\\':1631if(len <12||memcmp(line,"\\",2))1632return-1;1633break;1634}1635}1636if(oldlines || newlines)1637return-1;1638if(!deleted && !added)1639return-1;16401641 fragment->leading = leading;1642 fragment->trailing = trailing;16431644/*1645 * If a fragment ends with an incomplete line, we failed to include1646 * it in the above loop because we hit oldlines == newlines == 01647 * before seeing it.1648 */1649if(12< size && !memcmp(line,"\\",2))1650 offset +=linelen(line, size);16511652 patch->lines_added += added;1653 patch->lines_deleted += deleted;16541655if(0< patch->is_new && oldlines)1656returnerror(_("new file depends on old contents"));1657if(0< patch->is_delete && newlines)1658returnerror(_("deleted file still has contents"));1659return offset;1660}16611662/*1663 * We have seen "diff --git a/... b/..." header (or a traditional patch1664 * header). Read hunks that belong to this patch into fragments and hang1665 * them to the given patch structure.1666 *1667 * The (fragment->patch, fragment->size) pair points into the memory given1668 * by the caller, not a copy, when we return.1669 */1670static intparse_single_patch(struct apply_state *state,1671const char*line,1672unsigned long size,1673struct patch *patch)1674{1675unsigned long offset =0;1676unsigned long oldlines =0, newlines =0, context =0;1677struct fragment **fragp = &patch->fragments;16781679while(size >4&& !memcmp(line,"@@ -",4)) {1680struct fragment *fragment;1681int len;16821683 fragment =xcalloc(1,sizeof(*fragment));1684 fragment->linenr = state_linenr;1685 len =parse_fragment(state, line, size, patch, fragment);1686if(len <=0)1687die(_("corrupt patch at line%d"), state_linenr);1688 fragment->patch = line;1689 fragment->size = len;1690 oldlines += fragment->oldlines;1691 newlines += fragment->newlines;1692 context += fragment->leading + fragment->trailing;16931694*fragp = fragment;1695 fragp = &fragment->next;16961697 offset += len;1698 line += len;1699 size -= len;1700}17011702/*1703 * If something was removed (i.e. we have old-lines) it cannot1704 * be creation, and if something was added it cannot be1705 * deletion. However, the reverse is not true; --unified=01706 * patches that only add are not necessarily creation even1707 * though they do not have any old lines, and ones that only1708 * delete are not necessarily deletion.1709 *1710 * Unfortunately, a real creation/deletion patch do _not_ have1711 * any context line by definition, so we cannot safely tell it1712 * apart with --unified=0 insanity. At least if the patch has1713 * more than one hunk it is not creation or deletion.1714 */1715if(patch->is_new <0&&1716(oldlines || (patch->fragments && patch->fragments->next)))1717 patch->is_new =0;1718if(patch->is_delete <0&&1719(newlines || (patch->fragments && patch->fragments->next)))1720 patch->is_delete =0;17211722if(0< patch->is_new && oldlines)1723die(_("new file%sdepends on old contents"), patch->new_name);1724if(0< patch->is_delete && newlines)1725die(_("deleted file%sstill has contents"), patch->old_name);1726if(!patch->is_delete && !newlines && context)1727fprintf_ln(stderr,1728_("** warning: "1729"file%sbecomes empty but is not deleted"),1730 patch->new_name);17311732return offset;1733}17341735staticinlineintmetadata_changes(struct patch *patch)1736{1737return patch->is_rename >0||1738 patch->is_copy >0||1739 patch->is_new >0||1740 patch->is_delete ||1741(patch->old_mode && patch->new_mode &&1742 patch->old_mode != patch->new_mode);1743}17441745static char*inflate_it(const void*data,unsigned long size,1746unsigned long inflated_size)1747{1748 git_zstream stream;1749void*out;1750int st;17511752memset(&stream,0,sizeof(stream));17531754 stream.next_in = (unsigned char*)data;1755 stream.avail_in = size;1756 stream.next_out = out =xmalloc(inflated_size);1757 stream.avail_out = inflated_size;1758git_inflate_init(&stream);1759 st =git_inflate(&stream, Z_FINISH);1760git_inflate_end(&stream);1761if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1762free(out);1763return NULL;1764}1765return out;1766}17671768/*1769 * Read a binary hunk and return a new fragment; fragment->patch1770 * points at an allocated memory that the caller must free, so1771 * it is marked as "->free_patch = 1".1772 */1773static struct fragment *parse_binary_hunk(char**buf_p,1774unsigned long*sz_p,1775int*status_p,1776int*used_p)1777{1778/*1779 * Expect a line that begins with binary patch method ("literal"1780 * or "delta"), followed by the length of data before deflating.1781 * a sequence of 'length-byte' followed by base-85 encoded data1782 * should follow, terminated by a newline.1783 *1784 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1785 * and we would limit the patch line to 66 characters,1786 * so one line can fit up to 13 groups that would decode1787 * to 52 bytes max. The length byte 'A'-'Z' corresponds1788 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1789 */1790int llen, used;1791unsigned long size = *sz_p;1792char*buffer = *buf_p;1793int patch_method;1794unsigned long origlen;1795char*data = NULL;1796int hunk_size =0;1797struct fragment *frag;17981799 llen =linelen(buffer, size);1800 used = llen;18011802*status_p =0;18031804if(starts_with(buffer,"delta ")) {1805 patch_method = BINARY_DELTA_DEFLATED;1806 origlen =strtoul(buffer +6, NULL,10);1807}1808else if(starts_with(buffer,"literal ")) {1809 patch_method = BINARY_LITERAL_DEFLATED;1810 origlen =strtoul(buffer +8, NULL,10);1811}1812else1813return NULL;18141815 state_linenr++;1816 buffer += llen;1817while(1) {1818int byte_length, max_byte_length, newsize;1819 llen =linelen(buffer, size);1820 used += llen;1821 state_linenr++;1822if(llen ==1) {1823/* consume the blank line */1824 buffer++;1825 size--;1826break;1827}1828/*1829 * Minimum line is "A00000\n" which is 7-byte long,1830 * and the line length must be multiple of 5 plus 2.1831 */1832if((llen <7) || (llen-2) %5)1833goto corrupt;1834 max_byte_length = (llen -2) /5*4;1835 byte_length = *buffer;1836if('A'<= byte_length && byte_length <='Z')1837 byte_length = byte_length -'A'+1;1838else if('a'<= byte_length && byte_length <='z')1839 byte_length = byte_length -'a'+27;1840else1841goto corrupt;1842/* if the input length was not multiple of 4, we would1843 * have filler at the end but the filler should never1844 * exceed 3 bytes1845 */1846if(max_byte_length < byte_length ||1847 byte_length <= max_byte_length -4)1848goto corrupt;1849 newsize = hunk_size + byte_length;1850 data =xrealloc(data, newsize);1851if(decode_85(data + hunk_size, buffer +1, byte_length))1852goto corrupt;1853 hunk_size = newsize;1854 buffer += llen;1855 size -= llen;1856}18571858 frag =xcalloc(1,sizeof(*frag));1859 frag->patch =inflate_it(data, hunk_size, origlen);1860 frag->free_patch =1;1861if(!frag->patch)1862goto corrupt;1863free(data);1864 frag->size = origlen;1865*buf_p = buffer;1866*sz_p = size;1867*used_p = used;1868 frag->binary_patch_method = patch_method;1869return frag;18701871 corrupt:1872free(data);1873*status_p = -1;1874error(_("corrupt binary patch at line%d: %.*s"),1875 state_linenr-1, llen-1, buffer);1876return NULL;1877}18781879/*1880 * Returns:1881 * -1 in case of error,1882 * the length of the parsed binary patch otherwise1883 */1884static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1885{1886/*1887 * We have read "GIT binary patch\n"; what follows is a line1888 * that says the patch method (currently, either "literal" or1889 * "delta") and the length of data before deflating; a1890 * sequence of 'length-byte' followed by base-85 encoded data1891 * follows.1892 *1893 * When a binary patch is reversible, there is another binary1894 * hunk in the same format, starting with patch method (either1895 * "literal" or "delta") with the length of data, and a sequence1896 * of length-byte + base-85 encoded data, terminated with another1897 * empty line. This data, when applied to the postimage, produces1898 * the preimage.1899 */1900struct fragment *forward;1901struct fragment *reverse;1902int status;1903int used, used_1;19041905 forward =parse_binary_hunk(&buffer, &size, &status, &used);1906if(!forward && !status)1907/* there has to be one hunk (forward hunk) */1908returnerror(_("unrecognized binary patch at line%d"), state_linenr-1);1909if(status)1910/* otherwise we already gave an error message */1911return status;19121913 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1914if(reverse)1915 used += used_1;1916else if(status) {1917/*1918 * Not having reverse hunk is not an error, but having1919 * a corrupt reverse hunk is.1920 */1921free((void*) forward->patch);1922free(forward);1923return status;1924}1925 forward->next = reverse;1926 patch->fragments = forward;1927 patch->is_binary =1;1928return used;1929}19301931static voidprefix_one(struct apply_state *state,char**name)1932{1933char*old_name = *name;1934if(!old_name)1935return;1936*name =xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));1937free(old_name);1938}19391940static voidprefix_patch(struct apply_state *state,struct patch *p)1941{1942if(!state->prefix || p->is_toplevel_relative)1943return;1944prefix_one(state, &p->new_name);1945prefix_one(state, &p->old_name);1946}19471948/*1949 * include/exclude1950 */19511952static struct string_list limit_by_name;1953static int has_include;1954static voidadd_name_limit(const char*name,int exclude)1955{1956struct string_list_item *it;19571958 it =string_list_append(&limit_by_name, name);1959 it->util = exclude ? NULL : (void*)1;1960}19611962static intuse_patch(struct apply_state *state,struct patch *p)1963{1964const char*pathname = p->new_name ? p->new_name : p->old_name;1965int i;19661967/* Paths outside are not touched regardless of "--include" */1968if(0< state->prefix_length) {1969int pathlen =strlen(pathname);1970if(pathlen <= state->prefix_length ||1971memcmp(state->prefix, pathname, state->prefix_length))1972return0;1973}19741975/* See if it matches any of exclude/include rule */1976for(i =0; i < limit_by_name.nr; i++) {1977struct string_list_item *it = &limit_by_name.items[i];1978if(!wildmatch(it->string, pathname,0, NULL))1979return(it->util != NULL);1980}19811982/*1983 * If we had any include, a path that does not match any rule is1984 * not used. Otherwise, we saw bunch of exclude rules (or none)1985 * and such a path is used.1986 */1987return!has_include;1988}198919901991/*1992 * Read the patch text in "buffer" that extends for "size" bytes; stop1993 * reading after seeing a single patch (i.e. changes to a single file).1994 * Create fragments (i.e. patch hunks) and hang them to the given patch.1995 * Return the number of bytes consumed, so that the caller can call us1996 * again for the next patch.1997 */1998static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)1999{2000int hdrsize, patchsize;2001int offset =find_header(state, buffer, size, &hdrsize, patch);20022003if(offset <0)2004return offset;20052006prefix_patch(state, patch);20072008if(!use_patch(state, patch))2009 patch->ws_rule =0;2010else2011 patch->ws_rule =whitespace_rule(patch->new_name2012? patch->new_name2013: patch->old_name);20142015 patchsize =parse_single_patch(state,2016 buffer + offset + hdrsize,2017 size - offset - hdrsize,2018 patch);20192020if(!patchsize) {2021static const char git_binary[] ="GIT binary patch\n";2022int hd = hdrsize + offset;2023unsigned long llen =linelen(buffer + hd, size - hd);20242025if(llen ==sizeof(git_binary) -1&&2026!memcmp(git_binary, buffer + hd, llen)) {2027int used;2028 state_linenr++;2029 used =parse_binary(buffer + hd + llen,2030 size - hd - llen, patch);2031if(used <0)2032return-1;2033if(used)2034 patchsize = used + llen;2035else2036 patchsize =0;2037}2038else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2039static const char*binhdr[] = {2040"Binary files ",2041"Files ",2042 NULL,2043};2044int i;2045for(i =0; binhdr[i]; i++) {2046int len =strlen(binhdr[i]);2047if(len < size - hd &&2048!memcmp(binhdr[i], buffer + hd, len)) {2049 state_linenr++;2050 patch->is_binary =1;2051 patchsize = llen;2052break;2053}2054}2055}20562057/* Empty patch cannot be applied if it is a text patch2058 * without metadata change. A binary patch appears2059 * empty to us here.2060 */2061if((apply || state->check) &&2062(!patch->is_binary && !metadata_changes(patch)))2063die(_("patch with only garbage at line%d"), state_linenr);2064}20652066return offset + hdrsize + patchsize;2067}20682069#define swap(a,b) myswap((a),(b),sizeof(a))20702071#define myswap(a, b, size) do { \2072 unsigned char mytmp[size]; \2073 memcpy(mytmp, &a, size); \2074 memcpy(&a, &b, size); \2075 memcpy(&b, mytmp, size); \2076} while (0)20772078static voidreverse_patches(struct patch *p)2079{2080for(; p; p = p->next) {2081struct fragment *frag = p->fragments;20822083swap(p->new_name, p->old_name);2084swap(p->new_mode, p->old_mode);2085swap(p->is_new, p->is_delete);2086swap(p->lines_added, p->lines_deleted);2087swap(p->old_sha1_prefix, p->new_sha1_prefix);20882089for(; frag; frag = frag->next) {2090swap(frag->newpos, frag->oldpos);2091swap(frag->newlines, frag->oldlines);2092}2093}2094}20952096static const char pluses[] =2097"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2098static const char minuses[]=2099"----------------------------------------------------------------------";21002101static voidshow_stats(struct patch *patch)2102{2103struct strbuf qname = STRBUF_INIT;2104char*cp = patch->new_name ? patch->new_name : patch->old_name;2105int max, add, del;21062107quote_c_style(cp, &qname, NULL,0);21082109/*2110 * "scale" the filename2111 */2112 max = max_len;2113if(max >50)2114 max =50;21152116if(qname.len > max) {2117 cp =strchr(qname.buf + qname.len +3- max,'/');2118if(!cp)2119 cp = qname.buf + qname.len +3- max;2120strbuf_splice(&qname,0, cp - qname.buf,"...",3);2121}21222123if(patch->is_binary) {2124printf(" %-*s | Bin\n", max, qname.buf);2125strbuf_release(&qname);2126return;2127}21282129printf(" %-*s |", max, qname.buf);2130strbuf_release(&qname);21312132/*2133 * scale the add/delete2134 */2135 max = max + max_change >70?70- max : max_change;2136 add = patch->lines_added;2137 del = patch->lines_deleted;21382139if(max_change >0) {2140int total = ((add + del) * max + max_change /2) / max_change;2141 add = (add * max + max_change /2) / max_change;2142 del = total - add;2143}2144printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2145 add, pluses, del, minuses);2146}21472148static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2149{2150switch(st->st_mode & S_IFMT) {2151case S_IFLNK:2152if(strbuf_readlink(buf, path, st->st_size) <0)2153returnerror(_("unable to read symlink%s"), path);2154return0;2155case S_IFREG:2156if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2157returnerror(_("unable to open or read%s"), path);2158convert_to_git(path, buf->buf, buf->len, buf,0);2159return0;2160default:2161return-1;2162}2163}21642165/*2166 * Update the preimage, and the common lines in postimage,2167 * from buffer buf of length len. If postlen is 0 the postimage2168 * is updated in place, otherwise it's updated on a new buffer2169 * of length postlen2170 */21712172static voidupdate_pre_post_images(struct image *preimage,2173struct image *postimage,2174char*buf,2175size_t len,size_t postlen)2176{2177int i, ctx, reduced;2178char*new, *old, *fixed;2179struct image fixed_preimage;21802181/*2182 * Update the preimage with whitespace fixes. Note that we2183 * are not losing preimage->buf -- apply_one_fragment() will2184 * free "oldlines".2185 */2186prepare_image(&fixed_preimage, buf, len,1);2187assert(postlen2188? fixed_preimage.nr == preimage->nr2189: fixed_preimage.nr <= preimage->nr);2190for(i =0; i < fixed_preimage.nr; i++)2191 fixed_preimage.line[i].flag = preimage->line[i].flag;2192free(preimage->line_allocated);2193*preimage = fixed_preimage;21942195/*2196 * Adjust the common context lines in postimage. This can be2197 * done in-place when we are shrinking it with whitespace2198 * fixing, but needs a new buffer when ignoring whitespace or2199 * expanding leading tabs to spaces.2200 *2201 * We trust the caller to tell us if the update can be done2202 * in place (postlen==0) or not.2203 */2204 old = postimage->buf;2205if(postlen)2206new= postimage->buf =xmalloc(postlen);2207else2208new= old;2209 fixed = preimage->buf;22102211for(i = reduced = ctx =0; i < postimage->nr; i++) {2212size_t l_len = postimage->line[i].len;2213if(!(postimage->line[i].flag & LINE_COMMON)) {2214/* an added line -- no counterparts in preimage */2215memmove(new, old, l_len);2216 old += l_len;2217new+= l_len;2218continue;2219}22202221/* a common context -- skip it in the original postimage */2222 old += l_len;22232224/* and find the corresponding one in the fixed preimage */2225while(ctx < preimage->nr &&2226!(preimage->line[ctx].flag & LINE_COMMON)) {2227 fixed += preimage->line[ctx].len;2228 ctx++;2229}22302231/*2232 * preimage is expected to run out, if the caller2233 * fixed addition of trailing blank lines.2234 */2235if(preimage->nr <= ctx) {2236 reduced++;2237continue;2238}22392240/* and copy it in, while fixing the line length */2241 l_len = preimage->line[ctx].len;2242memcpy(new, fixed, l_len);2243new+= l_len;2244 fixed += l_len;2245 postimage->line[i].len = l_len;2246 ctx++;2247}22482249if(postlen2250? postlen <new- postimage->buf2251: postimage->len <new- postimage->buf)2252die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2253(int)postlen, (int) postimage->len, (int)(new- postimage->buf));22542255/* Fix the length of the whole thing */2256 postimage->len =new- postimage->buf;2257 postimage->nr -= reduced;2258}22592260static intline_by_line_fuzzy_match(struct image *img,2261struct image *preimage,2262struct image *postimage,2263unsigned longtry,2264int try_lno,2265int preimage_limit)2266{2267int i;2268size_t imgoff =0;2269size_t preoff =0;2270size_t postlen = postimage->len;2271size_t extra_chars;2272char*buf;2273char*preimage_eof;2274char*preimage_end;2275struct strbuf fixed;2276char*fixed_buf;2277size_t fixed_len;22782279for(i =0; i < preimage_limit; i++) {2280size_t prelen = preimage->line[i].len;2281size_t imglen = img->line[try_lno+i].len;22822283if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2284 preimage->buf + preoff, prelen))2285return0;2286if(preimage->line[i].flag & LINE_COMMON)2287 postlen += imglen - prelen;2288 imgoff += imglen;2289 preoff += prelen;2290}22912292/*2293 * Ok, the preimage matches with whitespace fuzz.2294 *2295 * imgoff now holds the true length of the target that2296 * matches the preimage before the end of the file.2297 *2298 * Count the number of characters in the preimage that fall2299 * beyond the end of the file and make sure that all of them2300 * are whitespace characters. (This can only happen if2301 * we are removing blank lines at the end of the file.)2302 */2303 buf = preimage_eof = preimage->buf + preoff;2304for( ; i < preimage->nr; i++)2305 preoff += preimage->line[i].len;2306 preimage_end = preimage->buf + preoff;2307for( ; buf < preimage_end; buf++)2308if(!isspace(*buf))2309return0;23102311/*2312 * Update the preimage and the common postimage context2313 * lines to use the same whitespace as the target.2314 * If whitespace is missing in the target (i.e.2315 * if the preimage extends beyond the end of the file),2316 * use the whitespace from the preimage.2317 */2318 extra_chars = preimage_end - preimage_eof;2319strbuf_init(&fixed, imgoff + extra_chars);2320strbuf_add(&fixed, img->buf +try, imgoff);2321strbuf_add(&fixed, preimage_eof, extra_chars);2322 fixed_buf =strbuf_detach(&fixed, &fixed_len);2323update_pre_post_images(preimage, postimage,2324 fixed_buf, fixed_len, postlen);2325return1;2326}23272328static intmatch_fragment(struct image *img,2329struct image *preimage,2330struct image *postimage,2331unsigned longtry,2332int try_lno,2333unsigned ws_rule,2334int match_beginning,int match_end)2335{2336int i;2337char*fixed_buf, *buf, *orig, *target;2338struct strbuf fixed;2339size_t fixed_len, postlen;2340int preimage_limit;23412342if(preimage->nr + try_lno <= img->nr) {2343/*2344 * The hunk falls within the boundaries of img.2345 */2346 preimage_limit = preimage->nr;2347if(match_end && (preimage->nr + try_lno != img->nr))2348return0;2349}else if(ws_error_action == correct_ws_error &&2350(ws_rule & WS_BLANK_AT_EOF)) {2351/*2352 * This hunk extends beyond the end of img, and we are2353 * removing blank lines at the end of the file. This2354 * many lines from the beginning of the preimage must2355 * match with img, and the remainder of the preimage2356 * must be blank.2357 */2358 preimage_limit = img->nr - try_lno;2359}else{2360/*2361 * The hunk extends beyond the end of the img and2362 * we are not removing blanks at the end, so we2363 * should reject the hunk at this position.2364 */2365return0;2366}23672368if(match_beginning && try_lno)2369return0;23702371/* Quick hash check */2372for(i =0; i < preimage_limit; i++)2373if((img->line[try_lno + i].flag & LINE_PATCHED) ||2374(preimage->line[i].hash != img->line[try_lno + i].hash))2375return0;23762377if(preimage_limit == preimage->nr) {2378/*2379 * Do we have an exact match? If we were told to match2380 * at the end, size must be exactly at try+fragsize,2381 * otherwise try+fragsize must be still within the preimage,2382 * and either case, the old piece should match the preimage2383 * exactly.2384 */2385if((match_end2386? (try+ preimage->len == img->len)2387: (try+ preimage->len <= img->len)) &&2388!memcmp(img->buf +try, preimage->buf, preimage->len))2389return1;2390}else{2391/*2392 * The preimage extends beyond the end of img, so2393 * there cannot be an exact match.2394 *2395 * There must be one non-blank context line that match2396 * a line before the end of img.2397 */2398char*buf_end;23992400 buf = preimage->buf;2401 buf_end = buf;2402for(i =0; i < preimage_limit; i++)2403 buf_end += preimage->line[i].len;24042405for( ; buf < buf_end; buf++)2406if(!isspace(*buf))2407break;2408if(buf == buf_end)2409return0;2410}24112412/*2413 * No exact match. If we are ignoring whitespace, run a line-by-line2414 * fuzzy matching. We collect all the line length information because2415 * we need it to adjust whitespace if we match.2416 */2417if(ws_ignore_action == ignore_ws_change)2418returnline_by_line_fuzzy_match(img, preimage, postimage,2419try, try_lno, preimage_limit);24202421if(ws_error_action != correct_ws_error)2422return0;24232424/*2425 * The hunk does not apply byte-by-byte, but the hash says2426 * it might with whitespace fuzz. We weren't asked to2427 * ignore whitespace, we were asked to correct whitespace2428 * errors, so let's try matching after whitespace correction.2429 *2430 * While checking the preimage against the target, whitespace2431 * errors in both fixed, we count how large the corresponding2432 * postimage needs to be. The postimage prepared by2433 * apply_one_fragment() has whitespace errors fixed on added2434 * lines already, but the common lines were propagated as-is,2435 * which may become longer when their whitespace errors are2436 * fixed.2437 */24382439/* First count added lines in postimage */2440 postlen =0;2441for(i =0; i < postimage->nr; i++) {2442if(!(postimage->line[i].flag & LINE_COMMON))2443 postlen += postimage->line[i].len;2444}24452446/*2447 * The preimage may extend beyond the end of the file,2448 * but in this loop we will only handle the part of the2449 * preimage that falls within the file.2450 */2451strbuf_init(&fixed, preimage->len +1);2452 orig = preimage->buf;2453 target = img->buf +try;2454for(i =0; i < preimage_limit; i++) {2455size_t oldlen = preimage->line[i].len;2456size_t tgtlen = img->line[try_lno + i].len;2457size_t fixstart = fixed.len;2458struct strbuf tgtfix;2459int match;24602461/* Try fixing the line in the preimage */2462ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24632464/* Try fixing the line in the target */2465strbuf_init(&tgtfix, tgtlen);2466ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);24672468/*2469 * If they match, either the preimage was based on2470 * a version before our tree fixed whitespace breakage,2471 * or we are lacking a whitespace-fix patch the tree2472 * the preimage was based on already had (i.e. target2473 * has whitespace breakage, the preimage doesn't).2474 * In either case, we are fixing the whitespace breakages2475 * so we might as well take the fix together with their2476 * real change.2477 */2478 match = (tgtfix.len == fixed.len - fixstart &&2479!memcmp(tgtfix.buf, fixed.buf + fixstart,2480 fixed.len - fixstart));24812482/* Add the length if this is common with the postimage */2483if(preimage->line[i].flag & LINE_COMMON)2484 postlen += tgtfix.len;24852486strbuf_release(&tgtfix);2487if(!match)2488goto unmatch_exit;24892490 orig += oldlen;2491 target += tgtlen;2492}249324942495/*2496 * Now handle the lines in the preimage that falls beyond the2497 * end of the file (if any). They will only match if they are2498 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2499 * false).2500 */2501for( ; i < preimage->nr; i++) {2502size_t fixstart = fixed.len;/* start of the fixed preimage */2503size_t oldlen = preimage->line[i].len;2504int j;25052506/* Try fixing the line in the preimage */2507ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25082509for(j = fixstart; j < fixed.len; j++)2510if(!isspace(fixed.buf[j]))2511goto unmatch_exit;25122513 orig += oldlen;2514}25152516/*2517 * Yes, the preimage is based on an older version that still2518 * has whitespace breakages unfixed, and fixing them makes the2519 * hunk match. Update the context lines in the postimage.2520 */2521 fixed_buf =strbuf_detach(&fixed, &fixed_len);2522if(postlen < postimage->len)2523 postlen =0;2524update_pre_post_images(preimage, postimage,2525 fixed_buf, fixed_len, postlen);2526return1;25272528 unmatch_exit:2529strbuf_release(&fixed);2530return0;2531}25322533static intfind_pos(struct image *img,2534struct image *preimage,2535struct image *postimage,2536int line,2537unsigned ws_rule,2538int match_beginning,int match_end)2539{2540int i;2541unsigned long backwards, forwards,try;2542int backwards_lno, forwards_lno, try_lno;25432544/*2545 * If match_beginning or match_end is specified, there is no2546 * point starting from a wrong line that will never match and2547 * wander around and wait for a match at the specified end.2548 */2549if(match_beginning)2550 line =0;2551else if(match_end)2552 line = img->nr - preimage->nr;25532554/*2555 * Because the comparison is unsigned, the following test2556 * will also take care of a negative line number that can2557 * result when match_end and preimage is larger than the target.2558 */2559if((size_t) line > img->nr)2560 line = img->nr;25612562try=0;2563for(i =0; i < line; i++)2564try+= img->line[i].len;25652566/*2567 * There's probably some smart way to do this, but I'll leave2568 * that to the smart and beautiful people. I'm simple and stupid.2569 */2570 backwards =try;2571 backwards_lno = line;2572 forwards =try;2573 forwards_lno = line;2574 try_lno = line;25752576for(i =0; ; i++) {2577if(match_fragment(img, preimage, postimage,2578try, try_lno, ws_rule,2579 match_beginning, match_end))2580return try_lno;25812582 again:2583if(backwards_lno ==0&& forwards_lno == img->nr)2584break;25852586if(i &1) {2587if(backwards_lno ==0) {2588 i++;2589goto again;2590}2591 backwards_lno--;2592 backwards -= img->line[backwards_lno].len;2593try= backwards;2594 try_lno = backwards_lno;2595}else{2596if(forwards_lno == img->nr) {2597 i++;2598goto again;2599}2600 forwards += img->line[forwards_lno].len;2601 forwards_lno++;2602try= forwards;2603 try_lno = forwards_lno;2604}26052606}2607return-1;2608}26092610static voidremove_first_line(struct image *img)2611{2612 img->buf += img->line[0].len;2613 img->len -= img->line[0].len;2614 img->line++;2615 img->nr--;2616}26172618static voidremove_last_line(struct image *img)2619{2620 img->len -= img->line[--img->nr].len;2621}26222623/*2624 * The change from "preimage" and "postimage" has been found to2625 * apply at applied_pos (counts in line numbers) in "img".2626 * Update "img" to remove "preimage" and replace it with "postimage".2627 */2628static voidupdate_image(struct apply_state *state,2629struct image *img,2630int applied_pos,2631struct image *preimage,2632struct image *postimage)2633{2634/*2635 * remove the copy of preimage at offset in img2636 * and replace it with postimage2637 */2638int i, nr;2639size_t remove_count, insert_count, applied_at =0;2640char*result;2641int preimage_limit;26422643/*2644 * If we are removing blank lines at the end of img,2645 * the preimage may extend beyond the end.2646 * If that is the case, we must be careful only to2647 * remove the part of the preimage that falls within2648 * the boundaries of img. Initialize preimage_limit2649 * to the number of lines in the preimage that falls2650 * within the boundaries.2651 */2652 preimage_limit = preimage->nr;2653if(preimage_limit > img->nr - applied_pos)2654 preimage_limit = img->nr - applied_pos;26552656for(i =0; i < applied_pos; i++)2657 applied_at += img->line[i].len;26582659 remove_count =0;2660for(i =0; i < preimage_limit; i++)2661 remove_count += img->line[applied_pos + i].len;2662 insert_count = postimage->len;26632664/* Adjust the contents */2665 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2666memcpy(result, img->buf, applied_at);2667memcpy(result + applied_at, postimage->buf, postimage->len);2668memcpy(result + applied_at + postimage->len,2669 img->buf + (applied_at + remove_count),2670 img->len - (applied_at + remove_count));2671free(img->buf);2672 img->buf = result;2673 img->len += insert_count - remove_count;2674 result[img->len] ='\0';26752676/* Adjust the line table */2677 nr = img->nr + postimage->nr - preimage_limit;2678if(preimage_limit < postimage->nr) {2679/*2680 * NOTE: this knows that we never call remove_first_line()2681 * on anything other than pre/post image.2682 */2683REALLOC_ARRAY(img->line, nr);2684 img->line_allocated = img->line;2685}2686if(preimage_limit != postimage->nr)2687memmove(img->line + applied_pos + postimage->nr,2688 img->line + applied_pos + preimage_limit,2689(img->nr - (applied_pos + preimage_limit)) *2690sizeof(*img->line));2691memcpy(img->line + applied_pos,2692 postimage->line,2693 postimage->nr *sizeof(*img->line));2694if(!state->allow_overlap)2695for(i =0; i < postimage->nr; i++)2696 img->line[applied_pos + i].flag |= LINE_PATCHED;2697 img->nr = nr;2698}26992700/*2701 * Use the patch-hunk text in "frag" to prepare two images (preimage and2702 * postimage) for the hunk. Find lines that match "preimage" in "img" and2703 * replace the part of "img" with "postimage" text.2704 */2705static intapply_one_fragment(struct apply_state *state,2706struct image *img,struct fragment *frag,2707int inaccurate_eof,unsigned ws_rule,2708int nth_fragment)2709{2710int match_beginning, match_end;2711const char*patch = frag->patch;2712int size = frag->size;2713char*old, *oldlines;2714struct strbuf newlines;2715int new_blank_lines_at_end =0;2716int found_new_blank_lines_at_end =0;2717int hunk_linenr = frag->linenr;2718unsigned long leading, trailing;2719int pos, applied_pos;2720struct image preimage;2721struct image postimage;27222723memset(&preimage,0,sizeof(preimage));2724memset(&postimage,0,sizeof(postimage));2725 oldlines =xmalloc(size);2726strbuf_init(&newlines, size);27272728 old = oldlines;2729while(size >0) {2730char first;2731int len =linelen(patch, size);2732int plen;2733int added_blank_line =0;2734int is_blank_context =0;2735size_t start;27362737if(!len)2738break;27392740/*2741 * "plen" is how much of the line we should use for2742 * the actual patch data. Normally we just remove the2743 * first character on the line, but if the line is2744 * followed by "\ No newline", then we also remove the2745 * last one (which is the newline, of course).2746 */2747 plen = len -1;2748if(len < size && patch[len] =='\\')2749 plen--;2750 first = *patch;2751if(state->apply_in_reverse) {2752if(first =='-')2753 first ='+';2754else if(first =='+')2755 first ='-';2756}27572758switch(first) {2759case'\n':2760/* Newer GNU diff, empty context line */2761if(plen <0)2762/* ... followed by '\No newline'; nothing */2763break;2764*old++ ='\n';2765strbuf_addch(&newlines,'\n');2766add_line_info(&preimage,"\n",1, LINE_COMMON);2767add_line_info(&postimage,"\n",1, LINE_COMMON);2768 is_blank_context =1;2769break;2770case' ':2771if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2772ws_blank_line(patch +1, plen, ws_rule))2773 is_blank_context =1;2774case'-':2775memcpy(old, patch +1, plen);2776add_line_info(&preimage, old, plen,2777(first ==' '? LINE_COMMON :0));2778 old += plen;2779if(first =='-')2780break;2781/* Fall-through for ' ' */2782case'+':2783/* --no-add does not add new lines */2784if(first =='+'&& state->no_add)2785break;27862787 start = newlines.len;2788if(first !='+'||2789!whitespace_error ||2790 ws_error_action != correct_ws_error) {2791strbuf_add(&newlines, patch +1, plen);2792}2793else{2794ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2795}2796add_line_info(&postimage, newlines.buf + start, newlines.len - start,2797(first =='+'?0: LINE_COMMON));2798if(first =='+'&&2799(ws_rule & WS_BLANK_AT_EOF) &&2800ws_blank_line(patch +1, plen, ws_rule))2801 added_blank_line =1;2802break;2803case'@':case'\\':2804/* Ignore it, we already handled it */2805break;2806default:2807if(state->apply_verbosely)2808error(_("invalid start of line: '%c'"), first);2809 applied_pos = -1;2810goto out;2811}2812if(added_blank_line) {2813if(!new_blank_lines_at_end)2814 found_new_blank_lines_at_end = hunk_linenr;2815 new_blank_lines_at_end++;2816}2817else if(is_blank_context)2818;2819else2820 new_blank_lines_at_end =0;2821 patch += len;2822 size -= len;2823 hunk_linenr++;2824}2825if(inaccurate_eof &&2826 old > oldlines && old[-1] =='\n'&&2827 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2828 old--;2829strbuf_setlen(&newlines, newlines.len -1);2830}28312832 leading = frag->leading;2833 trailing = frag->trailing;28342835/*2836 * A hunk to change lines at the beginning would begin with2837 * @@ -1,L +N,M @@2838 * but we need to be careful. -U0 that inserts before the second2839 * line also has this pattern.2840 *2841 * And a hunk to add to an empty file would begin with2842 * @@ -0,0 +N,M @@2843 *2844 * In other words, a hunk that is (frag->oldpos <= 1) with or2845 * without leading context must match at the beginning.2846 */2847 match_beginning = (!frag->oldpos ||2848(frag->oldpos ==1&& !state->unidiff_zero));28492850/*2851 * A hunk without trailing lines must match at the end.2852 * However, we simply cannot tell if a hunk must match end2853 * from the lack of trailing lines if the patch was generated2854 * with unidiff without any context.2855 */2856 match_end = !state->unidiff_zero && !trailing;28572858 pos = frag->newpos ? (frag->newpos -1) :0;2859 preimage.buf = oldlines;2860 preimage.len = old - oldlines;2861 postimage.buf = newlines.buf;2862 postimage.len = newlines.len;2863 preimage.line = preimage.line_allocated;2864 postimage.line = postimage.line_allocated;28652866for(;;) {28672868 applied_pos =find_pos(img, &preimage, &postimage, pos,2869 ws_rule, match_beginning, match_end);28702871if(applied_pos >=0)2872break;28732874/* Am I at my context limits? */2875if((leading <= state->p_context) && (trailing <= state->p_context))2876break;2877if(match_beginning || match_end) {2878 match_beginning = match_end =0;2879continue;2880}28812882/*2883 * Reduce the number of context lines; reduce both2884 * leading and trailing if they are equal otherwise2885 * just reduce the larger context.2886 */2887if(leading >= trailing) {2888remove_first_line(&preimage);2889remove_first_line(&postimage);2890 pos--;2891 leading--;2892}2893if(trailing > leading) {2894remove_last_line(&preimage);2895remove_last_line(&postimage);2896 trailing--;2897}2898}28992900if(applied_pos >=0) {2901if(new_blank_lines_at_end &&2902 preimage.nr + applied_pos >= img->nr &&2903(ws_rule & WS_BLANK_AT_EOF) &&2904 ws_error_action != nowarn_ws_error) {2905record_ws_error(WS_BLANK_AT_EOF,"+",1,2906 found_new_blank_lines_at_end);2907if(ws_error_action == correct_ws_error) {2908while(new_blank_lines_at_end--)2909remove_last_line(&postimage);2910}2911/*2912 * We would want to prevent write_out_results()2913 * from taking place in apply_patch() that follows2914 * the callchain led us here, which is:2915 * apply_patch->check_patch_list->check_patch->2916 * apply_data->apply_fragments->apply_one_fragment2917 */2918if(ws_error_action == die_on_ws_error)2919 apply =0;2920}29212922if(state->apply_verbosely && applied_pos != pos) {2923int offset = applied_pos - pos;2924if(state->apply_in_reverse)2925 offset =0- offset;2926fprintf_ln(stderr,2927Q_("Hunk #%dsucceeded at%d(offset%dline).",2928"Hunk #%dsucceeded at%d(offset%dlines).",2929 offset),2930 nth_fragment, applied_pos +1, offset);2931}29322933/*2934 * Warn if it was necessary to reduce the number2935 * of context lines.2936 */2937if((leading != frag->leading) ||2938(trailing != frag->trailing))2939fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2940" to apply fragment at%d"),2941 leading, trailing, applied_pos+1);2942update_image(state, img, applied_pos, &preimage, &postimage);2943}else{2944if(state->apply_verbosely)2945error(_("while searching for:\n%.*s"),2946(int)(old - oldlines), oldlines);2947}29482949out:2950free(oldlines);2951strbuf_release(&newlines);2952free(preimage.line_allocated);2953free(postimage.line_allocated);29542955return(applied_pos <0);2956}29572958static intapply_binary_fragment(struct apply_state *state,2959struct image *img,2960struct patch *patch)2961{2962struct fragment *fragment = patch->fragments;2963unsigned long len;2964void*dst;29652966if(!fragment)2967returnerror(_("missing binary patch data for '%s'"),2968 patch->new_name ?2969 patch->new_name :2970 patch->old_name);29712972/* Binary patch is irreversible without the optional second hunk */2973if(state->apply_in_reverse) {2974if(!fragment->next)2975returnerror("cannot reverse-apply a binary patch "2976"without the reverse hunk to '%s'",2977 patch->new_name2978? patch->new_name : patch->old_name);2979 fragment = fragment->next;2980}2981switch(fragment->binary_patch_method) {2982case BINARY_DELTA_DEFLATED:2983 dst =patch_delta(img->buf, img->len, fragment->patch,2984 fragment->size, &len);2985if(!dst)2986return-1;2987clear_image(img);2988 img->buf = dst;2989 img->len = len;2990return0;2991case BINARY_LITERAL_DEFLATED:2992clear_image(img);2993 img->len = fragment->size;2994 img->buf =xmemdupz(fragment->patch, img->len);2995return0;2996}2997return-1;2998}29993000/*3001 * Replace "img" with the result of applying the binary patch.3002 * The binary patch data itself in patch->fragment is still kept3003 * but the preimage prepared by the caller in "img" is freed here3004 * or in the helper function apply_binary_fragment() this calls.3005 */3006static intapply_binary(struct apply_state *state,3007struct image *img,3008struct patch *patch)3009{3010const char*name = patch->old_name ? patch->old_name : patch->new_name;3011unsigned char sha1[20];30123013/*3014 * For safety, we require patch index line to contain3015 * full 40-byte textual SHA1 for old and new, at least for now.3016 */3017if(strlen(patch->old_sha1_prefix) !=40||3018strlen(patch->new_sha1_prefix) !=40||3019get_sha1_hex(patch->old_sha1_prefix, sha1) ||3020get_sha1_hex(patch->new_sha1_prefix, sha1))3021returnerror("cannot apply binary patch to '%s' "3022"without full index line", name);30233024if(patch->old_name) {3025/*3026 * See if the old one matches what the patch3027 * applies to.3028 */3029hash_sha1_file(img->buf, img->len, blob_type, sha1);3030if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3031returnerror("the patch applies to '%s' (%s), "3032"which does not match the "3033"current contents.",3034 name,sha1_to_hex(sha1));3035}3036else{3037/* Otherwise, the old one must be empty. */3038if(img->len)3039returnerror("the patch applies to an empty "3040"'%s' but it is not empty", name);3041}30423043get_sha1_hex(patch->new_sha1_prefix, sha1);3044if(is_null_sha1(sha1)) {3045clear_image(img);3046return0;/* deletion patch */3047}30483049if(has_sha1_file(sha1)) {3050/* We already have the postimage */3051enum object_type type;3052unsigned long size;3053char*result;30543055 result =read_sha1_file(sha1, &type, &size);3056if(!result)3057returnerror("the necessary postimage%sfor "3058"'%s' cannot be read",3059 patch->new_sha1_prefix, name);3060clear_image(img);3061 img->buf = result;3062 img->len = size;3063}else{3064/*3065 * We have verified buf matches the preimage;3066 * apply the patch data to it, which is stored3067 * in the patch->fragments->{patch,size}.3068 */3069if(apply_binary_fragment(state, img, patch))3070returnerror(_("binary patch does not apply to '%s'"),3071 name);30723073/* verify that the result matches */3074hash_sha1_file(img->buf, img->len, blob_type, sha1);3075if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3076returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3077 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3078}30793080return0;3081}30823083static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3084{3085struct fragment *frag = patch->fragments;3086const char*name = patch->old_name ? patch->old_name : patch->new_name;3087unsigned ws_rule = patch->ws_rule;3088unsigned inaccurate_eof = patch->inaccurate_eof;3089int nth =0;30903091if(patch->is_binary)3092returnapply_binary(state, img, patch);30933094while(frag) {3095 nth++;3096if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3097error(_("patch failed:%s:%ld"), name, frag->oldpos);3098if(!state->apply_with_reject)3099return-1;3100 frag->rejected =1;3101}3102 frag = frag->next;3103}3104return0;3105}31063107static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3108{3109if(S_ISGITLINK(mode)) {3110strbuf_grow(buf,100);3111strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3112}else{3113enum object_type type;3114unsigned long sz;3115char*result;31163117 result =read_sha1_file(sha1, &type, &sz);3118if(!result)3119return-1;3120/* XXX read_sha1_file NUL-terminates */3121strbuf_attach(buf, result, sz, sz +1);3122}3123return0;3124}31253126static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3127{3128if(!ce)3129return0;3130returnread_blob_object(buf, ce->sha1, ce->ce_mode);3131}31323133static struct patch *in_fn_table(const char*name)3134{3135struct string_list_item *item;31363137if(name == NULL)3138return NULL;31393140 item =string_list_lookup(&fn_table, name);3141if(item != NULL)3142return(struct patch *)item->util;31433144return NULL;3145}31463147/*3148 * item->util in the filename table records the status of the path.3149 * Usually it points at a patch (whose result records the contents3150 * of it after applying it), but it could be PATH_WAS_DELETED for a3151 * path that a previously applied patch has already removed, or3152 * PATH_TO_BE_DELETED for a path that a later patch would remove.3153 *3154 * The latter is needed to deal with a case where two paths A and B3155 * are swapped by first renaming A to B and then renaming B to A;3156 * moving A to B should not be prevented due to presence of B as we3157 * will remove it in a later patch.3158 */3159#define PATH_TO_BE_DELETED ((struct patch *) -2)3160#define PATH_WAS_DELETED ((struct patch *) -1)31613162static intto_be_deleted(struct patch *patch)3163{3164return patch == PATH_TO_BE_DELETED;3165}31663167static intwas_deleted(struct patch *patch)3168{3169return patch == PATH_WAS_DELETED;3170}31713172static voidadd_to_fn_table(struct patch *patch)3173{3174struct string_list_item *item;31753176/*3177 * Always add new_name unless patch is a deletion3178 * This should cover the cases for normal diffs,3179 * file creations and copies3180 */3181if(patch->new_name != NULL) {3182 item =string_list_insert(&fn_table, patch->new_name);3183 item->util = patch;3184}31853186/*3187 * store a failure on rename/deletion cases because3188 * later chunks shouldn't patch old names3189 */3190if((patch->new_name == NULL) || (patch->is_rename)) {3191 item =string_list_insert(&fn_table, patch->old_name);3192 item->util = PATH_WAS_DELETED;3193}3194}31953196static voidprepare_fn_table(struct patch *patch)3197{3198/*3199 * store information about incoming file deletion3200 */3201while(patch) {3202if((patch->new_name == NULL) || (patch->is_rename)) {3203struct string_list_item *item;3204 item =string_list_insert(&fn_table, patch->old_name);3205 item->util = PATH_TO_BE_DELETED;3206}3207 patch = patch->next;3208}3209}32103211static intcheckout_target(struct index_state *istate,3212struct cache_entry *ce,struct stat *st)3213{3214struct checkout costate;32153216memset(&costate,0,sizeof(costate));3217 costate.base_dir ="";3218 costate.refresh_cache =1;3219 costate.istate = istate;3220if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3221returnerror(_("cannot checkout%s"), ce->name);3222return0;3223}32243225static struct patch *previous_patch(struct patch *patch,int*gone)3226{3227struct patch *previous;32283229*gone =0;3230if(patch->is_copy || patch->is_rename)3231return NULL;/* "git" patches do not depend on the order */32323233 previous =in_fn_table(patch->old_name);3234if(!previous)3235return NULL;32363237if(to_be_deleted(previous))3238return NULL;/* the deletion hasn't happened yet */32393240if(was_deleted(previous))3241*gone =1;32423243return previous;3244}32453246static intverify_index_match(const struct cache_entry *ce,struct stat *st)3247{3248if(S_ISGITLINK(ce->ce_mode)) {3249if(!S_ISDIR(st->st_mode))3250return-1;3251return0;3252}3253returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3254}32553256#define SUBMODULE_PATCH_WITHOUT_INDEX 132573258static intload_patch_target(struct apply_state *state,3259struct strbuf *buf,3260const struct cache_entry *ce,3261struct stat *st,3262const char*name,3263unsigned expected_mode)3264{3265if(state->cached || state->check_index) {3266if(read_file_or_gitlink(ce, buf))3267returnerror(_("read of%sfailed"), name);3268}else if(name) {3269if(S_ISGITLINK(expected_mode)) {3270if(ce)3271returnread_file_or_gitlink(ce, buf);3272else3273return SUBMODULE_PATCH_WITHOUT_INDEX;3274}else if(has_symlink_leading_path(name,strlen(name))) {3275returnerror(_("reading from '%s' beyond a symbolic link"), name);3276}else{3277if(read_old_data(st, name, buf))3278returnerror(_("read of%sfailed"), name);3279}3280}3281return0;3282}32833284/*3285 * We are about to apply "patch"; populate the "image" with the3286 * current version we have, from the working tree or from the index,3287 * depending on the situation e.g. --cached/--index. If we are3288 * applying a non-git patch that incrementally updates the tree,3289 * we read from the result of a previous diff.3290 */3291static intload_preimage(struct apply_state *state,3292struct image *image,3293struct patch *patch,struct stat *st,3294const struct cache_entry *ce)3295{3296struct strbuf buf = STRBUF_INIT;3297size_t len;3298char*img;3299struct patch *previous;3300int status;33013302 previous =previous_patch(patch, &status);3303if(status)3304returnerror(_("path%shas been renamed/deleted"),3305 patch->old_name);3306if(previous) {3307/* We have a patched copy in memory; use that. */3308strbuf_add(&buf, previous->result, previous->resultsize);3309}else{3310 status =load_patch_target(state, &buf, ce, st,3311 patch->old_name, patch->old_mode);3312if(status <0)3313return status;3314else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3315/*3316 * There is no way to apply subproject3317 * patch without looking at the index.3318 * NEEDSWORK: shouldn't this be flagged3319 * as an error???3320 */3321free_fragment_list(patch->fragments);3322 patch->fragments = NULL;3323}else if(status) {3324returnerror(_("read of%sfailed"), patch->old_name);3325}3326}33273328 img =strbuf_detach(&buf, &len);3329prepare_image(image, img, len, !patch->is_binary);3330return0;3331}33323333static intthree_way_merge(struct image *image,3334char*path,3335const unsigned char*base,3336const unsigned char*ours,3337const unsigned char*theirs)3338{3339 mmfile_t base_file, our_file, their_file;3340 mmbuffer_t result = { NULL };3341int status;33423343read_mmblob(&base_file, base);3344read_mmblob(&our_file, ours);3345read_mmblob(&their_file, theirs);3346 status =ll_merge(&result, path,3347&base_file,"base",3348&our_file,"ours",3349&their_file,"theirs", NULL);3350free(base_file.ptr);3351free(our_file.ptr);3352free(their_file.ptr);3353if(status <0|| !result.ptr) {3354free(result.ptr);3355return-1;3356}3357clear_image(image);3358 image->buf = result.ptr;3359 image->len = result.size;33603361return status;3362}33633364/*3365 * When directly falling back to add/add three-way merge, we read from3366 * the current contents of the new_name. In no cases other than that3367 * this function will be called.3368 */3369static intload_current(struct apply_state *state,3370struct image *image,3371struct patch *patch)3372{3373struct strbuf buf = STRBUF_INIT;3374int status, pos;3375size_t len;3376char*img;3377struct stat st;3378struct cache_entry *ce;3379char*name = patch->new_name;3380unsigned mode = patch->new_mode;33813382if(!patch->is_new)3383die("BUG: patch to%sis not a creation", patch->old_name);33843385 pos =cache_name_pos(name,strlen(name));3386if(pos <0)3387returnerror(_("%s: does not exist in index"), name);3388 ce = active_cache[pos];3389if(lstat(name, &st)) {3390if(errno != ENOENT)3391returnerror(_("%s:%s"), name,strerror(errno));3392if(checkout_target(&the_index, ce, &st))3393return-1;3394}3395if(verify_index_match(ce, &st))3396returnerror(_("%s: does not match index"), name);33973398 status =load_patch_target(state, &buf, ce, &st, name, mode);3399if(status <0)3400return status;3401else if(status)3402return-1;3403 img =strbuf_detach(&buf, &len);3404prepare_image(image, img, len, !patch->is_binary);3405return0;3406}34073408static inttry_threeway(struct apply_state *state,3409struct image *image,3410struct patch *patch,3411struct stat *st,3412const struct cache_entry *ce)3413{3414unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3415struct strbuf buf = STRBUF_INIT;3416size_t len;3417int status;3418char*img;3419struct image tmp_image;34203421/* No point falling back to 3-way merge in these cases */3422if(patch->is_delete ||3423S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3424return-1;34253426/* Preimage the patch was prepared for */3427if(patch->is_new)3428write_sha1_file("",0, blob_type, pre_sha1);3429else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3430read_blob_object(&buf, pre_sha1, patch->old_mode))3431returnerror("repository lacks the necessary blob to fall back on 3-way merge.");34323433fprintf(stderr,"Falling back to three-way merge...\n");34343435 img =strbuf_detach(&buf, &len);3436prepare_image(&tmp_image, img, len,1);3437/* Apply the patch to get the post image */3438if(apply_fragments(state, &tmp_image, patch) <0) {3439clear_image(&tmp_image);3440return-1;3441}3442/* post_sha1[] is theirs */3443write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3444clear_image(&tmp_image);34453446/* our_sha1[] is ours */3447if(patch->is_new) {3448if(load_current(state, &tmp_image, patch))3449returnerror("cannot read the current contents of '%s'",3450 patch->new_name);3451}else{3452if(load_preimage(state, &tmp_image, patch, st, ce))3453returnerror("cannot read the current contents of '%s'",3454 patch->old_name);3455}3456write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3457clear_image(&tmp_image);34583459/* in-core three-way merge between post and our using pre as base */3460 status =three_way_merge(image, patch->new_name,3461 pre_sha1, our_sha1, post_sha1);3462if(status <0) {3463fprintf(stderr,"Failed to fall back on three-way merge...\n");3464return status;3465}34663467if(status) {3468 patch->conflicted_threeway =1;3469if(patch->is_new)3470oidclr(&patch->threeway_stage[0]);3471else3472hashcpy(patch->threeway_stage[0].hash, pre_sha1);3473hashcpy(patch->threeway_stage[1].hash, our_sha1);3474hashcpy(patch->threeway_stage[2].hash, post_sha1);3475fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3476}else{3477fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3478}3479return0;3480}34813482static intapply_data(struct apply_state *state,struct patch *patch,3483struct stat *st,const struct cache_entry *ce)3484{3485struct image image;34863487if(load_preimage(state, &image, patch, st, ce) <0)3488return-1;34893490if(patch->direct_to_threeway ||3491apply_fragments(state, &image, patch) <0) {3492/* Note: with --reject, apply_fragments() returns 0 */3493if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3494return-1;3495}3496 patch->result = image.buf;3497 patch->resultsize = image.len;3498add_to_fn_table(patch);3499free(image.line_allocated);35003501if(0< patch->is_delete && patch->resultsize)3502returnerror(_("removal patch leaves file contents"));35033504return0;3505}35063507/*3508 * If "patch" that we are looking at modifies or deletes what we have,3509 * we would want it not to lose any local modification we have, either3510 * in the working tree or in the index.3511 *3512 * This also decides if a non-git patch is a creation patch or a3513 * modification to an existing empty file. We do not check the state3514 * of the current tree for a creation patch in this function; the caller3515 * check_patch() separately makes sure (and errors out otherwise) that3516 * the path the patch creates does not exist in the current tree.3517 */3518static intcheck_preimage(struct apply_state *state,3519struct patch *patch,3520struct cache_entry **ce,3521struct stat *st)3522{3523const char*old_name = patch->old_name;3524struct patch *previous = NULL;3525int stat_ret =0, status;3526unsigned st_mode =0;35273528if(!old_name)3529return0;35303531assert(patch->is_new <=0);3532 previous =previous_patch(patch, &status);35333534if(status)3535returnerror(_("path%shas been renamed/deleted"), old_name);3536if(previous) {3537 st_mode = previous->new_mode;3538}else if(!state->cached) {3539 stat_ret =lstat(old_name, st);3540if(stat_ret && errno != ENOENT)3541returnerror(_("%s:%s"), old_name,strerror(errno));3542}35433544if(state->check_index && !previous) {3545int pos =cache_name_pos(old_name,strlen(old_name));3546if(pos <0) {3547if(patch->is_new <0)3548goto is_new;3549returnerror(_("%s: does not exist in index"), old_name);3550}3551*ce = active_cache[pos];3552if(stat_ret <0) {3553if(checkout_target(&the_index, *ce, st))3554return-1;3555}3556if(!state->cached &&verify_index_match(*ce, st))3557returnerror(_("%s: does not match index"), old_name);3558if(state->cached)3559 st_mode = (*ce)->ce_mode;3560}else if(stat_ret <0) {3561if(patch->is_new <0)3562goto is_new;3563returnerror(_("%s:%s"), old_name,strerror(errno));3564}35653566if(!state->cached && !previous)3567 st_mode =ce_mode_from_stat(*ce, st->st_mode);35683569if(patch->is_new <0)3570 patch->is_new =0;3571if(!patch->old_mode)3572 patch->old_mode = st_mode;3573if((st_mode ^ patch->old_mode) & S_IFMT)3574returnerror(_("%s: wrong type"), old_name);3575if(st_mode != patch->old_mode)3576warning(_("%shas type%o, expected%o"),3577 old_name, st_mode, patch->old_mode);3578if(!patch->new_mode && !patch->is_delete)3579 patch->new_mode = st_mode;3580return0;35813582 is_new:3583 patch->is_new =1;3584 patch->is_delete =0;3585free(patch->old_name);3586 patch->old_name = NULL;3587return0;3588}358935903591#define EXISTS_IN_INDEX 13592#define EXISTS_IN_WORKTREE 235933594static intcheck_to_create(struct apply_state *state,3595const char*new_name,3596int ok_if_exists)3597{3598struct stat nst;35993600if(state->check_index &&3601cache_name_pos(new_name,strlen(new_name)) >=0&&3602!ok_if_exists)3603return EXISTS_IN_INDEX;3604if(state->cached)3605return0;36063607if(!lstat(new_name, &nst)) {3608if(S_ISDIR(nst.st_mode) || ok_if_exists)3609return0;3610/*3611 * A leading component of new_name might be a symlink3612 * that is going to be removed with this patch, but3613 * still pointing at somewhere that has the path.3614 * In such a case, path "new_name" does not exist as3615 * far as git is concerned.3616 */3617if(has_symlink_leading_path(new_name,strlen(new_name)))3618return0;36193620return EXISTS_IN_WORKTREE;3621}else if((errno != ENOENT) && (errno != ENOTDIR)) {3622returnerror("%s:%s", new_name,strerror(errno));3623}3624return0;3625}36263627/*3628 * We need to keep track of how symlinks in the preimage are3629 * manipulated by the patches. A patch to add a/b/c where a/b3630 * is a symlink should not be allowed to affect the directory3631 * the symlink points at, but if the same patch removes a/b,3632 * it is perfectly fine, as the patch removes a/b to make room3633 * to create a directory a/b so that a/b/c can be created.3634 */3635static struct string_list symlink_changes;3636#define SYMLINK_GOES_AWAY 013637#define SYMLINK_IN_RESULT 0236383639static uintptr_tregister_symlink_changes(const char*path,uintptr_t what)3640{3641struct string_list_item *ent;36423643 ent =string_list_lookup(&symlink_changes, path);3644if(!ent) {3645 ent =string_list_insert(&symlink_changes, path);3646 ent->util = (void*)0;3647}3648 ent->util = (void*)(what | ((uintptr_t)ent->util));3649return(uintptr_t)ent->util;3650}36513652static uintptr_tcheck_symlink_changes(const char*path)3653{3654struct string_list_item *ent;36553656 ent =string_list_lookup(&symlink_changes, path);3657if(!ent)3658return0;3659return(uintptr_t)ent->util;3660}36613662static voidprepare_symlink_changes(struct patch *patch)3663{3664for( ; patch; patch = patch->next) {3665if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3666(patch->is_rename || patch->is_delete))3667/* the symlink at patch->old_name is removed */3668register_symlink_changes(patch->old_name, SYMLINK_GOES_AWAY);36693670if(patch->new_name &&S_ISLNK(patch->new_mode))3671/* the symlink at patch->new_name is created or remains */3672register_symlink_changes(patch->new_name, SYMLINK_IN_RESULT);3673}3674}36753676static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3677{3678do{3679unsigned int change;36803681while(--name->len && name->buf[name->len] !='/')3682;/* scan backwards */3683if(!name->len)3684break;3685 name->buf[name->len] ='\0';3686 change =check_symlink_changes(name->buf);3687if(change & SYMLINK_IN_RESULT)3688return1;3689if(change & SYMLINK_GOES_AWAY)3690/*3691 * This cannot be "return 0", because we may3692 * see a new one created at a higher level.3693 */3694continue;36953696/* otherwise, check the preimage */3697if(state->check_index) {3698struct cache_entry *ce;36993700 ce =cache_file_exists(name->buf, name->len, ignore_case);3701if(ce &&S_ISLNK(ce->ce_mode))3702return1;3703}else{3704struct stat st;3705if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3706return1;3707}3708}while(1);3709return0;3710}37113712static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3713{3714int ret;3715struct strbuf name = STRBUF_INIT;37163717assert(*name_ !='\0');3718strbuf_addstr(&name, name_);3719 ret =path_is_beyond_symlink_1(state, &name);3720strbuf_release(&name);37213722return ret;3723}37243725static voiddie_on_unsafe_path(struct patch *patch)3726{3727const char*old_name = NULL;3728const char*new_name = NULL;3729if(patch->is_delete)3730 old_name = patch->old_name;3731else if(!patch->is_new && !patch->is_copy)3732 old_name = patch->old_name;3733if(!patch->is_delete)3734 new_name = patch->new_name;37353736if(old_name && !verify_path(old_name))3737die(_("invalid path '%s'"), old_name);3738if(new_name && !verify_path(new_name))3739die(_("invalid path '%s'"), new_name);3740}37413742/*3743 * Check and apply the patch in-core; leave the result in patch->result3744 * for the caller to write it out to the final destination.3745 */3746static intcheck_patch(struct apply_state *state,struct patch *patch)3747{3748struct stat st;3749const char*old_name = patch->old_name;3750const char*new_name = patch->new_name;3751const char*name = old_name ? old_name : new_name;3752struct cache_entry *ce = NULL;3753struct patch *tpatch;3754int ok_if_exists;3755int status;37563757 patch->rejected =1;/* we will drop this after we succeed */37583759 status =check_preimage(state, patch, &ce, &st);3760if(status)3761return status;3762 old_name = patch->old_name;37633764/*3765 * A type-change diff is always split into a patch to delete3766 * old, immediately followed by a patch to create new (see3767 * diff.c::run_diff()); in such a case it is Ok that the entry3768 * to be deleted by the previous patch is still in the working3769 * tree and in the index.3770 *3771 * A patch to swap-rename between A and B would first rename A3772 * to B and then rename B to A. While applying the first one,3773 * the presence of B should not stop A from getting renamed to3774 * B; ask to_be_deleted() about the later rename. Removal of3775 * B and rename from A to B is handled the same way by asking3776 * was_deleted().3777 */3778if((tpatch =in_fn_table(new_name)) &&3779(was_deleted(tpatch) ||to_be_deleted(tpatch)))3780 ok_if_exists =1;3781else3782 ok_if_exists =0;37833784if(new_name &&3785((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3786int err =check_to_create(state, new_name, ok_if_exists);37873788if(err && state->threeway) {3789 patch->direct_to_threeway =1;3790}else switch(err) {3791case0:3792break;/* happy */3793case EXISTS_IN_INDEX:3794returnerror(_("%s: already exists in index"), new_name);3795break;3796case EXISTS_IN_WORKTREE:3797returnerror(_("%s: already exists in working directory"),3798 new_name);3799default:3800return err;3801}38023803if(!patch->new_mode) {3804if(0< patch->is_new)3805 patch->new_mode = S_IFREG |0644;3806else3807 patch->new_mode = patch->old_mode;3808}3809}38103811if(new_name && old_name) {3812int same = !strcmp(old_name, new_name);3813if(!patch->new_mode)3814 patch->new_mode = patch->old_mode;3815if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3816if(same)3817returnerror(_("new mode (%o) of%sdoes not "3818"match old mode (%o)"),3819 patch->new_mode, new_name,3820 patch->old_mode);3821else3822returnerror(_("new mode (%o) of%sdoes not "3823"match old mode (%o) of%s"),3824 patch->new_mode, new_name,3825 patch->old_mode, old_name);3826}3827}38283829if(!state->unsafe_paths)3830die_on_unsafe_path(patch);38313832/*3833 * An attempt to read from or delete a path that is beyond a3834 * symbolic link will be prevented by load_patch_target() that3835 * is called at the beginning of apply_data() so we do not3836 * have to worry about a patch marked with "is_delete" bit3837 * here. We however need to make sure that the patch result3838 * is not deposited to a path that is beyond a symbolic link3839 * here.3840 */3841if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3842returnerror(_("affected file '%s' is beyond a symbolic link"),3843 patch->new_name);38443845if(apply_data(state, patch, &st, ce) <0)3846returnerror(_("%s: patch does not apply"), name);3847 patch->rejected =0;3848return0;3849}38503851static intcheck_patch_list(struct apply_state *state,struct patch *patch)3852{3853int err =0;38543855prepare_symlink_changes(patch);3856prepare_fn_table(patch);3857while(patch) {3858if(state->apply_verbosely)3859say_patch_name(stderr,3860_("Checking patch%s..."), patch);3861 err |=check_patch(state, patch);3862 patch = patch->next;3863}3864return err;3865}38663867/* This function tries to read the sha1 from the current index */3868static intget_current_sha1(const char*path,unsigned char*sha1)3869{3870int pos;38713872if(read_cache() <0)3873return-1;3874 pos =cache_name_pos(path,strlen(path));3875if(pos <0)3876return-1;3877hashcpy(sha1, active_cache[pos]->sha1);3878return0;3879}38803881static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3882{3883/*3884 * A usable gitlink patch has only one fragment (hunk) that looks like:3885 * @@ -1 +1 @@3886 * -Subproject commit <old sha1>3887 * +Subproject commit <new sha1>3888 * or3889 * @@ -1 +0,0 @@3890 * -Subproject commit <old sha1>3891 * for a removal patch.3892 */3893struct fragment *hunk = p->fragments;3894static const char heading[] ="-Subproject commit ";3895char*preimage;38963897if(/* does the patch have only one hunk? */3898 hunk && !hunk->next &&3899/* is its preimage one line? */3900 hunk->oldpos ==1&& hunk->oldlines ==1&&3901/* does preimage begin with the heading? */3902(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3903starts_with(++preimage, heading) &&3904/* does it record full SHA-1? */3905!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3906 preimage[sizeof(heading) +40-1] =='\n'&&3907/* does the abbreviated name on the index line agree with it? */3908starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3909return0;/* it all looks fine */39103911/* we may have full object name on the index line */3912returnget_sha1_hex(p->old_sha1_prefix, sha1);3913}39143915/* Build an index that contains the just the files needed for a 3way merge */3916static voidbuild_fake_ancestor(struct patch *list,const char*filename)3917{3918struct patch *patch;3919struct index_state result = { NULL };3920static struct lock_file lock;39213922/* Once we start supporting the reverse patch, it may be3923 * worth showing the new sha1 prefix, but until then...3924 */3925for(patch = list; patch; patch = patch->next) {3926unsigned char sha1[20];3927struct cache_entry *ce;3928const char*name;39293930 name = patch->old_name ? patch->old_name : patch->new_name;3931if(0< patch->is_new)3932continue;39333934if(S_ISGITLINK(patch->old_mode)) {3935if(!preimage_sha1_in_gitlink_patch(patch, sha1))3936;/* ok, the textual part looks sane */3937else3938die("sha1 information is lacking or useless for submodule%s",3939 name);3940}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {3941;/* ok */3942}else if(!patch->lines_added && !patch->lines_deleted) {3943/* mode-only change: update the current */3944if(get_current_sha1(patch->old_name, sha1))3945die("mode change for%s, which is not "3946"in current HEAD", name);3947}else3948die("sha1 information is lacking or useless "3949"(%s).", name);39503951 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);3952if(!ce)3953die(_("make_cache_entry failed for path '%s'"), name);3954if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3955die("Could not add%sto temporary index", name);3956}39573958hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);3959if(write_locked_index(&result, &lock, COMMIT_LOCK))3960die("Could not write temporary index to%s", filename);39613962discard_index(&result);3963}39643965static voidstat_patch_list(struct patch *patch)3966{3967int files, adds, dels;39683969for(files = adds = dels =0; patch ; patch = patch->next) {3970 files++;3971 adds += patch->lines_added;3972 dels += patch->lines_deleted;3973show_stats(patch);3974}39753976print_stat_summary(stdout, files, adds, dels);3977}39783979static voidnumstat_patch_list(struct apply_state *state,3980struct patch *patch)3981{3982for( ; patch; patch = patch->next) {3983const char*name;3984 name = patch->new_name ? patch->new_name : patch->old_name;3985if(patch->is_binary)3986printf("-\t-\t");3987else3988printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3989write_name_quoted(name, stdout, state->line_termination);3990}3991}39923993static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3994{3995if(mode)3996printf("%smode%06o%s\n", newdelete, mode, name);3997else3998printf("%s %s\n", newdelete, name);3999}40004001static voidshow_mode_change(struct patch *p,int show_name)4002{4003if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4004if(show_name)4005printf(" mode change%06o =>%06o%s\n",4006 p->old_mode, p->new_mode, p->new_name);4007else4008printf(" mode change%06o =>%06o\n",4009 p->old_mode, p->new_mode);4010}4011}40124013static voidshow_rename_copy(struct patch *p)4014{4015const char*renamecopy = p->is_rename ?"rename":"copy";4016const char*old, *new;40174018/* Find common prefix */4019 old = p->old_name;4020new= p->new_name;4021while(1) {4022const char*slash_old, *slash_new;4023 slash_old =strchr(old,'/');4024 slash_new =strchr(new,'/');4025if(!slash_old ||4026!slash_new ||4027 slash_old - old != slash_new -new||4028memcmp(old,new, slash_new -new))4029break;4030 old = slash_old +1;4031new= slash_new +1;4032}4033/* p->old_name thru old is the common prefix, and old and new4034 * through the end of names are renames4035 */4036if(old != p->old_name)4037printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4038(int)(old - p->old_name), p->old_name,4039 old,new, p->score);4040else4041printf("%s %s=>%s(%d%%)\n", renamecopy,4042 p->old_name, p->new_name, p->score);4043show_mode_change(p,0);4044}40454046static voidsummary_patch_list(struct patch *patch)4047{4048struct patch *p;40494050for(p = patch; p; p = p->next) {4051if(p->is_new)4052show_file_mode_name("create", p->new_mode, p->new_name);4053else if(p->is_delete)4054show_file_mode_name("delete", p->old_mode, p->old_name);4055else{4056if(p->is_rename || p->is_copy)4057show_rename_copy(p);4058else{4059if(p->score) {4060printf(" rewrite%s(%d%%)\n",4061 p->new_name, p->score);4062show_mode_change(p,0);4063}4064else4065show_mode_change(p,1);4066}4067}4068}4069}40704071static voidpatch_stats(struct patch *patch)4072{4073int lines = patch->lines_added + patch->lines_deleted;40744075if(lines > max_change)4076 max_change = lines;4077if(patch->old_name) {4078int len =quote_c_style(patch->old_name, NULL, NULL,0);4079if(!len)4080 len =strlen(patch->old_name);4081if(len > max_len)4082 max_len = len;4083}4084if(patch->new_name) {4085int len =quote_c_style(patch->new_name, NULL, NULL,0);4086if(!len)4087 len =strlen(patch->new_name);4088if(len > max_len)4089 max_len = len;4090}4091}40924093static voidremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4094{4095if(state->update_index) {4096if(remove_file_from_cache(patch->old_name) <0)4097die(_("unable to remove%sfrom index"), patch->old_name);4098}4099if(!state->cached) {4100if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4101remove_path(patch->old_name);4102}4103}4104}41054106static voidadd_index_file(struct apply_state *state,4107const char*path,4108unsigned mode,4109void*buf,4110unsigned long size)4111{4112struct stat st;4113struct cache_entry *ce;4114int namelen =strlen(path);4115unsigned ce_size =cache_entry_size(namelen);41164117if(!state->update_index)4118return;41194120 ce =xcalloc(1, ce_size);4121memcpy(ce->name, path, namelen);4122 ce->ce_mode =create_ce_mode(mode);4123 ce->ce_flags =create_ce_flags(0);4124 ce->ce_namelen = namelen;4125if(S_ISGITLINK(mode)) {4126const char*s;41274128if(!skip_prefix(buf,"Subproject commit ", &s) ||4129get_sha1_hex(s, ce->sha1))4130die(_("corrupt patch for submodule%s"), path);4131}else{4132if(!state->cached) {4133if(lstat(path, &st) <0)4134die_errno(_("unable to stat newly created file '%s'"),4135 path);4136fill_stat_cache_info(ce, &st);4137}4138if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4139die(_("unable to create backing store for newly created file%s"), path);4140}4141if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4142die(_("unable to add cache entry for%s"), path);4143}41444145static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4146{4147int fd;4148struct strbuf nbuf = STRBUF_INIT;41494150if(S_ISGITLINK(mode)) {4151struct stat st;4152if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4153return0;4154returnmkdir(path,0777);4155}41564157if(has_symlinks &&S_ISLNK(mode))4158/* Although buf:size is counted string, it also is NUL4159 * terminated.4160 */4161returnsymlink(buf, path);41624163 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4164if(fd <0)4165return-1;41664167if(convert_to_working_tree(path, buf, size, &nbuf)) {4168 size = nbuf.len;4169 buf = nbuf.buf;4170}4171write_or_die(fd, buf, size);4172strbuf_release(&nbuf);41734174if(close(fd) <0)4175die_errno(_("closing file '%s'"), path);4176return0;4177}41784179/*4180 * We optimistically assume that the directories exist,4181 * which is true 99% of the time anyway. If they don't,4182 * we create them and try again.4183 */4184static voidcreate_one_file(struct apply_state *state,4185char*path,4186unsigned mode,4187const char*buf,4188unsigned long size)4189{4190if(state->cached)4191return;4192if(!try_create_file(path, mode, buf, size))4193return;41944195if(errno == ENOENT) {4196if(safe_create_leading_directories(path))4197return;4198if(!try_create_file(path, mode, buf, size))4199return;4200}42014202if(errno == EEXIST || errno == EACCES) {4203/* We may be trying to create a file where a directory4204 * used to be.4205 */4206struct stat st;4207if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4208 errno = EEXIST;4209}42104211if(errno == EEXIST) {4212unsigned int nr =getpid();42134214for(;;) {4215char newpath[PATH_MAX];4216mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4217if(!try_create_file(newpath, mode, buf, size)) {4218if(!rename(newpath, path))4219return;4220unlink_or_warn(newpath);4221break;4222}4223if(errno != EEXIST)4224break;4225++nr;4226}4227}4228die_errno(_("unable to write file '%s' mode%o"), path, mode);4229}42304231static voidadd_conflicted_stages_file(struct apply_state *state,4232struct patch *patch)4233{4234int stage, namelen;4235unsigned ce_size, mode;4236struct cache_entry *ce;42374238if(!state->update_index)4239return;4240 namelen =strlen(patch->new_name);4241 ce_size =cache_entry_size(namelen);4242 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);42434244remove_file_from_cache(patch->new_name);4245for(stage =1; stage <4; stage++) {4246if(is_null_oid(&patch->threeway_stage[stage -1]))4247continue;4248 ce =xcalloc(1, ce_size);4249memcpy(ce->name, patch->new_name, namelen);4250 ce->ce_mode =create_ce_mode(mode);4251 ce->ce_flags =create_ce_flags(stage);4252 ce->ce_namelen = namelen;4253hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4254if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4255die(_("unable to add cache entry for%s"), patch->new_name);4256}4257}42584259static voidcreate_file(struct apply_state *state,struct patch *patch)4260{4261char*path = patch->new_name;4262unsigned mode = patch->new_mode;4263unsigned long size = patch->resultsize;4264char*buf = patch->result;42654266if(!mode)4267 mode = S_IFREG |0644;4268create_one_file(state, path, mode, buf, size);42694270if(patch->conflicted_threeway)4271add_conflicted_stages_file(state, patch);4272else4273add_index_file(state, path, mode, buf, size);4274}42754276/* phase zero is to remove, phase one is to create */4277static voidwrite_out_one_result(struct apply_state *state,4278struct patch *patch,4279int phase)4280{4281if(patch->is_delete >0) {4282if(phase ==0)4283remove_file(state, patch,1);4284return;4285}4286if(patch->is_new >0|| patch->is_copy) {4287if(phase ==1)4288create_file(state, patch);4289return;4290}4291/*4292 * Rename or modification boils down to the same4293 * thing: remove the old, write the new4294 */4295if(phase ==0)4296remove_file(state, patch, patch->is_rename);4297if(phase ==1)4298create_file(state, patch);4299}43004301static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4302{4303FILE*rej;4304char namebuf[PATH_MAX];4305struct fragment *frag;4306int cnt =0;4307struct strbuf sb = STRBUF_INIT;43084309for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4310if(!frag->rejected)4311continue;4312 cnt++;4313}43144315if(!cnt) {4316if(state->apply_verbosely)4317say_patch_name(stderr,4318_("Applied patch%scleanly."), patch);4319return0;4320}43214322/* This should not happen, because a removal patch that leaves4323 * contents are marked "rejected" at the patch level.4324 */4325if(!patch->new_name)4326die(_("internal error"));43274328/* Say this even without --verbose */4329strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4330"Applying patch %%swith%drejects...",4331 cnt),4332 cnt);4333say_patch_name(stderr, sb.buf, patch);4334strbuf_release(&sb);43354336 cnt =strlen(patch->new_name);4337if(ARRAY_SIZE(namebuf) <= cnt +5) {4338 cnt =ARRAY_SIZE(namebuf) -5;4339warning(_("truncating .rej filename to %.*s.rej"),4340 cnt -1, patch->new_name);4341}4342memcpy(namebuf, patch->new_name, cnt);4343memcpy(namebuf + cnt,".rej",5);43444345 rej =fopen(namebuf,"w");4346if(!rej)4347returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));43484349/* Normal git tools never deal with .rej, so do not pretend4350 * this is a git patch by saying --git or giving extended4351 * headers. While at it, maybe please "kompare" that wants4352 * the trailing TAB and some garbage at the end of line ;-).4353 */4354fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4355 patch->new_name, patch->new_name);4356for(cnt =1, frag = patch->fragments;4357 frag;4358 cnt++, frag = frag->next) {4359if(!frag->rejected) {4360fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4361continue;4362}4363fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4364fprintf(rej,"%.*s", frag->size, frag->patch);4365if(frag->patch[frag->size-1] !='\n')4366fputc('\n', rej);4367}4368fclose(rej);4369return-1;4370}43714372static intwrite_out_results(struct apply_state *state,struct patch *list)4373{4374int phase;4375int errs =0;4376struct patch *l;4377struct string_list cpath = STRING_LIST_INIT_DUP;43784379for(phase =0; phase <2; phase++) {4380 l = list;4381while(l) {4382if(l->rejected)4383 errs =1;4384else{4385write_out_one_result(state, l, phase);4386if(phase ==1) {4387if(write_out_one_reject(state, l))4388 errs =1;4389if(l->conflicted_threeway) {4390string_list_append(&cpath, l->new_name);4391 errs =1;4392}4393}4394}4395 l = l->next;4396}4397}43984399if(cpath.nr) {4400struct string_list_item *item;44014402string_list_sort(&cpath);4403for_each_string_list_item(item, &cpath)4404fprintf(stderr,"U%s\n", item->string);4405string_list_clear(&cpath,0);44064407rerere(0);4408}44094410return errs;4411}44124413static struct lock_file lock_file;44144415#define INACCURATE_EOF (1<<0)4416#define RECOUNT (1<<1)44174418static intapply_patch(struct apply_state *state,4419int fd,4420const char*filename,4421int options)4422{4423size_t offset;4424struct strbuf buf = STRBUF_INIT;/* owns the patch text */4425struct patch *list = NULL, **listp = &list;4426int skipped_patch =0;44274428 patch_input_file = filename;4429read_patch_file(&buf, fd);4430 offset =0;4431while(offset < buf.len) {4432struct patch *patch;4433int nr;44344435 patch =xcalloc(1,sizeof(*patch));4436 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4437 patch->recount = !!(options & RECOUNT);4438 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4439if(nr <0) {4440free_patch(patch);4441break;4442}4443if(state->apply_in_reverse)4444reverse_patches(patch);4445if(use_patch(state, patch)) {4446patch_stats(patch);4447*listp = patch;4448 listp = &patch->next;4449}4450else{4451if(state->apply_verbosely)4452say_patch_name(stderr,_("Skipped patch '%s'."), patch);4453free_patch(patch);4454 skipped_patch++;4455}4456 offset += nr;4457}44584459if(!list && !skipped_patch)4460die(_("unrecognized input"));44614462if(whitespace_error && (ws_error_action == die_on_ws_error))4463 apply =0;44644465 state->update_index = state->check_index && apply;4466if(state->update_index && newfd <0)4467 newfd =hold_locked_index(&lock_file,1);44684469if(state->check_index) {4470if(read_cache() <0)4471die(_("unable to read index file"));4472}44734474if((state->check || apply) &&4475check_patch_list(state, list) <0&&4476!state->apply_with_reject)4477exit(1);44784479if(apply &&write_out_results(state, list)) {4480if(state->apply_with_reject)4481exit(1);4482/* with --3way, we still need to write the index out */4483return1;4484}44854486if(state->fake_ancestor)4487build_fake_ancestor(list, state->fake_ancestor);44884489if(state->diffstat)4490stat_patch_list(list);44914492if(state->numstat)4493numstat_patch_list(state, list);44944495if(state->summary)4496summary_patch_list(list);44974498free_patch_list(list);4499strbuf_release(&buf);4500string_list_clear(&fn_table,0);4501return0;4502}45034504static voidgit_apply_config(void)4505{4506git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4507git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4508git_config(git_default_config, NULL);4509}45104511static intoption_parse_exclude(const struct option *opt,4512const char*arg,int unset)4513{4514add_name_limit(arg,1);4515return0;4516}45174518static intoption_parse_include(const struct option *opt,4519const char*arg,int unset)4520{4521add_name_limit(arg,0);4522 has_include =1;4523return0;4524}45254526static intoption_parse_p(const struct option *opt,4527const char*arg,int unset)4528{4529 state_p_value =atoi(arg);4530 p_value_known =1;4531return0;4532}45334534static intoption_parse_space_change(const struct option *opt,4535const char*arg,int unset)4536{4537if(unset)4538 ws_ignore_action = ignore_ws_none;4539else4540 ws_ignore_action = ignore_ws_change;4541return0;4542}45434544static intoption_parse_whitespace(const struct option *opt,4545const char*arg,int unset)4546{4547const char**whitespace_option = opt->value;45484549*whitespace_option = arg;4550parse_whitespace_option(arg);4551return0;4552}45534554static intoption_parse_directory(const struct option *opt,4555const char*arg,int unset)4556{4557strbuf_reset(&root);4558strbuf_addstr(&root, arg);4559strbuf_complete(&root,'/');4560return0;4561}45624563static voidinit_apply_state(struct apply_state *state,const char*prefix)4564{4565memset(state,0,sizeof(*state));4566 state->prefix = prefix;4567 state->prefix_length = state->prefix ?strlen(state->prefix) :0;4568 state->line_termination ='\n';4569 state->p_context = UINT_MAX;45704571git_apply_config();4572if(apply_default_whitespace)4573parse_whitespace_option(apply_default_whitespace);4574if(apply_default_ignorewhitespace)4575parse_ignorewhitespace_option(apply_default_ignorewhitespace);4576}45774578static voidclear_apply_state(struct apply_state *state)4579{4580/* empty for now */4581}45824583intcmd_apply(int argc,const char**argv,const char*prefix)4584{4585int i;4586int errs =0;4587int is_not_gitdir = !startup_info->have_repository;4588int force_apply =0;4589int options =0;4590int read_stdin =1;4591struct apply_state state;45924593const char*whitespace_option = NULL;45944595struct option builtin_apply_options[] = {4596{ OPTION_CALLBACK,0,"exclude", NULL,N_("path"),4597N_("don't apply changes matching the given path"),45980, option_parse_exclude },4599{ OPTION_CALLBACK,0,"include", NULL,N_("path"),4600N_("apply changes matching the given path"),46010, option_parse_include },4602{ OPTION_CALLBACK,'p', NULL, NULL,N_("num"),4603N_("remove <num> leading slashes from traditional diff paths"),46040, option_parse_p },4605OPT_BOOL(0,"no-add", &state.no_add,4606N_("ignore additions made by the patch")),4607OPT_BOOL(0,"stat", &state.diffstat,4608N_("instead of applying the patch, output diffstat for the input")),4609OPT_NOOP_NOARG(0,"allow-binary-replacement"),4610OPT_NOOP_NOARG(0,"binary"),4611OPT_BOOL(0,"numstat", &state.numstat,4612N_("show number of added and deleted lines in decimal notation")),4613OPT_BOOL(0,"summary", &state.summary,4614N_("instead of applying the patch, output a summary for the input")),4615OPT_BOOL(0,"check", &state.check,4616N_("instead of applying the patch, see if the patch is applicable")),4617OPT_BOOL(0,"index", &state.check_index,4618N_("make sure the patch is applicable to the current index")),4619OPT_BOOL(0,"cached", &state.cached,4620N_("apply a patch without touching the working tree")),4621OPT_BOOL(0,"unsafe-paths", &state.unsafe_paths,4622N_("accept a patch that touches outside the working area")),4623OPT_BOOL(0,"apply", &force_apply,4624N_("also apply the patch (use with --stat/--summary/--check)")),4625OPT_BOOL('3',"3way", &state.threeway,4626N_("attempt three-way merge if a patch does not apply")),4627OPT_FILENAME(0,"build-fake-ancestor", &state.fake_ancestor,4628N_("build a temporary index based on embedded index information")),4629/* Think twice before adding "--nul" synonym to this */4630OPT_SET_INT('z', NULL, &state.line_termination,4631N_("paths are separated with NUL character"),'\0'),4632OPT_INTEGER('C', NULL, &state.p_context,4633N_("ensure at least <n> lines of context match")),4634{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,N_("action"),4635N_("detect new or modified lines that have whitespace errors"),46360, option_parse_whitespace },4637{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,4638N_("ignore changes in whitespace when finding context"),4639 PARSE_OPT_NOARG, option_parse_space_change },4640{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,4641N_("ignore changes in whitespace when finding context"),4642 PARSE_OPT_NOARG, option_parse_space_change },4643OPT_BOOL('R',"reverse", &state.apply_in_reverse,4644N_("apply the patch in reverse")),4645OPT_BOOL(0,"unidiff-zero", &state.unidiff_zero,4646N_("don't expect at least one line of context")),4647OPT_BOOL(0,"reject", &state.apply_with_reject,4648N_("leave the rejected hunks in corresponding *.rej files")),4649OPT_BOOL(0,"allow-overlap", &state.allow_overlap,4650N_("allow overlapping hunks")),4651OPT__VERBOSE(&state.apply_verbosely,N_("be verbose")),4652OPT_BIT(0,"inaccurate-eof", &options,4653N_("tolerate incorrectly detected missing new-line at the end of file"),4654 INACCURATE_EOF),4655OPT_BIT(0,"recount", &options,4656N_("do not trust the line counts in the hunk headers"),4657 RECOUNT),4658{ OPTION_CALLBACK,0,"directory", NULL,N_("root"),4659N_("prepend <root> to all filenames"),46600, option_parse_directory },4661OPT_END()4662};46634664init_apply_state(&state, prefix);46654666 argc =parse_options(argc, argv, state.prefix, builtin_apply_options,4667 apply_usage,0);46684669if(state.apply_with_reject && state.threeway)4670die("--reject and --3way cannot be used together.");4671if(state.cached && state.threeway)4672die("--cached and --3way cannot be used together.");4673if(state.threeway) {4674if(is_not_gitdir)4675die(_("--3way outside a repository"));4676 state.check_index =1;4677}4678if(state.apply_with_reject)4679 apply = state.apply_verbosely =1;4680if(!force_apply && (state.diffstat || state.numstat || state.summary || state.check || state.fake_ancestor))4681 apply =0;4682if(state.check_index && is_not_gitdir)4683die(_("--index outside a repository"));4684if(state.cached) {4685if(is_not_gitdir)4686die(_("--cached outside a repository"));4687 state.check_index =1;4688}4689if(state.check_index)4690 state.unsafe_paths =0;46914692for(i =0; i < argc; i++) {4693const char*arg = argv[i];4694int fd;46954696if(!strcmp(arg,"-")) {4697 errs |=apply_patch(&state,0,"<stdin>", options);4698 read_stdin =0;4699continue;4700}else if(0< state.prefix_length)4701 arg =prefix_filename(state.prefix,4702 state.prefix_length,4703 arg);47044705 fd =open(arg, O_RDONLY);4706if(fd <0)4707die_errno(_("can't open patch '%s'"), arg);4708 read_stdin =0;4709set_default_whitespace_mode(whitespace_option);4710 errs |=apply_patch(&state, fd, arg, options);4711close(fd);4712}4713set_default_whitespace_mode(whitespace_option);4714if(read_stdin)4715 errs |=apply_patch(&state,0,"<stdin>", options);4716if(whitespace_error) {4717if(squelch_whitespace_errors &&4718 squelch_whitespace_errors < whitespace_error) {4719int squelched =4720 whitespace_error - squelch_whitespace_errors;4721warning(Q_("squelched%dwhitespace error",4722"squelched%dwhitespace errors",4723 squelched),4724 squelched);4725}4726if(ws_error_action == die_on_ws_error)4727die(Q_("%dline adds whitespace errors.",4728"%dlines add whitespace errors.",4729 whitespace_error),4730 whitespace_error);4731if(applied_after_fixing_ws && apply)4732warning("%dline%sapplied after"4733" fixing whitespace errors.",4734 applied_after_fixing_ws,4735 applied_after_fixing_ws ==1?"":"s");4736else if(whitespace_error)4737warning(Q_("%dline adds whitespace errors.",4738"%dlines add whitespace errors.",4739 whitespace_error),4740 whitespace_error);4741}47424743if(state.update_index) {4744if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK))4745die(_("Unable to write new index file"));4746}47474748clear_apply_state(&state);47494750return!!errs;4751}