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#include"apply.h" 24 25static const char*const apply_usage[] = { 26N_("git apply [<options>] [<patch>...]"), 27 NULL 28}; 29 30static voidset_default_whitespace_mode(struct apply_state *state) 31{ 32if(!state->whitespace_option && !apply_default_whitespace) 33 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 34} 35 36/* 37 * This represents one "hunk" from a patch, starting with 38 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 39 * patch text is pointed at by patch, and its byte length 40 * is stored in size. leading and trailing are the number 41 * of context lines. 42 */ 43struct fragment { 44unsigned long leading, trailing; 45unsigned long oldpos, oldlines; 46unsigned long newpos, newlines; 47/* 48 * 'patch' is usually borrowed from buf in apply_patch(), 49 * but some codepaths store an allocated buffer. 50 */ 51const char*patch; 52unsigned free_patch:1, 53 rejected:1; 54int size; 55int linenr; 56struct fragment *next; 57}; 58 59/* 60 * When dealing with a binary patch, we reuse "leading" field 61 * to store the type of the binary hunk, either deflated "delta" 62 * or deflated "literal". 63 */ 64#define binary_patch_method leading 65#define BINARY_DELTA_DEFLATED 1 66#define BINARY_LITERAL_DEFLATED 2 67 68/* 69 * This represents a "patch" to a file, both metainfo changes 70 * such as creation/deletion, filemode and content changes represented 71 * as a series of fragments. 72 */ 73struct patch { 74char*new_name, *old_name, *def_name; 75unsigned int old_mode, new_mode; 76int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 77int rejected; 78unsigned ws_rule; 79int lines_added, lines_deleted; 80int score; 81unsigned int is_toplevel_relative:1; 82unsigned int inaccurate_eof:1; 83unsigned int is_binary:1; 84unsigned int is_copy:1; 85unsigned int is_rename:1; 86unsigned int recount:1; 87unsigned int conflicted_threeway:1; 88unsigned int direct_to_threeway:1; 89struct fragment *fragments; 90char*result; 91size_t resultsize; 92char old_sha1_prefix[41]; 93char new_sha1_prefix[41]; 94struct patch *next; 95 96/* three-way fallback result */ 97struct object_id threeway_stage[3]; 98}; 99 100static voidfree_fragment_list(struct fragment *list) 101{ 102while(list) { 103struct fragment *next = list->next; 104if(list->free_patch) 105free((char*)list->patch); 106free(list); 107 list = next; 108} 109} 110 111static voidfree_patch(struct patch *patch) 112{ 113free_fragment_list(patch->fragments); 114free(patch->def_name); 115free(patch->old_name); 116free(patch->new_name); 117free(patch->result); 118free(patch); 119} 120 121static voidfree_patch_list(struct patch *list) 122{ 123while(list) { 124struct patch *next = list->next; 125free_patch(list); 126 list = next; 127} 128} 129 130/* 131 * A line in a file, len-bytes long (includes the terminating LF, 132 * except for an incomplete line at the end if the file ends with 133 * one), and its contents hashes to 'hash'. 134 */ 135struct line { 136size_t len; 137unsigned hash :24; 138unsigned flag :8; 139#define LINE_COMMON 1 140#define LINE_PATCHED 2 141}; 142 143/* 144 * This represents a "file", which is an array of "lines". 145 */ 146struct image { 147char*buf; 148size_t len; 149size_t nr; 150size_t alloc; 151struct line *line_allocated; 152struct line *line; 153}; 154 155static uint32_thash_line(const char*cp,size_t len) 156{ 157size_t i; 158uint32_t h; 159for(i =0, h =0; i < len; i++) { 160if(!isspace(cp[i])) { 161 h = h *3+ (cp[i] &0xff); 162} 163} 164return h; 165} 166 167/* 168 * Compare lines s1 of length n1 and s2 of length n2, ignoring 169 * whitespace difference. Returns 1 if they match, 0 otherwise 170 */ 171static intfuzzy_matchlines(const char*s1,size_t n1, 172const char*s2,size_t n2) 173{ 174const char*last1 = s1 + n1 -1; 175const char*last2 = s2 + n2 -1; 176int result =0; 177 178/* ignore line endings */ 179while((*last1 =='\r') || (*last1 =='\n')) 180 last1--; 181while((*last2 =='\r') || (*last2 =='\n')) 182 last2--; 183 184/* skip leading whitespaces, if both begin with whitespace */ 185if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 186while(isspace(*s1) && (s1 <= last1)) 187 s1++; 188while(isspace(*s2) && (s2 <= last2)) 189 s2++; 190} 191/* early return if both lines are empty */ 192if((s1 > last1) && (s2 > last2)) 193return1; 194while(!result) { 195 result = *s1++ - *s2++; 196/* 197 * Skip whitespace inside. We check for whitespace on 198 * both buffers because we don't want "a b" to match 199 * "ab" 200 */ 201if(isspace(*s1) &&isspace(*s2)) { 202while(isspace(*s1) && s1 <= last1) 203 s1++; 204while(isspace(*s2) && s2 <= last2) 205 s2++; 206} 207/* 208 * If we reached the end on one side only, 209 * lines don't match 210 */ 211if( 212((s2 > last2) && (s1 <= last1)) || 213((s1 > last1) && (s2 <= last2))) 214return0; 215if((s1 > last1) && (s2 > last2)) 216break; 217} 218 219return!result; 220} 221 222static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 223{ 224ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 225 img->line_allocated[img->nr].len = len; 226 img->line_allocated[img->nr].hash =hash_line(bol, len); 227 img->line_allocated[img->nr].flag = flag; 228 img->nr++; 229} 230 231/* 232 * "buf" has the file contents to be patched (read from various sources). 233 * attach it to "image" and add line-based index to it. 234 * "image" now owns the "buf". 235 */ 236static voidprepare_image(struct image *image,char*buf,size_t len, 237int prepare_linetable) 238{ 239const char*cp, *ep; 240 241memset(image,0,sizeof(*image)); 242 image->buf = buf; 243 image->len = len; 244 245if(!prepare_linetable) 246return; 247 248 ep = image->buf + image->len; 249 cp = image->buf; 250while(cp < ep) { 251const char*next; 252for(next = cp; next < ep && *next !='\n'; next++) 253; 254if(next < ep) 255 next++; 256add_line_info(image, cp, next - cp,0); 257 cp = next; 258} 259 image->line = image->line_allocated; 260} 261 262static voidclear_image(struct image *image) 263{ 264free(image->buf); 265free(image->line_allocated); 266memset(image,0,sizeof(*image)); 267} 268 269/* fmt must contain _one_ %s and no other substitution */ 270static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 271{ 272struct strbuf sb = STRBUF_INIT; 273 274if(patch->old_name && patch->new_name && 275strcmp(patch->old_name, patch->new_name)) { 276quote_c_style(patch->old_name, &sb, NULL,0); 277strbuf_addstr(&sb," => "); 278quote_c_style(patch->new_name, &sb, NULL,0); 279}else{ 280const char*n = patch->new_name; 281if(!n) 282 n = patch->old_name; 283quote_c_style(n, &sb, NULL,0); 284} 285fprintf(output, fmt, sb.buf); 286fputc('\n', output); 287strbuf_release(&sb); 288} 289 290#define SLOP (16) 291 292static intread_patch_file(struct strbuf *sb,int fd) 293{ 294if(strbuf_read(sb, fd,0) <0) 295returnerror_errno("git apply: failed to read"); 296 297/* 298 * Make sure that we have some slop in the buffer 299 * so that we can do speculative "memcmp" etc, and 300 * see to it that it is NUL-filled. 301 */ 302strbuf_grow(sb, SLOP); 303memset(sb->buf + sb->len,0, SLOP); 304return0; 305} 306 307static unsigned longlinelen(const char*buffer,unsigned long size) 308{ 309unsigned long len =0; 310while(size--) { 311 len++; 312if(*buffer++ =='\n') 313break; 314} 315return len; 316} 317 318static intis_dev_null(const char*str) 319{ 320returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 321} 322 323#define TERM_SPACE 1 324#define TERM_TAB 2 325 326static intname_terminate(int c,int terminate) 327{ 328if(c ==' '&& !(terminate & TERM_SPACE)) 329return0; 330if(c =='\t'&& !(terminate & TERM_TAB)) 331return0; 332 333return1; 334} 335 336/* remove double slashes to make --index work with such filenames */ 337static char*squash_slash(char*name) 338{ 339int i =0, j =0; 340 341if(!name) 342return NULL; 343 344while(name[i]) { 345if((name[j++] = name[i++]) =='/') 346while(name[i] =='/') 347 i++; 348} 349 name[j] ='\0'; 350return name; 351} 352 353static char*find_name_gnu(struct apply_state *state, 354const char*line, 355const char*def, 356int p_value) 357{ 358struct strbuf name = STRBUF_INIT; 359char*cp; 360 361/* 362 * Proposed "new-style" GNU patch/diff format; see 363 * http://marc.info/?l=git&m=112927316408690&w=2 364 */ 365if(unquote_c_style(&name, line, NULL)) { 366strbuf_release(&name); 367return NULL; 368} 369 370for(cp = name.buf; p_value; p_value--) { 371 cp =strchr(cp,'/'); 372if(!cp) { 373strbuf_release(&name); 374return NULL; 375} 376 cp++; 377} 378 379strbuf_remove(&name,0, cp - name.buf); 380if(state->root.len) 381strbuf_insert(&name,0, state->root.buf, state->root.len); 382returnsquash_slash(strbuf_detach(&name, NULL)); 383} 384 385static size_tsane_tz_len(const char*line,size_t len) 386{ 387const char*tz, *p; 388 389if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 390return0; 391 tz = line + len -strlen(" +0500"); 392 393if(tz[1] !='+'&& tz[1] !='-') 394return0; 395 396for(p = tz +2; p != line + len; p++) 397if(!isdigit(*p)) 398return0; 399 400return line + len - tz; 401} 402 403static size_ttz_with_colon_len(const char*line,size_t len) 404{ 405const char*tz, *p; 406 407if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 408return0; 409 tz = line + len -strlen(" +08:00"); 410 411if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 412return0; 413 p = tz +2; 414if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 415!isdigit(*p++) || !isdigit(*p++)) 416return0; 417 418return line + len - tz; 419} 420 421static size_tdate_len(const char*line,size_t len) 422{ 423const char*date, *p; 424 425if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 426return0; 427 p = date = line + len -strlen("72-02-05"); 428 429if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 430!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 431!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 432return0; 433 434if(date - line >=strlen("19") && 435isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 436 date -=strlen("19"); 437 438return line + len - date; 439} 440 441static size_tshort_time_len(const char*line,size_t len) 442{ 443const char*time, *p; 444 445if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 446return0; 447 p = time = line + len -strlen(" 07:01:32"); 448 449/* Permit 1-digit hours? */ 450if(*p++ !=' '|| 451!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 452!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 453!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 454return0; 455 456return line + len - time; 457} 458 459static size_tfractional_time_len(const char*line,size_t len) 460{ 461const char*p; 462size_t n; 463 464/* Expected format: 19:41:17.620000023 */ 465if(!len || !isdigit(line[len -1])) 466return0; 467 p = line + len -1; 468 469/* Fractional seconds. */ 470while(p > line &&isdigit(*p)) 471 p--; 472if(*p !='.') 473return0; 474 475/* Hours, minutes, and whole seconds. */ 476 n =short_time_len(line, p - line); 477if(!n) 478return0; 479 480return line + len - p + n; 481} 482 483static size_ttrailing_spaces_len(const char*line,size_t len) 484{ 485const char*p; 486 487/* Expected format: ' ' x (1 or more) */ 488if(!len || line[len -1] !=' ') 489return0; 490 491 p = line + len; 492while(p != line) { 493 p--; 494if(*p !=' ') 495return line + len - (p +1); 496} 497 498/* All spaces! */ 499return len; 500} 501 502static size_tdiff_timestamp_len(const char*line,size_t len) 503{ 504const char*end = line + len; 505size_t n; 506 507/* 508 * Posix: 2010-07-05 19:41:17 509 * GNU: 2010-07-05 19:41:17.620000023 -0500 510 */ 511 512if(!isdigit(end[-1])) 513return0; 514 515 n =sane_tz_len(line, end - line); 516if(!n) 517 n =tz_with_colon_len(line, end - line); 518 end -= n; 519 520 n =short_time_len(line, end - line); 521if(!n) 522 n =fractional_time_len(line, end - line); 523 end -= n; 524 525 n =date_len(line, end - line); 526if(!n)/* No date. Too bad. */ 527return0; 528 end -= n; 529 530if(end == line)/* No space before date. */ 531return0; 532if(end[-1] =='\t') {/* Success! */ 533 end--; 534return line + len - end; 535} 536if(end[-1] !=' ')/* No space before date. */ 537return0; 538 539/* Whitespace damage. */ 540 end -=trailing_spaces_len(line, end - line); 541return line + len - end; 542} 543 544static char*find_name_common(struct apply_state *state, 545const char*line, 546const char*def, 547int p_value, 548const char*end, 549int terminate) 550{ 551int len; 552const char*start = NULL; 553 554if(p_value ==0) 555 start = line; 556while(line != end) { 557char c = *line; 558 559if(!end &&isspace(c)) { 560if(c =='\n') 561break; 562if(name_terminate(c, terminate)) 563break; 564} 565 line++; 566if(c =='/'&& !--p_value) 567 start = line; 568} 569if(!start) 570returnsquash_slash(xstrdup_or_null(def)); 571 len = line - start; 572if(!len) 573returnsquash_slash(xstrdup_or_null(def)); 574 575/* 576 * Generally we prefer the shorter name, especially 577 * if the other one is just a variation of that with 578 * something else tacked on to the end (ie "file.orig" 579 * or "file~"). 580 */ 581if(def) { 582int deflen =strlen(def); 583if(deflen < len && !strncmp(start, def, deflen)) 584returnsquash_slash(xstrdup(def)); 585} 586 587if(state->root.len) { 588char*ret =xstrfmt("%s%.*s", state->root.buf, len, start); 589returnsquash_slash(ret); 590} 591 592returnsquash_slash(xmemdupz(start, len)); 593} 594 595static char*find_name(struct apply_state *state, 596const char*line, 597char*def, 598int p_value, 599int terminate) 600{ 601if(*line =='"') { 602char*name =find_name_gnu(state, line, def, p_value); 603if(name) 604return name; 605} 606 607returnfind_name_common(state, line, def, p_value, NULL, terminate); 608} 609 610static char*find_name_traditional(struct apply_state *state, 611const char*line, 612char*def, 613int p_value) 614{ 615size_t len; 616size_t date_len; 617 618if(*line =='"') { 619char*name =find_name_gnu(state, line, def, p_value); 620if(name) 621return name; 622} 623 624 len =strchrnul(line,'\n') - line; 625 date_len =diff_timestamp_len(line, len); 626if(!date_len) 627returnfind_name_common(state, line, def, p_value, NULL, TERM_TAB); 628 len -= date_len; 629 630returnfind_name_common(state, line, def, p_value, line + len,0); 631} 632 633static intcount_slashes(const char*cp) 634{ 635int cnt =0; 636char ch; 637 638while((ch = *cp++)) 639if(ch =='/') 640 cnt++; 641return cnt; 642} 643 644/* 645 * Given the string after "--- " or "+++ ", guess the appropriate 646 * p_value for the given patch. 647 */ 648static intguess_p_value(struct apply_state *state,const char*nameline) 649{ 650char*name, *cp; 651int val = -1; 652 653if(is_dev_null(nameline)) 654return-1; 655 name =find_name_traditional(state, nameline, NULL,0); 656if(!name) 657return-1; 658 cp =strchr(name,'/'); 659if(!cp) 660 val =0; 661else if(state->prefix) { 662/* 663 * Does it begin with "a/$our-prefix" and such? Then this is 664 * very likely to apply to our directory. 665 */ 666if(!strncmp(name, state->prefix, state->prefix_length)) 667 val =count_slashes(state->prefix); 668else{ 669 cp++; 670if(!strncmp(cp, state->prefix, state->prefix_length)) 671 val =count_slashes(state->prefix) +1; 672} 673} 674free(name); 675return val; 676} 677 678/* 679 * Does the ---/+++ line have the POSIX timestamp after the last HT? 680 * GNU diff puts epoch there to signal a creation/deletion event. Is 681 * this such a timestamp? 682 */ 683static inthas_epoch_timestamp(const char*nameline) 684{ 685/* 686 * We are only interested in epoch timestamp; any non-zero 687 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 688 * For the same reason, the date must be either 1969-12-31 or 689 * 1970-01-01, and the seconds part must be "00". 690 */ 691const char stamp_regexp[] = 692"^(1969-12-31|1970-01-01)" 693" " 694"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 695" " 696"([-+][0-2][0-9]:?[0-5][0-9])\n"; 697const char*timestamp = NULL, *cp, *colon; 698static regex_t *stamp; 699 regmatch_t m[10]; 700int zoneoffset; 701int hourminute; 702int status; 703 704for(cp = nameline; *cp !='\n'; cp++) { 705if(*cp =='\t') 706 timestamp = cp +1; 707} 708if(!timestamp) 709return0; 710if(!stamp) { 711 stamp =xmalloc(sizeof(*stamp)); 712if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 713warning(_("Cannot prepare timestamp regexp%s"), 714 stamp_regexp); 715return0; 716} 717} 718 719 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 720if(status) { 721if(status != REG_NOMATCH) 722warning(_("regexec returned%dfor input:%s"), 723 status, timestamp); 724return0; 725} 726 727 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 728if(*colon ==':') 729 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 730else 731 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 732if(timestamp[m[3].rm_so] =='-') 733 zoneoffset = -zoneoffset; 734 735/* 736 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 737 * (west of GMT) or 1970-01-01 (east of GMT) 738 */ 739if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 740(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 741return0; 742 743 hourminute = (strtol(timestamp +11, NULL,10) *60+ 744strtol(timestamp +14, NULL,10) - 745 zoneoffset); 746 747return((zoneoffset <0&& hourminute ==1440) || 748(0<= zoneoffset && !hourminute)); 749} 750 751/* 752 * Get the name etc info from the ---/+++ lines of a traditional patch header 753 * 754 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 755 * files, we can happily check the index for a match, but for creating a 756 * new file we should try to match whatever "patch" does. I have no idea. 757 */ 758static voidparse_traditional_patch(struct apply_state *state, 759const char*first, 760const char*second, 761struct patch *patch) 762{ 763char*name; 764 765 first +=4;/* skip "--- " */ 766 second +=4;/* skip "+++ " */ 767if(!state->p_value_known) { 768int p, q; 769 p =guess_p_value(state, first); 770 q =guess_p_value(state, second); 771if(p <0) p = q; 772if(0<= p && p == q) { 773 state->p_value = p; 774 state->p_value_known =1; 775} 776} 777if(is_dev_null(first)) { 778 patch->is_new =1; 779 patch->is_delete =0; 780 name =find_name_traditional(state, second, NULL, state->p_value); 781 patch->new_name = name; 782}else if(is_dev_null(second)) { 783 patch->is_new =0; 784 patch->is_delete =1; 785 name =find_name_traditional(state, first, NULL, state->p_value); 786 patch->old_name = name; 787}else{ 788char*first_name; 789 first_name =find_name_traditional(state, first, NULL, state->p_value); 790 name =find_name_traditional(state, second, first_name, state->p_value); 791free(first_name); 792if(has_epoch_timestamp(first)) { 793 patch->is_new =1; 794 patch->is_delete =0; 795 patch->new_name = name; 796}else if(has_epoch_timestamp(second)) { 797 patch->is_new =0; 798 patch->is_delete =1; 799 patch->old_name = name; 800}else{ 801 patch->old_name = name; 802 patch->new_name =xstrdup_or_null(name); 803} 804} 805if(!name) 806die(_("unable to find filename in patch at line%d"), state->linenr); 807} 808 809static intgitdiff_hdrend(struct apply_state *state, 810const char*line, 811struct patch *patch) 812{ 813return-1; 814} 815 816/* 817 * We're anal about diff header consistency, to make 818 * sure that we don't end up having strange ambiguous 819 * patches floating around. 820 * 821 * As a result, gitdiff_{old|new}name() will check 822 * their names against any previous information, just 823 * to make sure.. 824 */ 825#define DIFF_OLD_NAME 0 826#define DIFF_NEW_NAME 1 827 828static voidgitdiff_verify_name(struct apply_state *state, 829const char*line, 830int isnull, 831char**name, 832int side) 833{ 834if(!*name && !isnull) { 835*name =find_name(state, line, NULL, state->p_value, TERM_TAB); 836return; 837} 838 839if(*name) { 840int len =strlen(*name); 841char*another; 842if(isnull) 843die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 844*name, state->linenr); 845 another =find_name(state, line, NULL, state->p_value, TERM_TAB); 846if(!another ||memcmp(another, *name, len +1)) 847die((side == DIFF_NEW_NAME) ? 848_("git apply: bad git-diff - inconsistent new filename on line%d") : 849_("git apply: bad git-diff - inconsistent old filename on line%d"), state->linenr); 850free(another); 851}else{ 852/* expect "/dev/null" */ 853if(memcmp("/dev/null", line,9) || line[9] !='\n') 854die(_("git apply: bad git-diff - expected /dev/null on line%d"), state->linenr); 855} 856} 857 858static intgitdiff_oldname(struct apply_state *state, 859const char*line, 860struct patch *patch) 861{ 862gitdiff_verify_name(state, line, 863 patch->is_new, &patch->old_name, 864 DIFF_OLD_NAME); 865return0; 866} 867 868static intgitdiff_newname(struct apply_state *state, 869const char*line, 870struct patch *patch) 871{ 872gitdiff_verify_name(state, line, 873 patch->is_delete, &patch->new_name, 874 DIFF_NEW_NAME); 875return0; 876} 877 878static intgitdiff_oldmode(struct apply_state *state, 879const char*line, 880struct patch *patch) 881{ 882 patch->old_mode =strtoul(line, NULL,8); 883return0; 884} 885 886static intgitdiff_newmode(struct apply_state *state, 887const char*line, 888struct patch *patch) 889{ 890 patch->new_mode =strtoul(line, NULL,8); 891return0; 892} 893 894static intgitdiff_delete(struct apply_state *state, 895const char*line, 896struct patch *patch) 897{ 898 patch->is_delete =1; 899free(patch->old_name); 900 patch->old_name =xstrdup_or_null(patch->def_name); 901returngitdiff_oldmode(state, line, patch); 902} 903 904static intgitdiff_newfile(struct apply_state *state, 905const char*line, 906struct patch *patch) 907{ 908 patch->is_new =1; 909free(patch->new_name); 910 patch->new_name =xstrdup_or_null(patch->def_name); 911returngitdiff_newmode(state, line, patch); 912} 913 914static intgitdiff_copysrc(struct apply_state *state, 915const char*line, 916struct patch *patch) 917{ 918 patch->is_copy =1; 919free(patch->old_name); 920 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0); 921return0; 922} 923 924static intgitdiff_copydst(struct apply_state *state, 925const char*line, 926struct patch *patch) 927{ 928 patch->is_copy =1; 929free(patch->new_name); 930 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0); 931return0; 932} 933 934static intgitdiff_renamesrc(struct apply_state *state, 935const char*line, 936struct patch *patch) 937{ 938 patch->is_rename =1; 939free(patch->old_name); 940 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0); 941return0; 942} 943 944static intgitdiff_renamedst(struct apply_state *state, 945const char*line, 946struct patch *patch) 947{ 948 patch->is_rename =1; 949free(patch->new_name); 950 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0); 951return0; 952} 953 954static intgitdiff_similarity(struct apply_state *state, 955const char*line, 956struct patch *patch) 957{ 958unsigned long val =strtoul(line, NULL,10); 959if(val <=100) 960 patch->score = val; 961return0; 962} 963 964static intgitdiff_dissimilarity(struct apply_state *state, 965const char*line, 966struct patch *patch) 967{ 968unsigned long val =strtoul(line, NULL,10); 969if(val <=100) 970 patch->score = val; 971return0; 972} 973 974static intgitdiff_index(struct apply_state *state, 975const char*line, 976struct patch *patch) 977{ 978/* 979 * index line is N hexadecimal, "..", N hexadecimal, 980 * and optional space with octal mode. 981 */ 982const char*ptr, *eol; 983int len; 984 985 ptr =strchr(line,'.'); 986if(!ptr || ptr[1] !='.'||40< ptr - line) 987return0; 988 len = ptr - line; 989memcpy(patch->old_sha1_prefix, line, len); 990 patch->old_sha1_prefix[len] =0; 991 992 line = ptr +2; 993 ptr =strchr(line,' '); 994 eol =strchrnul(line,'\n'); 995 996if(!ptr || eol < ptr) 997 ptr = eol; 998 len = ptr - line; 9991000if(40< len)1001return0;1002memcpy(patch->new_sha1_prefix, line, len);1003 patch->new_sha1_prefix[len] =0;1004if(*ptr ==' ')1005 patch->old_mode =strtoul(ptr+1, NULL,8);1006return0;1007}10081009/*1010 * This is normal for a diff that doesn't change anything: we'll fall through1011 * into the next diff. Tell the parser to break out.1012 */1013static intgitdiff_unrecognized(struct apply_state *state,1014const char*line,1015struct patch *patch)1016{1017return-1;1018}10191020/*1021 * Skip p_value leading components from "line"; as we do not accept1022 * absolute paths, return NULL in that case.1023 */1024static const char*skip_tree_prefix(struct apply_state *state,1025const char*line,1026int llen)1027{1028int nslash;1029int i;10301031if(!state->p_value)1032return(llen && line[0] =='/') ? NULL : line;10331034 nslash = state->p_value;1035for(i =0; i < llen; i++) {1036int ch = line[i];1037if(ch =='/'&& --nslash <=0)1038return(i ==0) ? NULL : &line[i +1];1039}1040return NULL;1041}10421043/*1044 * This is to extract the same name that appears on "diff --git"1045 * line. We do not find and return anything if it is a rename1046 * patch, and it is OK because we will find the name elsewhere.1047 * We need to reliably find name only when it is mode-change only,1048 * creation or deletion of an empty file. In any of these cases,1049 * both sides are the same name under a/ and b/ respectively.1050 */1051static char*git_header_name(struct apply_state *state,1052const char*line,1053int llen)1054{1055const char*name;1056const char*second = NULL;1057size_t len, line_len;10581059 line +=strlen("diff --git ");1060 llen -=strlen("diff --git ");10611062if(*line =='"') {1063const char*cp;1064struct strbuf first = STRBUF_INIT;1065struct strbuf sp = STRBUF_INIT;10661067if(unquote_c_style(&first, line, &second))1068goto free_and_fail1;10691070/* strip the a/b prefix including trailing slash */1071 cp =skip_tree_prefix(state, first.buf, first.len);1072if(!cp)1073goto free_and_fail1;1074strbuf_remove(&first,0, cp - first.buf);10751076/*1077 * second points at one past closing dq of name.1078 * find the second name.1079 */1080while((second < line + llen) &&isspace(*second))1081 second++;10821083if(line + llen <= second)1084goto free_and_fail1;1085if(*second =='"') {1086if(unquote_c_style(&sp, second, NULL))1087goto free_and_fail1;1088 cp =skip_tree_prefix(state, sp.buf, sp.len);1089if(!cp)1090goto free_and_fail1;1091/* They must match, otherwise ignore */1092if(strcmp(cp, first.buf))1093goto free_and_fail1;1094strbuf_release(&sp);1095returnstrbuf_detach(&first, NULL);1096}10971098/* unquoted second */1099 cp =skip_tree_prefix(state, second, line + llen - second);1100if(!cp)1101goto free_and_fail1;1102if(line + llen - cp != first.len ||1103memcmp(first.buf, cp, first.len))1104goto free_and_fail1;1105returnstrbuf_detach(&first, NULL);11061107 free_and_fail1:1108strbuf_release(&first);1109strbuf_release(&sp);1110return NULL;1111}11121113/* unquoted first name */1114 name =skip_tree_prefix(state, line, llen);1115if(!name)1116return NULL;11171118/*1119 * since the first name is unquoted, a dq if exists must be1120 * the beginning of the second name.1121 */1122for(second = name; second < line + llen; second++) {1123if(*second =='"') {1124struct strbuf sp = STRBUF_INIT;1125const char*np;11261127if(unquote_c_style(&sp, second, NULL))1128goto free_and_fail2;11291130 np =skip_tree_prefix(state, sp.buf, sp.len);1131if(!np)1132goto free_and_fail2;11331134 len = sp.buf + sp.len - np;1135if(len < second - name &&1136!strncmp(np, name, len) &&1137isspace(name[len])) {1138/* Good */1139strbuf_remove(&sp,0, np - sp.buf);1140returnstrbuf_detach(&sp, NULL);1141}11421143 free_and_fail2:1144strbuf_release(&sp);1145return NULL;1146}1147}11481149/*1150 * Accept a name only if it shows up twice, exactly the same1151 * form.1152 */1153 second =strchr(name,'\n');1154if(!second)1155return NULL;1156 line_len = second - name;1157for(len =0; ; len++) {1158switch(name[len]) {1159default:1160continue;1161case'\n':1162return NULL;1163case'\t':case' ':1164/*1165 * Is this the separator between the preimage1166 * and the postimage pathname? Again, we are1167 * only interested in the case where there is1168 * no rename, as this is only to set def_name1169 * and a rename patch has the names elsewhere1170 * in an unambiguous form.1171 */1172if(!name[len +1])1173return NULL;/* no postimage name */1174 second =skip_tree_prefix(state, name + len +1,1175 line_len - (len +1));1176if(!second)1177return NULL;1178/*1179 * Does len bytes starting at "name" and "second"1180 * (that are separated by one HT or SP we just1181 * found) exactly match?1182 */1183if(second[len] =='\n'&& !strncmp(name, second, len))1184returnxmemdupz(name, len);1185}1186}1187}11881189/* Verify that we recognize the lines following a git header */1190static intparse_git_header(struct apply_state *state,1191const char*line,1192int len,1193unsigned int size,1194struct patch *patch)1195{1196unsigned long offset;11971198/* A git diff has explicit new/delete information, so we don't guess */1199 patch->is_new =0;1200 patch->is_delete =0;12011202/*1203 * Some things may not have the old name in the1204 * rest of the headers anywhere (pure mode changes,1205 * or removing or adding empty files), so we get1206 * the default name from the header.1207 */1208 patch->def_name =git_header_name(state, line, len);1209if(patch->def_name && state->root.len) {1210char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1211free(patch->def_name);1212 patch->def_name = s;1213}12141215 line += len;1216 size -= len;1217 state->linenr++;1218for(offset = len ; size >0; offset += len, size -= len, line += len, state->linenr++) {1219static const struct opentry {1220const char*str;1221int(*fn)(struct apply_state *,const char*,struct patch *);1222} optable[] = {1223{"@@ -", gitdiff_hdrend },1224{"--- ", gitdiff_oldname },1225{"+++ ", gitdiff_newname },1226{"old mode ", gitdiff_oldmode },1227{"new mode ", gitdiff_newmode },1228{"deleted file mode ", gitdiff_delete },1229{"new file mode ", gitdiff_newfile },1230{"copy from ", gitdiff_copysrc },1231{"copy to ", gitdiff_copydst },1232{"rename old ", gitdiff_renamesrc },1233{"rename new ", gitdiff_renamedst },1234{"rename from ", gitdiff_renamesrc },1235{"rename to ", gitdiff_renamedst },1236{"similarity index ", gitdiff_similarity },1237{"dissimilarity index ", gitdiff_dissimilarity },1238{"index ", gitdiff_index },1239{"", gitdiff_unrecognized },1240};1241int i;12421243 len =linelen(line, size);1244if(!len || line[len-1] !='\n')1245break;1246for(i =0; i <ARRAY_SIZE(optable); i++) {1247const struct opentry *p = optable + i;1248int oplen =strlen(p->str);1249if(len < oplen ||memcmp(p->str, line, oplen))1250continue;1251if(p->fn(state, line + oplen, patch) <0)1252return offset;1253break;1254}1255}12561257return offset;1258}12591260static intparse_num(const char*line,unsigned long*p)1261{1262char*ptr;12631264if(!isdigit(*line))1265return0;1266*p =strtoul(line, &ptr,10);1267return ptr - line;1268}12691270static intparse_range(const char*line,int len,int offset,const char*expect,1271unsigned long*p1,unsigned long*p2)1272{1273int digits, ex;12741275if(offset <0|| offset >= len)1276return-1;1277 line += offset;1278 len -= offset;12791280 digits =parse_num(line, p1);1281if(!digits)1282return-1;12831284 offset += digits;1285 line += digits;1286 len -= digits;12871288*p2 =1;1289if(*line ==',') {1290 digits =parse_num(line+1, p2);1291if(!digits)1292return-1;12931294 offset += digits+1;1295 line += digits+1;1296 len -= digits+1;1297}12981299 ex =strlen(expect);1300if(ex > len)1301return-1;1302if(memcmp(line, expect, ex))1303return-1;13041305return offset + ex;1306}13071308static voidrecount_diff(const char*line,int size,struct fragment *fragment)1309{1310int oldlines =0, newlines =0, ret =0;13111312if(size <1) {1313warning("recount: ignore empty hunk");1314return;1315}13161317for(;;) {1318int len =linelen(line, size);1319 size -= len;1320 line += len;13211322if(size <1)1323break;13241325switch(*line) {1326case' ':case'\n':1327 newlines++;1328/* fall through */1329case'-':1330 oldlines++;1331continue;1332case'+':1333 newlines++;1334continue;1335case'\\':1336continue;1337case'@':1338 ret = size <3|| !starts_with(line,"@@ ");1339break;1340case'd':1341 ret = size <5|| !starts_with(line,"diff ");1342break;1343default:1344 ret = -1;1345break;1346}1347if(ret) {1348warning(_("recount: unexpected line: %.*s"),1349(int)linelen(line, size), line);1350return;1351}1352break;1353}1354 fragment->oldlines = oldlines;1355 fragment->newlines = newlines;1356}13571358/*1359 * Parse a unified diff fragment header of the1360 * form "@@ -a,b +c,d @@"1361 */1362static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1363{1364int offset;13651366if(!len || line[len-1] !='\n')1367return-1;13681369/* Figure out the number of lines in a fragment */1370 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1371 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);13721373return offset;1374}13751376/*1377 * Find file diff header1378 *1379 * Returns:1380 * -1 if no header was found1381 * -128 in case of error1382 * the size of the header in bytes (called "offset") otherwise1383 */1384static intfind_header(struct apply_state *state,1385const char*line,1386unsigned long size,1387int*hdrsize,1388struct patch *patch)1389{1390unsigned long offset, len;13911392 patch->is_toplevel_relative =0;1393 patch->is_rename = patch->is_copy =0;1394 patch->is_new = patch->is_delete = -1;1395 patch->old_mode = patch->new_mode =0;1396 patch->old_name = patch->new_name = NULL;1397for(offset =0; size >0; offset += len, size -= len, line += len, state->linenr++) {1398unsigned long nextlen;13991400 len =linelen(line, size);1401if(!len)1402break;14031404/* Testing this early allows us to take a few shortcuts.. */1405if(len <6)1406continue;14071408/*1409 * Make sure we don't find any unconnected patch fragments.1410 * That's a sign that we didn't find a header, and that a1411 * patch has become corrupted/broken up.1412 */1413if(!memcmp("@@ -", line,4)) {1414struct fragment dummy;1415if(parse_fragment_header(line, len, &dummy) <0)1416continue;1417error(_("patch fragment without header at line%d: %.*s"),1418 state->linenr, (int)len-1, line);1419return-128;1420}14211422if(size < len +6)1423break;14241425/*1426 * Git patch? It might not have a real patch, just a rename1427 * or mode change, so we handle that specially1428 */1429if(!memcmp("diff --git ", line,11)) {1430int git_hdr_len =parse_git_header(state, line, len, size, patch);1431if(git_hdr_len <= len)1432continue;1433if(!patch->old_name && !patch->new_name) {1434if(!patch->def_name) {1435error(Q_("git diff header lacks filename information when removing "1436"%dleading pathname component (line%d)",1437"git diff header lacks filename information when removing "1438"%dleading pathname components (line%d)",1439 state->p_value),1440 state->p_value, state->linenr);1441return-128;1442}1443 patch->old_name =xstrdup(patch->def_name);1444 patch->new_name =xstrdup(patch->def_name);1445}1446if(!patch->is_delete && !patch->new_name) {1447error("git diff header lacks filename information "1448"(line%d)", state->linenr);1449return-128;1450}1451 patch->is_toplevel_relative =1;1452*hdrsize = git_hdr_len;1453return offset;1454}14551456/* --- followed by +++ ? */1457if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1458continue;14591460/*1461 * We only accept unified patches, so we want it to1462 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1463 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1464 */1465 nextlen =linelen(line + len, size - len);1466if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1467continue;14681469/* Ok, we'll consider it a patch */1470parse_traditional_patch(state, line, line+len, patch);1471*hdrsize = len + nextlen;1472 state->linenr +=2;1473return offset;1474}1475return-1;1476}14771478static voidrecord_ws_error(struct apply_state *state,1479unsigned result,1480const char*line,1481int len,1482int linenr)1483{1484char*err;14851486if(!result)1487return;14881489 state->whitespace_error++;1490if(state->squelch_whitespace_errors &&1491 state->squelch_whitespace_errors < state->whitespace_error)1492return;14931494 err =whitespace_error_string(result);1495fprintf(stderr,"%s:%d:%s.\n%.*s\n",1496 state->patch_input_file, linenr, err, len, line);1497free(err);1498}14991500static voidcheck_whitespace(struct apply_state *state,1501const char*line,1502int len,1503unsigned ws_rule)1504{1505unsigned result =ws_check(line +1, len -1, ws_rule);15061507record_ws_error(state, result, line +1, len -2, state->linenr);1508}15091510/*1511 * Parse a unified diff. Note that this really needs to parse each1512 * fragment separately, since the only way to know the difference1513 * between a "---" that is part of a patch, and a "---" that starts1514 * the next patch is to look at the line counts..1515 */1516static intparse_fragment(struct apply_state *state,1517const char*line,1518unsigned long size,1519struct patch *patch,1520struct fragment *fragment)1521{1522int added, deleted;1523int len =linelen(line, size), offset;1524unsigned long oldlines, newlines;1525unsigned long leading, trailing;15261527 offset =parse_fragment_header(line, len, fragment);1528if(offset <0)1529return-1;1530if(offset >0&& patch->recount)1531recount_diff(line + offset, size - offset, fragment);1532 oldlines = fragment->oldlines;1533 newlines = fragment->newlines;1534 leading =0;1535 trailing =0;15361537/* Parse the thing.. */1538 line += len;1539 size -= len;1540 state->linenr++;1541 added = deleted =0;1542for(offset = len;15430< size;1544 offset += len, size -= len, line += len, state->linenr++) {1545if(!oldlines && !newlines)1546break;1547 len =linelen(line, size);1548if(!len || line[len-1] !='\n')1549return-1;1550switch(*line) {1551default:1552return-1;1553case'\n':/* newer GNU diff, an empty context line */1554case' ':1555 oldlines--;1556 newlines--;1557if(!deleted && !added)1558 leading++;1559 trailing++;1560if(!state->apply_in_reverse &&1561 state->ws_error_action == correct_ws_error)1562check_whitespace(state, line, len, patch->ws_rule);1563break;1564case'-':1565if(state->apply_in_reverse &&1566 state->ws_error_action != nowarn_ws_error)1567check_whitespace(state, line, len, patch->ws_rule);1568 deleted++;1569 oldlines--;1570 trailing =0;1571break;1572case'+':1573if(!state->apply_in_reverse &&1574 state->ws_error_action != nowarn_ws_error)1575check_whitespace(state, line, len, patch->ws_rule);1576 added++;1577 newlines--;1578 trailing =0;1579break;15801581/*1582 * We allow "\ No newline at end of file". Depending1583 * on locale settings when the patch was produced we1584 * don't know what this line looks like. The only1585 * thing we do know is that it begins with "\ ".1586 * Checking for 12 is just for sanity check -- any1587 * l10n of "\ No newline..." is at least that long.1588 */1589case'\\':1590if(len <12||memcmp(line,"\\",2))1591return-1;1592break;1593}1594}1595if(oldlines || newlines)1596return-1;1597if(!deleted && !added)1598return-1;15991600 fragment->leading = leading;1601 fragment->trailing = trailing;16021603/*1604 * If a fragment ends with an incomplete line, we failed to include1605 * it in the above loop because we hit oldlines == newlines == 01606 * before seeing it.1607 */1608if(12< size && !memcmp(line,"\\",2))1609 offset +=linelen(line, size);16101611 patch->lines_added += added;1612 patch->lines_deleted += deleted;16131614if(0< patch->is_new && oldlines)1615returnerror(_("new file depends on old contents"));1616if(0< patch->is_delete && newlines)1617returnerror(_("deleted file still has contents"));1618return offset;1619}16201621/*1622 * We have seen "diff --git a/... b/..." header (or a traditional patch1623 * header). Read hunks that belong to this patch into fragments and hang1624 * them to the given patch structure.1625 *1626 * The (fragment->patch, fragment->size) pair points into the memory given1627 * by the caller, not a copy, when we return.1628 *1629 * Returns:1630 * -1 in case of error,1631 * the number of bytes in the patch otherwise.1632 */1633static intparse_single_patch(struct apply_state *state,1634const char*line,1635unsigned long size,1636struct patch *patch)1637{1638unsigned long offset =0;1639unsigned long oldlines =0, newlines =0, context =0;1640struct fragment **fragp = &patch->fragments;16411642while(size >4&& !memcmp(line,"@@ -",4)) {1643struct fragment *fragment;1644int len;16451646 fragment =xcalloc(1,sizeof(*fragment));1647 fragment->linenr = state->linenr;1648 len =parse_fragment(state, line, size, patch, fragment);1649if(len <=0) {1650free(fragment);1651returnerror(_("corrupt patch at line%d"), state->linenr);1652}1653 fragment->patch = line;1654 fragment->size = len;1655 oldlines += fragment->oldlines;1656 newlines += fragment->newlines;1657 context += fragment->leading + fragment->trailing;16581659*fragp = fragment;1660 fragp = &fragment->next;16611662 offset += len;1663 line += len;1664 size -= len;1665}16661667/*1668 * If something was removed (i.e. we have old-lines) it cannot1669 * be creation, and if something was added it cannot be1670 * deletion. However, the reverse is not true; --unified=01671 * patches that only add are not necessarily creation even1672 * though they do not have any old lines, and ones that only1673 * delete are not necessarily deletion.1674 *1675 * Unfortunately, a real creation/deletion patch do _not_ have1676 * any context line by definition, so we cannot safely tell it1677 * apart with --unified=0 insanity. At least if the patch has1678 * more than one hunk it is not creation or deletion.1679 */1680if(patch->is_new <0&&1681(oldlines || (patch->fragments && patch->fragments->next)))1682 patch->is_new =0;1683if(patch->is_delete <0&&1684(newlines || (patch->fragments && patch->fragments->next)))1685 patch->is_delete =0;16861687if(0< patch->is_new && oldlines)1688returnerror(_("new file%sdepends on old contents"), patch->new_name);1689if(0< patch->is_delete && newlines)1690returnerror(_("deleted file%sstill has contents"), patch->old_name);1691if(!patch->is_delete && !newlines && context)1692fprintf_ln(stderr,1693_("** warning: "1694"file%sbecomes empty but is not deleted"),1695 patch->new_name);16961697return offset;1698}16991700staticinlineintmetadata_changes(struct patch *patch)1701{1702return patch->is_rename >0||1703 patch->is_copy >0||1704 patch->is_new >0||1705 patch->is_delete ||1706(patch->old_mode && patch->new_mode &&1707 patch->old_mode != patch->new_mode);1708}17091710static char*inflate_it(const void*data,unsigned long size,1711unsigned long inflated_size)1712{1713 git_zstream stream;1714void*out;1715int st;17161717memset(&stream,0,sizeof(stream));17181719 stream.next_in = (unsigned char*)data;1720 stream.avail_in = size;1721 stream.next_out = out =xmalloc(inflated_size);1722 stream.avail_out = inflated_size;1723git_inflate_init(&stream);1724 st =git_inflate(&stream, Z_FINISH);1725git_inflate_end(&stream);1726if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1727free(out);1728return NULL;1729}1730return out;1731}17321733/*1734 * Read a binary hunk and return a new fragment; fragment->patch1735 * points at an allocated memory that the caller must free, so1736 * it is marked as "->free_patch = 1".1737 */1738static struct fragment *parse_binary_hunk(struct apply_state *state,1739char**buf_p,1740unsigned long*sz_p,1741int*status_p,1742int*used_p)1743{1744/*1745 * Expect a line that begins with binary patch method ("literal"1746 * or "delta"), followed by the length of data before deflating.1747 * a sequence of 'length-byte' followed by base-85 encoded data1748 * should follow, terminated by a newline.1749 *1750 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1751 * and we would limit the patch line to 66 characters,1752 * so one line can fit up to 13 groups that would decode1753 * to 52 bytes max. The length byte 'A'-'Z' corresponds1754 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1755 */1756int llen, used;1757unsigned long size = *sz_p;1758char*buffer = *buf_p;1759int patch_method;1760unsigned long origlen;1761char*data = NULL;1762int hunk_size =0;1763struct fragment *frag;17641765 llen =linelen(buffer, size);1766 used = llen;17671768*status_p =0;17691770if(starts_with(buffer,"delta ")) {1771 patch_method = BINARY_DELTA_DEFLATED;1772 origlen =strtoul(buffer +6, NULL,10);1773}1774else if(starts_with(buffer,"literal ")) {1775 patch_method = BINARY_LITERAL_DEFLATED;1776 origlen =strtoul(buffer +8, NULL,10);1777}1778else1779return NULL;17801781 state->linenr++;1782 buffer += llen;1783while(1) {1784int byte_length, max_byte_length, newsize;1785 llen =linelen(buffer, size);1786 used += llen;1787 state->linenr++;1788if(llen ==1) {1789/* consume the blank line */1790 buffer++;1791 size--;1792break;1793}1794/*1795 * Minimum line is "A00000\n" which is 7-byte long,1796 * and the line length must be multiple of 5 plus 2.1797 */1798if((llen <7) || (llen-2) %5)1799goto corrupt;1800 max_byte_length = (llen -2) /5*4;1801 byte_length = *buffer;1802if('A'<= byte_length && byte_length <='Z')1803 byte_length = byte_length -'A'+1;1804else if('a'<= byte_length && byte_length <='z')1805 byte_length = byte_length -'a'+27;1806else1807goto corrupt;1808/* if the input length was not multiple of 4, we would1809 * have filler at the end but the filler should never1810 * exceed 3 bytes1811 */1812if(max_byte_length < byte_length ||1813 byte_length <= max_byte_length -4)1814goto corrupt;1815 newsize = hunk_size + byte_length;1816 data =xrealloc(data, newsize);1817if(decode_85(data + hunk_size, buffer +1, byte_length))1818goto corrupt;1819 hunk_size = newsize;1820 buffer += llen;1821 size -= llen;1822}18231824 frag =xcalloc(1,sizeof(*frag));1825 frag->patch =inflate_it(data, hunk_size, origlen);1826 frag->free_patch =1;1827if(!frag->patch)1828goto corrupt;1829free(data);1830 frag->size = origlen;1831*buf_p = buffer;1832*sz_p = size;1833*used_p = used;1834 frag->binary_patch_method = patch_method;1835return frag;18361837 corrupt:1838free(data);1839*status_p = -1;1840error(_("corrupt binary patch at line%d: %.*s"),1841 state->linenr-1, llen-1, buffer);1842return NULL;1843}18441845/*1846 * Returns:1847 * -1 in case of error,1848 * the length of the parsed binary patch otherwise1849 */1850static intparse_binary(struct apply_state *state,1851char*buffer,1852unsigned long size,1853struct patch *patch)1854{1855/*1856 * We have read "GIT binary patch\n"; what follows is a line1857 * that says the patch method (currently, either "literal" or1858 * "delta") and the length of data before deflating; a1859 * sequence of 'length-byte' followed by base-85 encoded data1860 * follows.1861 *1862 * When a binary patch is reversible, there is another binary1863 * hunk in the same format, starting with patch method (either1864 * "literal" or "delta") with the length of data, and a sequence1865 * of length-byte + base-85 encoded data, terminated with another1866 * empty line. This data, when applied to the postimage, produces1867 * the preimage.1868 */1869struct fragment *forward;1870struct fragment *reverse;1871int status;1872int used, used_1;18731874 forward =parse_binary_hunk(state, &buffer, &size, &status, &used);1875if(!forward && !status)1876/* there has to be one hunk (forward hunk) */1877returnerror(_("unrecognized binary patch at line%d"), state->linenr-1);1878if(status)1879/* otherwise we already gave an error message */1880return status;18811882 reverse =parse_binary_hunk(state, &buffer, &size, &status, &used_1);1883if(reverse)1884 used += used_1;1885else if(status) {1886/*1887 * Not having reverse hunk is not an error, but having1888 * a corrupt reverse hunk is.1889 */1890free((void*) forward->patch);1891free(forward);1892return status;1893}1894 forward->next = reverse;1895 patch->fragments = forward;1896 patch->is_binary =1;1897return used;1898}18991900static voidprefix_one(struct apply_state *state,char**name)1901{1902char*old_name = *name;1903if(!old_name)1904return;1905*name =xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));1906free(old_name);1907}19081909static voidprefix_patch(struct apply_state *state,struct patch *p)1910{1911if(!state->prefix || p->is_toplevel_relative)1912return;1913prefix_one(state, &p->new_name);1914prefix_one(state, &p->old_name);1915}19161917/*1918 * include/exclude1919 */19201921static voidadd_name_limit(struct apply_state *state,1922const char*name,1923int exclude)1924{1925struct string_list_item *it;19261927 it =string_list_append(&state->limit_by_name, name);1928 it->util = exclude ? NULL : (void*)1;1929}19301931static intuse_patch(struct apply_state *state,struct patch *p)1932{1933const char*pathname = p->new_name ? p->new_name : p->old_name;1934int i;19351936/* Paths outside are not touched regardless of "--include" */1937if(0< state->prefix_length) {1938int pathlen =strlen(pathname);1939if(pathlen <= state->prefix_length ||1940memcmp(state->prefix, pathname, state->prefix_length))1941return0;1942}19431944/* See if it matches any of exclude/include rule */1945for(i =0; i < state->limit_by_name.nr; i++) {1946struct string_list_item *it = &state->limit_by_name.items[i];1947if(!wildmatch(it->string, pathname,0, NULL))1948return(it->util != NULL);1949}19501951/*1952 * If we had any include, a path that does not match any rule is1953 * not used. Otherwise, we saw bunch of exclude rules (or none)1954 * and such a path is used.1955 */1956return!state->has_include;1957}19581959/*1960 * Read the patch text in "buffer" that extends for "size" bytes; stop1961 * reading after seeing a single patch (i.e. changes to a single file).1962 * Create fragments (i.e. patch hunks) and hang them to the given patch.1963 *1964 * Returns:1965 * -1 if no header was found or parse_binary() failed,1966 * -128 on another error,1967 * the number of bytes consumed otherwise,1968 * so that the caller can call us again for the next patch.1969 */1970static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)1971{1972int hdrsize, patchsize;1973int offset =find_header(state, buffer, size, &hdrsize, patch);19741975if(offset <0)1976return offset;19771978prefix_patch(state, patch);19791980if(!use_patch(state, patch))1981 patch->ws_rule =0;1982else1983 patch->ws_rule =whitespace_rule(patch->new_name1984? patch->new_name1985: patch->old_name);19861987 patchsize =parse_single_patch(state,1988 buffer + offset + hdrsize,1989 size - offset - hdrsize,1990 patch);19911992if(patchsize <0)1993return-128;19941995if(!patchsize) {1996static const char git_binary[] ="GIT binary patch\n";1997int hd = hdrsize + offset;1998unsigned long llen =linelen(buffer + hd, size - hd);19992000if(llen ==sizeof(git_binary) -1&&2001!memcmp(git_binary, buffer + hd, llen)) {2002int used;2003 state->linenr++;2004 used =parse_binary(state, buffer + hd + llen,2005 size - hd - llen, patch);2006if(used <0)2007return-1;2008if(used)2009 patchsize = used + llen;2010else2011 patchsize =0;2012}2013else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2014static const char*binhdr[] = {2015"Binary files ",2016"Files ",2017 NULL,2018};2019int i;2020for(i =0; binhdr[i]; i++) {2021int len =strlen(binhdr[i]);2022if(len < size - hd &&2023!memcmp(binhdr[i], buffer + hd, len)) {2024 state->linenr++;2025 patch->is_binary =1;2026 patchsize = llen;2027break;2028}2029}2030}20312032/* Empty patch cannot be applied if it is a text patch2033 * without metadata change. A binary patch appears2034 * empty to us here.2035 */2036if((state->apply || state->check) &&2037(!patch->is_binary && !metadata_changes(patch))) {2038error(_("patch with only garbage at line%d"), state->linenr);2039return-128;2040}2041}20422043return offset + hdrsize + patchsize;2044}20452046#define swap(a,b) myswap((a),(b),sizeof(a))20472048#define myswap(a, b, size) do { \2049 unsigned char mytmp[size]; \2050 memcpy(mytmp, &a, size); \2051 memcpy(&a, &b, size); \2052 memcpy(&b, mytmp, size); \2053} while (0)20542055static voidreverse_patches(struct patch *p)2056{2057for(; p; p = p->next) {2058struct fragment *frag = p->fragments;20592060swap(p->new_name, p->old_name);2061swap(p->new_mode, p->old_mode);2062swap(p->is_new, p->is_delete);2063swap(p->lines_added, p->lines_deleted);2064swap(p->old_sha1_prefix, p->new_sha1_prefix);20652066for(; frag; frag = frag->next) {2067swap(frag->newpos, frag->oldpos);2068swap(frag->newlines, frag->oldlines);2069}2070}2071}20722073static const char pluses[] =2074"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2075static const char minuses[]=2076"----------------------------------------------------------------------";20772078static voidshow_stats(struct apply_state *state,struct patch *patch)2079{2080struct strbuf qname = STRBUF_INIT;2081char*cp = patch->new_name ? patch->new_name : patch->old_name;2082int max, add, del;20832084quote_c_style(cp, &qname, NULL,0);20852086/*2087 * "scale" the filename2088 */2089 max = state->max_len;2090if(max >50)2091 max =50;20922093if(qname.len > max) {2094 cp =strchr(qname.buf + qname.len +3- max,'/');2095if(!cp)2096 cp = qname.buf + qname.len +3- max;2097strbuf_splice(&qname,0, cp - qname.buf,"...",3);2098}20992100if(patch->is_binary) {2101printf(" %-*s | Bin\n", max, qname.buf);2102strbuf_release(&qname);2103return;2104}21052106printf(" %-*s |", max, qname.buf);2107strbuf_release(&qname);21082109/*2110 * scale the add/delete2111 */2112 max = max + state->max_change >70?70- max : state->max_change;2113 add = patch->lines_added;2114 del = patch->lines_deleted;21152116if(state->max_change >0) {2117int total = ((add + del) * max + state->max_change /2) / state->max_change;2118 add = (add * max + state->max_change /2) / state->max_change;2119 del = total - add;2120}2121printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2122 add, pluses, del, minuses);2123}21242125static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2126{2127switch(st->st_mode & S_IFMT) {2128case S_IFLNK:2129if(strbuf_readlink(buf, path, st->st_size) <0)2130returnerror(_("unable to read symlink%s"), path);2131return0;2132case S_IFREG:2133if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2134returnerror(_("unable to open or read%s"), path);2135convert_to_git(path, buf->buf, buf->len, buf,0);2136return0;2137default:2138return-1;2139}2140}21412142/*2143 * Update the preimage, and the common lines in postimage,2144 * from buffer buf of length len. If postlen is 0 the postimage2145 * is updated in place, otherwise it's updated on a new buffer2146 * of length postlen2147 */21482149static voidupdate_pre_post_images(struct image *preimage,2150struct image *postimage,2151char*buf,2152size_t len,size_t postlen)2153{2154int i, ctx, reduced;2155char*new, *old, *fixed;2156struct image fixed_preimage;21572158/*2159 * Update the preimage with whitespace fixes. Note that we2160 * are not losing preimage->buf -- apply_one_fragment() will2161 * free "oldlines".2162 */2163prepare_image(&fixed_preimage, buf, len,1);2164assert(postlen2165? fixed_preimage.nr == preimage->nr2166: fixed_preimage.nr <= preimage->nr);2167for(i =0; i < fixed_preimage.nr; i++)2168 fixed_preimage.line[i].flag = preimage->line[i].flag;2169free(preimage->line_allocated);2170*preimage = fixed_preimage;21712172/*2173 * Adjust the common context lines in postimage. This can be2174 * done in-place when we are shrinking it with whitespace2175 * fixing, but needs a new buffer when ignoring whitespace or2176 * expanding leading tabs to spaces.2177 *2178 * We trust the caller to tell us if the update can be done2179 * in place (postlen==0) or not.2180 */2181 old = postimage->buf;2182if(postlen)2183new= postimage->buf =xmalloc(postlen);2184else2185new= old;2186 fixed = preimage->buf;21872188for(i = reduced = ctx =0; i < postimage->nr; i++) {2189size_t l_len = postimage->line[i].len;2190if(!(postimage->line[i].flag & LINE_COMMON)) {2191/* an added line -- no counterparts in preimage */2192memmove(new, old, l_len);2193 old += l_len;2194new+= l_len;2195continue;2196}21972198/* a common context -- skip it in the original postimage */2199 old += l_len;22002201/* and find the corresponding one in the fixed preimage */2202while(ctx < preimage->nr &&2203!(preimage->line[ctx].flag & LINE_COMMON)) {2204 fixed += preimage->line[ctx].len;2205 ctx++;2206}22072208/*2209 * preimage is expected to run out, if the caller2210 * fixed addition of trailing blank lines.2211 */2212if(preimage->nr <= ctx) {2213 reduced++;2214continue;2215}22162217/* and copy it in, while fixing the line length */2218 l_len = preimage->line[ctx].len;2219memcpy(new, fixed, l_len);2220new+= l_len;2221 fixed += l_len;2222 postimage->line[i].len = l_len;2223 ctx++;2224}22252226if(postlen2227? postlen <new- postimage->buf2228: postimage->len <new- postimage->buf)2229die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2230(int)postlen, (int) postimage->len, (int)(new- postimage->buf));22312232/* Fix the length of the whole thing */2233 postimage->len =new- postimage->buf;2234 postimage->nr -= reduced;2235}22362237static intline_by_line_fuzzy_match(struct image *img,2238struct image *preimage,2239struct image *postimage,2240unsigned longtry,2241int try_lno,2242int preimage_limit)2243{2244int i;2245size_t imgoff =0;2246size_t preoff =0;2247size_t postlen = postimage->len;2248size_t extra_chars;2249char*buf;2250char*preimage_eof;2251char*preimage_end;2252struct strbuf fixed;2253char*fixed_buf;2254size_t fixed_len;22552256for(i =0; i < preimage_limit; i++) {2257size_t prelen = preimage->line[i].len;2258size_t imglen = img->line[try_lno+i].len;22592260if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2261 preimage->buf + preoff, prelen))2262return0;2263if(preimage->line[i].flag & LINE_COMMON)2264 postlen += imglen - prelen;2265 imgoff += imglen;2266 preoff += prelen;2267}22682269/*2270 * Ok, the preimage matches with whitespace fuzz.2271 *2272 * imgoff now holds the true length of the target that2273 * matches the preimage before the end of the file.2274 *2275 * Count the number of characters in the preimage that fall2276 * beyond the end of the file and make sure that all of them2277 * are whitespace characters. (This can only happen if2278 * we are removing blank lines at the end of the file.)2279 */2280 buf = preimage_eof = preimage->buf + preoff;2281for( ; i < preimage->nr; i++)2282 preoff += preimage->line[i].len;2283 preimage_end = preimage->buf + preoff;2284for( ; buf < preimage_end; buf++)2285if(!isspace(*buf))2286return0;22872288/*2289 * Update the preimage and the common postimage context2290 * lines to use the same whitespace as the target.2291 * If whitespace is missing in the target (i.e.2292 * if the preimage extends beyond the end of the file),2293 * use the whitespace from the preimage.2294 */2295 extra_chars = preimage_end - preimage_eof;2296strbuf_init(&fixed, imgoff + extra_chars);2297strbuf_add(&fixed, img->buf +try, imgoff);2298strbuf_add(&fixed, preimage_eof, extra_chars);2299 fixed_buf =strbuf_detach(&fixed, &fixed_len);2300update_pre_post_images(preimage, postimage,2301 fixed_buf, fixed_len, postlen);2302return1;2303}23042305static intmatch_fragment(struct apply_state *state,2306struct image *img,2307struct image *preimage,2308struct image *postimage,2309unsigned longtry,2310int try_lno,2311unsigned ws_rule,2312int match_beginning,int match_end)2313{2314int i;2315char*fixed_buf, *buf, *orig, *target;2316struct strbuf fixed;2317size_t fixed_len, postlen;2318int preimage_limit;23192320if(preimage->nr + try_lno <= img->nr) {2321/*2322 * The hunk falls within the boundaries of img.2323 */2324 preimage_limit = preimage->nr;2325if(match_end && (preimage->nr + try_lno != img->nr))2326return0;2327}else if(state->ws_error_action == correct_ws_error &&2328(ws_rule & WS_BLANK_AT_EOF)) {2329/*2330 * This hunk extends beyond the end of img, and we are2331 * removing blank lines at the end of the file. This2332 * many lines from the beginning of the preimage must2333 * match with img, and the remainder of the preimage2334 * must be blank.2335 */2336 preimage_limit = img->nr - try_lno;2337}else{2338/*2339 * The hunk extends beyond the end of the img and2340 * we are not removing blanks at the end, so we2341 * should reject the hunk at this position.2342 */2343return0;2344}23452346if(match_beginning && try_lno)2347return0;23482349/* Quick hash check */2350for(i =0; i < preimage_limit; i++)2351if((img->line[try_lno + i].flag & LINE_PATCHED) ||2352(preimage->line[i].hash != img->line[try_lno + i].hash))2353return0;23542355if(preimage_limit == preimage->nr) {2356/*2357 * Do we have an exact match? If we were told to match2358 * at the end, size must be exactly at try+fragsize,2359 * otherwise try+fragsize must be still within the preimage,2360 * and either case, the old piece should match the preimage2361 * exactly.2362 */2363if((match_end2364? (try+ preimage->len == img->len)2365: (try+ preimage->len <= img->len)) &&2366!memcmp(img->buf +try, preimage->buf, preimage->len))2367return1;2368}else{2369/*2370 * The preimage extends beyond the end of img, so2371 * there cannot be an exact match.2372 *2373 * There must be one non-blank context line that match2374 * a line before the end of img.2375 */2376char*buf_end;23772378 buf = preimage->buf;2379 buf_end = buf;2380for(i =0; i < preimage_limit; i++)2381 buf_end += preimage->line[i].len;23822383for( ; buf < buf_end; buf++)2384if(!isspace(*buf))2385break;2386if(buf == buf_end)2387return0;2388}23892390/*2391 * No exact match. If we are ignoring whitespace, run a line-by-line2392 * fuzzy matching. We collect all the line length information because2393 * we need it to adjust whitespace if we match.2394 */2395if(state->ws_ignore_action == ignore_ws_change)2396returnline_by_line_fuzzy_match(img, preimage, postimage,2397try, try_lno, preimage_limit);23982399if(state->ws_error_action != correct_ws_error)2400return0;24012402/*2403 * The hunk does not apply byte-by-byte, but the hash says2404 * it might with whitespace fuzz. We weren't asked to2405 * ignore whitespace, we were asked to correct whitespace2406 * errors, so let's try matching after whitespace correction.2407 *2408 * While checking the preimage against the target, whitespace2409 * errors in both fixed, we count how large the corresponding2410 * postimage needs to be. The postimage prepared by2411 * apply_one_fragment() has whitespace errors fixed on added2412 * lines already, but the common lines were propagated as-is,2413 * which may become longer when their whitespace errors are2414 * fixed.2415 */24162417/* First count added lines in postimage */2418 postlen =0;2419for(i =0; i < postimage->nr; i++) {2420if(!(postimage->line[i].flag & LINE_COMMON))2421 postlen += postimage->line[i].len;2422}24232424/*2425 * The preimage may extend beyond the end of the file,2426 * but in this loop we will only handle the part of the2427 * preimage that falls within the file.2428 */2429strbuf_init(&fixed, preimage->len +1);2430 orig = preimage->buf;2431 target = img->buf +try;2432for(i =0; i < preimage_limit; i++) {2433size_t oldlen = preimage->line[i].len;2434size_t tgtlen = img->line[try_lno + i].len;2435size_t fixstart = fixed.len;2436struct strbuf tgtfix;2437int match;24382439/* Try fixing the line in the preimage */2440ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24412442/* Try fixing the line in the target */2443strbuf_init(&tgtfix, tgtlen);2444ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);24452446/*2447 * If they match, either the preimage was based on2448 * a version before our tree fixed whitespace breakage,2449 * or we are lacking a whitespace-fix patch the tree2450 * the preimage was based on already had (i.e. target2451 * has whitespace breakage, the preimage doesn't).2452 * In either case, we are fixing the whitespace breakages2453 * so we might as well take the fix together with their2454 * real change.2455 */2456 match = (tgtfix.len == fixed.len - fixstart &&2457!memcmp(tgtfix.buf, fixed.buf + fixstart,2458 fixed.len - fixstart));24592460/* Add the length if this is common with the postimage */2461if(preimage->line[i].flag & LINE_COMMON)2462 postlen += tgtfix.len;24632464strbuf_release(&tgtfix);2465if(!match)2466goto unmatch_exit;24672468 orig += oldlen;2469 target += tgtlen;2470}247124722473/*2474 * Now handle the lines in the preimage that falls beyond the2475 * end of the file (if any). They will only match if they are2476 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2477 * false).2478 */2479for( ; i < preimage->nr; i++) {2480size_t fixstart = fixed.len;/* start of the fixed preimage */2481size_t oldlen = preimage->line[i].len;2482int j;24832484/* Try fixing the line in the preimage */2485ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24862487for(j = fixstart; j < fixed.len; j++)2488if(!isspace(fixed.buf[j]))2489goto unmatch_exit;24902491 orig += oldlen;2492}24932494/*2495 * Yes, the preimage is based on an older version that still2496 * has whitespace breakages unfixed, and fixing them makes the2497 * hunk match. Update the context lines in the postimage.2498 */2499 fixed_buf =strbuf_detach(&fixed, &fixed_len);2500if(postlen < postimage->len)2501 postlen =0;2502update_pre_post_images(preimage, postimage,2503 fixed_buf, fixed_len, postlen);2504return1;25052506 unmatch_exit:2507strbuf_release(&fixed);2508return0;2509}25102511static intfind_pos(struct apply_state *state,2512struct image *img,2513struct image *preimage,2514struct image *postimage,2515int line,2516unsigned ws_rule,2517int match_beginning,int match_end)2518{2519int i;2520unsigned long backwards, forwards,try;2521int backwards_lno, forwards_lno, try_lno;25222523/*2524 * If match_beginning or match_end is specified, there is no2525 * point starting from a wrong line that will never match and2526 * wander around and wait for a match at the specified end.2527 */2528if(match_beginning)2529 line =0;2530else if(match_end)2531 line = img->nr - preimage->nr;25322533/*2534 * Because the comparison is unsigned, the following test2535 * will also take care of a negative line number that can2536 * result when match_end and preimage is larger than the target.2537 */2538if((size_t) line > img->nr)2539 line = img->nr;25402541try=0;2542for(i =0; i < line; i++)2543try+= img->line[i].len;25442545/*2546 * There's probably some smart way to do this, but I'll leave2547 * that to the smart and beautiful people. I'm simple and stupid.2548 */2549 backwards =try;2550 backwards_lno = line;2551 forwards =try;2552 forwards_lno = line;2553 try_lno = line;25542555for(i =0; ; i++) {2556if(match_fragment(state, img, preimage, postimage,2557try, try_lno, ws_rule,2558 match_beginning, match_end))2559return try_lno;25602561 again:2562if(backwards_lno ==0&& forwards_lno == img->nr)2563break;25642565if(i &1) {2566if(backwards_lno ==0) {2567 i++;2568goto again;2569}2570 backwards_lno--;2571 backwards -= img->line[backwards_lno].len;2572try= backwards;2573 try_lno = backwards_lno;2574}else{2575if(forwards_lno == img->nr) {2576 i++;2577goto again;2578}2579 forwards += img->line[forwards_lno].len;2580 forwards_lno++;2581try= forwards;2582 try_lno = forwards_lno;2583}25842585}2586return-1;2587}25882589static voidremove_first_line(struct image *img)2590{2591 img->buf += img->line[0].len;2592 img->len -= img->line[0].len;2593 img->line++;2594 img->nr--;2595}25962597static voidremove_last_line(struct image *img)2598{2599 img->len -= img->line[--img->nr].len;2600}26012602/*2603 * The change from "preimage" and "postimage" has been found to2604 * apply at applied_pos (counts in line numbers) in "img".2605 * Update "img" to remove "preimage" and replace it with "postimage".2606 */2607static voidupdate_image(struct apply_state *state,2608struct image *img,2609int applied_pos,2610struct image *preimage,2611struct image *postimage)2612{2613/*2614 * remove the copy of preimage at offset in img2615 * and replace it with postimage2616 */2617int i, nr;2618size_t remove_count, insert_count, applied_at =0;2619char*result;2620int preimage_limit;26212622/*2623 * If we are removing blank lines at the end of img,2624 * the preimage may extend beyond the end.2625 * If that is the case, we must be careful only to2626 * remove the part of the preimage that falls within2627 * the boundaries of img. Initialize preimage_limit2628 * to the number of lines in the preimage that falls2629 * within the boundaries.2630 */2631 preimage_limit = preimage->nr;2632if(preimage_limit > img->nr - applied_pos)2633 preimage_limit = img->nr - applied_pos;26342635for(i =0; i < applied_pos; i++)2636 applied_at += img->line[i].len;26372638 remove_count =0;2639for(i =0; i < preimage_limit; i++)2640 remove_count += img->line[applied_pos + i].len;2641 insert_count = postimage->len;26422643/* Adjust the contents */2644 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2645memcpy(result, img->buf, applied_at);2646memcpy(result + applied_at, postimage->buf, postimage->len);2647memcpy(result + applied_at + postimage->len,2648 img->buf + (applied_at + remove_count),2649 img->len - (applied_at + remove_count));2650free(img->buf);2651 img->buf = result;2652 img->len += insert_count - remove_count;2653 result[img->len] ='\0';26542655/* Adjust the line table */2656 nr = img->nr + postimage->nr - preimage_limit;2657if(preimage_limit < postimage->nr) {2658/*2659 * NOTE: this knows that we never call remove_first_line()2660 * on anything other than pre/post image.2661 */2662REALLOC_ARRAY(img->line, nr);2663 img->line_allocated = img->line;2664}2665if(preimage_limit != postimage->nr)2666memmove(img->line + applied_pos + postimage->nr,2667 img->line + applied_pos + preimage_limit,2668(img->nr - (applied_pos + preimage_limit)) *2669sizeof(*img->line));2670memcpy(img->line + applied_pos,2671 postimage->line,2672 postimage->nr *sizeof(*img->line));2673if(!state->allow_overlap)2674for(i =0; i < postimage->nr; i++)2675 img->line[applied_pos + i].flag |= LINE_PATCHED;2676 img->nr = nr;2677}26782679/*2680 * Use the patch-hunk text in "frag" to prepare two images (preimage and2681 * postimage) for the hunk. Find lines that match "preimage" in "img" and2682 * replace the part of "img" with "postimage" text.2683 */2684static intapply_one_fragment(struct apply_state *state,2685struct image *img,struct fragment *frag,2686int inaccurate_eof,unsigned ws_rule,2687int nth_fragment)2688{2689int match_beginning, match_end;2690const char*patch = frag->patch;2691int size = frag->size;2692char*old, *oldlines;2693struct strbuf newlines;2694int new_blank_lines_at_end =0;2695int found_new_blank_lines_at_end =0;2696int hunk_linenr = frag->linenr;2697unsigned long leading, trailing;2698int pos, applied_pos;2699struct image preimage;2700struct image postimage;27012702memset(&preimage,0,sizeof(preimage));2703memset(&postimage,0,sizeof(postimage));2704 oldlines =xmalloc(size);2705strbuf_init(&newlines, size);27062707 old = oldlines;2708while(size >0) {2709char first;2710int len =linelen(patch, size);2711int plen;2712int added_blank_line =0;2713int is_blank_context =0;2714size_t start;27152716if(!len)2717break;27182719/*2720 * "plen" is how much of the line we should use for2721 * the actual patch data. Normally we just remove the2722 * first character on the line, but if the line is2723 * followed by "\ No newline", then we also remove the2724 * last one (which is the newline, of course).2725 */2726 plen = len -1;2727if(len < size && patch[len] =='\\')2728 plen--;2729 first = *patch;2730if(state->apply_in_reverse) {2731if(first =='-')2732 first ='+';2733else if(first =='+')2734 first ='-';2735}27362737switch(first) {2738case'\n':2739/* Newer GNU diff, empty context line */2740if(plen <0)2741/* ... followed by '\No newline'; nothing */2742break;2743*old++ ='\n';2744strbuf_addch(&newlines,'\n');2745add_line_info(&preimage,"\n",1, LINE_COMMON);2746add_line_info(&postimage,"\n",1, LINE_COMMON);2747 is_blank_context =1;2748break;2749case' ':2750if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2751ws_blank_line(patch +1, plen, ws_rule))2752 is_blank_context =1;2753case'-':2754memcpy(old, patch +1, plen);2755add_line_info(&preimage, old, plen,2756(first ==' '? LINE_COMMON :0));2757 old += plen;2758if(first =='-')2759break;2760/* Fall-through for ' ' */2761case'+':2762/* --no-add does not add new lines */2763if(first =='+'&& state->no_add)2764break;27652766 start = newlines.len;2767if(first !='+'||2768!state->whitespace_error ||2769 state->ws_error_action != correct_ws_error) {2770strbuf_add(&newlines, patch +1, plen);2771}2772else{2773ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2774}2775add_line_info(&postimage, newlines.buf + start, newlines.len - start,2776(first =='+'?0: LINE_COMMON));2777if(first =='+'&&2778(ws_rule & WS_BLANK_AT_EOF) &&2779ws_blank_line(patch +1, plen, ws_rule))2780 added_blank_line =1;2781break;2782case'@':case'\\':2783/* Ignore it, we already handled it */2784break;2785default:2786if(state->apply_verbosely)2787error(_("invalid start of line: '%c'"), first);2788 applied_pos = -1;2789goto out;2790}2791if(added_blank_line) {2792if(!new_blank_lines_at_end)2793 found_new_blank_lines_at_end = hunk_linenr;2794 new_blank_lines_at_end++;2795}2796else if(is_blank_context)2797;2798else2799 new_blank_lines_at_end =0;2800 patch += len;2801 size -= len;2802 hunk_linenr++;2803}2804if(inaccurate_eof &&2805 old > oldlines && old[-1] =='\n'&&2806 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2807 old--;2808strbuf_setlen(&newlines, newlines.len -1);2809}28102811 leading = frag->leading;2812 trailing = frag->trailing;28132814/*2815 * A hunk to change lines at the beginning would begin with2816 * @@ -1,L +N,M @@2817 * but we need to be careful. -U0 that inserts before the second2818 * line also has this pattern.2819 *2820 * And a hunk to add to an empty file would begin with2821 * @@ -0,0 +N,M @@2822 *2823 * In other words, a hunk that is (frag->oldpos <= 1) with or2824 * without leading context must match at the beginning.2825 */2826 match_beginning = (!frag->oldpos ||2827(frag->oldpos ==1&& !state->unidiff_zero));28282829/*2830 * A hunk without trailing lines must match at the end.2831 * However, we simply cannot tell if a hunk must match end2832 * from the lack of trailing lines if the patch was generated2833 * with unidiff without any context.2834 */2835 match_end = !state->unidiff_zero && !trailing;28362837 pos = frag->newpos ? (frag->newpos -1) :0;2838 preimage.buf = oldlines;2839 preimage.len = old - oldlines;2840 postimage.buf = newlines.buf;2841 postimage.len = newlines.len;2842 preimage.line = preimage.line_allocated;2843 postimage.line = postimage.line_allocated;28442845for(;;) {28462847 applied_pos =find_pos(state, img, &preimage, &postimage, pos,2848 ws_rule, match_beginning, match_end);28492850if(applied_pos >=0)2851break;28522853/* Am I at my context limits? */2854if((leading <= state->p_context) && (trailing <= state->p_context))2855break;2856if(match_beginning || match_end) {2857 match_beginning = match_end =0;2858continue;2859}28602861/*2862 * Reduce the number of context lines; reduce both2863 * leading and trailing if they are equal otherwise2864 * just reduce the larger context.2865 */2866if(leading >= trailing) {2867remove_first_line(&preimage);2868remove_first_line(&postimage);2869 pos--;2870 leading--;2871}2872if(trailing > leading) {2873remove_last_line(&preimage);2874remove_last_line(&postimage);2875 trailing--;2876}2877}28782879if(applied_pos >=0) {2880if(new_blank_lines_at_end &&2881 preimage.nr + applied_pos >= img->nr &&2882(ws_rule & WS_BLANK_AT_EOF) &&2883 state->ws_error_action != nowarn_ws_error) {2884record_ws_error(state, WS_BLANK_AT_EOF,"+",1,2885 found_new_blank_lines_at_end);2886if(state->ws_error_action == correct_ws_error) {2887while(new_blank_lines_at_end--)2888remove_last_line(&postimage);2889}2890/*2891 * We would want to prevent write_out_results()2892 * from taking place in apply_patch() that follows2893 * the callchain led us here, which is:2894 * apply_patch->check_patch_list->check_patch->2895 * apply_data->apply_fragments->apply_one_fragment2896 */2897if(state->ws_error_action == die_on_ws_error)2898 state->apply =0;2899}29002901if(state->apply_verbosely && applied_pos != pos) {2902int offset = applied_pos - pos;2903if(state->apply_in_reverse)2904 offset =0- offset;2905fprintf_ln(stderr,2906Q_("Hunk #%dsucceeded at%d(offset%dline).",2907"Hunk #%dsucceeded at%d(offset%dlines).",2908 offset),2909 nth_fragment, applied_pos +1, offset);2910}29112912/*2913 * Warn if it was necessary to reduce the number2914 * of context lines.2915 */2916if((leading != frag->leading) ||2917(trailing != frag->trailing))2918fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2919" to apply fragment at%d"),2920 leading, trailing, applied_pos+1);2921update_image(state, img, applied_pos, &preimage, &postimage);2922}else{2923if(state->apply_verbosely)2924error(_("while searching for:\n%.*s"),2925(int)(old - oldlines), oldlines);2926}29272928out:2929free(oldlines);2930strbuf_release(&newlines);2931free(preimage.line_allocated);2932free(postimage.line_allocated);29332934return(applied_pos <0);2935}29362937static intapply_binary_fragment(struct apply_state *state,2938struct image *img,2939struct patch *patch)2940{2941struct fragment *fragment = patch->fragments;2942unsigned long len;2943void*dst;29442945if(!fragment)2946returnerror(_("missing binary patch data for '%s'"),2947 patch->new_name ?2948 patch->new_name :2949 patch->old_name);29502951/* Binary patch is irreversible without the optional second hunk */2952if(state->apply_in_reverse) {2953if(!fragment->next)2954returnerror("cannot reverse-apply a binary patch "2955"without the reverse hunk to '%s'",2956 patch->new_name2957? patch->new_name : patch->old_name);2958 fragment = fragment->next;2959}2960switch(fragment->binary_patch_method) {2961case BINARY_DELTA_DEFLATED:2962 dst =patch_delta(img->buf, img->len, fragment->patch,2963 fragment->size, &len);2964if(!dst)2965return-1;2966clear_image(img);2967 img->buf = dst;2968 img->len = len;2969return0;2970case BINARY_LITERAL_DEFLATED:2971clear_image(img);2972 img->len = fragment->size;2973 img->buf =xmemdupz(fragment->patch, img->len);2974return0;2975}2976return-1;2977}29782979/*2980 * Replace "img" with the result of applying the binary patch.2981 * The binary patch data itself in patch->fragment is still kept2982 * but the preimage prepared by the caller in "img" is freed here2983 * or in the helper function apply_binary_fragment() this calls.2984 */2985static intapply_binary(struct apply_state *state,2986struct image *img,2987struct patch *patch)2988{2989const char*name = patch->old_name ? patch->old_name : patch->new_name;2990unsigned char sha1[20];29912992/*2993 * For safety, we require patch index line to contain2994 * full 40-byte textual SHA1 for old and new, at least for now.2995 */2996if(strlen(patch->old_sha1_prefix) !=40||2997strlen(patch->new_sha1_prefix) !=40||2998get_sha1_hex(patch->old_sha1_prefix, sha1) ||2999get_sha1_hex(patch->new_sha1_prefix, sha1))3000returnerror("cannot apply binary patch to '%s' "3001"without full index line", name);30023003if(patch->old_name) {3004/*3005 * See if the old one matches what the patch3006 * applies to.3007 */3008hash_sha1_file(img->buf, img->len, blob_type, sha1);3009if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3010returnerror("the patch applies to '%s' (%s), "3011"which does not match the "3012"current contents.",3013 name,sha1_to_hex(sha1));3014}3015else{3016/* Otherwise, the old one must be empty. */3017if(img->len)3018returnerror("the patch applies to an empty "3019"'%s' but it is not empty", name);3020}30213022get_sha1_hex(patch->new_sha1_prefix, sha1);3023if(is_null_sha1(sha1)) {3024clear_image(img);3025return0;/* deletion patch */3026}30273028if(has_sha1_file(sha1)) {3029/* We already have the postimage */3030enum object_type type;3031unsigned long size;3032char*result;30333034 result =read_sha1_file(sha1, &type, &size);3035if(!result)3036returnerror("the necessary postimage%sfor "3037"'%s' cannot be read",3038 patch->new_sha1_prefix, name);3039clear_image(img);3040 img->buf = result;3041 img->len = size;3042}else{3043/*3044 * We have verified buf matches the preimage;3045 * apply the patch data to it, which is stored3046 * in the patch->fragments->{patch,size}.3047 */3048if(apply_binary_fragment(state, img, patch))3049returnerror(_("binary patch does not apply to '%s'"),3050 name);30513052/* verify that the result matches */3053hash_sha1_file(img->buf, img->len, blob_type, sha1);3054if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3055returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3056 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3057}30583059return0;3060}30613062static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3063{3064struct fragment *frag = patch->fragments;3065const char*name = patch->old_name ? patch->old_name : patch->new_name;3066unsigned ws_rule = patch->ws_rule;3067unsigned inaccurate_eof = patch->inaccurate_eof;3068int nth =0;30693070if(patch->is_binary)3071returnapply_binary(state, img, patch);30723073while(frag) {3074 nth++;3075if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3076error(_("patch failed:%s:%ld"), name, frag->oldpos);3077if(!state->apply_with_reject)3078return-1;3079 frag->rejected =1;3080}3081 frag = frag->next;3082}3083return0;3084}30853086static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3087{3088if(S_ISGITLINK(mode)) {3089strbuf_grow(buf,100);3090strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3091}else{3092enum object_type type;3093unsigned long sz;3094char*result;30953096 result =read_sha1_file(sha1, &type, &sz);3097if(!result)3098return-1;3099/* XXX read_sha1_file NUL-terminates */3100strbuf_attach(buf, result, sz, sz +1);3101}3102return0;3103}31043105static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3106{3107if(!ce)3108return0;3109returnread_blob_object(buf, ce->sha1, ce->ce_mode);3110}31113112static struct patch *in_fn_table(struct apply_state *state,const char*name)3113{3114struct string_list_item *item;31153116if(name == NULL)3117return NULL;31183119 item =string_list_lookup(&state->fn_table, name);3120if(item != NULL)3121return(struct patch *)item->util;31223123return NULL;3124}31253126/*3127 * item->util in the filename table records the status of the path.3128 * Usually it points at a patch (whose result records the contents3129 * of it after applying it), but it could be PATH_WAS_DELETED for a3130 * path that a previously applied patch has already removed, or3131 * PATH_TO_BE_DELETED for a path that a later patch would remove.3132 *3133 * The latter is needed to deal with a case where two paths A and B3134 * are swapped by first renaming A to B and then renaming B to A;3135 * moving A to B should not be prevented due to presence of B as we3136 * will remove it in a later patch.3137 */3138#define PATH_TO_BE_DELETED ((struct patch *) -2)3139#define PATH_WAS_DELETED ((struct patch *) -1)31403141static intto_be_deleted(struct patch *patch)3142{3143return patch == PATH_TO_BE_DELETED;3144}31453146static intwas_deleted(struct patch *patch)3147{3148return patch == PATH_WAS_DELETED;3149}31503151static voidadd_to_fn_table(struct apply_state *state,struct patch *patch)3152{3153struct string_list_item *item;31543155/*3156 * Always add new_name unless patch is a deletion3157 * This should cover the cases for normal diffs,3158 * file creations and copies3159 */3160if(patch->new_name != NULL) {3161 item =string_list_insert(&state->fn_table, patch->new_name);3162 item->util = patch;3163}31643165/*3166 * store a failure on rename/deletion cases because3167 * later chunks shouldn't patch old names3168 */3169if((patch->new_name == NULL) || (patch->is_rename)) {3170 item =string_list_insert(&state->fn_table, patch->old_name);3171 item->util = PATH_WAS_DELETED;3172}3173}31743175static voidprepare_fn_table(struct apply_state *state,struct patch *patch)3176{3177/*3178 * store information about incoming file deletion3179 */3180while(patch) {3181if((patch->new_name == NULL) || (patch->is_rename)) {3182struct string_list_item *item;3183 item =string_list_insert(&state->fn_table, patch->old_name);3184 item->util = PATH_TO_BE_DELETED;3185}3186 patch = patch->next;3187}3188}31893190static intcheckout_target(struct index_state *istate,3191struct cache_entry *ce,struct stat *st)3192{3193struct checkout costate;31943195memset(&costate,0,sizeof(costate));3196 costate.base_dir ="";3197 costate.refresh_cache =1;3198 costate.istate = istate;3199if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3200returnerror(_("cannot checkout%s"), ce->name);3201return0;3202}32033204static struct patch *previous_patch(struct apply_state *state,3205struct patch *patch,3206int*gone)3207{3208struct patch *previous;32093210*gone =0;3211if(patch->is_copy || patch->is_rename)3212return NULL;/* "git" patches do not depend on the order */32133214 previous =in_fn_table(state, patch->old_name);3215if(!previous)3216return NULL;32173218if(to_be_deleted(previous))3219return NULL;/* the deletion hasn't happened yet */32203221if(was_deleted(previous))3222*gone =1;32233224return previous;3225}32263227static intverify_index_match(const struct cache_entry *ce,struct stat *st)3228{3229if(S_ISGITLINK(ce->ce_mode)) {3230if(!S_ISDIR(st->st_mode))3231return-1;3232return0;3233}3234returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3235}32363237#define SUBMODULE_PATCH_WITHOUT_INDEX 132383239static intload_patch_target(struct apply_state *state,3240struct strbuf *buf,3241const struct cache_entry *ce,3242struct stat *st,3243const char*name,3244unsigned expected_mode)3245{3246if(state->cached || state->check_index) {3247if(read_file_or_gitlink(ce, buf))3248returnerror(_("failed to read%s"), name);3249}else if(name) {3250if(S_ISGITLINK(expected_mode)) {3251if(ce)3252returnread_file_or_gitlink(ce, buf);3253else3254return SUBMODULE_PATCH_WITHOUT_INDEX;3255}else if(has_symlink_leading_path(name,strlen(name))) {3256returnerror(_("reading from '%s' beyond a symbolic link"), name);3257}else{3258if(read_old_data(st, name, buf))3259returnerror(_("failed to read%s"), name);3260}3261}3262return0;3263}32643265/*3266 * We are about to apply "patch"; populate the "image" with the3267 * current version we have, from the working tree or from the index,3268 * depending on the situation e.g. --cached/--index. If we are3269 * applying a non-git patch that incrementally updates the tree,3270 * we read from the result of a previous diff.3271 */3272static intload_preimage(struct apply_state *state,3273struct image *image,3274struct patch *patch,struct stat *st,3275const struct cache_entry *ce)3276{3277struct strbuf buf = STRBUF_INIT;3278size_t len;3279char*img;3280struct patch *previous;3281int status;32823283 previous =previous_patch(state, patch, &status);3284if(status)3285returnerror(_("path%shas been renamed/deleted"),3286 patch->old_name);3287if(previous) {3288/* We have a patched copy in memory; use that. */3289strbuf_add(&buf, previous->result, previous->resultsize);3290}else{3291 status =load_patch_target(state, &buf, ce, st,3292 patch->old_name, patch->old_mode);3293if(status <0)3294return status;3295else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3296/*3297 * There is no way to apply subproject3298 * patch without looking at the index.3299 * NEEDSWORK: shouldn't this be flagged3300 * as an error???3301 */3302free_fragment_list(patch->fragments);3303 patch->fragments = NULL;3304}else if(status) {3305returnerror(_("failed to read%s"), patch->old_name);3306}3307}33083309 img =strbuf_detach(&buf, &len);3310prepare_image(image, img, len, !patch->is_binary);3311return0;3312}33133314static intthree_way_merge(struct image *image,3315char*path,3316const unsigned char*base,3317const unsigned char*ours,3318const unsigned char*theirs)3319{3320 mmfile_t base_file, our_file, their_file;3321 mmbuffer_t result = { NULL };3322int status;33233324read_mmblob(&base_file, base);3325read_mmblob(&our_file, ours);3326read_mmblob(&their_file, theirs);3327 status =ll_merge(&result, path,3328&base_file,"base",3329&our_file,"ours",3330&their_file,"theirs", NULL);3331free(base_file.ptr);3332free(our_file.ptr);3333free(their_file.ptr);3334if(status <0|| !result.ptr) {3335free(result.ptr);3336return-1;3337}3338clear_image(image);3339 image->buf = result.ptr;3340 image->len = result.size;33413342return status;3343}33443345/*3346 * When directly falling back to add/add three-way merge, we read from3347 * the current contents of the new_name. In no cases other than that3348 * this function will be called.3349 */3350static intload_current(struct apply_state *state,3351struct image *image,3352struct patch *patch)3353{3354struct strbuf buf = STRBUF_INIT;3355int status, pos;3356size_t len;3357char*img;3358struct stat st;3359struct cache_entry *ce;3360char*name = patch->new_name;3361unsigned mode = patch->new_mode;33623363if(!patch->is_new)3364die("BUG: patch to%sis not a creation", patch->old_name);33653366 pos =cache_name_pos(name,strlen(name));3367if(pos <0)3368returnerror(_("%s: does not exist in index"), name);3369 ce = active_cache[pos];3370if(lstat(name, &st)) {3371if(errno != ENOENT)3372returnerror(_("%s:%s"), name,strerror(errno));3373if(checkout_target(&the_index, ce, &st))3374return-1;3375}3376if(verify_index_match(ce, &st))3377returnerror(_("%s: does not match index"), name);33783379 status =load_patch_target(state, &buf, ce, &st, name, mode);3380if(status <0)3381return status;3382else if(status)3383return-1;3384 img =strbuf_detach(&buf, &len);3385prepare_image(image, img, len, !patch->is_binary);3386return0;3387}33883389static inttry_threeway(struct apply_state *state,3390struct image *image,3391struct patch *patch,3392struct stat *st,3393const struct cache_entry *ce)3394{3395unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3396struct strbuf buf = STRBUF_INIT;3397size_t len;3398int status;3399char*img;3400struct image tmp_image;34013402/* No point falling back to 3-way merge in these cases */3403if(patch->is_delete ||3404S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3405return-1;34063407/* Preimage the patch was prepared for */3408if(patch->is_new)3409write_sha1_file("",0, blob_type, pre_sha1);3410else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3411read_blob_object(&buf, pre_sha1, patch->old_mode))3412returnerror("repository lacks the necessary blob to fall back on 3-way merge.");34133414fprintf(stderr,"Falling back to three-way merge...\n");34153416 img =strbuf_detach(&buf, &len);3417prepare_image(&tmp_image, img, len,1);3418/* Apply the patch to get the post image */3419if(apply_fragments(state, &tmp_image, patch) <0) {3420clear_image(&tmp_image);3421return-1;3422}3423/* post_sha1[] is theirs */3424write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3425clear_image(&tmp_image);34263427/* our_sha1[] is ours */3428if(patch->is_new) {3429if(load_current(state, &tmp_image, patch))3430returnerror("cannot read the current contents of '%s'",3431 patch->new_name);3432}else{3433if(load_preimage(state, &tmp_image, patch, st, ce))3434returnerror("cannot read the current contents of '%s'",3435 patch->old_name);3436}3437write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3438clear_image(&tmp_image);34393440/* in-core three-way merge between post and our using pre as base */3441 status =three_way_merge(image, patch->new_name,3442 pre_sha1, our_sha1, post_sha1);3443if(status <0) {3444fprintf(stderr,"Failed to fall back on three-way merge...\n");3445return status;3446}34473448if(status) {3449 patch->conflicted_threeway =1;3450if(patch->is_new)3451oidclr(&patch->threeway_stage[0]);3452else3453hashcpy(patch->threeway_stage[0].hash, pre_sha1);3454hashcpy(patch->threeway_stage[1].hash, our_sha1);3455hashcpy(patch->threeway_stage[2].hash, post_sha1);3456fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3457}else{3458fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3459}3460return0;3461}34623463static intapply_data(struct apply_state *state,struct patch *patch,3464struct stat *st,const struct cache_entry *ce)3465{3466struct image image;34673468if(load_preimage(state, &image, patch, st, ce) <0)3469return-1;34703471if(patch->direct_to_threeway ||3472apply_fragments(state, &image, patch) <0) {3473/* Note: with --reject, apply_fragments() returns 0 */3474if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3475return-1;3476}3477 patch->result = image.buf;3478 patch->resultsize = image.len;3479add_to_fn_table(state, patch);3480free(image.line_allocated);34813482if(0< patch->is_delete && patch->resultsize)3483returnerror(_("removal patch leaves file contents"));34843485return0;3486}34873488/*3489 * If "patch" that we are looking at modifies or deletes what we have,3490 * we would want it not to lose any local modification we have, either3491 * in the working tree or in the index.3492 *3493 * This also decides if a non-git patch is a creation patch or a3494 * modification to an existing empty file. We do not check the state3495 * of the current tree for a creation patch in this function; the caller3496 * check_patch() separately makes sure (and errors out otherwise) that3497 * the path the patch creates does not exist in the current tree.3498 */3499static intcheck_preimage(struct apply_state *state,3500struct patch *patch,3501struct cache_entry **ce,3502struct stat *st)3503{3504const char*old_name = patch->old_name;3505struct patch *previous = NULL;3506int stat_ret =0, status;3507unsigned st_mode =0;35083509if(!old_name)3510return0;35113512assert(patch->is_new <=0);3513 previous =previous_patch(state, patch, &status);35143515if(status)3516returnerror(_("path%shas been renamed/deleted"), old_name);3517if(previous) {3518 st_mode = previous->new_mode;3519}else if(!state->cached) {3520 stat_ret =lstat(old_name, st);3521if(stat_ret && errno != ENOENT)3522returnerror(_("%s:%s"), old_name,strerror(errno));3523}35243525if(state->check_index && !previous) {3526int pos =cache_name_pos(old_name,strlen(old_name));3527if(pos <0) {3528if(patch->is_new <0)3529goto is_new;3530returnerror(_("%s: does not exist in index"), old_name);3531}3532*ce = active_cache[pos];3533if(stat_ret <0) {3534if(checkout_target(&the_index, *ce, st))3535return-1;3536}3537if(!state->cached &&verify_index_match(*ce, st))3538returnerror(_("%s: does not match index"), old_name);3539if(state->cached)3540 st_mode = (*ce)->ce_mode;3541}else if(stat_ret <0) {3542if(patch->is_new <0)3543goto is_new;3544returnerror(_("%s:%s"), old_name,strerror(errno));3545}35463547if(!state->cached && !previous)3548 st_mode =ce_mode_from_stat(*ce, st->st_mode);35493550if(patch->is_new <0)3551 patch->is_new =0;3552if(!patch->old_mode)3553 patch->old_mode = st_mode;3554if((st_mode ^ patch->old_mode) & S_IFMT)3555returnerror(_("%s: wrong type"), old_name);3556if(st_mode != patch->old_mode)3557warning(_("%shas type%o, expected%o"),3558 old_name, st_mode, patch->old_mode);3559if(!patch->new_mode && !patch->is_delete)3560 patch->new_mode = st_mode;3561return0;35623563 is_new:3564 patch->is_new =1;3565 patch->is_delete =0;3566free(patch->old_name);3567 patch->old_name = NULL;3568return0;3569}357035713572#define EXISTS_IN_INDEX 13573#define EXISTS_IN_WORKTREE 235743575static intcheck_to_create(struct apply_state *state,3576const char*new_name,3577int ok_if_exists)3578{3579struct stat nst;35803581if(state->check_index &&3582cache_name_pos(new_name,strlen(new_name)) >=0&&3583!ok_if_exists)3584return EXISTS_IN_INDEX;3585if(state->cached)3586return0;35873588if(!lstat(new_name, &nst)) {3589if(S_ISDIR(nst.st_mode) || ok_if_exists)3590return0;3591/*3592 * A leading component of new_name might be a symlink3593 * that is going to be removed with this patch, but3594 * still pointing at somewhere that has the path.3595 * In such a case, path "new_name" does not exist as3596 * far as git is concerned.3597 */3598if(has_symlink_leading_path(new_name,strlen(new_name)))3599return0;36003601return EXISTS_IN_WORKTREE;3602}else if((errno != ENOENT) && (errno != ENOTDIR)) {3603returnerror("%s:%s", new_name,strerror(errno));3604}3605return0;3606}36073608static uintptr_tregister_symlink_changes(struct apply_state *state,3609const char*path,3610uintptr_t what)3611{3612struct string_list_item *ent;36133614 ent =string_list_lookup(&state->symlink_changes, path);3615if(!ent) {3616 ent =string_list_insert(&state->symlink_changes, path);3617 ent->util = (void*)0;3618}3619 ent->util = (void*)(what | ((uintptr_t)ent->util));3620return(uintptr_t)ent->util;3621}36223623static uintptr_tcheck_symlink_changes(struct apply_state *state,const char*path)3624{3625struct string_list_item *ent;36263627 ent =string_list_lookup(&state->symlink_changes, path);3628if(!ent)3629return0;3630return(uintptr_t)ent->util;3631}36323633static voidprepare_symlink_changes(struct apply_state *state,struct patch *patch)3634{3635for( ; patch; patch = patch->next) {3636if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3637(patch->is_rename || patch->is_delete))3638/* the symlink at patch->old_name is removed */3639register_symlink_changes(state, patch->old_name, APPLY_SYMLINK_GOES_AWAY);36403641if(patch->new_name &&S_ISLNK(patch->new_mode))3642/* the symlink at patch->new_name is created or remains */3643register_symlink_changes(state, patch->new_name, APPLY_SYMLINK_IN_RESULT);3644}3645}36463647static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3648{3649do{3650unsigned int change;36513652while(--name->len && name->buf[name->len] !='/')3653;/* scan backwards */3654if(!name->len)3655break;3656 name->buf[name->len] ='\0';3657 change =check_symlink_changes(state, name->buf);3658if(change & APPLY_SYMLINK_IN_RESULT)3659return1;3660if(change & APPLY_SYMLINK_GOES_AWAY)3661/*3662 * This cannot be "return 0", because we may3663 * see a new one created at a higher level.3664 */3665continue;36663667/* otherwise, check the preimage */3668if(state->check_index) {3669struct cache_entry *ce;36703671 ce =cache_file_exists(name->buf, name->len, ignore_case);3672if(ce &&S_ISLNK(ce->ce_mode))3673return1;3674}else{3675struct stat st;3676if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3677return1;3678}3679}while(1);3680return0;3681}36823683static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3684{3685int ret;3686struct strbuf name = STRBUF_INIT;36873688assert(*name_ !='\0');3689strbuf_addstr(&name, name_);3690 ret =path_is_beyond_symlink_1(state, &name);3691strbuf_release(&name);36923693return ret;3694}36953696static voiddie_on_unsafe_path(struct patch *patch)3697{3698const char*old_name = NULL;3699const char*new_name = NULL;3700if(patch->is_delete)3701 old_name = patch->old_name;3702else if(!patch->is_new && !patch->is_copy)3703 old_name = patch->old_name;3704if(!patch->is_delete)3705 new_name = patch->new_name;37063707if(old_name && !verify_path(old_name))3708die(_("invalid path '%s'"), old_name);3709if(new_name && !verify_path(new_name))3710die(_("invalid path '%s'"), new_name);3711}37123713/*3714 * Check and apply the patch in-core; leave the result in patch->result3715 * for the caller to write it out to the final destination.3716 */3717static intcheck_patch(struct apply_state *state,struct patch *patch)3718{3719struct stat st;3720const char*old_name = patch->old_name;3721const char*new_name = patch->new_name;3722const char*name = old_name ? old_name : new_name;3723struct cache_entry *ce = NULL;3724struct patch *tpatch;3725int ok_if_exists;3726int status;37273728 patch->rejected =1;/* we will drop this after we succeed */37293730 status =check_preimage(state, patch, &ce, &st);3731if(status)3732return status;3733 old_name = patch->old_name;37343735/*3736 * A type-change diff is always split into a patch to delete3737 * old, immediately followed by a patch to create new (see3738 * diff.c::run_diff()); in such a case it is Ok that the entry3739 * to be deleted by the previous patch is still in the working3740 * tree and in the index.3741 *3742 * A patch to swap-rename between A and B would first rename A3743 * to B and then rename B to A. While applying the first one,3744 * the presence of B should not stop A from getting renamed to3745 * B; ask to_be_deleted() about the later rename. Removal of3746 * B and rename from A to B is handled the same way by asking3747 * was_deleted().3748 */3749if((tpatch =in_fn_table(state, new_name)) &&3750(was_deleted(tpatch) ||to_be_deleted(tpatch)))3751 ok_if_exists =1;3752else3753 ok_if_exists =0;37543755if(new_name &&3756((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3757int err =check_to_create(state, new_name, ok_if_exists);37583759if(err && state->threeway) {3760 patch->direct_to_threeway =1;3761}else switch(err) {3762case0:3763break;/* happy */3764case EXISTS_IN_INDEX:3765returnerror(_("%s: already exists in index"), new_name);3766break;3767case EXISTS_IN_WORKTREE:3768returnerror(_("%s: already exists in working directory"),3769 new_name);3770default:3771return err;3772}37733774if(!patch->new_mode) {3775if(0< patch->is_new)3776 patch->new_mode = S_IFREG |0644;3777else3778 patch->new_mode = patch->old_mode;3779}3780}37813782if(new_name && old_name) {3783int same = !strcmp(old_name, new_name);3784if(!patch->new_mode)3785 patch->new_mode = patch->old_mode;3786if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3787if(same)3788returnerror(_("new mode (%o) of%sdoes not "3789"match old mode (%o)"),3790 patch->new_mode, new_name,3791 patch->old_mode);3792else3793returnerror(_("new mode (%o) of%sdoes not "3794"match old mode (%o) of%s"),3795 patch->new_mode, new_name,3796 patch->old_mode, old_name);3797}3798}37993800if(!state->unsafe_paths)3801die_on_unsafe_path(patch);38023803/*3804 * An attempt to read from or delete a path that is beyond a3805 * symbolic link will be prevented by load_patch_target() that3806 * is called at the beginning of apply_data() so we do not3807 * have to worry about a patch marked with "is_delete" bit3808 * here. We however need to make sure that the patch result3809 * is not deposited to a path that is beyond a symbolic link3810 * here.3811 */3812if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3813returnerror(_("affected file '%s' is beyond a symbolic link"),3814 patch->new_name);38153816if(apply_data(state, patch, &st, ce) <0)3817returnerror(_("%s: patch does not apply"), name);3818 patch->rejected =0;3819return0;3820}38213822static intcheck_patch_list(struct apply_state *state,struct patch *patch)3823{3824int err =0;38253826prepare_symlink_changes(state, patch);3827prepare_fn_table(state, patch);3828while(patch) {3829if(state->apply_verbosely)3830say_patch_name(stderr,3831_("Checking patch%s..."), patch);3832 err |=check_patch(state, patch);3833 patch = patch->next;3834}3835return err;3836}38373838/* This function tries to read the sha1 from the current index */3839static intget_current_sha1(const char*path,unsigned char*sha1)3840{3841int pos;38423843if(read_cache() <0)3844return-1;3845 pos =cache_name_pos(path,strlen(path));3846if(pos <0)3847return-1;3848hashcpy(sha1, active_cache[pos]->sha1);3849return0;3850}38513852static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3853{3854/*3855 * A usable gitlink patch has only one fragment (hunk) that looks like:3856 * @@ -1 +1 @@3857 * -Subproject commit <old sha1>3858 * +Subproject commit <new sha1>3859 * or3860 * @@ -1 +0,0 @@3861 * -Subproject commit <old sha1>3862 * for a removal patch.3863 */3864struct fragment *hunk = p->fragments;3865static const char heading[] ="-Subproject commit ";3866char*preimage;38673868if(/* does the patch have only one hunk? */3869 hunk && !hunk->next &&3870/* is its preimage one line? */3871 hunk->oldpos ==1&& hunk->oldlines ==1&&3872/* does preimage begin with the heading? */3873(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3874starts_with(++preimage, heading) &&3875/* does it record full SHA-1? */3876!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3877 preimage[sizeof(heading) +40-1] =='\n'&&3878/* does the abbreviated name on the index line agree with it? */3879starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3880return0;/* it all looks fine */38813882/* we may have full object name on the index line */3883returnget_sha1_hex(p->old_sha1_prefix, sha1);3884}38853886/* Build an index that contains the just the files needed for a 3way merge */3887static voidbuild_fake_ancestor(struct patch *list,const char*filename)3888{3889struct patch *patch;3890struct index_state result = { NULL };3891static struct lock_file lock;38923893/* Once we start supporting the reverse patch, it may be3894 * worth showing the new sha1 prefix, but until then...3895 */3896for(patch = list; patch; patch = patch->next) {3897unsigned char sha1[20];3898struct cache_entry *ce;3899const char*name;39003901 name = patch->old_name ? patch->old_name : patch->new_name;3902if(0< patch->is_new)3903continue;39043905if(S_ISGITLINK(patch->old_mode)) {3906if(!preimage_sha1_in_gitlink_patch(patch, sha1))3907;/* ok, the textual part looks sane */3908else3909die("sha1 information is lacking or useless for submodule%s",3910 name);3911}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {3912;/* ok */3913}else if(!patch->lines_added && !patch->lines_deleted) {3914/* mode-only change: update the current */3915if(get_current_sha1(patch->old_name, sha1))3916die("mode change for%s, which is not "3917"in current HEAD", name);3918}else3919die("sha1 information is lacking or useless "3920"(%s).", name);39213922 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);3923if(!ce)3924die(_("make_cache_entry failed for path '%s'"), name);3925if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3926die("Could not add%sto temporary index", name);3927}39283929hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);3930if(write_locked_index(&result, &lock, COMMIT_LOCK))3931die("Could not write temporary index to%s", filename);39323933discard_index(&result);3934}39353936static voidstat_patch_list(struct apply_state *state,struct patch *patch)3937{3938int files, adds, dels;39393940for(files = adds = dels =0; patch ; patch = patch->next) {3941 files++;3942 adds += patch->lines_added;3943 dels += patch->lines_deleted;3944show_stats(state, patch);3945}39463947print_stat_summary(stdout, files, adds, dels);3948}39493950static voidnumstat_patch_list(struct apply_state *state,3951struct patch *patch)3952{3953for( ; patch; patch = patch->next) {3954const char*name;3955 name = patch->new_name ? patch->new_name : patch->old_name;3956if(patch->is_binary)3957printf("-\t-\t");3958else3959printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3960write_name_quoted(name, stdout, state->line_termination);3961}3962}39633964static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3965{3966if(mode)3967printf("%smode%06o%s\n", newdelete, mode, name);3968else3969printf("%s %s\n", newdelete, name);3970}39713972static voidshow_mode_change(struct patch *p,int show_name)3973{3974if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3975if(show_name)3976printf(" mode change%06o =>%06o%s\n",3977 p->old_mode, p->new_mode, p->new_name);3978else3979printf(" mode change%06o =>%06o\n",3980 p->old_mode, p->new_mode);3981}3982}39833984static voidshow_rename_copy(struct patch *p)3985{3986const char*renamecopy = p->is_rename ?"rename":"copy";3987const char*old, *new;39883989/* Find common prefix */3990 old = p->old_name;3991new= p->new_name;3992while(1) {3993const char*slash_old, *slash_new;3994 slash_old =strchr(old,'/');3995 slash_new =strchr(new,'/');3996if(!slash_old ||3997!slash_new ||3998 slash_old - old != slash_new -new||3999memcmp(old,new, slash_new -new))4000break;4001 old = slash_old +1;4002new= slash_new +1;4003}4004/* p->old_name thru old is the common prefix, and old and new4005 * through the end of names are renames4006 */4007if(old != p->old_name)4008printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4009(int)(old - p->old_name), p->old_name,4010 old,new, p->score);4011else4012printf("%s %s=>%s(%d%%)\n", renamecopy,4013 p->old_name, p->new_name, p->score);4014show_mode_change(p,0);4015}40164017static voidsummary_patch_list(struct patch *patch)4018{4019struct patch *p;40204021for(p = patch; p; p = p->next) {4022if(p->is_new)4023show_file_mode_name("create", p->new_mode, p->new_name);4024else if(p->is_delete)4025show_file_mode_name("delete", p->old_mode, p->old_name);4026else{4027if(p->is_rename || p->is_copy)4028show_rename_copy(p);4029else{4030if(p->score) {4031printf(" rewrite%s(%d%%)\n",4032 p->new_name, p->score);4033show_mode_change(p,0);4034}4035else4036show_mode_change(p,1);4037}4038}4039}4040}40414042static voidpatch_stats(struct apply_state *state,struct patch *patch)4043{4044int lines = patch->lines_added + patch->lines_deleted;40454046if(lines > state->max_change)4047 state->max_change = lines;4048if(patch->old_name) {4049int len =quote_c_style(patch->old_name, NULL, NULL,0);4050if(!len)4051 len =strlen(patch->old_name);4052if(len > state->max_len)4053 state->max_len = len;4054}4055if(patch->new_name) {4056int len =quote_c_style(patch->new_name, NULL, NULL,0);4057if(!len)4058 len =strlen(patch->new_name);4059if(len > state->max_len)4060 state->max_len = len;4061}4062}40634064static voidremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4065{4066if(state->update_index) {4067if(remove_file_from_cache(patch->old_name) <0)4068die(_("unable to remove%sfrom index"), patch->old_name);4069}4070if(!state->cached) {4071if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4072remove_path(patch->old_name);4073}4074}4075}40764077static voidadd_index_file(struct apply_state *state,4078const char*path,4079unsigned mode,4080void*buf,4081unsigned long size)4082{4083struct stat st;4084struct cache_entry *ce;4085int namelen =strlen(path);4086unsigned ce_size =cache_entry_size(namelen);40874088if(!state->update_index)4089return;40904091 ce =xcalloc(1, ce_size);4092memcpy(ce->name, path, namelen);4093 ce->ce_mode =create_ce_mode(mode);4094 ce->ce_flags =create_ce_flags(0);4095 ce->ce_namelen = namelen;4096if(S_ISGITLINK(mode)) {4097const char*s;40984099if(!skip_prefix(buf,"Subproject commit ", &s) ||4100get_sha1_hex(s, ce->sha1))4101die(_("corrupt patch for submodule%s"), path);4102}else{4103if(!state->cached) {4104if(lstat(path, &st) <0)4105die_errno(_("unable to stat newly created file '%s'"),4106 path);4107fill_stat_cache_info(ce, &st);4108}4109if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4110die(_("unable to create backing store for newly created file%s"), path);4111}4112if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4113die(_("unable to add cache entry for%s"), path);4114}41154116static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4117{4118int fd;4119struct strbuf nbuf = STRBUF_INIT;41204121if(S_ISGITLINK(mode)) {4122struct stat st;4123if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4124return0;4125returnmkdir(path,0777);4126}41274128if(has_symlinks &&S_ISLNK(mode))4129/* Although buf:size is counted string, it also is NUL4130 * terminated.4131 */4132returnsymlink(buf, path);41334134 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4135if(fd <0)4136return-1;41374138if(convert_to_working_tree(path, buf, size, &nbuf)) {4139 size = nbuf.len;4140 buf = nbuf.buf;4141}4142write_or_die(fd, buf, size);4143strbuf_release(&nbuf);41444145if(close(fd) <0)4146die_errno(_("closing file '%s'"), path);4147return0;4148}41494150/*4151 * We optimistically assume that the directories exist,4152 * which is true 99% of the time anyway. If they don't,4153 * we create them and try again.4154 */4155static voidcreate_one_file(struct apply_state *state,4156char*path,4157unsigned mode,4158const char*buf,4159unsigned long size)4160{4161if(state->cached)4162return;4163if(!try_create_file(path, mode, buf, size))4164return;41654166if(errno == ENOENT) {4167if(safe_create_leading_directories(path))4168return;4169if(!try_create_file(path, mode, buf, size))4170return;4171}41724173if(errno == EEXIST || errno == EACCES) {4174/* We may be trying to create a file where a directory4175 * used to be.4176 */4177struct stat st;4178if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4179 errno = EEXIST;4180}41814182if(errno == EEXIST) {4183unsigned int nr =getpid();41844185for(;;) {4186char newpath[PATH_MAX];4187mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4188if(!try_create_file(newpath, mode, buf, size)) {4189if(!rename(newpath, path))4190return;4191unlink_or_warn(newpath);4192break;4193}4194if(errno != EEXIST)4195break;4196++nr;4197}4198}4199die_errno(_("unable to write file '%s' mode%o"), path, mode);4200}42014202static voidadd_conflicted_stages_file(struct apply_state *state,4203struct patch *patch)4204{4205int stage, namelen;4206unsigned ce_size, mode;4207struct cache_entry *ce;42084209if(!state->update_index)4210return;4211 namelen =strlen(patch->new_name);4212 ce_size =cache_entry_size(namelen);4213 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);42144215remove_file_from_cache(patch->new_name);4216for(stage =1; stage <4; stage++) {4217if(is_null_oid(&patch->threeway_stage[stage -1]))4218continue;4219 ce =xcalloc(1, ce_size);4220memcpy(ce->name, patch->new_name, namelen);4221 ce->ce_mode =create_ce_mode(mode);4222 ce->ce_flags =create_ce_flags(stage);4223 ce->ce_namelen = namelen;4224hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4225if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4226die(_("unable to add cache entry for%s"), patch->new_name);4227}4228}42294230static voidcreate_file(struct apply_state *state,struct patch *patch)4231{4232char*path = patch->new_name;4233unsigned mode = patch->new_mode;4234unsigned long size = patch->resultsize;4235char*buf = patch->result;42364237if(!mode)4238 mode = S_IFREG |0644;4239create_one_file(state, path, mode, buf, size);42404241if(patch->conflicted_threeway)4242add_conflicted_stages_file(state, patch);4243else4244add_index_file(state, path, mode, buf, size);4245}42464247/* phase zero is to remove, phase one is to create */4248static voidwrite_out_one_result(struct apply_state *state,4249struct patch *patch,4250int phase)4251{4252if(patch->is_delete >0) {4253if(phase ==0)4254remove_file(state, patch,1);4255return;4256}4257if(patch->is_new >0|| patch->is_copy) {4258if(phase ==1)4259create_file(state, patch);4260return;4261}4262/*4263 * Rename or modification boils down to the same4264 * thing: remove the old, write the new4265 */4266if(phase ==0)4267remove_file(state, patch, patch->is_rename);4268if(phase ==1)4269create_file(state, patch);4270}42714272static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4273{4274FILE*rej;4275char namebuf[PATH_MAX];4276struct fragment *frag;4277int cnt =0;4278struct strbuf sb = STRBUF_INIT;42794280for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4281if(!frag->rejected)4282continue;4283 cnt++;4284}42854286if(!cnt) {4287if(state->apply_verbosely)4288say_patch_name(stderr,4289_("Applied patch%scleanly."), patch);4290return0;4291}42924293/* This should not happen, because a removal patch that leaves4294 * contents are marked "rejected" at the patch level.4295 */4296if(!patch->new_name)4297die(_("internal error"));42984299/* Say this even without --verbose */4300strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4301"Applying patch %%swith%drejects...",4302 cnt),4303 cnt);4304say_patch_name(stderr, sb.buf, patch);4305strbuf_release(&sb);43064307 cnt =strlen(patch->new_name);4308if(ARRAY_SIZE(namebuf) <= cnt +5) {4309 cnt =ARRAY_SIZE(namebuf) -5;4310warning(_("truncating .rej filename to %.*s.rej"),4311 cnt -1, patch->new_name);4312}4313memcpy(namebuf, patch->new_name, cnt);4314memcpy(namebuf + cnt,".rej",5);43154316 rej =fopen(namebuf,"w");4317if(!rej)4318returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));43194320/* Normal git tools never deal with .rej, so do not pretend4321 * this is a git patch by saying --git or giving extended4322 * headers. While at it, maybe please "kompare" that wants4323 * the trailing TAB and some garbage at the end of line ;-).4324 */4325fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4326 patch->new_name, patch->new_name);4327for(cnt =1, frag = patch->fragments;4328 frag;4329 cnt++, frag = frag->next) {4330if(!frag->rejected) {4331fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4332continue;4333}4334fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4335fprintf(rej,"%.*s", frag->size, frag->patch);4336if(frag->patch[frag->size-1] !='\n')4337fputc('\n', rej);4338}4339fclose(rej);4340return-1;4341}43424343static intwrite_out_results(struct apply_state *state,struct patch *list)4344{4345int phase;4346int errs =0;4347struct patch *l;4348struct string_list cpath = STRING_LIST_INIT_DUP;43494350for(phase =0; phase <2; phase++) {4351 l = list;4352while(l) {4353if(l->rejected)4354 errs =1;4355else{4356write_out_one_result(state, l, phase);4357if(phase ==1) {4358if(write_out_one_reject(state, l))4359 errs =1;4360if(l->conflicted_threeway) {4361string_list_append(&cpath, l->new_name);4362 errs =1;4363}4364}4365}4366 l = l->next;4367}4368}43694370if(cpath.nr) {4371struct string_list_item *item;43724373string_list_sort(&cpath);4374for_each_string_list_item(item, &cpath)4375fprintf(stderr,"U%s\n", item->string);4376string_list_clear(&cpath,0);43774378rerere(0);4379}43804381return errs;4382}43834384static struct lock_file lock_file;43854386#define INACCURATE_EOF (1<<0)4387#define RECOUNT (1<<1)43884389/*4390 * Try to apply a patch.4391 *4392 * Returns:4393 * -128 if a bad error happened (like patch unreadable)4394 * -1 if patch did not apply and user cannot deal with it4395 * 0 if the patch applied4396 * 1 if the patch did not apply but user might fix it4397 */4398static intapply_patch(struct apply_state *state,4399int fd,4400const char*filename,4401int options)4402{4403size_t offset;4404struct strbuf buf = STRBUF_INIT;/* owns the patch text */4405struct patch *list = NULL, **listp = &list;4406int skipped_patch =0;4407int res =0;44084409 state->patch_input_file = filename;4410if(read_patch_file(&buf, fd) <0)4411return-128;4412 offset =0;4413while(offset < buf.len) {4414struct patch *patch;4415int nr;44164417 patch =xcalloc(1,sizeof(*patch));4418 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4419 patch->recount = !!(options & RECOUNT);4420 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4421if(nr <0) {4422free_patch(patch);4423if(nr == -128) {4424 res = -128;4425goto end;4426}4427break;4428}4429if(state->apply_in_reverse)4430reverse_patches(patch);4431if(use_patch(state, patch)) {4432patch_stats(state, patch);4433*listp = patch;4434 listp = &patch->next;4435}4436else{4437if(state->apply_verbosely)4438say_patch_name(stderr,_("Skipped patch '%s'."), patch);4439free_patch(patch);4440 skipped_patch++;4441}4442 offset += nr;4443}44444445if(!list && !skipped_patch) {4446error(_("unrecognized input"));4447 res = -128;4448goto end;4449}44504451if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4452 state->apply =0;44534454 state->update_index = state->check_index && state->apply;4455if(state->update_index && state->newfd <0)4456 state->newfd =hold_locked_index(state->lock_file,1);44574458if(state->check_index &&read_cache() <0) {4459error(_("unable to read index file"));4460 res = -128;4461goto end;4462}44634464if((state->check || state->apply) &&4465check_patch_list(state, list) <0&&4466!state->apply_with_reject) {4467 res = -1;4468goto end;4469}44704471if(state->apply &&write_out_results(state, list)) {4472/* with --3way, we still need to write the index out */4473 res = state->apply_with_reject ? -1:1;4474goto end;4475}44764477if(state->fake_ancestor)4478build_fake_ancestor(list, state->fake_ancestor);44794480if(state->diffstat)4481stat_patch_list(state, list);44824483if(state->numstat)4484numstat_patch_list(state, list);44854486if(state->summary)4487summary_patch_list(list);44884489end:4490free_patch_list(list);4491strbuf_release(&buf);4492string_list_clear(&state->fn_table,0);4493return res;4494}44954496static intoption_parse_exclude(const struct option *opt,4497const char*arg,int unset)4498{4499struct apply_state *state = opt->value;4500add_name_limit(state, arg,1);4501return0;4502}45034504static intoption_parse_include(const struct option *opt,4505const char*arg,int unset)4506{4507struct apply_state *state = opt->value;4508add_name_limit(state, arg,0);4509 state->has_include =1;4510return0;4511}45124513static intoption_parse_p(const struct option *opt,4514const char*arg,4515int unset)4516{4517struct apply_state *state = opt->value;4518 state->p_value =atoi(arg);4519 state->p_value_known =1;4520return0;4521}45224523static intoption_parse_space_change(const struct option *opt,4524const char*arg,int unset)4525{4526struct apply_state *state = opt->value;4527if(unset)4528 state->ws_ignore_action = ignore_ws_none;4529else4530 state->ws_ignore_action = ignore_ws_change;4531return0;4532}45334534static intoption_parse_whitespace(const struct option *opt,4535const char*arg,int unset)4536{4537struct apply_state *state = opt->value;4538 state->whitespace_option = arg;4539if(parse_whitespace_option(state, arg))4540exit(1);4541return0;4542}45434544static intoption_parse_directory(const struct option *opt,4545const char*arg,int unset)4546{4547struct apply_state *state = opt->value;4548strbuf_reset(&state->root);4549strbuf_addstr(&state->root, arg);4550strbuf_complete(&state->root,'/');4551return0;4552}45534554static voidcheck_apply_state(struct apply_state *state,int force_apply)4555{4556int is_not_gitdir = !startup_info->have_repository;45574558if(state->apply_with_reject && state->threeway)4559die("--reject and --3way cannot be used together.");4560if(state->cached && state->threeway)4561die("--cached and --3way cannot be used together.");4562if(state->threeway) {4563if(is_not_gitdir)4564die(_("--3way outside a repository"));4565 state->check_index =1;4566}4567if(state->apply_with_reject)4568 state->apply = state->apply_verbosely =1;4569if(!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor))4570 state->apply =0;4571if(state->check_index && is_not_gitdir)4572die(_("--index outside a repository"));4573if(state->cached) {4574if(is_not_gitdir)4575die(_("--cached outside a repository"));4576 state->check_index =1;4577}4578if(state->check_index)4579 state->unsafe_paths =0;4580if(!state->lock_file)4581die("BUG: state->lock_file should not be NULL");4582}45834584static intapply_all_patches(struct apply_state *state,4585int argc,4586const char**argv,4587int options)4588{4589int i;4590int res;4591int errs =0;4592int read_stdin =1;45934594for(i =0; i < argc; i++) {4595const char*arg = argv[i];4596int fd;45974598if(!strcmp(arg,"-")) {4599 res =apply_patch(state,0,"<stdin>", options);4600if(res <0)4601goto end;4602 errs |= res;4603 read_stdin =0;4604continue;4605}else if(0< state->prefix_length)4606 arg =prefix_filename(state->prefix,4607 state->prefix_length,4608 arg);46094610 fd =open(arg, O_RDONLY);4611if(fd <0)4612die_errno(_("can't open patch '%s'"), arg);4613 read_stdin =0;4614set_default_whitespace_mode(state);4615 res =apply_patch(state, fd, arg, options);4616if(res <0)4617goto end;4618 errs |= res;4619close(fd);4620}4621set_default_whitespace_mode(state);4622if(read_stdin) {4623 res =apply_patch(state,0,"<stdin>", options);4624if(res <0)4625goto end;4626 errs |= res;4627}46284629if(state->whitespace_error) {4630if(state->squelch_whitespace_errors &&4631 state->squelch_whitespace_errors < state->whitespace_error) {4632int squelched =4633 state->whitespace_error - state->squelch_whitespace_errors;4634warning(Q_("squelched%dwhitespace error",4635"squelched%dwhitespace errors",4636 squelched),4637 squelched);4638}4639if(state->ws_error_action == die_on_ws_error)4640die(Q_("%dline adds whitespace errors.",4641"%dlines add whitespace errors.",4642 state->whitespace_error),4643 state->whitespace_error);4644if(state->applied_after_fixing_ws && state->apply)4645warning("%dline%sapplied after"4646" fixing whitespace errors.",4647 state->applied_after_fixing_ws,4648 state->applied_after_fixing_ws ==1?"":"s");4649else if(state->whitespace_error)4650warning(Q_("%dline adds whitespace errors.",4651"%dlines add whitespace errors.",4652 state->whitespace_error),4653 state->whitespace_error);4654}46554656if(state->update_index) {4657if(write_locked_index(&the_index, state->lock_file, COMMIT_LOCK))4658die(_("Unable to write new index file"));4659 state->newfd = -1;4660}46614662return!!errs;46634664end:4665exit(res == -1?1:128);4666}46674668intcmd_apply(int argc,const char**argv,const char*prefix)4669{4670int force_apply =0;4671int options =0;4672int ret;4673struct apply_state state;46744675struct option builtin_apply_options[] = {4676{ OPTION_CALLBACK,0,"exclude", &state,N_("path"),4677N_("don't apply changes matching the given path"),46780, option_parse_exclude },4679{ OPTION_CALLBACK,0,"include", &state,N_("path"),4680N_("apply changes matching the given path"),46810, option_parse_include },4682{ OPTION_CALLBACK,'p', NULL, &state,N_("num"),4683N_("remove <num> leading slashes from traditional diff paths"),46840, option_parse_p },4685OPT_BOOL(0,"no-add", &state.no_add,4686N_("ignore additions made by the patch")),4687OPT_BOOL(0,"stat", &state.diffstat,4688N_("instead of applying the patch, output diffstat for the input")),4689OPT_NOOP_NOARG(0,"allow-binary-replacement"),4690OPT_NOOP_NOARG(0,"binary"),4691OPT_BOOL(0,"numstat", &state.numstat,4692N_("show number of added and deleted lines in decimal notation")),4693OPT_BOOL(0,"summary", &state.summary,4694N_("instead of applying the patch, output a summary for the input")),4695OPT_BOOL(0,"check", &state.check,4696N_("instead of applying the patch, see if the patch is applicable")),4697OPT_BOOL(0,"index", &state.check_index,4698N_("make sure the patch is applicable to the current index")),4699OPT_BOOL(0,"cached", &state.cached,4700N_("apply a patch without touching the working tree")),4701OPT_BOOL(0,"unsafe-paths", &state.unsafe_paths,4702N_("accept a patch that touches outside the working area")),4703OPT_BOOL(0,"apply", &force_apply,4704N_("also apply the patch (use with --stat/--summary/--check)")),4705OPT_BOOL('3',"3way", &state.threeway,4706N_("attempt three-way merge if a patch does not apply")),4707OPT_FILENAME(0,"build-fake-ancestor", &state.fake_ancestor,4708N_("build a temporary index based on embedded index information")),4709/* Think twice before adding "--nul" synonym to this */4710OPT_SET_INT('z', NULL, &state.line_termination,4711N_("paths are separated with NUL character"),'\0'),4712OPT_INTEGER('C', NULL, &state.p_context,4713N_("ensure at least <n> lines of context match")),4714{ OPTION_CALLBACK,0,"whitespace", &state,N_("action"),4715N_("detect new or modified lines that have whitespace errors"),47160, option_parse_whitespace },4717{ OPTION_CALLBACK,0,"ignore-space-change", &state, NULL,4718N_("ignore changes in whitespace when finding context"),4719 PARSE_OPT_NOARG, option_parse_space_change },4720{ OPTION_CALLBACK,0,"ignore-whitespace", &state, NULL,4721N_("ignore changes in whitespace when finding context"),4722 PARSE_OPT_NOARG, option_parse_space_change },4723OPT_BOOL('R',"reverse", &state.apply_in_reverse,4724N_("apply the patch in reverse")),4725OPT_BOOL(0,"unidiff-zero", &state.unidiff_zero,4726N_("don't expect at least one line of context")),4727OPT_BOOL(0,"reject", &state.apply_with_reject,4728N_("leave the rejected hunks in corresponding *.rej files")),4729OPT_BOOL(0,"allow-overlap", &state.allow_overlap,4730N_("allow overlapping hunks")),4731OPT__VERBOSE(&state.apply_verbosely,N_("be verbose")),4732OPT_BIT(0,"inaccurate-eof", &options,4733N_("tolerate incorrectly detected missing new-line at the end of file"),4734 INACCURATE_EOF),4735OPT_BIT(0,"recount", &options,4736N_("do not trust the line counts in the hunk headers"),4737 RECOUNT),4738{ OPTION_CALLBACK,0,"directory", &state,N_("root"),4739N_("prepend <root> to all filenames"),47400, option_parse_directory },4741OPT_END()4742};47434744init_apply_state(&state, prefix, &lock_file);47454746 argc =parse_options(argc, argv, state.prefix, builtin_apply_options,4747 apply_usage,0);47484749check_apply_state(&state, force_apply);47504751 ret =apply_all_patches(&state, argc, argv, options);47524753clear_apply_state(&state);47544755return ret;4756}