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 */ 30int check_index;/* preimage must match the indexed version */ 31 32/* These boolean parameters control how the apply is done */ 33int apply_in_reverse; 34int apply_with_reject; 35int unidiff_zero; 36}; 37 38/* 39 * --stat does just a diffstat, and doesn't actually apply 40 * --numstat does numeric diffstat, and doesn't actually apply 41 * --index-info shows the old and new index info for paths if available. 42 * --cached updates only the cache without ever touching the working tree. 43 */ 44static int newfd = -1; 45 46static int state_p_value =1; 47static int p_value_known; 48static int update_index; 49static int cached; 50static int diffstat; 51static int numstat; 52static int summary; 53static int apply =1; 54static int apply_verbosely; 55static int allow_overlap; 56static int no_add; 57static int threeway; 58static int unsafe_paths; 59static const char*fake_ancestor; 60static int line_termination ='\n'; 61static unsigned int p_context = UINT_MAX; 62static const char*const apply_usage[] = { 63N_("git apply [<options>] [<patch>...]"), 64 NULL 65}; 66 67static enum ws_error_action { 68 nowarn_ws_error, 69 warn_on_ws_error, 70 die_on_ws_error, 71 correct_ws_error 72} ws_error_action = warn_on_ws_error; 73static int whitespace_error; 74static int squelch_whitespace_errors =5; 75static int applied_after_fixing_ws; 76 77static enum ws_ignore { 78 ignore_ws_none, 79 ignore_ws_change 80} ws_ignore_action = ignore_ws_none; 81 82 83static const char*patch_input_file; 84static struct strbuf root = STRBUF_INIT; 85 86static voidparse_whitespace_option(const char*option) 87{ 88if(!option) { 89 ws_error_action = warn_on_ws_error; 90return; 91} 92if(!strcmp(option,"warn")) { 93 ws_error_action = warn_on_ws_error; 94return; 95} 96if(!strcmp(option,"nowarn")) { 97 ws_error_action = nowarn_ws_error; 98return; 99} 100if(!strcmp(option,"error")) { 101 ws_error_action = die_on_ws_error; 102return; 103} 104if(!strcmp(option,"error-all")) { 105 ws_error_action = die_on_ws_error; 106 squelch_whitespace_errors =0; 107return; 108} 109if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 110 ws_error_action = correct_ws_error; 111return; 112} 113die(_("unrecognized whitespace option '%s'"), option); 114} 115 116static voidparse_ignorewhitespace_option(const char*option) 117{ 118if(!option || !strcmp(option,"no") || 119!strcmp(option,"false") || !strcmp(option,"never") || 120!strcmp(option,"none")) { 121 ws_ignore_action = ignore_ws_none; 122return; 123} 124if(!strcmp(option,"change")) { 125 ws_ignore_action = ignore_ws_change; 126return; 127} 128die(_("unrecognized whitespace ignore option '%s'"), option); 129} 130 131static voidset_default_whitespace_mode(const char*whitespace_option) 132{ 133if(!whitespace_option && !apply_default_whitespace) 134 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 135} 136 137/* 138 * For "diff-stat" like behaviour, we keep track of the biggest change 139 * we've seen, and the longest filename. That allows us to do simple 140 * scaling. 141 */ 142static int max_change, max_len; 143 144/* 145 * Various "current state", notably line numbers and what 146 * file (and how) we're patching right now.. The "is_xxxx" 147 * things are flags, where -1 means "don't know yet". 148 */ 149static int state_linenr =1; 150 151/* 152 * This represents one "hunk" from a patch, starting with 153 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 154 * patch text is pointed at by patch, and its byte length 155 * is stored in size. leading and trailing are the number 156 * of context lines. 157 */ 158struct fragment { 159unsigned long leading, trailing; 160unsigned long oldpos, oldlines; 161unsigned long newpos, newlines; 162/* 163 * 'patch' is usually borrowed from buf in apply_patch(), 164 * but some codepaths store an allocated buffer. 165 */ 166const char*patch; 167unsigned free_patch:1, 168 rejected:1; 169int size; 170int linenr; 171struct fragment *next; 172}; 173 174/* 175 * When dealing with a binary patch, we reuse "leading" field 176 * to store the type of the binary hunk, either deflated "delta" 177 * or deflated "literal". 178 */ 179#define binary_patch_method leading 180#define BINARY_DELTA_DEFLATED 1 181#define BINARY_LITERAL_DEFLATED 2 182 183/* 184 * This represents a "patch" to a file, both metainfo changes 185 * such as creation/deletion, filemode and content changes represented 186 * as a series of fragments. 187 */ 188struct patch { 189char*new_name, *old_name, *def_name; 190unsigned int old_mode, new_mode; 191int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 192int rejected; 193unsigned ws_rule; 194int lines_added, lines_deleted; 195int score; 196unsigned int is_toplevel_relative:1; 197unsigned int inaccurate_eof:1; 198unsigned int is_binary:1; 199unsigned int is_copy:1; 200unsigned int is_rename:1; 201unsigned int recount:1; 202unsigned int conflicted_threeway:1; 203unsigned int direct_to_threeway:1; 204struct fragment *fragments; 205char*result; 206size_t resultsize; 207char old_sha1_prefix[41]; 208char new_sha1_prefix[41]; 209struct patch *next; 210 211/* three-way fallback result */ 212struct object_id threeway_stage[3]; 213}; 214 215static voidfree_fragment_list(struct fragment *list) 216{ 217while(list) { 218struct fragment *next = list->next; 219if(list->free_patch) 220free((char*)list->patch); 221free(list); 222 list = next; 223} 224} 225 226static voidfree_patch(struct patch *patch) 227{ 228free_fragment_list(patch->fragments); 229free(patch->def_name); 230free(patch->old_name); 231free(patch->new_name); 232free(patch->result); 233free(patch); 234} 235 236static voidfree_patch_list(struct patch *list) 237{ 238while(list) { 239struct patch *next = list->next; 240free_patch(list); 241 list = next; 242} 243} 244 245/* 246 * A line in a file, len-bytes long (includes the terminating LF, 247 * except for an incomplete line at the end if the file ends with 248 * one), and its contents hashes to 'hash'. 249 */ 250struct line { 251size_t len; 252unsigned hash :24; 253unsigned flag :8; 254#define LINE_COMMON 1 255#define LINE_PATCHED 2 256}; 257 258/* 259 * This represents a "file", which is an array of "lines". 260 */ 261struct image { 262char*buf; 263size_t len; 264size_t nr; 265size_t alloc; 266struct line *line_allocated; 267struct line *line; 268}; 269 270/* 271 * Records filenames that have been touched, in order to handle 272 * the case where more than one patches touch the same file. 273 */ 274 275static struct string_list fn_table; 276 277static uint32_thash_line(const char*cp,size_t len) 278{ 279size_t i; 280uint32_t h; 281for(i =0, h =0; i < len; i++) { 282if(!isspace(cp[i])) { 283 h = h *3+ (cp[i] &0xff); 284} 285} 286return h; 287} 288 289/* 290 * Compare lines s1 of length n1 and s2 of length n2, ignoring 291 * whitespace difference. Returns 1 if they match, 0 otherwise 292 */ 293static intfuzzy_matchlines(const char*s1,size_t n1, 294const char*s2,size_t n2) 295{ 296const char*last1 = s1 + n1 -1; 297const char*last2 = s2 + n2 -1; 298int result =0; 299 300/* ignore line endings */ 301while((*last1 =='\r') || (*last1 =='\n')) 302 last1--; 303while((*last2 =='\r') || (*last2 =='\n')) 304 last2--; 305 306/* skip leading whitespaces, if both begin with whitespace */ 307if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 308while(isspace(*s1) && (s1 <= last1)) 309 s1++; 310while(isspace(*s2) && (s2 <= last2)) 311 s2++; 312} 313/* early return if both lines are empty */ 314if((s1 > last1) && (s2 > last2)) 315return1; 316while(!result) { 317 result = *s1++ - *s2++; 318/* 319 * Skip whitespace inside. We check for whitespace on 320 * both buffers because we don't want "a b" to match 321 * "ab" 322 */ 323if(isspace(*s1) &&isspace(*s2)) { 324while(isspace(*s1) && s1 <= last1) 325 s1++; 326while(isspace(*s2) && s2 <= last2) 327 s2++; 328} 329/* 330 * If we reached the end on one side only, 331 * lines don't match 332 */ 333if( 334((s2 > last2) && (s1 <= last1)) || 335((s1 > last1) && (s2 <= last2))) 336return0; 337if((s1 > last1) && (s2 > last2)) 338break; 339} 340 341return!result; 342} 343 344static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 345{ 346ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 347 img->line_allocated[img->nr].len = len; 348 img->line_allocated[img->nr].hash =hash_line(bol, len); 349 img->line_allocated[img->nr].flag = flag; 350 img->nr++; 351} 352 353/* 354 * "buf" has the file contents to be patched (read from various sources). 355 * attach it to "image" and add line-based index to it. 356 * "image" now owns the "buf". 357 */ 358static voidprepare_image(struct image *image,char*buf,size_t len, 359int prepare_linetable) 360{ 361const char*cp, *ep; 362 363memset(image,0,sizeof(*image)); 364 image->buf = buf; 365 image->len = len; 366 367if(!prepare_linetable) 368return; 369 370 ep = image->buf + image->len; 371 cp = image->buf; 372while(cp < ep) { 373const char*next; 374for(next = cp; next < ep && *next !='\n'; next++) 375; 376if(next < ep) 377 next++; 378add_line_info(image, cp, next - cp,0); 379 cp = next; 380} 381 image->line = image->line_allocated; 382} 383 384static voidclear_image(struct image *image) 385{ 386free(image->buf); 387free(image->line_allocated); 388memset(image,0,sizeof(*image)); 389} 390 391/* fmt must contain _one_ %s and no other substitution */ 392static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 393{ 394struct strbuf sb = STRBUF_INIT; 395 396if(patch->old_name && patch->new_name && 397strcmp(patch->old_name, patch->new_name)) { 398quote_c_style(patch->old_name, &sb, NULL,0); 399strbuf_addstr(&sb," => "); 400quote_c_style(patch->new_name, &sb, NULL,0); 401}else{ 402const char*n = patch->new_name; 403if(!n) 404 n = patch->old_name; 405quote_c_style(n, &sb, NULL,0); 406} 407fprintf(output, fmt, sb.buf); 408fputc('\n', output); 409strbuf_release(&sb); 410} 411 412#define SLOP (16) 413 414static voidread_patch_file(struct strbuf *sb,int fd) 415{ 416if(strbuf_read(sb, fd,0) <0) 417die_errno("git apply: failed to read"); 418 419/* 420 * Make sure that we have some slop in the buffer 421 * so that we can do speculative "memcmp" etc, and 422 * see to it that it is NUL-filled. 423 */ 424strbuf_grow(sb, SLOP); 425memset(sb->buf + sb->len,0, SLOP); 426} 427 428static unsigned longlinelen(const char*buffer,unsigned long size) 429{ 430unsigned long len =0; 431while(size--) { 432 len++; 433if(*buffer++ =='\n') 434break; 435} 436return len; 437} 438 439static intis_dev_null(const char*str) 440{ 441returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 442} 443 444#define TERM_SPACE 1 445#define TERM_TAB 2 446 447static intname_terminate(const char*name,int namelen,int c,int terminate) 448{ 449if(c ==' '&& !(terminate & TERM_SPACE)) 450return0; 451if(c =='\t'&& !(terminate & TERM_TAB)) 452return0; 453 454return1; 455} 456 457/* remove double slashes to make --index work with such filenames */ 458static char*squash_slash(char*name) 459{ 460int i =0, j =0; 461 462if(!name) 463return NULL; 464 465while(name[i]) { 466if((name[j++] = name[i++]) =='/') 467while(name[i] =='/') 468 i++; 469} 470 name[j] ='\0'; 471return name; 472} 473 474static char*find_name_gnu(const char*line,const char*def,int p_value) 475{ 476struct strbuf name = STRBUF_INIT; 477char*cp; 478 479/* 480 * Proposed "new-style" GNU patch/diff format; see 481 * http://marc.info/?l=git&m=112927316408690&w=2 482 */ 483if(unquote_c_style(&name, line, NULL)) { 484strbuf_release(&name); 485return NULL; 486} 487 488for(cp = name.buf; p_value; p_value--) { 489 cp =strchr(cp,'/'); 490if(!cp) { 491strbuf_release(&name); 492return NULL; 493} 494 cp++; 495} 496 497strbuf_remove(&name,0, cp - name.buf); 498if(root.len) 499strbuf_insert(&name,0, root.buf, root.len); 500returnsquash_slash(strbuf_detach(&name, NULL)); 501} 502 503static size_tsane_tz_len(const char*line,size_t len) 504{ 505const char*tz, *p; 506 507if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 508return0; 509 tz = line + len -strlen(" +0500"); 510 511if(tz[1] !='+'&& tz[1] !='-') 512return0; 513 514for(p = tz +2; p != line + len; p++) 515if(!isdigit(*p)) 516return0; 517 518return line + len - tz; 519} 520 521static size_ttz_with_colon_len(const char*line,size_t len) 522{ 523const char*tz, *p; 524 525if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 526return0; 527 tz = line + len -strlen(" +08:00"); 528 529if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 530return0; 531 p = tz +2; 532if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 533!isdigit(*p++) || !isdigit(*p++)) 534return0; 535 536return line + len - tz; 537} 538 539static size_tdate_len(const char*line,size_t len) 540{ 541const char*date, *p; 542 543if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 544return0; 545 p = date = line + len -strlen("72-02-05"); 546 547if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 548!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 549!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 550return0; 551 552if(date - line >=strlen("19") && 553isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 554 date -=strlen("19"); 555 556return line + len - date; 557} 558 559static size_tshort_time_len(const char*line,size_t len) 560{ 561const char*time, *p; 562 563if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 564return0; 565 p = time = line + len -strlen(" 07:01:32"); 566 567/* Permit 1-digit hours? */ 568if(*p++ !=' '|| 569!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 570!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 571!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 572return0; 573 574return line + len - time; 575} 576 577static size_tfractional_time_len(const char*line,size_t len) 578{ 579const char*p; 580size_t n; 581 582/* Expected format: 19:41:17.620000023 */ 583if(!len || !isdigit(line[len -1])) 584return0; 585 p = line + len -1; 586 587/* Fractional seconds. */ 588while(p > line &&isdigit(*p)) 589 p--; 590if(*p !='.') 591return0; 592 593/* Hours, minutes, and whole seconds. */ 594 n =short_time_len(line, p - line); 595if(!n) 596return0; 597 598return line + len - p + n; 599} 600 601static size_ttrailing_spaces_len(const char*line,size_t len) 602{ 603const char*p; 604 605/* Expected format: ' ' x (1 or more) */ 606if(!len || line[len -1] !=' ') 607return0; 608 609 p = line + len; 610while(p != line) { 611 p--; 612if(*p !=' ') 613return line + len - (p +1); 614} 615 616/* All spaces! */ 617return len; 618} 619 620static size_tdiff_timestamp_len(const char*line,size_t len) 621{ 622const char*end = line + len; 623size_t n; 624 625/* 626 * Posix: 2010-07-05 19:41:17 627 * GNU: 2010-07-05 19:41:17.620000023 -0500 628 */ 629 630if(!isdigit(end[-1])) 631return0; 632 633 n =sane_tz_len(line, end - line); 634if(!n) 635 n =tz_with_colon_len(line, end - line); 636 end -= n; 637 638 n =short_time_len(line, end - line); 639if(!n) 640 n =fractional_time_len(line, end - line); 641 end -= n; 642 643 n =date_len(line, end - line); 644if(!n)/* No date. Too bad. */ 645return0; 646 end -= n; 647 648if(end == line)/* No space before date. */ 649return0; 650if(end[-1] =='\t') {/* Success! */ 651 end--; 652return line + len - end; 653} 654if(end[-1] !=' ')/* No space before date. */ 655return0; 656 657/* Whitespace damage. */ 658 end -=trailing_spaces_len(line, end - line); 659return line + len - end; 660} 661 662static char*find_name_common(const char*line,const char*def, 663int p_value,const char*end,int terminate) 664{ 665int len; 666const char*start = NULL; 667 668if(p_value ==0) 669 start = line; 670while(line != end) { 671char c = *line; 672 673if(!end &&isspace(c)) { 674if(c =='\n') 675break; 676if(name_terminate(start, line-start, c, terminate)) 677break; 678} 679 line++; 680if(c =='/'&& !--p_value) 681 start = line; 682} 683if(!start) 684returnsquash_slash(xstrdup_or_null(def)); 685 len = line - start; 686if(!len) 687returnsquash_slash(xstrdup_or_null(def)); 688 689/* 690 * Generally we prefer the shorter name, especially 691 * if the other one is just a variation of that with 692 * something else tacked on to the end (ie "file.orig" 693 * or "file~"). 694 */ 695if(def) { 696int deflen =strlen(def); 697if(deflen < len && !strncmp(start, def, deflen)) 698returnsquash_slash(xstrdup(def)); 699} 700 701if(root.len) { 702char*ret =xstrfmt("%s%.*s", root.buf, len, start); 703returnsquash_slash(ret); 704} 705 706returnsquash_slash(xmemdupz(start, len)); 707} 708 709static char*find_name(const char*line,char*def,int p_value,int terminate) 710{ 711if(*line =='"') { 712char*name =find_name_gnu(line, def, p_value); 713if(name) 714return name; 715} 716 717returnfind_name_common(line, def, p_value, NULL, terminate); 718} 719 720static char*find_name_traditional(const char*line,char*def,int p_value) 721{ 722size_t len; 723size_t date_len; 724 725if(*line =='"') { 726char*name =find_name_gnu(line, def, p_value); 727if(name) 728return name; 729} 730 731 len =strchrnul(line,'\n') - line; 732 date_len =diff_timestamp_len(line, len); 733if(!date_len) 734returnfind_name_common(line, def, p_value, NULL, TERM_TAB); 735 len -= date_len; 736 737returnfind_name_common(line, def, p_value, line + len,0); 738} 739 740static intcount_slashes(const char*cp) 741{ 742int cnt =0; 743char ch; 744 745while((ch = *cp++)) 746if(ch =='/') 747 cnt++; 748return cnt; 749} 750 751/* 752 * Given the string after "--- " or "+++ ", guess the appropriate 753 * p_value for the given patch. 754 */ 755static intguess_p_value(struct apply_state *state,const char*nameline) 756{ 757char*name, *cp; 758int val = -1; 759 760if(is_dev_null(nameline)) 761return-1; 762 name =find_name_traditional(nameline, NULL,0); 763if(!name) 764return-1; 765 cp =strchr(name,'/'); 766if(!cp) 767 val =0; 768else if(state->prefix) { 769/* 770 * Does it begin with "a/$our-prefix" and such? Then this is 771 * very likely to apply to our directory. 772 */ 773if(!strncmp(name, state->prefix, state->prefix_length)) 774 val =count_slashes(state->prefix); 775else{ 776 cp++; 777if(!strncmp(cp, state->prefix, state->prefix_length)) 778 val =count_slashes(state->prefix) +1; 779} 780} 781free(name); 782return val; 783} 784 785/* 786 * Does the ---/+++ line have the POSIX timestamp after the last HT? 787 * GNU diff puts epoch there to signal a creation/deletion event. Is 788 * this such a timestamp? 789 */ 790static inthas_epoch_timestamp(const char*nameline) 791{ 792/* 793 * We are only interested in epoch timestamp; any non-zero 794 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 795 * For the same reason, the date must be either 1969-12-31 or 796 * 1970-01-01, and the seconds part must be "00". 797 */ 798const char stamp_regexp[] = 799"^(1969-12-31|1970-01-01)" 800" " 801"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 802" " 803"([-+][0-2][0-9]:?[0-5][0-9])\n"; 804const char*timestamp = NULL, *cp, *colon; 805static regex_t *stamp; 806 regmatch_t m[10]; 807int zoneoffset; 808int hourminute; 809int status; 810 811for(cp = nameline; *cp !='\n'; cp++) { 812if(*cp =='\t') 813 timestamp = cp +1; 814} 815if(!timestamp) 816return0; 817if(!stamp) { 818 stamp =xmalloc(sizeof(*stamp)); 819if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 820warning(_("Cannot prepare timestamp regexp%s"), 821 stamp_regexp); 822return0; 823} 824} 825 826 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 827if(status) { 828if(status != REG_NOMATCH) 829warning(_("regexec returned%dfor input:%s"), 830 status, timestamp); 831return0; 832} 833 834 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 835if(*colon ==':') 836 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 837else 838 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 839if(timestamp[m[3].rm_so] =='-') 840 zoneoffset = -zoneoffset; 841 842/* 843 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 844 * (west of GMT) or 1970-01-01 (east of GMT) 845 */ 846if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 847(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 848return0; 849 850 hourminute = (strtol(timestamp +11, NULL,10) *60+ 851strtol(timestamp +14, NULL,10) - 852 zoneoffset); 853 854return((zoneoffset <0&& hourminute ==1440) || 855(0<= zoneoffset && !hourminute)); 856} 857 858/* 859 * Get the name etc info from the ---/+++ lines of a traditional patch header 860 * 861 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 862 * files, we can happily check the index for a match, but for creating a 863 * new file we should try to match whatever "patch" does. I have no idea. 864 */ 865static voidparse_traditional_patch(struct apply_state *state, 866const char*first, 867const char*second, 868struct patch *patch) 869{ 870char*name; 871 872 first +=4;/* skip "--- " */ 873 second +=4;/* skip "+++ " */ 874if(!p_value_known) { 875int p, q; 876 p =guess_p_value(state, first); 877 q =guess_p_value(state, second); 878if(p <0) p = q; 879if(0<= p && p == q) { 880 state_p_value = p; 881 p_value_known =1; 882} 883} 884if(is_dev_null(first)) { 885 patch->is_new =1; 886 patch->is_delete =0; 887 name =find_name_traditional(second, NULL, state_p_value); 888 patch->new_name = name; 889}else if(is_dev_null(second)) { 890 patch->is_new =0; 891 patch->is_delete =1; 892 name =find_name_traditional(first, NULL, state_p_value); 893 patch->old_name = name; 894}else{ 895char*first_name; 896 first_name =find_name_traditional(first, NULL, state_p_value); 897 name =find_name_traditional(second, first_name, state_p_value); 898free(first_name); 899if(has_epoch_timestamp(first)) { 900 patch->is_new =1; 901 patch->is_delete =0; 902 patch->new_name = name; 903}else if(has_epoch_timestamp(second)) { 904 patch->is_new =0; 905 patch->is_delete =1; 906 patch->old_name = name; 907}else{ 908 patch->old_name = name; 909 patch->new_name =xstrdup_or_null(name); 910} 911} 912if(!name) 913die(_("unable to find filename in patch at line%d"), state_linenr); 914} 915 916static intgitdiff_hdrend(const char*line,struct patch *patch) 917{ 918return-1; 919} 920 921/* 922 * We're anal about diff header consistency, to make 923 * sure that we don't end up having strange ambiguous 924 * patches floating around. 925 * 926 * As a result, gitdiff_{old|new}name() will check 927 * their names against any previous information, just 928 * to make sure.. 929 */ 930#define DIFF_OLD_NAME 0 931#define DIFF_NEW_NAME 1 932 933static voidgitdiff_verify_name(const char*line,int isnull,char**name,int side) 934{ 935if(!*name && !isnull) { 936*name =find_name(line, NULL, state_p_value, TERM_TAB); 937return; 938} 939 940if(*name) { 941int len =strlen(*name); 942char*another; 943if(isnull) 944die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 945*name, state_linenr); 946 another =find_name(line, NULL, state_p_value, TERM_TAB); 947if(!another ||memcmp(another, *name, len +1)) 948die((side == DIFF_NEW_NAME) ? 949_("git apply: bad git-diff - inconsistent new filename on line%d") : 950_("git apply: bad git-diff - inconsistent old filename on line%d"), state_linenr); 951free(another); 952}else{ 953/* expect "/dev/null" */ 954if(memcmp("/dev/null", line,9) || line[9] !='\n') 955die(_("git apply: bad git-diff - expected /dev/null on line%d"), state_linenr); 956} 957} 958 959static intgitdiff_oldname(const char*line,struct patch *patch) 960{ 961gitdiff_verify_name(line, patch->is_new, &patch->old_name, 962 DIFF_OLD_NAME); 963return0; 964} 965 966static intgitdiff_newname(const char*line,struct patch *patch) 967{ 968gitdiff_verify_name(line, patch->is_delete, &patch->new_name, 969 DIFF_NEW_NAME); 970return0; 971} 972 973static intgitdiff_oldmode(const char*line,struct patch *patch) 974{ 975 patch->old_mode =strtoul(line, NULL,8); 976return0; 977} 978 979static intgitdiff_newmode(const char*line,struct patch *patch) 980{ 981 patch->new_mode =strtoul(line, NULL,8); 982return0; 983} 984 985static intgitdiff_delete(const char*line,struct patch *patch) 986{ 987 patch->is_delete =1; 988free(patch->old_name); 989 patch->old_name =xstrdup_or_null(patch->def_name); 990returngitdiff_oldmode(line, patch); 991} 992 993static intgitdiff_newfile(const char*line,struct patch *patch) 994{ 995 patch->is_new =1; 996free(patch->new_name); 997 patch->new_name =xstrdup_or_null(patch->def_name); 998returngitdiff_newmode(line, patch); 999}10001001static intgitdiff_copysrc(const char*line,struct patch *patch)1002{1003 patch->is_copy =1;1004free(patch->old_name);1005 patch->old_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1006return0;1007}10081009static intgitdiff_copydst(const char*line,struct patch *patch)1010{1011 patch->is_copy =1;1012free(patch->new_name);1013 patch->new_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1014return0;1015}10161017static intgitdiff_renamesrc(const char*line,struct patch *patch)1018{1019 patch->is_rename =1;1020free(patch->old_name);1021 patch->old_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1022return0;1023}10241025static intgitdiff_renamedst(const char*line,struct patch *patch)1026{1027 patch->is_rename =1;1028free(patch->new_name);1029 patch->new_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1030return0;1031}10321033static intgitdiff_similarity(const char*line,struct patch *patch)1034{1035unsigned long val =strtoul(line, NULL,10);1036if(val <=100)1037 patch->score = val;1038return0;1039}10401041static intgitdiff_dissimilarity(const char*line,struct patch *patch)1042{1043unsigned long val =strtoul(line, NULL,10);1044if(val <=100)1045 patch->score = val;1046return0;1047}10481049static intgitdiff_index(const char*line,struct patch *patch)1050{1051/*1052 * index line is N hexadecimal, "..", N hexadecimal,1053 * and optional space with octal mode.1054 */1055const char*ptr, *eol;1056int len;10571058 ptr =strchr(line,'.');1059if(!ptr || ptr[1] !='.'||40< ptr - line)1060return0;1061 len = ptr - line;1062memcpy(patch->old_sha1_prefix, line, len);1063 patch->old_sha1_prefix[len] =0;10641065 line = ptr +2;1066 ptr =strchr(line,' ');1067 eol =strchrnul(line,'\n');10681069if(!ptr || eol < ptr)1070 ptr = eol;1071 len = ptr - line;10721073if(40< len)1074return0;1075memcpy(patch->new_sha1_prefix, line, len);1076 patch->new_sha1_prefix[len] =0;1077if(*ptr ==' ')1078 patch->old_mode =strtoul(ptr+1, NULL,8);1079return0;1080}10811082/*1083 * This is normal for a diff that doesn't change anything: we'll fall through1084 * into the next diff. Tell the parser to break out.1085 */1086static intgitdiff_unrecognized(const char*line,struct patch *patch)1087{1088return-1;1089}10901091/*1092 * Skip p_value leading components from "line"; as we do not accept1093 * absolute paths, return NULL in that case.1094 */1095static const char*skip_tree_prefix(const char*line,int llen)1096{1097int nslash;1098int i;10991100if(!state_p_value)1101return(llen && line[0] =='/') ? NULL : line;11021103 nslash = state_p_value;1104for(i =0; i < llen; i++) {1105int ch = line[i];1106if(ch =='/'&& --nslash <=0)1107return(i ==0) ? NULL : &line[i +1];1108}1109return NULL;1110}11111112/*1113 * This is to extract the same name that appears on "diff --git"1114 * line. We do not find and return anything if it is a rename1115 * patch, and it is OK because we will find the name elsewhere.1116 * We need to reliably find name only when it is mode-change only,1117 * creation or deletion of an empty file. In any of these cases,1118 * both sides are the same name under a/ and b/ respectively.1119 */1120static char*git_header_name(const char*line,int llen)1121{1122const char*name;1123const char*second = NULL;1124size_t len, line_len;11251126 line +=strlen("diff --git ");1127 llen -=strlen("diff --git ");11281129if(*line =='"') {1130const char*cp;1131struct strbuf first = STRBUF_INIT;1132struct strbuf sp = STRBUF_INIT;11331134if(unquote_c_style(&first, line, &second))1135goto free_and_fail1;11361137/* strip the a/b prefix including trailing slash */1138 cp =skip_tree_prefix(first.buf, first.len);1139if(!cp)1140goto free_and_fail1;1141strbuf_remove(&first,0, cp - first.buf);11421143/*1144 * second points at one past closing dq of name.1145 * find the second name.1146 */1147while((second < line + llen) &&isspace(*second))1148 second++;11491150if(line + llen <= second)1151goto free_and_fail1;1152if(*second =='"') {1153if(unquote_c_style(&sp, second, NULL))1154goto free_and_fail1;1155 cp =skip_tree_prefix(sp.buf, sp.len);1156if(!cp)1157goto free_and_fail1;1158/* They must match, otherwise ignore */1159if(strcmp(cp, first.buf))1160goto free_and_fail1;1161strbuf_release(&sp);1162returnstrbuf_detach(&first, NULL);1163}11641165/* unquoted second */1166 cp =skip_tree_prefix(second, line + llen - second);1167if(!cp)1168goto free_and_fail1;1169if(line + llen - cp != first.len ||1170memcmp(first.buf, cp, first.len))1171goto free_and_fail1;1172returnstrbuf_detach(&first, NULL);11731174 free_and_fail1:1175strbuf_release(&first);1176strbuf_release(&sp);1177return NULL;1178}11791180/* unquoted first name */1181 name =skip_tree_prefix(line, llen);1182if(!name)1183return NULL;11841185/*1186 * since the first name is unquoted, a dq if exists must be1187 * the beginning of the second name.1188 */1189for(second = name; second < line + llen; second++) {1190if(*second =='"') {1191struct strbuf sp = STRBUF_INIT;1192const char*np;11931194if(unquote_c_style(&sp, second, NULL))1195goto free_and_fail2;11961197 np =skip_tree_prefix(sp.buf, sp.len);1198if(!np)1199goto free_and_fail2;12001201 len = sp.buf + sp.len - np;1202if(len < second - name &&1203!strncmp(np, name, len) &&1204isspace(name[len])) {1205/* Good */1206strbuf_remove(&sp,0, np - sp.buf);1207returnstrbuf_detach(&sp, NULL);1208}12091210 free_and_fail2:1211strbuf_release(&sp);1212return NULL;1213}1214}12151216/*1217 * Accept a name only if it shows up twice, exactly the same1218 * form.1219 */1220 second =strchr(name,'\n');1221if(!second)1222return NULL;1223 line_len = second - name;1224for(len =0; ; len++) {1225switch(name[len]) {1226default:1227continue;1228case'\n':1229return NULL;1230case'\t':case' ':1231/*1232 * Is this the separator between the preimage1233 * and the postimage pathname? Again, we are1234 * only interested in the case where there is1235 * no rename, as this is only to set def_name1236 * and a rename patch has the names elsewhere1237 * in an unambiguous form.1238 */1239if(!name[len +1])1240return NULL;/* no postimage name */1241 second =skip_tree_prefix(name + len +1,1242 line_len - (len +1));1243if(!second)1244return NULL;1245/*1246 * Does len bytes starting at "name" and "second"1247 * (that are separated by one HT or SP we just1248 * found) exactly match?1249 */1250if(second[len] =='\n'&& !strncmp(name, second, len))1251returnxmemdupz(name, len);1252}1253}1254}12551256/* Verify that we recognize the lines following a git header */1257static intparse_git_header(const char*line,int len,unsigned int size,struct patch *patch)1258{1259unsigned long offset;12601261/* A git diff has explicit new/delete information, so we don't guess */1262 patch->is_new =0;1263 patch->is_delete =0;12641265/*1266 * Some things may not have the old name in the1267 * rest of the headers anywhere (pure mode changes,1268 * or removing or adding empty files), so we get1269 * the default name from the header.1270 */1271 patch->def_name =git_header_name(line, len);1272if(patch->def_name && root.len) {1273char*s =xstrfmt("%s%s", root.buf, patch->def_name);1274free(patch->def_name);1275 patch->def_name = s;1276}12771278 line += len;1279 size -= len;1280 state_linenr++;1281for(offset = len ; size >0; offset += len, size -= len, line += len, state_linenr++) {1282static const struct opentry {1283const char*str;1284int(*fn)(const char*,struct patch *);1285} optable[] = {1286{"@@ -", gitdiff_hdrend },1287{"--- ", gitdiff_oldname },1288{"+++ ", gitdiff_newname },1289{"old mode ", gitdiff_oldmode },1290{"new mode ", gitdiff_newmode },1291{"deleted file mode ", gitdiff_delete },1292{"new file mode ", gitdiff_newfile },1293{"copy from ", gitdiff_copysrc },1294{"copy to ", gitdiff_copydst },1295{"rename old ", gitdiff_renamesrc },1296{"rename new ", gitdiff_renamedst },1297{"rename from ", gitdiff_renamesrc },1298{"rename to ", gitdiff_renamedst },1299{"similarity index ", gitdiff_similarity },1300{"dissimilarity index ", gitdiff_dissimilarity },1301{"index ", gitdiff_index },1302{"", gitdiff_unrecognized },1303};1304int i;13051306 len =linelen(line, size);1307if(!len || line[len-1] !='\n')1308break;1309for(i =0; i <ARRAY_SIZE(optable); i++) {1310const struct opentry *p = optable + i;1311int oplen =strlen(p->str);1312if(len < oplen ||memcmp(p->str, line, oplen))1313continue;1314if(p->fn(line + oplen, patch) <0)1315return offset;1316break;1317}1318}13191320return offset;1321}13221323static intparse_num(const char*line,unsigned long*p)1324{1325char*ptr;13261327if(!isdigit(*line))1328return0;1329*p =strtoul(line, &ptr,10);1330return ptr - line;1331}13321333static intparse_range(const char*line,int len,int offset,const char*expect,1334unsigned long*p1,unsigned long*p2)1335{1336int digits, ex;13371338if(offset <0|| offset >= len)1339return-1;1340 line += offset;1341 len -= offset;13421343 digits =parse_num(line, p1);1344if(!digits)1345return-1;13461347 offset += digits;1348 line += digits;1349 len -= digits;13501351*p2 =1;1352if(*line ==',') {1353 digits =parse_num(line+1, p2);1354if(!digits)1355return-1;13561357 offset += digits+1;1358 line += digits+1;1359 len -= digits+1;1360}13611362 ex =strlen(expect);1363if(ex > len)1364return-1;1365if(memcmp(line, expect, ex))1366return-1;13671368return offset + ex;1369}13701371static voidrecount_diff(const char*line,int size,struct fragment *fragment)1372{1373int oldlines =0, newlines =0, ret =0;13741375if(size <1) {1376warning("recount: ignore empty hunk");1377return;1378}13791380for(;;) {1381int len =linelen(line, size);1382 size -= len;1383 line += len;13841385if(size <1)1386break;13871388switch(*line) {1389case' ':case'\n':1390 newlines++;1391/* fall through */1392case'-':1393 oldlines++;1394continue;1395case'+':1396 newlines++;1397continue;1398case'\\':1399continue;1400case'@':1401 ret = size <3|| !starts_with(line,"@@ ");1402break;1403case'd':1404 ret = size <5|| !starts_with(line,"diff ");1405break;1406default:1407 ret = -1;1408break;1409}1410if(ret) {1411warning(_("recount: unexpected line: %.*s"),1412(int)linelen(line, size), line);1413return;1414}1415break;1416}1417 fragment->oldlines = oldlines;1418 fragment->newlines = newlines;1419}14201421/*1422 * Parse a unified diff fragment header of the1423 * form "@@ -a,b +c,d @@"1424 */1425static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1426{1427int offset;14281429if(!len || line[len-1] !='\n')1430return-1;14311432/* Figure out the number of lines in a fragment */1433 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1434 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14351436return offset;1437}14381439static intfind_header(struct apply_state *state,1440const char*line,1441unsigned long size,1442int*hdrsize,1443struct patch *patch)1444{1445unsigned long offset, len;14461447 patch->is_toplevel_relative =0;1448 patch->is_rename = patch->is_copy =0;1449 patch->is_new = patch->is_delete = -1;1450 patch->old_mode = patch->new_mode =0;1451 patch->old_name = patch->new_name = NULL;1452for(offset =0; size >0; offset += len, size -= len, line += len, state_linenr++) {1453unsigned long nextlen;14541455 len =linelen(line, size);1456if(!len)1457break;14581459/* Testing this early allows us to take a few shortcuts.. */1460if(len <6)1461continue;14621463/*1464 * Make sure we don't find any unconnected patch fragments.1465 * That's a sign that we didn't find a header, and that a1466 * patch has become corrupted/broken up.1467 */1468if(!memcmp("@@ -", line,4)) {1469struct fragment dummy;1470if(parse_fragment_header(line, len, &dummy) <0)1471continue;1472die(_("patch fragment without header at line%d: %.*s"),1473 state_linenr, (int)len-1, line);1474}14751476if(size < len +6)1477break;14781479/*1480 * Git patch? It might not have a real patch, just a rename1481 * or mode change, so we handle that specially1482 */1483if(!memcmp("diff --git ", line,11)) {1484int git_hdr_len =parse_git_header(line, len, size, patch);1485if(git_hdr_len <= len)1486continue;1487if(!patch->old_name && !patch->new_name) {1488if(!patch->def_name)1489die(Q_("git diff header lacks filename information when removing "1490"%dleading pathname component (line%d)",1491"git diff header lacks filename information when removing "1492"%dleading pathname components (line%d)",1493 state_p_value),1494 state_p_value, state_linenr);1495 patch->old_name =xstrdup(patch->def_name);1496 patch->new_name =xstrdup(patch->def_name);1497}1498if(!patch->is_delete && !patch->new_name)1499die("git diff header lacks filename information "1500"(line%d)", state_linenr);1501 patch->is_toplevel_relative =1;1502*hdrsize = git_hdr_len;1503return offset;1504}15051506/* --- followed by +++ ? */1507if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1508continue;15091510/*1511 * We only accept unified patches, so we want it to1512 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1513 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1514 */1515 nextlen =linelen(line + len, size - len);1516if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1517continue;15181519/* Ok, we'll consider it a patch */1520parse_traditional_patch(state, line, line+len, patch);1521*hdrsize = len + nextlen;1522 state_linenr +=2;1523return offset;1524}1525return-1;1526}15271528static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1529{1530char*err;15311532if(!result)1533return;15341535 whitespace_error++;1536if(squelch_whitespace_errors &&1537 squelch_whitespace_errors < whitespace_error)1538return;15391540 err =whitespace_error_string(result);1541fprintf(stderr,"%s:%d:%s.\n%.*s\n",1542 patch_input_file, linenr, err, len, line);1543free(err);1544}15451546static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1547{1548unsigned result =ws_check(line +1, len -1, ws_rule);15491550record_ws_error(result, line +1, len -2, state_linenr);1551}15521553/*1554 * Parse a unified diff. Note that this really needs to parse each1555 * fragment separately, since the only way to know the difference1556 * between a "---" that is part of a patch, and a "---" that starts1557 * the next patch is to look at the line counts..1558 */1559static intparse_fragment(struct apply_state *state,1560const char*line,1561unsigned long size,1562struct patch *patch,1563struct fragment *fragment)1564{1565int added, deleted;1566int len =linelen(line, size), offset;1567unsigned long oldlines, newlines;1568unsigned long leading, trailing;15691570 offset =parse_fragment_header(line, len, fragment);1571if(offset <0)1572return-1;1573if(offset >0&& patch->recount)1574recount_diff(line + offset, size - offset, fragment);1575 oldlines = fragment->oldlines;1576 newlines = fragment->newlines;1577 leading =0;1578 trailing =0;15791580/* Parse the thing.. */1581 line += len;1582 size -= len;1583 state_linenr++;1584 added = deleted =0;1585for(offset = len;15860< size;1587 offset += len, size -= len, line += len, state_linenr++) {1588if(!oldlines && !newlines)1589break;1590 len =linelen(line, size);1591if(!len || line[len-1] !='\n')1592return-1;1593switch(*line) {1594default:1595return-1;1596case'\n':/* newer GNU diff, an empty context line */1597case' ':1598 oldlines--;1599 newlines--;1600if(!deleted && !added)1601 leading++;1602 trailing++;1603if(!state->apply_in_reverse &&1604 ws_error_action == correct_ws_error)1605check_whitespace(line, len, patch->ws_rule);1606break;1607case'-':1608if(state->apply_in_reverse &&1609 ws_error_action != nowarn_ws_error)1610check_whitespace(line, len, patch->ws_rule);1611 deleted++;1612 oldlines--;1613 trailing =0;1614break;1615case'+':1616if(!state->apply_in_reverse &&1617 ws_error_action != nowarn_ws_error)1618check_whitespace(line, len, patch->ws_rule);1619 added++;1620 newlines--;1621 trailing =0;1622break;16231624/*1625 * We allow "\ No newline at end of file". Depending1626 * on locale settings when the patch was produced we1627 * don't know what this line looks like. The only1628 * thing we do know is that it begins with "\ ".1629 * Checking for 12 is just for sanity check -- any1630 * l10n of "\ No newline..." is at least that long.1631 */1632case'\\':1633if(len <12||memcmp(line,"\\",2))1634return-1;1635break;1636}1637}1638if(oldlines || newlines)1639return-1;1640if(!deleted && !added)1641return-1;16421643 fragment->leading = leading;1644 fragment->trailing = trailing;16451646/*1647 * If a fragment ends with an incomplete line, we failed to include1648 * it in the above loop because we hit oldlines == newlines == 01649 * before seeing it.1650 */1651if(12< size && !memcmp(line,"\\",2))1652 offset +=linelen(line, size);16531654 patch->lines_added += added;1655 patch->lines_deleted += deleted;16561657if(0< patch->is_new && oldlines)1658returnerror(_("new file depends on old contents"));1659if(0< patch->is_delete && newlines)1660returnerror(_("deleted file still has contents"));1661return offset;1662}16631664/*1665 * We have seen "diff --git a/... b/..." header (or a traditional patch1666 * header). Read hunks that belong to this patch into fragments and hang1667 * them to the given patch structure.1668 *1669 * The (fragment->patch, fragment->size) pair points into the memory given1670 * by the caller, not a copy, when we return.1671 */1672static intparse_single_patch(struct apply_state *state,1673const char*line,1674unsigned long size,1675struct patch *patch)1676{1677unsigned long offset =0;1678unsigned long oldlines =0, newlines =0, context =0;1679struct fragment **fragp = &patch->fragments;16801681while(size >4&& !memcmp(line,"@@ -",4)) {1682struct fragment *fragment;1683int len;16841685 fragment =xcalloc(1,sizeof(*fragment));1686 fragment->linenr = state_linenr;1687 len =parse_fragment(state, line, size, patch, fragment);1688if(len <=0)1689die(_("corrupt patch at line%d"), state_linenr);1690 fragment->patch = line;1691 fragment->size = len;1692 oldlines += fragment->oldlines;1693 newlines += fragment->newlines;1694 context += fragment->leading + fragment->trailing;16951696*fragp = fragment;1697 fragp = &fragment->next;16981699 offset += len;1700 line += len;1701 size -= len;1702}17031704/*1705 * If something was removed (i.e. we have old-lines) it cannot1706 * be creation, and if something was added it cannot be1707 * deletion. However, the reverse is not true; --unified=01708 * patches that only add are not necessarily creation even1709 * though they do not have any old lines, and ones that only1710 * delete are not necessarily deletion.1711 *1712 * Unfortunately, a real creation/deletion patch do _not_ have1713 * any context line by definition, so we cannot safely tell it1714 * apart with --unified=0 insanity. At least if the patch has1715 * more than one hunk it is not creation or deletion.1716 */1717if(patch->is_new <0&&1718(oldlines || (patch->fragments && patch->fragments->next)))1719 patch->is_new =0;1720if(patch->is_delete <0&&1721(newlines || (patch->fragments && patch->fragments->next)))1722 patch->is_delete =0;17231724if(0< patch->is_new && oldlines)1725die(_("new file%sdepends on old contents"), patch->new_name);1726if(0< patch->is_delete && newlines)1727die(_("deleted file%sstill has contents"), patch->old_name);1728if(!patch->is_delete && !newlines && context)1729fprintf_ln(stderr,1730_("** warning: "1731"file%sbecomes empty but is not deleted"),1732 patch->new_name);17331734return offset;1735}17361737staticinlineintmetadata_changes(struct patch *patch)1738{1739return patch->is_rename >0||1740 patch->is_copy >0||1741 patch->is_new >0||1742 patch->is_delete ||1743(patch->old_mode && patch->new_mode &&1744 patch->old_mode != patch->new_mode);1745}17461747static char*inflate_it(const void*data,unsigned long size,1748unsigned long inflated_size)1749{1750 git_zstream stream;1751void*out;1752int st;17531754memset(&stream,0,sizeof(stream));17551756 stream.next_in = (unsigned char*)data;1757 stream.avail_in = size;1758 stream.next_out = out =xmalloc(inflated_size);1759 stream.avail_out = inflated_size;1760git_inflate_init(&stream);1761 st =git_inflate(&stream, Z_FINISH);1762git_inflate_end(&stream);1763if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1764free(out);1765return NULL;1766}1767return out;1768}17691770/*1771 * Read a binary hunk and return a new fragment; fragment->patch1772 * points at an allocated memory that the caller must free, so1773 * it is marked as "->free_patch = 1".1774 */1775static struct fragment *parse_binary_hunk(char**buf_p,1776unsigned long*sz_p,1777int*status_p,1778int*used_p)1779{1780/*1781 * Expect a line that begins with binary patch method ("literal"1782 * or "delta"), followed by the length of data before deflating.1783 * a sequence of 'length-byte' followed by base-85 encoded data1784 * should follow, terminated by a newline.1785 *1786 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1787 * and we would limit the patch line to 66 characters,1788 * so one line can fit up to 13 groups that would decode1789 * to 52 bytes max. The length byte 'A'-'Z' corresponds1790 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1791 */1792int llen, used;1793unsigned long size = *sz_p;1794char*buffer = *buf_p;1795int patch_method;1796unsigned long origlen;1797char*data = NULL;1798int hunk_size =0;1799struct fragment *frag;18001801 llen =linelen(buffer, size);1802 used = llen;18031804*status_p =0;18051806if(starts_with(buffer,"delta ")) {1807 patch_method = BINARY_DELTA_DEFLATED;1808 origlen =strtoul(buffer +6, NULL,10);1809}1810else if(starts_with(buffer,"literal ")) {1811 patch_method = BINARY_LITERAL_DEFLATED;1812 origlen =strtoul(buffer +8, NULL,10);1813}1814else1815return NULL;18161817 state_linenr++;1818 buffer += llen;1819while(1) {1820int byte_length, max_byte_length, newsize;1821 llen =linelen(buffer, size);1822 used += llen;1823 state_linenr++;1824if(llen ==1) {1825/* consume the blank line */1826 buffer++;1827 size--;1828break;1829}1830/*1831 * Minimum line is "A00000\n" which is 7-byte long,1832 * and the line length must be multiple of 5 plus 2.1833 */1834if((llen <7) || (llen-2) %5)1835goto corrupt;1836 max_byte_length = (llen -2) /5*4;1837 byte_length = *buffer;1838if('A'<= byte_length && byte_length <='Z')1839 byte_length = byte_length -'A'+1;1840else if('a'<= byte_length && byte_length <='z')1841 byte_length = byte_length -'a'+27;1842else1843goto corrupt;1844/* if the input length was not multiple of 4, we would1845 * have filler at the end but the filler should never1846 * exceed 3 bytes1847 */1848if(max_byte_length < byte_length ||1849 byte_length <= max_byte_length -4)1850goto corrupt;1851 newsize = hunk_size + byte_length;1852 data =xrealloc(data, newsize);1853if(decode_85(data + hunk_size, buffer +1, byte_length))1854goto corrupt;1855 hunk_size = newsize;1856 buffer += llen;1857 size -= llen;1858}18591860 frag =xcalloc(1,sizeof(*frag));1861 frag->patch =inflate_it(data, hunk_size, origlen);1862 frag->free_patch =1;1863if(!frag->patch)1864goto corrupt;1865free(data);1866 frag->size = origlen;1867*buf_p = buffer;1868*sz_p = size;1869*used_p = used;1870 frag->binary_patch_method = patch_method;1871return frag;18721873 corrupt:1874free(data);1875*status_p = -1;1876error(_("corrupt binary patch at line%d: %.*s"),1877 state_linenr-1, llen-1, buffer);1878return NULL;1879}18801881/*1882 * Returns:1883 * -1 in case of error,1884 * the length of the parsed binary patch otherwise1885 */1886static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1887{1888/*1889 * We have read "GIT binary patch\n"; what follows is a line1890 * that says the patch method (currently, either "literal" or1891 * "delta") and the length of data before deflating; a1892 * sequence of 'length-byte' followed by base-85 encoded data1893 * follows.1894 *1895 * When a binary patch is reversible, there is another binary1896 * hunk in the same format, starting with patch method (either1897 * "literal" or "delta") with the length of data, and a sequence1898 * of length-byte + base-85 encoded data, terminated with another1899 * empty line. This data, when applied to the postimage, produces1900 * the preimage.1901 */1902struct fragment *forward;1903struct fragment *reverse;1904int status;1905int used, used_1;19061907 forward =parse_binary_hunk(&buffer, &size, &status, &used);1908if(!forward && !status)1909/* there has to be one hunk (forward hunk) */1910returnerror(_("unrecognized binary patch at line%d"), state_linenr-1);1911if(status)1912/* otherwise we already gave an error message */1913return status;19141915 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1916if(reverse)1917 used += used_1;1918else if(status) {1919/*1920 * Not having reverse hunk is not an error, but having1921 * a corrupt reverse hunk is.1922 */1923free((void*) forward->patch);1924free(forward);1925return status;1926}1927 forward->next = reverse;1928 patch->fragments = forward;1929 patch->is_binary =1;1930return used;1931}19321933static voidprefix_one(struct apply_state *state,char**name)1934{1935char*old_name = *name;1936if(!old_name)1937return;1938*name =xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));1939free(old_name);1940}19411942static voidprefix_patch(struct apply_state *state,struct patch *p)1943{1944if(!state->prefix || p->is_toplevel_relative)1945return;1946prefix_one(state, &p->new_name);1947prefix_one(state, &p->old_name);1948}19491950/*1951 * include/exclude1952 */19531954static struct string_list limit_by_name;1955static int has_include;1956static voidadd_name_limit(const char*name,int exclude)1957{1958struct string_list_item *it;19591960 it =string_list_append(&limit_by_name, name);1961 it->util = exclude ? NULL : (void*)1;1962}19631964static intuse_patch(struct apply_state *state,struct patch *p)1965{1966const char*pathname = p->new_name ? p->new_name : p->old_name;1967int i;19681969/* Paths outside are not touched regardless of "--include" */1970if(0< state->prefix_length) {1971int pathlen =strlen(pathname);1972if(pathlen <= state->prefix_length ||1973memcmp(state->prefix, pathname, state->prefix_length))1974return0;1975}19761977/* See if it matches any of exclude/include rule */1978for(i =0; i < limit_by_name.nr; i++) {1979struct string_list_item *it = &limit_by_name.items[i];1980if(!wildmatch(it->string, pathname,0, NULL))1981return(it->util != NULL);1982}19831984/*1985 * If we had any include, a path that does not match any rule is1986 * not used. Otherwise, we saw bunch of exclude rules (or none)1987 * and such a path is used.1988 */1989return!has_include;1990}199119921993/*1994 * Read the patch text in "buffer" that extends for "size" bytes; stop1995 * reading after seeing a single patch (i.e. changes to a single file).1996 * Create fragments (i.e. patch hunks) and hang them to the given patch.1997 * Return the number of bytes consumed, so that the caller can call us1998 * again for the next patch.1999 */2000static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2001{2002int hdrsize, patchsize;2003int offset =find_header(state, buffer, size, &hdrsize, patch);20042005if(offset <0)2006return offset;20072008prefix_patch(state, patch);20092010if(!use_patch(state, patch))2011 patch->ws_rule =0;2012else2013 patch->ws_rule =whitespace_rule(patch->new_name2014? patch->new_name2015: patch->old_name);20162017 patchsize =parse_single_patch(state,2018 buffer + offset + hdrsize,2019 size - offset - hdrsize,2020 patch);20212022if(!patchsize) {2023static const char git_binary[] ="GIT binary patch\n";2024int hd = hdrsize + offset;2025unsigned long llen =linelen(buffer + hd, size - hd);20262027if(llen ==sizeof(git_binary) -1&&2028!memcmp(git_binary, buffer + hd, llen)) {2029int used;2030 state_linenr++;2031 used =parse_binary(buffer + hd + llen,2032 size - hd - llen, patch);2033if(used <0)2034return-1;2035if(used)2036 patchsize = used + llen;2037else2038 patchsize =0;2039}2040else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2041static const char*binhdr[] = {2042"Binary files ",2043"Files ",2044 NULL,2045};2046int i;2047for(i =0; binhdr[i]; i++) {2048int len =strlen(binhdr[i]);2049if(len < size - hd &&2050!memcmp(binhdr[i], buffer + hd, len)) {2051 state_linenr++;2052 patch->is_binary =1;2053 patchsize = llen;2054break;2055}2056}2057}20582059/* Empty patch cannot be applied if it is a text patch2060 * without metadata change. A binary patch appears2061 * empty to us here.2062 */2063if((apply || state->check) &&2064(!patch->is_binary && !metadata_changes(patch)))2065die(_("patch with only garbage at line%d"), state_linenr);2066}20672068return offset + hdrsize + patchsize;2069}20702071#define swap(a,b) myswap((a),(b),sizeof(a))20722073#define myswap(a, b, size) do { \2074 unsigned char mytmp[size]; \2075 memcpy(mytmp, &a, size); \2076 memcpy(&a, &b, size); \2077 memcpy(&b, mytmp, size); \2078} while (0)20792080static voidreverse_patches(struct patch *p)2081{2082for(; p; p = p->next) {2083struct fragment *frag = p->fragments;20842085swap(p->new_name, p->old_name);2086swap(p->new_mode, p->old_mode);2087swap(p->is_new, p->is_delete);2088swap(p->lines_added, p->lines_deleted);2089swap(p->old_sha1_prefix, p->new_sha1_prefix);20902091for(; frag; frag = frag->next) {2092swap(frag->newpos, frag->oldpos);2093swap(frag->newlines, frag->oldlines);2094}2095}2096}20972098static const char pluses[] =2099"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2100static const char minuses[]=2101"----------------------------------------------------------------------";21022103static voidshow_stats(struct patch *patch)2104{2105struct strbuf qname = STRBUF_INIT;2106char*cp = patch->new_name ? patch->new_name : patch->old_name;2107int max, add, del;21082109quote_c_style(cp, &qname, NULL,0);21102111/*2112 * "scale" the filename2113 */2114 max = max_len;2115if(max >50)2116 max =50;21172118if(qname.len > max) {2119 cp =strchr(qname.buf + qname.len +3- max,'/');2120if(!cp)2121 cp = qname.buf + qname.len +3- max;2122strbuf_splice(&qname,0, cp - qname.buf,"...",3);2123}21242125if(patch->is_binary) {2126printf(" %-*s | Bin\n", max, qname.buf);2127strbuf_release(&qname);2128return;2129}21302131printf(" %-*s |", max, qname.buf);2132strbuf_release(&qname);21332134/*2135 * scale the add/delete2136 */2137 max = max + max_change >70?70- max : max_change;2138 add = patch->lines_added;2139 del = patch->lines_deleted;21402141if(max_change >0) {2142int total = ((add + del) * max + max_change /2) / max_change;2143 add = (add * max + max_change /2) / max_change;2144 del = total - add;2145}2146printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2147 add, pluses, del, minuses);2148}21492150static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2151{2152switch(st->st_mode & S_IFMT) {2153case S_IFLNK:2154if(strbuf_readlink(buf, path, st->st_size) <0)2155returnerror(_("unable to read symlink%s"), path);2156return0;2157case S_IFREG:2158if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2159returnerror(_("unable to open or read%s"), path);2160convert_to_git(path, buf->buf, buf->len, buf,0);2161return0;2162default:2163return-1;2164}2165}21662167/*2168 * Update the preimage, and the common lines in postimage,2169 * from buffer buf of length len. If postlen is 0 the postimage2170 * is updated in place, otherwise it's updated on a new buffer2171 * of length postlen2172 */21732174static voidupdate_pre_post_images(struct image *preimage,2175struct image *postimage,2176char*buf,2177size_t len,size_t postlen)2178{2179int i, ctx, reduced;2180char*new, *old, *fixed;2181struct image fixed_preimage;21822183/*2184 * Update the preimage with whitespace fixes. Note that we2185 * are not losing preimage->buf -- apply_one_fragment() will2186 * free "oldlines".2187 */2188prepare_image(&fixed_preimage, buf, len,1);2189assert(postlen2190? fixed_preimage.nr == preimage->nr2191: fixed_preimage.nr <= preimage->nr);2192for(i =0; i < fixed_preimage.nr; i++)2193 fixed_preimage.line[i].flag = preimage->line[i].flag;2194free(preimage->line_allocated);2195*preimage = fixed_preimage;21962197/*2198 * Adjust the common context lines in postimage. This can be2199 * done in-place when we are shrinking it with whitespace2200 * fixing, but needs a new buffer when ignoring whitespace or2201 * expanding leading tabs to spaces.2202 *2203 * We trust the caller to tell us if the update can be done2204 * in place (postlen==0) or not.2205 */2206 old = postimage->buf;2207if(postlen)2208new= postimage->buf =xmalloc(postlen);2209else2210new= old;2211 fixed = preimage->buf;22122213for(i = reduced = ctx =0; i < postimage->nr; i++) {2214size_t l_len = postimage->line[i].len;2215if(!(postimage->line[i].flag & LINE_COMMON)) {2216/* an added line -- no counterparts in preimage */2217memmove(new, old, l_len);2218 old += l_len;2219new+= l_len;2220continue;2221}22222223/* a common context -- skip it in the original postimage */2224 old += l_len;22252226/* and find the corresponding one in the fixed preimage */2227while(ctx < preimage->nr &&2228!(preimage->line[ctx].flag & LINE_COMMON)) {2229 fixed += preimage->line[ctx].len;2230 ctx++;2231}22322233/*2234 * preimage is expected to run out, if the caller2235 * fixed addition of trailing blank lines.2236 */2237if(preimage->nr <= ctx) {2238 reduced++;2239continue;2240}22412242/* and copy it in, while fixing the line length */2243 l_len = preimage->line[ctx].len;2244memcpy(new, fixed, l_len);2245new+= l_len;2246 fixed += l_len;2247 postimage->line[i].len = l_len;2248 ctx++;2249}22502251if(postlen2252? postlen <new- postimage->buf2253: postimage->len <new- postimage->buf)2254die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2255(int)postlen, (int) postimage->len, (int)(new- postimage->buf));22562257/* Fix the length of the whole thing */2258 postimage->len =new- postimage->buf;2259 postimage->nr -= reduced;2260}22612262static intline_by_line_fuzzy_match(struct image *img,2263struct image *preimage,2264struct image *postimage,2265unsigned longtry,2266int try_lno,2267int preimage_limit)2268{2269int i;2270size_t imgoff =0;2271size_t preoff =0;2272size_t postlen = postimage->len;2273size_t extra_chars;2274char*buf;2275char*preimage_eof;2276char*preimage_end;2277struct strbuf fixed;2278char*fixed_buf;2279size_t fixed_len;22802281for(i =0; i < preimage_limit; i++) {2282size_t prelen = preimage->line[i].len;2283size_t imglen = img->line[try_lno+i].len;22842285if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2286 preimage->buf + preoff, prelen))2287return0;2288if(preimage->line[i].flag & LINE_COMMON)2289 postlen += imglen - prelen;2290 imgoff += imglen;2291 preoff += prelen;2292}22932294/*2295 * Ok, the preimage matches with whitespace fuzz.2296 *2297 * imgoff now holds the true length of the target that2298 * matches the preimage before the end of the file.2299 *2300 * Count the number of characters in the preimage that fall2301 * beyond the end of the file and make sure that all of them2302 * are whitespace characters. (This can only happen if2303 * we are removing blank lines at the end of the file.)2304 */2305 buf = preimage_eof = preimage->buf + preoff;2306for( ; i < preimage->nr; i++)2307 preoff += preimage->line[i].len;2308 preimage_end = preimage->buf + preoff;2309for( ; buf < preimage_end; buf++)2310if(!isspace(*buf))2311return0;23122313/*2314 * Update the preimage and the common postimage context2315 * lines to use the same whitespace as the target.2316 * If whitespace is missing in the target (i.e.2317 * if the preimage extends beyond the end of the file),2318 * use the whitespace from the preimage.2319 */2320 extra_chars = preimage_end - preimage_eof;2321strbuf_init(&fixed, imgoff + extra_chars);2322strbuf_add(&fixed, img->buf +try, imgoff);2323strbuf_add(&fixed, preimage_eof, extra_chars);2324 fixed_buf =strbuf_detach(&fixed, &fixed_len);2325update_pre_post_images(preimage, postimage,2326 fixed_buf, fixed_len, postlen);2327return1;2328}23292330static intmatch_fragment(struct image *img,2331struct image *preimage,2332struct image *postimage,2333unsigned longtry,2334int try_lno,2335unsigned ws_rule,2336int match_beginning,int match_end)2337{2338int i;2339char*fixed_buf, *buf, *orig, *target;2340struct strbuf fixed;2341size_t fixed_len, postlen;2342int preimage_limit;23432344if(preimage->nr + try_lno <= img->nr) {2345/*2346 * The hunk falls within the boundaries of img.2347 */2348 preimage_limit = preimage->nr;2349if(match_end && (preimage->nr + try_lno != img->nr))2350return0;2351}else if(ws_error_action == correct_ws_error &&2352(ws_rule & WS_BLANK_AT_EOF)) {2353/*2354 * This hunk extends beyond the end of img, and we are2355 * removing blank lines at the end of the file. This2356 * many lines from the beginning of the preimage must2357 * match with img, and the remainder of the preimage2358 * must be blank.2359 */2360 preimage_limit = img->nr - try_lno;2361}else{2362/*2363 * The hunk extends beyond the end of the img and2364 * we are not removing blanks at the end, so we2365 * should reject the hunk at this position.2366 */2367return0;2368}23692370if(match_beginning && try_lno)2371return0;23722373/* Quick hash check */2374for(i =0; i < preimage_limit; i++)2375if((img->line[try_lno + i].flag & LINE_PATCHED) ||2376(preimage->line[i].hash != img->line[try_lno + i].hash))2377return0;23782379if(preimage_limit == preimage->nr) {2380/*2381 * Do we have an exact match? If we were told to match2382 * at the end, size must be exactly at try+fragsize,2383 * otherwise try+fragsize must be still within the preimage,2384 * and either case, the old piece should match the preimage2385 * exactly.2386 */2387if((match_end2388? (try+ preimage->len == img->len)2389: (try+ preimage->len <= img->len)) &&2390!memcmp(img->buf +try, preimage->buf, preimage->len))2391return1;2392}else{2393/*2394 * The preimage extends beyond the end of img, so2395 * there cannot be an exact match.2396 *2397 * There must be one non-blank context line that match2398 * a line before the end of img.2399 */2400char*buf_end;24012402 buf = preimage->buf;2403 buf_end = buf;2404for(i =0; i < preimage_limit; i++)2405 buf_end += preimage->line[i].len;24062407for( ; buf < buf_end; buf++)2408if(!isspace(*buf))2409break;2410if(buf == buf_end)2411return0;2412}24132414/*2415 * No exact match. If we are ignoring whitespace, run a line-by-line2416 * fuzzy matching. We collect all the line length information because2417 * we need it to adjust whitespace if we match.2418 */2419if(ws_ignore_action == ignore_ws_change)2420returnline_by_line_fuzzy_match(img, preimage, postimage,2421try, try_lno, preimage_limit);24222423if(ws_error_action != correct_ws_error)2424return0;24252426/*2427 * The hunk does not apply byte-by-byte, but the hash says2428 * it might with whitespace fuzz. We weren't asked to2429 * ignore whitespace, we were asked to correct whitespace2430 * errors, so let's try matching after whitespace correction.2431 *2432 * While checking the preimage against the target, whitespace2433 * errors in both fixed, we count how large the corresponding2434 * postimage needs to be. The postimage prepared by2435 * apply_one_fragment() has whitespace errors fixed on added2436 * lines already, but the common lines were propagated as-is,2437 * which may become longer when their whitespace errors are2438 * fixed.2439 */24402441/* First count added lines in postimage */2442 postlen =0;2443for(i =0; i < postimage->nr; i++) {2444if(!(postimage->line[i].flag & LINE_COMMON))2445 postlen += postimage->line[i].len;2446}24472448/*2449 * The preimage may extend beyond the end of the file,2450 * but in this loop we will only handle the part of the2451 * preimage that falls within the file.2452 */2453strbuf_init(&fixed, preimage->len +1);2454 orig = preimage->buf;2455 target = img->buf +try;2456for(i =0; i < preimage_limit; i++) {2457size_t oldlen = preimage->line[i].len;2458size_t tgtlen = img->line[try_lno + i].len;2459size_t fixstart = fixed.len;2460struct strbuf tgtfix;2461int match;24622463/* Try fixing the line in the preimage */2464ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24652466/* Try fixing the line in the target */2467strbuf_init(&tgtfix, tgtlen);2468ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);24692470/*2471 * If they match, either the preimage was based on2472 * a version before our tree fixed whitespace breakage,2473 * or we are lacking a whitespace-fix patch the tree2474 * the preimage was based on already had (i.e. target2475 * has whitespace breakage, the preimage doesn't).2476 * In either case, we are fixing the whitespace breakages2477 * so we might as well take the fix together with their2478 * real change.2479 */2480 match = (tgtfix.len == fixed.len - fixstart &&2481!memcmp(tgtfix.buf, fixed.buf + fixstart,2482 fixed.len - fixstart));24832484/* Add the length if this is common with the postimage */2485if(preimage->line[i].flag & LINE_COMMON)2486 postlen += tgtfix.len;24872488strbuf_release(&tgtfix);2489if(!match)2490goto unmatch_exit;24912492 orig += oldlen;2493 target += tgtlen;2494}249524962497/*2498 * Now handle the lines in the preimage that falls beyond the2499 * end of the file (if any). They will only match if they are2500 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2501 * false).2502 */2503for( ; i < preimage->nr; i++) {2504size_t fixstart = fixed.len;/* start of the fixed preimage */2505size_t oldlen = preimage->line[i].len;2506int j;25072508/* Try fixing the line in the preimage */2509ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25102511for(j = fixstart; j < fixed.len; j++)2512if(!isspace(fixed.buf[j]))2513goto unmatch_exit;25142515 orig += oldlen;2516}25172518/*2519 * Yes, the preimage is based on an older version that still2520 * has whitespace breakages unfixed, and fixing them makes the2521 * hunk match. Update the context lines in the postimage.2522 */2523 fixed_buf =strbuf_detach(&fixed, &fixed_len);2524if(postlen < postimage->len)2525 postlen =0;2526update_pre_post_images(preimage, postimage,2527 fixed_buf, fixed_len, postlen);2528return1;25292530 unmatch_exit:2531strbuf_release(&fixed);2532return0;2533}25342535static intfind_pos(struct image *img,2536struct image *preimage,2537struct image *postimage,2538int line,2539unsigned ws_rule,2540int match_beginning,int match_end)2541{2542int i;2543unsigned long backwards, forwards,try;2544int backwards_lno, forwards_lno, try_lno;25452546/*2547 * If match_beginning or match_end is specified, there is no2548 * point starting from a wrong line that will never match and2549 * wander around and wait for a match at the specified end.2550 */2551if(match_beginning)2552 line =0;2553else if(match_end)2554 line = img->nr - preimage->nr;25552556/*2557 * Because the comparison is unsigned, the following test2558 * will also take care of a negative line number that can2559 * result when match_end and preimage is larger than the target.2560 */2561if((size_t) line > img->nr)2562 line = img->nr;25632564try=0;2565for(i =0; i < line; i++)2566try+= img->line[i].len;25672568/*2569 * There's probably some smart way to do this, but I'll leave2570 * that to the smart and beautiful people. I'm simple and stupid.2571 */2572 backwards =try;2573 backwards_lno = line;2574 forwards =try;2575 forwards_lno = line;2576 try_lno = line;25772578for(i =0; ; i++) {2579if(match_fragment(img, preimage, postimage,2580try, try_lno, ws_rule,2581 match_beginning, match_end))2582return try_lno;25832584 again:2585if(backwards_lno ==0&& forwards_lno == img->nr)2586break;25872588if(i &1) {2589if(backwards_lno ==0) {2590 i++;2591goto again;2592}2593 backwards_lno--;2594 backwards -= img->line[backwards_lno].len;2595try= backwards;2596 try_lno = backwards_lno;2597}else{2598if(forwards_lno == img->nr) {2599 i++;2600goto again;2601}2602 forwards += img->line[forwards_lno].len;2603 forwards_lno++;2604try= forwards;2605 try_lno = forwards_lno;2606}26072608}2609return-1;2610}26112612static voidremove_first_line(struct image *img)2613{2614 img->buf += img->line[0].len;2615 img->len -= img->line[0].len;2616 img->line++;2617 img->nr--;2618}26192620static voidremove_last_line(struct image *img)2621{2622 img->len -= img->line[--img->nr].len;2623}26242625/*2626 * The change from "preimage" and "postimage" has been found to2627 * apply at applied_pos (counts in line numbers) in "img".2628 * Update "img" to remove "preimage" and replace it with "postimage".2629 */2630static voidupdate_image(struct image *img,2631int applied_pos,2632struct image *preimage,2633struct image *postimage)2634{2635/*2636 * remove the copy of preimage at offset in img2637 * and replace it with postimage2638 */2639int i, nr;2640size_t remove_count, insert_count, applied_at =0;2641char*result;2642int preimage_limit;26432644/*2645 * If we are removing blank lines at the end of img,2646 * the preimage may extend beyond the end.2647 * If that is the case, we must be careful only to2648 * remove the part of the preimage that falls within2649 * the boundaries of img. Initialize preimage_limit2650 * to the number of lines in the preimage that falls2651 * within the boundaries.2652 */2653 preimage_limit = preimage->nr;2654if(preimage_limit > img->nr - applied_pos)2655 preimage_limit = img->nr - applied_pos;26562657for(i =0; i < applied_pos; i++)2658 applied_at += img->line[i].len;26592660 remove_count =0;2661for(i =0; i < preimage_limit; i++)2662 remove_count += img->line[applied_pos + i].len;2663 insert_count = postimage->len;26642665/* Adjust the contents */2666 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2667memcpy(result, img->buf, applied_at);2668memcpy(result + applied_at, postimage->buf, postimage->len);2669memcpy(result + applied_at + postimage->len,2670 img->buf + (applied_at + remove_count),2671 img->len - (applied_at + remove_count));2672free(img->buf);2673 img->buf = result;2674 img->len += insert_count - remove_count;2675 result[img->len] ='\0';26762677/* Adjust the line table */2678 nr = img->nr + postimage->nr - preimage_limit;2679if(preimage_limit < postimage->nr) {2680/*2681 * NOTE: this knows that we never call remove_first_line()2682 * on anything other than pre/post image.2683 */2684REALLOC_ARRAY(img->line, nr);2685 img->line_allocated = img->line;2686}2687if(preimage_limit != postimage->nr)2688memmove(img->line + applied_pos + postimage->nr,2689 img->line + applied_pos + preimage_limit,2690(img->nr - (applied_pos + preimage_limit)) *2691sizeof(*img->line));2692memcpy(img->line + applied_pos,2693 postimage->line,2694 postimage->nr *sizeof(*img->line));2695if(!allow_overlap)2696for(i =0; i < postimage->nr; i++)2697 img->line[applied_pos + i].flag |= LINE_PATCHED;2698 img->nr = nr;2699}27002701/*2702 * Use the patch-hunk text in "frag" to prepare two images (preimage and2703 * postimage) for the hunk. Find lines that match "preimage" in "img" and2704 * replace the part of "img" with "postimage" text.2705 */2706static intapply_one_fragment(struct apply_state *state,2707struct image *img,struct fragment *frag,2708int inaccurate_eof,unsigned ws_rule,2709int nth_fragment)2710{2711int match_beginning, match_end;2712const char*patch = frag->patch;2713int size = frag->size;2714char*old, *oldlines;2715struct strbuf newlines;2716int new_blank_lines_at_end =0;2717int found_new_blank_lines_at_end =0;2718int hunk_linenr = frag->linenr;2719unsigned long leading, trailing;2720int pos, applied_pos;2721struct image preimage;2722struct image postimage;27232724memset(&preimage,0,sizeof(preimage));2725memset(&postimage,0,sizeof(postimage));2726 oldlines =xmalloc(size);2727strbuf_init(&newlines, size);27282729 old = oldlines;2730while(size >0) {2731char first;2732int len =linelen(patch, size);2733int plen;2734int added_blank_line =0;2735int is_blank_context =0;2736size_t start;27372738if(!len)2739break;27402741/*2742 * "plen" is how much of the line we should use for2743 * the actual patch data. Normally we just remove the2744 * first character on the line, but if the line is2745 * followed by "\ No newline", then we also remove the2746 * last one (which is the newline, of course).2747 */2748 plen = len -1;2749if(len < size && patch[len] =='\\')2750 plen--;2751 first = *patch;2752if(state->apply_in_reverse) {2753if(first =='-')2754 first ='+';2755else if(first =='+')2756 first ='-';2757}27582759switch(first) {2760case'\n':2761/* Newer GNU diff, empty context line */2762if(plen <0)2763/* ... followed by '\No newline'; nothing */2764break;2765*old++ ='\n';2766strbuf_addch(&newlines,'\n');2767add_line_info(&preimage,"\n",1, LINE_COMMON);2768add_line_info(&postimage,"\n",1, LINE_COMMON);2769 is_blank_context =1;2770break;2771case' ':2772if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2773ws_blank_line(patch +1, plen, ws_rule))2774 is_blank_context =1;2775case'-':2776memcpy(old, patch +1, plen);2777add_line_info(&preimage, old, plen,2778(first ==' '? LINE_COMMON :0));2779 old += plen;2780if(first =='-')2781break;2782/* Fall-through for ' ' */2783case'+':2784/* --no-add does not add new lines */2785if(first =='+'&& no_add)2786break;27872788 start = newlines.len;2789if(first !='+'||2790!whitespace_error ||2791 ws_error_action != correct_ws_error) {2792strbuf_add(&newlines, patch +1, plen);2793}2794else{2795ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2796}2797add_line_info(&postimage, newlines.buf + start, newlines.len - start,2798(first =='+'?0: LINE_COMMON));2799if(first =='+'&&2800(ws_rule & WS_BLANK_AT_EOF) &&2801ws_blank_line(patch +1, plen, ws_rule))2802 added_blank_line =1;2803break;2804case'@':case'\\':2805/* Ignore it, we already handled it */2806break;2807default:2808if(apply_verbosely)2809error(_("invalid start of line: '%c'"), first);2810 applied_pos = -1;2811goto out;2812}2813if(added_blank_line) {2814if(!new_blank_lines_at_end)2815 found_new_blank_lines_at_end = hunk_linenr;2816 new_blank_lines_at_end++;2817}2818else if(is_blank_context)2819;2820else2821 new_blank_lines_at_end =0;2822 patch += len;2823 size -= len;2824 hunk_linenr++;2825}2826if(inaccurate_eof &&2827 old > oldlines && old[-1] =='\n'&&2828 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2829 old--;2830strbuf_setlen(&newlines, newlines.len -1);2831}28322833 leading = frag->leading;2834 trailing = frag->trailing;28352836/*2837 * A hunk to change lines at the beginning would begin with2838 * @@ -1,L +N,M @@2839 * but we need to be careful. -U0 that inserts before the second2840 * line also has this pattern.2841 *2842 * And a hunk to add to an empty file would begin with2843 * @@ -0,0 +N,M @@2844 *2845 * In other words, a hunk that is (frag->oldpos <= 1) with or2846 * without leading context must match at the beginning.2847 */2848 match_beginning = (!frag->oldpos ||2849(frag->oldpos ==1&& !state->unidiff_zero));28502851/*2852 * A hunk without trailing lines must match at the end.2853 * However, we simply cannot tell if a hunk must match end2854 * from the lack of trailing lines if the patch was generated2855 * with unidiff without any context.2856 */2857 match_end = !state->unidiff_zero && !trailing;28582859 pos = frag->newpos ? (frag->newpos -1) :0;2860 preimage.buf = oldlines;2861 preimage.len = old - oldlines;2862 postimage.buf = newlines.buf;2863 postimage.len = newlines.len;2864 preimage.line = preimage.line_allocated;2865 postimage.line = postimage.line_allocated;28662867for(;;) {28682869 applied_pos =find_pos(img, &preimage, &postimage, pos,2870 ws_rule, match_beginning, match_end);28712872if(applied_pos >=0)2873break;28742875/* Am I at my context limits? */2876if((leading <= p_context) && (trailing <= p_context))2877break;2878if(match_beginning || match_end) {2879 match_beginning = match_end =0;2880continue;2881}28822883/*2884 * Reduce the number of context lines; reduce both2885 * leading and trailing if they are equal otherwise2886 * just reduce the larger context.2887 */2888if(leading >= trailing) {2889remove_first_line(&preimage);2890remove_first_line(&postimage);2891 pos--;2892 leading--;2893}2894if(trailing > leading) {2895remove_last_line(&preimage);2896remove_last_line(&postimage);2897 trailing--;2898}2899}29002901if(applied_pos >=0) {2902if(new_blank_lines_at_end &&2903 preimage.nr + applied_pos >= img->nr &&2904(ws_rule & WS_BLANK_AT_EOF) &&2905 ws_error_action != nowarn_ws_error) {2906record_ws_error(WS_BLANK_AT_EOF,"+",1,2907 found_new_blank_lines_at_end);2908if(ws_error_action == correct_ws_error) {2909while(new_blank_lines_at_end--)2910remove_last_line(&postimage);2911}2912/*2913 * We would want to prevent write_out_results()2914 * from taking place in apply_patch() that follows2915 * the callchain led us here, which is:2916 * apply_patch->check_patch_list->check_patch->2917 * apply_data->apply_fragments->apply_one_fragment2918 */2919if(ws_error_action == die_on_ws_error)2920 apply =0;2921}29222923if(apply_verbosely && applied_pos != pos) {2924int offset = applied_pos - pos;2925if(state->apply_in_reverse)2926 offset =0- offset;2927fprintf_ln(stderr,2928Q_("Hunk #%dsucceeded at%d(offset%dline).",2929"Hunk #%dsucceeded at%d(offset%dlines).",2930 offset),2931 nth_fragment, applied_pos +1, offset);2932}29332934/*2935 * Warn if it was necessary to reduce the number2936 * of context lines.2937 */2938if((leading != frag->leading) ||2939(trailing != frag->trailing))2940fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2941" to apply fragment at%d"),2942 leading, trailing, applied_pos+1);2943update_image(img, applied_pos, &preimage, &postimage);2944}else{2945if(apply_verbosely)2946error(_("while searching for:\n%.*s"),2947(int)(old - oldlines), oldlines);2948}29492950out:2951free(oldlines);2952strbuf_release(&newlines);2953free(preimage.line_allocated);2954free(postimage.line_allocated);29552956return(applied_pos <0);2957}29582959static intapply_binary_fragment(struct apply_state *state,2960struct image *img,2961struct patch *patch)2962{2963struct fragment *fragment = patch->fragments;2964unsigned long len;2965void*dst;29662967if(!fragment)2968returnerror(_("missing binary patch data for '%s'"),2969 patch->new_name ?2970 patch->new_name :2971 patch->old_name);29722973/* Binary patch is irreversible without the optional second hunk */2974if(state->apply_in_reverse) {2975if(!fragment->next)2976returnerror("cannot reverse-apply a binary patch "2977"without the reverse hunk to '%s'",2978 patch->new_name2979? patch->new_name : patch->old_name);2980 fragment = fragment->next;2981}2982switch(fragment->binary_patch_method) {2983case BINARY_DELTA_DEFLATED:2984 dst =patch_delta(img->buf, img->len, fragment->patch,2985 fragment->size, &len);2986if(!dst)2987return-1;2988clear_image(img);2989 img->buf = dst;2990 img->len = len;2991return0;2992case BINARY_LITERAL_DEFLATED:2993clear_image(img);2994 img->len = fragment->size;2995 img->buf =xmemdupz(fragment->patch, img->len);2996return0;2997}2998return-1;2999}30003001/*3002 * Replace "img" with the result of applying the binary patch.3003 * The binary patch data itself in patch->fragment is still kept3004 * but the preimage prepared by the caller in "img" is freed here3005 * or in the helper function apply_binary_fragment() this calls.3006 */3007static intapply_binary(struct apply_state *state,3008struct image *img,3009struct patch *patch)3010{3011const char*name = patch->old_name ? patch->old_name : patch->new_name;3012unsigned char sha1[20];30133014/*3015 * For safety, we require patch index line to contain3016 * full 40-byte textual SHA1 for old and new, at least for now.3017 */3018if(strlen(patch->old_sha1_prefix) !=40||3019strlen(patch->new_sha1_prefix) !=40||3020get_sha1_hex(patch->old_sha1_prefix, sha1) ||3021get_sha1_hex(patch->new_sha1_prefix, sha1))3022returnerror("cannot apply binary patch to '%s' "3023"without full index line", name);30243025if(patch->old_name) {3026/*3027 * See if the old one matches what the patch3028 * applies to.3029 */3030hash_sha1_file(img->buf, img->len, blob_type, sha1);3031if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3032returnerror("the patch applies to '%s' (%s), "3033"which does not match the "3034"current contents.",3035 name,sha1_to_hex(sha1));3036}3037else{3038/* Otherwise, the old one must be empty. */3039if(img->len)3040returnerror("the patch applies to an empty "3041"'%s' but it is not empty", name);3042}30433044get_sha1_hex(patch->new_sha1_prefix, sha1);3045if(is_null_sha1(sha1)) {3046clear_image(img);3047return0;/* deletion patch */3048}30493050if(has_sha1_file(sha1)) {3051/* We already have the postimage */3052enum object_type type;3053unsigned long size;3054char*result;30553056 result =read_sha1_file(sha1, &type, &size);3057if(!result)3058returnerror("the necessary postimage%sfor "3059"'%s' cannot be read",3060 patch->new_sha1_prefix, name);3061clear_image(img);3062 img->buf = result;3063 img->len = size;3064}else{3065/*3066 * We have verified buf matches the preimage;3067 * apply the patch data to it, which is stored3068 * in the patch->fragments->{patch,size}.3069 */3070if(apply_binary_fragment(state, img, patch))3071returnerror(_("binary patch does not apply to '%s'"),3072 name);30733074/* verify that the result matches */3075hash_sha1_file(img->buf, img->len, blob_type, sha1);3076if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3077returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3078 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3079}30803081return0;3082}30833084static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3085{3086struct fragment *frag = patch->fragments;3087const char*name = patch->old_name ? patch->old_name : patch->new_name;3088unsigned ws_rule = patch->ws_rule;3089unsigned inaccurate_eof = patch->inaccurate_eof;3090int nth =0;30913092if(patch->is_binary)3093returnapply_binary(state, img, patch);30943095while(frag) {3096 nth++;3097if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3098error(_("patch failed:%s:%ld"), name, frag->oldpos);3099if(!state->apply_with_reject)3100return-1;3101 frag->rejected =1;3102}3103 frag = frag->next;3104}3105return0;3106}31073108static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3109{3110if(S_ISGITLINK(mode)) {3111strbuf_grow(buf,100);3112strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3113}else{3114enum object_type type;3115unsigned long sz;3116char*result;31173118 result =read_sha1_file(sha1, &type, &sz);3119if(!result)3120return-1;3121/* XXX read_sha1_file NUL-terminates */3122strbuf_attach(buf, result, sz, sz +1);3123}3124return0;3125}31263127static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3128{3129if(!ce)3130return0;3131returnread_blob_object(buf, ce->sha1, ce->ce_mode);3132}31333134static struct patch *in_fn_table(const char*name)3135{3136struct string_list_item *item;31373138if(name == NULL)3139return NULL;31403141 item =string_list_lookup(&fn_table, name);3142if(item != NULL)3143return(struct patch *)item->util;31443145return NULL;3146}31473148/*3149 * item->util in the filename table records the status of the path.3150 * Usually it points at a patch (whose result records the contents3151 * of it after applying it), but it could be PATH_WAS_DELETED for a3152 * path that a previously applied patch has already removed, or3153 * PATH_TO_BE_DELETED for a path that a later patch would remove.3154 *3155 * The latter is needed to deal with a case where two paths A and B3156 * are swapped by first renaming A to B and then renaming B to A;3157 * moving A to B should not be prevented due to presence of B as we3158 * will remove it in a later patch.3159 */3160#define PATH_TO_BE_DELETED ((struct patch *) -2)3161#define PATH_WAS_DELETED ((struct patch *) -1)31623163static intto_be_deleted(struct patch *patch)3164{3165return patch == PATH_TO_BE_DELETED;3166}31673168static intwas_deleted(struct patch *patch)3169{3170return patch == PATH_WAS_DELETED;3171}31723173static voidadd_to_fn_table(struct patch *patch)3174{3175struct string_list_item *item;31763177/*3178 * Always add new_name unless patch is a deletion3179 * This should cover the cases for normal diffs,3180 * file creations and copies3181 */3182if(patch->new_name != NULL) {3183 item =string_list_insert(&fn_table, patch->new_name);3184 item->util = patch;3185}31863187/*3188 * store a failure on rename/deletion cases because3189 * later chunks shouldn't patch old names3190 */3191if((patch->new_name == NULL) || (patch->is_rename)) {3192 item =string_list_insert(&fn_table, patch->old_name);3193 item->util = PATH_WAS_DELETED;3194}3195}31963197static voidprepare_fn_table(struct patch *patch)3198{3199/*3200 * store information about incoming file deletion3201 */3202while(patch) {3203if((patch->new_name == NULL) || (patch->is_rename)) {3204struct string_list_item *item;3205 item =string_list_insert(&fn_table, patch->old_name);3206 item->util = PATH_TO_BE_DELETED;3207}3208 patch = patch->next;3209}3210}32113212static intcheckout_target(struct index_state *istate,3213struct cache_entry *ce,struct stat *st)3214{3215struct checkout costate;32163217memset(&costate,0,sizeof(costate));3218 costate.base_dir ="";3219 costate.refresh_cache =1;3220 costate.istate = istate;3221if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3222returnerror(_("cannot checkout%s"), ce->name);3223return0;3224}32253226static struct patch *previous_patch(struct patch *patch,int*gone)3227{3228struct patch *previous;32293230*gone =0;3231if(patch->is_copy || patch->is_rename)3232return NULL;/* "git" patches do not depend on the order */32333234 previous =in_fn_table(patch->old_name);3235if(!previous)3236return NULL;32373238if(to_be_deleted(previous))3239return NULL;/* the deletion hasn't happened yet */32403241if(was_deleted(previous))3242*gone =1;32433244return previous;3245}32463247static intverify_index_match(const struct cache_entry *ce,struct stat *st)3248{3249if(S_ISGITLINK(ce->ce_mode)) {3250if(!S_ISDIR(st->st_mode))3251return-1;3252return0;3253}3254returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3255}32563257#define SUBMODULE_PATCH_WITHOUT_INDEX 132583259static intload_patch_target(struct apply_state *state,3260struct strbuf *buf,3261const struct cache_entry *ce,3262struct stat *st,3263const char*name,3264unsigned expected_mode)3265{3266if(cached || state->check_index) {3267if(read_file_or_gitlink(ce, buf))3268returnerror(_("read of%sfailed"), name);3269}else if(name) {3270if(S_ISGITLINK(expected_mode)) {3271if(ce)3272returnread_file_or_gitlink(ce, buf);3273else3274return SUBMODULE_PATCH_WITHOUT_INDEX;3275}else if(has_symlink_leading_path(name,strlen(name))) {3276returnerror(_("reading from '%s' beyond a symbolic link"), name);3277}else{3278if(read_old_data(st, name, buf))3279returnerror(_("read of%sfailed"), name);3280}3281}3282return0;3283}32843285/*3286 * We are about to apply "patch"; populate the "image" with the3287 * current version we have, from the working tree or from the index,3288 * depending on the situation e.g. --cached/--index. If we are3289 * applying a non-git patch that incrementally updates the tree,3290 * we read from the result of a previous diff.3291 */3292static intload_preimage(struct apply_state *state,3293struct image *image,3294struct patch *patch,struct stat *st,3295const struct cache_entry *ce)3296{3297struct strbuf buf = STRBUF_INIT;3298size_t len;3299char*img;3300struct patch *previous;3301int status;33023303 previous =previous_patch(patch, &status);3304if(status)3305returnerror(_("path%shas been renamed/deleted"),3306 patch->old_name);3307if(previous) {3308/* We have a patched copy in memory; use that. */3309strbuf_add(&buf, previous->result, previous->resultsize);3310}else{3311 status =load_patch_target(state, &buf, ce, st,3312 patch->old_name, patch->old_mode);3313if(status <0)3314return status;3315else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3316/*3317 * There is no way to apply subproject3318 * patch without looking at the index.3319 * NEEDSWORK: shouldn't this be flagged3320 * as an error???3321 */3322free_fragment_list(patch->fragments);3323 patch->fragments = NULL;3324}else if(status) {3325returnerror(_("read of%sfailed"), patch->old_name);3326}3327}33283329 img =strbuf_detach(&buf, &len);3330prepare_image(image, img, len, !patch->is_binary);3331return0;3332}33333334static intthree_way_merge(struct image *image,3335char*path,3336const unsigned char*base,3337const unsigned char*ours,3338const unsigned char*theirs)3339{3340 mmfile_t base_file, our_file, their_file;3341 mmbuffer_t result = { NULL };3342int status;33433344read_mmblob(&base_file, base);3345read_mmblob(&our_file, ours);3346read_mmblob(&their_file, theirs);3347 status =ll_merge(&result, path,3348&base_file,"base",3349&our_file,"ours",3350&their_file,"theirs", NULL);3351free(base_file.ptr);3352free(our_file.ptr);3353free(their_file.ptr);3354if(status <0|| !result.ptr) {3355free(result.ptr);3356return-1;3357}3358clear_image(image);3359 image->buf = result.ptr;3360 image->len = result.size;33613362return status;3363}33643365/*3366 * When directly falling back to add/add three-way merge, we read from3367 * the current contents of the new_name. In no cases other than that3368 * this function will be called.3369 */3370static intload_current(struct apply_state *state,3371struct image *image,3372struct patch *patch)3373{3374struct strbuf buf = STRBUF_INIT;3375int status, pos;3376size_t len;3377char*img;3378struct stat st;3379struct cache_entry *ce;3380char*name = patch->new_name;3381unsigned mode = patch->new_mode;33823383if(!patch->is_new)3384die("BUG: patch to%sis not a creation", patch->old_name);33853386 pos =cache_name_pos(name,strlen(name));3387if(pos <0)3388returnerror(_("%s: does not exist in index"), name);3389 ce = active_cache[pos];3390if(lstat(name, &st)) {3391if(errno != ENOENT)3392returnerror(_("%s:%s"), name,strerror(errno));3393if(checkout_target(&the_index, ce, &st))3394return-1;3395}3396if(verify_index_match(ce, &st))3397returnerror(_("%s: does not match index"), name);33983399 status =load_patch_target(state, &buf, ce, &st, name, mode);3400if(status <0)3401return status;3402else if(status)3403return-1;3404 img =strbuf_detach(&buf, &len);3405prepare_image(image, img, len, !patch->is_binary);3406return0;3407}34083409static inttry_threeway(struct apply_state *state,3410struct image *image,3411struct patch *patch,3412struct stat *st,3413const struct cache_entry *ce)3414{3415unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3416struct strbuf buf = STRBUF_INIT;3417size_t len;3418int status;3419char*img;3420struct image tmp_image;34213422/* No point falling back to 3-way merge in these cases */3423if(patch->is_delete ||3424S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3425return-1;34263427/* Preimage the patch was prepared for */3428if(patch->is_new)3429write_sha1_file("",0, blob_type, pre_sha1);3430else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3431read_blob_object(&buf, pre_sha1, patch->old_mode))3432returnerror("repository lacks the necessary blob to fall back on 3-way merge.");34333434fprintf(stderr,"Falling back to three-way merge...\n");34353436 img =strbuf_detach(&buf, &len);3437prepare_image(&tmp_image, img, len,1);3438/* Apply the patch to get the post image */3439if(apply_fragments(state, &tmp_image, patch) <0) {3440clear_image(&tmp_image);3441return-1;3442}3443/* post_sha1[] is theirs */3444write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3445clear_image(&tmp_image);34463447/* our_sha1[] is ours */3448if(patch->is_new) {3449if(load_current(state, &tmp_image, patch))3450returnerror("cannot read the current contents of '%s'",3451 patch->new_name);3452}else{3453if(load_preimage(state, &tmp_image, patch, st, ce))3454returnerror("cannot read the current contents of '%s'",3455 patch->old_name);3456}3457write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3458clear_image(&tmp_image);34593460/* in-core three-way merge between post and our using pre as base */3461 status =three_way_merge(image, patch->new_name,3462 pre_sha1, our_sha1, post_sha1);3463if(status <0) {3464fprintf(stderr,"Failed to fall back on three-way merge...\n");3465return status;3466}34673468if(status) {3469 patch->conflicted_threeway =1;3470if(patch->is_new)3471oidclr(&patch->threeway_stage[0]);3472else3473hashcpy(patch->threeway_stage[0].hash, pre_sha1);3474hashcpy(patch->threeway_stage[1].hash, our_sha1);3475hashcpy(patch->threeway_stage[2].hash, post_sha1);3476fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3477}else{3478fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3479}3480return0;3481}34823483static intapply_data(struct apply_state *state,struct patch *patch,3484struct stat *st,const struct cache_entry *ce)3485{3486struct image image;34873488if(load_preimage(state, &image, patch, st, ce) <0)3489return-1;34903491if(patch->direct_to_threeway ||3492apply_fragments(state, &image, patch) <0) {3493/* Note: with --reject, apply_fragments() returns 0 */3494if(!threeway ||try_threeway(state, &image, patch, st, ce) <0)3495return-1;3496}3497 patch->result = image.buf;3498 patch->resultsize = image.len;3499add_to_fn_table(patch);3500free(image.line_allocated);35013502if(0< patch->is_delete && patch->resultsize)3503returnerror(_("removal patch leaves file contents"));35043505return0;3506}35073508/*3509 * If "patch" that we are looking at modifies or deletes what we have,3510 * we would want it not to lose any local modification we have, either3511 * in the working tree or in the index.3512 *3513 * This also decides if a non-git patch is a creation patch or a3514 * modification to an existing empty file. We do not check the state3515 * of the current tree for a creation patch in this function; the caller3516 * check_patch() separately makes sure (and errors out otherwise) that3517 * the path the patch creates does not exist in the current tree.3518 */3519static intcheck_preimage(struct apply_state *state,3520struct patch *patch,3521struct cache_entry **ce,3522struct stat *st)3523{3524const char*old_name = patch->old_name;3525struct patch *previous = NULL;3526int stat_ret =0, status;3527unsigned st_mode =0;35283529if(!old_name)3530return0;35313532assert(patch->is_new <=0);3533 previous =previous_patch(patch, &status);35343535if(status)3536returnerror(_("path%shas been renamed/deleted"), old_name);3537if(previous) {3538 st_mode = previous->new_mode;3539}else if(!cached) {3540 stat_ret =lstat(old_name, st);3541if(stat_ret && errno != ENOENT)3542returnerror(_("%s:%s"), old_name,strerror(errno));3543}35443545if(state->check_index && !previous) {3546int pos =cache_name_pos(old_name,strlen(old_name));3547if(pos <0) {3548if(patch->is_new <0)3549goto is_new;3550returnerror(_("%s: does not exist in index"), old_name);3551}3552*ce = active_cache[pos];3553if(stat_ret <0) {3554if(checkout_target(&the_index, *ce, st))3555return-1;3556}3557if(!cached &&verify_index_match(*ce, st))3558returnerror(_("%s: does not match index"), old_name);3559if(cached)3560 st_mode = (*ce)->ce_mode;3561}else if(stat_ret <0) {3562if(patch->is_new <0)3563goto is_new;3564returnerror(_("%s:%s"), old_name,strerror(errno));3565}35663567if(!cached && !previous)3568 st_mode =ce_mode_from_stat(*ce, st->st_mode);35693570if(patch->is_new <0)3571 patch->is_new =0;3572if(!patch->old_mode)3573 patch->old_mode = st_mode;3574if((st_mode ^ patch->old_mode) & S_IFMT)3575returnerror(_("%s: wrong type"), old_name);3576if(st_mode != patch->old_mode)3577warning(_("%shas type%o, expected%o"),3578 old_name, st_mode, patch->old_mode);3579if(!patch->new_mode && !patch->is_delete)3580 patch->new_mode = st_mode;3581return0;35823583 is_new:3584 patch->is_new =1;3585 patch->is_delete =0;3586free(patch->old_name);3587 patch->old_name = NULL;3588return0;3589}359035913592#define EXISTS_IN_INDEX 13593#define EXISTS_IN_WORKTREE 235943595static intcheck_to_create(struct apply_state *state,3596const char*new_name,3597int ok_if_exists)3598{3599struct stat nst;36003601if(state->check_index &&3602cache_name_pos(new_name,strlen(new_name)) >=0&&3603!ok_if_exists)3604return EXISTS_IN_INDEX;3605if(cached)3606return0;36073608if(!lstat(new_name, &nst)) {3609if(S_ISDIR(nst.st_mode) || ok_if_exists)3610return0;3611/*3612 * A leading component of new_name might be a symlink3613 * that is going to be removed with this patch, but3614 * still pointing at somewhere that has the path.3615 * In such a case, path "new_name" does not exist as3616 * far as git is concerned.3617 */3618if(has_symlink_leading_path(new_name,strlen(new_name)))3619return0;36203621return EXISTS_IN_WORKTREE;3622}else if((errno != ENOENT) && (errno != ENOTDIR)) {3623returnerror("%s:%s", new_name,strerror(errno));3624}3625return0;3626}36273628/*3629 * We need to keep track of how symlinks in the preimage are3630 * manipulated by the patches. A patch to add a/b/c where a/b3631 * is a symlink should not be allowed to affect the directory3632 * the symlink points at, but if the same patch removes a/b,3633 * it is perfectly fine, as the patch removes a/b to make room3634 * to create a directory a/b so that a/b/c can be created.3635 */3636static struct string_list symlink_changes;3637#define SYMLINK_GOES_AWAY 013638#define SYMLINK_IN_RESULT 0236393640static uintptr_tregister_symlink_changes(const char*path,uintptr_t what)3641{3642struct string_list_item *ent;36433644 ent =string_list_lookup(&symlink_changes, path);3645if(!ent) {3646 ent =string_list_insert(&symlink_changes, path);3647 ent->util = (void*)0;3648}3649 ent->util = (void*)(what | ((uintptr_t)ent->util));3650return(uintptr_t)ent->util;3651}36523653static uintptr_tcheck_symlink_changes(const char*path)3654{3655struct string_list_item *ent;36563657 ent =string_list_lookup(&symlink_changes, path);3658if(!ent)3659return0;3660return(uintptr_t)ent->util;3661}36623663static voidprepare_symlink_changes(struct patch *patch)3664{3665for( ; patch; patch = patch->next) {3666if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3667(patch->is_rename || patch->is_delete))3668/* the symlink at patch->old_name is removed */3669register_symlink_changes(patch->old_name, SYMLINK_GOES_AWAY);36703671if(patch->new_name &&S_ISLNK(patch->new_mode))3672/* the symlink at patch->new_name is created or remains */3673register_symlink_changes(patch->new_name, SYMLINK_IN_RESULT);3674}3675}36763677static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3678{3679do{3680unsigned int change;36813682while(--name->len && name->buf[name->len] !='/')3683;/* scan backwards */3684if(!name->len)3685break;3686 name->buf[name->len] ='\0';3687 change =check_symlink_changes(name->buf);3688if(change & SYMLINK_IN_RESULT)3689return1;3690if(change & SYMLINK_GOES_AWAY)3691/*3692 * This cannot be "return 0", because we may3693 * see a new one created at a higher level.3694 */3695continue;36963697/* otherwise, check the preimage */3698if(state->check_index) {3699struct cache_entry *ce;37003701 ce =cache_file_exists(name->buf, name->len, ignore_case);3702if(ce &&S_ISLNK(ce->ce_mode))3703return1;3704}else{3705struct stat st;3706if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3707return1;3708}3709}while(1);3710return0;3711}37123713static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3714{3715int ret;3716struct strbuf name = STRBUF_INIT;37173718assert(*name_ !='\0');3719strbuf_addstr(&name, name_);3720 ret =path_is_beyond_symlink_1(state, &name);3721strbuf_release(&name);37223723return ret;3724}37253726static voiddie_on_unsafe_path(struct patch *patch)3727{3728const char*old_name = NULL;3729const char*new_name = NULL;3730if(patch->is_delete)3731 old_name = patch->old_name;3732else if(!patch->is_new && !patch->is_copy)3733 old_name = patch->old_name;3734if(!patch->is_delete)3735 new_name = patch->new_name;37363737if(old_name && !verify_path(old_name))3738die(_("invalid path '%s'"), old_name);3739if(new_name && !verify_path(new_name))3740die(_("invalid path '%s'"), new_name);3741}37423743/*3744 * Check and apply the patch in-core; leave the result in patch->result3745 * for the caller to write it out to the final destination.3746 */3747static intcheck_patch(struct apply_state *state,struct patch *patch)3748{3749struct stat st;3750const char*old_name = patch->old_name;3751const char*new_name = patch->new_name;3752const char*name = old_name ? old_name : new_name;3753struct cache_entry *ce = NULL;3754struct patch *tpatch;3755int ok_if_exists;3756int status;37573758 patch->rejected =1;/* we will drop this after we succeed */37593760 status =check_preimage(state, patch, &ce, &st);3761if(status)3762return status;3763 old_name = patch->old_name;37643765/*3766 * A type-change diff is always split into a patch to delete3767 * old, immediately followed by a patch to create new (see3768 * diff.c::run_diff()); in such a case it is Ok that the entry3769 * to be deleted by the previous patch is still in the working3770 * tree and in the index.3771 *3772 * A patch to swap-rename between A and B would first rename A3773 * to B and then rename B to A. While applying the first one,3774 * the presence of B should not stop A from getting renamed to3775 * B; ask to_be_deleted() about the later rename. Removal of3776 * B and rename from A to B is handled the same way by asking3777 * was_deleted().3778 */3779if((tpatch =in_fn_table(new_name)) &&3780(was_deleted(tpatch) ||to_be_deleted(tpatch)))3781 ok_if_exists =1;3782else3783 ok_if_exists =0;37843785if(new_name &&3786((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3787int err =check_to_create(state, new_name, ok_if_exists);37883789if(err && threeway) {3790 patch->direct_to_threeway =1;3791}else switch(err) {3792case0:3793break;/* happy */3794case EXISTS_IN_INDEX:3795returnerror(_("%s: already exists in index"), new_name);3796break;3797case EXISTS_IN_WORKTREE:3798returnerror(_("%s: already exists in working directory"),3799 new_name);3800default:3801return err;3802}38033804if(!patch->new_mode) {3805if(0< patch->is_new)3806 patch->new_mode = S_IFREG |0644;3807else3808 patch->new_mode = patch->old_mode;3809}3810}38113812if(new_name && old_name) {3813int same = !strcmp(old_name, new_name);3814if(!patch->new_mode)3815 patch->new_mode = patch->old_mode;3816if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3817if(same)3818returnerror(_("new mode (%o) of%sdoes not "3819"match old mode (%o)"),3820 patch->new_mode, new_name,3821 patch->old_mode);3822else3823returnerror(_("new mode (%o) of%sdoes not "3824"match old mode (%o) of%s"),3825 patch->new_mode, new_name,3826 patch->old_mode, old_name);3827}3828}38293830if(!unsafe_paths)3831die_on_unsafe_path(patch);38323833/*3834 * An attempt to read from or delete a path that is beyond a3835 * symbolic link will be prevented by load_patch_target() that3836 * is called at the beginning of apply_data() so we do not3837 * have to worry about a patch marked with "is_delete" bit3838 * here. We however need to make sure that the patch result3839 * is not deposited to a path that is beyond a symbolic link3840 * here.3841 */3842if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3843returnerror(_("affected file '%s' is beyond a symbolic link"),3844 patch->new_name);38453846if(apply_data(state, patch, &st, ce) <0)3847returnerror(_("%s: patch does not apply"), name);3848 patch->rejected =0;3849return0;3850}38513852static intcheck_patch_list(struct apply_state *state,struct patch *patch)3853{3854int err =0;38553856prepare_symlink_changes(patch);3857prepare_fn_table(patch);3858while(patch) {3859if(apply_verbosely)3860say_patch_name(stderr,3861_("Checking patch%s..."), patch);3862 err |=check_patch(state, patch);3863 patch = patch->next;3864}3865return err;3866}38673868/* This function tries to read the sha1 from the current index */3869static intget_current_sha1(const char*path,unsigned char*sha1)3870{3871int pos;38723873if(read_cache() <0)3874return-1;3875 pos =cache_name_pos(path,strlen(path));3876if(pos <0)3877return-1;3878hashcpy(sha1, active_cache[pos]->sha1);3879return0;3880}38813882static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3883{3884/*3885 * A usable gitlink patch has only one fragment (hunk) that looks like:3886 * @@ -1 +1 @@3887 * -Subproject commit <old sha1>3888 * +Subproject commit <new sha1>3889 * or3890 * @@ -1 +0,0 @@3891 * -Subproject commit <old sha1>3892 * for a removal patch.3893 */3894struct fragment *hunk = p->fragments;3895static const char heading[] ="-Subproject commit ";3896char*preimage;38973898if(/* does the patch have only one hunk? */3899 hunk && !hunk->next &&3900/* is its preimage one line? */3901 hunk->oldpos ==1&& hunk->oldlines ==1&&3902/* does preimage begin with the heading? */3903(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3904starts_with(++preimage, heading) &&3905/* does it record full SHA-1? */3906!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3907 preimage[sizeof(heading) +40-1] =='\n'&&3908/* does the abbreviated name on the index line agree with it? */3909starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3910return0;/* it all looks fine */39113912/* we may have full object name on the index line */3913returnget_sha1_hex(p->old_sha1_prefix, sha1);3914}39153916/* Build an index that contains the just the files needed for a 3way merge */3917static voidbuild_fake_ancestor(struct patch *list,const char*filename)3918{3919struct patch *patch;3920struct index_state result = { NULL };3921static struct lock_file lock;39223923/* Once we start supporting the reverse patch, it may be3924 * worth showing the new sha1 prefix, but until then...3925 */3926for(patch = list; patch; patch = patch->next) {3927unsigned char sha1[20];3928struct cache_entry *ce;3929const char*name;39303931 name = patch->old_name ? patch->old_name : patch->new_name;3932if(0< patch->is_new)3933continue;39343935if(S_ISGITLINK(patch->old_mode)) {3936if(!preimage_sha1_in_gitlink_patch(patch, sha1))3937;/* ok, the textual part looks sane */3938else3939die("sha1 information is lacking or useless for submodule%s",3940 name);3941}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {3942;/* ok */3943}else if(!patch->lines_added && !patch->lines_deleted) {3944/* mode-only change: update the current */3945if(get_current_sha1(patch->old_name, sha1))3946die("mode change for%s, which is not "3947"in current HEAD", name);3948}else3949die("sha1 information is lacking or useless "3950"(%s).", name);39513952 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);3953if(!ce)3954die(_("make_cache_entry failed for path '%s'"), name);3955if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3956die("Could not add%sto temporary index", name);3957}39583959hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);3960if(write_locked_index(&result, &lock, COMMIT_LOCK))3961die("Could not write temporary index to%s", filename);39623963discard_index(&result);3964}39653966static voidstat_patch_list(struct patch *patch)3967{3968int files, adds, dels;39693970for(files = adds = dels =0; patch ; patch = patch->next) {3971 files++;3972 adds += patch->lines_added;3973 dels += patch->lines_deleted;3974show_stats(patch);3975}39763977print_stat_summary(stdout, files, adds, dels);3978}39793980static voidnumstat_patch_list(struct patch *patch)3981{3982for( ; patch; patch = patch->next) {3983const char*name;3984 name = patch->new_name ? patch->new_name : patch->old_name;3985if(patch->is_binary)3986printf("-\t-\t");3987else3988printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3989write_name_quoted(name, stdout, line_termination);3990}3991}39923993static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3994{3995if(mode)3996printf("%smode%06o%s\n", newdelete, mode, name);3997else3998printf("%s %s\n", newdelete, name);3999}40004001static voidshow_mode_change(struct patch *p,int show_name)4002{4003if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4004if(show_name)4005printf(" mode change%06o =>%06o%s\n",4006 p->old_mode, p->new_mode, p->new_name);4007else4008printf(" mode change%06o =>%06o\n",4009 p->old_mode, p->new_mode);4010}4011}40124013static voidshow_rename_copy(struct patch *p)4014{4015const char*renamecopy = p->is_rename ?"rename":"copy";4016const char*old, *new;40174018/* Find common prefix */4019 old = p->old_name;4020new= p->new_name;4021while(1) {4022const char*slash_old, *slash_new;4023 slash_old =strchr(old,'/');4024 slash_new =strchr(new,'/');4025if(!slash_old ||4026!slash_new ||4027 slash_old - old != slash_new -new||4028memcmp(old,new, slash_new -new))4029break;4030 old = slash_old +1;4031new= slash_new +1;4032}4033/* p->old_name thru old is the common prefix, and old and new4034 * through the end of names are renames4035 */4036if(old != p->old_name)4037printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4038(int)(old - p->old_name), p->old_name,4039 old,new, p->score);4040else4041printf("%s %s=>%s(%d%%)\n", renamecopy,4042 p->old_name, p->new_name, p->score);4043show_mode_change(p,0);4044}40454046static voidsummary_patch_list(struct patch *patch)4047{4048struct patch *p;40494050for(p = patch; p; p = p->next) {4051if(p->is_new)4052show_file_mode_name("create", p->new_mode, p->new_name);4053else if(p->is_delete)4054show_file_mode_name("delete", p->old_mode, p->old_name);4055else{4056if(p->is_rename || p->is_copy)4057show_rename_copy(p);4058else{4059if(p->score) {4060printf(" rewrite%s(%d%%)\n",4061 p->new_name, p->score);4062show_mode_change(p,0);4063}4064else4065show_mode_change(p,1);4066}4067}4068}4069}40704071static voidpatch_stats(struct patch *patch)4072{4073int lines = patch->lines_added + patch->lines_deleted;40744075if(lines > max_change)4076 max_change = lines;4077if(patch->old_name) {4078int len =quote_c_style(patch->old_name, NULL, NULL,0);4079if(!len)4080 len =strlen(patch->old_name);4081if(len > max_len)4082 max_len = len;4083}4084if(patch->new_name) {4085int len =quote_c_style(patch->new_name, NULL, NULL,0);4086if(!len)4087 len =strlen(patch->new_name);4088if(len > max_len)4089 max_len = len;4090}4091}40924093static voidremove_file(struct patch *patch,int rmdir_empty)4094{4095if(update_index) {4096if(remove_file_from_cache(patch->old_name) <0)4097die(_("unable to remove%sfrom index"), patch->old_name);4098}4099if(!cached) {4100if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4101remove_path(patch->old_name);4102}4103}4104}41054106static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)4107{4108struct stat st;4109struct cache_entry *ce;4110int namelen =strlen(path);4111unsigned ce_size =cache_entry_size(namelen);41124113if(!update_index)4114return;41154116 ce =xcalloc(1, ce_size);4117memcpy(ce->name, path, namelen);4118 ce->ce_mode =create_ce_mode(mode);4119 ce->ce_flags =create_ce_flags(0);4120 ce->ce_namelen = namelen;4121if(S_ISGITLINK(mode)) {4122const char*s;41234124if(!skip_prefix(buf,"Subproject commit ", &s) ||4125get_sha1_hex(s, ce->sha1))4126die(_("corrupt patch for submodule%s"), path);4127}else{4128if(!cached) {4129if(lstat(path, &st) <0)4130die_errno(_("unable to stat newly created file '%s'"),4131 path);4132fill_stat_cache_info(ce, &st);4133}4134if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4135die(_("unable to create backing store for newly created file%s"), path);4136}4137if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4138die(_("unable to add cache entry for%s"), path);4139}41404141static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4142{4143int fd;4144struct strbuf nbuf = STRBUF_INIT;41454146if(S_ISGITLINK(mode)) {4147struct stat st;4148if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4149return0;4150returnmkdir(path,0777);4151}41524153if(has_symlinks &&S_ISLNK(mode))4154/* Although buf:size is counted string, it also is NUL4155 * terminated.4156 */4157returnsymlink(buf, path);41584159 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4160if(fd <0)4161return-1;41624163if(convert_to_working_tree(path, buf, size, &nbuf)) {4164 size = nbuf.len;4165 buf = nbuf.buf;4166}4167write_or_die(fd, buf, size);4168strbuf_release(&nbuf);41694170if(close(fd) <0)4171die_errno(_("closing file '%s'"), path);4172return0;4173}41744175/*4176 * We optimistically assume that the directories exist,4177 * which is true 99% of the time anyway. If they don't,4178 * we create them and try again.4179 */4180static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)4181{4182if(cached)4183return;4184if(!try_create_file(path, mode, buf, size))4185return;41864187if(errno == ENOENT) {4188if(safe_create_leading_directories(path))4189return;4190if(!try_create_file(path, mode, buf, size))4191return;4192}41934194if(errno == EEXIST || errno == EACCES) {4195/* We may be trying to create a file where a directory4196 * used to be.4197 */4198struct stat st;4199if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4200 errno = EEXIST;4201}42024203if(errno == EEXIST) {4204unsigned int nr =getpid();42054206for(;;) {4207char newpath[PATH_MAX];4208mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4209if(!try_create_file(newpath, mode, buf, size)) {4210if(!rename(newpath, path))4211return;4212unlink_or_warn(newpath);4213break;4214}4215if(errno != EEXIST)4216break;4217++nr;4218}4219}4220die_errno(_("unable to write file '%s' mode%o"), path, mode);4221}42224223static voidadd_conflicted_stages_file(struct patch *patch)4224{4225int stage, namelen;4226unsigned ce_size, mode;4227struct cache_entry *ce;42284229if(!update_index)4230return;4231 namelen =strlen(patch->new_name);4232 ce_size =cache_entry_size(namelen);4233 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);42344235remove_file_from_cache(patch->new_name);4236for(stage =1; stage <4; stage++) {4237if(is_null_oid(&patch->threeway_stage[stage -1]))4238continue;4239 ce =xcalloc(1, ce_size);4240memcpy(ce->name, patch->new_name, namelen);4241 ce->ce_mode =create_ce_mode(mode);4242 ce->ce_flags =create_ce_flags(stage);4243 ce->ce_namelen = namelen;4244hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4245if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4246die(_("unable to add cache entry for%s"), patch->new_name);4247}4248}42494250static voidcreate_file(struct patch *patch)4251{4252char*path = patch->new_name;4253unsigned mode = patch->new_mode;4254unsigned long size = patch->resultsize;4255char*buf = patch->result;42564257if(!mode)4258 mode = S_IFREG |0644;4259create_one_file(path, mode, buf, size);42604261if(patch->conflicted_threeway)4262add_conflicted_stages_file(patch);4263else4264add_index_file(path, mode, buf, size);4265}42664267/* phase zero is to remove, phase one is to create */4268static voidwrite_out_one_result(struct patch *patch,int phase)4269{4270if(patch->is_delete >0) {4271if(phase ==0)4272remove_file(patch,1);4273return;4274}4275if(patch->is_new >0|| patch->is_copy) {4276if(phase ==1)4277create_file(patch);4278return;4279}4280/*4281 * Rename or modification boils down to the same4282 * thing: remove the old, write the new4283 */4284if(phase ==0)4285remove_file(patch, patch->is_rename);4286if(phase ==1)4287create_file(patch);4288}42894290static intwrite_out_one_reject(struct patch *patch)4291{4292FILE*rej;4293char namebuf[PATH_MAX];4294struct fragment *frag;4295int cnt =0;4296struct strbuf sb = STRBUF_INIT;42974298for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4299if(!frag->rejected)4300continue;4301 cnt++;4302}43034304if(!cnt) {4305if(apply_verbosely)4306say_patch_name(stderr,4307_("Applied patch%scleanly."), patch);4308return0;4309}43104311/* This should not happen, because a removal patch that leaves4312 * contents are marked "rejected" at the patch level.4313 */4314if(!patch->new_name)4315die(_("internal error"));43164317/* Say this even without --verbose */4318strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4319"Applying patch %%swith%drejects...",4320 cnt),4321 cnt);4322say_patch_name(stderr, sb.buf, patch);4323strbuf_release(&sb);43244325 cnt =strlen(patch->new_name);4326if(ARRAY_SIZE(namebuf) <= cnt +5) {4327 cnt =ARRAY_SIZE(namebuf) -5;4328warning(_("truncating .rej filename to %.*s.rej"),4329 cnt -1, patch->new_name);4330}4331memcpy(namebuf, patch->new_name, cnt);4332memcpy(namebuf + cnt,".rej",5);43334334 rej =fopen(namebuf,"w");4335if(!rej)4336returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));43374338/* Normal git tools never deal with .rej, so do not pretend4339 * this is a git patch by saying --git or giving extended4340 * headers. While at it, maybe please "kompare" that wants4341 * the trailing TAB and some garbage at the end of line ;-).4342 */4343fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4344 patch->new_name, patch->new_name);4345for(cnt =1, frag = patch->fragments;4346 frag;4347 cnt++, frag = frag->next) {4348if(!frag->rejected) {4349fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4350continue;4351}4352fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4353fprintf(rej,"%.*s", frag->size, frag->patch);4354if(frag->patch[frag->size-1] !='\n')4355fputc('\n', rej);4356}4357fclose(rej);4358return-1;4359}43604361static intwrite_out_results(struct patch *list)4362{4363int phase;4364int errs =0;4365struct patch *l;4366struct string_list cpath = STRING_LIST_INIT_DUP;43674368for(phase =0; phase <2; phase++) {4369 l = list;4370while(l) {4371if(l->rejected)4372 errs =1;4373else{4374write_out_one_result(l, phase);4375if(phase ==1) {4376if(write_out_one_reject(l))4377 errs =1;4378if(l->conflicted_threeway) {4379string_list_append(&cpath, l->new_name);4380 errs =1;4381}4382}4383}4384 l = l->next;4385}4386}43874388if(cpath.nr) {4389struct string_list_item *item;43904391string_list_sort(&cpath);4392for_each_string_list_item(item, &cpath)4393fprintf(stderr,"U%s\n", item->string);4394string_list_clear(&cpath,0);43954396rerere(0);4397}43984399return errs;4400}44014402static struct lock_file lock_file;44034404#define INACCURATE_EOF (1<<0)4405#define RECOUNT (1<<1)44064407static intapply_patch(struct apply_state *state,4408int fd,4409const char*filename,4410int options)4411{4412size_t offset;4413struct strbuf buf = STRBUF_INIT;/* owns the patch text */4414struct patch *list = NULL, **listp = &list;4415int skipped_patch =0;44164417 patch_input_file = filename;4418read_patch_file(&buf, fd);4419 offset =0;4420while(offset < buf.len) {4421struct patch *patch;4422int nr;44234424 patch =xcalloc(1,sizeof(*patch));4425 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4426 patch->recount = !!(options & RECOUNT);4427 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4428if(nr <0) {4429free_patch(patch);4430break;4431}4432if(state->apply_in_reverse)4433reverse_patches(patch);4434if(use_patch(state, patch)) {4435patch_stats(patch);4436*listp = patch;4437 listp = &patch->next;4438}4439else{4440if(apply_verbosely)4441say_patch_name(stderr,_("Skipped patch '%s'."), patch);4442free_patch(patch);4443 skipped_patch++;4444}4445 offset += nr;4446}44474448if(!list && !skipped_patch)4449die(_("unrecognized input"));44504451if(whitespace_error && (ws_error_action == die_on_ws_error))4452 apply =0;44534454 update_index = state->check_index && apply;4455if(update_index && newfd <0)4456 newfd =hold_locked_index(&lock_file,1);44574458if(state->check_index) {4459if(read_cache() <0)4460die(_("unable to read index file"));4461}44624463if((state->check || apply) &&4464check_patch_list(state, list) <0&&4465!state->apply_with_reject)4466exit(1);44674468if(apply &&write_out_results(list)) {4469if(state->apply_with_reject)4470exit(1);4471/* with --3way, we still need to write the index out */4472return1;4473}44744475if(fake_ancestor)4476build_fake_ancestor(list, fake_ancestor);44774478if(diffstat)4479stat_patch_list(list);44804481if(numstat)4482numstat_patch_list(list);44834484if(summary)4485summary_patch_list(list);44864487free_patch_list(list);4488strbuf_release(&buf);4489string_list_clear(&fn_table,0);4490return0;4491}44924493static voidgit_apply_config(void)4494{4495git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4496git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4497git_config(git_default_config, NULL);4498}44994500static intoption_parse_exclude(const struct option *opt,4501const char*arg,int unset)4502{4503add_name_limit(arg,1);4504return0;4505}45064507static intoption_parse_include(const struct option *opt,4508const char*arg,int unset)4509{4510add_name_limit(arg,0);4511 has_include =1;4512return0;4513}45144515static intoption_parse_p(const struct option *opt,4516const char*arg,int unset)4517{4518 state_p_value =atoi(arg);4519 p_value_known =1;4520return0;4521}45224523static intoption_parse_space_change(const struct option *opt,4524const char*arg,int unset)4525{4526if(unset)4527 ws_ignore_action = ignore_ws_none;4528else4529 ws_ignore_action = ignore_ws_change;4530return0;4531}45324533static intoption_parse_whitespace(const struct option *opt,4534const char*arg,int unset)4535{4536const char**whitespace_option = opt->value;45374538*whitespace_option = arg;4539parse_whitespace_option(arg);4540return0;4541}45424543static intoption_parse_directory(const struct option *opt,4544const char*arg,int unset)4545{4546strbuf_reset(&root);4547strbuf_addstr(&root, arg);4548strbuf_complete(&root,'/');4549return0;4550}45514552static voidinit_apply_state(struct apply_state *state,const char*prefix)4553{4554memset(state,0,sizeof(*state));4555 state->prefix = prefix;4556 state->prefix_length = state->prefix ?strlen(state->prefix) :0;45574558git_apply_config();4559if(apply_default_whitespace)4560parse_whitespace_option(apply_default_whitespace);4561if(apply_default_ignorewhitespace)4562parse_ignorewhitespace_option(apply_default_ignorewhitespace);4563}45644565static voidclear_apply_state(struct apply_state *state)4566{4567/* empty for now */4568}45694570intcmd_apply(int argc,const char**argv,const char*prefix)4571{4572int i;4573int errs =0;4574int is_not_gitdir = !startup_info->have_repository;4575int force_apply =0;4576int options =0;4577int read_stdin =1;4578struct apply_state state;45794580const char*whitespace_option = NULL;45814582struct option builtin_apply_options[] = {4583{ OPTION_CALLBACK,0,"exclude", NULL,N_("path"),4584N_("don't apply changes matching the given path"),45850, option_parse_exclude },4586{ OPTION_CALLBACK,0,"include", NULL,N_("path"),4587N_("apply changes matching the given path"),45880, option_parse_include },4589{ OPTION_CALLBACK,'p', NULL, NULL,N_("num"),4590N_("remove <num> leading slashes from traditional diff paths"),45910, option_parse_p },4592OPT_BOOL(0,"no-add", &no_add,4593N_("ignore additions made by the patch")),4594OPT_BOOL(0,"stat", &diffstat,4595N_("instead of applying the patch, output diffstat for the input")),4596OPT_NOOP_NOARG(0,"allow-binary-replacement"),4597OPT_NOOP_NOARG(0,"binary"),4598OPT_BOOL(0,"numstat", &numstat,4599N_("show number of added and deleted lines in decimal notation")),4600OPT_BOOL(0,"summary", &summary,4601N_("instead of applying the patch, output a summary for the input")),4602OPT_BOOL(0,"check", &state.check,4603N_("instead of applying the patch, see if the patch is applicable")),4604OPT_BOOL(0,"index", &state.check_index,4605N_("make sure the patch is applicable to the current index")),4606OPT_BOOL(0,"cached", &cached,4607N_("apply a patch without touching the working tree")),4608OPT_BOOL(0,"unsafe-paths", &unsafe_paths,4609N_("accept a patch that touches outside the working area")),4610OPT_BOOL(0,"apply", &force_apply,4611N_("also apply the patch (use with --stat/--summary/--check)")),4612OPT_BOOL('3',"3way", &threeway,4613N_("attempt three-way merge if a patch does not apply")),4614OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,4615N_("build a temporary index based on embedded index information")),4616/* Think twice before adding "--nul" synonym to this */4617OPT_SET_INT('z', NULL, &line_termination,4618N_("paths are separated with NUL character"),'\0'),4619OPT_INTEGER('C', NULL, &p_context,4620N_("ensure at least <n> lines of context match")),4621{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,N_("action"),4622N_("detect new or modified lines that have whitespace errors"),46230, option_parse_whitespace },4624{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,4625N_("ignore changes in whitespace when finding context"),4626 PARSE_OPT_NOARG, option_parse_space_change },4627{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,4628N_("ignore changes in whitespace when finding context"),4629 PARSE_OPT_NOARG, option_parse_space_change },4630OPT_BOOL('R',"reverse", &state.apply_in_reverse,4631N_("apply the patch in reverse")),4632OPT_BOOL(0,"unidiff-zero", &state.unidiff_zero,4633N_("don't expect at least one line of context")),4634OPT_BOOL(0,"reject", &state.apply_with_reject,4635N_("leave the rejected hunks in corresponding *.rej files")),4636OPT_BOOL(0,"allow-overlap", &allow_overlap,4637N_("allow overlapping hunks")),4638OPT__VERBOSE(&apply_verbosely,N_("be verbose")),4639OPT_BIT(0,"inaccurate-eof", &options,4640N_("tolerate incorrectly detected missing new-line at the end of file"),4641 INACCURATE_EOF),4642OPT_BIT(0,"recount", &options,4643N_("do not trust the line counts in the hunk headers"),4644 RECOUNT),4645{ OPTION_CALLBACK,0,"directory", NULL,N_("root"),4646N_("prepend <root> to all filenames"),46470, option_parse_directory },4648OPT_END()4649};46504651init_apply_state(&state, prefix);46524653 argc =parse_options(argc, argv, state.prefix, builtin_apply_options,4654 apply_usage,0);46554656if(state.apply_with_reject && threeway)4657die("--reject and --3way cannot be used together.");4658if(cached && threeway)4659die("--cached and --3way cannot be used together.");4660if(threeway) {4661if(is_not_gitdir)4662die(_("--3way outside a repository"));4663 state.check_index =1;4664}4665if(state.apply_with_reject)4666 apply = apply_verbosely =1;4667if(!force_apply && (diffstat || numstat || summary || state.check || fake_ancestor))4668 apply =0;4669if(state.check_index && is_not_gitdir)4670die(_("--index outside a repository"));4671if(cached) {4672if(is_not_gitdir)4673die(_("--cached outside a repository"));4674 state.check_index =1;4675}4676if(state.check_index)4677 unsafe_paths =0;46784679for(i =0; i < argc; i++) {4680const char*arg = argv[i];4681int fd;46824683if(!strcmp(arg,"-")) {4684 errs |=apply_patch(&state,0,"<stdin>", options);4685 read_stdin =0;4686continue;4687}else if(0< state.prefix_length)4688 arg =prefix_filename(state.prefix,4689 state.prefix_length,4690 arg);46914692 fd =open(arg, O_RDONLY);4693if(fd <0)4694die_errno(_("can't open patch '%s'"), arg);4695 read_stdin =0;4696set_default_whitespace_mode(whitespace_option);4697 errs |=apply_patch(&state, fd, arg, options);4698close(fd);4699}4700set_default_whitespace_mode(whitespace_option);4701if(read_stdin)4702 errs |=apply_patch(&state,0,"<stdin>", options);4703if(whitespace_error) {4704if(squelch_whitespace_errors &&4705 squelch_whitespace_errors < whitespace_error) {4706int squelched =4707 whitespace_error - squelch_whitespace_errors;4708warning(Q_("squelched%dwhitespace error",4709"squelched%dwhitespace errors",4710 squelched),4711 squelched);4712}4713if(ws_error_action == die_on_ws_error)4714die(Q_("%dline adds whitespace errors.",4715"%dlines add whitespace errors.",4716 whitespace_error),4717 whitespace_error);4718if(applied_after_fixing_ws && apply)4719warning("%dline%sapplied after"4720" fixing whitespace errors.",4721 applied_after_fixing_ws,4722 applied_after_fixing_ws ==1?"":"s");4723else if(whitespace_error)4724warning(Q_("%dline adds whitespace errors.",4725"%dlines add whitespace errors.",4726 whitespace_error),4727 whitespace_error);4728}47294730if(update_index) {4731if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK))4732die(_("Unable to write new index file"));4733}47344735clear_apply_state(&state);47364737return!!errs;4738}