1/* 2 * apply.c 3 * 4 * Copyright (C) Linus Torvalds, 2005 5 * 6 * This applies patches on top of some (arbitrary) version of the SCM. 7 * 8 */ 9#include"cache.h" 10#include"lockfile.h" 11#include"cache-tree.h" 12#include"quote.h" 13#include"blob.h" 14#include"delta.h" 15#include"builtin.h" 16#include"string-list.h" 17#include"dir.h" 18#include"diff.h" 19#include"parse-options.h" 20#include"xdiff-interface.h" 21#include"ll-merge.h" 22#include"rerere.h" 23 24struct apply_state { 25const char*prefix; 26int prefix_length; 27 28/* These control what gets looked at and modified */ 29int check;/* preimage must match working tree, don't actually apply */ 30 31/* These boolean parameters control how the apply is done */ 32int unidiff_zero; 33}; 34 35/* 36 * --stat does just a diffstat, and doesn't actually apply 37 * --numstat does numeric diffstat, and doesn't actually apply 38 * --index-info shows the old and new index info for paths if available. 39 * --index updates the cache as well. 40 * --cached updates only the cache without ever touching the working tree. 41 */ 42static int newfd = -1; 43 44static int state_p_value =1; 45static int p_value_known; 46static int check_index; 47static int update_index; 48static int cached; 49static int diffstat; 50static int numstat; 51static int summary; 52static int apply =1; 53static int apply_in_reverse; 54static int apply_with_reject; 55static int apply_verbosely; 56static int allow_overlap; 57static int no_add; 58static int threeway; 59static int unsafe_paths; 60static const char*fake_ancestor; 61static int line_termination ='\n'; 62static unsigned int p_context = UINT_MAX; 63static const char*const apply_usage[] = { 64N_("git apply [<options>] [<patch>...]"), 65 NULL 66}; 67 68static enum ws_error_action { 69 nowarn_ws_error, 70 warn_on_ws_error, 71 die_on_ws_error, 72 correct_ws_error 73} ws_error_action = warn_on_ws_error; 74static int whitespace_error; 75static int squelch_whitespace_errors =5; 76static int applied_after_fixing_ws; 77 78static enum ws_ignore { 79 ignore_ws_none, 80 ignore_ws_change 81} ws_ignore_action = ignore_ws_none; 82 83 84static const char*patch_input_file; 85static struct strbuf root = STRBUF_INIT; 86 87static voidparse_whitespace_option(const char*option) 88{ 89if(!option) { 90 ws_error_action = warn_on_ws_error; 91return; 92} 93if(!strcmp(option,"warn")) { 94 ws_error_action = warn_on_ws_error; 95return; 96} 97if(!strcmp(option,"nowarn")) { 98 ws_error_action = nowarn_ws_error; 99return; 100} 101if(!strcmp(option,"error")) { 102 ws_error_action = die_on_ws_error; 103return; 104} 105if(!strcmp(option,"error-all")) { 106 ws_error_action = die_on_ws_error; 107 squelch_whitespace_errors =0; 108return; 109} 110if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 111 ws_error_action = correct_ws_error; 112return; 113} 114die(_("unrecognized whitespace option '%s'"), option); 115} 116 117static voidparse_ignorewhitespace_option(const char*option) 118{ 119if(!option || !strcmp(option,"no") || 120!strcmp(option,"false") || !strcmp(option,"never") || 121!strcmp(option,"none")) { 122 ws_ignore_action = ignore_ws_none; 123return; 124} 125if(!strcmp(option,"change")) { 126 ws_ignore_action = ignore_ws_change; 127return; 128} 129die(_("unrecognized whitespace ignore option '%s'"), option); 130} 131 132static voidset_default_whitespace_mode(const char*whitespace_option) 133{ 134if(!whitespace_option && !apply_default_whitespace) 135 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 136} 137 138/* 139 * For "diff-stat" like behaviour, we keep track of the biggest change 140 * we've seen, and the longest filename. That allows us to do simple 141 * scaling. 142 */ 143static int max_change, max_len; 144 145/* 146 * Various "current state", notably line numbers and what 147 * file (and how) we're patching right now.. The "is_xxxx" 148 * things are flags, where -1 means "don't know yet". 149 */ 150static int state_linenr =1; 151 152/* 153 * This represents one "hunk" from a patch, starting with 154 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 155 * patch text is pointed at by patch, and its byte length 156 * is stored in size. leading and trailing are the number 157 * of context lines. 158 */ 159struct fragment { 160unsigned long leading, trailing; 161unsigned long oldpos, oldlines; 162unsigned long newpos, newlines; 163/* 164 * 'patch' is usually borrowed from buf in apply_patch(), 165 * but some codepaths store an allocated buffer. 166 */ 167const char*patch; 168unsigned free_patch:1, 169 rejected:1; 170int size; 171int linenr; 172struct fragment *next; 173}; 174 175/* 176 * When dealing with a binary patch, we reuse "leading" field 177 * to store the type of the binary hunk, either deflated "delta" 178 * or deflated "literal". 179 */ 180#define binary_patch_method leading 181#define BINARY_DELTA_DEFLATED 1 182#define BINARY_LITERAL_DEFLATED 2 183 184/* 185 * This represents a "patch" to a file, both metainfo changes 186 * such as creation/deletion, filemode and content changes represented 187 * as a series of fragments. 188 */ 189struct patch { 190char*new_name, *old_name, *def_name; 191unsigned int old_mode, new_mode; 192int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 193int rejected; 194unsigned ws_rule; 195int lines_added, lines_deleted; 196int score; 197unsigned int is_toplevel_relative:1; 198unsigned int inaccurate_eof:1; 199unsigned int is_binary:1; 200unsigned int is_copy:1; 201unsigned int is_rename:1; 202unsigned int recount:1; 203unsigned int conflicted_threeway:1; 204unsigned int direct_to_threeway:1; 205struct fragment *fragments; 206char*result; 207size_t resultsize; 208char old_sha1_prefix[41]; 209char new_sha1_prefix[41]; 210struct patch *next; 211 212/* three-way fallback result */ 213struct object_id threeway_stage[3]; 214}; 215 216static voidfree_fragment_list(struct fragment *list) 217{ 218while(list) { 219struct fragment *next = list->next; 220if(list->free_patch) 221free((char*)list->patch); 222free(list); 223 list = next; 224} 225} 226 227static voidfree_patch(struct patch *patch) 228{ 229free_fragment_list(patch->fragments); 230free(patch->def_name); 231free(patch->old_name); 232free(patch->new_name); 233free(patch->result); 234free(patch); 235} 236 237static voidfree_patch_list(struct patch *list) 238{ 239while(list) { 240struct patch *next = list->next; 241free_patch(list); 242 list = next; 243} 244} 245 246/* 247 * A line in a file, len-bytes long (includes the terminating LF, 248 * except for an incomplete line at the end if the file ends with 249 * one), and its contents hashes to 'hash'. 250 */ 251struct line { 252size_t len; 253unsigned hash :24; 254unsigned flag :8; 255#define LINE_COMMON 1 256#define LINE_PATCHED 2 257}; 258 259/* 260 * This represents a "file", which is an array of "lines". 261 */ 262struct image { 263char*buf; 264size_t len; 265size_t nr; 266size_t alloc; 267struct line *line_allocated; 268struct line *line; 269}; 270 271/* 272 * Records filenames that have been touched, in order to handle 273 * the case where more than one patches touch the same file. 274 */ 275 276static struct string_list fn_table; 277 278static uint32_thash_line(const char*cp,size_t len) 279{ 280size_t i; 281uint32_t h; 282for(i =0, h =0; i < len; i++) { 283if(!isspace(cp[i])) { 284 h = h *3+ (cp[i] &0xff); 285} 286} 287return h; 288} 289 290/* 291 * Compare lines s1 of length n1 and s2 of length n2, ignoring 292 * whitespace difference. Returns 1 if they match, 0 otherwise 293 */ 294static intfuzzy_matchlines(const char*s1,size_t n1, 295const char*s2,size_t n2) 296{ 297const char*last1 = s1 + n1 -1; 298const char*last2 = s2 + n2 -1; 299int result =0; 300 301/* ignore line endings */ 302while((*last1 =='\r') || (*last1 =='\n')) 303 last1--; 304while((*last2 =='\r') || (*last2 =='\n')) 305 last2--; 306 307/* skip leading whitespaces, if both begin with whitespace */ 308if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 309while(isspace(*s1) && (s1 <= last1)) 310 s1++; 311while(isspace(*s2) && (s2 <= last2)) 312 s2++; 313} 314/* early return if both lines are empty */ 315if((s1 > last1) && (s2 > last2)) 316return1; 317while(!result) { 318 result = *s1++ - *s2++; 319/* 320 * Skip whitespace inside. We check for whitespace on 321 * both buffers because we don't want "a b" to match 322 * "ab" 323 */ 324if(isspace(*s1) &&isspace(*s2)) { 325while(isspace(*s1) && s1 <= last1) 326 s1++; 327while(isspace(*s2) && s2 <= last2) 328 s2++; 329} 330/* 331 * If we reached the end on one side only, 332 * lines don't match 333 */ 334if( 335((s2 > last2) && (s1 <= last1)) || 336((s1 > last1) && (s2 <= last2))) 337return0; 338if((s1 > last1) && (s2 > last2)) 339break; 340} 341 342return!result; 343} 344 345static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 346{ 347ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 348 img->line_allocated[img->nr].len = len; 349 img->line_allocated[img->nr].hash =hash_line(bol, len); 350 img->line_allocated[img->nr].flag = flag; 351 img->nr++; 352} 353 354/* 355 * "buf" has the file contents to be patched (read from various sources). 356 * attach it to "image" and add line-based index to it. 357 * "image" now owns the "buf". 358 */ 359static voidprepare_image(struct image *image,char*buf,size_t len, 360int prepare_linetable) 361{ 362const char*cp, *ep; 363 364memset(image,0,sizeof(*image)); 365 image->buf = buf; 366 image->len = len; 367 368if(!prepare_linetable) 369return; 370 371 ep = image->buf + image->len; 372 cp = image->buf; 373while(cp < ep) { 374const char*next; 375for(next = cp; next < ep && *next !='\n'; next++) 376; 377if(next < ep) 378 next++; 379add_line_info(image, cp, next - cp,0); 380 cp = next; 381} 382 image->line = image->line_allocated; 383} 384 385static voidclear_image(struct image *image) 386{ 387free(image->buf); 388free(image->line_allocated); 389memset(image,0,sizeof(*image)); 390} 391 392/* fmt must contain _one_ %s and no other substitution */ 393static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 394{ 395struct strbuf sb = STRBUF_INIT; 396 397if(patch->old_name && patch->new_name && 398strcmp(patch->old_name, patch->new_name)) { 399quote_c_style(patch->old_name, &sb, NULL,0); 400strbuf_addstr(&sb," => "); 401quote_c_style(patch->new_name, &sb, NULL,0); 402}else{ 403const char*n = patch->new_name; 404if(!n) 405 n = patch->old_name; 406quote_c_style(n, &sb, NULL,0); 407} 408fprintf(output, fmt, sb.buf); 409fputc('\n', output); 410strbuf_release(&sb); 411} 412 413#define SLOP (16) 414 415static voidread_patch_file(struct strbuf *sb,int fd) 416{ 417if(strbuf_read(sb, fd,0) <0) 418die_errno("git apply: failed to read"); 419 420/* 421 * Make sure that we have some slop in the buffer 422 * so that we can do speculative "memcmp" etc, and 423 * see to it that it is NUL-filled. 424 */ 425strbuf_grow(sb, SLOP); 426memset(sb->buf + sb->len,0, SLOP); 427} 428 429static unsigned longlinelen(const char*buffer,unsigned long size) 430{ 431unsigned long len =0; 432while(size--) { 433 len++; 434if(*buffer++ =='\n') 435break; 436} 437return len; 438} 439 440static intis_dev_null(const char*str) 441{ 442returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 443} 444 445#define TERM_SPACE 1 446#define TERM_TAB 2 447 448static intname_terminate(const char*name,int namelen,int c,int terminate) 449{ 450if(c ==' '&& !(terminate & TERM_SPACE)) 451return0; 452if(c =='\t'&& !(terminate & TERM_TAB)) 453return0; 454 455return1; 456} 457 458/* remove double slashes to make --index work with such filenames */ 459static char*squash_slash(char*name) 460{ 461int i =0, j =0; 462 463if(!name) 464return NULL; 465 466while(name[i]) { 467if((name[j++] = name[i++]) =='/') 468while(name[i] =='/') 469 i++; 470} 471 name[j] ='\0'; 472return name; 473} 474 475static char*find_name_gnu(const char*line,const char*def,int p_value) 476{ 477struct strbuf name = STRBUF_INIT; 478char*cp; 479 480/* 481 * Proposed "new-style" GNU patch/diff format; see 482 * http://marc.info/?l=git&m=112927316408690&w=2 483 */ 484if(unquote_c_style(&name, line, NULL)) { 485strbuf_release(&name); 486return NULL; 487} 488 489for(cp = name.buf; p_value; p_value--) { 490 cp =strchr(cp,'/'); 491if(!cp) { 492strbuf_release(&name); 493return NULL; 494} 495 cp++; 496} 497 498strbuf_remove(&name,0, cp - name.buf); 499if(root.len) 500strbuf_insert(&name,0, root.buf, root.len); 501returnsquash_slash(strbuf_detach(&name, NULL)); 502} 503 504static size_tsane_tz_len(const char*line,size_t len) 505{ 506const char*tz, *p; 507 508if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 509return0; 510 tz = line + len -strlen(" +0500"); 511 512if(tz[1] !='+'&& tz[1] !='-') 513return0; 514 515for(p = tz +2; p != line + len; p++) 516if(!isdigit(*p)) 517return0; 518 519return line + len - tz; 520} 521 522static size_ttz_with_colon_len(const char*line,size_t len) 523{ 524const char*tz, *p; 525 526if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 527return0; 528 tz = line + len -strlen(" +08:00"); 529 530if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 531return0; 532 p = tz +2; 533if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 534!isdigit(*p++) || !isdigit(*p++)) 535return0; 536 537return line + len - tz; 538} 539 540static size_tdate_len(const char*line,size_t len) 541{ 542const char*date, *p; 543 544if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 545return0; 546 p = date = line + len -strlen("72-02-05"); 547 548if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 549!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 550!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 551return0; 552 553if(date - line >=strlen("19") && 554isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 555 date -=strlen("19"); 556 557return line + len - date; 558} 559 560static size_tshort_time_len(const char*line,size_t len) 561{ 562const char*time, *p; 563 564if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 565return0; 566 p = time = line + len -strlen(" 07:01:32"); 567 568/* Permit 1-digit hours? */ 569if(*p++ !=' '|| 570!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 571!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 572!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 573return0; 574 575return line + len - time; 576} 577 578static size_tfractional_time_len(const char*line,size_t len) 579{ 580const char*p; 581size_t n; 582 583/* Expected format: 19:41:17.620000023 */ 584if(!len || !isdigit(line[len -1])) 585return0; 586 p = line + len -1; 587 588/* Fractional seconds. */ 589while(p > line &&isdigit(*p)) 590 p--; 591if(*p !='.') 592return0; 593 594/* Hours, minutes, and whole seconds. */ 595 n =short_time_len(line, p - line); 596if(!n) 597return0; 598 599return line + len - p + n; 600} 601 602static size_ttrailing_spaces_len(const char*line,size_t len) 603{ 604const char*p; 605 606/* Expected format: ' ' x (1 or more) */ 607if(!len || line[len -1] !=' ') 608return0; 609 610 p = line + len; 611while(p != line) { 612 p--; 613if(*p !=' ') 614return line + len - (p +1); 615} 616 617/* All spaces! */ 618return len; 619} 620 621static size_tdiff_timestamp_len(const char*line,size_t len) 622{ 623const char*end = line + len; 624size_t n; 625 626/* 627 * Posix: 2010-07-05 19:41:17 628 * GNU: 2010-07-05 19:41:17.620000023 -0500 629 */ 630 631if(!isdigit(end[-1])) 632return0; 633 634 n =sane_tz_len(line, end - line); 635if(!n) 636 n =tz_with_colon_len(line, end - line); 637 end -= n; 638 639 n =short_time_len(line, end - line); 640if(!n) 641 n =fractional_time_len(line, end - line); 642 end -= n; 643 644 n =date_len(line, end - line); 645if(!n)/* No date. Too bad. */ 646return0; 647 end -= n; 648 649if(end == line)/* No space before date. */ 650return0; 651if(end[-1] =='\t') {/* Success! */ 652 end--; 653return line + len - end; 654} 655if(end[-1] !=' ')/* No space before date. */ 656return0; 657 658/* Whitespace damage. */ 659 end -=trailing_spaces_len(line, end - line); 660return line + len - end; 661} 662 663static char*find_name_common(const char*line,const char*def, 664int p_value,const char*end,int terminate) 665{ 666int len; 667const char*start = NULL; 668 669if(p_value ==0) 670 start = line; 671while(line != end) { 672char c = *line; 673 674if(!end &&isspace(c)) { 675if(c =='\n') 676break; 677if(name_terminate(start, line-start, c, terminate)) 678break; 679} 680 line++; 681if(c =='/'&& !--p_value) 682 start = line; 683} 684if(!start) 685returnsquash_slash(xstrdup_or_null(def)); 686 len = line - start; 687if(!len) 688returnsquash_slash(xstrdup_or_null(def)); 689 690/* 691 * Generally we prefer the shorter name, especially 692 * if the other one is just a variation of that with 693 * something else tacked on to the end (ie "file.orig" 694 * or "file~"). 695 */ 696if(def) { 697int deflen =strlen(def); 698if(deflen < len && !strncmp(start, def, deflen)) 699returnsquash_slash(xstrdup(def)); 700} 701 702if(root.len) { 703char*ret =xstrfmt("%s%.*s", root.buf, len, start); 704returnsquash_slash(ret); 705} 706 707returnsquash_slash(xmemdupz(start, len)); 708} 709 710static char*find_name(const char*line,char*def,int p_value,int terminate) 711{ 712if(*line =='"') { 713char*name =find_name_gnu(line, def, p_value); 714if(name) 715return name; 716} 717 718returnfind_name_common(line, def, p_value, NULL, terminate); 719} 720 721static char*find_name_traditional(const char*line,char*def,int p_value) 722{ 723size_t len; 724size_t date_len; 725 726if(*line =='"') { 727char*name =find_name_gnu(line, def, p_value); 728if(name) 729return name; 730} 731 732 len =strchrnul(line,'\n') - line; 733 date_len =diff_timestamp_len(line, len); 734if(!date_len) 735returnfind_name_common(line, def, p_value, NULL, TERM_TAB); 736 len -= date_len; 737 738returnfind_name_common(line, def, p_value, line + len,0); 739} 740 741static intcount_slashes(const char*cp) 742{ 743int cnt =0; 744char ch; 745 746while((ch = *cp++)) 747if(ch =='/') 748 cnt++; 749return cnt; 750} 751 752/* 753 * Given the string after "--- " or "+++ ", guess the appropriate 754 * p_value for the given patch. 755 */ 756static intguess_p_value(struct apply_state *state,const char*nameline) 757{ 758char*name, *cp; 759int val = -1; 760 761if(is_dev_null(nameline)) 762return-1; 763 name =find_name_traditional(nameline, NULL,0); 764if(!name) 765return-1; 766 cp =strchr(name,'/'); 767if(!cp) 768 val =0; 769else if(state->prefix) { 770/* 771 * Does it begin with "a/$our-prefix" and such? Then this is 772 * very likely to apply to our directory. 773 */ 774if(!strncmp(name, state->prefix, state->prefix_length)) 775 val =count_slashes(state->prefix); 776else{ 777 cp++; 778if(!strncmp(cp, state->prefix, state->prefix_length)) 779 val =count_slashes(state->prefix) +1; 780} 781} 782free(name); 783return val; 784} 785 786/* 787 * Does the ---/+++ line have the POSIX timestamp after the last HT? 788 * GNU diff puts epoch there to signal a creation/deletion event. Is 789 * this such a timestamp? 790 */ 791static inthas_epoch_timestamp(const char*nameline) 792{ 793/* 794 * We are only interested in epoch timestamp; any non-zero 795 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 796 * For the same reason, the date must be either 1969-12-31 or 797 * 1970-01-01, and the seconds part must be "00". 798 */ 799const char stamp_regexp[] = 800"^(1969-12-31|1970-01-01)" 801" " 802"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 803" " 804"([-+][0-2][0-9]:?[0-5][0-9])\n"; 805const char*timestamp = NULL, *cp, *colon; 806static regex_t *stamp; 807 regmatch_t m[10]; 808int zoneoffset; 809int hourminute; 810int status; 811 812for(cp = nameline; *cp !='\n'; cp++) { 813if(*cp =='\t') 814 timestamp = cp +1; 815} 816if(!timestamp) 817return0; 818if(!stamp) { 819 stamp =xmalloc(sizeof(*stamp)); 820if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 821warning(_("Cannot prepare timestamp regexp%s"), 822 stamp_regexp); 823return0; 824} 825} 826 827 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 828if(status) { 829if(status != REG_NOMATCH) 830warning(_("regexec returned%dfor input:%s"), 831 status, timestamp); 832return0; 833} 834 835 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 836if(*colon ==':') 837 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 838else 839 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 840if(timestamp[m[3].rm_so] =='-') 841 zoneoffset = -zoneoffset; 842 843/* 844 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 845 * (west of GMT) or 1970-01-01 (east of GMT) 846 */ 847if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 848(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 849return0; 850 851 hourminute = (strtol(timestamp +11, NULL,10) *60+ 852strtol(timestamp +14, NULL,10) - 853 zoneoffset); 854 855return((zoneoffset <0&& hourminute ==1440) || 856(0<= zoneoffset && !hourminute)); 857} 858 859/* 860 * Get the name etc info from the ---/+++ lines of a traditional patch header 861 * 862 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 863 * files, we can happily check the index for a match, but for creating a 864 * new file we should try to match whatever "patch" does. I have no idea. 865 */ 866static voidparse_traditional_patch(struct apply_state *state, 867const char*first, 868const char*second, 869struct patch *patch) 870{ 871char*name; 872 873 first +=4;/* skip "--- " */ 874 second +=4;/* skip "+++ " */ 875if(!p_value_known) { 876int p, q; 877 p =guess_p_value(state, first); 878 q =guess_p_value(state, second); 879if(p <0) p = q; 880if(0<= p && p == q) { 881 state_p_value = p; 882 p_value_known =1; 883} 884} 885if(is_dev_null(first)) { 886 patch->is_new =1; 887 patch->is_delete =0; 888 name =find_name_traditional(second, NULL, state_p_value); 889 patch->new_name = name; 890}else if(is_dev_null(second)) { 891 patch->is_new =0; 892 patch->is_delete =1; 893 name =find_name_traditional(first, NULL, state_p_value); 894 patch->old_name = name; 895}else{ 896char*first_name; 897 first_name =find_name_traditional(first, NULL, state_p_value); 898 name =find_name_traditional(second, first_name, state_p_value); 899free(first_name); 900if(has_epoch_timestamp(first)) { 901 patch->is_new =1; 902 patch->is_delete =0; 903 patch->new_name = name; 904}else if(has_epoch_timestamp(second)) { 905 patch->is_new =0; 906 patch->is_delete =1; 907 patch->old_name = name; 908}else{ 909 patch->old_name = name; 910 patch->new_name =xstrdup_or_null(name); 911} 912} 913if(!name) 914die(_("unable to find filename in patch at line%d"), state_linenr); 915} 916 917static intgitdiff_hdrend(const char*line,struct patch *patch) 918{ 919return-1; 920} 921 922/* 923 * We're anal about diff header consistency, to make 924 * sure that we don't end up having strange ambiguous 925 * patches floating around. 926 * 927 * As a result, gitdiff_{old|new}name() will check 928 * their names against any previous information, just 929 * to make sure.. 930 */ 931#define DIFF_OLD_NAME 0 932#define DIFF_NEW_NAME 1 933 934static voidgitdiff_verify_name(const char*line,int isnull,char**name,int side) 935{ 936if(!*name && !isnull) { 937*name =find_name(line, NULL, state_p_value, TERM_TAB); 938return; 939} 940 941if(*name) { 942int len =strlen(*name); 943char*another; 944if(isnull) 945die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 946*name, state_linenr); 947 another =find_name(line, NULL, state_p_value, TERM_TAB); 948if(!another ||memcmp(another, *name, len +1)) 949die((side == DIFF_NEW_NAME) ? 950_("git apply: bad git-diff - inconsistent new filename on line%d") : 951_("git apply: bad git-diff - inconsistent old filename on line%d"), state_linenr); 952free(another); 953}else{ 954/* expect "/dev/null" */ 955if(memcmp("/dev/null", line,9) || line[9] !='\n') 956die(_("git apply: bad git-diff - expected /dev/null on line%d"), state_linenr); 957} 958} 959 960static intgitdiff_oldname(const char*line,struct patch *patch) 961{ 962gitdiff_verify_name(line, patch->is_new, &patch->old_name, 963 DIFF_OLD_NAME); 964return0; 965} 966 967static intgitdiff_newname(const char*line,struct patch *patch) 968{ 969gitdiff_verify_name(line, patch->is_delete, &patch->new_name, 970 DIFF_NEW_NAME); 971return0; 972} 973 974static intgitdiff_oldmode(const char*line,struct patch *patch) 975{ 976 patch->old_mode =strtoul(line, NULL,8); 977return0; 978} 979 980static intgitdiff_newmode(const char*line,struct patch *patch) 981{ 982 patch->new_mode =strtoul(line, NULL,8); 983return0; 984} 985 986static intgitdiff_delete(const char*line,struct patch *patch) 987{ 988 patch->is_delete =1; 989free(patch->old_name); 990 patch->old_name =xstrdup_or_null(patch->def_name); 991returngitdiff_oldmode(line, patch); 992} 993 994static intgitdiff_newfile(const char*line,struct patch *patch) 995{ 996 patch->is_new =1; 997free(patch->new_name); 998 patch->new_name =xstrdup_or_null(patch->def_name); 999returngitdiff_newmode(line, patch);1000}10011002static intgitdiff_copysrc(const char*line,struct patch *patch)1003{1004 patch->is_copy =1;1005free(patch->old_name);1006 patch->old_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1007return0;1008}10091010static intgitdiff_copydst(const char*line,struct patch *patch)1011{1012 patch->is_copy =1;1013free(patch->new_name);1014 patch->new_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1015return0;1016}10171018static intgitdiff_renamesrc(const char*line,struct patch *patch)1019{1020 patch->is_rename =1;1021free(patch->old_name);1022 patch->old_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1023return0;1024}10251026static intgitdiff_renamedst(const char*line,struct patch *patch)1027{1028 patch->is_rename =1;1029free(patch->new_name);1030 patch->new_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1031return0;1032}10331034static intgitdiff_similarity(const char*line,struct patch *patch)1035{1036unsigned long val =strtoul(line, NULL,10);1037if(val <=100)1038 patch->score = val;1039return0;1040}10411042static intgitdiff_dissimilarity(const char*line,struct patch *patch)1043{1044unsigned long val =strtoul(line, NULL,10);1045if(val <=100)1046 patch->score = val;1047return0;1048}10491050static intgitdiff_index(const char*line,struct patch *patch)1051{1052/*1053 * index line is N hexadecimal, "..", N hexadecimal,1054 * and optional space with octal mode.1055 */1056const char*ptr, *eol;1057int len;10581059 ptr =strchr(line,'.');1060if(!ptr || ptr[1] !='.'||40< ptr - line)1061return0;1062 len = ptr - line;1063memcpy(patch->old_sha1_prefix, line, len);1064 patch->old_sha1_prefix[len] =0;10651066 line = ptr +2;1067 ptr =strchr(line,' ');1068 eol =strchrnul(line,'\n');10691070if(!ptr || eol < ptr)1071 ptr = eol;1072 len = ptr - line;10731074if(40< len)1075return0;1076memcpy(patch->new_sha1_prefix, line, len);1077 patch->new_sha1_prefix[len] =0;1078if(*ptr ==' ')1079 patch->old_mode =strtoul(ptr+1, NULL,8);1080return0;1081}10821083/*1084 * This is normal for a diff that doesn't change anything: we'll fall through1085 * into the next diff. Tell the parser to break out.1086 */1087static intgitdiff_unrecognized(const char*line,struct patch *patch)1088{1089return-1;1090}10911092/*1093 * Skip p_value leading components from "line"; as we do not accept1094 * absolute paths, return NULL in that case.1095 */1096static const char*skip_tree_prefix(const char*line,int llen)1097{1098int nslash;1099int i;11001101if(!state_p_value)1102return(llen && line[0] =='/') ? NULL : line;11031104 nslash = state_p_value;1105for(i =0; i < llen; i++) {1106int ch = line[i];1107if(ch =='/'&& --nslash <=0)1108return(i ==0) ? NULL : &line[i +1];1109}1110return NULL;1111}11121113/*1114 * This is to extract the same name that appears on "diff --git"1115 * line. We do not find and return anything if it is a rename1116 * patch, and it is OK because we will find the name elsewhere.1117 * We need to reliably find name only when it is mode-change only,1118 * creation or deletion of an empty file. In any of these cases,1119 * both sides are the same name under a/ and b/ respectively.1120 */1121static char*git_header_name(const char*line,int llen)1122{1123const char*name;1124const char*second = NULL;1125size_t len, line_len;11261127 line +=strlen("diff --git ");1128 llen -=strlen("diff --git ");11291130if(*line =='"') {1131const char*cp;1132struct strbuf first = STRBUF_INIT;1133struct strbuf sp = STRBUF_INIT;11341135if(unquote_c_style(&first, line, &second))1136goto free_and_fail1;11371138/* strip the a/b prefix including trailing slash */1139 cp =skip_tree_prefix(first.buf, first.len);1140if(!cp)1141goto free_and_fail1;1142strbuf_remove(&first,0, cp - first.buf);11431144/*1145 * second points at one past closing dq of name.1146 * find the second name.1147 */1148while((second < line + llen) &&isspace(*second))1149 second++;11501151if(line + llen <= second)1152goto free_and_fail1;1153if(*second =='"') {1154if(unquote_c_style(&sp, second, NULL))1155goto free_and_fail1;1156 cp =skip_tree_prefix(sp.buf, sp.len);1157if(!cp)1158goto free_and_fail1;1159/* They must match, otherwise ignore */1160if(strcmp(cp, first.buf))1161goto free_and_fail1;1162strbuf_release(&sp);1163returnstrbuf_detach(&first, NULL);1164}11651166/* unquoted second */1167 cp =skip_tree_prefix(second, line + llen - second);1168if(!cp)1169goto free_and_fail1;1170if(line + llen - cp != first.len ||1171memcmp(first.buf, cp, first.len))1172goto free_and_fail1;1173returnstrbuf_detach(&first, NULL);11741175 free_and_fail1:1176strbuf_release(&first);1177strbuf_release(&sp);1178return NULL;1179}11801181/* unquoted first name */1182 name =skip_tree_prefix(line, llen);1183if(!name)1184return NULL;11851186/*1187 * since the first name is unquoted, a dq if exists must be1188 * the beginning of the second name.1189 */1190for(second = name; second < line + llen; second++) {1191if(*second =='"') {1192struct strbuf sp = STRBUF_INIT;1193const char*np;11941195if(unquote_c_style(&sp, second, NULL))1196goto free_and_fail2;11971198 np =skip_tree_prefix(sp.buf, sp.len);1199if(!np)1200goto free_and_fail2;12011202 len = sp.buf + sp.len - np;1203if(len < second - name &&1204!strncmp(np, name, len) &&1205isspace(name[len])) {1206/* Good */1207strbuf_remove(&sp,0, np - sp.buf);1208returnstrbuf_detach(&sp, NULL);1209}12101211 free_and_fail2:1212strbuf_release(&sp);1213return NULL;1214}1215}12161217/*1218 * Accept a name only if it shows up twice, exactly the same1219 * form.1220 */1221 second =strchr(name,'\n');1222if(!second)1223return NULL;1224 line_len = second - name;1225for(len =0; ; len++) {1226switch(name[len]) {1227default:1228continue;1229case'\n':1230return NULL;1231case'\t':case' ':1232/*1233 * Is this the separator between the preimage1234 * and the postimage pathname? Again, we are1235 * only interested in the case where there is1236 * no rename, as this is only to set def_name1237 * and a rename patch has the names elsewhere1238 * in an unambiguous form.1239 */1240if(!name[len +1])1241return NULL;/* no postimage name */1242 second =skip_tree_prefix(name + len +1,1243 line_len - (len +1));1244if(!second)1245return NULL;1246/*1247 * Does len bytes starting at "name" and "second"1248 * (that are separated by one HT or SP we just1249 * found) exactly match?1250 */1251if(second[len] =='\n'&& !strncmp(name, second, len))1252returnxmemdupz(name, len);1253}1254}1255}12561257/* Verify that we recognize the lines following a git header */1258static intparse_git_header(const char*line,int len,unsigned int size,struct patch *patch)1259{1260unsigned long offset;12611262/* A git diff has explicit new/delete information, so we don't guess */1263 patch->is_new =0;1264 patch->is_delete =0;12651266/*1267 * Some things may not have the old name in the1268 * rest of the headers anywhere (pure mode changes,1269 * or removing or adding empty files), so we get1270 * the default name from the header.1271 */1272 patch->def_name =git_header_name(line, len);1273if(patch->def_name && root.len) {1274char*s =xstrfmt("%s%s", root.buf, patch->def_name);1275free(patch->def_name);1276 patch->def_name = s;1277}12781279 line += len;1280 size -= len;1281 state_linenr++;1282for(offset = len ; size >0; offset += len, size -= len, line += len, state_linenr++) {1283static const struct opentry {1284const char*str;1285int(*fn)(const char*,struct patch *);1286} optable[] = {1287{"@@ -", gitdiff_hdrend },1288{"--- ", gitdiff_oldname },1289{"+++ ", gitdiff_newname },1290{"old mode ", gitdiff_oldmode },1291{"new mode ", gitdiff_newmode },1292{"deleted file mode ", gitdiff_delete },1293{"new file mode ", gitdiff_newfile },1294{"copy from ", gitdiff_copysrc },1295{"copy to ", gitdiff_copydst },1296{"rename old ", gitdiff_renamesrc },1297{"rename new ", gitdiff_renamedst },1298{"rename from ", gitdiff_renamesrc },1299{"rename to ", gitdiff_renamedst },1300{"similarity index ", gitdiff_similarity },1301{"dissimilarity index ", gitdiff_dissimilarity },1302{"index ", gitdiff_index },1303{"", gitdiff_unrecognized },1304};1305int i;13061307 len =linelen(line, size);1308if(!len || line[len-1] !='\n')1309break;1310for(i =0; i <ARRAY_SIZE(optable); i++) {1311const struct opentry *p = optable + i;1312int oplen =strlen(p->str);1313if(len < oplen ||memcmp(p->str, line, oplen))1314continue;1315if(p->fn(line + oplen, patch) <0)1316return offset;1317break;1318}1319}13201321return offset;1322}13231324static intparse_num(const char*line,unsigned long*p)1325{1326char*ptr;13271328if(!isdigit(*line))1329return0;1330*p =strtoul(line, &ptr,10);1331return ptr - line;1332}13331334static intparse_range(const char*line,int len,int offset,const char*expect,1335unsigned long*p1,unsigned long*p2)1336{1337int digits, ex;13381339if(offset <0|| offset >= len)1340return-1;1341 line += offset;1342 len -= offset;13431344 digits =parse_num(line, p1);1345if(!digits)1346return-1;13471348 offset += digits;1349 line += digits;1350 len -= digits;13511352*p2 =1;1353if(*line ==',') {1354 digits =parse_num(line+1, p2);1355if(!digits)1356return-1;13571358 offset += digits+1;1359 line += digits+1;1360 len -= digits+1;1361}13621363 ex =strlen(expect);1364if(ex > len)1365return-1;1366if(memcmp(line, expect, ex))1367return-1;13681369return offset + ex;1370}13711372static voidrecount_diff(const char*line,int size,struct fragment *fragment)1373{1374int oldlines =0, newlines =0, ret =0;13751376if(size <1) {1377warning("recount: ignore empty hunk");1378return;1379}13801381for(;;) {1382int len =linelen(line, size);1383 size -= len;1384 line += len;13851386if(size <1)1387break;13881389switch(*line) {1390case' ':case'\n':1391 newlines++;1392/* fall through */1393case'-':1394 oldlines++;1395continue;1396case'+':1397 newlines++;1398continue;1399case'\\':1400continue;1401case'@':1402 ret = size <3|| !starts_with(line,"@@ ");1403break;1404case'd':1405 ret = size <5|| !starts_with(line,"diff ");1406break;1407default:1408 ret = -1;1409break;1410}1411if(ret) {1412warning(_("recount: unexpected line: %.*s"),1413(int)linelen(line, size), line);1414return;1415}1416break;1417}1418 fragment->oldlines = oldlines;1419 fragment->newlines = newlines;1420}14211422/*1423 * Parse a unified diff fragment header of the1424 * form "@@ -a,b +c,d @@"1425 */1426static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1427{1428int offset;14291430if(!len || line[len-1] !='\n')1431return-1;14321433/* Figure out the number of lines in a fragment */1434 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1435 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14361437return offset;1438}14391440static intfind_header(struct apply_state *state,1441const char*line,1442unsigned long size,1443int*hdrsize,1444struct patch *patch)1445{1446unsigned long offset, len;14471448 patch->is_toplevel_relative =0;1449 patch->is_rename = patch->is_copy =0;1450 patch->is_new = patch->is_delete = -1;1451 patch->old_mode = patch->new_mode =0;1452 patch->old_name = patch->new_name = NULL;1453for(offset =0; size >0; offset += len, size -= len, line += len, state_linenr++) {1454unsigned long nextlen;14551456 len =linelen(line, size);1457if(!len)1458break;14591460/* Testing this early allows us to take a few shortcuts.. */1461if(len <6)1462continue;14631464/*1465 * Make sure we don't find any unconnected patch fragments.1466 * That's a sign that we didn't find a header, and that a1467 * patch has become corrupted/broken up.1468 */1469if(!memcmp("@@ -", line,4)) {1470struct fragment dummy;1471if(parse_fragment_header(line, len, &dummy) <0)1472continue;1473die(_("patch fragment without header at line%d: %.*s"),1474 state_linenr, (int)len-1, line);1475}14761477if(size < len +6)1478break;14791480/*1481 * Git patch? It might not have a real patch, just a rename1482 * or mode change, so we handle that specially1483 */1484if(!memcmp("diff --git ", line,11)) {1485int git_hdr_len =parse_git_header(line, len, size, patch);1486if(git_hdr_len <= len)1487continue;1488if(!patch->old_name && !patch->new_name) {1489if(!patch->def_name)1490die(Q_("git diff header lacks filename information when removing "1491"%dleading pathname component (line%d)",1492"git diff header lacks filename information when removing "1493"%dleading pathname components (line%d)",1494 state_p_value),1495 state_p_value, state_linenr);1496 patch->old_name =xstrdup(patch->def_name);1497 patch->new_name =xstrdup(patch->def_name);1498}1499if(!patch->is_delete && !patch->new_name)1500die("git diff header lacks filename information "1501"(line%d)", state_linenr);1502 patch->is_toplevel_relative =1;1503*hdrsize = git_hdr_len;1504return offset;1505}15061507/* --- followed by +++ ? */1508if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1509continue;15101511/*1512 * We only accept unified patches, so we want it to1513 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1514 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1515 */1516 nextlen =linelen(line + len, size - len);1517if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1518continue;15191520/* Ok, we'll consider it a patch */1521parse_traditional_patch(state, line, line+len, patch);1522*hdrsize = len + nextlen;1523 state_linenr +=2;1524return offset;1525}1526return-1;1527}15281529static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1530{1531char*err;15321533if(!result)1534return;15351536 whitespace_error++;1537if(squelch_whitespace_errors &&1538 squelch_whitespace_errors < whitespace_error)1539return;15401541 err =whitespace_error_string(result);1542fprintf(stderr,"%s:%d:%s.\n%.*s\n",1543 patch_input_file, linenr, err, len, line);1544free(err);1545}15461547static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1548{1549unsigned result =ws_check(line +1, len -1, ws_rule);15501551record_ws_error(result, line +1, len -2, state_linenr);1552}15531554/*1555 * Parse a unified diff. Note that this really needs to parse each1556 * fragment separately, since the only way to know the difference1557 * between a "---" that is part of a patch, and a "---" that starts1558 * the next patch is to look at the line counts..1559 */1560static intparse_fragment(const char*line,unsigned long size,1561struct patch *patch,struct fragment *fragment)1562{1563int added, deleted;1564int len =linelen(line, size), offset;1565unsigned long oldlines, newlines;1566unsigned long leading, trailing;15671568 offset =parse_fragment_header(line, len, fragment);1569if(offset <0)1570return-1;1571if(offset >0&& patch->recount)1572recount_diff(line + offset, size - offset, fragment);1573 oldlines = fragment->oldlines;1574 newlines = fragment->newlines;1575 leading =0;1576 trailing =0;15771578/* Parse the thing.. */1579 line += len;1580 size -= len;1581 state_linenr++;1582 added = deleted =0;1583for(offset = len;15840< size;1585 offset += len, size -= len, line += len, state_linenr++) {1586if(!oldlines && !newlines)1587break;1588 len =linelen(line, size);1589if(!len || line[len-1] !='\n')1590return-1;1591switch(*line) {1592default:1593return-1;1594case'\n':/* newer GNU diff, an empty context line */1595case' ':1596 oldlines--;1597 newlines--;1598if(!deleted && !added)1599 leading++;1600 trailing++;1601if(!apply_in_reverse &&1602 ws_error_action == correct_ws_error)1603check_whitespace(line, len, patch->ws_rule);1604break;1605case'-':1606if(apply_in_reverse &&1607 ws_error_action != nowarn_ws_error)1608check_whitespace(line, len, patch->ws_rule);1609 deleted++;1610 oldlines--;1611 trailing =0;1612break;1613case'+':1614if(!apply_in_reverse &&1615 ws_error_action != nowarn_ws_error)1616check_whitespace(line, len, patch->ws_rule);1617 added++;1618 newlines--;1619 trailing =0;1620break;16211622/*1623 * We allow "\ No newline at end of file". Depending1624 * on locale settings when the patch was produced we1625 * don't know what this line looks like. The only1626 * thing we do know is that it begins with "\ ".1627 * Checking for 12 is just for sanity check -- any1628 * l10n of "\ No newline..." is at least that long.1629 */1630case'\\':1631if(len <12||memcmp(line,"\\",2))1632return-1;1633break;1634}1635}1636if(oldlines || newlines)1637return-1;1638if(!deleted && !added)1639return-1;16401641 fragment->leading = leading;1642 fragment->trailing = trailing;16431644/*1645 * If a fragment ends with an incomplete line, we failed to include1646 * it in the above loop because we hit oldlines == newlines == 01647 * before seeing it.1648 */1649if(12< size && !memcmp(line,"\\",2))1650 offset +=linelen(line, size);16511652 patch->lines_added += added;1653 patch->lines_deleted += deleted;16541655if(0< patch->is_new && oldlines)1656returnerror(_("new file depends on old contents"));1657if(0< patch->is_delete && newlines)1658returnerror(_("deleted file still has contents"));1659return offset;1660}16611662/*1663 * We have seen "diff --git a/... b/..." header (or a traditional patch1664 * header). Read hunks that belong to this patch into fragments and hang1665 * them to the given patch structure.1666 *1667 * The (fragment->patch, fragment->size) pair points into the memory given1668 * by the caller, not a copy, when we return.1669 */1670static intparse_single_patch(const char*line,unsigned long size,struct patch *patch)1671{1672unsigned long offset =0;1673unsigned long oldlines =0, newlines =0, context =0;1674struct fragment **fragp = &patch->fragments;16751676while(size >4&& !memcmp(line,"@@ -",4)) {1677struct fragment *fragment;1678int len;16791680 fragment =xcalloc(1,sizeof(*fragment));1681 fragment->linenr = state_linenr;1682 len =parse_fragment(line, size, patch, fragment);1683if(len <=0)1684die(_("corrupt patch at line%d"), state_linenr);1685 fragment->patch = line;1686 fragment->size = len;1687 oldlines += fragment->oldlines;1688 newlines += fragment->newlines;1689 context += fragment->leading + fragment->trailing;16901691*fragp = fragment;1692 fragp = &fragment->next;16931694 offset += len;1695 line += len;1696 size -= len;1697}16981699/*1700 * If something was removed (i.e. we have old-lines) it cannot1701 * be creation, and if something was added it cannot be1702 * deletion. However, the reverse is not true; --unified=01703 * patches that only add are not necessarily creation even1704 * though they do not have any old lines, and ones that only1705 * delete are not necessarily deletion.1706 *1707 * Unfortunately, a real creation/deletion patch do _not_ have1708 * any context line by definition, so we cannot safely tell it1709 * apart with --unified=0 insanity. At least if the patch has1710 * more than one hunk it is not creation or deletion.1711 */1712if(patch->is_new <0&&1713(oldlines || (patch->fragments && patch->fragments->next)))1714 patch->is_new =0;1715if(patch->is_delete <0&&1716(newlines || (patch->fragments && patch->fragments->next)))1717 patch->is_delete =0;17181719if(0< patch->is_new && oldlines)1720die(_("new file%sdepends on old contents"), patch->new_name);1721if(0< patch->is_delete && newlines)1722die(_("deleted file%sstill has contents"), patch->old_name);1723if(!patch->is_delete && !newlines && context)1724fprintf_ln(stderr,1725_("** warning: "1726"file%sbecomes empty but is not deleted"),1727 patch->new_name);17281729return offset;1730}17311732staticinlineintmetadata_changes(struct patch *patch)1733{1734return patch->is_rename >0||1735 patch->is_copy >0||1736 patch->is_new >0||1737 patch->is_delete ||1738(patch->old_mode && patch->new_mode &&1739 patch->old_mode != patch->new_mode);1740}17411742static char*inflate_it(const void*data,unsigned long size,1743unsigned long inflated_size)1744{1745 git_zstream stream;1746void*out;1747int st;17481749memset(&stream,0,sizeof(stream));17501751 stream.next_in = (unsigned char*)data;1752 stream.avail_in = size;1753 stream.next_out = out =xmalloc(inflated_size);1754 stream.avail_out = inflated_size;1755git_inflate_init(&stream);1756 st =git_inflate(&stream, Z_FINISH);1757git_inflate_end(&stream);1758if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1759free(out);1760return NULL;1761}1762return out;1763}17641765/*1766 * Read a binary hunk and return a new fragment; fragment->patch1767 * points at an allocated memory that the caller must free, so1768 * it is marked as "->free_patch = 1".1769 */1770static struct fragment *parse_binary_hunk(char**buf_p,1771unsigned long*sz_p,1772int*status_p,1773int*used_p)1774{1775/*1776 * Expect a line that begins with binary patch method ("literal"1777 * or "delta"), followed by the length of data before deflating.1778 * a sequence of 'length-byte' followed by base-85 encoded data1779 * should follow, terminated by a newline.1780 *1781 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1782 * and we would limit the patch line to 66 characters,1783 * so one line can fit up to 13 groups that would decode1784 * to 52 bytes max. The length byte 'A'-'Z' corresponds1785 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1786 */1787int llen, used;1788unsigned long size = *sz_p;1789char*buffer = *buf_p;1790int patch_method;1791unsigned long origlen;1792char*data = NULL;1793int hunk_size =0;1794struct fragment *frag;17951796 llen =linelen(buffer, size);1797 used = llen;17981799*status_p =0;18001801if(starts_with(buffer,"delta ")) {1802 patch_method = BINARY_DELTA_DEFLATED;1803 origlen =strtoul(buffer +6, NULL,10);1804}1805else if(starts_with(buffer,"literal ")) {1806 patch_method = BINARY_LITERAL_DEFLATED;1807 origlen =strtoul(buffer +8, NULL,10);1808}1809else1810return NULL;18111812 state_linenr++;1813 buffer += llen;1814while(1) {1815int byte_length, max_byte_length, newsize;1816 llen =linelen(buffer, size);1817 used += llen;1818 state_linenr++;1819if(llen ==1) {1820/* consume the blank line */1821 buffer++;1822 size--;1823break;1824}1825/*1826 * Minimum line is "A00000\n" which is 7-byte long,1827 * and the line length must be multiple of 5 plus 2.1828 */1829if((llen <7) || (llen-2) %5)1830goto corrupt;1831 max_byte_length = (llen -2) /5*4;1832 byte_length = *buffer;1833if('A'<= byte_length && byte_length <='Z')1834 byte_length = byte_length -'A'+1;1835else if('a'<= byte_length && byte_length <='z')1836 byte_length = byte_length -'a'+27;1837else1838goto corrupt;1839/* if the input length was not multiple of 4, we would1840 * have filler at the end but the filler should never1841 * exceed 3 bytes1842 */1843if(max_byte_length < byte_length ||1844 byte_length <= max_byte_length -4)1845goto corrupt;1846 newsize = hunk_size + byte_length;1847 data =xrealloc(data, newsize);1848if(decode_85(data + hunk_size, buffer +1, byte_length))1849goto corrupt;1850 hunk_size = newsize;1851 buffer += llen;1852 size -= llen;1853}18541855 frag =xcalloc(1,sizeof(*frag));1856 frag->patch =inflate_it(data, hunk_size, origlen);1857 frag->free_patch =1;1858if(!frag->patch)1859goto corrupt;1860free(data);1861 frag->size = origlen;1862*buf_p = buffer;1863*sz_p = size;1864*used_p = used;1865 frag->binary_patch_method = patch_method;1866return frag;18671868 corrupt:1869free(data);1870*status_p = -1;1871error(_("corrupt binary patch at line%d: %.*s"),1872 state_linenr-1, llen-1, buffer);1873return NULL;1874}18751876/*1877 * Returns:1878 * -1 in case of error,1879 * the length of the parsed binary patch otherwise1880 */1881static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1882{1883/*1884 * We have read "GIT binary patch\n"; what follows is a line1885 * that says the patch method (currently, either "literal" or1886 * "delta") and the length of data before deflating; a1887 * sequence of 'length-byte' followed by base-85 encoded data1888 * follows.1889 *1890 * When a binary patch is reversible, there is another binary1891 * hunk in the same format, starting with patch method (either1892 * "literal" or "delta") with the length of data, and a sequence1893 * of length-byte + base-85 encoded data, terminated with another1894 * empty line. This data, when applied to the postimage, produces1895 * the preimage.1896 */1897struct fragment *forward;1898struct fragment *reverse;1899int status;1900int used, used_1;19011902 forward =parse_binary_hunk(&buffer, &size, &status, &used);1903if(!forward && !status)1904/* there has to be one hunk (forward hunk) */1905returnerror(_("unrecognized binary patch at line%d"), state_linenr-1);1906if(status)1907/* otherwise we already gave an error message */1908return status;19091910 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1911if(reverse)1912 used += used_1;1913else if(status) {1914/*1915 * Not having reverse hunk is not an error, but having1916 * a corrupt reverse hunk is.1917 */1918free((void*) forward->patch);1919free(forward);1920return status;1921}1922 forward->next = reverse;1923 patch->fragments = forward;1924 patch->is_binary =1;1925return used;1926}19271928static voidprefix_one(struct apply_state *state,char**name)1929{1930char*old_name = *name;1931if(!old_name)1932return;1933*name =xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));1934free(old_name);1935}19361937static voidprefix_patch(struct apply_state *state,struct patch *p)1938{1939if(!state->prefix || p->is_toplevel_relative)1940return;1941prefix_one(state, &p->new_name);1942prefix_one(state, &p->old_name);1943}19441945/*1946 * include/exclude1947 */19481949static struct string_list limit_by_name;1950static int has_include;1951static voidadd_name_limit(const char*name,int exclude)1952{1953struct string_list_item *it;19541955 it =string_list_append(&limit_by_name, name);1956 it->util = exclude ? NULL : (void*)1;1957}19581959static intuse_patch(struct apply_state *state,struct patch *p)1960{1961const char*pathname = p->new_name ? p->new_name : p->old_name;1962int i;19631964/* Paths outside are not touched regardless of "--include" */1965if(0< state->prefix_length) {1966int pathlen =strlen(pathname);1967if(pathlen <= state->prefix_length ||1968memcmp(state->prefix, pathname, state->prefix_length))1969return0;1970}19711972/* See if it matches any of exclude/include rule */1973for(i =0; i < limit_by_name.nr; i++) {1974struct string_list_item *it = &limit_by_name.items[i];1975if(!wildmatch(it->string, pathname,0, NULL))1976return(it->util != NULL);1977}19781979/*1980 * If we had any include, a path that does not match any rule is1981 * not used. Otherwise, we saw bunch of exclude rules (or none)1982 * and such a path is used.1983 */1984return!has_include;1985}198619871988/*1989 * Read the patch text in "buffer" that extends for "size" bytes; stop1990 * reading after seeing a single patch (i.e. changes to a single file).1991 * Create fragments (i.e. patch hunks) and hang them to the given patch.1992 * Return the number of bytes consumed, so that the caller can call us1993 * again for the next patch.1994 */1995static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)1996{1997int hdrsize, patchsize;1998int offset =find_header(state, buffer, size, &hdrsize, patch);19992000if(offset <0)2001return offset;20022003prefix_patch(state, patch);20042005if(!use_patch(state, patch))2006 patch->ws_rule =0;2007else2008 patch->ws_rule =whitespace_rule(patch->new_name2009? patch->new_name2010: patch->old_name);20112012 patchsize =parse_single_patch(buffer + offset + hdrsize,2013 size - offset - hdrsize, patch);20142015if(!patchsize) {2016static const char git_binary[] ="GIT binary patch\n";2017int hd = hdrsize + offset;2018unsigned long llen =linelen(buffer + hd, size - hd);20192020if(llen ==sizeof(git_binary) -1&&2021!memcmp(git_binary, buffer + hd, llen)) {2022int used;2023 state_linenr++;2024 used =parse_binary(buffer + hd + llen,2025 size - hd - llen, patch);2026if(used <0)2027return-1;2028if(used)2029 patchsize = used + llen;2030else2031 patchsize =0;2032}2033else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2034static const char*binhdr[] = {2035"Binary files ",2036"Files ",2037 NULL,2038};2039int i;2040for(i =0; binhdr[i]; i++) {2041int len =strlen(binhdr[i]);2042if(len < size - hd &&2043!memcmp(binhdr[i], buffer + hd, len)) {2044 state_linenr++;2045 patch->is_binary =1;2046 patchsize = llen;2047break;2048}2049}2050}20512052/* Empty patch cannot be applied if it is a text patch2053 * without metadata change. A binary patch appears2054 * empty to us here.2055 */2056if((apply || state->check) &&2057(!patch->is_binary && !metadata_changes(patch)))2058die(_("patch with only garbage at line%d"), state_linenr);2059}20602061return offset + hdrsize + patchsize;2062}20632064#define swap(a,b) myswap((a),(b),sizeof(a))20652066#define myswap(a, b, size) do { \2067 unsigned char mytmp[size]; \2068 memcpy(mytmp, &a, size); \2069 memcpy(&a, &b, size); \2070 memcpy(&b, mytmp, size); \2071} while (0)20722073static voidreverse_patches(struct patch *p)2074{2075for(; p; p = p->next) {2076struct fragment *frag = p->fragments;20772078swap(p->new_name, p->old_name);2079swap(p->new_mode, p->old_mode);2080swap(p->is_new, p->is_delete);2081swap(p->lines_added, p->lines_deleted);2082swap(p->old_sha1_prefix, p->new_sha1_prefix);20832084for(; frag; frag = frag->next) {2085swap(frag->newpos, frag->oldpos);2086swap(frag->newlines, frag->oldlines);2087}2088}2089}20902091static const char pluses[] =2092"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2093static const char minuses[]=2094"----------------------------------------------------------------------";20952096static voidshow_stats(struct patch *patch)2097{2098struct strbuf qname = STRBUF_INIT;2099char*cp = patch->new_name ? patch->new_name : patch->old_name;2100int max, add, del;21012102quote_c_style(cp, &qname, NULL,0);21032104/*2105 * "scale" the filename2106 */2107 max = max_len;2108if(max >50)2109 max =50;21102111if(qname.len > max) {2112 cp =strchr(qname.buf + qname.len +3- max,'/');2113if(!cp)2114 cp = qname.buf + qname.len +3- max;2115strbuf_splice(&qname,0, cp - qname.buf,"...",3);2116}21172118if(patch->is_binary) {2119printf(" %-*s | Bin\n", max, qname.buf);2120strbuf_release(&qname);2121return;2122}21232124printf(" %-*s |", max, qname.buf);2125strbuf_release(&qname);21262127/*2128 * scale the add/delete2129 */2130 max = max + max_change >70?70- max : max_change;2131 add = patch->lines_added;2132 del = patch->lines_deleted;21332134if(max_change >0) {2135int total = ((add + del) * max + max_change /2) / max_change;2136 add = (add * max + max_change /2) / max_change;2137 del = total - add;2138}2139printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2140 add, pluses, del, minuses);2141}21422143static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2144{2145switch(st->st_mode & S_IFMT) {2146case S_IFLNK:2147if(strbuf_readlink(buf, path, st->st_size) <0)2148returnerror(_("unable to read symlink%s"), path);2149return0;2150case S_IFREG:2151if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2152returnerror(_("unable to open or read%s"), path);2153convert_to_git(path, buf->buf, buf->len, buf,0);2154return0;2155default:2156return-1;2157}2158}21592160/*2161 * Update the preimage, and the common lines in postimage,2162 * from buffer buf of length len. If postlen is 0 the postimage2163 * is updated in place, otherwise it's updated on a new buffer2164 * of length postlen2165 */21662167static voidupdate_pre_post_images(struct image *preimage,2168struct image *postimage,2169char*buf,2170size_t len,size_t postlen)2171{2172int i, ctx, reduced;2173char*new, *old, *fixed;2174struct image fixed_preimage;21752176/*2177 * Update the preimage with whitespace fixes. Note that we2178 * are not losing preimage->buf -- apply_one_fragment() will2179 * free "oldlines".2180 */2181prepare_image(&fixed_preimage, buf, len,1);2182assert(postlen2183? fixed_preimage.nr == preimage->nr2184: fixed_preimage.nr <= preimage->nr);2185for(i =0; i < fixed_preimage.nr; i++)2186 fixed_preimage.line[i].flag = preimage->line[i].flag;2187free(preimage->line_allocated);2188*preimage = fixed_preimage;21892190/*2191 * Adjust the common context lines in postimage. This can be2192 * done in-place when we are shrinking it with whitespace2193 * fixing, but needs a new buffer when ignoring whitespace or2194 * expanding leading tabs to spaces.2195 *2196 * We trust the caller to tell us if the update can be done2197 * in place (postlen==0) or not.2198 */2199 old = postimage->buf;2200if(postlen)2201new= postimage->buf =xmalloc(postlen);2202else2203new= old;2204 fixed = preimage->buf;22052206for(i = reduced = ctx =0; i < postimage->nr; i++) {2207size_t l_len = postimage->line[i].len;2208if(!(postimage->line[i].flag & LINE_COMMON)) {2209/* an added line -- no counterparts in preimage */2210memmove(new, old, l_len);2211 old += l_len;2212new+= l_len;2213continue;2214}22152216/* a common context -- skip it in the original postimage */2217 old += l_len;22182219/* and find the corresponding one in the fixed preimage */2220while(ctx < preimage->nr &&2221!(preimage->line[ctx].flag & LINE_COMMON)) {2222 fixed += preimage->line[ctx].len;2223 ctx++;2224}22252226/*2227 * preimage is expected to run out, if the caller2228 * fixed addition of trailing blank lines.2229 */2230if(preimage->nr <= ctx) {2231 reduced++;2232continue;2233}22342235/* and copy it in, while fixing the line length */2236 l_len = preimage->line[ctx].len;2237memcpy(new, fixed, l_len);2238new+= l_len;2239 fixed += l_len;2240 postimage->line[i].len = l_len;2241 ctx++;2242}22432244if(postlen2245? postlen <new- postimage->buf2246: postimage->len <new- postimage->buf)2247die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2248(int)postlen, (int) postimage->len, (int)(new- postimage->buf));22492250/* Fix the length of the whole thing */2251 postimage->len =new- postimage->buf;2252 postimage->nr -= reduced;2253}22542255static intline_by_line_fuzzy_match(struct image *img,2256struct image *preimage,2257struct image *postimage,2258unsigned longtry,2259int try_lno,2260int preimage_limit)2261{2262int i;2263size_t imgoff =0;2264size_t preoff =0;2265size_t postlen = postimage->len;2266size_t extra_chars;2267char*buf;2268char*preimage_eof;2269char*preimage_end;2270struct strbuf fixed;2271char*fixed_buf;2272size_t fixed_len;22732274for(i =0; i < preimage_limit; i++) {2275size_t prelen = preimage->line[i].len;2276size_t imglen = img->line[try_lno+i].len;22772278if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2279 preimage->buf + preoff, prelen))2280return0;2281if(preimage->line[i].flag & LINE_COMMON)2282 postlen += imglen - prelen;2283 imgoff += imglen;2284 preoff += prelen;2285}22862287/*2288 * Ok, the preimage matches with whitespace fuzz.2289 *2290 * imgoff now holds the true length of the target that2291 * matches the preimage before the end of the file.2292 *2293 * Count the number of characters in the preimage that fall2294 * beyond the end of the file and make sure that all of them2295 * are whitespace characters. (This can only happen if2296 * we are removing blank lines at the end of the file.)2297 */2298 buf = preimage_eof = preimage->buf + preoff;2299for( ; i < preimage->nr; i++)2300 preoff += preimage->line[i].len;2301 preimage_end = preimage->buf + preoff;2302for( ; buf < preimage_end; buf++)2303if(!isspace(*buf))2304return0;23052306/*2307 * Update the preimage and the common postimage context2308 * lines to use the same whitespace as the target.2309 * If whitespace is missing in the target (i.e.2310 * if the preimage extends beyond the end of the file),2311 * use the whitespace from the preimage.2312 */2313 extra_chars = preimage_end - preimage_eof;2314strbuf_init(&fixed, imgoff + extra_chars);2315strbuf_add(&fixed, img->buf +try, imgoff);2316strbuf_add(&fixed, preimage_eof, extra_chars);2317 fixed_buf =strbuf_detach(&fixed, &fixed_len);2318update_pre_post_images(preimage, postimage,2319 fixed_buf, fixed_len, postlen);2320return1;2321}23222323static intmatch_fragment(struct image *img,2324struct image *preimage,2325struct image *postimage,2326unsigned longtry,2327int try_lno,2328unsigned ws_rule,2329int match_beginning,int match_end)2330{2331int i;2332char*fixed_buf, *buf, *orig, *target;2333struct strbuf fixed;2334size_t fixed_len, postlen;2335int preimage_limit;23362337if(preimage->nr + try_lno <= img->nr) {2338/*2339 * The hunk falls within the boundaries of img.2340 */2341 preimage_limit = preimage->nr;2342if(match_end && (preimage->nr + try_lno != img->nr))2343return0;2344}else if(ws_error_action == correct_ws_error &&2345(ws_rule & WS_BLANK_AT_EOF)) {2346/*2347 * This hunk extends beyond the end of img, and we are2348 * removing blank lines at the end of the file. This2349 * many lines from the beginning of the preimage must2350 * match with img, and the remainder of the preimage2351 * must be blank.2352 */2353 preimage_limit = img->nr - try_lno;2354}else{2355/*2356 * The hunk extends beyond the end of the img and2357 * we are not removing blanks at the end, so we2358 * should reject the hunk at this position.2359 */2360return0;2361}23622363if(match_beginning && try_lno)2364return0;23652366/* Quick hash check */2367for(i =0; i < preimage_limit; i++)2368if((img->line[try_lno + i].flag & LINE_PATCHED) ||2369(preimage->line[i].hash != img->line[try_lno + i].hash))2370return0;23712372if(preimage_limit == preimage->nr) {2373/*2374 * Do we have an exact match? If we were told to match2375 * at the end, size must be exactly at try+fragsize,2376 * otherwise try+fragsize must be still within the preimage,2377 * and either case, the old piece should match the preimage2378 * exactly.2379 */2380if((match_end2381? (try+ preimage->len == img->len)2382: (try+ preimage->len <= img->len)) &&2383!memcmp(img->buf +try, preimage->buf, preimage->len))2384return1;2385}else{2386/*2387 * The preimage extends beyond the end of img, so2388 * there cannot be an exact match.2389 *2390 * There must be one non-blank context line that match2391 * a line before the end of img.2392 */2393char*buf_end;23942395 buf = preimage->buf;2396 buf_end = buf;2397for(i =0; i < preimage_limit; i++)2398 buf_end += preimage->line[i].len;23992400for( ; buf < buf_end; buf++)2401if(!isspace(*buf))2402break;2403if(buf == buf_end)2404return0;2405}24062407/*2408 * No exact match. If we are ignoring whitespace, run a line-by-line2409 * fuzzy matching. We collect all the line length information because2410 * we need it to adjust whitespace if we match.2411 */2412if(ws_ignore_action == ignore_ws_change)2413returnline_by_line_fuzzy_match(img, preimage, postimage,2414try, try_lno, preimage_limit);24152416if(ws_error_action != correct_ws_error)2417return0;24182419/*2420 * The hunk does not apply byte-by-byte, but the hash says2421 * it might with whitespace fuzz. We weren't asked to2422 * ignore whitespace, we were asked to correct whitespace2423 * errors, so let's try matching after whitespace correction.2424 *2425 * While checking the preimage against the target, whitespace2426 * errors in both fixed, we count how large the corresponding2427 * postimage needs to be. The postimage prepared by2428 * apply_one_fragment() has whitespace errors fixed on added2429 * lines already, but the common lines were propagated as-is,2430 * which may become longer when their whitespace errors are2431 * fixed.2432 */24332434/* First count added lines in postimage */2435 postlen =0;2436for(i =0; i < postimage->nr; i++) {2437if(!(postimage->line[i].flag & LINE_COMMON))2438 postlen += postimage->line[i].len;2439}24402441/*2442 * The preimage may extend beyond the end of the file,2443 * but in this loop we will only handle the part of the2444 * preimage that falls within the file.2445 */2446strbuf_init(&fixed, preimage->len +1);2447 orig = preimage->buf;2448 target = img->buf +try;2449for(i =0; i < preimage_limit; i++) {2450size_t oldlen = preimage->line[i].len;2451size_t tgtlen = img->line[try_lno + i].len;2452size_t fixstart = fixed.len;2453struct strbuf tgtfix;2454int match;24552456/* Try fixing the line in the preimage */2457ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24582459/* Try fixing the line in the target */2460strbuf_init(&tgtfix, tgtlen);2461ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);24622463/*2464 * If they match, either the preimage was based on2465 * a version before our tree fixed whitespace breakage,2466 * or we are lacking a whitespace-fix patch the tree2467 * the preimage was based on already had (i.e. target2468 * has whitespace breakage, the preimage doesn't).2469 * In either case, we are fixing the whitespace breakages2470 * so we might as well take the fix together with their2471 * real change.2472 */2473 match = (tgtfix.len == fixed.len - fixstart &&2474!memcmp(tgtfix.buf, fixed.buf + fixstart,2475 fixed.len - fixstart));24762477/* Add the length if this is common with the postimage */2478if(preimage->line[i].flag & LINE_COMMON)2479 postlen += tgtfix.len;24802481strbuf_release(&tgtfix);2482if(!match)2483goto unmatch_exit;24842485 orig += oldlen;2486 target += tgtlen;2487}248824892490/*2491 * Now handle the lines in the preimage that falls beyond the2492 * end of the file (if any). They will only match if they are2493 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2494 * false).2495 */2496for( ; i < preimage->nr; i++) {2497size_t fixstart = fixed.len;/* start of the fixed preimage */2498size_t oldlen = preimage->line[i].len;2499int j;25002501/* Try fixing the line in the preimage */2502ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25032504for(j = fixstart; j < fixed.len; j++)2505if(!isspace(fixed.buf[j]))2506goto unmatch_exit;25072508 orig += oldlen;2509}25102511/*2512 * Yes, the preimage is based on an older version that still2513 * has whitespace breakages unfixed, and fixing them makes the2514 * hunk match. Update the context lines in the postimage.2515 */2516 fixed_buf =strbuf_detach(&fixed, &fixed_len);2517if(postlen < postimage->len)2518 postlen =0;2519update_pre_post_images(preimage, postimage,2520 fixed_buf, fixed_len, postlen);2521return1;25222523 unmatch_exit:2524strbuf_release(&fixed);2525return0;2526}25272528static intfind_pos(struct image *img,2529struct image *preimage,2530struct image *postimage,2531int line,2532unsigned ws_rule,2533int match_beginning,int match_end)2534{2535int i;2536unsigned long backwards, forwards,try;2537int backwards_lno, forwards_lno, try_lno;25382539/*2540 * If match_beginning or match_end is specified, there is no2541 * point starting from a wrong line that will never match and2542 * wander around and wait for a match at the specified end.2543 */2544if(match_beginning)2545 line =0;2546else if(match_end)2547 line = img->nr - preimage->nr;25482549/*2550 * Because the comparison is unsigned, the following test2551 * will also take care of a negative line number that can2552 * result when match_end and preimage is larger than the target.2553 */2554if((size_t) line > img->nr)2555 line = img->nr;25562557try=0;2558for(i =0; i < line; i++)2559try+= img->line[i].len;25602561/*2562 * There's probably some smart way to do this, but I'll leave2563 * that to the smart and beautiful people. I'm simple and stupid.2564 */2565 backwards =try;2566 backwards_lno = line;2567 forwards =try;2568 forwards_lno = line;2569 try_lno = line;25702571for(i =0; ; i++) {2572if(match_fragment(img, preimage, postimage,2573try, try_lno, ws_rule,2574 match_beginning, match_end))2575return try_lno;25762577 again:2578if(backwards_lno ==0&& forwards_lno == img->nr)2579break;25802581if(i &1) {2582if(backwards_lno ==0) {2583 i++;2584goto again;2585}2586 backwards_lno--;2587 backwards -= img->line[backwards_lno].len;2588try= backwards;2589 try_lno = backwards_lno;2590}else{2591if(forwards_lno == img->nr) {2592 i++;2593goto again;2594}2595 forwards += img->line[forwards_lno].len;2596 forwards_lno++;2597try= forwards;2598 try_lno = forwards_lno;2599}26002601}2602return-1;2603}26042605static voidremove_first_line(struct image *img)2606{2607 img->buf += img->line[0].len;2608 img->len -= img->line[0].len;2609 img->line++;2610 img->nr--;2611}26122613static voidremove_last_line(struct image *img)2614{2615 img->len -= img->line[--img->nr].len;2616}26172618/*2619 * The change from "preimage" and "postimage" has been found to2620 * apply at applied_pos (counts in line numbers) in "img".2621 * Update "img" to remove "preimage" and replace it with "postimage".2622 */2623static voidupdate_image(struct image *img,2624int applied_pos,2625struct image *preimage,2626struct image *postimage)2627{2628/*2629 * remove the copy of preimage at offset in img2630 * and replace it with postimage2631 */2632int i, nr;2633size_t remove_count, insert_count, applied_at =0;2634char*result;2635int preimage_limit;26362637/*2638 * If we are removing blank lines at the end of img,2639 * the preimage may extend beyond the end.2640 * If that is the case, we must be careful only to2641 * remove the part of the preimage that falls within2642 * the boundaries of img. Initialize preimage_limit2643 * to the number of lines in the preimage that falls2644 * within the boundaries.2645 */2646 preimage_limit = preimage->nr;2647if(preimage_limit > img->nr - applied_pos)2648 preimage_limit = img->nr - applied_pos;26492650for(i =0; i < applied_pos; i++)2651 applied_at += img->line[i].len;26522653 remove_count =0;2654for(i =0; i < preimage_limit; i++)2655 remove_count += img->line[applied_pos + i].len;2656 insert_count = postimage->len;26572658/* Adjust the contents */2659 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2660memcpy(result, img->buf, applied_at);2661memcpy(result + applied_at, postimage->buf, postimage->len);2662memcpy(result + applied_at + postimage->len,2663 img->buf + (applied_at + remove_count),2664 img->len - (applied_at + remove_count));2665free(img->buf);2666 img->buf = result;2667 img->len += insert_count - remove_count;2668 result[img->len] ='\0';26692670/* Adjust the line table */2671 nr = img->nr + postimage->nr - preimage_limit;2672if(preimage_limit < postimage->nr) {2673/*2674 * NOTE: this knows that we never call remove_first_line()2675 * on anything other than pre/post image.2676 */2677REALLOC_ARRAY(img->line, nr);2678 img->line_allocated = img->line;2679}2680if(preimage_limit != postimage->nr)2681memmove(img->line + applied_pos + postimage->nr,2682 img->line + applied_pos + preimage_limit,2683(img->nr - (applied_pos + preimage_limit)) *2684sizeof(*img->line));2685memcpy(img->line + applied_pos,2686 postimage->line,2687 postimage->nr *sizeof(*img->line));2688if(!allow_overlap)2689for(i =0; i < postimage->nr; i++)2690 img->line[applied_pos + i].flag |= LINE_PATCHED;2691 img->nr = nr;2692}26932694/*2695 * Use the patch-hunk text in "frag" to prepare two images (preimage and2696 * postimage) for the hunk. Find lines that match "preimage" in "img" and2697 * replace the part of "img" with "postimage" text.2698 */2699static intapply_one_fragment(struct apply_state *state,2700struct image *img,struct fragment *frag,2701int inaccurate_eof,unsigned ws_rule,2702int nth_fragment)2703{2704int match_beginning, match_end;2705const char*patch = frag->patch;2706int size = frag->size;2707char*old, *oldlines;2708struct strbuf newlines;2709int new_blank_lines_at_end =0;2710int found_new_blank_lines_at_end =0;2711int hunk_linenr = frag->linenr;2712unsigned long leading, trailing;2713int pos, applied_pos;2714struct image preimage;2715struct image postimage;27162717memset(&preimage,0,sizeof(preimage));2718memset(&postimage,0,sizeof(postimage));2719 oldlines =xmalloc(size);2720strbuf_init(&newlines, size);27212722 old = oldlines;2723while(size >0) {2724char first;2725int len =linelen(patch, size);2726int plen;2727int added_blank_line =0;2728int is_blank_context =0;2729size_t start;27302731if(!len)2732break;27332734/*2735 * "plen" is how much of the line we should use for2736 * the actual patch data. Normally we just remove the2737 * first character on the line, but if the line is2738 * followed by "\ No newline", then we also remove the2739 * last one (which is the newline, of course).2740 */2741 plen = len -1;2742if(len < size && patch[len] =='\\')2743 plen--;2744 first = *patch;2745if(apply_in_reverse) {2746if(first =='-')2747 first ='+';2748else if(first =='+')2749 first ='-';2750}27512752switch(first) {2753case'\n':2754/* Newer GNU diff, empty context line */2755if(plen <0)2756/* ... followed by '\No newline'; nothing */2757break;2758*old++ ='\n';2759strbuf_addch(&newlines,'\n');2760add_line_info(&preimage,"\n",1, LINE_COMMON);2761add_line_info(&postimage,"\n",1, LINE_COMMON);2762 is_blank_context =1;2763break;2764case' ':2765if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2766ws_blank_line(patch +1, plen, ws_rule))2767 is_blank_context =1;2768case'-':2769memcpy(old, patch +1, plen);2770add_line_info(&preimage, old, plen,2771(first ==' '? LINE_COMMON :0));2772 old += plen;2773if(first =='-')2774break;2775/* Fall-through for ' ' */2776case'+':2777/* --no-add does not add new lines */2778if(first =='+'&& no_add)2779break;27802781 start = newlines.len;2782if(first !='+'||2783!whitespace_error ||2784 ws_error_action != correct_ws_error) {2785strbuf_add(&newlines, patch +1, plen);2786}2787else{2788ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2789}2790add_line_info(&postimage, newlines.buf + start, newlines.len - start,2791(first =='+'?0: LINE_COMMON));2792if(first =='+'&&2793(ws_rule & WS_BLANK_AT_EOF) &&2794ws_blank_line(patch +1, plen, ws_rule))2795 added_blank_line =1;2796break;2797case'@':case'\\':2798/* Ignore it, we already handled it */2799break;2800default:2801if(apply_verbosely)2802error(_("invalid start of line: '%c'"), first);2803 applied_pos = -1;2804goto out;2805}2806if(added_blank_line) {2807if(!new_blank_lines_at_end)2808 found_new_blank_lines_at_end = hunk_linenr;2809 new_blank_lines_at_end++;2810}2811else if(is_blank_context)2812;2813else2814 new_blank_lines_at_end =0;2815 patch += len;2816 size -= len;2817 hunk_linenr++;2818}2819if(inaccurate_eof &&2820 old > oldlines && old[-1] =='\n'&&2821 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2822 old--;2823strbuf_setlen(&newlines, newlines.len -1);2824}28252826 leading = frag->leading;2827 trailing = frag->trailing;28282829/*2830 * A hunk to change lines at the beginning would begin with2831 * @@ -1,L +N,M @@2832 * but we need to be careful. -U0 that inserts before the second2833 * line also has this pattern.2834 *2835 * And a hunk to add to an empty file would begin with2836 * @@ -0,0 +N,M @@2837 *2838 * In other words, a hunk that is (frag->oldpos <= 1) with or2839 * without leading context must match at the beginning.2840 */2841 match_beginning = (!frag->oldpos ||2842(frag->oldpos ==1&& !state->unidiff_zero));28432844/*2845 * A hunk without trailing lines must match at the end.2846 * However, we simply cannot tell if a hunk must match end2847 * from the lack of trailing lines if the patch was generated2848 * with unidiff without any context.2849 */2850 match_end = !state->unidiff_zero && !trailing;28512852 pos = frag->newpos ? (frag->newpos -1) :0;2853 preimage.buf = oldlines;2854 preimage.len = old - oldlines;2855 postimage.buf = newlines.buf;2856 postimage.len = newlines.len;2857 preimage.line = preimage.line_allocated;2858 postimage.line = postimage.line_allocated;28592860for(;;) {28612862 applied_pos =find_pos(img, &preimage, &postimage, pos,2863 ws_rule, match_beginning, match_end);28642865if(applied_pos >=0)2866break;28672868/* Am I at my context limits? */2869if((leading <= p_context) && (trailing <= p_context))2870break;2871if(match_beginning || match_end) {2872 match_beginning = match_end =0;2873continue;2874}28752876/*2877 * Reduce the number of context lines; reduce both2878 * leading and trailing if they are equal otherwise2879 * just reduce the larger context.2880 */2881if(leading >= trailing) {2882remove_first_line(&preimage);2883remove_first_line(&postimage);2884 pos--;2885 leading--;2886}2887if(trailing > leading) {2888remove_last_line(&preimage);2889remove_last_line(&postimage);2890 trailing--;2891}2892}28932894if(applied_pos >=0) {2895if(new_blank_lines_at_end &&2896 preimage.nr + applied_pos >= img->nr &&2897(ws_rule & WS_BLANK_AT_EOF) &&2898 ws_error_action != nowarn_ws_error) {2899record_ws_error(WS_BLANK_AT_EOF,"+",1,2900 found_new_blank_lines_at_end);2901if(ws_error_action == correct_ws_error) {2902while(new_blank_lines_at_end--)2903remove_last_line(&postimage);2904}2905/*2906 * We would want to prevent write_out_results()2907 * from taking place in apply_patch() that follows2908 * the callchain led us here, which is:2909 * apply_patch->check_patch_list->check_patch->2910 * apply_data->apply_fragments->apply_one_fragment2911 */2912if(ws_error_action == die_on_ws_error)2913 apply =0;2914}29152916if(apply_verbosely && applied_pos != pos) {2917int offset = applied_pos - pos;2918if(apply_in_reverse)2919 offset =0- offset;2920fprintf_ln(stderr,2921Q_("Hunk #%dsucceeded at%d(offset%dline).",2922"Hunk #%dsucceeded at%d(offset%dlines).",2923 offset),2924 nth_fragment, applied_pos +1, offset);2925}29262927/*2928 * Warn if it was necessary to reduce the number2929 * of context lines.2930 */2931if((leading != frag->leading) ||2932(trailing != frag->trailing))2933fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2934" to apply fragment at%d"),2935 leading, trailing, applied_pos+1);2936update_image(img, applied_pos, &preimage, &postimage);2937}else{2938if(apply_verbosely)2939error(_("while searching for:\n%.*s"),2940(int)(old - oldlines), oldlines);2941}29422943out:2944free(oldlines);2945strbuf_release(&newlines);2946free(preimage.line_allocated);2947free(postimage.line_allocated);29482949return(applied_pos <0);2950}29512952static intapply_binary_fragment(struct image *img,struct patch *patch)2953{2954struct fragment *fragment = patch->fragments;2955unsigned long len;2956void*dst;29572958if(!fragment)2959returnerror(_("missing binary patch data for '%s'"),2960 patch->new_name ?2961 patch->new_name :2962 patch->old_name);29632964/* Binary patch is irreversible without the optional second hunk */2965if(apply_in_reverse) {2966if(!fragment->next)2967returnerror("cannot reverse-apply a binary patch "2968"without the reverse hunk to '%s'",2969 patch->new_name2970? patch->new_name : patch->old_name);2971 fragment = fragment->next;2972}2973switch(fragment->binary_patch_method) {2974case BINARY_DELTA_DEFLATED:2975 dst =patch_delta(img->buf, img->len, fragment->patch,2976 fragment->size, &len);2977if(!dst)2978return-1;2979clear_image(img);2980 img->buf = dst;2981 img->len = len;2982return0;2983case BINARY_LITERAL_DEFLATED:2984clear_image(img);2985 img->len = fragment->size;2986 img->buf =xmemdupz(fragment->patch, img->len);2987return0;2988}2989return-1;2990}29912992/*2993 * Replace "img" with the result of applying the binary patch.2994 * The binary patch data itself in patch->fragment is still kept2995 * but the preimage prepared by the caller in "img" is freed here2996 * or in the helper function apply_binary_fragment() this calls.2997 */2998static intapply_binary(struct image *img,struct patch *patch)2999{3000const char*name = patch->old_name ? patch->old_name : patch->new_name;3001unsigned char sha1[20];30023003/*3004 * For safety, we require patch index line to contain3005 * full 40-byte textual SHA1 for old and new, at least for now.3006 */3007if(strlen(patch->old_sha1_prefix) !=40||3008strlen(patch->new_sha1_prefix) !=40||3009get_sha1_hex(patch->old_sha1_prefix, sha1) ||3010get_sha1_hex(patch->new_sha1_prefix, sha1))3011returnerror("cannot apply binary patch to '%s' "3012"without full index line", name);30133014if(patch->old_name) {3015/*3016 * See if the old one matches what the patch3017 * applies to.3018 */3019hash_sha1_file(img->buf, img->len, blob_type, sha1);3020if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3021returnerror("the patch applies to '%s' (%s), "3022"which does not match the "3023"current contents.",3024 name,sha1_to_hex(sha1));3025}3026else{3027/* Otherwise, the old one must be empty. */3028if(img->len)3029returnerror("the patch applies to an empty "3030"'%s' but it is not empty", name);3031}30323033get_sha1_hex(patch->new_sha1_prefix, sha1);3034if(is_null_sha1(sha1)) {3035clear_image(img);3036return0;/* deletion patch */3037}30383039if(has_sha1_file(sha1)) {3040/* We already have the postimage */3041enum object_type type;3042unsigned long size;3043char*result;30443045 result =read_sha1_file(sha1, &type, &size);3046if(!result)3047returnerror("the necessary postimage%sfor "3048"'%s' cannot be read",3049 patch->new_sha1_prefix, name);3050clear_image(img);3051 img->buf = result;3052 img->len = size;3053}else{3054/*3055 * We have verified buf matches the preimage;3056 * apply the patch data to it, which is stored3057 * in the patch->fragments->{patch,size}.3058 */3059if(apply_binary_fragment(img, patch))3060returnerror(_("binary patch does not apply to '%s'"),3061 name);30623063/* verify that the result matches */3064hash_sha1_file(img->buf, img->len, blob_type, sha1);3065if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3066returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3067 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3068}30693070return0;3071}30723073static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3074{3075struct fragment *frag = patch->fragments;3076const char*name = patch->old_name ? patch->old_name : patch->new_name;3077unsigned ws_rule = patch->ws_rule;3078unsigned inaccurate_eof = patch->inaccurate_eof;3079int nth =0;30803081if(patch->is_binary)3082returnapply_binary(img, patch);30833084while(frag) {3085 nth++;3086if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3087error(_("patch failed:%s:%ld"), name, frag->oldpos);3088if(!apply_with_reject)3089return-1;3090 frag->rejected =1;3091}3092 frag = frag->next;3093}3094return0;3095}30963097static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3098{3099if(S_ISGITLINK(mode)) {3100strbuf_grow(buf,100);3101strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3102}else{3103enum object_type type;3104unsigned long sz;3105char*result;31063107 result =read_sha1_file(sha1, &type, &sz);3108if(!result)3109return-1;3110/* XXX read_sha1_file NUL-terminates */3111strbuf_attach(buf, result, sz, sz +1);3112}3113return0;3114}31153116static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3117{3118if(!ce)3119return0;3120returnread_blob_object(buf, ce->sha1, ce->ce_mode);3121}31223123static struct patch *in_fn_table(const char*name)3124{3125struct string_list_item *item;31263127if(name == NULL)3128return NULL;31293130 item =string_list_lookup(&fn_table, name);3131if(item != NULL)3132return(struct patch *)item->util;31333134return NULL;3135}31363137/*3138 * item->util in the filename table records the status of the path.3139 * Usually it points at a patch (whose result records the contents3140 * of it after applying it), but it could be PATH_WAS_DELETED for a3141 * path that a previously applied patch has already removed, or3142 * PATH_TO_BE_DELETED for a path that a later patch would remove.3143 *3144 * The latter is needed to deal with a case where two paths A and B3145 * are swapped by first renaming A to B and then renaming B to A;3146 * moving A to B should not be prevented due to presence of B as we3147 * will remove it in a later patch.3148 */3149#define PATH_TO_BE_DELETED ((struct patch *) -2)3150#define PATH_WAS_DELETED ((struct patch *) -1)31513152static intto_be_deleted(struct patch *patch)3153{3154return patch == PATH_TO_BE_DELETED;3155}31563157static intwas_deleted(struct patch *patch)3158{3159return patch == PATH_WAS_DELETED;3160}31613162static voidadd_to_fn_table(struct patch *patch)3163{3164struct string_list_item *item;31653166/*3167 * Always add new_name unless patch is a deletion3168 * This should cover the cases for normal diffs,3169 * file creations and copies3170 */3171if(patch->new_name != NULL) {3172 item =string_list_insert(&fn_table, patch->new_name);3173 item->util = patch;3174}31753176/*3177 * store a failure on rename/deletion cases because3178 * later chunks shouldn't patch old names3179 */3180if((patch->new_name == NULL) || (patch->is_rename)) {3181 item =string_list_insert(&fn_table, patch->old_name);3182 item->util = PATH_WAS_DELETED;3183}3184}31853186static voidprepare_fn_table(struct patch *patch)3187{3188/*3189 * store information about incoming file deletion3190 */3191while(patch) {3192if((patch->new_name == NULL) || (patch->is_rename)) {3193struct string_list_item *item;3194 item =string_list_insert(&fn_table, patch->old_name);3195 item->util = PATH_TO_BE_DELETED;3196}3197 patch = patch->next;3198}3199}32003201static intcheckout_target(struct index_state *istate,3202struct cache_entry *ce,struct stat *st)3203{3204struct checkout costate;32053206memset(&costate,0,sizeof(costate));3207 costate.base_dir ="";3208 costate.refresh_cache =1;3209 costate.istate = istate;3210if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3211returnerror(_("cannot checkout%s"), ce->name);3212return0;3213}32143215static struct patch *previous_patch(struct patch *patch,int*gone)3216{3217struct patch *previous;32183219*gone =0;3220if(patch->is_copy || patch->is_rename)3221return NULL;/* "git" patches do not depend on the order */32223223 previous =in_fn_table(patch->old_name);3224if(!previous)3225return NULL;32263227if(to_be_deleted(previous))3228return NULL;/* the deletion hasn't happened yet */32293230if(was_deleted(previous))3231*gone =1;32323233return previous;3234}32353236static intverify_index_match(const struct cache_entry *ce,struct stat *st)3237{3238if(S_ISGITLINK(ce->ce_mode)) {3239if(!S_ISDIR(st->st_mode))3240return-1;3241return0;3242}3243returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3244}32453246#define SUBMODULE_PATCH_WITHOUT_INDEX 132473248static intload_patch_target(struct strbuf *buf,3249const struct cache_entry *ce,3250struct stat *st,3251const char*name,3252unsigned expected_mode)3253{3254if(cached || check_index) {3255if(read_file_or_gitlink(ce, buf))3256returnerror(_("read of%sfailed"), name);3257}else if(name) {3258if(S_ISGITLINK(expected_mode)) {3259if(ce)3260returnread_file_or_gitlink(ce, buf);3261else3262return SUBMODULE_PATCH_WITHOUT_INDEX;3263}else if(has_symlink_leading_path(name,strlen(name))) {3264returnerror(_("reading from '%s' beyond a symbolic link"), name);3265}else{3266if(read_old_data(st, name, buf))3267returnerror(_("read of%sfailed"), name);3268}3269}3270return0;3271}32723273/*3274 * We are about to apply "patch"; populate the "image" with the3275 * current version we have, from the working tree or from the index,3276 * depending on the situation e.g. --cached/--index. If we are3277 * applying a non-git patch that incrementally updates the tree,3278 * we read from the result of a previous diff.3279 */3280static intload_preimage(struct image *image,3281struct patch *patch,struct stat *st,3282const struct cache_entry *ce)3283{3284struct strbuf buf = STRBUF_INIT;3285size_t len;3286char*img;3287struct patch *previous;3288int status;32893290 previous =previous_patch(patch, &status);3291if(status)3292returnerror(_("path%shas been renamed/deleted"),3293 patch->old_name);3294if(previous) {3295/* We have a patched copy in memory; use that. */3296strbuf_add(&buf, previous->result, previous->resultsize);3297}else{3298 status =load_patch_target(&buf, ce, st,3299 patch->old_name, patch->old_mode);3300if(status <0)3301return status;3302else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3303/*3304 * There is no way to apply subproject3305 * patch without looking at the index.3306 * NEEDSWORK: shouldn't this be flagged3307 * as an error???3308 */3309free_fragment_list(patch->fragments);3310 patch->fragments = NULL;3311}else if(status) {3312returnerror(_("read of%sfailed"), patch->old_name);3313}3314}33153316 img =strbuf_detach(&buf, &len);3317prepare_image(image, img, len, !patch->is_binary);3318return0;3319}33203321static intthree_way_merge(struct image *image,3322char*path,3323const unsigned char*base,3324const unsigned char*ours,3325const unsigned char*theirs)3326{3327 mmfile_t base_file, our_file, their_file;3328 mmbuffer_t result = { NULL };3329int status;33303331read_mmblob(&base_file, base);3332read_mmblob(&our_file, ours);3333read_mmblob(&their_file, theirs);3334 status =ll_merge(&result, path,3335&base_file,"base",3336&our_file,"ours",3337&their_file,"theirs", NULL);3338free(base_file.ptr);3339free(our_file.ptr);3340free(their_file.ptr);3341if(status <0|| !result.ptr) {3342free(result.ptr);3343return-1;3344}3345clear_image(image);3346 image->buf = result.ptr;3347 image->len = result.size;33483349return status;3350}33513352/*3353 * When directly falling back to add/add three-way merge, we read from3354 * the current contents of the new_name. In no cases other than that3355 * this function will be called.3356 */3357static intload_current(struct image *image,struct patch *patch)3358{3359struct strbuf buf = STRBUF_INIT;3360int status, pos;3361size_t len;3362char*img;3363struct stat st;3364struct cache_entry *ce;3365char*name = patch->new_name;3366unsigned mode = patch->new_mode;33673368if(!patch->is_new)3369die("BUG: patch to%sis not a creation", patch->old_name);33703371 pos =cache_name_pos(name,strlen(name));3372if(pos <0)3373returnerror(_("%s: does not exist in index"), name);3374 ce = active_cache[pos];3375if(lstat(name, &st)) {3376if(errno != ENOENT)3377returnerror(_("%s:%s"), name,strerror(errno));3378if(checkout_target(&the_index, ce, &st))3379return-1;3380}3381if(verify_index_match(ce, &st))3382returnerror(_("%s: does not match index"), name);33833384 status =load_patch_target(&buf, ce, &st, name, mode);3385if(status <0)3386return status;3387else if(status)3388return-1;3389 img =strbuf_detach(&buf, &len);3390prepare_image(image, img, len, !patch->is_binary);3391return0;3392}33933394static inttry_threeway(struct apply_state *state,3395struct image *image,3396struct patch *patch,3397struct stat *st,3398const struct cache_entry *ce)3399{3400unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3401struct strbuf buf = STRBUF_INIT;3402size_t len;3403int status;3404char*img;3405struct image tmp_image;34063407/* No point falling back to 3-way merge in these cases */3408if(patch->is_delete ||3409S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3410return-1;34113412/* Preimage the patch was prepared for */3413if(patch->is_new)3414write_sha1_file("",0, blob_type, pre_sha1);3415else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3416read_blob_object(&buf, pre_sha1, patch->old_mode))3417returnerror("repository lacks the necessary blob to fall back on 3-way merge.");34183419fprintf(stderr,"Falling back to three-way merge...\n");34203421 img =strbuf_detach(&buf, &len);3422prepare_image(&tmp_image, img, len,1);3423/* Apply the patch to get the post image */3424if(apply_fragments(state, &tmp_image, patch) <0) {3425clear_image(&tmp_image);3426return-1;3427}3428/* post_sha1[] is theirs */3429write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3430clear_image(&tmp_image);34313432/* our_sha1[] is ours */3433if(patch->is_new) {3434if(load_current(&tmp_image, patch))3435returnerror("cannot read the current contents of '%s'",3436 patch->new_name);3437}else{3438if(load_preimage(&tmp_image, patch, st, ce))3439returnerror("cannot read the current contents of '%s'",3440 patch->old_name);3441}3442write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3443clear_image(&tmp_image);34443445/* in-core three-way merge between post and our using pre as base */3446 status =three_way_merge(image, patch->new_name,3447 pre_sha1, our_sha1, post_sha1);3448if(status <0) {3449fprintf(stderr,"Failed to fall back on three-way merge...\n");3450return status;3451}34523453if(status) {3454 patch->conflicted_threeway =1;3455if(patch->is_new)3456oidclr(&patch->threeway_stage[0]);3457else3458hashcpy(patch->threeway_stage[0].hash, pre_sha1);3459hashcpy(patch->threeway_stage[1].hash, our_sha1);3460hashcpy(patch->threeway_stage[2].hash, post_sha1);3461fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3462}else{3463fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3464}3465return0;3466}34673468static intapply_data(struct apply_state *state,struct patch *patch,3469struct stat *st,const struct cache_entry *ce)3470{3471struct image image;34723473if(load_preimage(&image, patch, st, ce) <0)3474return-1;34753476if(patch->direct_to_threeway ||3477apply_fragments(state, &image, patch) <0) {3478/* Note: with --reject, apply_fragments() returns 0 */3479if(!threeway ||try_threeway(state, &image, patch, st, ce) <0)3480return-1;3481}3482 patch->result = image.buf;3483 patch->resultsize = image.len;3484add_to_fn_table(patch);3485free(image.line_allocated);34863487if(0< patch->is_delete && patch->resultsize)3488returnerror(_("removal patch leaves file contents"));34893490return0;3491}34923493/*3494 * If "patch" that we are looking at modifies or deletes what we have,3495 * we would want it not to lose any local modification we have, either3496 * in the working tree or in the index.3497 *3498 * This also decides if a non-git patch is a creation patch or a3499 * modification to an existing empty file. We do not check the state3500 * of the current tree for a creation patch in this function; the caller3501 * check_patch() separately makes sure (and errors out otherwise) that3502 * the path the patch creates does not exist in the current tree.3503 */3504static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)3505{3506const char*old_name = patch->old_name;3507struct patch *previous = NULL;3508int stat_ret =0, status;3509unsigned st_mode =0;35103511if(!old_name)3512return0;35133514assert(patch->is_new <=0);3515 previous =previous_patch(patch, &status);35163517if(status)3518returnerror(_("path%shas been renamed/deleted"), old_name);3519if(previous) {3520 st_mode = previous->new_mode;3521}else if(!cached) {3522 stat_ret =lstat(old_name, st);3523if(stat_ret && errno != ENOENT)3524returnerror(_("%s:%s"), old_name,strerror(errno));3525}35263527if(check_index && !previous) {3528int pos =cache_name_pos(old_name,strlen(old_name));3529if(pos <0) {3530if(patch->is_new <0)3531goto is_new;3532returnerror(_("%s: does not exist in index"), old_name);3533}3534*ce = active_cache[pos];3535if(stat_ret <0) {3536if(checkout_target(&the_index, *ce, st))3537return-1;3538}3539if(!cached &&verify_index_match(*ce, st))3540returnerror(_("%s: does not match index"), old_name);3541if(cached)3542 st_mode = (*ce)->ce_mode;3543}else if(stat_ret <0) {3544if(patch->is_new <0)3545goto is_new;3546returnerror(_("%s:%s"), old_name,strerror(errno));3547}35483549if(!cached && !previous)3550 st_mode =ce_mode_from_stat(*ce, st->st_mode);35513552if(patch->is_new <0)3553 patch->is_new =0;3554if(!patch->old_mode)3555 patch->old_mode = st_mode;3556if((st_mode ^ patch->old_mode) & S_IFMT)3557returnerror(_("%s: wrong type"), old_name);3558if(st_mode != patch->old_mode)3559warning(_("%shas type%o, expected%o"),3560 old_name, st_mode, patch->old_mode);3561if(!patch->new_mode && !patch->is_delete)3562 patch->new_mode = st_mode;3563return0;35643565 is_new:3566 patch->is_new =1;3567 patch->is_delete =0;3568free(patch->old_name);3569 patch->old_name = NULL;3570return0;3571}357235733574#define EXISTS_IN_INDEX 13575#define EXISTS_IN_WORKTREE 235763577static intcheck_to_create(const char*new_name,int ok_if_exists)3578{3579struct stat nst;35803581if(check_index &&3582cache_name_pos(new_name,strlen(new_name)) >=0&&3583!ok_if_exists)3584return EXISTS_IN_INDEX;3585if(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}36073608/*3609 * We need to keep track of how symlinks in the preimage are3610 * manipulated by the patches. A patch to add a/b/c where a/b3611 * is a symlink should not be allowed to affect the directory3612 * the symlink points at, but if the same patch removes a/b,3613 * it is perfectly fine, as the patch removes a/b to make room3614 * to create a directory a/b so that a/b/c can be created.3615 */3616static struct string_list symlink_changes;3617#define SYMLINK_GOES_AWAY 013618#define SYMLINK_IN_RESULT 0236193620static uintptr_tregister_symlink_changes(const char*path,uintptr_t what)3621{3622struct string_list_item *ent;36233624 ent =string_list_lookup(&symlink_changes, path);3625if(!ent) {3626 ent =string_list_insert(&symlink_changes, path);3627 ent->util = (void*)0;3628}3629 ent->util = (void*)(what | ((uintptr_t)ent->util));3630return(uintptr_t)ent->util;3631}36323633static uintptr_tcheck_symlink_changes(const char*path)3634{3635struct string_list_item *ent;36363637 ent =string_list_lookup(&symlink_changes, path);3638if(!ent)3639return0;3640return(uintptr_t)ent->util;3641}36423643static voidprepare_symlink_changes(struct patch *patch)3644{3645for( ; patch; patch = patch->next) {3646if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3647(patch->is_rename || patch->is_delete))3648/* the symlink at patch->old_name is removed */3649register_symlink_changes(patch->old_name, SYMLINK_GOES_AWAY);36503651if(patch->new_name &&S_ISLNK(patch->new_mode))3652/* the symlink at patch->new_name is created or remains */3653register_symlink_changes(patch->new_name, SYMLINK_IN_RESULT);3654}3655}36563657static intpath_is_beyond_symlink_1(struct strbuf *name)3658{3659do{3660unsigned int change;36613662while(--name->len && name->buf[name->len] !='/')3663;/* scan backwards */3664if(!name->len)3665break;3666 name->buf[name->len] ='\0';3667 change =check_symlink_changes(name->buf);3668if(change & SYMLINK_IN_RESULT)3669return1;3670if(change & SYMLINK_GOES_AWAY)3671/*3672 * This cannot be "return 0", because we may3673 * see a new one created at a higher level.3674 */3675continue;36763677/* otherwise, check the preimage */3678if(check_index) {3679struct cache_entry *ce;36803681 ce =cache_file_exists(name->buf, name->len, ignore_case);3682if(ce &&S_ISLNK(ce->ce_mode))3683return1;3684}else{3685struct stat st;3686if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3687return1;3688}3689}while(1);3690return0;3691}36923693static intpath_is_beyond_symlink(const char*name_)3694{3695int ret;3696struct strbuf name = STRBUF_INIT;36973698assert(*name_ !='\0');3699strbuf_addstr(&name, name_);3700 ret =path_is_beyond_symlink_1(&name);3701strbuf_release(&name);37023703return ret;3704}37053706static voiddie_on_unsafe_path(struct patch *patch)3707{3708const char*old_name = NULL;3709const char*new_name = NULL;3710if(patch->is_delete)3711 old_name = patch->old_name;3712else if(!patch->is_new && !patch->is_copy)3713 old_name = patch->old_name;3714if(!patch->is_delete)3715 new_name = patch->new_name;37163717if(old_name && !verify_path(old_name))3718die(_("invalid path '%s'"), old_name);3719if(new_name && !verify_path(new_name))3720die(_("invalid path '%s'"), new_name);3721}37223723/*3724 * Check and apply the patch in-core; leave the result in patch->result3725 * for the caller to write it out to the final destination.3726 */3727static intcheck_patch(struct apply_state *state,struct patch *patch)3728{3729struct stat st;3730const char*old_name = patch->old_name;3731const char*new_name = patch->new_name;3732const char*name = old_name ? old_name : new_name;3733struct cache_entry *ce = NULL;3734struct patch *tpatch;3735int ok_if_exists;3736int status;37373738 patch->rejected =1;/* we will drop this after we succeed */37393740 status =check_preimage(patch, &ce, &st);3741if(status)3742return status;3743 old_name = patch->old_name;37443745/*3746 * A type-change diff is always split into a patch to delete3747 * old, immediately followed by a patch to create new (see3748 * diff.c::run_diff()); in such a case it is Ok that the entry3749 * to be deleted by the previous patch is still in the working3750 * tree and in the index.3751 *3752 * A patch to swap-rename between A and B would first rename A3753 * to B and then rename B to A. While applying the first one,3754 * the presence of B should not stop A from getting renamed to3755 * B; ask to_be_deleted() about the later rename. Removal of3756 * B and rename from A to B is handled the same way by asking3757 * was_deleted().3758 */3759if((tpatch =in_fn_table(new_name)) &&3760(was_deleted(tpatch) ||to_be_deleted(tpatch)))3761 ok_if_exists =1;3762else3763 ok_if_exists =0;37643765if(new_name &&3766((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3767int err =check_to_create(new_name, ok_if_exists);37683769if(err && threeway) {3770 patch->direct_to_threeway =1;3771}else switch(err) {3772case0:3773break;/* happy */3774case EXISTS_IN_INDEX:3775returnerror(_("%s: already exists in index"), new_name);3776break;3777case EXISTS_IN_WORKTREE:3778returnerror(_("%s: already exists in working directory"),3779 new_name);3780default:3781return err;3782}37833784if(!patch->new_mode) {3785if(0< patch->is_new)3786 patch->new_mode = S_IFREG |0644;3787else3788 patch->new_mode = patch->old_mode;3789}3790}37913792if(new_name && old_name) {3793int same = !strcmp(old_name, new_name);3794if(!patch->new_mode)3795 patch->new_mode = patch->old_mode;3796if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3797if(same)3798returnerror(_("new mode (%o) of%sdoes not "3799"match old mode (%o)"),3800 patch->new_mode, new_name,3801 patch->old_mode);3802else3803returnerror(_("new mode (%o) of%sdoes not "3804"match old mode (%o) of%s"),3805 patch->new_mode, new_name,3806 patch->old_mode, old_name);3807}3808}38093810if(!unsafe_paths)3811die_on_unsafe_path(patch);38123813/*3814 * An attempt to read from or delete a path that is beyond a3815 * symbolic link will be prevented by load_patch_target() that3816 * is called at the beginning of apply_data() so we do not3817 * have to worry about a patch marked with "is_delete" bit3818 * here. We however need to make sure that the patch result3819 * is not deposited to a path that is beyond a symbolic link3820 * here.3821 */3822if(!patch->is_delete &&path_is_beyond_symlink(patch->new_name))3823returnerror(_("affected file '%s' is beyond a symbolic link"),3824 patch->new_name);38253826if(apply_data(state, patch, &st, ce) <0)3827returnerror(_("%s: patch does not apply"), name);3828 patch->rejected =0;3829return0;3830}38313832static intcheck_patch_list(struct apply_state *state,struct patch *patch)3833{3834int err =0;38353836prepare_symlink_changes(patch);3837prepare_fn_table(patch);3838while(patch) {3839if(apply_verbosely)3840say_patch_name(stderr,3841_("Checking patch%s..."), patch);3842 err |=check_patch(state, patch);3843 patch = patch->next;3844}3845return err;3846}38473848/* This function tries to read the sha1 from the current index */3849static intget_current_sha1(const char*path,unsigned char*sha1)3850{3851int pos;38523853if(read_cache() <0)3854return-1;3855 pos =cache_name_pos(path,strlen(path));3856if(pos <0)3857return-1;3858hashcpy(sha1, active_cache[pos]->sha1);3859return0;3860}38613862static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3863{3864/*3865 * A usable gitlink patch has only one fragment (hunk) that looks like:3866 * @@ -1 +1 @@3867 * -Subproject commit <old sha1>3868 * +Subproject commit <new sha1>3869 * or3870 * @@ -1 +0,0 @@3871 * -Subproject commit <old sha1>3872 * for a removal patch.3873 */3874struct fragment *hunk = p->fragments;3875static const char heading[] ="-Subproject commit ";3876char*preimage;38773878if(/* does the patch have only one hunk? */3879 hunk && !hunk->next &&3880/* is its preimage one line? */3881 hunk->oldpos ==1&& hunk->oldlines ==1&&3882/* does preimage begin with the heading? */3883(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3884starts_with(++preimage, heading) &&3885/* does it record full SHA-1? */3886!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3887 preimage[sizeof(heading) +40-1] =='\n'&&3888/* does the abbreviated name on the index line agree with it? */3889starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3890return0;/* it all looks fine */38913892/* we may have full object name on the index line */3893returnget_sha1_hex(p->old_sha1_prefix, sha1);3894}38953896/* Build an index that contains the just the files needed for a 3way merge */3897static voidbuild_fake_ancestor(struct patch *list,const char*filename)3898{3899struct patch *patch;3900struct index_state result = { NULL };3901static struct lock_file lock;39023903/* Once we start supporting the reverse patch, it may be3904 * worth showing the new sha1 prefix, but until then...3905 */3906for(patch = list; patch; patch = patch->next) {3907unsigned char sha1[20];3908struct cache_entry *ce;3909const char*name;39103911 name = patch->old_name ? patch->old_name : patch->new_name;3912if(0< patch->is_new)3913continue;39143915if(S_ISGITLINK(patch->old_mode)) {3916if(!preimage_sha1_in_gitlink_patch(patch, sha1))3917;/* ok, the textual part looks sane */3918else3919die("sha1 information is lacking or useless for submodule%s",3920 name);3921}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {3922;/* ok */3923}else if(!patch->lines_added && !patch->lines_deleted) {3924/* mode-only change: update the current */3925if(get_current_sha1(patch->old_name, sha1))3926die("mode change for%s, which is not "3927"in current HEAD", name);3928}else3929die("sha1 information is lacking or useless "3930"(%s).", name);39313932 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);3933if(!ce)3934die(_("make_cache_entry failed for path '%s'"), name);3935if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3936die("Could not add%sto temporary index", name);3937}39383939hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);3940if(write_locked_index(&result, &lock, COMMIT_LOCK))3941die("Could not write temporary index to%s", filename);39423943discard_index(&result);3944}39453946static voidstat_patch_list(struct patch *patch)3947{3948int files, adds, dels;39493950for(files = adds = dels =0; patch ; patch = patch->next) {3951 files++;3952 adds += patch->lines_added;3953 dels += patch->lines_deleted;3954show_stats(patch);3955}39563957print_stat_summary(stdout, files, adds, dels);3958}39593960static voidnumstat_patch_list(struct patch *patch)3961{3962for( ; patch; patch = patch->next) {3963const char*name;3964 name = patch->new_name ? patch->new_name : patch->old_name;3965if(patch->is_binary)3966printf("-\t-\t");3967else3968printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3969write_name_quoted(name, stdout, line_termination);3970}3971}39723973static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3974{3975if(mode)3976printf("%smode%06o%s\n", newdelete, mode, name);3977else3978printf("%s %s\n", newdelete, name);3979}39803981static voidshow_mode_change(struct patch *p,int show_name)3982{3983if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3984if(show_name)3985printf(" mode change%06o =>%06o%s\n",3986 p->old_mode, p->new_mode, p->new_name);3987else3988printf(" mode change%06o =>%06o\n",3989 p->old_mode, p->new_mode);3990}3991}39923993static voidshow_rename_copy(struct patch *p)3994{3995const char*renamecopy = p->is_rename ?"rename":"copy";3996const char*old, *new;39973998/* Find common prefix */3999 old = p->old_name;4000new= p->new_name;4001while(1) {4002const char*slash_old, *slash_new;4003 slash_old =strchr(old,'/');4004 slash_new =strchr(new,'/');4005if(!slash_old ||4006!slash_new ||4007 slash_old - old != slash_new -new||4008memcmp(old,new, slash_new -new))4009break;4010 old = slash_old +1;4011new= slash_new +1;4012}4013/* p->old_name thru old is the common prefix, and old and new4014 * through the end of names are renames4015 */4016if(old != p->old_name)4017printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4018(int)(old - p->old_name), p->old_name,4019 old,new, p->score);4020else4021printf("%s %s=>%s(%d%%)\n", renamecopy,4022 p->old_name, p->new_name, p->score);4023show_mode_change(p,0);4024}40254026static voidsummary_patch_list(struct patch *patch)4027{4028struct patch *p;40294030for(p = patch; p; p = p->next) {4031if(p->is_new)4032show_file_mode_name("create", p->new_mode, p->new_name);4033else if(p->is_delete)4034show_file_mode_name("delete", p->old_mode, p->old_name);4035else{4036if(p->is_rename || p->is_copy)4037show_rename_copy(p);4038else{4039if(p->score) {4040printf(" rewrite%s(%d%%)\n",4041 p->new_name, p->score);4042show_mode_change(p,0);4043}4044else4045show_mode_change(p,1);4046}4047}4048}4049}40504051static voidpatch_stats(struct patch *patch)4052{4053int lines = patch->lines_added + patch->lines_deleted;40544055if(lines > max_change)4056 max_change = lines;4057if(patch->old_name) {4058int len =quote_c_style(patch->old_name, NULL, NULL,0);4059if(!len)4060 len =strlen(patch->old_name);4061if(len > max_len)4062 max_len = len;4063}4064if(patch->new_name) {4065int len =quote_c_style(patch->new_name, NULL, NULL,0);4066if(!len)4067 len =strlen(patch->new_name);4068if(len > max_len)4069 max_len = len;4070}4071}40724073static voidremove_file(struct patch *patch,int rmdir_empty)4074{4075if(update_index) {4076if(remove_file_from_cache(patch->old_name) <0)4077die(_("unable to remove%sfrom index"), patch->old_name);4078}4079if(!cached) {4080if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4081remove_path(patch->old_name);4082}4083}4084}40854086static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)4087{4088struct stat st;4089struct cache_entry *ce;4090int namelen =strlen(path);4091unsigned ce_size =cache_entry_size(namelen);40924093if(!update_index)4094return;40954096 ce =xcalloc(1, ce_size);4097memcpy(ce->name, path, namelen);4098 ce->ce_mode =create_ce_mode(mode);4099 ce->ce_flags =create_ce_flags(0);4100 ce->ce_namelen = namelen;4101if(S_ISGITLINK(mode)) {4102const char*s;41034104if(!skip_prefix(buf,"Subproject commit ", &s) ||4105get_sha1_hex(s, ce->sha1))4106die(_("corrupt patch for submodule%s"), path);4107}else{4108if(!cached) {4109if(lstat(path, &st) <0)4110die_errno(_("unable to stat newly created file '%s'"),4111 path);4112fill_stat_cache_info(ce, &st);4113}4114if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4115die(_("unable to create backing store for newly created file%s"), path);4116}4117if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4118die(_("unable to add cache entry for%s"), path);4119}41204121static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4122{4123int fd;4124struct strbuf nbuf = STRBUF_INIT;41254126if(S_ISGITLINK(mode)) {4127struct stat st;4128if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4129return0;4130returnmkdir(path,0777);4131}41324133if(has_symlinks &&S_ISLNK(mode))4134/* Although buf:size is counted string, it also is NUL4135 * terminated.4136 */4137returnsymlink(buf, path);41384139 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4140if(fd <0)4141return-1;41424143if(convert_to_working_tree(path, buf, size, &nbuf)) {4144 size = nbuf.len;4145 buf = nbuf.buf;4146}4147write_or_die(fd, buf, size);4148strbuf_release(&nbuf);41494150if(close(fd) <0)4151die_errno(_("closing file '%s'"), path);4152return0;4153}41544155/*4156 * We optimistically assume that the directories exist,4157 * which is true 99% of the time anyway. If they don't,4158 * we create them and try again.4159 */4160static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)4161{4162if(cached)4163return;4164if(!try_create_file(path, mode, buf, size))4165return;41664167if(errno == ENOENT) {4168if(safe_create_leading_directories(path))4169return;4170if(!try_create_file(path, mode, buf, size))4171return;4172}41734174if(errno == EEXIST || errno == EACCES) {4175/* We may be trying to create a file where a directory4176 * used to be.4177 */4178struct stat st;4179if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4180 errno = EEXIST;4181}41824183if(errno == EEXIST) {4184unsigned int nr =getpid();41854186for(;;) {4187char newpath[PATH_MAX];4188mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4189if(!try_create_file(newpath, mode, buf, size)) {4190if(!rename(newpath, path))4191return;4192unlink_or_warn(newpath);4193break;4194}4195if(errno != EEXIST)4196break;4197++nr;4198}4199}4200die_errno(_("unable to write file '%s' mode%o"), path, mode);4201}42024203static voidadd_conflicted_stages_file(struct patch *patch)4204{4205int stage, namelen;4206unsigned ce_size, mode;4207struct cache_entry *ce;42084209if(!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 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(path, mode, buf, size);42404241if(patch->conflicted_threeway)4242add_conflicted_stages_file(patch);4243else4244add_index_file(path, mode, buf, size);4245}42464247/* phase zero is to remove, phase one is to create */4248static voidwrite_out_one_result(struct patch *patch,int phase)4249{4250if(patch->is_delete >0) {4251if(phase ==0)4252remove_file(patch,1);4253return;4254}4255if(patch->is_new >0|| patch->is_copy) {4256if(phase ==1)4257create_file(patch);4258return;4259}4260/*4261 * Rename or modification boils down to the same4262 * thing: remove the old, write the new4263 */4264if(phase ==0)4265remove_file(patch, patch->is_rename);4266if(phase ==1)4267create_file(patch);4268}42694270static intwrite_out_one_reject(struct patch *patch)4271{4272FILE*rej;4273char namebuf[PATH_MAX];4274struct fragment *frag;4275int cnt =0;4276struct strbuf sb = STRBUF_INIT;42774278for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4279if(!frag->rejected)4280continue;4281 cnt++;4282}42834284if(!cnt) {4285if(apply_verbosely)4286say_patch_name(stderr,4287_("Applied patch%scleanly."), patch);4288return0;4289}42904291/* This should not happen, because a removal patch that leaves4292 * contents are marked "rejected" at the patch level.4293 */4294if(!patch->new_name)4295die(_("internal error"));42964297/* Say this even without --verbose */4298strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4299"Applying patch %%swith%drejects...",4300 cnt),4301 cnt);4302say_patch_name(stderr, sb.buf, patch);4303strbuf_release(&sb);43044305 cnt =strlen(patch->new_name);4306if(ARRAY_SIZE(namebuf) <= cnt +5) {4307 cnt =ARRAY_SIZE(namebuf) -5;4308warning(_("truncating .rej filename to %.*s.rej"),4309 cnt -1, patch->new_name);4310}4311memcpy(namebuf, patch->new_name, cnt);4312memcpy(namebuf + cnt,".rej",5);43134314 rej =fopen(namebuf,"w");4315if(!rej)4316returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));43174318/* Normal git tools never deal with .rej, so do not pretend4319 * this is a git patch by saying --git or giving extended4320 * headers. While at it, maybe please "kompare" that wants4321 * the trailing TAB and some garbage at the end of line ;-).4322 */4323fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4324 patch->new_name, patch->new_name);4325for(cnt =1, frag = patch->fragments;4326 frag;4327 cnt++, frag = frag->next) {4328if(!frag->rejected) {4329fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4330continue;4331}4332fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4333fprintf(rej,"%.*s", frag->size, frag->patch);4334if(frag->patch[frag->size-1] !='\n')4335fputc('\n', rej);4336}4337fclose(rej);4338return-1;4339}43404341static intwrite_out_results(struct patch *list)4342{4343int phase;4344int errs =0;4345struct patch *l;4346struct string_list cpath = STRING_LIST_INIT_DUP;43474348for(phase =0; phase <2; phase++) {4349 l = list;4350while(l) {4351if(l->rejected)4352 errs =1;4353else{4354write_out_one_result(l, phase);4355if(phase ==1) {4356if(write_out_one_reject(l))4357 errs =1;4358if(l->conflicted_threeway) {4359string_list_append(&cpath, l->new_name);4360 errs =1;4361}4362}4363}4364 l = l->next;4365}4366}43674368if(cpath.nr) {4369struct string_list_item *item;43704371string_list_sort(&cpath);4372for_each_string_list_item(item, &cpath)4373fprintf(stderr,"U%s\n", item->string);4374string_list_clear(&cpath,0);43754376rerere(0);4377}43784379return errs;4380}43814382static struct lock_file lock_file;43834384#define INACCURATE_EOF (1<<0)4385#define RECOUNT (1<<1)43864387static intapply_patch(struct apply_state *state,4388int fd,4389const char*filename,4390int options)4391{4392size_t offset;4393struct strbuf buf = STRBUF_INIT;/* owns the patch text */4394struct patch *list = NULL, **listp = &list;4395int skipped_patch =0;43964397 patch_input_file = filename;4398read_patch_file(&buf, fd);4399 offset =0;4400while(offset < buf.len) {4401struct patch *patch;4402int nr;44034404 patch =xcalloc(1,sizeof(*patch));4405 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4406 patch->recount = !!(options & RECOUNT);4407 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4408if(nr <0) {4409free_patch(patch);4410break;4411}4412if(apply_in_reverse)4413reverse_patches(patch);4414if(use_patch(state, patch)) {4415patch_stats(patch);4416*listp = patch;4417 listp = &patch->next;4418}4419else{4420if(apply_verbosely)4421say_patch_name(stderr,_("Skipped patch '%s'."), patch);4422free_patch(patch);4423 skipped_patch++;4424}4425 offset += nr;4426}44274428if(!list && !skipped_patch)4429die(_("unrecognized input"));44304431if(whitespace_error && (ws_error_action == die_on_ws_error))4432 apply =0;44334434 update_index = check_index && apply;4435if(update_index && newfd <0)4436 newfd =hold_locked_index(&lock_file,1);44374438if(check_index) {4439if(read_cache() <0)4440die(_("unable to read index file"));4441}44424443if((state->check || apply) &&4444check_patch_list(state, list) <0&&4445!apply_with_reject)4446exit(1);44474448if(apply &&write_out_results(list)) {4449if(apply_with_reject)4450exit(1);4451/* with --3way, we still need to write the index out */4452return1;4453}44544455if(fake_ancestor)4456build_fake_ancestor(list, fake_ancestor);44574458if(diffstat)4459stat_patch_list(list);44604461if(numstat)4462numstat_patch_list(list);44634464if(summary)4465summary_patch_list(list);44664467free_patch_list(list);4468strbuf_release(&buf);4469string_list_clear(&fn_table,0);4470return0;4471}44724473static voidgit_apply_config(void)4474{4475git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4476git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4477git_config(git_default_config, NULL);4478}44794480static intoption_parse_exclude(const struct option *opt,4481const char*arg,int unset)4482{4483add_name_limit(arg,1);4484return0;4485}44864487static intoption_parse_include(const struct option *opt,4488const char*arg,int unset)4489{4490add_name_limit(arg,0);4491 has_include =1;4492return0;4493}44944495static intoption_parse_p(const struct option *opt,4496const char*arg,int unset)4497{4498 state_p_value =atoi(arg);4499 p_value_known =1;4500return0;4501}45024503static intoption_parse_space_change(const struct option *opt,4504const char*arg,int unset)4505{4506if(unset)4507 ws_ignore_action = ignore_ws_none;4508else4509 ws_ignore_action = ignore_ws_change;4510return0;4511}45124513static intoption_parse_whitespace(const struct option *opt,4514const char*arg,int unset)4515{4516const char**whitespace_option = opt->value;45174518*whitespace_option = arg;4519parse_whitespace_option(arg);4520return0;4521}45224523static intoption_parse_directory(const struct option *opt,4524const char*arg,int unset)4525{4526strbuf_reset(&root);4527strbuf_addstr(&root, arg);4528strbuf_complete(&root,'/');4529return0;4530}45314532static voidinit_apply_state(struct apply_state *state,const char*prefix)4533{4534memset(state,0,sizeof(*state));4535 state->prefix = prefix;4536 state->prefix_length = state->prefix ?strlen(state->prefix) :0;45374538git_apply_config();4539if(apply_default_whitespace)4540parse_whitespace_option(apply_default_whitespace);4541if(apply_default_ignorewhitespace)4542parse_ignorewhitespace_option(apply_default_ignorewhitespace);4543}45444545static voidclear_apply_state(struct apply_state *state)4546{4547/* empty for now */4548}45494550intcmd_apply(int argc,const char**argv,const char*prefix)4551{4552int i;4553int errs =0;4554int is_not_gitdir = !startup_info->have_repository;4555int force_apply =0;4556int options =0;4557int read_stdin =1;4558struct apply_state state;45594560const char*whitespace_option = NULL;45614562struct option builtin_apply_options[] = {4563{ OPTION_CALLBACK,0,"exclude", NULL,N_("path"),4564N_("don't apply changes matching the given path"),45650, option_parse_exclude },4566{ OPTION_CALLBACK,0,"include", NULL,N_("path"),4567N_("apply changes matching the given path"),45680, option_parse_include },4569{ OPTION_CALLBACK,'p', NULL, NULL,N_("num"),4570N_("remove <num> leading slashes from traditional diff paths"),45710, option_parse_p },4572OPT_BOOL(0,"no-add", &no_add,4573N_("ignore additions made by the patch")),4574OPT_BOOL(0,"stat", &diffstat,4575N_("instead of applying the patch, output diffstat for the input")),4576OPT_NOOP_NOARG(0,"allow-binary-replacement"),4577OPT_NOOP_NOARG(0,"binary"),4578OPT_BOOL(0,"numstat", &numstat,4579N_("show number of added and deleted lines in decimal notation")),4580OPT_BOOL(0,"summary", &summary,4581N_("instead of applying the patch, output a summary for the input")),4582OPT_BOOL(0,"check", &state.check,4583N_("instead of applying the patch, see if the patch is applicable")),4584OPT_BOOL(0,"index", &check_index,4585N_("make sure the patch is applicable to the current index")),4586OPT_BOOL(0,"cached", &cached,4587N_("apply a patch without touching the working tree")),4588OPT_BOOL(0,"unsafe-paths", &unsafe_paths,4589N_("accept a patch that touches outside the working area")),4590OPT_BOOL(0,"apply", &force_apply,4591N_("also apply the patch (use with --stat/--summary/--check)")),4592OPT_BOOL('3',"3way", &threeway,4593N_("attempt three-way merge if a patch does not apply")),4594OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,4595N_("build a temporary index based on embedded index information")),4596/* Think twice before adding "--nul" synonym to this */4597OPT_SET_INT('z', NULL, &line_termination,4598N_("paths are separated with NUL character"),'\0'),4599OPT_INTEGER('C', NULL, &p_context,4600N_("ensure at least <n> lines of context match")),4601{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,N_("action"),4602N_("detect new or modified lines that have whitespace errors"),46030, option_parse_whitespace },4604{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,4605N_("ignore changes in whitespace when finding context"),4606 PARSE_OPT_NOARG, option_parse_space_change },4607{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,4608N_("ignore changes in whitespace when finding context"),4609 PARSE_OPT_NOARG, option_parse_space_change },4610OPT_BOOL('R',"reverse", &apply_in_reverse,4611N_("apply the patch in reverse")),4612OPT_BOOL(0,"unidiff-zero", &state.unidiff_zero,4613N_("don't expect at least one line of context")),4614OPT_BOOL(0,"reject", &apply_with_reject,4615N_("leave the rejected hunks in corresponding *.rej files")),4616OPT_BOOL(0,"allow-overlap", &allow_overlap,4617N_("allow overlapping hunks")),4618OPT__VERBOSE(&apply_verbosely,N_("be verbose")),4619OPT_BIT(0,"inaccurate-eof", &options,4620N_("tolerate incorrectly detected missing new-line at the end of file"),4621 INACCURATE_EOF),4622OPT_BIT(0,"recount", &options,4623N_("do not trust the line counts in the hunk headers"),4624 RECOUNT),4625{ OPTION_CALLBACK,0,"directory", NULL,N_("root"),4626N_("prepend <root> to all filenames"),46270, option_parse_directory },4628OPT_END()4629};46304631init_apply_state(&state, prefix);46324633 argc =parse_options(argc, argv, state.prefix, builtin_apply_options,4634 apply_usage,0);46354636if(apply_with_reject && threeway)4637die("--reject and --3way cannot be used together.");4638if(cached && threeway)4639die("--cached and --3way cannot be used together.");4640if(threeway) {4641if(is_not_gitdir)4642die(_("--3way outside a repository"));4643 check_index =1;4644}4645if(apply_with_reject)4646 apply = apply_verbosely =1;4647if(!force_apply && (diffstat || numstat || summary || state.check || fake_ancestor))4648 apply =0;4649if(check_index && is_not_gitdir)4650die(_("--index outside a repository"));4651if(cached) {4652if(is_not_gitdir)4653die(_("--cached outside a repository"));4654 check_index =1;4655}4656if(check_index)4657 unsafe_paths =0;46584659for(i =0; i < argc; i++) {4660const char*arg = argv[i];4661int fd;46624663if(!strcmp(arg,"-")) {4664 errs |=apply_patch(&state,0,"<stdin>", options);4665 read_stdin =0;4666continue;4667}else if(0< state.prefix_length)4668 arg =prefix_filename(state.prefix,4669 state.prefix_length,4670 arg);46714672 fd =open(arg, O_RDONLY);4673if(fd <0)4674die_errno(_("can't open patch '%s'"), arg);4675 read_stdin =0;4676set_default_whitespace_mode(whitespace_option);4677 errs |=apply_patch(&state, fd, arg, options);4678close(fd);4679}4680set_default_whitespace_mode(whitespace_option);4681if(read_stdin)4682 errs |=apply_patch(&state,0,"<stdin>", options);4683if(whitespace_error) {4684if(squelch_whitespace_errors &&4685 squelch_whitespace_errors < whitespace_error) {4686int squelched =4687 whitespace_error - squelch_whitespace_errors;4688warning(Q_("squelched%dwhitespace error",4689"squelched%dwhitespace errors",4690 squelched),4691 squelched);4692}4693if(ws_error_action == die_on_ws_error)4694die(Q_("%dline adds whitespace errors.",4695"%dlines add whitespace errors.",4696 whitespace_error),4697 whitespace_error);4698if(applied_after_fixing_ws && apply)4699warning("%dline%sapplied after"4700" fixing whitespace errors.",4701 applied_after_fixing_ws,4702 applied_after_fixing_ws ==1?"":"s");4703else if(whitespace_error)4704warning(Q_("%dline adds whitespace errors.",4705"%dlines add whitespace errors.",4706 whitespace_error),4707 whitespace_error);4708}47094710if(update_index) {4711if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK))4712die(_("Unable to write new index file"));4713}47144715clear_apply_state(&state);47164717return!!errs;4718}