1/* 2 * apply.c 3 * 4 * Copyright (C) Linus Torvalds, 2005 5 * 6 * This applies patches on top of some (arbitrary) version of the SCM. 7 * 8 */ 9#include"cache.h" 10#include"lockfile.h" 11#include"cache-tree.h" 12#include"quote.h" 13#include"blob.h" 14#include"delta.h" 15#include"builtin.h" 16#include"string-list.h" 17#include"dir.h" 18#include"diff.h" 19#include"parse-options.h" 20#include"xdiff-interface.h" 21#include"ll-merge.h" 22#include"rerere.h" 23 24struct apply_state { 25const char*prefix; 26int prefix_length; 27 28/* These control what gets looked at and modified */ 29int cached;/* apply to the index only */ 30int check;/* preimage must match working tree, don't actually apply */ 31int check_index;/* preimage must match the indexed version */ 32int update_index;/* check_index && apply */ 33 34/* These control cosmetic aspect of the output */ 35int diffstat;/* just show a diffstat, and don't actually apply */ 36 37/* These boolean parameters control how the apply is done */ 38int allow_overlap; 39int apply_in_reverse; 40int apply_with_reject; 41int apply_verbosely; 42int unidiff_zero; 43}; 44 45/* 46 * --numstat does numeric diffstat, and doesn't actually apply 47 * --index-info shows the old and new index info for paths if available. 48 */ 49static int newfd = -1; 50 51static int state_p_value =1; 52static int p_value_known; 53static int numstat; 54static int summary; 55static int apply =1; 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 apply_state *state,2631struct image *img,2632int applied_pos,2633struct image *preimage,2634struct image *postimage)2635{2636/*2637 * remove the copy of preimage at offset in img2638 * and replace it with postimage2639 */2640int i, nr;2641size_t remove_count, insert_count, applied_at =0;2642char*result;2643int preimage_limit;26442645/*2646 * If we are removing blank lines at the end of img,2647 * the preimage may extend beyond the end.2648 * If that is the case, we must be careful only to2649 * remove the part of the preimage that falls within2650 * the boundaries of img. Initialize preimage_limit2651 * to the number of lines in the preimage that falls2652 * within the boundaries.2653 */2654 preimage_limit = preimage->nr;2655if(preimage_limit > img->nr - applied_pos)2656 preimage_limit = img->nr - applied_pos;26572658for(i =0; i < applied_pos; i++)2659 applied_at += img->line[i].len;26602661 remove_count =0;2662for(i =0; i < preimage_limit; i++)2663 remove_count += img->line[applied_pos + i].len;2664 insert_count = postimage->len;26652666/* Adjust the contents */2667 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2668memcpy(result, img->buf, applied_at);2669memcpy(result + applied_at, postimage->buf, postimage->len);2670memcpy(result + applied_at + postimage->len,2671 img->buf + (applied_at + remove_count),2672 img->len - (applied_at + remove_count));2673free(img->buf);2674 img->buf = result;2675 img->len += insert_count - remove_count;2676 result[img->len] ='\0';26772678/* Adjust the line table */2679 nr = img->nr + postimage->nr - preimage_limit;2680if(preimage_limit < postimage->nr) {2681/*2682 * NOTE: this knows that we never call remove_first_line()2683 * on anything other than pre/post image.2684 */2685REALLOC_ARRAY(img->line, nr);2686 img->line_allocated = img->line;2687}2688if(preimage_limit != postimage->nr)2689memmove(img->line + applied_pos + postimage->nr,2690 img->line + applied_pos + preimage_limit,2691(img->nr - (applied_pos + preimage_limit)) *2692sizeof(*img->line));2693memcpy(img->line + applied_pos,2694 postimage->line,2695 postimage->nr *sizeof(*img->line));2696if(!state->allow_overlap)2697for(i =0; i < postimage->nr; i++)2698 img->line[applied_pos + i].flag |= LINE_PATCHED;2699 img->nr = nr;2700}27012702/*2703 * Use the patch-hunk text in "frag" to prepare two images (preimage and2704 * postimage) for the hunk. Find lines that match "preimage" in "img" and2705 * replace the part of "img" with "postimage" text.2706 */2707static intapply_one_fragment(struct apply_state *state,2708struct image *img,struct fragment *frag,2709int inaccurate_eof,unsigned ws_rule,2710int nth_fragment)2711{2712int match_beginning, match_end;2713const char*patch = frag->patch;2714int size = frag->size;2715char*old, *oldlines;2716struct strbuf newlines;2717int new_blank_lines_at_end =0;2718int found_new_blank_lines_at_end =0;2719int hunk_linenr = frag->linenr;2720unsigned long leading, trailing;2721int pos, applied_pos;2722struct image preimage;2723struct image postimage;27242725memset(&preimage,0,sizeof(preimage));2726memset(&postimage,0,sizeof(postimage));2727 oldlines =xmalloc(size);2728strbuf_init(&newlines, size);27292730 old = oldlines;2731while(size >0) {2732char first;2733int len =linelen(patch, size);2734int plen;2735int added_blank_line =0;2736int is_blank_context =0;2737size_t start;27382739if(!len)2740break;27412742/*2743 * "plen" is how much of the line we should use for2744 * the actual patch data. Normally we just remove the2745 * first character on the line, but if the line is2746 * followed by "\ No newline", then we also remove the2747 * last one (which is the newline, of course).2748 */2749 plen = len -1;2750if(len < size && patch[len] =='\\')2751 plen--;2752 first = *patch;2753if(state->apply_in_reverse) {2754if(first =='-')2755 first ='+';2756else if(first =='+')2757 first ='-';2758}27592760switch(first) {2761case'\n':2762/* Newer GNU diff, empty context line */2763if(plen <0)2764/* ... followed by '\No newline'; nothing */2765break;2766*old++ ='\n';2767strbuf_addch(&newlines,'\n');2768add_line_info(&preimage,"\n",1, LINE_COMMON);2769add_line_info(&postimage,"\n",1, LINE_COMMON);2770 is_blank_context =1;2771break;2772case' ':2773if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2774ws_blank_line(patch +1, plen, ws_rule))2775 is_blank_context =1;2776case'-':2777memcpy(old, patch +1, plen);2778add_line_info(&preimage, old, plen,2779(first ==' '? LINE_COMMON :0));2780 old += plen;2781if(first =='-')2782break;2783/* Fall-through for ' ' */2784case'+':2785/* --no-add does not add new lines */2786if(first =='+'&& no_add)2787break;27882789 start = newlines.len;2790if(first !='+'||2791!whitespace_error ||2792 ws_error_action != correct_ws_error) {2793strbuf_add(&newlines, patch +1, plen);2794}2795else{2796ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2797}2798add_line_info(&postimage, newlines.buf + start, newlines.len - start,2799(first =='+'?0: LINE_COMMON));2800if(first =='+'&&2801(ws_rule & WS_BLANK_AT_EOF) &&2802ws_blank_line(patch +1, plen, ws_rule))2803 added_blank_line =1;2804break;2805case'@':case'\\':2806/* Ignore it, we already handled it */2807break;2808default:2809if(state->apply_verbosely)2810error(_("invalid start of line: '%c'"), first);2811 applied_pos = -1;2812goto out;2813}2814if(added_blank_line) {2815if(!new_blank_lines_at_end)2816 found_new_blank_lines_at_end = hunk_linenr;2817 new_blank_lines_at_end++;2818}2819else if(is_blank_context)2820;2821else2822 new_blank_lines_at_end =0;2823 patch += len;2824 size -= len;2825 hunk_linenr++;2826}2827if(inaccurate_eof &&2828 old > oldlines && old[-1] =='\n'&&2829 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2830 old--;2831strbuf_setlen(&newlines, newlines.len -1);2832}28332834 leading = frag->leading;2835 trailing = frag->trailing;28362837/*2838 * A hunk to change lines at the beginning would begin with2839 * @@ -1,L +N,M @@2840 * but we need to be careful. -U0 that inserts before the second2841 * line also has this pattern.2842 *2843 * And a hunk to add to an empty file would begin with2844 * @@ -0,0 +N,M @@2845 *2846 * In other words, a hunk that is (frag->oldpos <= 1) with or2847 * without leading context must match at the beginning.2848 */2849 match_beginning = (!frag->oldpos ||2850(frag->oldpos ==1&& !state->unidiff_zero));28512852/*2853 * A hunk without trailing lines must match at the end.2854 * However, we simply cannot tell if a hunk must match end2855 * from the lack of trailing lines if the patch was generated2856 * with unidiff without any context.2857 */2858 match_end = !state->unidiff_zero && !trailing;28592860 pos = frag->newpos ? (frag->newpos -1) :0;2861 preimage.buf = oldlines;2862 preimage.len = old - oldlines;2863 postimage.buf = newlines.buf;2864 postimage.len = newlines.len;2865 preimage.line = preimage.line_allocated;2866 postimage.line = postimage.line_allocated;28672868for(;;) {28692870 applied_pos =find_pos(img, &preimage, &postimage, pos,2871 ws_rule, match_beginning, match_end);28722873if(applied_pos >=0)2874break;28752876/* Am I at my context limits? */2877if((leading <= p_context) && (trailing <= p_context))2878break;2879if(match_beginning || match_end) {2880 match_beginning = match_end =0;2881continue;2882}28832884/*2885 * Reduce the number of context lines; reduce both2886 * leading and trailing if they are equal otherwise2887 * just reduce the larger context.2888 */2889if(leading >= trailing) {2890remove_first_line(&preimage);2891remove_first_line(&postimage);2892 pos--;2893 leading--;2894}2895if(trailing > leading) {2896remove_last_line(&preimage);2897remove_last_line(&postimage);2898 trailing--;2899}2900}29012902if(applied_pos >=0) {2903if(new_blank_lines_at_end &&2904 preimage.nr + applied_pos >= img->nr &&2905(ws_rule & WS_BLANK_AT_EOF) &&2906 ws_error_action != nowarn_ws_error) {2907record_ws_error(WS_BLANK_AT_EOF,"+",1,2908 found_new_blank_lines_at_end);2909if(ws_error_action == correct_ws_error) {2910while(new_blank_lines_at_end--)2911remove_last_line(&postimage);2912}2913/*2914 * We would want to prevent write_out_results()2915 * from taking place in apply_patch() that follows2916 * the callchain led us here, which is:2917 * apply_patch->check_patch_list->check_patch->2918 * apply_data->apply_fragments->apply_one_fragment2919 */2920if(ws_error_action == die_on_ws_error)2921 apply =0;2922}29232924if(state->apply_verbosely && applied_pos != pos) {2925int offset = applied_pos - pos;2926if(state->apply_in_reverse)2927 offset =0- offset;2928fprintf_ln(stderr,2929Q_("Hunk #%dsucceeded at%d(offset%dline).",2930"Hunk #%dsucceeded at%d(offset%dlines).",2931 offset),2932 nth_fragment, applied_pos +1, offset);2933}29342935/*2936 * Warn if it was necessary to reduce the number2937 * of context lines.2938 */2939if((leading != frag->leading) ||2940(trailing != frag->trailing))2941fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2942" to apply fragment at%d"),2943 leading, trailing, applied_pos+1);2944update_image(state, img, applied_pos, &preimage, &postimage);2945}else{2946if(state->apply_verbosely)2947error(_("while searching for:\n%.*s"),2948(int)(old - oldlines), oldlines);2949}29502951out:2952free(oldlines);2953strbuf_release(&newlines);2954free(preimage.line_allocated);2955free(postimage.line_allocated);29562957return(applied_pos <0);2958}29592960static intapply_binary_fragment(struct apply_state *state,2961struct image *img,2962struct patch *patch)2963{2964struct fragment *fragment = patch->fragments;2965unsigned long len;2966void*dst;29672968if(!fragment)2969returnerror(_("missing binary patch data for '%s'"),2970 patch->new_name ?2971 patch->new_name :2972 patch->old_name);29732974/* Binary patch is irreversible without the optional second hunk */2975if(state->apply_in_reverse) {2976if(!fragment->next)2977returnerror("cannot reverse-apply a binary patch "2978"without the reverse hunk to '%s'",2979 patch->new_name2980? patch->new_name : patch->old_name);2981 fragment = fragment->next;2982}2983switch(fragment->binary_patch_method) {2984case BINARY_DELTA_DEFLATED:2985 dst =patch_delta(img->buf, img->len, fragment->patch,2986 fragment->size, &len);2987if(!dst)2988return-1;2989clear_image(img);2990 img->buf = dst;2991 img->len = len;2992return0;2993case BINARY_LITERAL_DEFLATED:2994clear_image(img);2995 img->len = fragment->size;2996 img->buf =xmemdupz(fragment->patch, img->len);2997return0;2998}2999return-1;3000}30013002/*3003 * Replace "img" with the result of applying the binary patch.3004 * The binary patch data itself in patch->fragment is still kept3005 * but the preimage prepared by the caller in "img" is freed here3006 * or in the helper function apply_binary_fragment() this calls.3007 */3008static intapply_binary(struct apply_state *state,3009struct image *img,3010struct patch *patch)3011{3012const char*name = patch->old_name ? patch->old_name : patch->new_name;3013unsigned char sha1[20];30143015/*3016 * For safety, we require patch index line to contain3017 * full 40-byte textual SHA1 for old and new, at least for now.3018 */3019if(strlen(patch->old_sha1_prefix) !=40||3020strlen(patch->new_sha1_prefix) !=40||3021get_sha1_hex(patch->old_sha1_prefix, sha1) ||3022get_sha1_hex(patch->new_sha1_prefix, sha1))3023returnerror("cannot apply binary patch to '%s' "3024"without full index line", name);30253026if(patch->old_name) {3027/*3028 * See if the old one matches what the patch3029 * applies to.3030 */3031hash_sha1_file(img->buf, img->len, blob_type, sha1);3032if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3033returnerror("the patch applies to '%s' (%s), "3034"which does not match the "3035"current contents.",3036 name,sha1_to_hex(sha1));3037}3038else{3039/* Otherwise, the old one must be empty. */3040if(img->len)3041returnerror("the patch applies to an empty "3042"'%s' but it is not empty", name);3043}30443045get_sha1_hex(patch->new_sha1_prefix, sha1);3046if(is_null_sha1(sha1)) {3047clear_image(img);3048return0;/* deletion patch */3049}30503051if(has_sha1_file(sha1)) {3052/* We already have the postimage */3053enum object_type type;3054unsigned long size;3055char*result;30563057 result =read_sha1_file(sha1, &type, &size);3058if(!result)3059returnerror("the necessary postimage%sfor "3060"'%s' cannot be read",3061 patch->new_sha1_prefix, name);3062clear_image(img);3063 img->buf = result;3064 img->len = size;3065}else{3066/*3067 * We have verified buf matches the preimage;3068 * apply the patch data to it, which is stored3069 * in the patch->fragments->{patch,size}.3070 */3071if(apply_binary_fragment(state, img, patch))3072returnerror(_("binary patch does not apply to '%s'"),3073 name);30743075/* verify that the result matches */3076hash_sha1_file(img->buf, img->len, blob_type, sha1);3077if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3078returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3079 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3080}30813082return0;3083}30843085static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3086{3087struct fragment *frag = patch->fragments;3088const char*name = patch->old_name ? patch->old_name : patch->new_name;3089unsigned ws_rule = patch->ws_rule;3090unsigned inaccurate_eof = patch->inaccurate_eof;3091int nth =0;30923093if(patch->is_binary)3094returnapply_binary(state, img, patch);30953096while(frag) {3097 nth++;3098if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3099error(_("patch failed:%s:%ld"), name, frag->oldpos);3100if(!state->apply_with_reject)3101return-1;3102 frag->rejected =1;3103}3104 frag = frag->next;3105}3106return0;3107}31083109static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3110{3111if(S_ISGITLINK(mode)) {3112strbuf_grow(buf,100);3113strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3114}else{3115enum object_type type;3116unsigned long sz;3117char*result;31183119 result =read_sha1_file(sha1, &type, &sz);3120if(!result)3121return-1;3122/* XXX read_sha1_file NUL-terminates */3123strbuf_attach(buf, result, sz, sz +1);3124}3125return0;3126}31273128static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3129{3130if(!ce)3131return0;3132returnread_blob_object(buf, ce->sha1, ce->ce_mode);3133}31343135static struct patch *in_fn_table(const char*name)3136{3137struct string_list_item *item;31383139if(name == NULL)3140return NULL;31413142 item =string_list_lookup(&fn_table, name);3143if(item != NULL)3144return(struct patch *)item->util;31453146return NULL;3147}31483149/*3150 * item->util in the filename table records the status of the path.3151 * Usually it points at a patch (whose result records the contents3152 * of it after applying it), but it could be PATH_WAS_DELETED for a3153 * path that a previously applied patch has already removed, or3154 * PATH_TO_BE_DELETED for a path that a later patch would remove.3155 *3156 * The latter is needed to deal with a case where two paths A and B3157 * are swapped by first renaming A to B and then renaming B to A;3158 * moving A to B should not be prevented due to presence of B as we3159 * will remove it in a later patch.3160 */3161#define PATH_TO_BE_DELETED ((struct patch *) -2)3162#define PATH_WAS_DELETED ((struct patch *) -1)31633164static intto_be_deleted(struct patch *patch)3165{3166return patch == PATH_TO_BE_DELETED;3167}31683169static intwas_deleted(struct patch *patch)3170{3171return patch == PATH_WAS_DELETED;3172}31733174static voidadd_to_fn_table(struct patch *patch)3175{3176struct string_list_item *item;31773178/*3179 * Always add new_name unless patch is a deletion3180 * This should cover the cases for normal diffs,3181 * file creations and copies3182 */3183if(patch->new_name != NULL) {3184 item =string_list_insert(&fn_table, patch->new_name);3185 item->util = patch;3186}31873188/*3189 * store a failure on rename/deletion cases because3190 * later chunks shouldn't patch old names3191 */3192if((patch->new_name == NULL) || (patch->is_rename)) {3193 item =string_list_insert(&fn_table, patch->old_name);3194 item->util = PATH_WAS_DELETED;3195}3196}31973198static voidprepare_fn_table(struct patch *patch)3199{3200/*3201 * store information about incoming file deletion3202 */3203while(patch) {3204if((patch->new_name == NULL) || (patch->is_rename)) {3205struct string_list_item *item;3206 item =string_list_insert(&fn_table, patch->old_name);3207 item->util = PATH_TO_BE_DELETED;3208}3209 patch = patch->next;3210}3211}32123213static intcheckout_target(struct index_state *istate,3214struct cache_entry *ce,struct stat *st)3215{3216struct checkout costate;32173218memset(&costate,0,sizeof(costate));3219 costate.base_dir ="";3220 costate.refresh_cache =1;3221 costate.istate = istate;3222if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3223returnerror(_("cannot checkout%s"), ce->name);3224return0;3225}32263227static struct patch *previous_patch(struct patch *patch,int*gone)3228{3229struct patch *previous;32303231*gone =0;3232if(patch->is_copy || patch->is_rename)3233return NULL;/* "git" patches do not depend on the order */32343235 previous =in_fn_table(patch->old_name);3236if(!previous)3237return NULL;32383239if(to_be_deleted(previous))3240return NULL;/* the deletion hasn't happened yet */32413242if(was_deleted(previous))3243*gone =1;32443245return previous;3246}32473248static intverify_index_match(const struct cache_entry *ce,struct stat *st)3249{3250if(S_ISGITLINK(ce->ce_mode)) {3251if(!S_ISDIR(st->st_mode))3252return-1;3253return0;3254}3255returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3256}32573258#define SUBMODULE_PATCH_WITHOUT_INDEX 132593260static intload_patch_target(struct apply_state *state,3261struct strbuf *buf,3262const struct cache_entry *ce,3263struct stat *st,3264const char*name,3265unsigned expected_mode)3266{3267if(state->cached || state->check_index) {3268if(read_file_or_gitlink(ce, buf))3269returnerror(_("read of%sfailed"), name);3270}else if(name) {3271if(S_ISGITLINK(expected_mode)) {3272if(ce)3273returnread_file_or_gitlink(ce, buf);3274else3275return SUBMODULE_PATCH_WITHOUT_INDEX;3276}else if(has_symlink_leading_path(name,strlen(name))) {3277returnerror(_("reading from '%s' beyond a symbolic link"), name);3278}else{3279if(read_old_data(st, name, buf))3280returnerror(_("read of%sfailed"), name);3281}3282}3283return0;3284}32853286/*3287 * We are about to apply "patch"; populate the "image" with the3288 * current version we have, from the working tree or from the index,3289 * depending on the situation e.g. --cached/--index. If we are3290 * applying a non-git patch that incrementally updates the tree,3291 * we read from the result of a previous diff.3292 */3293static intload_preimage(struct apply_state *state,3294struct image *image,3295struct patch *patch,struct stat *st,3296const struct cache_entry *ce)3297{3298struct strbuf buf = STRBUF_INIT;3299size_t len;3300char*img;3301struct patch *previous;3302int status;33033304 previous =previous_patch(patch, &status);3305if(status)3306returnerror(_("path%shas been renamed/deleted"),3307 patch->old_name);3308if(previous) {3309/* We have a patched copy in memory; use that. */3310strbuf_add(&buf, previous->result, previous->resultsize);3311}else{3312 status =load_patch_target(state, &buf, ce, st,3313 patch->old_name, patch->old_mode);3314if(status <0)3315return status;3316else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3317/*3318 * There is no way to apply subproject3319 * patch without looking at the index.3320 * NEEDSWORK: shouldn't this be flagged3321 * as an error???3322 */3323free_fragment_list(patch->fragments);3324 patch->fragments = NULL;3325}else if(status) {3326returnerror(_("read of%sfailed"), patch->old_name);3327}3328}33293330 img =strbuf_detach(&buf, &len);3331prepare_image(image, img, len, !patch->is_binary);3332return0;3333}33343335static intthree_way_merge(struct image *image,3336char*path,3337const unsigned char*base,3338const unsigned char*ours,3339const unsigned char*theirs)3340{3341 mmfile_t base_file, our_file, their_file;3342 mmbuffer_t result = { NULL };3343int status;33443345read_mmblob(&base_file, base);3346read_mmblob(&our_file, ours);3347read_mmblob(&their_file, theirs);3348 status =ll_merge(&result, path,3349&base_file,"base",3350&our_file,"ours",3351&their_file,"theirs", NULL);3352free(base_file.ptr);3353free(our_file.ptr);3354free(their_file.ptr);3355if(status <0|| !result.ptr) {3356free(result.ptr);3357return-1;3358}3359clear_image(image);3360 image->buf = result.ptr;3361 image->len = result.size;33623363return status;3364}33653366/*3367 * When directly falling back to add/add three-way merge, we read from3368 * the current contents of the new_name. In no cases other than that3369 * this function will be called.3370 */3371static intload_current(struct apply_state *state,3372struct image *image,3373struct patch *patch)3374{3375struct strbuf buf = STRBUF_INIT;3376int status, pos;3377size_t len;3378char*img;3379struct stat st;3380struct cache_entry *ce;3381char*name = patch->new_name;3382unsigned mode = patch->new_mode;33833384if(!patch->is_new)3385die("BUG: patch to%sis not a creation", patch->old_name);33863387 pos =cache_name_pos(name,strlen(name));3388if(pos <0)3389returnerror(_("%s: does not exist in index"), name);3390 ce = active_cache[pos];3391if(lstat(name, &st)) {3392if(errno != ENOENT)3393returnerror(_("%s:%s"), name,strerror(errno));3394if(checkout_target(&the_index, ce, &st))3395return-1;3396}3397if(verify_index_match(ce, &st))3398returnerror(_("%s: does not match index"), name);33993400 status =load_patch_target(state, &buf, ce, &st, name, mode);3401if(status <0)3402return status;3403else if(status)3404return-1;3405 img =strbuf_detach(&buf, &len);3406prepare_image(image, img, len, !patch->is_binary);3407return0;3408}34093410static inttry_threeway(struct apply_state *state,3411struct image *image,3412struct patch *patch,3413struct stat *st,3414const struct cache_entry *ce)3415{3416unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3417struct strbuf buf = STRBUF_INIT;3418size_t len;3419int status;3420char*img;3421struct image tmp_image;34223423/* No point falling back to 3-way merge in these cases */3424if(patch->is_delete ||3425S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3426return-1;34273428/* Preimage the patch was prepared for */3429if(patch->is_new)3430write_sha1_file("",0, blob_type, pre_sha1);3431else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3432read_blob_object(&buf, pre_sha1, patch->old_mode))3433returnerror("repository lacks the necessary blob to fall back on 3-way merge.");34343435fprintf(stderr,"Falling back to three-way merge...\n");34363437 img =strbuf_detach(&buf, &len);3438prepare_image(&tmp_image, img, len,1);3439/* Apply the patch to get the post image */3440if(apply_fragments(state, &tmp_image, patch) <0) {3441clear_image(&tmp_image);3442return-1;3443}3444/* post_sha1[] is theirs */3445write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3446clear_image(&tmp_image);34473448/* our_sha1[] is ours */3449if(patch->is_new) {3450if(load_current(state, &tmp_image, patch))3451returnerror("cannot read the current contents of '%s'",3452 patch->new_name);3453}else{3454if(load_preimage(state, &tmp_image, patch, st, ce))3455returnerror("cannot read the current contents of '%s'",3456 patch->old_name);3457}3458write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3459clear_image(&tmp_image);34603461/* in-core three-way merge between post and our using pre as base */3462 status =three_way_merge(image, patch->new_name,3463 pre_sha1, our_sha1, post_sha1);3464if(status <0) {3465fprintf(stderr,"Failed to fall back on three-way merge...\n");3466return status;3467}34683469if(status) {3470 patch->conflicted_threeway =1;3471if(patch->is_new)3472oidclr(&patch->threeway_stage[0]);3473else3474hashcpy(patch->threeway_stage[0].hash, pre_sha1);3475hashcpy(patch->threeway_stage[1].hash, our_sha1);3476hashcpy(patch->threeway_stage[2].hash, post_sha1);3477fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3478}else{3479fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3480}3481return0;3482}34833484static intapply_data(struct apply_state *state,struct patch *patch,3485struct stat *st,const struct cache_entry *ce)3486{3487struct image image;34883489if(load_preimage(state, &image, patch, st, ce) <0)3490return-1;34913492if(patch->direct_to_threeway ||3493apply_fragments(state, &image, patch) <0) {3494/* Note: with --reject, apply_fragments() returns 0 */3495if(!threeway ||try_threeway(state, &image, patch, st, ce) <0)3496return-1;3497}3498 patch->result = image.buf;3499 patch->resultsize = image.len;3500add_to_fn_table(patch);3501free(image.line_allocated);35023503if(0< patch->is_delete && patch->resultsize)3504returnerror(_("removal patch leaves file contents"));35053506return0;3507}35083509/*3510 * If "patch" that we are looking at modifies or deletes what we have,3511 * we would want it not to lose any local modification we have, either3512 * in the working tree or in the index.3513 *3514 * This also decides if a non-git patch is a creation patch or a3515 * modification to an existing empty file. We do not check the state3516 * of the current tree for a creation patch in this function; the caller3517 * check_patch() separately makes sure (and errors out otherwise) that3518 * the path the patch creates does not exist in the current tree.3519 */3520static intcheck_preimage(struct apply_state *state,3521struct patch *patch,3522struct cache_entry **ce,3523struct stat *st)3524{3525const char*old_name = patch->old_name;3526struct patch *previous = NULL;3527int stat_ret =0, status;3528unsigned st_mode =0;35293530if(!old_name)3531return0;35323533assert(patch->is_new <=0);3534 previous =previous_patch(patch, &status);35353536if(status)3537returnerror(_("path%shas been renamed/deleted"), old_name);3538if(previous) {3539 st_mode = previous->new_mode;3540}else if(!state->cached) {3541 stat_ret =lstat(old_name, st);3542if(stat_ret && errno != ENOENT)3543returnerror(_("%s:%s"), old_name,strerror(errno));3544}35453546if(state->check_index && !previous) {3547int pos =cache_name_pos(old_name,strlen(old_name));3548if(pos <0) {3549if(patch->is_new <0)3550goto is_new;3551returnerror(_("%s: does not exist in index"), old_name);3552}3553*ce = active_cache[pos];3554if(stat_ret <0) {3555if(checkout_target(&the_index, *ce, st))3556return-1;3557}3558if(!state->cached &&verify_index_match(*ce, st))3559returnerror(_("%s: does not match index"), old_name);3560if(state->cached)3561 st_mode = (*ce)->ce_mode;3562}else if(stat_ret <0) {3563if(patch->is_new <0)3564goto is_new;3565returnerror(_("%s:%s"), old_name,strerror(errno));3566}35673568if(!state->cached && !previous)3569 st_mode =ce_mode_from_stat(*ce, st->st_mode);35703571if(patch->is_new <0)3572 patch->is_new =0;3573if(!patch->old_mode)3574 patch->old_mode = st_mode;3575if((st_mode ^ patch->old_mode) & S_IFMT)3576returnerror(_("%s: wrong type"), old_name);3577if(st_mode != patch->old_mode)3578warning(_("%shas type%o, expected%o"),3579 old_name, st_mode, patch->old_mode);3580if(!patch->new_mode && !patch->is_delete)3581 patch->new_mode = st_mode;3582return0;35833584 is_new:3585 patch->is_new =1;3586 patch->is_delete =0;3587free(patch->old_name);3588 patch->old_name = NULL;3589return0;3590}359135923593#define EXISTS_IN_INDEX 13594#define EXISTS_IN_WORKTREE 235953596static intcheck_to_create(struct apply_state *state,3597const char*new_name,3598int ok_if_exists)3599{3600struct stat nst;36013602if(state->check_index &&3603cache_name_pos(new_name,strlen(new_name)) >=0&&3604!ok_if_exists)3605return EXISTS_IN_INDEX;3606if(state->cached)3607return0;36083609if(!lstat(new_name, &nst)) {3610if(S_ISDIR(nst.st_mode) || ok_if_exists)3611return0;3612/*3613 * A leading component of new_name might be a symlink3614 * that is going to be removed with this patch, but3615 * still pointing at somewhere that has the path.3616 * In such a case, path "new_name" does not exist as3617 * far as git is concerned.3618 */3619if(has_symlink_leading_path(new_name,strlen(new_name)))3620return0;36213622return EXISTS_IN_WORKTREE;3623}else if((errno != ENOENT) && (errno != ENOTDIR)) {3624returnerror("%s:%s", new_name,strerror(errno));3625}3626return0;3627}36283629/*3630 * We need to keep track of how symlinks in the preimage are3631 * manipulated by the patches. A patch to add a/b/c where a/b3632 * is a symlink should not be allowed to affect the directory3633 * the symlink points at, but if the same patch removes a/b,3634 * it is perfectly fine, as the patch removes a/b to make room3635 * to create a directory a/b so that a/b/c can be created.3636 */3637static struct string_list symlink_changes;3638#define SYMLINK_GOES_AWAY 013639#define SYMLINK_IN_RESULT 0236403641static uintptr_tregister_symlink_changes(const char*path,uintptr_t what)3642{3643struct string_list_item *ent;36443645 ent =string_list_lookup(&symlink_changes, path);3646if(!ent) {3647 ent =string_list_insert(&symlink_changes, path);3648 ent->util = (void*)0;3649}3650 ent->util = (void*)(what | ((uintptr_t)ent->util));3651return(uintptr_t)ent->util;3652}36533654static uintptr_tcheck_symlink_changes(const char*path)3655{3656struct string_list_item *ent;36573658 ent =string_list_lookup(&symlink_changes, path);3659if(!ent)3660return0;3661return(uintptr_t)ent->util;3662}36633664static voidprepare_symlink_changes(struct patch *patch)3665{3666for( ; patch; patch = patch->next) {3667if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3668(patch->is_rename || patch->is_delete))3669/* the symlink at patch->old_name is removed */3670register_symlink_changes(patch->old_name, SYMLINK_GOES_AWAY);36713672if(patch->new_name &&S_ISLNK(patch->new_mode))3673/* the symlink at patch->new_name is created or remains */3674register_symlink_changes(patch->new_name, SYMLINK_IN_RESULT);3675}3676}36773678static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3679{3680do{3681unsigned int change;36823683while(--name->len && name->buf[name->len] !='/')3684;/* scan backwards */3685if(!name->len)3686break;3687 name->buf[name->len] ='\0';3688 change =check_symlink_changes(name->buf);3689if(change & SYMLINK_IN_RESULT)3690return1;3691if(change & SYMLINK_GOES_AWAY)3692/*3693 * This cannot be "return 0", because we may3694 * see a new one created at a higher level.3695 */3696continue;36973698/* otherwise, check the preimage */3699if(state->check_index) {3700struct cache_entry *ce;37013702 ce =cache_file_exists(name->buf, name->len, ignore_case);3703if(ce &&S_ISLNK(ce->ce_mode))3704return1;3705}else{3706struct stat st;3707if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3708return1;3709}3710}while(1);3711return0;3712}37133714static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3715{3716int ret;3717struct strbuf name = STRBUF_INIT;37183719assert(*name_ !='\0');3720strbuf_addstr(&name, name_);3721 ret =path_is_beyond_symlink_1(state, &name);3722strbuf_release(&name);37233724return ret;3725}37263727static voiddie_on_unsafe_path(struct patch *patch)3728{3729const char*old_name = NULL;3730const char*new_name = NULL;3731if(patch->is_delete)3732 old_name = patch->old_name;3733else if(!patch->is_new && !patch->is_copy)3734 old_name = patch->old_name;3735if(!patch->is_delete)3736 new_name = patch->new_name;37373738if(old_name && !verify_path(old_name))3739die(_("invalid path '%s'"), old_name);3740if(new_name && !verify_path(new_name))3741die(_("invalid path '%s'"), new_name);3742}37433744/*3745 * Check and apply the patch in-core; leave the result in patch->result3746 * for the caller to write it out to the final destination.3747 */3748static intcheck_patch(struct apply_state *state,struct patch *patch)3749{3750struct stat st;3751const char*old_name = patch->old_name;3752const char*new_name = patch->new_name;3753const char*name = old_name ? old_name : new_name;3754struct cache_entry *ce = NULL;3755struct patch *tpatch;3756int ok_if_exists;3757int status;37583759 patch->rejected =1;/* we will drop this after we succeed */37603761 status =check_preimage(state, patch, &ce, &st);3762if(status)3763return status;3764 old_name = patch->old_name;37653766/*3767 * A type-change diff is always split into a patch to delete3768 * old, immediately followed by a patch to create new (see3769 * diff.c::run_diff()); in such a case it is Ok that the entry3770 * to be deleted by the previous patch is still in the working3771 * tree and in the index.3772 *3773 * A patch to swap-rename between A and B would first rename A3774 * to B and then rename B to A. While applying the first one,3775 * the presence of B should not stop A from getting renamed to3776 * B; ask to_be_deleted() about the later rename. Removal of3777 * B and rename from A to B is handled the same way by asking3778 * was_deleted().3779 */3780if((tpatch =in_fn_table(new_name)) &&3781(was_deleted(tpatch) ||to_be_deleted(tpatch)))3782 ok_if_exists =1;3783else3784 ok_if_exists =0;37853786if(new_name &&3787((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3788int err =check_to_create(state, new_name, ok_if_exists);37893790if(err && threeway) {3791 patch->direct_to_threeway =1;3792}else switch(err) {3793case0:3794break;/* happy */3795case EXISTS_IN_INDEX:3796returnerror(_("%s: already exists in index"), new_name);3797break;3798case EXISTS_IN_WORKTREE:3799returnerror(_("%s: already exists in working directory"),3800 new_name);3801default:3802return err;3803}38043805if(!patch->new_mode) {3806if(0< patch->is_new)3807 patch->new_mode = S_IFREG |0644;3808else3809 patch->new_mode = patch->old_mode;3810}3811}38123813if(new_name && old_name) {3814int same = !strcmp(old_name, new_name);3815if(!patch->new_mode)3816 patch->new_mode = patch->old_mode;3817if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3818if(same)3819returnerror(_("new mode (%o) of%sdoes not "3820"match old mode (%o)"),3821 patch->new_mode, new_name,3822 patch->old_mode);3823else3824returnerror(_("new mode (%o) of%sdoes not "3825"match old mode (%o) of%s"),3826 patch->new_mode, new_name,3827 patch->old_mode, old_name);3828}3829}38303831if(!unsafe_paths)3832die_on_unsafe_path(patch);38333834/*3835 * An attempt to read from or delete a path that is beyond a3836 * symbolic link will be prevented by load_patch_target() that3837 * is called at the beginning of apply_data() so we do not3838 * have to worry about a patch marked with "is_delete" bit3839 * here. We however need to make sure that the patch result3840 * is not deposited to a path that is beyond a symbolic link3841 * here.3842 */3843if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3844returnerror(_("affected file '%s' is beyond a symbolic link"),3845 patch->new_name);38463847if(apply_data(state, patch, &st, ce) <0)3848returnerror(_("%s: patch does not apply"), name);3849 patch->rejected =0;3850return0;3851}38523853static intcheck_patch_list(struct apply_state *state,struct patch *patch)3854{3855int err =0;38563857prepare_symlink_changes(patch);3858prepare_fn_table(patch);3859while(patch) {3860if(state->apply_verbosely)3861say_patch_name(stderr,3862_("Checking patch%s..."), patch);3863 err |=check_patch(state, patch);3864 patch = patch->next;3865}3866return err;3867}38683869/* This function tries to read the sha1 from the current index */3870static intget_current_sha1(const char*path,unsigned char*sha1)3871{3872int pos;38733874if(read_cache() <0)3875return-1;3876 pos =cache_name_pos(path,strlen(path));3877if(pos <0)3878return-1;3879hashcpy(sha1, active_cache[pos]->sha1);3880return0;3881}38823883static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3884{3885/*3886 * A usable gitlink patch has only one fragment (hunk) that looks like:3887 * @@ -1 +1 @@3888 * -Subproject commit <old sha1>3889 * +Subproject commit <new sha1>3890 * or3891 * @@ -1 +0,0 @@3892 * -Subproject commit <old sha1>3893 * for a removal patch.3894 */3895struct fragment *hunk = p->fragments;3896static const char heading[] ="-Subproject commit ";3897char*preimage;38983899if(/* does the patch have only one hunk? */3900 hunk && !hunk->next &&3901/* is its preimage one line? */3902 hunk->oldpos ==1&& hunk->oldlines ==1&&3903/* does preimage begin with the heading? */3904(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3905starts_with(++preimage, heading) &&3906/* does it record full SHA-1? */3907!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3908 preimage[sizeof(heading) +40-1] =='\n'&&3909/* does the abbreviated name on the index line agree with it? */3910starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3911return0;/* it all looks fine */39123913/* we may have full object name on the index line */3914returnget_sha1_hex(p->old_sha1_prefix, sha1);3915}39163917/* Build an index that contains the just the files needed for a 3way merge */3918static voidbuild_fake_ancestor(struct patch *list,const char*filename)3919{3920struct patch *patch;3921struct index_state result = { NULL };3922static struct lock_file lock;39233924/* Once we start supporting the reverse patch, it may be3925 * worth showing the new sha1 prefix, but until then...3926 */3927for(patch = list; patch; patch = patch->next) {3928unsigned char sha1[20];3929struct cache_entry *ce;3930const char*name;39313932 name = patch->old_name ? patch->old_name : patch->new_name;3933if(0< patch->is_new)3934continue;39353936if(S_ISGITLINK(patch->old_mode)) {3937if(!preimage_sha1_in_gitlink_patch(patch, sha1))3938;/* ok, the textual part looks sane */3939else3940die("sha1 information is lacking or useless for submodule%s",3941 name);3942}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {3943;/* ok */3944}else if(!patch->lines_added && !patch->lines_deleted) {3945/* mode-only change: update the current */3946if(get_current_sha1(patch->old_name, sha1))3947die("mode change for%s, which is not "3948"in current HEAD", name);3949}else3950die("sha1 information is lacking or useless "3951"(%s).", name);39523953 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);3954if(!ce)3955die(_("make_cache_entry failed for path '%s'"), name);3956if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3957die("Could not add%sto temporary index", name);3958}39593960hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);3961if(write_locked_index(&result, &lock, COMMIT_LOCK))3962die("Could not write temporary index to%s", filename);39633964discard_index(&result);3965}39663967static voidstat_patch_list(struct patch *patch)3968{3969int files, adds, dels;39703971for(files = adds = dels =0; patch ; patch = patch->next) {3972 files++;3973 adds += patch->lines_added;3974 dels += patch->lines_deleted;3975show_stats(patch);3976}39773978print_stat_summary(stdout, files, adds, dels);3979}39803981static voidnumstat_patch_list(struct patch *patch)3982{3983for( ; patch; patch = patch->next) {3984const char*name;3985 name = patch->new_name ? patch->new_name : patch->old_name;3986if(patch->is_binary)3987printf("-\t-\t");3988else3989printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3990write_name_quoted(name, stdout, line_termination);3991}3992}39933994static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3995{3996if(mode)3997printf("%smode%06o%s\n", newdelete, mode, name);3998else3999printf("%s %s\n", newdelete, name);4000}40014002static voidshow_mode_change(struct patch *p,int show_name)4003{4004if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4005if(show_name)4006printf(" mode change%06o =>%06o%s\n",4007 p->old_mode, p->new_mode, p->new_name);4008else4009printf(" mode change%06o =>%06o\n",4010 p->old_mode, p->new_mode);4011}4012}40134014static voidshow_rename_copy(struct patch *p)4015{4016const char*renamecopy = p->is_rename ?"rename":"copy";4017const char*old, *new;40184019/* Find common prefix */4020 old = p->old_name;4021new= p->new_name;4022while(1) {4023const char*slash_old, *slash_new;4024 slash_old =strchr(old,'/');4025 slash_new =strchr(new,'/');4026if(!slash_old ||4027!slash_new ||4028 slash_old - old != slash_new -new||4029memcmp(old,new, slash_new -new))4030break;4031 old = slash_old +1;4032new= slash_new +1;4033}4034/* p->old_name thru old is the common prefix, and old and new4035 * through the end of names are renames4036 */4037if(old != p->old_name)4038printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4039(int)(old - p->old_name), p->old_name,4040 old,new, p->score);4041else4042printf("%s %s=>%s(%d%%)\n", renamecopy,4043 p->old_name, p->new_name, p->score);4044show_mode_change(p,0);4045}40464047static voidsummary_patch_list(struct patch *patch)4048{4049struct patch *p;40504051for(p = patch; p; p = p->next) {4052if(p->is_new)4053show_file_mode_name("create", p->new_mode, p->new_name);4054else if(p->is_delete)4055show_file_mode_name("delete", p->old_mode, p->old_name);4056else{4057if(p->is_rename || p->is_copy)4058show_rename_copy(p);4059else{4060if(p->score) {4061printf(" rewrite%s(%d%%)\n",4062 p->new_name, p->score);4063show_mode_change(p,0);4064}4065else4066show_mode_change(p,1);4067}4068}4069}4070}40714072static voidpatch_stats(struct patch *patch)4073{4074int lines = patch->lines_added + patch->lines_deleted;40754076if(lines > max_change)4077 max_change = lines;4078if(patch->old_name) {4079int len =quote_c_style(patch->old_name, NULL, NULL,0);4080if(!len)4081 len =strlen(patch->old_name);4082if(len > max_len)4083 max_len = len;4084}4085if(patch->new_name) {4086int len =quote_c_style(patch->new_name, NULL, NULL,0);4087if(!len)4088 len =strlen(patch->new_name);4089if(len > max_len)4090 max_len = len;4091}4092}40934094static voidremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4095{4096if(state->update_index) {4097if(remove_file_from_cache(patch->old_name) <0)4098die(_("unable to remove%sfrom index"), patch->old_name);4099}4100if(!state->cached) {4101if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4102remove_path(patch->old_name);4103}4104}4105}41064107static voidadd_index_file(struct apply_state *state,4108const char*path,4109unsigned mode,4110void*buf,4111unsigned long size)4112{4113struct stat st;4114struct cache_entry *ce;4115int namelen =strlen(path);4116unsigned ce_size =cache_entry_size(namelen);41174118if(!state->update_index)4119return;41204121 ce =xcalloc(1, ce_size);4122memcpy(ce->name, path, namelen);4123 ce->ce_mode =create_ce_mode(mode);4124 ce->ce_flags =create_ce_flags(0);4125 ce->ce_namelen = namelen;4126if(S_ISGITLINK(mode)) {4127const char*s;41284129if(!skip_prefix(buf,"Subproject commit ", &s) ||4130get_sha1_hex(s, ce->sha1))4131die(_("corrupt patch for submodule%s"), path);4132}else{4133if(!state->cached) {4134if(lstat(path, &st) <0)4135die_errno(_("unable to stat newly created file '%s'"),4136 path);4137fill_stat_cache_info(ce, &st);4138}4139if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4140die(_("unable to create backing store for newly created file%s"), path);4141}4142if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4143die(_("unable to add cache entry for%s"), path);4144}41454146static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4147{4148int fd;4149struct strbuf nbuf = STRBUF_INIT;41504151if(S_ISGITLINK(mode)) {4152struct stat st;4153if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4154return0;4155returnmkdir(path,0777);4156}41574158if(has_symlinks &&S_ISLNK(mode))4159/* Although buf:size is counted string, it also is NUL4160 * terminated.4161 */4162returnsymlink(buf, path);41634164 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4165if(fd <0)4166return-1;41674168if(convert_to_working_tree(path, buf, size, &nbuf)) {4169 size = nbuf.len;4170 buf = nbuf.buf;4171}4172write_or_die(fd, buf, size);4173strbuf_release(&nbuf);41744175if(close(fd) <0)4176die_errno(_("closing file '%s'"), path);4177return0;4178}41794180/*4181 * We optimistically assume that the directories exist,4182 * which is true 99% of the time anyway. If they don't,4183 * we create them and try again.4184 */4185static voidcreate_one_file(struct apply_state *state,4186char*path,4187unsigned mode,4188const char*buf,4189unsigned long size)4190{4191if(state->cached)4192return;4193if(!try_create_file(path, mode, buf, size))4194return;41954196if(errno == ENOENT) {4197if(safe_create_leading_directories(path))4198return;4199if(!try_create_file(path, mode, buf, size))4200return;4201}42024203if(errno == EEXIST || errno == EACCES) {4204/* We may be trying to create a file where a directory4205 * used to be.4206 */4207struct stat st;4208if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4209 errno = EEXIST;4210}42114212if(errno == EEXIST) {4213unsigned int nr =getpid();42144215for(;;) {4216char newpath[PATH_MAX];4217mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4218if(!try_create_file(newpath, mode, buf, size)) {4219if(!rename(newpath, path))4220return;4221unlink_or_warn(newpath);4222break;4223}4224if(errno != EEXIST)4225break;4226++nr;4227}4228}4229die_errno(_("unable to write file '%s' mode%o"), path, mode);4230}42314232static voidadd_conflicted_stages_file(struct apply_state *state,4233struct patch *patch)4234{4235int stage, namelen;4236unsigned ce_size, mode;4237struct cache_entry *ce;42384239if(!state->update_index)4240return;4241 namelen =strlen(patch->new_name);4242 ce_size =cache_entry_size(namelen);4243 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);42444245remove_file_from_cache(patch->new_name);4246for(stage =1; stage <4; stage++) {4247if(is_null_oid(&patch->threeway_stage[stage -1]))4248continue;4249 ce =xcalloc(1, ce_size);4250memcpy(ce->name, patch->new_name, namelen);4251 ce->ce_mode =create_ce_mode(mode);4252 ce->ce_flags =create_ce_flags(stage);4253 ce->ce_namelen = namelen;4254hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4255if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4256die(_("unable to add cache entry for%s"), patch->new_name);4257}4258}42594260static voidcreate_file(struct apply_state *state,struct patch *patch)4261{4262char*path = patch->new_name;4263unsigned mode = patch->new_mode;4264unsigned long size = patch->resultsize;4265char*buf = patch->result;42664267if(!mode)4268 mode = S_IFREG |0644;4269create_one_file(state, path, mode, buf, size);42704271if(patch->conflicted_threeway)4272add_conflicted_stages_file(state, patch);4273else4274add_index_file(state, path, mode, buf, size);4275}42764277/* phase zero is to remove, phase one is to create */4278static voidwrite_out_one_result(struct apply_state *state,4279struct patch *patch,4280int phase)4281{4282if(patch->is_delete >0) {4283if(phase ==0)4284remove_file(state, patch,1);4285return;4286}4287if(patch->is_new >0|| patch->is_copy) {4288if(phase ==1)4289create_file(state, patch);4290return;4291}4292/*4293 * Rename or modification boils down to the same4294 * thing: remove the old, write the new4295 */4296if(phase ==0)4297remove_file(state, patch, patch->is_rename);4298if(phase ==1)4299create_file(state, patch);4300}43014302static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4303{4304FILE*rej;4305char namebuf[PATH_MAX];4306struct fragment *frag;4307int cnt =0;4308struct strbuf sb = STRBUF_INIT;43094310for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4311if(!frag->rejected)4312continue;4313 cnt++;4314}43154316if(!cnt) {4317if(state->apply_verbosely)4318say_patch_name(stderr,4319_("Applied patch%scleanly."), patch);4320return0;4321}43224323/* This should not happen, because a removal patch that leaves4324 * contents are marked "rejected" at the patch level.4325 */4326if(!patch->new_name)4327die(_("internal error"));43284329/* Say this even without --verbose */4330strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4331"Applying patch %%swith%drejects...",4332 cnt),4333 cnt);4334say_patch_name(stderr, sb.buf, patch);4335strbuf_release(&sb);43364337 cnt =strlen(patch->new_name);4338if(ARRAY_SIZE(namebuf) <= cnt +5) {4339 cnt =ARRAY_SIZE(namebuf) -5;4340warning(_("truncating .rej filename to %.*s.rej"),4341 cnt -1, patch->new_name);4342}4343memcpy(namebuf, patch->new_name, cnt);4344memcpy(namebuf + cnt,".rej",5);43454346 rej =fopen(namebuf,"w");4347if(!rej)4348returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));43494350/* Normal git tools never deal with .rej, so do not pretend4351 * this is a git patch by saying --git or giving extended4352 * headers. While at it, maybe please "kompare" that wants4353 * the trailing TAB and some garbage at the end of line ;-).4354 */4355fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4356 patch->new_name, patch->new_name);4357for(cnt =1, frag = patch->fragments;4358 frag;4359 cnt++, frag = frag->next) {4360if(!frag->rejected) {4361fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4362continue;4363}4364fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4365fprintf(rej,"%.*s", frag->size, frag->patch);4366if(frag->patch[frag->size-1] !='\n')4367fputc('\n', rej);4368}4369fclose(rej);4370return-1;4371}43724373static intwrite_out_results(struct apply_state *state,struct patch *list)4374{4375int phase;4376int errs =0;4377struct patch *l;4378struct string_list cpath = STRING_LIST_INIT_DUP;43794380for(phase =0; phase <2; phase++) {4381 l = list;4382while(l) {4383if(l->rejected)4384 errs =1;4385else{4386write_out_one_result(state, l, phase);4387if(phase ==1) {4388if(write_out_one_reject(state, l))4389 errs =1;4390if(l->conflicted_threeway) {4391string_list_append(&cpath, l->new_name);4392 errs =1;4393}4394}4395}4396 l = l->next;4397}4398}43994400if(cpath.nr) {4401struct string_list_item *item;44024403string_list_sort(&cpath);4404for_each_string_list_item(item, &cpath)4405fprintf(stderr,"U%s\n", item->string);4406string_list_clear(&cpath,0);44074408rerere(0);4409}44104411return errs;4412}44134414static struct lock_file lock_file;44154416#define INACCURATE_EOF (1<<0)4417#define RECOUNT (1<<1)44184419static intapply_patch(struct apply_state *state,4420int fd,4421const char*filename,4422int options)4423{4424size_t offset;4425struct strbuf buf = STRBUF_INIT;/* owns the patch text */4426struct patch *list = NULL, **listp = &list;4427int skipped_patch =0;44284429 patch_input_file = filename;4430read_patch_file(&buf, fd);4431 offset =0;4432while(offset < buf.len) {4433struct patch *patch;4434int nr;44354436 patch =xcalloc(1,sizeof(*patch));4437 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4438 patch->recount = !!(options & RECOUNT);4439 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4440if(nr <0) {4441free_patch(patch);4442break;4443}4444if(state->apply_in_reverse)4445reverse_patches(patch);4446if(use_patch(state, patch)) {4447patch_stats(patch);4448*listp = patch;4449 listp = &patch->next;4450}4451else{4452if(state->apply_verbosely)4453say_patch_name(stderr,_("Skipped patch '%s'."), patch);4454free_patch(patch);4455 skipped_patch++;4456}4457 offset += nr;4458}44594460if(!list && !skipped_patch)4461die(_("unrecognized input"));44624463if(whitespace_error && (ws_error_action == die_on_ws_error))4464 apply =0;44654466 state->update_index = state->check_index && apply;4467if(state->update_index && newfd <0)4468 newfd =hold_locked_index(&lock_file,1);44694470if(state->check_index) {4471if(read_cache() <0)4472die(_("unable to read index file"));4473}44744475if((state->check || apply) &&4476check_patch_list(state, list) <0&&4477!state->apply_with_reject)4478exit(1);44794480if(apply &&write_out_results(state, list)) {4481if(state->apply_with_reject)4482exit(1);4483/* with --3way, we still need to write the index out */4484return1;4485}44864487if(fake_ancestor)4488build_fake_ancestor(list, fake_ancestor);44894490if(state->diffstat)4491stat_patch_list(list);44924493if(numstat)4494numstat_patch_list(list);44954496if(summary)4497summary_patch_list(list);44984499free_patch_list(list);4500strbuf_release(&buf);4501string_list_clear(&fn_table,0);4502return0;4503}45044505static voidgit_apply_config(void)4506{4507git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4508git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4509git_config(git_default_config, NULL);4510}45114512static intoption_parse_exclude(const struct option *opt,4513const char*arg,int unset)4514{4515add_name_limit(arg,1);4516return0;4517}45184519static intoption_parse_include(const struct option *opt,4520const char*arg,int unset)4521{4522add_name_limit(arg,0);4523 has_include =1;4524return0;4525}45264527static intoption_parse_p(const struct option *opt,4528const char*arg,int unset)4529{4530 state_p_value =atoi(arg);4531 p_value_known =1;4532return0;4533}45344535static intoption_parse_space_change(const struct option *opt,4536const char*arg,int unset)4537{4538if(unset)4539 ws_ignore_action = ignore_ws_none;4540else4541 ws_ignore_action = ignore_ws_change;4542return0;4543}45444545static intoption_parse_whitespace(const struct option *opt,4546const char*arg,int unset)4547{4548const char**whitespace_option = opt->value;45494550*whitespace_option = arg;4551parse_whitespace_option(arg);4552return0;4553}45544555static intoption_parse_directory(const struct option *opt,4556const char*arg,int unset)4557{4558strbuf_reset(&root);4559strbuf_addstr(&root, arg);4560strbuf_complete(&root,'/');4561return0;4562}45634564static voidinit_apply_state(struct apply_state *state,const char*prefix)4565{4566memset(state,0,sizeof(*state));4567 state->prefix = prefix;4568 state->prefix_length = state->prefix ?strlen(state->prefix) :0;45694570git_apply_config();4571if(apply_default_whitespace)4572parse_whitespace_option(apply_default_whitespace);4573if(apply_default_ignorewhitespace)4574parse_ignorewhitespace_option(apply_default_ignorewhitespace);4575}45764577static voidclear_apply_state(struct apply_state *state)4578{4579/* empty for now */4580}45814582intcmd_apply(int argc,const char**argv,const char*prefix)4583{4584int i;4585int errs =0;4586int is_not_gitdir = !startup_info->have_repository;4587int force_apply =0;4588int options =0;4589int read_stdin =1;4590struct apply_state state;45914592const char*whitespace_option = NULL;45934594struct option builtin_apply_options[] = {4595{ OPTION_CALLBACK,0,"exclude", NULL,N_("path"),4596N_("don't apply changes matching the given path"),45970, option_parse_exclude },4598{ OPTION_CALLBACK,0,"include", NULL,N_("path"),4599N_("apply changes matching the given path"),46000, option_parse_include },4601{ OPTION_CALLBACK,'p', NULL, NULL,N_("num"),4602N_("remove <num> leading slashes from traditional diff paths"),46030, option_parse_p },4604OPT_BOOL(0,"no-add", &no_add,4605N_("ignore additions made by the patch")),4606OPT_BOOL(0,"stat", &state.diffstat,4607N_("instead of applying the patch, output diffstat for the input")),4608OPT_NOOP_NOARG(0,"allow-binary-replacement"),4609OPT_NOOP_NOARG(0,"binary"),4610OPT_BOOL(0,"numstat", &numstat,4611N_("show number of added and deleted lines in decimal notation")),4612OPT_BOOL(0,"summary", &summary,4613N_("instead of applying the patch, output a summary for the input")),4614OPT_BOOL(0,"check", &state.check,4615N_("instead of applying the patch, see if the patch is applicable")),4616OPT_BOOL(0,"index", &state.check_index,4617N_("make sure the patch is applicable to the current index")),4618OPT_BOOL(0,"cached", &state.cached,4619N_("apply a patch without touching the working tree")),4620OPT_BOOL(0,"unsafe-paths", &unsafe_paths,4621N_("accept a patch that touches outside the working area")),4622OPT_BOOL(0,"apply", &force_apply,4623N_("also apply the patch (use with --stat/--summary/--check)")),4624OPT_BOOL('3',"3way", &threeway,4625N_("attempt three-way merge if a patch does not apply")),4626OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,4627N_("build a temporary index based on embedded index information")),4628/* Think twice before adding "--nul" synonym to this */4629OPT_SET_INT('z', NULL, &line_termination,4630N_("paths are separated with NUL character"),'\0'),4631OPT_INTEGER('C', NULL, &p_context,4632N_("ensure at least <n> lines of context match")),4633{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,N_("action"),4634N_("detect new or modified lines that have whitespace errors"),46350, option_parse_whitespace },4636{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,4637N_("ignore changes in whitespace when finding context"),4638 PARSE_OPT_NOARG, option_parse_space_change },4639{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,4640N_("ignore changes in whitespace when finding context"),4641 PARSE_OPT_NOARG, option_parse_space_change },4642OPT_BOOL('R',"reverse", &state.apply_in_reverse,4643N_("apply the patch in reverse")),4644OPT_BOOL(0,"unidiff-zero", &state.unidiff_zero,4645N_("don't expect at least one line of context")),4646OPT_BOOL(0,"reject", &state.apply_with_reject,4647N_("leave the rejected hunks in corresponding *.rej files")),4648OPT_BOOL(0,"allow-overlap", &state.allow_overlap,4649N_("allow overlapping hunks")),4650OPT__VERBOSE(&state.apply_verbosely,N_("be verbose")),4651OPT_BIT(0,"inaccurate-eof", &options,4652N_("tolerate incorrectly detected missing new-line at the end of file"),4653 INACCURATE_EOF),4654OPT_BIT(0,"recount", &options,4655N_("do not trust the line counts in the hunk headers"),4656 RECOUNT),4657{ OPTION_CALLBACK,0,"directory", NULL,N_("root"),4658N_("prepend <root> to all filenames"),46590, option_parse_directory },4660OPT_END()4661};46624663init_apply_state(&state, prefix);46644665 argc =parse_options(argc, argv, state.prefix, builtin_apply_options,4666 apply_usage,0);46674668if(state.apply_with_reject && threeway)4669die("--reject and --3way cannot be used together.");4670if(state.cached && threeway)4671die("--cached and --3way cannot be used together.");4672if(threeway) {4673if(is_not_gitdir)4674die(_("--3way outside a repository"));4675 state.check_index =1;4676}4677if(state.apply_with_reject)4678 apply = state.apply_verbosely =1;4679if(!force_apply && (state.diffstat || numstat || summary || state.check || fake_ancestor))4680 apply =0;4681if(state.check_index && is_not_gitdir)4682die(_("--index outside a repository"));4683if(state.cached) {4684if(is_not_gitdir)4685die(_("--cached outside a repository"));4686 state.check_index =1;4687}4688if(state.check_index)4689 unsafe_paths =0;46904691for(i =0; i < argc; i++) {4692const char*arg = argv[i];4693int fd;46944695if(!strcmp(arg,"-")) {4696 errs |=apply_patch(&state,0,"<stdin>", options);4697 read_stdin =0;4698continue;4699}else if(0< state.prefix_length)4700 arg =prefix_filename(state.prefix,4701 state.prefix_length,4702 arg);47034704 fd =open(arg, O_RDONLY);4705if(fd <0)4706die_errno(_("can't open patch '%s'"), arg);4707 read_stdin =0;4708set_default_whitespace_mode(whitespace_option);4709 errs |=apply_patch(&state, fd, arg, options);4710close(fd);4711}4712set_default_whitespace_mode(whitespace_option);4713if(read_stdin)4714 errs |=apply_patch(&state,0,"<stdin>", options);4715if(whitespace_error) {4716if(squelch_whitespace_errors &&4717 squelch_whitespace_errors < whitespace_error) {4718int squelched =4719 whitespace_error - squelch_whitespace_errors;4720warning(Q_("squelched%dwhitespace error",4721"squelched%dwhitespace errors",4722 squelched),4723 squelched);4724}4725if(ws_error_action == die_on_ws_error)4726die(Q_("%dline adds whitespace errors.",4727"%dlines add whitespace errors.",4728 whitespace_error),4729 whitespace_error);4730if(applied_after_fixing_ws && apply)4731warning("%dline%sapplied after"4732" fixing whitespace errors.",4733 applied_after_fixing_ws,4734 applied_after_fixing_ws ==1?"":"s");4735else if(whitespace_error)4736warning(Q_("%dline adds whitespace errors.",4737"%dlines add whitespace errors.",4738 whitespace_error),4739 whitespace_error);4740}47414742if(state.update_index) {4743if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK))4744die(_("Unable to write new index file"));4745}47464747clear_apply_state(&state);47484749return!!errs;4750}