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 apply;/* this is not a dry-run */ 30int cached;/* apply to the index only */ 31int check;/* preimage must match working tree, don't actually apply */ 32int check_index;/* preimage must match the indexed version */ 33int update_index;/* check_index && apply */ 34 35/* These control cosmetic aspect of the output */ 36int diffstat;/* just show a diffstat, and don't actually apply */ 37int numstat;/* just show a numeric diffstat, and don't actually apply */ 38int summary;/* just report creation, deletion, etc, and don't actually apply */ 39 40/* These boolean parameters control how the apply is done */ 41int allow_overlap; 42int apply_in_reverse; 43int apply_with_reject; 44int apply_verbosely; 45int no_add; 46int threeway; 47int unidiff_zero; 48int unsafe_paths; 49 50/* Other non boolean parameters */ 51const char*fake_ancestor; 52const char*patch_input_file; 53int line_termination; 54unsigned int p_context; 55}; 56 57static int newfd = -1; 58 59static int state_p_value =1; 60static int p_value_known; 61 62static const char*const apply_usage[] = { 63N_("git apply [<options>] [<patch>...]"), 64 NULL 65}; 66 67static enum ws_error_action { 68 nowarn_ws_error, 69 warn_on_ws_error, 70 die_on_ws_error, 71 correct_ws_error 72} ws_error_action = warn_on_ws_error; 73static int whitespace_error; 74static int squelch_whitespace_errors =5; 75static int applied_after_fixing_ws; 76 77static enum ws_ignore { 78 ignore_ws_none, 79 ignore_ws_change 80} ws_ignore_action = ignore_ws_none; 81 82 83static struct strbuf root = STRBUF_INIT; 84 85static voidparse_whitespace_option(const char*option) 86{ 87if(!option) { 88 ws_error_action = warn_on_ws_error; 89return; 90} 91if(!strcmp(option,"warn")) { 92 ws_error_action = warn_on_ws_error; 93return; 94} 95if(!strcmp(option,"nowarn")) { 96 ws_error_action = nowarn_ws_error; 97return; 98} 99if(!strcmp(option,"error")) { 100 ws_error_action = die_on_ws_error; 101return; 102} 103if(!strcmp(option,"error-all")) { 104 ws_error_action = die_on_ws_error; 105 squelch_whitespace_errors =0; 106return; 107} 108if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 109 ws_error_action = correct_ws_error; 110return; 111} 112die(_("unrecognized whitespace option '%s'"), option); 113} 114 115static voidparse_ignorewhitespace_option(const char*option) 116{ 117if(!option || !strcmp(option,"no") || 118!strcmp(option,"false") || !strcmp(option,"never") || 119!strcmp(option,"none")) { 120 ws_ignore_action = ignore_ws_none; 121return; 122} 123if(!strcmp(option,"change")) { 124 ws_ignore_action = ignore_ws_change; 125return; 126} 127die(_("unrecognized whitespace ignore option '%s'"), option); 128} 129 130static voidset_default_whitespace_mode(struct apply_state *state, 131const char*whitespace_option) 132{ 133if(!whitespace_option && !apply_default_whitespace) 134 ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 135} 136 137/* 138 * For "diff-stat" like behaviour, we keep track of the biggest change 139 * we've seen, and the longest filename. That allows us to do simple 140 * scaling. 141 */ 142static int max_change, max_len; 143 144/* 145 * Various "current state", notably line numbers and what 146 * file (and how) we're patching right now.. The "is_xxxx" 147 * things are flags, where -1 means "don't know yet". 148 */ 149static int state_linenr =1; 150 151/* 152 * This represents one "hunk" from a patch, starting with 153 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 154 * patch text is pointed at by patch, and its byte length 155 * is stored in size. leading and trailing are the number 156 * of context lines. 157 */ 158struct fragment { 159unsigned long leading, trailing; 160unsigned long oldpos, oldlines; 161unsigned long newpos, newlines; 162/* 163 * 'patch' is usually borrowed from buf in apply_patch(), 164 * but some codepaths store an allocated buffer. 165 */ 166const char*patch; 167unsigned free_patch:1, 168 rejected:1; 169int size; 170int linenr; 171struct fragment *next; 172}; 173 174/* 175 * When dealing with a binary patch, we reuse "leading" field 176 * to store the type of the binary hunk, either deflated "delta" 177 * or deflated "literal". 178 */ 179#define binary_patch_method leading 180#define BINARY_DELTA_DEFLATED 1 181#define BINARY_LITERAL_DEFLATED 2 182 183/* 184 * This represents a "patch" to a file, both metainfo changes 185 * such as creation/deletion, filemode and content changes represented 186 * as a series of fragments. 187 */ 188struct patch { 189char*new_name, *old_name, *def_name; 190unsigned int old_mode, new_mode; 191int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 192int rejected; 193unsigned ws_rule; 194int lines_added, lines_deleted; 195int score; 196unsigned int is_toplevel_relative:1; 197unsigned int inaccurate_eof:1; 198unsigned int is_binary:1; 199unsigned int is_copy:1; 200unsigned int is_rename:1; 201unsigned int recount:1; 202unsigned int conflicted_threeway:1; 203unsigned int direct_to_threeway:1; 204struct fragment *fragments; 205char*result; 206size_t resultsize; 207char old_sha1_prefix[41]; 208char new_sha1_prefix[41]; 209struct patch *next; 210 211/* three-way fallback result */ 212struct object_id threeway_stage[3]; 213}; 214 215static voidfree_fragment_list(struct fragment *list) 216{ 217while(list) { 218struct fragment *next = list->next; 219if(list->free_patch) 220free((char*)list->patch); 221free(list); 222 list = next; 223} 224} 225 226static voidfree_patch(struct patch *patch) 227{ 228free_fragment_list(patch->fragments); 229free(patch->def_name); 230free(patch->old_name); 231free(patch->new_name); 232free(patch->result); 233free(patch); 234} 235 236static voidfree_patch_list(struct patch *list) 237{ 238while(list) { 239struct patch *next = list->next; 240free_patch(list); 241 list = next; 242} 243} 244 245/* 246 * A line in a file, len-bytes long (includes the terminating LF, 247 * except for an incomplete line at the end if the file ends with 248 * one), and its contents hashes to 'hash'. 249 */ 250struct line { 251size_t len; 252unsigned hash :24; 253unsigned flag :8; 254#define LINE_COMMON 1 255#define LINE_PATCHED 2 256}; 257 258/* 259 * This represents a "file", which is an array of "lines". 260 */ 261struct image { 262char*buf; 263size_t len; 264size_t nr; 265size_t alloc; 266struct line *line_allocated; 267struct line *line; 268}; 269 270/* 271 * Records filenames that have been touched, in order to handle 272 * the case where more than one patches touch the same file. 273 */ 274 275static struct string_list fn_table; 276 277static uint32_thash_line(const char*cp,size_t len) 278{ 279size_t i; 280uint32_t h; 281for(i =0, h =0; i < len; i++) { 282if(!isspace(cp[i])) { 283 h = h *3+ (cp[i] &0xff); 284} 285} 286return h; 287} 288 289/* 290 * Compare lines s1 of length n1 and s2 of length n2, ignoring 291 * whitespace difference. Returns 1 if they match, 0 otherwise 292 */ 293static intfuzzy_matchlines(const char*s1,size_t n1, 294const char*s2,size_t n2) 295{ 296const char*last1 = s1 + n1 -1; 297const char*last2 = s2 + n2 -1; 298int result =0; 299 300/* ignore line endings */ 301while((*last1 =='\r') || (*last1 =='\n')) 302 last1--; 303while((*last2 =='\r') || (*last2 =='\n')) 304 last2--; 305 306/* skip leading whitespaces, if both begin with whitespace */ 307if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 308while(isspace(*s1) && (s1 <= last1)) 309 s1++; 310while(isspace(*s2) && (s2 <= last2)) 311 s2++; 312} 313/* early return if both lines are empty */ 314if((s1 > last1) && (s2 > last2)) 315return1; 316while(!result) { 317 result = *s1++ - *s2++; 318/* 319 * Skip whitespace inside. We check for whitespace on 320 * both buffers because we don't want "a b" to match 321 * "ab" 322 */ 323if(isspace(*s1) &&isspace(*s2)) { 324while(isspace(*s1) && s1 <= last1) 325 s1++; 326while(isspace(*s2) && s2 <= last2) 327 s2++; 328} 329/* 330 * If we reached the end on one side only, 331 * lines don't match 332 */ 333if( 334((s2 > last2) && (s1 <= last1)) || 335((s1 > last1) && (s2 <= last2))) 336return0; 337if((s1 > last1) && (s2 > last2)) 338break; 339} 340 341return!result; 342} 343 344static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 345{ 346ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 347 img->line_allocated[img->nr].len = len; 348 img->line_allocated[img->nr].hash =hash_line(bol, len); 349 img->line_allocated[img->nr].flag = flag; 350 img->nr++; 351} 352 353/* 354 * "buf" has the file contents to be patched (read from various sources). 355 * attach it to "image" and add line-based index to it. 356 * "image" now owns the "buf". 357 */ 358static voidprepare_image(struct image *image,char*buf,size_t len, 359int prepare_linetable) 360{ 361const char*cp, *ep; 362 363memset(image,0,sizeof(*image)); 364 image->buf = buf; 365 image->len = len; 366 367if(!prepare_linetable) 368return; 369 370 ep = image->buf + image->len; 371 cp = image->buf; 372while(cp < ep) { 373const char*next; 374for(next = cp; next < ep && *next !='\n'; next++) 375; 376if(next < ep) 377 next++; 378add_line_info(image, cp, next - cp,0); 379 cp = next; 380} 381 image->line = image->line_allocated; 382} 383 384static voidclear_image(struct image *image) 385{ 386free(image->buf); 387free(image->line_allocated); 388memset(image,0,sizeof(*image)); 389} 390 391/* fmt must contain _one_ %s and no other substitution */ 392static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 393{ 394struct strbuf sb = STRBUF_INIT; 395 396if(patch->old_name && patch->new_name && 397strcmp(patch->old_name, patch->new_name)) { 398quote_c_style(patch->old_name, &sb, NULL,0); 399strbuf_addstr(&sb," => "); 400quote_c_style(patch->new_name, &sb, NULL,0); 401}else{ 402const char*n = patch->new_name; 403if(!n) 404 n = patch->old_name; 405quote_c_style(n, &sb, NULL,0); 406} 407fprintf(output, fmt, sb.buf); 408fputc('\n', output); 409strbuf_release(&sb); 410} 411 412#define SLOP (16) 413 414static voidread_patch_file(struct strbuf *sb,int fd) 415{ 416if(strbuf_read(sb, fd,0) <0) 417die_errno("git apply: failed to read"); 418 419/* 420 * Make sure that we have some slop in the buffer 421 * so that we can do speculative "memcmp" etc, and 422 * see to it that it is NUL-filled. 423 */ 424strbuf_grow(sb, SLOP); 425memset(sb->buf + sb->len,0, SLOP); 426} 427 428static unsigned longlinelen(const char*buffer,unsigned long size) 429{ 430unsigned long len =0; 431while(size--) { 432 len++; 433if(*buffer++ =='\n') 434break; 435} 436return len; 437} 438 439static intis_dev_null(const char*str) 440{ 441returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 442} 443 444#define TERM_SPACE 1 445#define TERM_TAB 2 446 447static intname_terminate(const char*name,int namelen,int c,int terminate) 448{ 449if(c ==' '&& !(terminate & TERM_SPACE)) 450return0; 451if(c =='\t'&& !(terminate & TERM_TAB)) 452return0; 453 454return1; 455} 456 457/* remove double slashes to make --index work with such filenames */ 458static char*squash_slash(char*name) 459{ 460int i =0, j =0; 461 462if(!name) 463return NULL; 464 465while(name[i]) { 466if((name[j++] = name[i++]) =='/') 467while(name[i] =='/') 468 i++; 469} 470 name[j] ='\0'; 471return name; 472} 473 474static char*find_name_gnu(const char*line,const char*def,int p_value) 475{ 476struct strbuf name = STRBUF_INIT; 477char*cp; 478 479/* 480 * Proposed "new-style" GNU patch/diff format; see 481 * http://marc.info/?l=git&m=112927316408690&w=2 482 */ 483if(unquote_c_style(&name, line, NULL)) { 484strbuf_release(&name); 485return NULL; 486} 487 488for(cp = name.buf; p_value; p_value--) { 489 cp =strchr(cp,'/'); 490if(!cp) { 491strbuf_release(&name); 492return NULL; 493} 494 cp++; 495} 496 497strbuf_remove(&name,0, cp - name.buf); 498if(root.len) 499strbuf_insert(&name,0, root.buf, root.len); 500returnsquash_slash(strbuf_detach(&name, NULL)); 501} 502 503static size_tsane_tz_len(const char*line,size_t len) 504{ 505const char*tz, *p; 506 507if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 508return0; 509 tz = line + len -strlen(" +0500"); 510 511if(tz[1] !='+'&& tz[1] !='-') 512return0; 513 514for(p = tz +2; p != line + len; p++) 515if(!isdigit(*p)) 516return0; 517 518return line + len - tz; 519} 520 521static size_ttz_with_colon_len(const char*line,size_t len) 522{ 523const char*tz, *p; 524 525if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 526return0; 527 tz = line + len -strlen(" +08:00"); 528 529if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 530return0; 531 p = tz +2; 532if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 533!isdigit(*p++) || !isdigit(*p++)) 534return0; 535 536return line + len - tz; 537} 538 539static size_tdate_len(const char*line,size_t len) 540{ 541const char*date, *p; 542 543if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 544return0; 545 p = date = line + len -strlen("72-02-05"); 546 547if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 548!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 549!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 550return0; 551 552if(date - line >=strlen("19") && 553isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 554 date -=strlen("19"); 555 556return line + len - date; 557} 558 559static size_tshort_time_len(const char*line,size_t len) 560{ 561const char*time, *p; 562 563if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 564return0; 565 p = time = line + len -strlen(" 07:01:32"); 566 567/* Permit 1-digit hours? */ 568if(*p++ !=' '|| 569!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 570!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 571!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 572return0; 573 574return line + len - time; 575} 576 577static size_tfractional_time_len(const char*line,size_t len) 578{ 579const char*p; 580size_t n; 581 582/* Expected format: 19:41:17.620000023 */ 583if(!len || !isdigit(line[len -1])) 584return0; 585 p = line + len -1; 586 587/* Fractional seconds. */ 588while(p > line &&isdigit(*p)) 589 p--; 590if(*p !='.') 591return0; 592 593/* Hours, minutes, and whole seconds. */ 594 n =short_time_len(line, p - line); 595if(!n) 596return0; 597 598return line + len - p + n; 599} 600 601static size_ttrailing_spaces_len(const char*line,size_t len) 602{ 603const char*p; 604 605/* Expected format: ' ' x (1 or more) */ 606if(!len || line[len -1] !=' ') 607return0; 608 609 p = line + len; 610while(p != line) { 611 p--; 612if(*p !=' ') 613return line + len - (p +1); 614} 615 616/* All spaces! */ 617return len; 618} 619 620static size_tdiff_timestamp_len(const char*line,size_t len) 621{ 622const char*end = line + len; 623size_t n; 624 625/* 626 * Posix: 2010-07-05 19:41:17 627 * GNU: 2010-07-05 19:41:17.620000023 -0500 628 */ 629 630if(!isdigit(end[-1])) 631return0; 632 633 n =sane_tz_len(line, end - line); 634if(!n) 635 n =tz_with_colon_len(line, end - line); 636 end -= n; 637 638 n =short_time_len(line, end - line); 639if(!n) 640 n =fractional_time_len(line, end - line); 641 end -= n; 642 643 n =date_len(line, end - line); 644if(!n)/* No date. Too bad. */ 645return0; 646 end -= n; 647 648if(end == line)/* No space before date. */ 649return0; 650if(end[-1] =='\t') {/* Success! */ 651 end--; 652return line + len - end; 653} 654if(end[-1] !=' ')/* No space before date. */ 655return0; 656 657/* Whitespace damage. */ 658 end -=trailing_spaces_len(line, end - line); 659return line + len - end; 660} 661 662static char*find_name_common(const char*line,const char*def, 663int p_value,const char*end,int terminate) 664{ 665int len; 666const char*start = NULL; 667 668if(p_value ==0) 669 start = line; 670while(line != end) { 671char c = *line; 672 673if(!end &&isspace(c)) { 674if(c =='\n') 675break; 676if(name_terminate(start, line-start, c, terminate)) 677break; 678} 679 line++; 680if(c =='/'&& !--p_value) 681 start = line; 682} 683if(!start) 684returnsquash_slash(xstrdup_or_null(def)); 685 len = line - start; 686if(!len) 687returnsquash_slash(xstrdup_or_null(def)); 688 689/* 690 * Generally we prefer the shorter name, especially 691 * if the other one is just a variation of that with 692 * something else tacked on to the end (ie "file.orig" 693 * or "file~"). 694 */ 695if(def) { 696int deflen =strlen(def); 697if(deflen < len && !strncmp(start, def, deflen)) 698returnsquash_slash(xstrdup(def)); 699} 700 701if(root.len) { 702char*ret =xstrfmt("%s%.*s", root.buf, len, start); 703returnsquash_slash(ret); 704} 705 706returnsquash_slash(xmemdupz(start, len)); 707} 708 709static char*find_name(const char*line,char*def,int p_value,int terminate) 710{ 711if(*line =='"') { 712char*name =find_name_gnu(line, def, p_value); 713if(name) 714return name; 715} 716 717returnfind_name_common(line, def, p_value, NULL, terminate); 718} 719 720static char*find_name_traditional(const char*line,char*def,int p_value) 721{ 722size_t len; 723size_t date_len; 724 725if(*line =='"') { 726char*name =find_name_gnu(line, def, p_value); 727if(name) 728return name; 729} 730 731 len =strchrnul(line,'\n') - line; 732 date_len =diff_timestamp_len(line, len); 733if(!date_len) 734returnfind_name_common(line, def, p_value, NULL, TERM_TAB); 735 len -= date_len; 736 737returnfind_name_common(line, def, p_value, line + len,0); 738} 739 740static intcount_slashes(const char*cp) 741{ 742int cnt =0; 743char ch; 744 745while((ch = *cp++)) 746if(ch =='/') 747 cnt++; 748return cnt; 749} 750 751/* 752 * Given the string after "--- " or "+++ ", guess the appropriate 753 * p_value for the given patch. 754 */ 755static intguess_p_value(struct apply_state *state,const char*nameline) 756{ 757char*name, *cp; 758int val = -1; 759 760if(is_dev_null(nameline)) 761return-1; 762 name =find_name_traditional(nameline, NULL,0); 763if(!name) 764return-1; 765 cp =strchr(name,'/'); 766if(!cp) 767 val =0; 768else if(state->prefix) { 769/* 770 * Does it begin with "a/$our-prefix" and such? Then this is 771 * very likely to apply to our directory. 772 */ 773if(!strncmp(name, state->prefix, state->prefix_length)) 774 val =count_slashes(state->prefix); 775else{ 776 cp++; 777if(!strncmp(cp, state->prefix, state->prefix_length)) 778 val =count_slashes(state->prefix) +1; 779} 780} 781free(name); 782return val; 783} 784 785/* 786 * Does the ---/+++ line have the POSIX timestamp after the last HT? 787 * GNU diff puts epoch there to signal a creation/deletion event. Is 788 * this such a timestamp? 789 */ 790static inthas_epoch_timestamp(const char*nameline) 791{ 792/* 793 * We are only interested in epoch timestamp; any non-zero 794 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 795 * For the same reason, the date must be either 1969-12-31 or 796 * 1970-01-01, and the seconds part must be "00". 797 */ 798const char stamp_regexp[] = 799"^(1969-12-31|1970-01-01)" 800" " 801"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 802" " 803"([-+][0-2][0-9]:?[0-5][0-9])\n"; 804const char*timestamp = NULL, *cp, *colon; 805static regex_t *stamp; 806 regmatch_t m[10]; 807int zoneoffset; 808int hourminute; 809int status; 810 811for(cp = nameline; *cp !='\n'; cp++) { 812if(*cp =='\t') 813 timestamp = cp +1; 814} 815if(!timestamp) 816return0; 817if(!stamp) { 818 stamp =xmalloc(sizeof(*stamp)); 819if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 820warning(_("Cannot prepare timestamp regexp%s"), 821 stamp_regexp); 822return0; 823} 824} 825 826 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 827if(status) { 828if(status != REG_NOMATCH) 829warning(_("regexec returned%dfor input:%s"), 830 status, timestamp); 831return0; 832} 833 834 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 835if(*colon ==':') 836 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 837else 838 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 839if(timestamp[m[3].rm_so] =='-') 840 zoneoffset = -zoneoffset; 841 842/* 843 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 844 * (west of GMT) or 1970-01-01 (east of GMT) 845 */ 846if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 847(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 848return0; 849 850 hourminute = (strtol(timestamp +11, NULL,10) *60+ 851strtol(timestamp +14, NULL,10) - 852 zoneoffset); 853 854return((zoneoffset <0&& hourminute ==1440) || 855(0<= zoneoffset && !hourminute)); 856} 857 858/* 859 * Get the name etc info from the ---/+++ lines of a traditional patch header 860 * 861 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 862 * files, we can happily check the index for a match, but for creating a 863 * new file we should try to match whatever "patch" does. I have no idea. 864 */ 865static voidparse_traditional_patch(struct apply_state *state, 866const char*first, 867const char*second, 868struct patch *patch) 869{ 870char*name; 871 872 first +=4;/* skip "--- " */ 873 second +=4;/* skip "+++ " */ 874if(!p_value_known) { 875int p, q; 876 p =guess_p_value(state, first); 877 q =guess_p_value(state, second); 878if(p <0) p = q; 879if(0<= p && p == q) { 880 state_p_value = p; 881 p_value_known =1; 882} 883} 884if(is_dev_null(first)) { 885 patch->is_new =1; 886 patch->is_delete =0; 887 name =find_name_traditional(second, NULL, state_p_value); 888 patch->new_name = name; 889}else if(is_dev_null(second)) { 890 patch->is_new =0; 891 patch->is_delete =1; 892 name =find_name_traditional(first, NULL, state_p_value); 893 patch->old_name = name; 894}else{ 895char*first_name; 896 first_name =find_name_traditional(first, NULL, state_p_value); 897 name =find_name_traditional(second, first_name, state_p_value); 898free(first_name); 899if(has_epoch_timestamp(first)) { 900 patch->is_new =1; 901 patch->is_delete =0; 902 patch->new_name = name; 903}else if(has_epoch_timestamp(second)) { 904 patch->is_new =0; 905 patch->is_delete =1; 906 patch->old_name = name; 907}else{ 908 patch->old_name = name; 909 patch->new_name =xstrdup_or_null(name); 910} 911} 912if(!name) 913die(_("unable to find filename in patch at line%d"), state_linenr); 914} 915 916static intgitdiff_hdrend(const char*line,struct patch *patch) 917{ 918return-1; 919} 920 921/* 922 * We're anal about diff header consistency, to make 923 * sure that we don't end up having strange ambiguous 924 * patches floating around. 925 * 926 * As a result, gitdiff_{old|new}name() will check 927 * their names against any previous information, just 928 * to make sure.. 929 */ 930#define DIFF_OLD_NAME 0 931#define DIFF_NEW_NAME 1 932 933static voidgitdiff_verify_name(const char*line,int isnull,char**name,int side) 934{ 935if(!*name && !isnull) { 936*name =find_name(line, NULL, state_p_value, TERM_TAB); 937return; 938} 939 940if(*name) { 941int len =strlen(*name); 942char*another; 943if(isnull) 944die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 945*name, state_linenr); 946 another =find_name(line, NULL, state_p_value, TERM_TAB); 947if(!another ||memcmp(another, *name, len +1)) 948die((side == DIFF_NEW_NAME) ? 949_("git apply: bad git-diff - inconsistent new filename on line%d") : 950_("git apply: bad git-diff - inconsistent old filename on line%d"), state_linenr); 951free(another); 952}else{ 953/* expect "/dev/null" */ 954if(memcmp("/dev/null", line,9) || line[9] !='\n') 955die(_("git apply: bad git-diff - expected /dev/null on line%d"), state_linenr); 956} 957} 958 959static intgitdiff_oldname(const char*line,struct patch *patch) 960{ 961gitdiff_verify_name(line, patch->is_new, &patch->old_name, 962 DIFF_OLD_NAME); 963return0; 964} 965 966static intgitdiff_newname(const char*line,struct patch *patch) 967{ 968gitdiff_verify_name(line, patch->is_delete, &patch->new_name, 969 DIFF_NEW_NAME); 970return0; 971} 972 973static intgitdiff_oldmode(const char*line,struct patch *patch) 974{ 975 patch->old_mode =strtoul(line, NULL,8); 976return0; 977} 978 979static intgitdiff_newmode(const char*line,struct patch *patch) 980{ 981 patch->new_mode =strtoul(line, NULL,8); 982return0; 983} 984 985static intgitdiff_delete(const char*line,struct patch *patch) 986{ 987 patch->is_delete =1; 988free(patch->old_name); 989 patch->old_name =xstrdup_or_null(patch->def_name); 990returngitdiff_oldmode(line, patch); 991} 992 993static intgitdiff_newfile(const char*line,struct patch *patch) 994{ 995 patch->is_new =1; 996free(patch->new_name); 997 patch->new_name =xstrdup_or_null(patch->def_name); 998returngitdiff_newmode(line, patch); 999}10001001static intgitdiff_copysrc(const char*line,struct patch *patch)1002{1003 patch->is_copy =1;1004free(patch->old_name);1005 patch->old_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1006return0;1007}10081009static intgitdiff_copydst(const char*line,struct patch *patch)1010{1011 patch->is_copy =1;1012free(patch->new_name);1013 patch->new_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1014return0;1015}10161017static intgitdiff_renamesrc(const char*line,struct patch *patch)1018{1019 patch->is_rename =1;1020free(patch->old_name);1021 patch->old_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1022return0;1023}10241025static intgitdiff_renamedst(const char*line,struct patch *patch)1026{1027 patch->is_rename =1;1028free(patch->new_name);1029 patch->new_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1030return0;1031}10321033static intgitdiff_similarity(const char*line,struct patch *patch)1034{1035unsigned long val =strtoul(line, NULL,10);1036if(val <=100)1037 patch->score = val;1038return0;1039}10401041static intgitdiff_dissimilarity(const char*line,struct patch *patch)1042{1043unsigned long val =strtoul(line, NULL,10);1044if(val <=100)1045 patch->score = val;1046return0;1047}10481049static intgitdiff_index(const char*line,struct patch *patch)1050{1051/*1052 * index line is N hexadecimal, "..", N hexadecimal,1053 * and optional space with octal mode.1054 */1055const char*ptr, *eol;1056int len;10571058 ptr =strchr(line,'.');1059if(!ptr || ptr[1] !='.'||40< ptr - line)1060return0;1061 len = ptr - line;1062memcpy(patch->old_sha1_prefix, line, len);1063 patch->old_sha1_prefix[len] =0;10641065 line = ptr +2;1066 ptr =strchr(line,' ');1067 eol =strchrnul(line,'\n');10681069if(!ptr || eol < ptr)1070 ptr = eol;1071 len = ptr - line;10721073if(40< len)1074return0;1075memcpy(patch->new_sha1_prefix, line, len);1076 patch->new_sha1_prefix[len] =0;1077if(*ptr ==' ')1078 patch->old_mode =strtoul(ptr+1, NULL,8);1079return0;1080}10811082/*1083 * This is normal for a diff that doesn't change anything: we'll fall through1084 * into the next diff. Tell the parser to break out.1085 */1086static intgitdiff_unrecognized(const char*line,struct patch *patch)1087{1088return-1;1089}10901091/*1092 * Skip p_value leading components from "line"; as we do not accept1093 * absolute paths, return NULL in that case.1094 */1095static const char*skip_tree_prefix(const char*line,int llen)1096{1097int nslash;1098int i;10991100if(!state_p_value)1101return(llen && line[0] =='/') ? NULL : line;11021103 nslash = state_p_value;1104for(i =0; i < llen; i++) {1105int ch = line[i];1106if(ch =='/'&& --nslash <=0)1107return(i ==0) ? NULL : &line[i +1];1108}1109return NULL;1110}11111112/*1113 * This is to extract the same name that appears on "diff --git"1114 * line. We do not find and return anything if it is a rename1115 * patch, and it is OK because we will find the name elsewhere.1116 * We need to reliably find name only when it is mode-change only,1117 * creation or deletion of an empty file. In any of these cases,1118 * both sides are the same name under a/ and b/ respectively.1119 */1120static char*git_header_name(const char*line,int llen)1121{1122const char*name;1123const char*second = NULL;1124size_t len, line_len;11251126 line +=strlen("diff --git ");1127 llen -=strlen("diff --git ");11281129if(*line =='"') {1130const char*cp;1131struct strbuf first = STRBUF_INIT;1132struct strbuf sp = STRBUF_INIT;11331134if(unquote_c_style(&first, line, &second))1135goto free_and_fail1;11361137/* strip the a/b prefix including trailing slash */1138 cp =skip_tree_prefix(first.buf, first.len);1139if(!cp)1140goto free_and_fail1;1141strbuf_remove(&first,0, cp - first.buf);11421143/*1144 * second points at one past closing dq of name.1145 * find the second name.1146 */1147while((second < line + llen) &&isspace(*second))1148 second++;11491150if(line + llen <= second)1151goto free_and_fail1;1152if(*second =='"') {1153if(unquote_c_style(&sp, second, NULL))1154goto free_and_fail1;1155 cp =skip_tree_prefix(sp.buf, sp.len);1156if(!cp)1157goto free_and_fail1;1158/* They must match, otherwise ignore */1159if(strcmp(cp, first.buf))1160goto free_and_fail1;1161strbuf_release(&sp);1162returnstrbuf_detach(&first, NULL);1163}11641165/* unquoted second */1166 cp =skip_tree_prefix(second, line + llen - second);1167if(!cp)1168goto free_and_fail1;1169if(line + llen - cp != first.len ||1170memcmp(first.buf, cp, first.len))1171goto free_and_fail1;1172returnstrbuf_detach(&first, NULL);11731174 free_and_fail1:1175strbuf_release(&first);1176strbuf_release(&sp);1177return NULL;1178}11791180/* unquoted first name */1181 name =skip_tree_prefix(line, llen);1182if(!name)1183return NULL;11841185/*1186 * since the first name is unquoted, a dq if exists must be1187 * the beginning of the second name.1188 */1189for(second = name; second < line + llen; second++) {1190if(*second =='"') {1191struct strbuf sp = STRBUF_INIT;1192const char*np;11931194if(unquote_c_style(&sp, second, NULL))1195goto free_and_fail2;11961197 np =skip_tree_prefix(sp.buf, sp.len);1198if(!np)1199goto free_and_fail2;12001201 len = sp.buf + sp.len - np;1202if(len < second - name &&1203!strncmp(np, name, len) &&1204isspace(name[len])) {1205/* Good */1206strbuf_remove(&sp,0, np - sp.buf);1207returnstrbuf_detach(&sp, NULL);1208}12091210 free_and_fail2:1211strbuf_release(&sp);1212return NULL;1213}1214}12151216/*1217 * Accept a name only if it shows up twice, exactly the same1218 * form.1219 */1220 second =strchr(name,'\n');1221if(!second)1222return NULL;1223 line_len = second - name;1224for(len =0; ; len++) {1225switch(name[len]) {1226default:1227continue;1228case'\n':1229return NULL;1230case'\t':case' ':1231/*1232 * Is this the separator between the preimage1233 * and the postimage pathname? Again, we are1234 * only interested in the case where there is1235 * no rename, as this is only to set def_name1236 * and a rename patch has the names elsewhere1237 * in an unambiguous form.1238 */1239if(!name[len +1])1240return NULL;/* no postimage name */1241 second =skip_tree_prefix(name + len +1,1242 line_len - (len +1));1243if(!second)1244return NULL;1245/*1246 * Does len bytes starting at "name" and "second"1247 * (that are separated by one HT or SP we just1248 * found) exactly match?1249 */1250if(second[len] =='\n'&& !strncmp(name, second, len))1251returnxmemdupz(name, len);1252}1253}1254}12551256/* Verify that we recognize the lines following a git header */1257static intparse_git_header(const char*line,int len,unsigned int size,struct patch *patch)1258{1259unsigned long offset;12601261/* A git diff has explicit new/delete information, so we don't guess */1262 patch->is_new =0;1263 patch->is_delete =0;12641265/*1266 * Some things may not have the old name in the1267 * rest of the headers anywhere (pure mode changes,1268 * or removing or adding empty files), so we get1269 * the default name from the header.1270 */1271 patch->def_name =git_header_name(line, len);1272if(patch->def_name && root.len) {1273char*s =xstrfmt("%s%s", root.buf, patch->def_name);1274free(patch->def_name);1275 patch->def_name = s;1276}12771278 line += len;1279 size -= len;1280 state_linenr++;1281for(offset = len ; size >0; offset += len, size -= len, line += len, state_linenr++) {1282static const struct opentry {1283const char*str;1284int(*fn)(const char*,struct patch *);1285} optable[] = {1286{"@@ -", gitdiff_hdrend },1287{"--- ", gitdiff_oldname },1288{"+++ ", gitdiff_newname },1289{"old mode ", gitdiff_oldmode },1290{"new mode ", gitdiff_newmode },1291{"deleted file mode ", gitdiff_delete },1292{"new file mode ", gitdiff_newfile },1293{"copy from ", gitdiff_copysrc },1294{"copy to ", gitdiff_copydst },1295{"rename old ", gitdiff_renamesrc },1296{"rename new ", gitdiff_renamedst },1297{"rename from ", gitdiff_renamesrc },1298{"rename to ", gitdiff_renamedst },1299{"similarity index ", gitdiff_similarity },1300{"dissimilarity index ", gitdiff_dissimilarity },1301{"index ", gitdiff_index },1302{"", gitdiff_unrecognized },1303};1304int i;13051306 len =linelen(line, size);1307if(!len || line[len-1] !='\n')1308break;1309for(i =0; i <ARRAY_SIZE(optable); i++) {1310const struct opentry *p = optable + i;1311int oplen =strlen(p->str);1312if(len < oplen ||memcmp(p->str, line, oplen))1313continue;1314if(p->fn(line + oplen, patch) <0)1315return offset;1316break;1317}1318}13191320return offset;1321}13221323static intparse_num(const char*line,unsigned long*p)1324{1325char*ptr;13261327if(!isdigit(*line))1328return0;1329*p =strtoul(line, &ptr,10);1330return ptr - line;1331}13321333static intparse_range(const char*line,int len,int offset,const char*expect,1334unsigned long*p1,unsigned long*p2)1335{1336int digits, ex;13371338if(offset <0|| offset >= len)1339return-1;1340 line += offset;1341 len -= offset;13421343 digits =parse_num(line, p1);1344if(!digits)1345return-1;13461347 offset += digits;1348 line += digits;1349 len -= digits;13501351*p2 =1;1352if(*line ==',') {1353 digits =parse_num(line+1, p2);1354if(!digits)1355return-1;13561357 offset += digits+1;1358 line += digits+1;1359 len -= digits+1;1360}13611362 ex =strlen(expect);1363if(ex > len)1364return-1;1365if(memcmp(line, expect, ex))1366return-1;13671368return offset + ex;1369}13701371static voidrecount_diff(const char*line,int size,struct fragment *fragment)1372{1373int oldlines =0, newlines =0, ret =0;13741375if(size <1) {1376warning("recount: ignore empty hunk");1377return;1378}13791380for(;;) {1381int len =linelen(line, size);1382 size -= len;1383 line += len;13841385if(size <1)1386break;13871388switch(*line) {1389case' ':case'\n':1390 newlines++;1391/* fall through */1392case'-':1393 oldlines++;1394continue;1395case'+':1396 newlines++;1397continue;1398case'\\':1399continue;1400case'@':1401 ret = size <3|| !starts_with(line,"@@ ");1402break;1403case'd':1404 ret = size <5|| !starts_with(line,"diff ");1405break;1406default:1407 ret = -1;1408break;1409}1410if(ret) {1411warning(_("recount: unexpected line: %.*s"),1412(int)linelen(line, size), line);1413return;1414}1415break;1416}1417 fragment->oldlines = oldlines;1418 fragment->newlines = newlines;1419}14201421/*1422 * Parse a unified diff fragment header of the1423 * form "@@ -a,b +c,d @@"1424 */1425static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1426{1427int offset;14281429if(!len || line[len-1] !='\n')1430return-1;14311432/* Figure out the number of lines in a fragment */1433 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1434 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14351436return offset;1437}14381439static intfind_header(struct apply_state *state,1440const char*line,1441unsigned long size,1442int*hdrsize,1443struct patch *patch)1444{1445unsigned long offset, len;14461447 patch->is_toplevel_relative =0;1448 patch->is_rename = patch->is_copy =0;1449 patch->is_new = patch->is_delete = -1;1450 patch->old_mode = patch->new_mode =0;1451 patch->old_name = patch->new_name = NULL;1452for(offset =0; size >0; offset += len, size -= len, line += len, state_linenr++) {1453unsigned long nextlen;14541455 len =linelen(line, size);1456if(!len)1457break;14581459/* Testing this early allows us to take a few shortcuts.. */1460if(len <6)1461continue;14621463/*1464 * Make sure we don't find any unconnected patch fragments.1465 * That's a sign that we didn't find a header, and that a1466 * patch has become corrupted/broken up.1467 */1468if(!memcmp("@@ -", line,4)) {1469struct fragment dummy;1470if(parse_fragment_header(line, len, &dummy) <0)1471continue;1472die(_("patch fragment without header at line%d: %.*s"),1473 state_linenr, (int)len-1, line);1474}14751476if(size < len +6)1477break;14781479/*1480 * Git patch? It might not have a real patch, just a rename1481 * or mode change, so we handle that specially1482 */1483if(!memcmp("diff --git ", line,11)) {1484int git_hdr_len =parse_git_header(line, len, size, patch);1485if(git_hdr_len <= len)1486continue;1487if(!patch->old_name && !patch->new_name) {1488if(!patch->def_name)1489die(Q_("git diff header lacks filename information when removing "1490"%dleading pathname component (line%d)",1491"git diff header lacks filename information when removing "1492"%dleading pathname components (line%d)",1493 state_p_value),1494 state_p_value, state_linenr);1495 patch->old_name =xstrdup(patch->def_name);1496 patch->new_name =xstrdup(patch->def_name);1497}1498if(!patch->is_delete && !patch->new_name)1499die("git diff header lacks filename information "1500"(line%d)", state_linenr);1501 patch->is_toplevel_relative =1;1502*hdrsize = git_hdr_len;1503return offset;1504}15051506/* --- followed by +++ ? */1507if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1508continue;15091510/*1511 * We only accept unified patches, so we want it to1512 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1513 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1514 */1515 nextlen =linelen(line + len, size - len);1516if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1517continue;15181519/* Ok, we'll consider it a patch */1520parse_traditional_patch(state, line, line+len, patch);1521*hdrsize = len + nextlen;1522 state_linenr +=2;1523return offset;1524}1525return-1;1526}15271528static voidrecord_ws_error(struct apply_state *state,1529unsigned result,1530const char*line,1531int len,1532int linenr)1533{1534char*err;15351536if(!result)1537return;15381539 whitespace_error++;1540if(squelch_whitespace_errors &&1541 squelch_whitespace_errors < whitespace_error)1542return;15431544 err =whitespace_error_string(result);1545fprintf(stderr,"%s:%d:%s.\n%.*s\n",1546 state->patch_input_file, linenr, err, len, line);1547free(err);1548}15491550static voidcheck_whitespace(struct apply_state *state,1551const char*line,1552int len,1553unsigned ws_rule)1554{1555unsigned result =ws_check(line +1, len -1, ws_rule);15561557record_ws_error(state, result, line +1, len -2, state_linenr);1558}15591560/*1561 * Parse a unified diff. Note that this really needs to parse each1562 * fragment separately, since the only way to know the difference1563 * between a "---" that is part of a patch, and a "---" that starts1564 * the next patch is to look at the line counts..1565 */1566static intparse_fragment(struct apply_state *state,1567const char*line,1568unsigned long size,1569struct patch *patch,1570struct fragment *fragment)1571{1572int added, deleted;1573int len =linelen(line, size), offset;1574unsigned long oldlines, newlines;1575unsigned long leading, trailing;15761577 offset =parse_fragment_header(line, len, fragment);1578if(offset <0)1579return-1;1580if(offset >0&& patch->recount)1581recount_diff(line + offset, size - offset, fragment);1582 oldlines = fragment->oldlines;1583 newlines = fragment->newlines;1584 leading =0;1585 trailing =0;15861587/* Parse the thing.. */1588 line += len;1589 size -= len;1590 state_linenr++;1591 added = deleted =0;1592for(offset = len;15930< size;1594 offset += len, size -= len, line += len, state_linenr++) {1595if(!oldlines && !newlines)1596break;1597 len =linelen(line, size);1598if(!len || line[len-1] !='\n')1599return-1;1600switch(*line) {1601default:1602return-1;1603case'\n':/* newer GNU diff, an empty context line */1604case' ':1605 oldlines--;1606 newlines--;1607if(!deleted && !added)1608 leading++;1609 trailing++;1610if(!state->apply_in_reverse &&1611 ws_error_action == correct_ws_error)1612check_whitespace(state, line, len, patch->ws_rule);1613break;1614case'-':1615if(state->apply_in_reverse &&1616 ws_error_action != nowarn_ws_error)1617check_whitespace(state, line, len, patch->ws_rule);1618 deleted++;1619 oldlines--;1620 trailing =0;1621break;1622case'+':1623if(!state->apply_in_reverse &&1624 ws_error_action != nowarn_ws_error)1625check_whitespace(state, line, len, patch->ws_rule);1626 added++;1627 newlines--;1628 trailing =0;1629break;16301631/*1632 * We allow "\ No newline at end of file". Depending1633 * on locale settings when the patch was produced we1634 * don't know what this line looks like. The only1635 * thing we do know is that it begins with "\ ".1636 * Checking for 12 is just for sanity check -- any1637 * l10n of "\ No newline..." is at least that long.1638 */1639case'\\':1640if(len <12||memcmp(line,"\\",2))1641return-1;1642break;1643}1644}1645if(oldlines || newlines)1646return-1;1647if(!deleted && !added)1648return-1;16491650 fragment->leading = leading;1651 fragment->trailing = trailing;16521653/*1654 * If a fragment ends with an incomplete line, we failed to include1655 * it in the above loop because we hit oldlines == newlines == 01656 * before seeing it.1657 */1658if(12< size && !memcmp(line,"\\",2))1659 offset +=linelen(line, size);16601661 patch->lines_added += added;1662 patch->lines_deleted += deleted;16631664if(0< patch->is_new && oldlines)1665returnerror(_("new file depends on old contents"));1666if(0< patch->is_delete && newlines)1667returnerror(_("deleted file still has contents"));1668return offset;1669}16701671/*1672 * We have seen "diff --git a/... b/..." header (or a traditional patch1673 * header). Read hunks that belong to this patch into fragments and hang1674 * them to the given patch structure.1675 *1676 * The (fragment->patch, fragment->size) pair points into the memory given1677 * by the caller, not a copy, when we return.1678 */1679static intparse_single_patch(struct apply_state *state,1680const char*line,1681unsigned long size,1682struct patch *patch)1683{1684unsigned long offset =0;1685unsigned long oldlines =0, newlines =0, context =0;1686struct fragment **fragp = &patch->fragments;16871688while(size >4&& !memcmp(line,"@@ -",4)) {1689struct fragment *fragment;1690int len;16911692 fragment =xcalloc(1,sizeof(*fragment));1693 fragment->linenr = state_linenr;1694 len =parse_fragment(state, line, size, patch, fragment);1695if(len <=0)1696die(_("corrupt patch at line%d"), state_linenr);1697 fragment->patch = line;1698 fragment->size = len;1699 oldlines += fragment->oldlines;1700 newlines += fragment->newlines;1701 context += fragment->leading + fragment->trailing;17021703*fragp = fragment;1704 fragp = &fragment->next;17051706 offset += len;1707 line += len;1708 size -= len;1709}17101711/*1712 * If something was removed (i.e. we have old-lines) it cannot1713 * be creation, and if something was added it cannot be1714 * deletion. However, the reverse is not true; --unified=01715 * patches that only add are not necessarily creation even1716 * though they do not have any old lines, and ones that only1717 * delete are not necessarily deletion.1718 *1719 * Unfortunately, a real creation/deletion patch do _not_ have1720 * any context line by definition, so we cannot safely tell it1721 * apart with --unified=0 insanity. At least if the patch has1722 * more than one hunk it is not creation or deletion.1723 */1724if(patch->is_new <0&&1725(oldlines || (patch->fragments && patch->fragments->next)))1726 patch->is_new =0;1727if(patch->is_delete <0&&1728(newlines || (patch->fragments && patch->fragments->next)))1729 patch->is_delete =0;17301731if(0< patch->is_new && oldlines)1732die(_("new file%sdepends on old contents"), patch->new_name);1733if(0< patch->is_delete && newlines)1734die(_("deleted file%sstill has contents"), patch->old_name);1735if(!patch->is_delete && !newlines && context)1736fprintf_ln(stderr,1737_("** warning: "1738"file%sbecomes empty but is not deleted"),1739 patch->new_name);17401741return offset;1742}17431744staticinlineintmetadata_changes(struct patch *patch)1745{1746return patch->is_rename >0||1747 patch->is_copy >0||1748 patch->is_new >0||1749 patch->is_delete ||1750(patch->old_mode && patch->new_mode &&1751 patch->old_mode != patch->new_mode);1752}17531754static char*inflate_it(const void*data,unsigned long size,1755unsigned long inflated_size)1756{1757 git_zstream stream;1758void*out;1759int st;17601761memset(&stream,0,sizeof(stream));17621763 stream.next_in = (unsigned char*)data;1764 stream.avail_in = size;1765 stream.next_out = out =xmalloc(inflated_size);1766 stream.avail_out = inflated_size;1767git_inflate_init(&stream);1768 st =git_inflate(&stream, Z_FINISH);1769git_inflate_end(&stream);1770if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1771free(out);1772return NULL;1773}1774return out;1775}17761777/*1778 * Read a binary hunk and return a new fragment; fragment->patch1779 * points at an allocated memory that the caller must free, so1780 * it is marked as "->free_patch = 1".1781 */1782static struct fragment *parse_binary_hunk(char**buf_p,1783unsigned long*sz_p,1784int*status_p,1785int*used_p)1786{1787/*1788 * Expect a line that begins with binary patch method ("literal"1789 * or "delta"), followed by the length of data before deflating.1790 * a sequence of 'length-byte' followed by base-85 encoded data1791 * should follow, terminated by a newline.1792 *1793 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1794 * and we would limit the patch line to 66 characters,1795 * so one line can fit up to 13 groups that would decode1796 * to 52 bytes max. The length byte 'A'-'Z' corresponds1797 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1798 */1799int llen, used;1800unsigned long size = *sz_p;1801char*buffer = *buf_p;1802int patch_method;1803unsigned long origlen;1804char*data = NULL;1805int hunk_size =0;1806struct fragment *frag;18071808 llen =linelen(buffer, size);1809 used = llen;18101811*status_p =0;18121813if(starts_with(buffer,"delta ")) {1814 patch_method = BINARY_DELTA_DEFLATED;1815 origlen =strtoul(buffer +6, NULL,10);1816}1817else if(starts_with(buffer,"literal ")) {1818 patch_method = BINARY_LITERAL_DEFLATED;1819 origlen =strtoul(buffer +8, NULL,10);1820}1821else1822return NULL;18231824 state_linenr++;1825 buffer += llen;1826while(1) {1827int byte_length, max_byte_length, newsize;1828 llen =linelen(buffer, size);1829 used += llen;1830 state_linenr++;1831if(llen ==1) {1832/* consume the blank line */1833 buffer++;1834 size--;1835break;1836}1837/*1838 * Minimum line is "A00000\n" which is 7-byte long,1839 * and the line length must be multiple of 5 plus 2.1840 */1841if((llen <7) || (llen-2) %5)1842goto corrupt;1843 max_byte_length = (llen -2) /5*4;1844 byte_length = *buffer;1845if('A'<= byte_length && byte_length <='Z')1846 byte_length = byte_length -'A'+1;1847else if('a'<= byte_length && byte_length <='z')1848 byte_length = byte_length -'a'+27;1849else1850goto corrupt;1851/* if the input length was not multiple of 4, we would1852 * have filler at the end but the filler should never1853 * exceed 3 bytes1854 */1855if(max_byte_length < byte_length ||1856 byte_length <= max_byte_length -4)1857goto corrupt;1858 newsize = hunk_size + byte_length;1859 data =xrealloc(data, newsize);1860if(decode_85(data + hunk_size, buffer +1, byte_length))1861goto corrupt;1862 hunk_size = newsize;1863 buffer += llen;1864 size -= llen;1865}18661867 frag =xcalloc(1,sizeof(*frag));1868 frag->patch =inflate_it(data, hunk_size, origlen);1869 frag->free_patch =1;1870if(!frag->patch)1871goto corrupt;1872free(data);1873 frag->size = origlen;1874*buf_p = buffer;1875*sz_p = size;1876*used_p = used;1877 frag->binary_patch_method = patch_method;1878return frag;18791880 corrupt:1881free(data);1882*status_p = -1;1883error(_("corrupt binary patch at line%d: %.*s"),1884 state_linenr-1, llen-1, buffer);1885return NULL;1886}18871888/*1889 * Returns:1890 * -1 in case of error,1891 * the length of the parsed binary patch otherwise1892 */1893static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1894{1895/*1896 * We have read "GIT binary patch\n"; what follows is a line1897 * that says the patch method (currently, either "literal" or1898 * "delta") and the length of data before deflating; a1899 * sequence of 'length-byte' followed by base-85 encoded data1900 * follows.1901 *1902 * When a binary patch is reversible, there is another binary1903 * hunk in the same format, starting with patch method (either1904 * "literal" or "delta") with the length of data, and a sequence1905 * of length-byte + base-85 encoded data, terminated with another1906 * empty line. This data, when applied to the postimage, produces1907 * the preimage.1908 */1909struct fragment *forward;1910struct fragment *reverse;1911int status;1912int used, used_1;19131914 forward =parse_binary_hunk(&buffer, &size, &status, &used);1915if(!forward && !status)1916/* there has to be one hunk (forward hunk) */1917returnerror(_("unrecognized binary patch at line%d"), state_linenr-1);1918if(status)1919/* otherwise we already gave an error message */1920return status;19211922 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1923if(reverse)1924 used += used_1;1925else if(status) {1926/*1927 * Not having reverse hunk is not an error, but having1928 * a corrupt reverse hunk is.1929 */1930free((void*) forward->patch);1931free(forward);1932return status;1933}1934 forward->next = reverse;1935 patch->fragments = forward;1936 patch->is_binary =1;1937return used;1938}19391940static voidprefix_one(struct apply_state *state,char**name)1941{1942char*old_name = *name;1943if(!old_name)1944return;1945*name =xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));1946free(old_name);1947}19481949static voidprefix_patch(struct apply_state *state,struct patch *p)1950{1951if(!state->prefix || p->is_toplevel_relative)1952return;1953prefix_one(state, &p->new_name);1954prefix_one(state, &p->old_name);1955}19561957/*1958 * include/exclude1959 */19601961static struct string_list limit_by_name;1962static int has_include;1963static voidadd_name_limit(const char*name,int exclude)1964{1965struct string_list_item *it;19661967 it =string_list_append(&limit_by_name, name);1968 it->util = exclude ? NULL : (void*)1;1969}19701971static intuse_patch(struct apply_state *state,struct patch *p)1972{1973const char*pathname = p->new_name ? p->new_name : p->old_name;1974int i;19751976/* Paths outside are not touched regardless of "--include" */1977if(0< state->prefix_length) {1978int pathlen =strlen(pathname);1979if(pathlen <= state->prefix_length ||1980memcmp(state->prefix, pathname, state->prefix_length))1981return0;1982}19831984/* See if it matches any of exclude/include rule */1985for(i =0; i < limit_by_name.nr; i++) {1986struct string_list_item *it = &limit_by_name.items[i];1987if(!wildmatch(it->string, pathname,0, NULL))1988return(it->util != NULL);1989}19901991/*1992 * If we had any include, a path that does not match any rule is1993 * not used. Otherwise, we saw bunch of exclude rules (or none)1994 * and such a path is used.1995 */1996return!has_include;1997}199819992000/*2001 * Read the patch text in "buffer" that extends for "size" bytes; stop2002 * reading after seeing a single patch (i.e. changes to a single file).2003 * Create fragments (i.e. patch hunks) and hang them to the given patch.2004 * Return the number of bytes consumed, so that the caller can call us2005 * again for the next patch.2006 */2007static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2008{2009int hdrsize, patchsize;2010int offset =find_header(state, buffer, size, &hdrsize, patch);20112012if(offset <0)2013return offset;20142015prefix_patch(state, patch);20162017if(!use_patch(state, patch))2018 patch->ws_rule =0;2019else2020 patch->ws_rule =whitespace_rule(patch->new_name2021? patch->new_name2022: patch->old_name);20232024 patchsize =parse_single_patch(state,2025 buffer + offset + hdrsize,2026 size - offset - hdrsize,2027 patch);20282029if(!patchsize) {2030static const char git_binary[] ="GIT binary patch\n";2031int hd = hdrsize + offset;2032unsigned long llen =linelen(buffer + hd, size - hd);20332034if(llen ==sizeof(git_binary) -1&&2035!memcmp(git_binary, buffer + hd, llen)) {2036int used;2037 state_linenr++;2038 used =parse_binary(buffer + hd + llen,2039 size - hd - llen, patch);2040if(used <0)2041return-1;2042if(used)2043 patchsize = used + llen;2044else2045 patchsize =0;2046}2047else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2048static const char*binhdr[] = {2049"Binary files ",2050"Files ",2051 NULL,2052};2053int i;2054for(i =0; binhdr[i]; i++) {2055int len =strlen(binhdr[i]);2056if(len < size - hd &&2057!memcmp(binhdr[i], buffer + hd, len)) {2058 state_linenr++;2059 patch->is_binary =1;2060 patchsize = llen;2061break;2062}2063}2064}20652066/* Empty patch cannot be applied if it is a text patch2067 * without metadata change. A binary patch appears2068 * empty to us here.2069 */2070if((state->apply || state->check) &&2071(!patch->is_binary && !metadata_changes(patch)))2072die(_("patch with only garbage at line%d"), state_linenr);2073}20742075return offset + hdrsize + patchsize;2076}20772078#define swap(a,b) myswap((a),(b),sizeof(a))20792080#define myswap(a, b, size) do { \2081 unsigned char mytmp[size]; \2082 memcpy(mytmp, &a, size); \2083 memcpy(&a, &b, size); \2084 memcpy(&b, mytmp, size); \2085} while (0)20862087static voidreverse_patches(struct patch *p)2088{2089for(; p; p = p->next) {2090struct fragment *frag = p->fragments;20912092swap(p->new_name, p->old_name);2093swap(p->new_mode, p->old_mode);2094swap(p->is_new, p->is_delete);2095swap(p->lines_added, p->lines_deleted);2096swap(p->old_sha1_prefix, p->new_sha1_prefix);20972098for(; frag; frag = frag->next) {2099swap(frag->newpos, frag->oldpos);2100swap(frag->newlines, frag->oldlines);2101}2102}2103}21042105static const char pluses[] =2106"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2107static const char minuses[]=2108"----------------------------------------------------------------------";21092110static voidshow_stats(struct patch *patch)2111{2112struct strbuf qname = STRBUF_INIT;2113char*cp = patch->new_name ? patch->new_name : patch->old_name;2114int max, add, del;21152116quote_c_style(cp, &qname, NULL,0);21172118/*2119 * "scale" the filename2120 */2121 max = max_len;2122if(max >50)2123 max =50;21242125if(qname.len > max) {2126 cp =strchr(qname.buf + qname.len +3- max,'/');2127if(!cp)2128 cp = qname.buf + qname.len +3- max;2129strbuf_splice(&qname,0, cp - qname.buf,"...",3);2130}21312132if(patch->is_binary) {2133printf(" %-*s | Bin\n", max, qname.buf);2134strbuf_release(&qname);2135return;2136}21372138printf(" %-*s |", max, qname.buf);2139strbuf_release(&qname);21402141/*2142 * scale the add/delete2143 */2144 max = max + max_change >70?70- max : max_change;2145 add = patch->lines_added;2146 del = patch->lines_deleted;21472148if(max_change >0) {2149int total = ((add + del) * max + max_change /2) / max_change;2150 add = (add * max + max_change /2) / max_change;2151 del = total - add;2152}2153printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2154 add, pluses, del, minuses);2155}21562157static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2158{2159switch(st->st_mode & S_IFMT) {2160case S_IFLNK:2161if(strbuf_readlink(buf, path, st->st_size) <0)2162returnerror(_("unable to read symlink%s"), path);2163return0;2164case S_IFREG:2165if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2166returnerror(_("unable to open or read%s"), path);2167convert_to_git(path, buf->buf, buf->len, buf,0);2168return0;2169default:2170return-1;2171}2172}21732174/*2175 * Update the preimage, and the common lines in postimage,2176 * from buffer buf of length len. If postlen is 0 the postimage2177 * is updated in place, otherwise it's updated on a new buffer2178 * of length postlen2179 */21802181static voidupdate_pre_post_images(struct image *preimage,2182struct image *postimage,2183char*buf,2184size_t len,size_t postlen)2185{2186int i, ctx, reduced;2187char*new, *old, *fixed;2188struct image fixed_preimage;21892190/*2191 * Update the preimage with whitespace fixes. Note that we2192 * are not losing preimage->buf -- apply_one_fragment() will2193 * free "oldlines".2194 */2195prepare_image(&fixed_preimage, buf, len,1);2196assert(postlen2197? fixed_preimage.nr == preimage->nr2198: fixed_preimage.nr <= preimage->nr);2199for(i =0; i < fixed_preimage.nr; i++)2200 fixed_preimage.line[i].flag = preimage->line[i].flag;2201free(preimage->line_allocated);2202*preimage = fixed_preimage;22032204/*2205 * Adjust the common context lines in postimage. This can be2206 * done in-place when we are shrinking it with whitespace2207 * fixing, but needs a new buffer when ignoring whitespace or2208 * expanding leading tabs to spaces.2209 *2210 * We trust the caller to tell us if the update can be done2211 * in place (postlen==0) or not.2212 */2213 old = postimage->buf;2214if(postlen)2215new= postimage->buf =xmalloc(postlen);2216else2217new= old;2218 fixed = preimage->buf;22192220for(i = reduced = ctx =0; i < postimage->nr; i++) {2221size_t l_len = postimage->line[i].len;2222if(!(postimage->line[i].flag & LINE_COMMON)) {2223/* an added line -- no counterparts in preimage */2224memmove(new, old, l_len);2225 old += l_len;2226new+= l_len;2227continue;2228}22292230/* a common context -- skip it in the original postimage */2231 old += l_len;22322233/* and find the corresponding one in the fixed preimage */2234while(ctx < preimage->nr &&2235!(preimage->line[ctx].flag & LINE_COMMON)) {2236 fixed += preimage->line[ctx].len;2237 ctx++;2238}22392240/*2241 * preimage is expected to run out, if the caller2242 * fixed addition of trailing blank lines.2243 */2244if(preimage->nr <= ctx) {2245 reduced++;2246continue;2247}22482249/* and copy it in, while fixing the line length */2250 l_len = preimage->line[ctx].len;2251memcpy(new, fixed, l_len);2252new+= l_len;2253 fixed += l_len;2254 postimage->line[i].len = l_len;2255 ctx++;2256}22572258if(postlen2259? postlen <new- postimage->buf2260: postimage->len <new- postimage->buf)2261die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2262(int)postlen, (int) postimage->len, (int)(new- postimage->buf));22632264/* Fix the length of the whole thing */2265 postimage->len =new- postimage->buf;2266 postimage->nr -= reduced;2267}22682269static intline_by_line_fuzzy_match(struct image *img,2270struct image *preimage,2271struct image *postimage,2272unsigned longtry,2273int try_lno,2274int preimage_limit)2275{2276int i;2277size_t imgoff =0;2278size_t preoff =0;2279size_t postlen = postimage->len;2280size_t extra_chars;2281char*buf;2282char*preimage_eof;2283char*preimage_end;2284struct strbuf fixed;2285char*fixed_buf;2286size_t fixed_len;22872288for(i =0; i < preimage_limit; i++) {2289size_t prelen = preimage->line[i].len;2290size_t imglen = img->line[try_lno+i].len;22912292if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2293 preimage->buf + preoff, prelen))2294return0;2295if(preimage->line[i].flag & LINE_COMMON)2296 postlen += imglen - prelen;2297 imgoff += imglen;2298 preoff += prelen;2299}23002301/*2302 * Ok, the preimage matches with whitespace fuzz.2303 *2304 * imgoff now holds the true length of the target that2305 * matches the preimage before the end of the file.2306 *2307 * Count the number of characters in the preimage that fall2308 * beyond the end of the file and make sure that all of them2309 * are whitespace characters. (This can only happen if2310 * we are removing blank lines at the end of the file.)2311 */2312 buf = preimage_eof = preimage->buf + preoff;2313for( ; i < preimage->nr; i++)2314 preoff += preimage->line[i].len;2315 preimage_end = preimage->buf + preoff;2316for( ; buf < preimage_end; buf++)2317if(!isspace(*buf))2318return0;23192320/*2321 * Update the preimage and the common postimage context2322 * lines to use the same whitespace as the target.2323 * If whitespace is missing in the target (i.e.2324 * if the preimage extends beyond the end of the file),2325 * use the whitespace from the preimage.2326 */2327 extra_chars = preimage_end - preimage_eof;2328strbuf_init(&fixed, imgoff + extra_chars);2329strbuf_add(&fixed, img->buf +try, imgoff);2330strbuf_add(&fixed, preimage_eof, extra_chars);2331 fixed_buf =strbuf_detach(&fixed, &fixed_len);2332update_pre_post_images(preimage, postimage,2333 fixed_buf, fixed_len, postlen);2334return1;2335}23362337static intmatch_fragment(struct image *img,2338struct image *preimage,2339struct image *postimage,2340unsigned longtry,2341int try_lno,2342unsigned ws_rule,2343int match_beginning,int match_end)2344{2345int i;2346char*fixed_buf, *buf, *orig, *target;2347struct strbuf fixed;2348size_t fixed_len, postlen;2349int preimage_limit;23502351if(preimage->nr + try_lno <= img->nr) {2352/*2353 * The hunk falls within the boundaries of img.2354 */2355 preimage_limit = preimage->nr;2356if(match_end && (preimage->nr + try_lno != img->nr))2357return0;2358}else if(ws_error_action == correct_ws_error &&2359(ws_rule & WS_BLANK_AT_EOF)) {2360/*2361 * This hunk extends beyond the end of img, and we are2362 * removing blank lines at the end of the file. This2363 * many lines from the beginning of the preimage must2364 * match with img, and the remainder of the preimage2365 * must be blank.2366 */2367 preimage_limit = img->nr - try_lno;2368}else{2369/*2370 * The hunk extends beyond the end of the img and2371 * we are not removing blanks at the end, so we2372 * should reject the hunk at this position.2373 */2374return0;2375}23762377if(match_beginning && try_lno)2378return0;23792380/* Quick hash check */2381for(i =0; i < preimage_limit; i++)2382if((img->line[try_lno + i].flag & LINE_PATCHED) ||2383(preimage->line[i].hash != img->line[try_lno + i].hash))2384return0;23852386if(preimage_limit == preimage->nr) {2387/*2388 * Do we have an exact match? If we were told to match2389 * at the end, size must be exactly at try+fragsize,2390 * otherwise try+fragsize must be still within the preimage,2391 * and either case, the old piece should match the preimage2392 * exactly.2393 */2394if((match_end2395? (try+ preimage->len == img->len)2396: (try+ preimage->len <= img->len)) &&2397!memcmp(img->buf +try, preimage->buf, preimage->len))2398return1;2399}else{2400/*2401 * The preimage extends beyond the end of img, so2402 * there cannot be an exact match.2403 *2404 * There must be one non-blank context line that match2405 * a line before the end of img.2406 */2407char*buf_end;24082409 buf = preimage->buf;2410 buf_end = buf;2411for(i =0; i < preimage_limit; i++)2412 buf_end += preimage->line[i].len;24132414for( ; buf < buf_end; buf++)2415if(!isspace(*buf))2416break;2417if(buf == buf_end)2418return0;2419}24202421/*2422 * No exact match. If we are ignoring whitespace, run a line-by-line2423 * fuzzy matching. We collect all the line length information because2424 * we need it to adjust whitespace if we match.2425 */2426if(ws_ignore_action == ignore_ws_change)2427returnline_by_line_fuzzy_match(img, preimage, postimage,2428try, try_lno, preimage_limit);24292430if(ws_error_action != correct_ws_error)2431return0;24322433/*2434 * The hunk does not apply byte-by-byte, but the hash says2435 * it might with whitespace fuzz. We weren't asked to2436 * ignore whitespace, we were asked to correct whitespace2437 * errors, so let's try matching after whitespace correction.2438 *2439 * While checking the preimage against the target, whitespace2440 * errors in both fixed, we count how large the corresponding2441 * postimage needs to be. The postimage prepared by2442 * apply_one_fragment() has whitespace errors fixed on added2443 * lines already, but the common lines were propagated as-is,2444 * which may become longer when their whitespace errors are2445 * fixed.2446 */24472448/* First count added lines in postimage */2449 postlen =0;2450for(i =0; i < postimage->nr; i++) {2451if(!(postimage->line[i].flag & LINE_COMMON))2452 postlen += postimage->line[i].len;2453}24542455/*2456 * The preimage may extend beyond the end of the file,2457 * but in this loop we will only handle the part of the2458 * preimage that falls within the file.2459 */2460strbuf_init(&fixed, preimage->len +1);2461 orig = preimage->buf;2462 target = img->buf +try;2463for(i =0; i < preimage_limit; i++) {2464size_t oldlen = preimage->line[i].len;2465size_t tgtlen = img->line[try_lno + i].len;2466size_t fixstart = fixed.len;2467struct strbuf tgtfix;2468int match;24692470/* Try fixing the line in the preimage */2471ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24722473/* Try fixing the line in the target */2474strbuf_init(&tgtfix, tgtlen);2475ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);24762477/*2478 * If they match, either the preimage was based on2479 * a version before our tree fixed whitespace breakage,2480 * or we are lacking a whitespace-fix patch the tree2481 * the preimage was based on already had (i.e. target2482 * has whitespace breakage, the preimage doesn't).2483 * In either case, we are fixing the whitespace breakages2484 * so we might as well take the fix together with their2485 * real change.2486 */2487 match = (tgtfix.len == fixed.len - fixstart &&2488!memcmp(tgtfix.buf, fixed.buf + fixstart,2489 fixed.len - fixstart));24902491/* Add the length if this is common with the postimage */2492if(preimage->line[i].flag & LINE_COMMON)2493 postlen += tgtfix.len;24942495strbuf_release(&tgtfix);2496if(!match)2497goto unmatch_exit;24982499 orig += oldlen;2500 target += tgtlen;2501}250225032504/*2505 * Now handle the lines in the preimage that falls beyond the2506 * end of the file (if any). They will only match if they are2507 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2508 * false).2509 */2510for( ; i < preimage->nr; i++) {2511size_t fixstart = fixed.len;/* start of the fixed preimage */2512size_t oldlen = preimage->line[i].len;2513int j;25142515/* Try fixing the line in the preimage */2516ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25172518for(j = fixstart; j < fixed.len; j++)2519if(!isspace(fixed.buf[j]))2520goto unmatch_exit;25212522 orig += oldlen;2523}25242525/*2526 * Yes, the preimage is based on an older version that still2527 * has whitespace breakages unfixed, and fixing them makes the2528 * hunk match. Update the context lines in the postimage.2529 */2530 fixed_buf =strbuf_detach(&fixed, &fixed_len);2531if(postlen < postimage->len)2532 postlen =0;2533update_pre_post_images(preimage, postimage,2534 fixed_buf, fixed_len, postlen);2535return1;25362537 unmatch_exit:2538strbuf_release(&fixed);2539return0;2540}25412542static intfind_pos(struct image *img,2543struct image *preimage,2544struct image *postimage,2545int line,2546unsigned ws_rule,2547int match_beginning,int match_end)2548{2549int i;2550unsigned long backwards, forwards,try;2551int backwards_lno, forwards_lno, try_lno;25522553/*2554 * If match_beginning or match_end is specified, there is no2555 * point starting from a wrong line that will never match and2556 * wander around and wait for a match at the specified end.2557 */2558if(match_beginning)2559 line =0;2560else if(match_end)2561 line = img->nr - preimage->nr;25622563/*2564 * Because the comparison is unsigned, the following test2565 * will also take care of a negative line number that can2566 * result when match_end and preimage is larger than the target.2567 */2568if((size_t) line > img->nr)2569 line = img->nr;25702571try=0;2572for(i =0; i < line; i++)2573try+= img->line[i].len;25742575/*2576 * There's probably some smart way to do this, but I'll leave2577 * that to the smart and beautiful people. I'm simple and stupid.2578 */2579 backwards =try;2580 backwards_lno = line;2581 forwards =try;2582 forwards_lno = line;2583 try_lno = line;25842585for(i =0; ; i++) {2586if(match_fragment(img, preimage, postimage,2587try, try_lno, ws_rule,2588 match_beginning, match_end))2589return try_lno;25902591 again:2592if(backwards_lno ==0&& forwards_lno == img->nr)2593break;25942595if(i &1) {2596if(backwards_lno ==0) {2597 i++;2598goto again;2599}2600 backwards_lno--;2601 backwards -= img->line[backwards_lno].len;2602try= backwards;2603 try_lno = backwards_lno;2604}else{2605if(forwards_lno == img->nr) {2606 i++;2607goto again;2608}2609 forwards += img->line[forwards_lno].len;2610 forwards_lno++;2611try= forwards;2612 try_lno = forwards_lno;2613}26142615}2616return-1;2617}26182619static voidremove_first_line(struct image *img)2620{2621 img->buf += img->line[0].len;2622 img->len -= img->line[0].len;2623 img->line++;2624 img->nr--;2625}26262627static voidremove_last_line(struct image *img)2628{2629 img->len -= img->line[--img->nr].len;2630}26312632/*2633 * The change from "preimage" and "postimage" has been found to2634 * apply at applied_pos (counts in line numbers) in "img".2635 * Update "img" to remove "preimage" and replace it with "postimage".2636 */2637static voidupdate_image(struct apply_state *state,2638struct image *img,2639int applied_pos,2640struct image *preimage,2641struct image *postimage)2642{2643/*2644 * remove the copy of preimage at offset in img2645 * and replace it with postimage2646 */2647int i, nr;2648size_t remove_count, insert_count, applied_at =0;2649char*result;2650int preimage_limit;26512652/*2653 * If we are removing blank lines at the end of img,2654 * the preimage may extend beyond the end.2655 * If that is the case, we must be careful only to2656 * remove the part of the preimage that falls within2657 * the boundaries of img. Initialize preimage_limit2658 * to the number of lines in the preimage that falls2659 * within the boundaries.2660 */2661 preimage_limit = preimage->nr;2662if(preimage_limit > img->nr - applied_pos)2663 preimage_limit = img->nr - applied_pos;26642665for(i =0; i < applied_pos; i++)2666 applied_at += img->line[i].len;26672668 remove_count =0;2669for(i =0; i < preimage_limit; i++)2670 remove_count += img->line[applied_pos + i].len;2671 insert_count = postimage->len;26722673/* Adjust the contents */2674 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2675memcpy(result, img->buf, applied_at);2676memcpy(result + applied_at, postimage->buf, postimage->len);2677memcpy(result + applied_at + postimage->len,2678 img->buf + (applied_at + remove_count),2679 img->len - (applied_at + remove_count));2680free(img->buf);2681 img->buf = result;2682 img->len += insert_count - remove_count;2683 result[img->len] ='\0';26842685/* Adjust the line table */2686 nr = img->nr + postimage->nr - preimage_limit;2687if(preimage_limit < postimage->nr) {2688/*2689 * NOTE: this knows that we never call remove_first_line()2690 * on anything other than pre/post image.2691 */2692REALLOC_ARRAY(img->line, nr);2693 img->line_allocated = img->line;2694}2695if(preimage_limit != postimage->nr)2696memmove(img->line + applied_pos + postimage->nr,2697 img->line + applied_pos + preimage_limit,2698(img->nr - (applied_pos + preimage_limit)) *2699sizeof(*img->line));2700memcpy(img->line + applied_pos,2701 postimage->line,2702 postimage->nr *sizeof(*img->line));2703if(!state->allow_overlap)2704for(i =0; i < postimage->nr; i++)2705 img->line[applied_pos + i].flag |= LINE_PATCHED;2706 img->nr = nr;2707}27082709/*2710 * Use the patch-hunk text in "frag" to prepare two images (preimage and2711 * postimage) for the hunk. Find lines that match "preimage" in "img" and2712 * replace the part of "img" with "postimage" text.2713 */2714static intapply_one_fragment(struct apply_state *state,2715struct image *img,struct fragment *frag,2716int inaccurate_eof,unsigned ws_rule,2717int nth_fragment)2718{2719int match_beginning, match_end;2720const char*patch = frag->patch;2721int size = frag->size;2722char*old, *oldlines;2723struct strbuf newlines;2724int new_blank_lines_at_end =0;2725int found_new_blank_lines_at_end =0;2726int hunk_linenr = frag->linenr;2727unsigned long leading, trailing;2728int pos, applied_pos;2729struct image preimage;2730struct image postimage;27312732memset(&preimage,0,sizeof(preimage));2733memset(&postimage,0,sizeof(postimage));2734 oldlines =xmalloc(size);2735strbuf_init(&newlines, size);27362737 old = oldlines;2738while(size >0) {2739char first;2740int len =linelen(patch, size);2741int plen;2742int added_blank_line =0;2743int is_blank_context =0;2744size_t start;27452746if(!len)2747break;27482749/*2750 * "plen" is how much of the line we should use for2751 * the actual patch data. Normally we just remove the2752 * first character on the line, but if the line is2753 * followed by "\ No newline", then we also remove the2754 * last one (which is the newline, of course).2755 */2756 plen = len -1;2757if(len < size && patch[len] =='\\')2758 plen--;2759 first = *patch;2760if(state->apply_in_reverse) {2761if(first =='-')2762 first ='+';2763else if(first =='+')2764 first ='-';2765}27662767switch(first) {2768case'\n':2769/* Newer GNU diff, empty context line */2770if(plen <0)2771/* ... followed by '\No newline'; nothing */2772break;2773*old++ ='\n';2774strbuf_addch(&newlines,'\n');2775add_line_info(&preimage,"\n",1, LINE_COMMON);2776add_line_info(&postimage,"\n",1, LINE_COMMON);2777 is_blank_context =1;2778break;2779case' ':2780if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2781ws_blank_line(patch +1, plen, ws_rule))2782 is_blank_context =1;2783case'-':2784memcpy(old, patch +1, plen);2785add_line_info(&preimage, old, plen,2786(first ==' '? LINE_COMMON :0));2787 old += plen;2788if(first =='-')2789break;2790/* Fall-through for ' ' */2791case'+':2792/* --no-add does not add new lines */2793if(first =='+'&& state->no_add)2794break;27952796 start = newlines.len;2797if(first !='+'||2798!whitespace_error ||2799 ws_error_action != correct_ws_error) {2800strbuf_add(&newlines, patch +1, plen);2801}2802else{2803ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2804}2805add_line_info(&postimage, newlines.buf + start, newlines.len - start,2806(first =='+'?0: LINE_COMMON));2807if(first =='+'&&2808(ws_rule & WS_BLANK_AT_EOF) &&2809ws_blank_line(patch +1, plen, ws_rule))2810 added_blank_line =1;2811break;2812case'@':case'\\':2813/* Ignore it, we already handled it */2814break;2815default:2816if(state->apply_verbosely)2817error(_("invalid start of line: '%c'"), first);2818 applied_pos = -1;2819goto out;2820}2821if(added_blank_line) {2822if(!new_blank_lines_at_end)2823 found_new_blank_lines_at_end = hunk_linenr;2824 new_blank_lines_at_end++;2825}2826else if(is_blank_context)2827;2828else2829 new_blank_lines_at_end =0;2830 patch += len;2831 size -= len;2832 hunk_linenr++;2833}2834if(inaccurate_eof &&2835 old > oldlines && old[-1] =='\n'&&2836 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2837 old--;2838strbuf_setlen(&newlines, newlines.len -1);2839}28402841 leading = frag->leading;2842 trailing = frag->trailing;28432844/*2845 * A hunk to change lines at the beginning would begin with2846 * @@ -1,L +N,M @@2847 * but we need to be careful. -U0 that inserts before the second2848 * line also has this pattern.2849 *2850 * And a hunk to add to an empty file would begin with2851 * @@ -0,0 +N,M @@2852 *2853 * In other words, a hunk that is (frag->oldpos <= 1) with or2854 * without leading context must match at the beginning.2855 */2856 match_beginning = (!frag->oldpos ||2857(frag->oldpos ==1&& !state->unidiff_zero));28582859/*2860 * A hunk without trailing lines must match at the end.2861 * However, we simply cannot tell if a hunk must match end2862 * from the lack of trailing lines if the patch was generated2863 * with unidiff without any context.2864 */2865 match_end = !state->unidiff_zero && !trailing;28662867 pos = frag->newpos ? (frag->newpos -1) :0;2868 preimage.buf = oldlines;2869 preimage.len = old - oldlines;2870 postimage.buf = newlines.buf;2871 postimage.len = newlines.len;2872 preimage.line = preimage.line_allocated;2873 postimage.line = postimage.line_allocated;28742875for(;;) {28762877 applied_pos =find_pos(img, &preimage, &postimage, pos,2878 ws_rule, match_beginning, match_end);28792880if(applied_pos >=0)2881break;28822883/* Am I at my context limits? */2884if((leading <= state->p_context) && (trailing <= state->p_context))2885break;2886if(match_beginning || match_end) {2887 match_beginning = match_end =0;2888continue;2889}28902891/*2892 * Reduce the number of context lines; reduce both2893 * leading and trailing if they are equal otherwise2894 * just reduce the larger context.2895 */2896if(leading >= trailing) {2897remove_first_line(&preimage);2898remove_first_line(&postimage);2899 pos--;2900 leading--;2901}2902if(trailing > leading) {2903remove_last_line(&preimage);2904remove_last_line(&postimage);2905 trailing--;2906}2907}29082909if(applied_pos >=0) {2910if(new_blank_lines_at_end &&2911 preimage.nr + applied_pos >= img->nr &&2912(ws_rule & WS_BLANK_AT_EOF) &&2913 ws_error_action != nowarn_ws_error) {2914record_ws_error(state, WS_BLANK_AT_EOF,"+",1,2915 found_new_blank_lines_at_end);2916if(ws_error_action == correct_ws_error) {2917while(new_blank_lines_at_end--)2918remove_last_line(&postimage);2919}2920/*2921 * We would want to prevent write_out_results()2922 * from taking place in apply_patch() that follows2923 * the callchain led us here, which is:2924 * apply_patch->check_patch_list->check_patch->2925 * apply_data->apply_fragments->apply_one_fragment2926 */2927if(ws_error_action == die_on_ws_error)2928 state->apply =0;2929}29302931if(state->apply_verbosely && applied_pos != pos) {2932int offset = applied_pos - pos;2933if(state->apply_in_reverse)2934 offset =0- offset;2935fprintf_ln(stderr,2936Q_("Hunk #%dsucceeded at%d(offset%dline).",2937"Hunk #%dsucceeded at%d(offset%dlines).",2938 offset),2939 nth_fragment, applied_pos +1, offset);2940}29412942/*2943 * Warn if it was necessary to reduce the number2944 * of context lines.2945 */2946if((leading != frag->leading) ||2947(trailing != frag->trailing))2948fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2949" to apply fragment at%d"),2950 leading, trailing, applied_pos+1);2951update_image(state, img, applied_pos, &preimage, &postimage);2952}else{2953if(state->apply_verbosely)2954error(_("while searching for:\n%.*s"),2955(int)(old - oldlines), oldlines);2956}29572958out:2959free(oldlines);2960strbuf_release(&newlines);2961free(preimage.line_allocated);2962free(postimage.line_allocated);29632964return(applied_pos <0);2965}29662967static intapply_binary_fragment(struct apply_state *state,2968struct image *img,2969struct patch *patch)2970{2971struct fragment *fragment = patch->fragments;2972unsigned long len;2973void*dst;29742975if(!fragment)2976returnerror(_("missing binary patch data for '%s'"),2977 patch->new_name ?2978 patch->new_name :2979 patch->old_name);29802981/* Binary patch is irreversible without the optional second hunk */2982if(state->apply_in_reverse) {2983if(!fragment->next)2984returnerror("cannot reverse-apply a binary patch "2985"without the reverse hunk to '%s'",2986 patch->new_name2987? patch->new_name : patch->old_name);2988 fragment = fragment->next;2989}2990switch(fragment->binary_patch_method) {2991case BINARY_DELTA_DEFLATED:2992 dst =patch_delta(img->buf, img->len, fragment->patch,2993 fragment->size, &len);2994if(!dst)2995return-1;2996clear_image(img);2997 img->buf = dst;2998 img->len = len;2999return0;3000case BINARY_LITERAL_DEFLATED:3001clear_image(img);3002 img->len = fragment->size;3003 img->buf =xmemdupz(fragment->patch, img->len);3004return0;3005}3006return-1;3007}30083009/*3010 * Replace "img" with the result of applying the binary patch.3011 * The binary patch data itself in patch->fragment is still kept3012 * but the preimage prepared by the caller in "img" is freed here3013 * or in the helper function apply_binary_fragment() this calls.3014 */3015static intapply_binary(struct apply_state *state,3016struct image *img,3017struct patch *patch)3018{3019const char*name = patch->old_name ? patch->old_name : patch->new_name;3020unsigned char sha1[20];30213022/*3023 * For safety, we require patch index line to contain3024 * full 40-byte textual SHA1 for old and new, at least for now.3025 */3026if(strlen(patch->old_sha1_prefix) !=40||3027strlen(patch->new_sha1_prefix) !=40||3028get_sha1_hex(patch->old_sha1_prefix, sha1) ||3029get_sha1_hex(patch->new_sha1_prefix, sha1))3030returnerror("cannot apply binary patch to '%s' "3031"without full index line", name);30323033if(patch->old_name) {3034/*3035 * See if the old one matches what the patch3036 * applies to.3037 */3038hash_sha1_file(img->buf, img->len, blob_type, sha1);3039if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3040returnerror("the patch applies to '%s' (%s), "3041"which does not match the "3042"current contents.",3043 name,sha1_to_hex(sha1));3044}3045else{3046/* Otherwise, the old one must be empty. */3047if(img->len)3048returnerror("the patch applies to an empty "3049"'%s' but it is not empty", name);3050}30513052get_sha1_hex(patch->new_sha1_prefix, sha1);3053if(is_null_sha1(sha1)) {3054clear_image(img);3055return0;/* deletion patch */3056}30573058if(has_sha1_file(sha1)) {3059/* We already have the postimage */3060enum object_type type;3061unsigned long size;3062char*result;30633064 result =read_sha1_file(sha1, &type, &size);3065if(!result)3066returnerror("the necessary postimage%sfor "3067"'%s' cannot be read",3068 patch->new_sha1_prefix, name);3069clear_image(img);3070 img->buf = result;3071 img->len = size;3072}else{3073/*3074 * We have verified buf matches the preimage;3075 * apply the patch data to it, which is stored3076 * in the patch->fragments->{patch,size}.3077 */3078if(apply_binary_fragment(state, img, patch))3079returnerror(_("binary patch does not apply to '%s'"),3080 name);30813082/* verify that the result matches */3083hash_sha1_file(img->buf, img->len, blob_type, sha1);3084if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3085returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3086 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3087}30883089return0;3090}30913092static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3093{3094struct fragment *frag = patch->fragments;3095const char*name = patch->old_name ? patch->old_name : patch->new_name;3096unsigned ws_rule = patch->ws_rule;3097unsigned inaccurate_eof = patch->inaccurate_eof;3098int nth =0;30993100if(patch->is_binary)3101returnapply_binary(state, img, patch);31023103while(frag) {3104 nth++;3105if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3106error(_("patch failed:%s:%ld"), name, frag->oldpos);3107if(!state->apply_with_reject)3108return-1;3109 frag->rejected =1;3110}3111 frag = frag->next;3112}3113return0;3114}31153116static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3117{3118if(S_ISGITLINK(mode)) {3119strbuf_grow(buf,100);3120strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3121}else{3122enum object_type type;3123unsigned long sz;3124char*result;31253126 result =read_sha1_file(sha1, &type, &sz);3127if(!result)3128return-1;3129/* XXX read_sha1_file NUL-terminates */3130strbuf_attach(buf, result, sz, sz +1);3131}3132return0;3133}31343135static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3136{3137if(!ce)3138return0;3139returnread_blob_object(buf, ce->sha1, ce->ce_mode);3140}31413142static struct patch *in_fn_table(const char*name)3143{3144struct string_list_item *item;31453146if(name == NULL)3147return NULL;31483149 item =string_list_lookup(&fn_table, name);3150if(item != NULL)3151return(struct patch *)item->util;31523153return NULL;3154}31553156/*3157 * item->util in the filename table records the status of the path.3158 * Usually it points at a patch (whose result records the contents3159 * of it after applying it), but it could be PATH_WAS_DELETED for a3160 * path that a previously applied patch has already removed, or3161 * PATH_TO_BE_DELETED for a path that a later patch would remove.3162 *3163 * The latter is needed to deal with a case where two paths A and B3164 * are swapped by first renaming A to B and then renaming B to A;3165 * moving A to B should not be prevented due to presence of B as we3166 * will remove it in a later patch.3167 */3168#define PATH_TO_BE_DELETED ((struct patch *) -2)3169#define PATH_WAS_DELETED ((struct patch *) -1)31703171static intto_be_deleted(struct patch *patch)3172{3173return patch == PATH_TO_BE_DELETED;3174}31753176static intwas_deleted(struct patch *patch)3177{3178return patch == PATH_WAS_DELETED;3179}31803181static voidadd_to_fn_table(struct patch *patch)3182{3183struct string_list_item *item;31843185/*3186 * Always add new_name unless patch is a deletion3187 * This should cover the cases for normal diffs,3188 * file creations and copies3189 */3190if(patch->new_name != NULL) {3191 item =string_list_insert(&fn_table, patch->new_name);3192 item->util = patch;3193}31943195/*3196 * store a failure on rename/deletion cases because3197 * later chunks shouldn't patch old names3198 */3199if((patch->new_name == NULL) || (patch->is_rename)) {3200 item =string_list_insert(&fn_table, patch->old_name);3201 item->util = PATH_WAS_DELETED;3202}3203}32043205static voidprepare_fn_table(struct patch *patch)3206{3207/*3208 * store information about incoming file deletion3209 */3210while(patch) {3211if((patch->new_name == NULL) || (patch->is_rename)) {3212struct string_list_item *item;3213 item =string_list_insert(&fn_table, patch->old_name);3214 item->util = PATH_TO_BE_DELETED;3215}3216 patch = patch->next;3217}3218}32193220static intcheckout_target(struct index_state *istate,3221struct cache_entry *ce,struct stat *st)3222{3223struct checkout costate;32243225memset(&costate,0,sizeof(costate));3226 costate.base_dir ="";3227 costate.refresh_cache =1;3228 costate.istate = istate;3229if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3230returnerror(_("cannot checkout%s"), ce->name);3231return0;3232}32333234static struct patch *previous_patch(struct patch *patch,int*gone)3235{3236struct patch *previous;32373238*gone =0;3239if(patch->is_copy || patch->is_rename)3240return NULL;/* "git" patches do not depend on the order */32413242 previous =in_fn_table(patch->old_name);3243if(!previous)3244return NULL;32453246if(to_be_deleted(previous))3247return NULL;/* the deletion hasn't happened yet */32483249if(was_deleted(previous))3250*gone =1;32513252return previous;3253}32543255static intverify_index_match(const struct cache_entry *ce,struct stat *st)3256{3257if(S_ISGITLINK(ce->ce_mode)) {3258if(!S_ISDIR(st->st_mode))3259return-1;3260return0;3261}3262returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3263}32643265#define SUBMODULE_PATCH_WITHOUT_INDEX 132663267static intload_patch_target(struct apply_state *state,3268struct strbuf *buf,3269const struct cache_entry *ce,3270struct stat *st,3271const char*name,3272unsigned expected_mode)3273{3274if(state->cached || state->check_index) {3275if(read_file_or_gitlink(ce, buf))3276returnerror(_("read of%sfailed"), name);3277}else if(name) {3278if(S_ISGITLINK(expected_mode)) {3279if(ce)3280returnread_file_or_gitlink(ce, buf);3281else3282return SUBMODULE_PATCH_WITHOUT_INDEX;3283}else if(has_symlink_leading_path(name,strlen(name))) {3284returnerror(_("reading from '%s' beyond a symbolic link"), name);3285}else{3286if(read_old_data(st, name, buf))3287returnerror(_("read of%sfailed"), name);3288}3289}3290return0;3291}32923293/*3294 * We are about to apply "patch"; populate the "image" with the3295 * current version we have, from the working tree or from the index,3296 * depending on the situation e.g. --cached/--index. If we are3297 * applying a non-git patch that incrementally updates the tree,3298 * we read from the result of a previous diff.3299 */3300static intload_preimage(struct apply_state *state,3301struct image *image,3302struct patch *patch,struct stat *st,3303const struct cache_entry *ce)3304{3305struct strbuf buf = STRBUF_INIT;3306size_t len;3307char*img;3308struct patch *previous;3309int status;33103311 previous =previous_patch(patch, &status);3312if(status)3313returnerror(_("path%shas been renamed/deleted"),3314 patch->old_name);3315if(previous) {3316/* We have a patched copy in memory; use that. */3317strbuf_add(&buf, previous->result, previous->resultsize);3318}else{3319 status =load_patch_target(state, &buf, ce, st,3320 patch->old_name, patch->old_mode);3321if(status <0)3322return status;3323else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3324/*3325 * There is no way to apply subproject3326 * patch without looking at the index.3327 * NEEDSWORK: shouldn't this be flagged3328 * as an error???3329 */3330free_fragment_list(patch->fragments);3331 patch->fragments = NULL;3332}else if(status) {3333returnerror(_("read of%sfailed"), patch->old_name);3334}3335}33363337 img =strbuf_detach(&buf, &len);3338prepare_image(image, img, len, !patch->is_binary);3339return0;3340}33413342static intthree_way_merge(struct image *image,3343char*path,3344const unsigned char*base,3345const unsigned char*ours,3346const unsigned char*theirs)3347{3348 mmfile_t base_file, our_file, their_file;3349 mmbuffer_t result = { NULL };3350int status;33513352read_mmblob(&base_file, base);3353read_mmblob(&our_file, ours);3354read_mmblob(&their_file, theirs);3355 status =ll_merge(&result, path,3356&base_file,"base",3357&our_file,"ours",3358&their_file,"theirs", NULL);3359free(base_file.ptr);3360free(our_file.ptr);3361free(their_file.ptr);3362if(status <0|| !result.ptr) {3363free(result.ptr);3364return-1;3365}3366clear_image(image);3367 image->buf = result.ptr;3368 image->len = result.size;33693370return status;3371}33723373/*3374 * When directly falling back to add/add three-way merge, we read from3375 * the current contents of the new_name. In no cases other than that3376 * this function will be called.3377 */3378static intload_current(struct apply_state *state,3379struct image *image,3380struct patch *patch)3381{3382struct strbuf buf = STRBUF_INIT;3383int status, pos;3384size_t len;3385char*img;3386struct stat st;3387struct cache_entry *ce;3388char*name = patch->new_name;3389unsigned mode = patch->new_mode;33903391if(!patch->is_new)3392die("BUG: patch to%sis not a creation", patch->old_name);33933394 pos =cache_name_pos(name,strlen(name));3395if(pos <0)3396returnerror(_("%s: does not exist in index"), name);3397 ce = active_cache[pos];3398if(lstat(name, &st)) {3399if(errno != ENOENT)3400returnerror(_("%s:%s"), name,strerror(errno));3401if(checkout_target(&the_index, ce, &st))3402return-1;3403}3404if(verify_index_match(ce, &st))3405returnerror(_("%s: does not match index"), name);34063407 status =load_patch_target(state, &buf, ce, &st, name, mode);3408if(status <0)3409return status;3410else if(status)3411return-1;3412 img =strbuf_detach(&buf, &len);3413prepare_image(image, img, len, !patch->is_binary);3414return0;3415}34163417static inttry_threeway(struct apply_state *state,3418struct image *image,3419struct patch *patch,3420struct stat *st,3421const struct cache_entry *ce)3422{3423unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3424struct strbuf buf = STRBUF_INIT;3425size_t len;3426int status;3427char*img;3428struct image tmp_image;34293430/* No point falling back to 3-way merge in these cases */3431if(patch->is_delete ||3432S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3433return-1;34343435/* Preimage the patch was prepared for */3436if(patch->is_new)3437write_sha1_file("",0, blob_type, pre_sha1);3438else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3439read_blob_object(&buf, pre_sha1, patch->old_mode))3440returnerror("repository lacks the necessary blob to fall back on 3-way merge.");34413442fprintf(stderr,"Falling back to three-way merge...\n");34433444 img =strbuf_detach(&buf, &len);3445prepare_image(&tmp_image, img, len,1);3446/* Apply the patch to get the post image */3447if(apply_fragments(state, &tmp_image, patch) <0) {3448clear_image(&tmp_image);3449return-1;3450}3451/* post_sha1[] is theirs */3452write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3453clear_image(&tmp_image);34543455/* our_sha1[] is ours */3456if(patch->is_new) {3457if(load_current(state, &tmp_image, patch))3458returnerror("cannot read the current contents of '%s'",3459 patch->new_name);3460}else{3461if(load_preimage(state, &tmp_image, patch, st, ce))3462returnerror("cannot read the current contents of '%s'",3463 patch->old_name);3464}3465write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3466clear_image(&tmp_image);34673468/* in-core three-way merge between post and our using pre as base */3469 status =three_way_merge(image, patch->new_name,3470 pre_sha1, our_sha1, post_sha1);3471if(status <0) {3472fprintf(stderr,"Failed to fall back on three-way merge...\n");3473return status;3474}34753476if(status) {3477 patch->conflicted_threeway =1;3478if(patch->is_new)3479oidclr(&patch->threeway_stage[0]);3480else3481hashcpy(patch->threeway_stage[0].hash, pre_sha1);3482hashcpy(patch->threeway_stage[1].hash, our_sha1);3483hashcpy(patch->threeway_stage[2].hash, post_sha1);3484fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3485}else{3486fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3487}3488return0;3489}34903491static intapply_data(struct apply_state *state,struct patch *patch,3492struct stat *st,const struct cache_entry *ce)3493{3494struct image image;34953496if(load_preimage(state, &image, patch, st, ce) <0)3497return-1;34983499if(patch->direct_to_threeway ||3500apply_fragments(state, &image, patch) <0) {3501/* Note: with --reject, apply_fragments() returns 0 */3502if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3503return-1;3504}3505 patch->result = image.buf;3506 patch->resultsize = image.len;3507add_to_fn_table(patch);3508free(image.line_allocated);35093510if(0< patch->is_delete && patch->resultsize)3511returnerror(_("removal patch leaves file contents"));35123513return0;3514}35153516/*3517 * If "patch" that we are looking at modifies or deletes what we have,3518 * we would want it not to lose any local modification we have, either3519 * in the working tree or in the index.3520 *3521 * This also decides if a non-git patch is a creation patch or a3522 * modification to an existing empty file. We do not check the state3523 * of the current tree for a creation patch in this function; the caller3524 * check_patch() separately makes sure (and errors out otherwise) that3525 * the path the patch creates does not exist in the current tree.3526 */3527static intcheck_preimage(struct apply_state *state,3528struct patch *patch,3529struct cache_entry **ce,3530struct stat *st)3531{3532const char*old_name = patch->old_name;3533struct patch *previous = NULL;3534int stat_ret =0, status;3535unsigned st_mode =0;35363537if(!old_name)3538return0;35393540assert(patch->is_new <=0);3541 previous =previous_patch(patch, &status);35423543if(status)3544returnerror(_("path%shas been renamed/deleted"), old_name);3545if(previous) {3546 st_mode = previous->new_mode;3547}else if(!state->cached) {3548 stat_ret =lstat(old_name, st);3549if(stat_ret && errno != ENOENT)3550returnerror(_("%s:%s"), old_name,strerror(errno));3551}35523553if(state->check_index && !previous) {3554int pos =cache_name_pos(old_name,strlen(old_name));3555if(pos <0) {3556if(patch->is_new <0)3557goto is_new;3558returnerror(_("%s: does not exist in index"), old_name);3559}3560*ce = active_cache[pos];3561if(stat_ret <0) {3562if(checkout_target(&the_index, *ce, st))3563return-1;3564}3565if(!state->cached &&verify_index_match(*ce, st))3566returnerror(_("%s: does not match index"), old_name);3567if(state->cached)3568 st_mode = (*ce)->ce_mode;3569}else if(stat_ret <0) {3570if(patch->is_new <0)3571goto is_new;3572returnerror(_("%s:%s"), old_name,strerror(errno));3573}35743575if(!state->cached && !previous)3576 st_mode =ce_mode_from_stat(*ce, st->st_mode);35773578if(patch->is_new <0)3579 patch->is_new =0;3580if(!patch->old_mode)3581 patch->old_mode = st_mode;3582if((st_mode ^ patch->old_mode) & S_IFMT)3583returnerror(_("%s: wrong type"), old_name);3584if(st_mode != patch->old_mode)3585warning(_("%shas type%o, expected%o"),3586 old_name, st_mode, patch->old_mode);3587if(!patch->new_mode && !patch->is_delete)3588 patch->new_mode = st_mode;3589return0;35903591 is_new:3592 patch->is_new =1;3593 patch->is_delete =0;3594free(patch->old_name);3595 patch->old_name = NULL;3596return0;3597}359835993600#define EXISTS_IN_INDEX 13601#define EXISTS_IN_WORKTREE 236023603static intcheck_to_create(struct apply_state *state,3604const char*new_name,3605int ok_if_exists)3606{3607struct stat nst;36083609if(state->check_index &&3610cache_name_pos(new_name,strlen(new_name)) >=0&&3611!ok_if_exists)3612return EXISTS_IN_INDEX;3613if(state->cached)3614return0;36153616if(!lstat(new_name, &nst)) {3617if(S_ISDIR(nst.st_mode) || ok_if_exists)3618return0;3619/*3620 * A leading component of new_name might be a symlink3621 * that is going to be removed with this patch, but3622 * still pointing at somewhere that has the path.3623 * In such a case, path "new_name" does not exist as3624 * far as git is concerned.3625 */3626if(has_symlink_leading_path(new_name,strlen(new_name)))3627return0;36283629return EXISTS_IN_WORKTREE;3630}else if((errno != ENOENT) && (errno != ENOTDIR)) {3631returnerror("%s:%s", new_name,strerror(errno));3632}3633return0;3634}36353636/*3637 * We need to keep track of how symlinks in the preimage are3638 * manipulated by the patches. A patch to add a/b/c where a/b3639 * is a symlink should not be allowed to affect the directory3640 * the symlink points at, but if the same patch removes a/b,3641 * it is perfectly fine, as the patch removes a/b to make room3642 * to create a directory a/b so that a/b/c can be created.3643 */3644static struct string_list symlink_changes;3645#define SYMLINK_GOES_AWAY 013646#define SYMLINK_IN_RESULT 0236473648static uintptr_tregister_symlink_changes(const char*path,uintptr_t what)3649{3650struct string_list_item *ent;36513652 ent =string_list_lookup(&symlink_changes, path);3653if(!ent) {3654 ent =string_list_insert(&symlink_changes, path);3655 ent->util = (void*)0;3656}3657 ent->util = (void*)(what | ((uintptr_t)ent->util));3658return(uintptr_t)ent->util;3659}36603661static uintptr_tcheck_symlink_changes(const char*path)3662{3663struct string_list_item *ent;36643665 ent =string_list_lookup(&symlink_changes, path);3666if(!ent)3667return0;3668return(uintptr_t)ent->util;3669}36703671static voidprepare_symlink_changes(struct patch *patch)3672{3673for( ; patch; patch = patch->next) {3674if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3675(patch->is_rename || patch->is_delete))3676/* the symlink at patch->old_name is removed */3677register_symlink_changes(patch->old_name, SYMLINK_GOES_AWAY);36783679if(patch->new_name &&S_ISLNK(patch->new_mode))3680/* the symlink at patch->new_name is created or remains */3681register_symlink_changes(patch->new_name, SYMLINK_IN_RESULT);3682}3683}36843685static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3686{3687do{3688unsigned int change;36893690while(--name->len && name->buf[name->len] !='/')3691;/* scan backwards */3692if(!name->len)3693break;3694 name->buf[name->len] ='\0';3695 change =check_symlink_changes(name->buf);3696if(change & SYMLINK_IN_RESULT)3697return1;3698if(change & SYMLINK_GOES_AWAY)3699/*3700 * This cannot be "return 0", because we may3701 * see a new one created at a higher level.3702 */3703continue;37043705/* otherwise, check the preimage */3706if(state->check_index) {3707struct cache_entry *ce;37083709 ce =cache_file_exists(name->buf, name->len, ignore_case);3710if(ce &&S_ISLNK(ce->ce_mode))3711return1;3712}else{3713struct stat st;3714if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3715return1;3716}3717}while(1);3718return0;3719}37203721static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3722{3723int ret;3724struct strbuf name = STRBUF_INIT;37253726assert(*name_ !='\0');3727strbuf_addstr(&name, name_);3728 ret =path_is_beyond_symlink_1(state, &name);3729strbuf_release(&name);37303731return ret;3732}37333734static voiddie_on_unsafe_path(struct patch *patch)3735{3736const char*old_name = NULL;3737const char*new_name = NULL;3738if(patch->is_delete)3739 old_name = patch->old_name;3740else if(!patch->is_new && !patch->is_copy)3741 old_name = patch->old_name;3742if(!patch->is_delete)3743 new_name = patch->new_name;37443745if(old_name && !verify_path(old_name))3746die(_("invalid path '%s'"), old_name);3747if(new_name && !verify_path(new_name))3748die(_("invalid path '%s'"), new_name);3749}37503751/*3752 * Check and apply the patch in-core; leave the result in patch->result3753 * for the caller to write it out to the final destination.3754 */3755static intcheck_patch(struct apply_state *state,struct patch *patch)3756{3757struct stat st;3758const char*old_name = patch->old_name;3759const char*new_name = patch->new_name;3760const char*name = old_name ? old_name : new_name;3761struct cache_entry *ce = NULL;3762struct patch *tpatch;3763int ok_if_exists;3764int status;37653766 patch->rejected =1;/* we will drop this after we succeed */37673768 status =check_preimage(state, patch, &ce, &st);3769if(status)3770return status;3771 old_name = patch->old_name;37723773/*3774 * A type-change diff is always split into a patch to delete3775 * old, immediately followed by a patch to create new (see3776 * diff.c::run_diff()); in such a case it is Ok that the entry3777 * to be deleted by the previous patch is still in the working3778 * tree and in the index.3779 *3780 * A patch to swap-rename between A and B would first rename A3781 * to B and then rename B to A. While applying the first one,3782 * the presence of B should not stop A from getting renamed to3783 * B; ask to_be_deleted() about the later rename. Removal of3784 * B and rename from A to B is handled the same way by asking3785 * was_deleted().3786 */3787if((tpatch =in_fn_table(new_name)) &&3788(was_deleted(tpatch) ||to_be_deleted(tpatch)))3789 ok_if_exists =1;3790else3791 ok_if_exists =0;37923793if(new_name &&3794((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3795int err =check_to_create(state, new_name, ok_if_exists);37963797if(err && state->threeway) {3798 patch->direct_to_threeway =1;3799}else switch(err) {3800case0:3801break;/* happy */3802case EXISTS_IN_INDEX:3803returnerror(_("%s: already exists in index"), new_name);3804break;3805case EXISTS_IN_WORKTREE:3806returnerror(_("%s: already exists in working directory"),3807 new_name);3808default:3809return err;3810}38113812if(!patch->new_mode) {3813if(0< patch->is_new)3814 patch->new_mode = S_IFREG |0644;3815else3816 patch->new_mode = patch->old_mode;3817}3818}38193820if(new_name && old_name) {3821int same = !strcmp(old_name, new_name);3822if(!patch->new_mode)3823 patch->new_mode = patch->old_mode;3824if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3825if(same)3826returnerror(_("new mode (%o) of%sdoes not "3827"match old mode (%o)"),3828 patch->new_mode, new_name,3829 patch->old_mode);3830else3831returnerror(_("new mode (%o) of%sdoes not "3832"match old mode (%o) of%s"),3833 patch->new_mode, new_name,3834 patch->old_mode, old_name);3835}3836}38373838if(!state->unsafe_paths)3839die_on_unsafe_path(patch);38403841/*3842 * An attempt to read from or delete a path that is beyond a3843 * symbolic link will be prevented by load_patch_target() that3844 * is called at the beginning of apply_data() so we do not3845 * have to worry about a patch marked with "is_delete" bit3846 * here. We however need to make sure that the patch result3847 * is not deposited to a path that is beyond a symbolic link3848 * here.3849 */3850if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3851returnerror(_("affected file '%s' is beyond a symbolic link"),3852 patch->new_name);38533854if(apply_data(state, patch, &st, ce) <0)3855returnerror(_("%s: patch does not apply"), name);3856 patch->rejected =0;3857return0;3858}38593860static intcheck_patch_list(struct apply_state *state,struct patch *patch)3861{3862int err =0;38633864prepare_symlink_changes(patch);3865prepare_fn_table(patch);3866while(patch) {3867if(state->apply_verbosely)3868say_patch_name(stderr,3869_("Checking patch%s..."), patch);3870 err |=check_patch(state, patch);3871 patch = patch->next;3872}3873return err;3874}38753876/* This function tries to read the sha1 from the current index */3877static intget_current_sha1(const char*path,unsigned char*sha1)3878{3879int pos;38803881if(read_cache() <0)3882return-1;3883 pos =cache_name_pos(path,strlen(path));3884if(pos <0)3885return-1;3886hashcpy(sha1, active_cache[pos]->sha1);3887return0;3888}38893890static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3891{3892/*3893 * A usable gitlink patch has only one fragment (hunk) that looks like:3894 * @@ -1 +1 @@3895 * -Subproject commit <old sha1>3896 * +Subproject commit <new sha1>3897 * or3898 * @@ -1 +0,0 @@3899 * -Subproject commit <old sha1>3900 * for a removal patch.3901 */3902struct fragment *hunk = p->fragments;3903static const char heading[] ="-Subproject commit ";3904char*preimage;39053906if(/* does the patch have only one hunk? */3907 hunk && !hunk->next &&3908/* is its preimage one line? */3909 hunk->oldpos ==1&& hunk->oldlines ==1&&3910/* does preimage begin with the heading? */3911(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3912starts_with(++preimage, heading) &&3913/* does it record full SHA-1? */3914!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3915 preimage[sizeof(heading) +40-1] =='\n'&&3916/* does the abbreviated name on the index line agree with it? */3917starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3918return0;/* it all looks fine */39193920/* we may have full object name on the index line */3921returnget_sha1_hex(p->old_sha1_prefix, sha1);3922}39233924/* Build an index that contains the just the files needed for a 3way merge */3925static voidbuild_fake_ancestor(struct patch *list,const char*filename)3926{3927struct patch *patch;3928struct index_state result = { NULL };3929static struct lock_file lock;39303931/* Once we start supporting the reverse patch, it may be3932 * worth showing the new sha1 prefix, but until then...3933 */3934for(patch = list; patch; patch = patch->next) {3935unsigned char sha1[20];3936struct cache_entry *ce;3937const char*name;39383939 name = patch->old_name ? patch->old_name : patch->new_name;3940if(0< patch->is_new)3941continue;39423943if(S_ISGITLINK(patch->old_mode)) {3944if(!preimage_sha1_in_gitlink_patch(patch, sha1))3945;/* ok, the textual part looks sane */3946else3947die("sha1 information is lacking or useless for submodule%s",3948 name);3949}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {3950;/* ok */3951}else if(!patch->lines_added && !patch->lines_deleted) {3952/* mode-only change: update the current */3953if(get_current_sha1(patch->old_name, sha1))3954die("mode change for%s, which is not "3955"in current HEAD", name);3956}else3957die("sha1 information is lacking or useless "3958"(%s).", name);39593960 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);3961if(!ce)3962die(_("make_cache_entry failed for path '%s'"), name);3963if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3964die("Could not add%sto temporary index", name);3965}39663967hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);3968if(write_locked_index(&result, &lock, COMMIT_LOCK))3969die("Could not write temporary index to%s", filename);39703971discard_index(&result);3972}39733974static voidstat_patch_list(struct patch *patch)3975{3976int files, adds, dels;39773978for(files = adds = dels =0; patch ; patch = patch->next) {3979 files++;3980 adds += patch->lines_added;3981 dels += patch->lines_deleted;3982show_stats(patch);3983}39843985print_stat_summary(stdout, files, adds, dels);3986}39873988static voidnumstat_patch_list(struct apply_state *state,3989struct patch *patch)3990{3991for( ; patch; patch = patch->next) {3992const char*name;3993 name = patch->new_name ? patch->new_name : patch->old_name;3994if(patch->is_binary)3995printf("-\t-\t");3996else3997printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3998write_name_quoted(name, stdout, state->line_termination);3999}4000}40014002static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4003{4004if(mode)4005printf("%smode%06o%s\n", newdelete, mode, name);4006else4007printf("%s %s\n", newdelete, name);4008}40094010static voidshow_mode_change(struct patch *p,int show_name)4011{4012if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4013if(show_name)4014printf(" mode change%06o =>%06o%s\n",4015 p->old_mode, p->new_mode, p->new_name);4016else4017printf(" mode change%06o =>%06o\n",4018 p->old_mode, p->new_mode);4019}4020}40214022static voidshow_rename_copy(struct patch *p)4023{4024const char*renamecopy = p->is_rename ?"rename":"copy";4025const char*old, *new;40264027/* Find common prefix */4028 old = p->old_name;4029new= p->new_name;4030while(1) {4031const char*slash_old, *slash_new;4032 slash_old =strchr(old,'/');4033 slash_new =strchr(new,'/');4034if(!slash_old ||4035!slash_new ||4036 slash_old - old != slash_new -new||4037memcmp(old,new, slash_new -new))4038break;4039 old = slash_old +1;4040new= slash_new +1;4041}4042/* p->old_name thru old is the common prefix, and old and new4043 * through the end of names are renames4044 */4045if(old != p->old_name)4046printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4047(int)(old - p->old_name), p->old_name,4048 old,new, p->score);4049else4050printf("%s %s=>%s(%d%%)\n", renamecopy,4051 p->old_name, p->new_name, p->score);4052show_mode_change(p,0);4053}40544055static voidsummary_patch_list(struct patch *patch)4056{4057struct patch *p;40584059for(p = patch; p; p = p->next) {4060if(p->is_new)4061show_file_mode_name("create", p->new_mode, p->new_name);4062else if(p->is_delete)4063show_file_mode_name("delete", p->old_mode, p->old_name);4064else{4065if(p->is_rename || p->is_copy)4066show_rename_copy(p);4067else{4068if(p->score) {4069printf(" rewrite%s(%d%%)\n",4070 p->new_name, p->score);4071show_mode_change(p,0);4072}4073else4074show_mode_change(p,1);4075}4076}4077}4078}40794080static voidpatch_stats(struct patch *patch)4081{4082int lines = patch->lines_added + patch->lines_deleted;40834084if(lines > max_change)4085 max_change = lines;4086if(patch->old_name) {4087int len =quote_c_style(patch->old_name, NULL, NULL,0);4088if(!len)4089 len =strlen(patch->old_name);4090if(len > max_len)4091 max_len = len;4092}4093if(patch->new_name) {4094int len =quote_c_style(patch->new_name, NULL, NULL,0);4095if(!len)4096 len =strlen(patch->new_name);4097if(len > max_len)4098 max_len = len;4099}4100}41014102static voidremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4103{4104if(state->update_index) {4105if(remove_file_from_cache(patch->old_name) <0)4106die(_("unable to remove%sfrom index"), patch->old_name);4107}4108if(!state->cached) {4109if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4110remove_path(patch->old_name);4111}4112}4113}41144115static voidadd_index_file(struct apply_state *state,4116const char*path,4117unsigned mode,4118void*buf,4119unsigned long size)4120{4121struct stat st;4122struct cache_entry *ce;4123int namelen =strlen(path);4124unsigned ce_size =cache_entry_size(namelen);41254126if(!state->update_index)4127return;41284129 ce =xcalloc(1, ce_size);4130memcpy(ce->name, path, namelen);4131 ce->ce_mode =create_ce_mode(mode);4132 ce->ce_flags =create_ce_flags(0);4133 ce->ce_namelen = namelen;4134if(S_ISGITLINK(mode)) {4135const char*s;41364137if(!skip_prefix(buf,"Subproject commit ", &s) ||4138get_sha1_hex(s, ce->sha1))4139die(_("corrupt patch for submodule%s"), path);4140}else{4141if(!state->cached) {4142if(lstat(path, &st) <0)4143die_errno(_("unable to stat newly created file '%s'"),4144 path);4145fill_stat_cache_info(ce, &st);4146}4147if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4148die(_("unable to create backing store for newly created file%s"), path);4149}4150if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4151die(_("unable to add cache entry for%s"), path);4152}41534154static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4155{4156int fd;4157struct strbuf nbuf = STRBUF_INIT;41584159if(S_ISGITLINK(mode)) {4160struct stat st;4161if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4162return0;4163returnmkdir(path,0777);4164}41654166if(has_symlinks &&S_ISLNK(mode))4167/* Although buf:size is counted string, it also is NUL4168 * terminated.4169 */4170returnsymlink(buf, path);41714172 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4173if(fd <0)4174return-1;41754176if(convert_to_working_tree(path, buf, size, &nbuf)) {4177 size = nbuf.len;4178 buf = nbuf.buf;4179}4180write_or_die(fd, buf, size);4181strbuf_release(&nbuf);41824183if(close(fd) <0)4184die_errno(_("closing file '%s'"), path);4185return0;4186}41874188/*4189 * We optimistically assume that the directories exist,4190 * which is true 99% of the time anyway. If they don't,4191 * we create them and try again.4192 */4193static voidcreate_one_file(struct apply_state *state,4194char*path,4195unsigned mode,4196const char*buf,4197unsigned long size)4198{4199if(state->cached)4200return;4201if(!try_create_file(path, mode, buf, size))4202return;42034204if(errno == ENOENT) {4205if(safe_create_leading_directories(path))4206return;4207if(!try_create_file(path, mode, buf, size))4208return;4209}42104211if(errno == EEXIST || errno == EACCES) {4212/* We may be trying to create a file where a directory4213 * used to be.4214 */4215struct stat st;4216if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4217 errno = EEXIST;4218}42194220if(errno == EEXIST) {4221unsigned int nr =getpid();42224223for(;;) {4224char newpath[PATH_MAX];4225mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4226if(!try_create_file(newpath, mode, buf, size)) {4227if(!rename(newpath, path))4228return;4229unlink_or_warn(newpath);4230break;4231}4232if(errno != EEXIST)4233break;4234++nr;4235}4236}4237die_errno(_("unable to write file '%s' mode%o"), path, mode);4238}42394240static voidadd_conflicted_stages_file(struct apply_state *state,4241struct patch *patch)4242{4243int stage, namelen;4244unsigned ce_size, mode;4245struct cache_entry *ce;42464247if(!state->update_index)4248return;4249 namelen =strlen(patch->new_name);4250 ce_size =cache_entry_size(namelen);4251 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);42524253remove_file_from_cache(patch->new_name);4254for(stage =1; stage <4; stage++) {4255if(is_null_oid(&patch->threeway_stage[stage -1]))4256continue;4257 ce =xcalloc(1, ce_size);4258memcpy(ce->name, patch->new_name, namelen);4259 ce->ce_mode =create_ce_mode(mode);4260 ce->ce_flags =create_ce_flags(stage);4261 ce->ce_namelen = namelen;4262hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4263if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4264die(_("unable to add cache entry for%s"), patch->new_name);4265}4266}42674268static voidcreate_file(struct apply_state *state,struct patch *patch)4269{4270char*path = patch->new_name;4271unsigned mode = patch->new_mode;4272unsigned long size = patch->resultsize;4273char*buf = patch->result;42744275if(!mode)4276 mode = S_IFREG |0644;4277create_one_file(state, path, mode, buf, size);42784279if(patch->conflicted_threeway)4280add_conflicted_stages_file(state, patch);4281else4282add_index_file(state, path, mode, buf, size);4283}42844285/* phase zero is to remove, phase one is to create */4286static voidwrite_out_one_result(struct apply_state *state,4287struct patch *patch,4288int phase)4289{4290if(patch->is_delete >0) {4291if(phase ==0)4292remove_file(state, patch,1);4293return;4294}4295if(patch->is_new >0|| patch->is_copy) {4296if(phase ==1)4297create_file(state, patch);4298return;4299}4300/*4301 * Rename or modification boils down to the same4302 * thing: remove the old, write the new4303 */4304if(phase ==0)4305remove_file(state, patch, patch->is_rename);4306if(phase ==1)4307create_file(state, patch);4308}43094310static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4311{4312FILE*rej;4313char namebuf[PATH_MAX];4314struct fragment *frag;4315int cnt =0;4316struct strbuf sb = STRBUF_INIT;43174318for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4319if(!frag->rejected)4320continue;4321 cnt++;4322}43234324if(!cnt) {4325if(state->apply_verbosely)4326say_patch_name(stderr,4327_("Applied patch%scleanly."), patch);4328return0;4329}43304331/* This should not happen, because a removal patch that leaves4332 * contents are marked "rejected" at the patch level.4333 */4334if(!patch->new_name)4335die(_("internal error"));43364337/* Say this even without --verbose */4338strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4339"Applying patch %%swith%drejects...",4340 cnt),4341 cnt);4342say_patch_name(stderr, sb.buf, patch);4343strbuf_release(&sb);43444345 cnt =strlen(patch->new_name);4346if(ARRAY_SIZE(namebuf) <= cnt +5) {4347 cnt =ARRAY_SIZE(namebuf) -5;4348warning(_("truncating .rej filename to %.*s.rej"),4349 cnt -1, patch->new_name);4350}4351memcpy(namebuf, patch->new_name, cnt);4352memcpy(namebuf + cnt,".rej",5);43534354 rej =fopen(namebuf,"w");4355if(!rej)4356returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));43574358/* Normal git tools never deal with .rej, so do not pretend4359 * this is a git patch by saying --git or giving extended4360 * headers. While at it, maybe please "kompare" that wants4361 * the trailing TAB and some garbage at the end of line ;-).4362 */4363fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4364 patch->new_name, patch->new_name);4365for(cnt =1, frag = patch->fragments;4366 frag;4367 cnt++, frag = frag->next) {4368if(!frag->rejected) {4369fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4370continue;4371}4372fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4373fprintf(rej,"%.*s", frag->size, frag->patch);4374if(frag->patch[frag->size-1] !='\n')4375fputc('\n', rej);4376}4377fclose(rej);4378return-1;4379}43804381static intwrite_out_results(struct apply_state *state,struct patch *list)4382{4383int phase;4384int errs =0;4385struct patch *l;4386struct string_list cpath = STRING_LIST_INIT_DUP;43874388for(phase =0; phase <2; phase++) {4389 l = list;4390while(l) {4391if(l->rejected)4392 errs =1;4393else{4394write_out_one_result(state, l, phase);4395if(phase ==1) {4396if(write_out_one_reject(state, l))4397 errs =1;4398if(l->conflicted_threeway) {4399string_list_append(&cpath, l->new_name);4400 errs =1;4401}4402}4403}4404 l = l->next;4405}4406}44074408if(cpath.nr) {4409struct string_list_item *item;44104411string_list_sort(&cpath);4412for_each_string_list_item(item, &cpath)4413fprintf(stderr,"U%s\n", item->string);4414string_list_clear(&cpath,0);44154416rerere(0);4417}44184419return errs;4420}44214422static struct lock_file lock_file;44234424#define INACCURATE_EOF (1<<0)4425#define RECOUNT (1<<1)44264427static intapply_patch(struct apply_state *state,4428int fd,4429const char*filename,4430int options)4431{4432size_t offset;4433struct strbuf buf = STRBUF_INIT;/* owns the patch text */4434struct patch *list = NULL, **listp = &list;4435int skipped_patch =0;44364437 state->patch_input_file = filename;4438read_patch_file(&buf, fd);4439 offset =0;4440while(offset < buf.len) {4441struct patch *patch;4442int nr;44434444 patch =xcalloc(1,sizeof(*patch));4445 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4446 patch->recount = !!(options & RECOUNT);4447 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4448if(nr <0) {4449free_patch(patch);4450break;4451}4452if(state->apply_in_reverse)4453reverse_patches(patch);4454if(use_patch(state, patch)) {4455patch_stats(patch);4456*listp = patch;4457 listp = &patch->next;4458}4459else{4460if(state->apply_verbosely)4461say_patch_name(stderr,_("Skipped patch '%s'."), patch);4462free_patch(patch);4463 skipped_patch++;4464}4465 offset += nr;4466}44674468if(!list && !skipped_patch)4469die(_("unrecognized input"));44704471if(whitespace_error && (ws_error_action == die_on_ws_error))4472 state->apply =0;44734474 state->update_index = state->check_index && state->apply;4475if(state->update_index && newfd <0)4476 newfd =hold_locked_index(&lock_file,1);44774478if(state->check_index) {4479if(read_cache() <0)4480die(_("unable to read index file"));4481}44824483if((state->check || state->apply) &&4484check_patch_list(state, list) <0&&4485!state->apply_with_reject)4486exit(1);44874488if(state->apply &&write_out_results(state, list)) {4489if(state->apply_with_reject)4490exit(1);4491/* with --3way, we still need to write the index out */4492return1;4493}44944495if(state->fake_ancestor)4496build_fake_ancestor(list, state->fake_ancestor);44974498if(state->diffstat)4499stat_patch_list(list);45004501if(state->numstat)4502numstat_patch_list(state, list);45034504if(state->summary)4505summary_patch_list(list);45064507free_patch_list(list);4508strbuf_release(&buf);4509string_list_clear(&fn_table,0);4510return0;4511}45124513static voidgit_apply_config(void)4514{4515git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4516git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4517git_config(git_default_config, NULL);4518}45194520static intoption_parse_exclude(const struct option *opt,4521const char*arg,int unset)4522{4523add_name_limit(arg,1);4524return0;4525}45264527static intoption_parse_include(const struct option *opt,4528const char*arg,int unset)4529{4530add_name_limit(arg,0);4531 has_include =1;4532return0;4533}45344535static intoption_parse_p(const struct option *opt,4536const char*arg,int unset)4537{4538 state_p_value =atoi(arg);4539 p_value_known =1;4540return0;4541}45424543static intoption_parse_space_change(const struct option *opt,4544const char*arg,int unset)4545{4546if(unset)4547 ws_ignore_action = ignore_ws_none;4548else4549 ws_ignore_action = ignore_ws_change;4550return0;4551}45524553static intoption_parse_whitespace(const struct option *opt,4554const char*arg,int unset)4555{4556const char**whitespace_option = opt->value;45574558*whitespace_option = arg;4559parse_whitespace_option(arg);4560return0;4561}45624563static intoption_parse_directory(const struct option *opt,4564const char*arg,int unset)4565{4566strbuf_reset(&root);4567strbuf_addstr(&root, arg);4568strbuf_complete(&root,'/');4569return0;4570}45714572static voidinit_apply_state(struct apply_state *state,const char*prefix)4573{4574memset(state,0,sizeof(*state));4575 state->prefix = prefix;4576 state->prefix_length = state->prefix ?strlen(state->prefix) :0;4577 state->apply =1;4578 state->line_termination ='\n';4579 state->p_context = UINT_MAX;45804581git_apply_config();4582if(apply_default_whitespace)4583parse_whitespace_option(apply_default_whitespace);4584if(apply_default_ignorewhitespace)4585parse_ignorewhitespace_option(apply_default_ignorewhitespace);4586}45874588static voidclear_apply_state(struct apply_state *state)4589{4590/* empty for now */4591}45924593intcmd_apply(int argc,const char**argv,const char*prefix)4594{4595int i;4596int errs =0;4597int is_not_gitdir = !startup_info->have_repository;4598int force_apply =0;4599int options =0;4600int read_stdin =1;4601struct apply_state state;46024603const char*whitespace_option = NULL;46044605struct option builtin_apply_options[] = {4606{ OPTION_CALLBACK,0,"exclude", NULL,N_("path"),4607N_("don't apply changes matching the given path"),46080, option_parse_exclude },4609{ OPTION_CALLBACK,0,"include", NULL,N_("path"),4610N_("apply changes matching the given path"),46110, option_parse_include },4612{ OPTION_CALLBACK,'p', NULL, NULL,N_("num"),4613N_("remove <num> leading slashes from traditional diff paths"),46140, option_parse_p },4615OPT_BOOL(0,"no-add", &state.no_add,4616N_("ignore additions made by the patch")),4617OPT_BOOL(0,"stat", &state.diffstat,4618N_("instead of applying the patch, output diffstat for the input")),4619OPT_NOOP_NOARG(0,"allow-binary-replacement"),4620OPT_NOOP_NOARG(0,"binary"),4621OPT_BOOL(0,"numstat", &state.numstat,4622N_("show number of added and deleted lines in decimal notation")),4623OPT_BOOL(0,"summary", &state.summary,4624N_("instead of applying the patch, output a summary for the input")),4625OPT_BOOL(0,"check", &state.check,4626N_("instead of applying the patch, see if the patch is applicable")),4627OPT_BOOL(0,"index", &state.check_index,4628N_("make sure the patch is applicable to the current index")),4629OPT_BOOL(0,"cached", &state.cached,4630N_("apply a patch without touching the working tree")),4631OPT_BOOL(0,"unsafe-paths", &state.unsafe_paths,4632N_("accept a patch that touches outside the working area")),4633OPT_BOOL(0,"apply", &force_apply,4634N_("also apply the patch (use with --stat/--summary/--check)")),4635OPT_BOOL('3',"3way", &state.threeway,4636N_("attempt three-way merge if a patch does not apply")),4637OPT_FILENAME(0,"build-fake-ancestor", &state.fake_ancestor,4638N_("build a temporary index based on embedded index information")),4639/* Think twice before adding "--nul" synonym to this */4640OPT_SET_INT('z', NULL, &state.line_termination,4641N_("paths are separated with NUL character"),'\0'),4642OPT_INTEGER('C', NULL, &state.p_context,4643N_("ensure at least <n> lines of context match")),4644{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,N_("action"),4645N_("detect new or modified lines that have whitespace errors"),46460, option_parse_whitespace },4647{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,4648N_("ignore changes in whitespace when finding context"),4649 PARSE_OPT_NOARG, option_parse_space_change },4650{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,4651N_("ignore changes in whitespace when finding context"),4652 PARSE_OPT_NOARG, option_parse_space_change },4653OPT_BOOL('R',"reverse", &state.apply_in_reverse,4654N_("apply the patch in reverse")),4655OPT_BOOL(0,"unidiff-zero", &state.unidiff_zero,4656N_("don't expect at least one line of context")),4657OPT_BOOL(0,"reject", &state.apply_with_reject,4658N_("leave the rejected hunks in corresponding *.rej files")),4659OPT_BOOL(0,"allow-overlap", &state.allow_overlap,4660N_("allow overlapping hunks")),4661OPT__VERBOSE(&state.apply_verbosely,N_("be verbose")),4662OPT_BIT(0,"inaccurate-eof", &options,4663N_("tolerate incorrectly detected missing new-line at the end of file"),4664 INACCURATE_EOF),4665OPT_BIT(0,"recount", &options,4666N_("do not trust the line counts in the hunk headers"),4667 RECOUNT),4668{ OPTION_CALLBACK,0,"directory", NULL,N_("root"),4669N_("prepend <root> to all filenames"),46700, option_parse_directory },4671OPT_END()4672};46734674init_apply_state(&state, prefix);46754676 argc =parse_options(argc, argv, state.prefix, builtin_apply_options,4677 apply_usage,0);46784679if(state.apply_with_reject && state.threeway)4680die("--reject and --3way cannot be used together.");4681if(state.cached && state.threeway)4682die("--cached and --3way cannot be used together.");4683if(state.threeway) {4684if(is_not_gitdir)4685die(_("--3way outside a repository"));4686 state.check_index =1;4687}4688if(state.apply_with_reject)4689 state.apply = state.apply_verbosely =1;4690if(!force_apply && (state.diffstat || state.numstat || state.summary || state.check || state.fake_ancestor))4691 state.apply =0;4692if(state.check_index && is_not_gitdir)4693die(_("--index outside a repository"));4694if(state.cached) {4695if(is_not_gitdir)4696die(_("--cached outside a repository"));4697 state.check_index =1;4698}4699if(state.check_index)4700 state.unsafe_paths =0;47014702for(i =0; i < argc; i++) {4703const char*arg = argv[i];4704int fd;47054706if(!strcmp(arg,"-")) {4707 errs |=apply_patch(&state,0,"<stdin>", options);4708 read_stdin =0;4709continue;4710}else if(0< state.prefix_length)4711 arg =prefix_filename(state.prefix,4712 state.prefix_length,4713 arg);47144715 fd =open(arg, O_RDONLY);4716if(fd <0)4717die_errno(_("can't open patch '%s'"), arg);4718 read_stdin =0;4719set_default_whitespace_mode(&state, whitespace_option);4720 errs |=apply_patch(&state, fd, arg, options);4721close(fd);4722}4723set_default_whitespace_mode(&state, whitespace_option);4724if(read_stdin)4725 errs |=apply_patch(&state,0,"<stdin>", options);4726if(whitespace_error) {4727if(squelch_whitespace_errors &&4728 squelch_whitespace_errors < whitespace_error) {4729int squelched =4730 whitespace_error - squelch_whitespace_errors;4731warning(Q_("squelched%dwhitespace error",4732"squelched%dwhitespace errors",4733 squelched),4734 squelched);4735}4736if(ws_error_action == die_on_ws_error)4737die(Q_("%dline adds whitespace errors.",4738"%dlines add whitespace errors.",4739 whitespace_error),4740 whitespace_error);4741if(applied_after_fixing_ws && state.apply)4742warning("%dline%sapplied after"4743" fixing whitespace errors.",4744 applied_after_fixing_ws,4745 applied_after_fixing_ws ==1?"":"s");4746else if(whitespace_error)4747warning(Q_("%dline adds whitespace errors.",4748"%dlines add whitespace errors.",4749 whitespace_error),4750 whitespace_error);4751}47524753if(state.update_index) {4754if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK))4755die(_("Unable to write new index file"));4756}47574758clear_apply_state(&state);47594760return!!errs;4761}