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 boolean parameters control how the apply is done */ 35int allow_overlap; 36int apply_in_reverse; 37int apply_with_reject; 38int apply_verbosely; 39int unidiff_zero; 40}; 41 42/* 43 * --stat does just a diffstat, and doesn't actually apply 44 * --numstat does numeric diffstat, and doesn't actually apply 45 * --index-info shows the old and new index info for paths if available. 46 */ 47static int newfd = -1; 48 49static int state_p_value =1; 50static int p_value_known; 51static int diffstat; 52static int numstat; 53static int summary; 54static int apply =1; 55static int no_add; 56static int threeway; 57static int unsafe_paths; 58static const char*fake_ancestor; 59static int line_termination ='\n'; 60static unsigned int p_context = UINT_MAX; 61static const char*const apply_usage[] = { 62N_("git apply [<options>] [<patch>...]"), 63 NULL 64}; 65 66static enum ws_error_action { 67 nowarn_ws_error, 68 warn_on_ws_error, 69 die_on_ws_error, 70 correct_ws_error 71} ws_error_action = warn_on_ws_error; 72static int whitespace_error; 73static int squelch_whitespace_errors =5; 74static int applied_after_fixing_ws; 75 76static enum ws_ignore { 77 ignore_ws_none, 78 ignore_ws_change 79} ws_ignore_action = ignore_ws_none; 80 81 82static const char*patch_input_file; 83static struct strbuf root = STRBUF_INIT; 84 85static voidparse_whitespace_option(const char*option) 86{ 87if(!option) { 88 ws_error_action = warn_on_ws_error; 89return; 90} 91if(!strcmp(option,"warn")) { 92 ws_error_action = warn_on_ws_error; 93return; 94} 95if(!strcmp(option,"nowarn")) { 96 ws_error_action = nowarn_ws_error; 97return; 98} 99if(!strcmp(option,"error")) { 100 ws_error_action = die_on_ws_error; 101return; 102} 103if(!strcmp(option,"error-all")) { 104 ws_error_action = die_on_ws_error; 105 squelch_whitespace_errors =0; 106return; 107} 108if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 109 ws_error_action = correct_ws_error; 110return; 111} 112die(_("unrecognized whitespace option '%s'"), option); 113} 114 115static voidparse_ignorewhitespace_option(const char*option) 116{ 117if(!option || !strcmp(option,"no") || 118!strcmp(option,"false") || !strcmp(option,"never") || 119!strcmp(option,"none")) { 120 ws_ignore_action = ignore_ws_none; 121return; 122} 123if(!strcmp(option,"change")) { 124 ws_ignore_action = ignore_ws_change; 125return; 126} 127die(_("unrecognized whitespace ignore option '%s'"), option); 128} 129 130static voidset_default_whitespace_mode(const char*whitespace_option) 131{ 132if(!whitespace_option && !apply_default_whitespace) 133 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 134} 135 136/* 137 * For "diff-stat" like behaviour, we keep track of the biggest change 138 * we've seen, and the longest filename. That allows us to do simple 139 * scaling. 140 */ 141static int max_change, max_len; 142 143/* 144 * Various "current state", notably line numbers and what 145 * file (and how) we're patching right now.. The "is_xxxx" 146 * things are flags, where -1 means "don't know yet". 147 */ 148static int state_linenr =1; 149 150/* 151 * This represents one "hunk" from a patch, starting with 152 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 153 * patch text is pointed at by patch, and its byte length 154 * is stored in size. leading and trailing are the number 155 * of context lines. 156 */ 157struct fragment { 158unsigned long leading, trailing; 159unsigned long oldpos, oldlines; 160unsigned long newpos, newlines; 161/* 162 * 'patch' is usually borrowed from buf in apply_patch(), 163 * but some codepaths store an allocated buffer. 164 */ 165const char*patch; 166unsigned free_patch:1, 167 rejected:1; 168int size; 169int linenr; 170struct fragment *next; 171}; 172 173/* 174 * When dealing with a binary patch, we reuse "leading" field 175 * to store the type of the binary hunk, either deflated "delta" 176 * or deflated "literal". 177 */ 178#define binary_patch_method leading 179#define BINARY_DELTA_DEFLATED 1 180#define BINARY_LITERAL_DEFLATED 2 181 182/* 183 * This represents a "patch" to a file, both metainfo changes 184 * such as creation/deletion, filemode and content changes represented 185 * as a series of fragments. 186 */ 187struct patch { 188char*new_name, *old_name, *def_name; 189unsigned int old_mode, new_mode; 190int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 191int rejected; 192unsigned ws_rule; 193int lines_added, lines_deleted; 194int score; 195unsigned int is_toplevel_relative:1; 196unsigned int inaccurate_eof:1; 197unsigned int is_binary:1; 198unsigned int is_copy:1; 199unsigned int is_rename:1; 200unsigned int recount:1; 201unsigned int conflicted_threeway:1; 202unsigned int direct_to_threeway:1; 203struct fragment *fragments; 204char*result; 205size_t resultsize; 206char old_sha1_prefix[41]; 207char new_sha1_prefix[41]; 208struct patch *next; 209 210/* three-way fallback result */ 211struct object_id threeway_stage[3]; 212}; 213 214static voidfree_fragment_list(struct fragment *list) 215{ 216while(list) { 217struct fragment *next = list->next; 218if(list->free_patch) 219free((char*)list->patch); 220free(list); 221 list = next; 222} 223} 224 225static voidfree_patch(struct patch *patch) 226{ 227free_fragment_list(patch->fragments); 228free(patch->def_name); 229free(patch->old_name); 230free(patch->new_name); 231free(patch->result); 232free(patch); 233} 234 235static voidfree_patch_list(struct patch *list) 236{ 237while(list) { 238struct patch *next = list->next; 239free_patch(list); 240 list = next; 241} 242} 243 244/* 245 * A line in a file, len-bytes long (includes the terminating LF, 246 * except for an incomplete line at the end if the file ends with 247 * one), and its contents hashes to 'hash'. 248 */ 249struct line { 250size_t len; 251unsigned hash :24; 252unsigned flag :8; 253#define LINE_COMMON 1 254#define LINE_PATCHED 2 255}; 256 257/* 258 * This represents a "file", which is an array of "lines". 259 */ 260struct image { 261char*buf; 262size_t len; 263size_t nr; 264size_t alloc; 265struct line *line_allocated; 266struct line *line; 267}; 268 269/* 270 * Records filenames that have been touched, in order to handle 271 * the case where more than one patches touch the same file. 272 */ 273 274static struct string_list fn_table; 275 276static uint32_thash_line(const char*cp,size_t len) 277{ 278size_t i; 279uint32_t h; 280for(i =0, h =0; i < len; i++) { 281if(!isspace(cp[i])) { 282 h = h *3+ (cp[i] &0xff); 283} 284} 285return h; 286} 287 288/* 289 * Compare lines s1 of length n1 and s2 of length n2, ignoring 290 * whitespace difference. Returns 1 if they match, 0 otherwise 291 */ 292static intfuzzy_matchlines(const char*s1,size_t n1, 293const char*s2,size_t n2) 294{ 295const char*last1 = s1 + n1 -1; 296const char*last2 = s2 + n2 -1; 297int result =0; 298 299/* ignore line endings */ 300while((*last1 =='\r') || (*last1 =='\n')) 301 last1--; 302while((*last2 =='\r') || (*last2 =='\n')) 303 last2--; 304 305/* skip leading whitespaces, if both begin with whitespace */ 306if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 307while(isspace(*s1) && (s1 <= last1)) 308 s1++; 309while(isspace(*s2) && (s2 <= last2)) 310 s2++; 311} 312/* early return if both lines are empty */ 313if((s1 > last1) && (s2 > last2)) 314return1; 315while(!result) { 316 result = *s1++ - *s2++; 317/* 318 * Skip whitespace inside. We check for whitespace on 319 * both buffers because we don't want "a b" to match 320 * "ab" 321 */ 322if(isspace(*s1) &&isspace(*s2)) { 323while(isspace(*s1) && s1 <= last1) 324 s1++; 325while(isspace(*s2) && s2 <= last2) 326 s2++; 327} 328/* 329 * If we reached the end on one side only, 330 * lines don't match 331 */ 332if( 333((s2 > last2) && (s1 <= last1)) || 334((s1 > last1) && (s2 <= last2))) 335return0; 336if((s1 > last1) && (s2 > last2)) 337break; 338} 339 340return!result; 341} 342 343static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 344{ 345ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 346 img->line_allocated[img->nr].len = len; 347 img->line_allocated[img->nr].hash =hash_line(bol, len); 348 img->line_allocated[img->nr].flag = flag; 349 img->nr++; 350} 351 352/* 353 * "buf" has the file contents to be patched (read from various sources). 354 * attach it to "image" and add line-based index to it. 355 * "image" now owns the "buf". 356 */ 357static voidprepare_image(struct image *image,char*buf,size_t len, 358int prepare_linetable) 359{ 360const char*cp, *ep; 361 362memset(image,0,sizeof(*image)); 363 image->buf = buf; 364 image->len = len; 365 366if(!prepare_linetable) 367return; 368 369 ep = image->buf + image->len; 370 cp = image->buf; 371while(cp < ep) { 372const char*next; 373for(next = cp; next < ep && *next !='\n'; next++) 374; 375if(next < ep) 376 next++; 377add_line_info(image, cp, next - cp,0); 378 cp = next; 379} 380 image->line = image->line_allocated; 381} 382 383static voidclear_image(struct image *image) 384{ 385free(image->buf); 386free(image->line_allocated); 387memset(image,0,sizeof(*image)); 388} 389 390/* fmt must contain _one_ %s and no other substitution */ 391static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 392{ 393struct strbuf sb = STRBUF_INIT; 394 395if(patch->old_name && patch->new_name && 396strcmp(patch->old_name, patch->new_name)) { 397quote_c_style(patch->old_name, &sb, NULL,0); 398strbuf_addstr(&sb," => "); 399quote_c_style(patch->new_name, &sb, NULL,0); 400}else{ 401const char*n = patch->new_name; 402if(!n) 403 n = patch->old_name; 404quote_c_style(n, &sb, NULL,0); 405} 406fprintf(output, fmt, sb.buf); 407fputc('\n', output); 408strbuf_release(&sb); 409} 410 411#define SLOP (16) 412 413static voidread_patch_file(struct strbuf *sb,int fd) 414{ 415if(strbuf_read(sb, fd,0) <0) 416die_errno("git apply: failed to read"); 417 418/* 419 * Make sure that we have some slop in the buffer 420 * so that we can do speculative "memcmp" etc, and 421 * see to it that it is NUL-filled. 422 */ 423strbuf_grow(sb, SLOP); 424memset(sb->buf + sb->len,0, SLOP); 425} 426 427static unsigned longlinelen(const char*buffer,unsigned long size) 428{ 429unsigned long len =0; 430while(size--) { 431 len++; 432if(*buffer++ =='\n') 433break; 434} 435return len; 436} 437 438static intis_dev_null(const char*str) 439{ 440returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 441} 442 443#define TERM_SPACE 1 444#define TERM_TAB 2 445 446static intname_terminate(const char*name,int namelen,int c,int terminate) 447{ 448if(c ==' '&& !(terminate & TERM_SPACE)) 449return0; 450if(c =='\t'&& !(terminate & TERM_TAB)) 451return0; 452 453return1; 454} 455 456/* remove double slashes to make --index work with such filenames */ 457static char*squash_slash(char*name) 458{ 459int i =0, j =0; 460 461if(!name) 462return NULL; 463 464while(name[i]) { 465if((name[j++] = name[i++]) =='/') 466while(name[i] =='/') 467 i++; 468} 469 name[j] ='\0'; 470return name; 471} 472 473static char*find_name_gnu(const char*line,const char*def,int p_value) 474{ 475struct strbuf name = STRBUF_INIT; 476char*cp; 477 478/* 479 * Proposed "new-style" GNU patch/diff format; see 480 * http://marc.info/?l=git&m=112927316408690&w=2 481 */ 482if(unquote_c_style(&name, line, NULL)) { 483strbuf_release(&name); 484return NULL; 485} 486 487for(cp = name.buf; p_value; p_value--) { 488 cp =strchr(cp,'/'); 489if(!cp) { 490strbuf_release(&name); 491return NULL; 492} 493 cp++; 494} 495 496strbuf_remove(&name,0, cp - name.buf); 497if(root.len) 498strbuf_insert(&name,0, root.buf, root.len); 499returnsquash_slash(strbuf_detach(&name, NULL)); 500} 501 502static size_tsane_tz_len(const char*line,size_t len) 503{ 504const char*tz, *p; 505 506if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 507return0; 508 tz = line + len -strlen(" +0500"); 509 510if(tz[1] !='+'&& tz[1] !='-') 511return0; 512 513for(p = tz +2; p != line + len; p++) 514if(!isdigit(*p)) 515return0; 516 517return line + len - tz; 518} 519 520static size_ttz_with_colon_len(const char*line,size_t len) 521{ 522const char*tz, *p; 523 524if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 525return0; 526 tz = line + len -strlen(" +08:00"); 527 528if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 529return0; 530 p = tz +2; 531if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 532!isdigit(*p++) || !isdigit(*p++)) 533return0; 534 535return line + len - tz; 536} 537 538static size_tdate_len(const char*line,size_t len) 539{ 540const char*date, *p; 541 542if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 543return0; 544 p = date = line + len -strlen("72-02-05"); 545 546if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 547!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 548!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 549return0; 550 551if(date - line >=strlen("19") && 552isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 553 date -=strlen("19"); 554 555return line + len - date; 556} 557 558static size_tshort_time_len(const char*line,size_t len) 559{ 560const char*time, *p; 561 562if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 563return0; 564 p = time = line + len -strlen(" 07:01:32"); 565 566/* Permit 1-digit hours? */ 567if(*p++ !=' '|| 568!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 569!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 570!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 571return0; 572 573return line + len - time; 574} 575 576static size_tfractional_time_len(const char*line,size_t len) 577{ 578const char*p; 579size_t n; 580 581/* Expected format: 19:41:17.620000023 */ 582if(!len || !isdigit(line[len -1])) 583return0; 584 p = line + len -1; 585 586/* Fractional seconds. */ 587while(p > line &&isdigit(*p)) 588 p--; 589if(*p !='.') 590return0; 591 592/* Hours, minutes, and whole seconds. */ 593 n =short_time_len(line, p - line); 594if(!n) 595return0; 596 597return line + len - p + n; 598} 599 600static size_ttrailing_spaces_len(const char*line,size_t len) 601{ 602const char*p; 603 604/* Expected format: ' ' x (1 or more) */ 605if(!len || line[len -1] !=' ') 606return0; 607 608 p = line + len; 609while(p != line) { 610 p--; 611if(*p !=' ') 612return line + len - (p +1); 613} 614 615/* All spaces! */ 616return len; 617} 618 619static size_tdiff_timestamp_len(const char*line,size_t len) 620{ 621const char*end = line + len; 622size_t n; 623 624/* 625 * Posix: 2010-07-05 19:41:17 626 * GNU: 2010-07-05 19:41:17.620000023 -0500 627 */ 628 629if(!isdigit(end[-1])) 630return0; 631 632 n =sane_tz_len(line, end - line); 633if(!n) 634 n =tz_with_colon_len(line, end - line); 635 end -= n; 636 637 n =short_time_len(line, end - line); 638if(!n) 639 n =fractional_time_len(line, end - line); 640 end -= n; 641 642 n =date_len(line, end - line); 643if(!n)/* No date. Too bad. */ 644return0; 645 end -= n; 646 647if(end == line)/* No space before date. */ 648return0; 649if(end[-1] =='\t') {/* Success! */ 650 end--; 651return line + len - end; 652} 653if(end[-1] !=' ')/* No space before date. */ 654return0; 655 656/* Whitespace damage. */ 657 end -=trailing_spaces_len(line, end - line); 658return line + len - end; 659} 660 661static char*find_name_common(const char*line,const char*def, 662int p_value,const char*end,int terminate) 663{ 664int len; 665const char*start = NULL; 666 667if(p_value ==0) 668 start = line; 669while(line != end) { 670char c = *line; 671 672if(!end &&isspace(c)) { 673if(c =='\n') 674break; 675if(name_terminate(start, line-start, c, terminate)) 676break; 677} 678 line++; 679if(c =='/'&& !--p_value) 680 start = line; 681} 682if(!start) 683returnsquash_slash(xstrdup_or_null(def)); 684 len = line - start; 685if(!len) 686returnsquash_slash(xstrdup_or_null(def)); 687 688/* 689 * Generally we prefer the shorter name, especially 690 * if the other one is just a variation of that with 691 * something else tacked on to the end (ie "file.orig" 692 * or "file~"). 693 */ 694if(def) { 695int deflen =strlen(def); 696if(deflen < len && !strncmp(start, def, deflen)) 697returnsquash_slash(xstrdup(def)); 698} 699 700if(root.len) { 701char*ret =xstrfmt("%s%.*s", root.buf, len, start); 702returnsquash_slash(ret); 703} 704 705returnsquash_slash(xmemdupz(start, len)); 706} 707 708static char*find_name(const char*line,char*def,int p_value,int terminate) 709{ 710if(*line =='"') { 711char*name =find_name_gnu(line, def, p_value); 712if(name) 713return name; 714} 715 716returnfind_name_common(line, def, p_value, NULL, terminate); 717} 718 719static char*find_name_traditional(const char*line,char*def,int p_value) 720{ 721size_t len; 722size_t date_len; 723 724if(*line =='"') { 725char*name =find_name_gnu(line, def, p_value); 726if(name) 727return name; 728} 729 730 len =strchrnul(line,'\n') - line; 731 date_len =diff_timestamp_len(line, len); 732if(!date_len) 733returnfind_name_common(line, def, p_value, NULL, TERM_TAB); 734 len -= date_len; 735 736returnfind_name_common(line, def, p_value, line + len,0); 737} 738 739static intcount_slashes(const char*cp) 740{ 741int cnt =0; 742char ch; 743 744while((ch = *cp++)) 745if(ch =='/') 746 cnt++; 747return cnt; 748} 749 750/* 751 * Given the string after "--- " or "+++ ", guess the appropriate 752 * p_value for the given patch. 753 */ 754static intguess_p_value(struct apply_state *state,const char*nameline) 755{ 756char*name, *cp; 757int val = -1; 758 759if(is_dev_null(nameline)) 760return-1; 761 name =find_name_traditional(nameline, NULL,0); 762if(!name) 763return-1; 764 cp =strchr(name,'/'); 765if(!cp) 766 val =0; 767else if(state->prefix) { 768/* 769 * Does it begin with "a/$our-prefix" and such? Then this is 770 * very likely to apply to our directory. 771 */ 772if(!strncmp(name, state->prefix, state->prefix_length)) 773 val =count_slashes(state->prefix); 774else{ 775 cp++; 776if(!strncmp(cp, state->prefix, state->prefix_length)) 777 val =count_slashes(state->prefix) +1; 778} 779} 780free(name); 781return val; 782} 783 784/* 785 * Does the ---/+++ line have the POSIX timestamp after the last HT? 786 * GNU diff puts epoch there to signal a creation/deletion event. Is 787 * this such a timestamp? 788 */ 789static inthas_epoch_timestamp(const char*nameline) 790{ 791/* 792 * We are only interested in epoch timestamp; any non-zero 793 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 794 * For the same reason, the date must be either 1969-12-31 or 795 * 1970-01-01, and the seconds part must be "00". 796 */ 797const char stamp_regexp[] = 798"^(1969-12-31|1970-01-01)" 799" " 800"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 801" " 802"([-+][0-2][0-9]:?[0-5][0-9])\n"; 803const char*timestamp = NULL, *cp, *colon; 804static regex_t *stamp; 805 regmatch_t m[10]; 806int zoneoffset; 807int hourminute; 808int status; 809 810for(cp = nameline; *cp !='\n'; cp++) { 811if(*cp =='\t') 812 timestamp = cp +1; 813} 814if(!timestamp) 815return0; 816if(!stamp) { 817 stamp =xmalloc(sizeof(*stamp)); 818if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 819warning(_("Cannot prepare timestamp regexp%s"), 820 stamp_regexp); 821return0; 822} 823} 824 825 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 826if(status) { 827if(status != REG_NOMATCH) 828warning(_("regexec returned%dfor input:%s"), 829 status, timestamp); 830return0; 831} 832 833 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 834if(*colon ==':') 835 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 836else 837 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 838if(timestamp[m[3].rm_so] =='-') 839 zoneoffset = -zoneoffset; 840 841/* 842 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 843 * (west of GMT) or 1970-01-01 (east of GMT) 844 */ 845if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 846(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 847return0; 848 849 hourminute = (strtol(timestamp +11, NULL,10) *60+ 850strtol(timestamp +14, NULL,10) - 851 zoneoffset); 852 853return((zoneoffset <0&& hourminute ==1440) || 854(0<= zoneoffset && !hourminute)); 855} 856 857/* 858 * Get the name etc info from the ---/+++ lines of a traditional patch header 859 * 860 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 861 * files, we can happily check the index for a match, but for creating a 862 * new file we should try to match whatever "patch" does. I have no idea. 863 */ 864static voidparse_traditional_patch(struct apply_state *state, 865const char*first, 866const char*second, 867struct patch *patch) 868{ 869char*name; 870 871 first +=4;/* skip "--- " */ 872 second +=4;/* skip "+++ " */ 873if(!p_value_known) { 874int p, q; 875 p =guess_p_value(state, first); 876 q =guess_p_value(state, second); 877if(p <0) p = q; 878if(0<= p && p == q) { 879 state_p_value = p; 880 p_value_known =1; 881} 882} 883if(is_dev_null(first)) { 884 patch->is_new =1; 885 patch->is_delete =0; 886 name =find_name_traditional(second, NULL, state_p_value); 887 patch->new_name = name; 888}else if(is_dev_null(second)) { 889 patch->is_new =0; 890 patch->is_delete =1; 891 name =find_name_traditional(first, NULL, state_p_value); 892 patch->old_name = name; 893}else{ 894char*first_name; 895 first_name =find_name_traditional(first, NULL, state_p_value); 896 name =find_name_traditional(second, first_name, state_p_value); 897free(first_name); 898if(has_epoch_timestamp(first)) { 899 patch->is_new =1; 900 patch->is_delete =0; 901 patch->new_name = name; 902}else if(has_epoch_timestamp(second)) { 903 patch->is_new =0; 904 patch->is_delete =1; 905 patch->old_name = name; 906}else{ 907 patch->old_name = name; 908 patch->new_name =xstrdup_or_null(name); 909} 910} 911if(!name) 912die(_("unable to find filename in patch at line%d"), state_linenr); 913} 914 915static intgitdiff_hdrend(const char*line,struct patch *patch) 916{ 917return-1; 918} 919 920/* 921 * We're anal about diff header consistency, to make 922 * sure that we don't end up having strange ambiguous 923 * patches floating around. 924 * 925 * As a result, gitdiff_{old|new}name() will check 926 * their names against any previous information, just 927 * to make sure.. 928 */ 929#define DIFF_OLD_NAME 0 930#define DIFF_NEW_NAME 1 931 932static voidgitdiff_verify_name(const char*line,int isnull,char**name,int side) 933{ 934if(!*name && !isnull) { 935*name =find_name(line, NULL, state_p_value, TERM_TAB); 936return; 937} 938 939if(*name) { 940int len =strlen(*name); 941char*another; 942if(isnull) 943die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 944*name, state_linenr); 945 another =find_name(line, NULL, state_p_value, TERM_TAB); 946if(!another ||memcmp(another, *name, len +1)) 947die((side == DIFF_NEW_NAME) ? 948_("git apply: bad git-diff - inconsistent new filename on line%d") : 949_("git apply: bad git-diff - inconsistent old filename on line%d"), state_linenr); 950free(another); 951}else{ 952/* expect "/dev/null" */ 953if(memcmp("/dev/null", line,9) || line[9] !='\n') 954die(_("git apply: bad git-diff - expected /dev/null on line%d"), state_linenr); 955} 956} 957 958static intgitdiff_oldname(const char*line,struct patch *patch) 959{ 960gitdiff_verify_name(line, patch->is_new, &patch->old_name, 961 DIFF_OLD_NAME); 962return0; 963} 964 965static intgitdiff_newname(const char*line,struct patch *patch) 966{ 967gitdiff_verify_name(line, patch->is_delete, &patch->new_name, 968 DIFF_NEW_NAME); 969return0; 970} 971 972static intgitdiff_oldmode(const char*line,struct patch *patch) 973{ 974 patch->old_mode =strtoul(line, NULL,8); 975return0; 976} 977 978static intgitdiff_newmode(const char*line,struct patch *patch) 979{ 980 patch->new_mode =strtoul(line, NULL,8); 981return0; 982} 983 984static intgitdiff_delete(const char*line,struct patch *patch) 985{ 986 patch->is_delete =1; 987free(patch->old_name); 988 patch->old_name =xstrdup_or_null(patch->def_name); 989returngitdiff_oldmode(line, patch); 990} 991 992static intgitdiff_newfile(const char*line,struct patch *patch) 993{ 994 patch->is_new =1; 995free(patch->new_name); 996 patch->new_name =xstrdup_or_null(patch->def_name); 997returngitdiff_newmode(line, patch); 998} 9991000static intgitdiff_copysrc(const char*line,struct patch *patch)1001{1002 patch->is_copy =1;1003free(patch->old_name);1004 patch->old_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1005return0;1006}10071008static intgitdiff_copydst(const char*line,struct patch *patch)1009{1010 patch->is_copy =1;1011free(patch->new_name);1012 patch->new_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1013return0;1014}10151016static intgitdiff_renamesrc(const char*line,struct patch *patch)1017{1018 patch->is_rename =1;1019free(patch->old_name);1020 patch->old_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1021return0;1022}10231024static intgitdiff_renamedst(const char*line,struct patch *patch)1025{1026 patch->is_rename =1;1027free(patch->new_name);1028 patch->new_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1029return0;1030}10311032static intgitdiff_similarity(const char*line,struct patch *patch)1033{1034unsigned long val =strtoul(line, NULL,10);1035if(val <=100)1036 patch->score = val;1037return0;1038}10391040static intgitdiff_dissimilarity(const char*line,struct patch *patch)1041{1042unsigned long val =strtoul(line, NULL,10);1043if(val <=100)1044 patch->score = val;1045return0;1046}10471048static intgitdiff_index(const char*line,struct patch *patch)1049{1050/*1051 * index line is N hexadecimal, "..", N hexadecimal,1052 * and optional space with octal mode.1053 */1054const char*ptr, *eol;1055int len;10561057 ptr =strchr(line,'.');1058if(!ptr || ptr[1] !='.'||40< ptr - line)1059return0;1060 len = ptr - line;1061memcpy(patch->old_sha1_prefix, line, len);1062 patch->old_sha1_prefix[len] =0;10631064 line = ptr +2;1065 ptr =strchr(line,' ');1066 eol =strchrnul(line,'\n');10671068if(!ptr || eol < ptr)1069 ptr = eol;1070 len = ptr - line;10711072if(40< len)1073return0;1074memcpy(patch->new_sha1_prefix, line, len);1075 patch->new_sha1_prefix[len] =0;1076if(*ptr ==' ')1077 patch->old_mode =strtoul(ptr+1, NULL,8);1078return0;1079}10801081/*1082 * This is normal for a diff that doesn't change anything: we'll fall through1083 * into the next diff. Tell the parser to break out.1084 */1085static intgitdiff_unrecognized(const char*line,struct patch *patch)1086{1087return-1;1088}10891090/*1091 * Skip p_value leading components from "line"; as we do not accept1092 * absolute paths, return NULL in that case.1093 */1094static const char*skip_tree_prefix(const char*line,int llen)1095{1096int nslash;1097int i;10981099if(!state_p_value)1100return(llen && line[0] =='/') ? NULL : line;11011102 nslash = state_p_value;1103for(i =0; i < llen; i++) {1104int ch = line[i];1105if(ch =='/'&& --nslash <=0)1106return(i ==0) ? NULL : &line[i +1];1107}1108return NULL;1109}11101111/*1112 * This is to extract the same name that appears on "diff --git"1113 * line. We do not find and return anything if it is a rename1114 * patch, and it is OK because we will find the name elsewhere.1115 * We need to reliably find name only when it is mode-change only,1116 * creation or deletion of an empty file. In any of these cases,1117 * both sides are the same name under a/ and b/ respectively.1118 */1119static char*git_header_name(const char*line,int llen)1120{1121const char*name;1122const char*second = NULL;1123size_t len, line_len;11241125 line +=strlen("diff --git ");1126 llen -=strlen("diff --git ");11271128if(*line =='"') {1129const char*cp;1130struct strbuf first = STRBUF_INIT;1131struct strbuf sp = STRBUF_INIT;11321133if(unquote_c_style(&first, line, &second))1134goto free_and_fail1;11351136/* strip the a/b prefix including trailing slash */1137 cp =skip_tree_prefix(first.buf, first.len);1138if(!cp)1139goto free_and_fail1;1140strbuf_remove(&first,0, cp - first.buf);11411142/*1143 * second points at one past closing dq of name.1144 * find the second name.1145 */1146while((second < line + llen) &&isspace(*second))1147 second++;11481149if(line + llen <= second)1150goto free_and_fail1;1151if(*second =='"') {1152if(unquote_c_style(&sp, second, NULL))1153goto free_and_fail1;1154 cp =skip_tree_prefix(sp.buf, sp.len);1155if(!cp)1156goto free_and_fail1;1157/* They must match, otherwise ignore */1158if(strcmp(cp, first.buf))1159goto free_and_fail1;1160strbuf_release(&sp);1161returnstrbuf_detach(&first, NULL);1162}11631164/* unquoted second */1165 cp =skip_tree_prefix(second, line + llen - second);1166if(!cp)1167goto free_and_fail1;1168if(line + llen - cp != first.len ||1169memcmp(first.buf, cp, first.len))1170goto free_and_fail1;1171returnstrbuf_detach(&first, NULL);11721173 free_and_fail1:1174strbuf_release(&first);1175strbuf_release(&sp);1176return NULL;1177}11781179/* unquoted first name */1180 name =skip_tree_prefix(line, llen);1181if(!name)1182return NULL;11831184/*1185 * since the first name is unquoted, a dq if exists must be1186 * the beginning of the second name.1187 */1188for(second = name; second < line + llen; second++) {1189if(*second =='"') {1190struct strbuf sp = STRBUF_INIT;1191const char*np;11921193if(unquote_c_style(&sp, second, NULL))1194goto free_and_fail2;11951196 np =skip_tree_prefix(sp.buf, sp.len);1197if(!np)1198goto free_and_fail2;11991200 len = sp.buf + sp.len - np;1201if(len < second - name &&1202!strncmp(np, name, len) &&1203isspace(name[len])) {1204/* Good */1205strbuf_remove(&sp,0, np - sp.buf);1206returnstrbuf_detach(&sp, NULL);1207}12081209 free_and_fail2:1210strbuf_release(&sp);1211return NULL;1212}1213}12141215/*1216 * Accept a name only if it shows up twice, exactly the same1217 * form.1218 */1219 second =strchr(name,'\n');1220if(!second)1221return NULL;1222 line_len = second - name;1223for(len =0; ; len++) {1224switch(name[len]) {1225default:1226continue;1227case'\n':1228return NULL;1229case'\t':case' ':1230/*1231 * Is this the separator between the preimage1232 * and the postimage pathname? Again, we are1233 * only interested in the case where there is1234 * no rename, as this is only to set def_name1235 * and a rename patch has the names elsewhere1236 * in an unambiguous form.1237 */1238if(!name[len +1])1239return NULL;/* no postimage name */1240 second =skip_tree_prefix(name + len +1,1241 line_len - (len +1));1242if(!second)1243return NULL;1244/*1245 * Does len bytes starting at "name" and "second"1246 * (that are separated by one HT or SP we just1247 * found) exactly match?1248 */1249if(second[len] =='\n'&& !strncmp(name, second, len))1250returnxmemdupz(name, len);1251}1252}1253}12541255/* Verify that we recognize the lines following a git header */1256static intparse_git_header(const char*line,int len,unsigned int size,struct patch *patch)1257{1258unsigned long offset;12591260/* A git diff has explicit new/delete information, so we don't guess */1261 patch->is_new =0;1262 patch->is_delete =0;12631264/*1265 * Some things may not have the old name in the1266 * rest of the headers anywhere (pure mode changes,1267 * or removing or adding empty files), so we get1268 * the default name from the header.1269 */1270 patch->def_name =git_header_name(line, len);1271if(patch->def_name && root.len) {1272char*s =xstrfmt("%s%s", root.buf, patch->def_name);1273free(patch->def_name);1274 patch->def_name = s;1275}12761277 line += len;1278 size -= len;1279 state_linenr++;1280for(offset = len ; size >0; offset += len, size -= len, line += len, state_linenr++) {1281static const struct opentry {1282const char*str;1283int(*fn)(const char*,struct patch *);1284} optable[] = {1285{"@@ -", gitdiff_hdrend },1286{"--- ", gitdiff_oldname },1287{"+++ ", gitdiff_newname },1288{"old mode ", gitdiff_oldmode },1289{"new mode ", gitdiff_newmode },1290{"deleted file mode ", gitdiff_delete },1291{"new file mode ", gitdiff_newfile },1292{"copy from ", gitdiff_copysrc },1293{"copy to ", gitdiff_copydst },1294{"rename old ", gitdiff_renamesrc },1295{"rename new ", gitdiff_renamedst },1296{"rename from ", gitdiff_renamesrc },1297{"rename to ", gitdiff_renamedst },1298{"similarity index ", gitdiff_similarity },1299{"dissimilarity index ", gitdiff_dissimilarity },1300{"index ", gitdiff_index },1301{"", gitdiff_unrecognized },1302};1303int i;13041305 len =linelen(line, size);1306if(!len || line[len-1] !='\n')1307break;1308for(i =0; i <ARRAY_SIZE(optable); i++) {1309const struct opentry *p = optable + i;1310int oplen =strlen(p->str);1311if(len < oplen ||memcmp(p->str, line, oplen))1312continue;1313if(p->fn(line + oplen, patch) <0)1314return offset;1315break;1316}1317}13181319return offset;1320}13211322static intparse_num(const char*line,unsigned long*p)1323{1324char*ptr;13251326if(!isdigit(*line))1327return0;1328*p =strtoul(line, &ptr,10);1329return ptr - line;1330}13311332static intparse_range(const char*line,int len,int offset,const char*expect,1333unsigned long*p1,unsigned long*p2)1334{1335int digits, ex;13361337if(offset <0|| offset >= len)1338return-1;1339 line += offset;1340 len -= offset;13411342 digits =parse_num(line, p1);1343if(!digits)1344return-1;13451346 offset += digits;1347 line += digits;1348 len -= digits;13491350*p2 =1;1351if(*line ==',') {1352 digits =parse_num(line+1, p2);1353if(!digits)1354return-1;13551356 offset += digits+1;1357 line += digits+1;1358 len -= digits+1;1359}13601361 ex =strlen(expect);1362if(ex > len)1363return-1;1364if(memcmp(line, expect, ex))1365return-1;13661367return offset + ex;1368}13691370static voidrecount_diff(const char*line,int size,struct fragment *fragment)1371{1372int oldlines =0, newlines =0, ret =0;13731374if(size <1) {1375warning("recount: ignore empty hunk");1376return;1377}13781379for(;;) {1380int len =linelen(line, size);1381 size -= len;1382 line += len;13831384if(size <1)1385break;13861387switch(*line) {1388case' ':case'\n':1389 newlines++;1390/* fall through */1391case'-':1392 oldlines++;1393continue;1394case'+':1395 newlines++;1396continue;1397case'\\':1398continue;1399case'@':1400 ret = size <3|| !starts_with(line,"@@ ");1401break;1402case'd':1403 ret = size <5|| !starts_with(line,"diff ");1404break;1405default:1406 ret = -1;1407break;1408}1409if(ret) {1410warning(_("recount: unexpected line: %.*s"),1411(int)linelen(line, size), line);1412return;1413}1414break;1415}1416 fragment->oldlines = oldlines;1417 fragment->newlines = newlines;1418}14191420/*1421 * Parse a unified diff fragment header of the1422 * form "@@ -a,b +c,d @@"1423 */1424static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1425{1426int offset;14271428if(!len || line[len-1] !='\n')1429return-1;14301431/* Figure out the number of lines in a fragment */1432 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1433 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14341435return offset;1436}14371438static intfind_header(struct apply_state *state,1439const char*line,1440unsigned long size,1441int*hdrsize,1442struct patch *patch)1443{1444unsigned long offset, len;14451446 patch->is_toplevel_relative =0;1447 patch->is_rename = patch->is_copy =0;1448 patch->is_new = patch->is_delete = -1;1449 patch->old_mode = patch->new_mode =0;1450 patch->old_name = patch->new_name = NULL;1451for(offset =0; size >0; offset += len, size -= len, line += len, state_linenr++) {1452unsigned long nextlen;14531454 len =linelen(line, size);1455if(!len)1456break;14571458/* Testing this early allows us to take a few shortcuts.. */1459if(len <6)1460continue;14611462/*1463 * Make sure we don't find any unconnected patch fragments.1464 * That's a sign that we didn't find a header, and that a1465 * patch has become corrupted/broken up.1466 */1467if(!memcmp("@@ -", line,4)) {1468struct fragment dummy;1469if(parse_fragment_header(line, len, &dummy) <0)1470continue;1471die(_("patch fragment without header at line%d: %.*s"),1472 state_linenr, (int)len-1, line);1473}14741475if(size < len +6)1476break;14771478/*1479 * Git patch? It might not have a real patch, just a rename1480 * or mode change, so we handle that specially1481 */1482if(!memcmp("diff --git ", line,11)) {1483int git_hdr_len =parse_git_header(line, len, size, patch);1484if(git_hdr_len <= len)1485continue;1486if(!patch->old_name && !patch->new_name) {1487if(!patch->def_name)1488die(Q_("git diff header lacks filename information when removing "1489"%dleading pathname component (line%d)",1490"git diff header lacks filename information when removing "1491"%dleading pathname components (line%d)",1492 state_p_value),1493 state_p_value, state_linenr);1494 patch->old_name =xstrdup(patch->def_name);1495 patch->new_name =xstrdup(patch->def_name);1496}1497if(!patch->is_delete && !patch->new_name)1498die("git diff header lacks filename information "1499"(line%d)", state_linenr);1500 patch->is_toplevel_relative =1;1501*hdrsize = git_hdr_len;1502return offset;1503}15041505/* --- followed by +++ ? */1506if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1507continue;15081509/*1510 * We only accept unified patches, so we want it to1511 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1512 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1513 */1514 nextlen =linelen(line + len, size - len);1515if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1516continue;15171518/* Ok, we'll consider it a patch */1519parse_traditional_patch(state, line, line+len, patch);1520*hdrsize = len + nextlen;1521 state_linenr +=2;1522return offset;1523}1524return-1;1525}15261527static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1528{1529char*err;15301531if(!result)1532return;15331534 whitespace_error++;1535if(squelch_whitespace_errors &&1536 squelch_whitespace_errors < whitespace_error)1537return;15381539 err =whitespace_error_string(result);1540fprintf(stderr,"%s:%d:%s.\n%.*s\n",1541 patch_input_file, linenr, err, len, line);1542free(err);1543}15441545static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1546{1547unsigned result =ws_check(line +1, len -1, ws_rule);15481549record_ws_error(result, line +1, len -2, state_linenr);1550}15511552/*1553 * Parse a unified diff. Note that this really needs to parse each1554 * fragment separately, since the only way to know the difference1555 * between a "---" that is part of a patch, and a "---" that starts1556 * the next patch is to look at the line counts..1557 */1558static intparse_fragment(struct apply_state *state,1559const char*line,1560unsigned long size,1561struct patch *patch,1562struct fragment *fragment)1563{1564int added, deleted;1565int len =linelen(line, size), offset;1566unsigned long oldlines, newlines;1567unsigned long leading, trailing;15681569 offset =parse_fragment_header(line, len, fragment);1570if(offset <0)1571return-1;1572if(offset >0&& patch->recount)1573recount_diff(line + offset, size - offset, fragment);1574 oldlines = fragment->oldlines;1575 newlines = fragment->newlines;1576 leading =0;1577 trailing =0;15781579/* Parse the thing.. */1580 line += len;1581 size -= len;1582 state_linenr++;1583 added = deleted =0;1584for(offset = len;15850< size;1586 offset += len, size -= len, line += len, state_linenr++) {1587if(!oldlines && !newlines)1588break;1589 len =linelen(line, size);1590if(!len || line[len-1] !='\n')1591return-1;1592switch(*line) {1593default:1594return-1;1595case'\n':/* newer GNU diff, an empty context line */1596case' ':1597 oldlines--;1598 newlines--;1599if(!deleted && !added)1600 leading++;1601 trailing++;1602if(!state->apply_in_reverse &&1603 ws_error_action == correct_ws_error)1604check_whitespace(line, len, patch->ws_rule);1605break;1606case'-':1607if(state->apply_in_reverse &&1608 ws_error_action != nowarn_ws_error)1609check_whitespace(line, len, patch->ws_rule);1610 deleted++;1611 oldlines--;1612 trailing =0;1613break;1614case'+':1615if(!state->apply_in_reverse &&1616 ws_error_action != nowarn_ws_error)1617check_whitespace(line, len, patch->ws_rule);1618 added++;1619 newlines--;1620 trailing =0;1621break;16221623/*1624 * We allow "\ No newline at end of file". Depending1625 * on locale settings when the patch was produced we1626 * don't know what this line looks like. The only1627 * thing we do know is that it begins with "\ ".1628 * Checking for 12 is just for sanity check -- any1629 * l10n of "\ No newline..." is at least that long.1630 */1631case'\\':1632if(len <12||memcmp(line,"\\",2))1633return-1;1634break;1635}1636}1637if(oldlines || newlines)1638return-1;1639if(!deleted && !added)1640return-1;16411642 fragment->leading = leading;1643 fragment->trailing = trailing;16441645/*1646 * If a fragment ends with an incomplete line, we failed to include1647 * it in the above loop because we hit oldlines == newlines == 01648 * before seeing it.1649 */1650if(12< size && !memcmp(line,"\\",2))1651 offset +=linelen(line, size);16521653 patch->lines_added += added;1654 patch->lines_deleted += deleted;16551656if(0< patch->is_new && oldlines)1657returnerror(_("new file depends on old contents"));1658if(0< patch->is_delete && newlines)1659returnerror(_("deleted file still has contents"));1660return offset;1661}16621663/*1664 * We have seen "diff --git a/... b/..." header (or a traditional patch1665 * header). Read hunks that belong to this patch into fragments and hang1666 * them to the given patch structure.1667 *1668 * The (fragment->patch, fragment->size) pair points into the memory given1669 * by the caller, not a copy, when we return.1670 */1671static intparse_single_patch(struct apply_state *state,1672const char*line,1673unsigned long size,1674struct patch *patch)1675{1676unsigned long offset =0;1677unsigned long oldlines =0, newlines =0, context =0;1678struct fragment **fragp = &patch->fragments;16791680while(size >4&& !memcmp(line,"@@ -",4)) {1681struct fragment *fragment;1682int len;16831684 fragment =xcalloc(1,sizeof(*fragment));1685 fragment->linenr = state_linenr;1686 len =parse_fragment(state, line, size, patch, fragment);1687if(len <=0)1688die(_("corrupt patch at line%d"), state_linenr);1689 fragment->patch = line;1690 fragment->size = len;1691 oldlines += fragment->oldlines;1692 newlines += fragment->newlines;1693 context += fragment->leading + fragment->trailing;16941695*fragp = fragment;1696 fragp = &fragment->next;16971698 offset += len;1699 line += len;1700 size -= len;1701}17021703/*1704 * If something was removed (i.e. we have old-lines) it cannot1705 * be creation, and if something was added it cannot be1706 * deletion. However, the reverse is not true; --unified=01707 * patches that only add are not necessarily creation even1708 * though they do not have any old lines, and ones that only1709 * delete are not necessarily deletion.1710 *1711 * Unfortunately, a real creation/deletion patch do _not_ have1712 * any context line by definition, so we cannot safely tell it1713 * apart with --unified=0 insanity. At least if the patch has1714 * more than one hunk it is not creation or deletion.1715 */1716if(patch->is_new <0&&1717(oldlines || (patch->fragments && patch->fragments->next)))1718 patch->is_new =0;1719if(patch->is_delete <0&&1720(newlines || (patch->fragments && patch->fragments->next)))1721 patch->is_delete =0;17221723if(0< patch->is_new && oldlines)1724die(_("new file%sdepends on old contents"), patch->new_name);1725if(0< patch->is_delete && newlines)1726die(_("deleted file%sstill has contents"), patch->old_name);1727if(!patch->is_delete && !newlines && context)1728fprintf_ln(stderr,1729_("** warning: "1730"file%sbecomes empty but is not deleted"),1731 patch->new_name);17321733return offset;1734}17351736staticinlineintmetadata_changes(struct patch *patch)1737{1738return patch->is_rename >0||1739 patch->is_copy >0||1740 patch->is_new >0||1741 patch->is_delete ||1742(patch->old_mode && patch->new_mode &&1743 patch->old_mode != patch->new_mode);1744}17451746static char*inflate_it(const void*data,unsigned long size,1747unsigned long inflated_size)1748{1749 git_zstream stream;1750void*out;1751int st;17521753memset(&stream,0,sizeof(stream));17541755 stream.next_in = (unsigned char*)data;1756 stream.avail_in = size;1757 stream.next_out = out =xmalloc(inflated_size);1758 stream.avail_out = inflated_size;1759git_inflate_init(&stream);1760 st =git_inflate(&stream, Z_FINISH);1761git_inflate_end(&stream);1762if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1763free(out);1764return NULL;1765}1766return out;1767}17681769/*1770 * Read a binary hunk and return a new fragment; fragment->patch1771 * points at an allocated memory that the caller must free, so1772 * it is marked as "->free_patch = 1".1773 */1774static struct fragment *parse_binary_hunk(char**buf_p,1775unsigned long*sz_p,1776int*status_p,1777int*used_p)1778{1779/*1780 * Expect a line that begins with binary patch method ("literal"1781 * or "delta"), followed by the length of data before deflating.1782 * a sequence of 'length-byte' followed by base-85 encoded data1783 * should follow, terminated by a newline.1784 *1785 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1786 * and we would limit the patch line to 66 characters,1787 * so one line can fit up to 13 groups that would decode1788 * to 52 bytes max. The length byte 'A'-'Z' corresponds1789 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1790 */1791int llen, used;1792unsigned long size = *sz_p;1793char*buffer = *buf_p;1794int patch_method;1795unsigned long origlen;1796char*data = NULL;1797int hunk_size =0;1798struct fragment *frag;17991800 llen =linelen(buffer, size);1801 used = llen;18021803*status_p =0;18041805if(starts_with(buffer,"delta ")) {1806 patch_method = BINARY_DELTA_DEFLATED;1807 origlen =strtoul(buffer +6, NULL,10);1808}1809else if(starts_with(buffer,"literal ")) {1810 patch_method = BINARY_LITERAL_DEFLATED;1811 origlen =strtoul(buffer +8, NULL,10);1812}1813else1814return NULL;18151816 state_linenr++;1817 buffer += llen;1818while(1) {1819int byte_length, max_byte_length, newsize;1820 llen =linelen(buffer, size);1821 used += llen;1822 state_linenr++;1823if(llen ==1) {1824/* consume the blank line */1825 buffer++;1826 size--;1827break;1828}1829/*1830 * Minimum line is "A00000\n" which is 7-byte long,1831 * and the line length must be multiple of 5 plus 2.1832 */1833if((llen <7) || (llen-2) %5)1834goto corrupt;1835 max_byte_length = (llen -2) /5*4;1836 byte_length = *buffer;1837if('A'<= byte_length && byte_length <='Z')1838 byte_length = byte_length -'A'+1;1839else if('a'<= byte_length && byte_length <='z')1840 byte_length = byte_length -'a'+27;1841else1842goto corrupt;1843/* if the input length was not multiple of 4, we would1844 * have filler at the end but the filler should never1845 * exceed 3 bytes1846 */1847if(max_byte_length < byte_length ||1848 byte_length <= max_byte_length -4)1849goto corrupt;1850 newsize = hunk_size + byte_length;1851 data =xrealloc(data, newsize);1852if(decode_85(data + hunk_size, buffer +1, byte_length))1853goto corrupt;1854 hunk_size = newsize;1855 buffer += llen;1856 size -= llen;1857}18581859 frag =xcalloc(1,sizeof(*frag));1860 frag->patch =inflate_it(data, hunk_size, origlen);1861 frag->free_patch =1;1862if(!frag->patch)1863goto corrupt;1864free(data);1865 frag->size = origlen;1866*buf_p = buffer;1867*sz_p = size;1868*used_p = used;1869 frag->binary_patch_method = patch_method;1870return frag;18711872 corrupt:1873free(data);1874*status_p = -1;1875error(_("corrupt binary patch at line%d: %.*s"),1876 state_linenr-1, llen-1, buffer);1877return NULL;1878}18791880/*1881 * Returns:1882 * -1 in case of error,1883 * the length of the parsed binary patch otherwise1884 */1885static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1886{1887/*1888 * We have read "GIT binary patch\n"; what follows is a line1889 * that says the patch method (currently, either "literal" or1890 * "delta") and the length of data before deflating; a1891 * sequence of 'length-byte' followed by base-85 encoded data1892 * follows.1893 *1894 * When a binary patch is reversible, there is another binary1895 * hunk in the same format, starting with patch method (either1896 * "literal" or "delta") with the length of data, and a sequence1897 * of length-byte + base-85 encoded data, terminated with another1898 * empty line. This data, when applied to the postimage, produces1899 * the preimage.1900 */1901struct fragment *forward;1902struct fragment *reverse;1903int status;1904int used, used_1;19051906 forward =parse_binary_hunk(&buffer, &size, &status, &used);1907if(!forward && !status)1908/* there has to be one hunk (forward hunk) */1909returnerror(_("unrecognized binary patch at line%d"), state_linenr-1);1910if(status)1911/* otherwise we already gave an error message */1912return status;19131914 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1915if(reverse)1916 used += used_1;1917else if(status) {1918/*1919 * Not having reverse hunk is not an error, but having1920 * a corrupt reverse hunk is.1921 */1922free((void*) forward->patch);1923free(forward);1924return status;1925}1926 forward->next = reverse;1927 patch->fragments = forward;1928 patch->is_binary =1;1929return used;1930}19311932static voidprefix_one(struct apply_state *state,char**name)1933{1934char*old_name = *name;1935if(!old_name)1936return;1937*name =xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));1938free(old_name);1939}19401941static voidprefix_patch(struct apply_state *state,struct patch *p)1942{1943if(!state->prefix || p->is_toplevel_relative)1944return;1945prefix_one(state, &p->new_name);1946prefix_one(state, &p->old_name);1947}19481949/*1950 * include/exclude1951 */19521953static struct string_list limit_by_name;1954static int has_include;1955static voidadd_name_limit(const char*name,int exclude)1956{1957struct string_list_item *it;19581959 it =string_list_append(&limit_by_name, name);1960 it->util = exclude ? NULL : (void*)1;1961}19621963static intuse_patch(struct apply_state *state,struct patch *p)1964{1965const char*pathname = p->new_name ? p->new_name : p->old_name;1966int i;19671968/* Paths outside are not touched regardless of "--include" */1969if(0< state->prefix_length) {1970int pathlen =strlen(pathname);1971if(pathlen <= state->prefix_length ||1972memcmp(state->prefix, pathname, state->prefix_length))1973return0;1974}19751976/* See if it matches any of exclude/include rule */1977for(i =0; i < limit_by_name.nr; i++) {1978struct string_list_item *it = &limit_by_name.items[i];1979if(!wildmatch(it->string, pathname,0, NULL))1980return(it->util != NULL);1981}19821983/*1984 * If we had any include, a path that does not match any rule is1985 * not used. Otherwise, we saw bunch of exclude rules (or none)1986 * and such a path is used.1987 */1988return!has_include;1989}199019911992/*1993 * Read the patch text in "buffer" that extends for "size" bytes; stop1994 * reading after seeing a single patch (i.e. changes to a single file).1995 * Create fragments (i.e. patch hunks) and hang them to the given patch.1996 * Return the number of bytes consumed, so that the caller can call us1997 * again for the next patch.1998 */1999static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2000{2001int hdrsize, patchsize;2002int offset =find_header(state, buffer, size, &hdrsize, patch);20032004if(offset <0)2005return offset;20062007prefix_patch(state, patch);20082009if(!use_patch(state, patch))2010 patch->ws_rule =0;2011else2012 patch->ws_rule =whitespace_rule(patch->new_name2013? patch->new_name2014: patch->old_name);20152016 patchsize =parse_single_patch(state,2017 buffer + offset + hdrsize,2018 size - offset - hdrsize,2019 patch);20202021if(!patchsize) {2022static const char git_binary[] ="GIT binary patch\n";2023int hd = hdrsize + offset;2024unsigned long llen =linelen(buffer + hd, size - hd);20252026if(llen ==sizeof(git_binary) -1&&2027!memcmp(git_binary, buffer + hd, llen)) {2028int used;2029 state_linenr++;2030 used =parse_binary(buffer + hd + llen,2031 size - hd - llen, patch);2032if(used <0)2033return-1;2034if(used)2035 patchsize = used + llen;2036else2037 patchsize =0;2038}2039else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2040static const char*binhdr[] = {2041"Binary files ",2042"Files ",2043 NULL,2044};2045int i;2046for(i =0; binhdr[i]; i++) {2047int len =strlen(binhdr[i]);2048if(len < size - hd &&2049!memcmp(binhdr[i], buffer + hd, len)) {2050 state_linenr++;2051 patch->is_binary =1;2052 patchsize = llen;2053break;2054}2055}2056}20572058/* Empty patch cannot be applied if it is a text patch2059 * without metadata change. A binary patch appears2060 * empty to us here.2061 */2062if((apply || state->check) &&2063(!patch->is_binary && !metadata_changes(patch)))2064die(_("patch with only garbage at line%d"), state_linenr);2065}20662067return offset + hdrsize + patchsize;2068}20692070#define swap(a,b) myswap((a),(b),sizeof(a))20712072#define myswap(a, b, size) do { \2073 unsigned char mytmp[size]; \2074 memcpy(mytmp, &a, size); \2075 memcpy(&a, &b, size); \2076 memcpy(&b, mytmp, size); \2077} while (0)20782079static voidreverse_patches(struct patch *p)2080{2081for(; p; p = p->next) {2082struct fragment *frag = p->fragments;20832084swap(p->new_name, p->old_name);2085swap(p->new_mode, p->old_mode);2086swap(p->is_new, p->is_delete);2087swap(p->lines_added, p->lines_deleted);2088swap(p->old_sha1_prefix, p->new_sha1_prefix);20892090for(; frag; frag = frag->next) {2091swap(frag->newpos, frag->oldpos);2092swap(frag->newlines, frag->oldlines);2093}2094}2095}20962097static const char pluses[] =2098"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2099static const char minuses[]=2100"----------------------------------------------------------------------";21012102static voidshow_stats(struct patch *patch)2103{2104struct strbuf qname = STRBUF_INIT;2105char*cp = patch->new_name ? patch->new_name : patch->old_name;2106int max, add, del;21072108quote_c_style(cp, &qname, NULL,0);21092110/*2111 * "scale" the filename2112 */2113 max = max_len;2114if(max >50)2115 max =50;21162117if(qname.len > max) {2118 cp =strchr(qname.buf + qname.len +3- max,'/');2119if(!cp)2120 cp = qname.buf + qname.len +3- max;2121strbuf_splice(&qname,0, cp - qname.buf,"...",3);2122}21232124if(patch->is_binary) {2125printf(" %-*s | Bin\n", max, qname.buf);2126strbuf_release(&qname);2127return;2128}21292130printf(" %-*s |", max, qname.buf);2131strbuf_release(&qname);21322133/*2134 * scale the add/delete2135 */2136 max = max + max_change >70?70- max : max_change;2137 add = patch->lines_added;2138 del = patch->lines_deleted;21392140if(max_change >0) {2141int total = ((add + del) * max + max_change /2) / max_change;2142 add = (add * max + max_change /2) / max_change;2143 del = total - add;2144}2145printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2146 add, pluses, del, minuses);2147}21482149static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2150{2151switch(st->st_mode & S_IFMT) {2152case S_IFLNK:2153if(strbuf_readlink(buf, path, st->st_size) <0)2154returnerror(_("unable to read symlink%s"), path);2155return0;2156case S_IFREG:2157if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2158returnerror(_("unable to open or read%s"), path);2159convert_to_git(path, buf->buf, buf->len, buf,0);2160return0;2161default:2162return-1;2163}2164}21652166/*2167 * Update the preimage, and the common lines in postimage,2168 * from buffer buf of length len. If postlen is 0 the postimage2169 * is updated in place, otherwise it's updated on a new buffer2170 * of length postlen2171 */21722173static voidupdate_pre_post_images(struct image *preimage,2174struct image *postimage,2175char*buf,2176size_t len,size_t postlen)2177{2178int i, ctx, reduced;2179char*new, *old, *fixed;2180struct image fixed_preimage;21812182/*2183 * Update the preimage with whitespace fixes. Note that we2184 * are not losing preimage->buf -- apply_one_fragment() will2185 * free "oldlines".2186 */2187prepare_image(&fixed_preimage, buf, len,1);2188assert(postlen2189? fixed_preimage.nr == preimage->nr2190: fixed_preimage.nr <= preimage->nr);2191for(i =0; i < fixed_preimage.nr; i++)2192 fixed_preimage.line[i].flag = preimage->line[i].flag;2193free(preimage->line_allocated);2194*preimage = fixed_preimage;21952196/*2197 * Adjust the common context lines in postimage. This can be2198 * done in-place when we are shrinking it with whitespace2199 * fixing, but needs a new buffer when ignoring whitespace or2200 * expanding leading tabs to spaces.2201 *2202 * We trust the caller to tell us if the update can be done2203 * in place (postlen==0) or not.2204 */2205 old = postimage->buf;2206if(postlen)2207new= postimage->buf =xmalloc(postlen);2208else2209new= old;2210 fixed = preimage->buf;22112212for(i = reduced = ctx =0; i < postimage->nr; i++) {2213size_t l_len = postimage->line[i].len;2214if(!(postimage->line[i].flag & LINE_COMMON)) {2215/* an added line -- no counterparts in preimage */2216memmove(new, old, l_len);2217 old += l_len;2218new+= l_len;2219continue;2220}22212222/* a common context -- skip it in the original postimage */2223 old += l_len;22242225/* and find the corresponding one in the fixed preimage */2226while(ctx < preimage->nr &&2227!(preimage->line[ctx].flag & LINE_COMMON)) {2228 fixed += preimage->line[ctx].len;2229 ctx++;2230}22312232/*2233 * preimage is expected to run out, if the caller2234 * fixed addition of trailing blank lines.2235 */2236if(preimage->nr <= ctx) {2237 reduced++;2238continue;2239}22402241/* and copy it in, while fixing the line length */2242 l_len = preimage->line[ctx].len;2243memcpy(new, fixed, l_len);2244new+= l_len;2245 fixed += l_len;2246 postimage->line[i].len = l_len;2247 ctx++;2248}22492250if(postlen2251? postlen <new- postimage->buf2252: postimage->len <new- postimage->buf)2253die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2254(int)postlen, (int) postimage->len, (int)(new- postimage->buf));22552256/* Fix the length of the whole thing */2257 postimage->len =new- postimage->buf;2258 postimage->nr -= reduced;2259}22602261static intline_by_line_fuzzy_match(struct image *img,2262struct image *preimage,2263struct image *postimage,2264unsigned longtry,2265int try_lno,2266int preimage_limit)2267{2268int i;2269size_t imgoff =0;2270size_t preoff =0;2271size_t postlen = postimage->len;2272size_t extra_chars;2273char*buf;2274char*preimage_eof;2275char*preimage_end;2276struct strbuf fixed;2277char*fixed_buf;2278size_t fixed_len;22792280for(i =0; i < preimage_limit; i++) {2281size_t prelen = preimage->line[i].len;2282size_t imglen = img->line[try_lno+i].len;22832284if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2285 preimage->buf + preoff, prelen))2286return0;2287if(preimage->line[i].flag & LINE_COMMON)2288 postlen += imglen - prelen;2289 imgoff += imglen;2290 preoff += prelen;2291}22922293/*2294 * Ok, the preimage matches with whitespace fuzz.2295 *2296 * imgoff now holds the true length of the target that2297 * matches the preimage before the end of the file.2298 *2299 * Count the number of characters in the preimage that fall2300 * beyond the end of the file and make sure that all of them2301 * are whitespace characters. (This can only happen if2302 * we are removing blank lines at the end of the file.)2303 */2304 buf = preimage_eof = preimage->buf + preoff;2305for( ; i < preimage->nr; i++)2306 preoff += preimage->line[i].len;2307 preimage_end = preimage->buf + preoff;2308for( ; buf < preimage_end; buf++)2309if(!isspace(*buf))2310return0;23112312/*2313 * Update the preimage and the common postimage context2314 * lines to use the same whitespace as the target.2315 * If whitespace is missing in the target (i.e.2316 * if the preimage extends beyond the end of the file),2317 * use the whitespace from the preimage.2318 */2319 extra_chars = preimage_end - preimage_eof;2320strbuf_init(&fixed, imgoff + extra_chars);2321strbuf_add(&fixed, img->buf +try, imgoff);2322strbuf_add(&fixed, preimage_eof, extra_chars);2323 fixed_buf =strbuf_detach(&fixed, &fixed_len);2324update_pre_post_images(preimage, postimage,2325 fixed_buf, fixed_len, postlen);2326return1;2327}23282329static intmatch_fragment(struct image *img,2330struct image *preimage,2331struct image *postimage,2332unsigned longtry,2333int try_lno,2334unsigned ws_rule,2335int match_beginning,int match_end)2336{2337int i;2338char*fixed_buf, *buf, *orig, *target;2339struct strbuf fixed;2340size_t fixed_len, postlen;2341int preimage_limit;23422343if(preimage->nr + try_lno <= img->nr) {2344/*2345 * The hunk falls within the boundaries of img.2346 */2347 preimage_limit = preimage->nr;2348if(match_end && (preimage->nr + try_lno != img->nr))2349return0;2350}else if(ws_error_action == correct_ws_error &&2351(ws_rule & WS_BLANK_AT_EOF)) {2352/*2353 * This hunk extends beyond the end of img, and we are2354 * removing blank lines at the end of the file. This2355 * many lines from the beginning of the preimage must2356 * match with img, and the remainder of the preimage2357 * must be blank.2358 */2359 preimage_limit = img->nr - try_lno;2360}else{2361/*2362 * The hunk extends beyond the end of the img and2363 * we are not removing blanks at the end, so we2364 * should reject the hunk at this position.2365 */2366return0;2367}23682369if(match_beginning && try_lno)2370return0;23712372/* Quick hash check */2373for(i =0; i < preimage_limit; i++)2374if((img->line[try_lno + i].flag & LINE_PATCHED) ||2375(preimage->line[i].hash != img->line[try_lno + i].hash))2376return0;23772378if(preimage_limit == preimage->nr) {2379/*2380 * Do we have an exact match? If we were told to match2381 * at the end, size must be exactly at try+fragsize,2382 * otherwise try+fragsize must be still within the preimage,2383 * and either case, the old piece should match the preimage2384 * exactly.2385 */2386if((match_end2387? (try+ preimage->len == img->len)2388: (try+ preimage->len <= img->len)) &&2389!memcmp(img->buf +try, preimage->buf, preimage->len))2390return1;2391}else{2392/*2393 * The preimage extends beyond the end of img, so2394 * there cannot be an exact match.2395 *2396 * There must be one non-blank context line that match2397 * a line before the end of img.2398 */2399char*buf_end;24002401 buf = preimage->buf;2402 buf_end = buf;2403for(i =0; i < preimage_limit; i++)2404 buf_end += preimage->line[i].len;24052406for( ; buf < buf_end; buf++)2407if(!isspace(*buf))2408break;2409if(buf == buf_end)2410return0;2411}24122413/*2414 * No exact match. If we are ignoring whitespace, run a line-by-line2415 * fuzzy matching. We collect all the line length information because2416 * we need it to adjust whitespace if we match.2417 */2418if(ws_ignore_action == ignore_ws_change)2419returnline_by_line_fuzzy_match(img, preimage, postimage,2420try, try_lno, preimage_limit);24212422if(ws_error_action != correct_ws_error)2423return0;24242425/*2426 * The hunk does not apply byte-by-byte, but the hash says2427 * it might with whitespace fuzz. We weren't asked to2428 * ignore whitespace, we were asked to correct whitespace2429 * errors, so let's try matching after whitespace correction.2430 *2431 * While checking the preimage against the target, whitespace2432 * errors in both fixed, we count how large the corresponding2433 * postimage needs to be. The postimage prepared by2434 * apply_one_fragment() has whitespace errors fixed on added2435 * lines already, but the common lines were propagated as-is,2436 * which may become longer when their whitespace errors are2437 * fixed.2438 */24392440/* First count added lines in postimage */2441 postlen =0;2442for(i =0; i < postimage->nr; i++) {2443if(!(postimage->line[i].flag & LINE_COMMON))2444 postlen += postimage->line[i].len;2445}24462447/*2448 * The preimage may extend beyond the end of the file,2449 * but in this loop we will only handle the part of the2450 * preimage that falls within the file.2451 */2452strbuf_init(&fixed, preimage->len +1);2453 orig = preimage->buf;2454 target = img->buf +try;2455for(i =0; i < preimage_limit; i++) {2456size_t oldlen = preimage->line[i].len;2457size_t tgtlen = img->line[try_lno + i].len;2458size_t fixstart = fixed.len;2459struct strbuf tgtfix;2460int match;24612462/* Try fixing the line in the preimage */2463ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24642465/* Try fixing the line in the target */2466strbuf_init(&tgtfix, tgtlen);2467ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);24682469/*2470 * If they match, either the preimage was based on2471 * a version before our tree fixed whitespace breakage,2472 * or we are lacking a whitespace-fix patch the tree2473 * the preimage was based on already had (i.e. target2474 * has whitespace breakage, the preimage doesn't).2475 * In either case, we are fixing the whitespace breakages2476 * so we might as well take the fix together with their2477 * real change.2478 */2479 match = (tgtfix.len == fixed.len - fixstart &&2480!memcmp(tgtfix.buf, fixed.buf + fixstart,2481 fixed.len - fixstart));24822483/* Add the length if this is common with the postimage */2484if(preimage->line[i].flag & LINE_COMMON)2485 postlen += tgtfix.len;24862487strbuf_release(&tgtfix);2488if(!match)2489goto unmatch_exit;24902491 orig += oldlen;2492 target += tgtlen;2493}249424952496/*2497 * Now handle the lines in the preimage that falls beyond the2498 * end of the file (if any). They will only match if they are2499 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2500 * false).2501 */2502for( ; i < preimage->nr; i++) {2503size_t fixstart = fixed.len;/* start of the fixed preimage */2504size_t oldlen = preimage->line[i].len;2505int j;25062507/* Try fixing the line in the preimage */2508ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25092510for(j = fixstart; j < fixed.len; j++)2511if(!isspace(fixed.buf[j]))2512goto unmatch_exit;25132514 orig += oldlen;2515}25162517/*2518 * Yes, the preimage is based on an older version that still2519 * has whitespace breakages unfixed, and fixing them makes the2520 * hunk match. Update the context lines in the postimage.2521 */2522 fixed_buf =strbuf_detach(&fixed, &fixed_len);2523if(postlen < postimage->len)2524 postlen =0;2525update_pre_post_images(preimage, postimage,2526 fixed_buf, fixed_len, postlen);2527return1;25282529 unmatch_exit:2530strbuf_release(&fixed);2531return0;2532}25332534static intfind_pos(struct image *img,2535struct image *preimage,2536struct image *postimage,2537int line,2538unsigned ws_rule,2539int match_beginning,int match_end)2540{2541int i;2542unsigned long backwards, forwards,try;2543int backwards_lno, forwards_lno, try_lno;25442545/*2546 * If match_beginning or match_end is specified, there is no2547 * point starting from a wrong line that will never match and2548 * wander around and wait for a match at the specified end.2549 */2550if(match_beginning)2551 line =0;2552else if(match_end)2553 line = img->nr - preimage->nr;25542555/*2556 * Because the comparison is unsigned, the following test2557 * will also take care of a negative line number that can2558 * result when match_end and preimage is larger than the target.2559 */2560if((size_t) line > img->nr)2561 line = img->nr;25622563try=0;2564for(i =0; i < line; i++)2565try+= img->line[i].len;25662567/*2568 * There's probably some smart way to do this, but I'll leave2569 * that to the smart and beautiful people. I'm simple and stupid.2570 */2571 backwards =try;2572 backwards_lno = line;2573 forwards =try;2574 forwards_lno = line;2575 try_lno = line;25762577for(i =0; ; i++) {2578if(match_fragment(img, preimage, postimage,2579try, try_lno, ws_rule,2580 match_beginning, match_end))2581return try_lno;25822583 again:2584if(backwards_lno ==0&& forwards_lno == img->nr)2585break;25862587if(i &1) {2588if(backwards_lno ==0) {2589 i++;2590goto again;2591}2592 backwards_lno--;2593 backwards -= img->line[backwards_lno].len;2594try= backwards;2595 try_lno = backwards_lno;2596}else{2597if(forwards_lno == img->nr) {2598 i++;2599goto again;2600}2601 forwards += img->line[forwards_lno].len;2602 forwards_lno++;2603try= forwards;2604 try_lno = forwards_lno;2605}26062607}2608return-1;2609}26102611static voidremove_first_line(struct image *img)2612{2613 img->buf += img->line[0].len;2614 img->len -= img->line[0].len;2615 img->line++;2616 img->nr--;2617}26182619static voidremove_last_line(struct image *img)2620{2621 img->len -= img->line[--img->nr].len;2622}26232624/*2625 * The change from "preimage" and "postimage" has been found to2626 * apply at applied_pos (counts in line numbers) in "img".2627 * Update "img" to remove "preimage" and replace it with "postimage".2628 */2629static voidupdate_image(struct apply_state *state,2630struct image *img,2631int applied_pos,2632struct image *preimage,2633struct image *postimage)2634{2635/*2636 * remove the copy of preimage at offset in img2637 * and replace it with postimage2638 */2639int i, nr;2640size_t remove_count, insert_count, applied_at =0;2641char*result;2642int preimage_limit;26432644/*2645 * If we are removing blank lines at the end of img,2646 * the preimage may extend beyond the end.2647 * If that is the case, we must be careful only to2648 * remove the part of the preimage that falls within2649 * the boundaries of img. Initialize preimage_limit2650 * to the number of lines in the preimage that falls2651 * within the boundaries.2652 */2653 preimage_limit = preimage->nr;2654if(preimage_limit > img->nr - applied_pos)2655 preimage_limit = img->nr - applied_pos;26562657for(i =0; i < applied_pos; i++)2658 applied_at += img->line[i].len;26592660 remove_count =0;2661for(i =0; i < preimage_limit; i++)2662 remove_count += img->line[applied_pos + i].len;2663 insert_count = postimage->len;26642665/* Adjust the contents */2666 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2667memcpy(result, img->buf, applied_at);2668memcpy(result + applied_at, postimage->buf, postimage->len);2669memcpy(result + applied_at + postimage->len,2670 img->buf + (applied_at + remove_count),2671 img->len - (applied_at + remove_count));2672free(img->buf);2673 img->buf = result;2674 img->len += insert_count - remove_count;2675 result[img->len] ='\0';26762677/* Adjust the line table */2678 nr = img->nr + postimage->nr - preimage_limit;2679if(preimage_limit < postimage->nr) {2680/*2681 * NOTE: this knows that we never call remove_first_line()2682 * on anything other than pre/post image.2683 */2684REALLOC_ARRAY(img->line, nr);2685 img->line_allocated = img->line;2686}2687if(preimage_limit != postimage->nr)2688memmove(img->line + applied_pos + postimage->nr,2689 img->line + applied_pos + preimage_limit,2690(img->nr - (applied_pos + preimage_limit)) *2691sizeof(*img->line));2692memcpy(img->line + applied_pos,2693 postimage->line,2694 postimage->nr *sizeof(*img->line));2695if(!state->allow_overlap)2696for(i =0; i < postimage->nr; i++)2697 img->line[applied_pos + i].flag |= LINE_PATCHED;2698 img->nr = nr;2699}27002701/*2702 * Use the patch-hunk text in "frag" to prepare two images (preimage and2703 * postimage) for the hunk. Find lines that match "preimage" in "img" and2704 * replace the part of "img" with "postimage" text.2705 */2706static intapply_one_fragment(struct apply_state *state,2707struct image *img,struct fragment *frag,2708int inaccurate_eof,unsigned ws_rule,2709int nth_fragment)2710{2711int match_beginning, match_end;2712const char*patch = frag->patch;2713int size = frag->size;2714char*old, *oldlines;2715struct strbuf newlines;2716int new_blank_lines_at_end =0;2717int found_new_blank_lines_at_end =0;2718int hunk_linenr = frag->linenr;2719unsigned long leading, trailing;2720int pos, applied_pos;2721struct image preimage;2722struct image postimage;27232724memset(&preimage,0,sizeof(preimage));2725memset(&postimage,0,sizeof(postimage));2726 oldlines =xmalloc(size);2727strbuf_init(&newlines, size);27282729 old = oldlines;2730while(size >0) {2731char first;2732int len =linelen(patch, size);2733int plen;2734int added_blank_line =0;2735int is_blank_context =0;2736size_t start;27372738if(!len)2739break;27402741/*2742 * "plen" is how much of the line we should use for2743 * the actual patch data. Normally we just remove the2744 * first character on the line, but if the line is2745 * followed by "\ No newline", then we also remove the2746 * last one (which is the newline, of course).2747 */2748 plen = len -1;2749if(len < size && patch[len] =='\\')2750 plen--;2751 first = *patch;2752if(state->apply_in_reverse) {2753if(first =='-')2754 first ='+';2755else if(first =='+')2756 first ='-';2757}27582759switch(first) {2760case'\n':2761/* Newer GNU diff, empty context line */2762if(plen <0)2763/* ... followed by '\No newline'; nothing */2764break;2765*old++ ='\n';2766strbuf_addch(&newlines,'\n');2767add_line_info(&preimage,"\n",1, LINE_COMMON);2768add_line_info(&postimage,"\n",1, LINE_COMMON);2769 is_blank_context =1;2770break;2771case' ':2772if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2773ws_blank_line(patch +1, plen, ws_rule))2774 is_blank_context =1;2775case'-':2776memcpy(old, patch +1, plen);2777add_line_info(&preimage, old, plen,2778(first ==' '? LINE_COMMON :0));2779 old += plen;2780if(first =='-')2781break;2782/* Fall-through for ' ' */2783case'+':2784/* --no-add does not add new lines */2785if(first =='+'&& no_add)2786break;27872788 start = newlines.len;2789if(first !='+'||2790!whitespace_error ||2791 ws_error_action != correct_ws_error) {2792strbuf_add(&newlines, patch +1, plen);2793}2794else{2795ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2796}2797add_line_info(&postimage, newlines.buf + start, newlines.len - start,2798(first =='+'?0: LINE_COMMON));2799if(first =='+'&&2800(ws_rule & WS_BLANK_AT_EOF) &&2801ws_blank_line(patch +1, plen, ws_rule))2802 added_blank_line =1;2803break;2804case'@':case'\\':2805/* Ignore it, we already handled it */2806break;2807default:2808if(state->apply_verbosely)2809error(_("invalid start of line: '%c'"), first);2810 applied_pos = -1;2811goto out;2812}2813if(added_blank_line) {2814if(!new_blank_lines_at_end)2815 found_new_blank_lines_at_end = hunk_linenr;2816 new_blank_lines_at_end++;2817}2818else if(is_blank_context)2819;2820else2821 new_blank_lines_at_end =0;2822 patch += len;2823 size -= len;2824 hunk_linenr++;2825}2826if(inaccurate_eof &&2827 old > oldlines && old[-1] =='\n'&&2828 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2829 old--;2830strbuf_setlen(&newlines, newlines.len -1);2831}28322833 leading = frag->leading;2834 trailing = frag->trailing;28352836/*2837 * A hunk to change lines at the beginning would begin with2838 * @@ -1,L +N,M @@2839 * but we need to be careful. -U0 that inserts before the second2840 * line also has this pattern.2841 *2842 * And a hunk to add to an empty file would begin with2843 * @@ -0,0 +N,M @@2844 *2845 * In other words, a hunk that is (frag->oldpos <= 1) with or2846 * without leading context must match at the beginning.2847 */2848 match_beginning = (!frag->oldpos ||2849(frag->oldpos ==1&& !state->unidiff_zero));28502851/*2852 * A hunk without trailing lines must match at the end.2853 * However, we simply cannot tell if a hunk must match end2854 * from the lack of trailing lines if the patch was generated2855 * with unidiff without any context.2856 */2857 match_end = !state->unidiff_zero && !trailing;28582859 pos = frag->newpos ? (frag->newpos -1) :0;2860 preimage.buf = oldlines;2861 preimage.len = old - oldlines;2862 postimage.buf = newlines.buf;2863 postimage.len = newlines.len;2864 preimage.line = preimage.line_allocated;2865 postimage.line = postimage.line_allocated;28662867for(;;) {28682869 applied_pos =find_pos(img, &preimage, &postimage, pos,2870 ws_rule, match_beginning, match_end);28712872if(applied_pos >=0)2873break;28742875/* Am I at my context limits? */2876if((leading <= p_context) && (trailing <= p_context))2877break;2878if(match_beginning || match_end) {2879 match_beginning = match_end =0;2880continue;2881}28822883/*2884 * Reduce the number of context lines; reduce both2885 * leading and trailing if they are equal otherwise2886 * just reduce the larger context.2887 */2888if(leading >= trailing) {2889remove_first_line(&preimage);2890remove_first_line(&postimage);2891 pos--;2892 leading--;2893}2894if(trailing > leading) {2895remove_last_line(&preimage);2896remove_last_line(&postimage);2897 trailing--;2898}2899}29002901if(applied_pos >=0) {2902if(new_blank_lines_at_end &&2903 preimage.nr + applied_pos >= img->nr &&2904(ws_rule & WS_BLANK_AT_EOF) &&2905 ws_error_action != nowarn_ws_error) {2906record_ws_error(WS_BLANK_AT_EOF,"+",1,2907 found_new_blank_lines_at_end);2908if(ws_error_action == correct_ws_error) {2909while(new_blank_lines_at_end--)2910remove_last_line(&postimage);2911}2912/*2913 * We would want to prevent write_out_results()2914 * from taking place in apply_patch() that follows2915 * the callchain led us here, which is:2916 * apply_patch->check_patch_list->check_patch->2917 * apply_data->apply_fragments->apply_one_fragment2918 */2919if(ws_error_action == die_on_ws_error)2920 apply =0;2921}29222923if(state->apply_verbosely && applied_pos != pos) {2924int offset = applied_pos - pos;2925if(state->apply_in_reverse)2926 offset =0- offset;2927fprintf_ln(stderr,2928Q_("Hunk #%dsucceeded at%d(offset%dline).",2929"Hunk #%dsucceeded at%d(offset%dlines).",2930 offset),2931 nth_fragment, applied_pos +1, offset);2932}29332934/*2935 * Warn if it was necessary to reduce the number2936 * of context lines.2937 */2938if((leading != frag->leading) ||2939(trailing != frag->trailing))2940fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2941" to apply fragment at%d"),2942 leading, trailing, applied_pos+1);2943update_image(state, img, applied_pos, &preimage, &postimage);2944}else{2945if(state->apply_verbosely)2946error(_("while searching for:\n%.*s"),2947(int)(old - oldlines), oldlines);2948}29492950out:2951free(oldlines);2952strbuf_release(&newlines);2953free(preimage.line_allocated);2954free(postimage.line_allocated);29552956return(applied_pos <0);2957}29582959static intapply_binary_fragment(struct apply_state *state,2960struct image *img,2961struct patch *patch)2962{2963struct fragment *fragment = patch->fragments;2964unsigned long len;2965void*dst;29662967if(!fragment)2968returnerror(_("missing binary patch data for '%s'"),2969 patch->new_name ?2970 patch->new_name :2971 patch->old_name);29722973/* Binary patch is irreversible without the optional second hunk */2974if(state->apply_in_reverse) {2975if(!fragment->next)2976returnerror("cannot reverse-apply a binary patch "2977"without the reverse hunk to '%s'",2978 patch->new_name2979? patch->new_name : patch->old_name);2980 fragment = fragment->next;2981}2982switch(fragment->binary_patch_method) {2983case BINARY_DELTA_DEFLATED:2984 dst =patch_delta(img->buf, img->len, fragment->patch,2985 fragment->size, &len);2986if(!dst)2987return-1;2988clear_image(img);2989 img->buf = dst;2990 img->len = len;2991return0;2992case BINARY_LITERAL_DEFLATED:2993clear_image(img);2994 img->len = fragment->size;2995 img->buf =xmemdupz(fragment->patch, img->len);2996return0;2997}2998return-1;2999}30003001/*3002 * Replace "img" with the result of applying the binary patch.3003 * The binary patch data itself in patch->fragment is still kept3004 * but the preimage prepared by the caller in "img" is freed here3005 * or in the helper function apply_binary_fragment() this calls.3006 */3007static intapply_binary(struct apply_state *state,3008struct image *img,3009struct patch *patch)3010{3011const char*name = patch->old_name ? patch->old_name : patch->new_name;3012unsigned char sha1[20];30133014/*3015 * For safety, we require patch index line to contain3016 * full 40-byte textual SHA1 for old and new, at least for now.3017 */3018if(strlen(patch->old_sha1_prefix) !=40||3019strlen(patch->new_sha1_prefix) !=40||3020get_sha1_hex(patch->old_sha1_prefix, sha1) ||3021get_sha1_hex(patch->new_sha1_prefix, sha1))3022returnerror("cannot apply binary patch to '%s' "3023"without full index line", name);30243025if(patch->old_name) {3026/*3027 * See if the old one matches what the patch3028 * applies to.3029 */3030hash_sha1_file(img->buf, img->len, blob_type, sha1);3031if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3032returnerror("the patch applies to '%s' (%s), "3033"which does not match the "3034"current contents.",3035 name,sha1_to_hex(sha1));3036}3037else{3038/* Otherwise, the old one must be empty. */3039if(img->len)3040returnerror("the patch applies to an empty "3041"'%s' but it is not empty", name);3042}30433044get_sha1_hex(patch->new_sha1_prefix, sha1);3045if(is_null_sha1(sha1)) {3046clear_image(img);3047return0;/* deletion patch */3048}30493050if(has_sha1_file(sha1)) {3051/* We already have the postimage */3052enum object_type type;3053unsigned long size;3054char*result;30553056 result =read_sha1_file(sha1, &type, &size);3057if(!result)3058returnerror("the necessary postimage%sfor "3059"'%s' cannot be read",3060 patch->new_sha1_prefix, name);3061clear_image(img);3062 img->buf = result;3063 img->len = size;3064}else{3065/*3066 * We have verified buf matches the preimage;3067 * apply the patch data to it, which is stored3068 * in the patch->fragments->{patch,size}.3069 */3070if(apply_binary_fragment(state, img, patch))3071returnerror(_("binary patch does not apply to '%s'"),3072 name);30733074/* verify that the result matches */3075hash_sha1_file(img->buf, img->len, blob_type, sha1);3076if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3077returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3078 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3079}30803081return0;3082}30833084static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3085{3086struct fragment *frag = patch->fragments;3087const char*name = patch->old_name ? patch->old_name : patch->new_name;3088unsigned ws_rule = patch->ws_rule;3089unsigned inaccurate_eof = patch->inaccurate_eof;3090int nth =0;30913092if(patch->is_binary)3093returnapply_binary(state, img, patch);30943095while(frag) {3096 nth++;3097if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3098error(_("patch failed:%s:%ld"), name, frag->oldpos);3099if(!state->apply_with_reject)3100return-1;3101 frag->rejected =1;3102}3103 frag = frag->next;3104}3105return0;3106}31073108static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3109{3110if(S_ISGITLINK(mode)) {3111strbuf_grow(buf,100);3112strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3113}else{3114enum object_type type;3115unsigned long sz;3116char*result;31173118 result =read_sha1_file(sha1, &type, &sz);3119if(!result)3120return-1;3121/* XXX read_sha1_file NUL-terminates */3122strbuf_attach(buf, result, sz, sz +1);3123}3124return0;3125}31263127static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3128{3129if(!ce)3130return0;3131returnread_blob_object(buf, ce->sha1, ce->ce_mode);3132}31333134static struct patch *in_fn_table(const char*name)3135{3136struct string_list_item *item;31373138if(name == NULL)3139return NULL;31403141 item =string_list_lookup(&fn_table, name);3142if(item != NULL)3143return(struct patch *)item->util;31443145return NULL;3146}31473148/*3149 * item->util in the filename table records the status of the path.3150 * Usually it points at a patch (whose result records the contents3151 * of it after applying it), but it could be PATH_WAS_DELETED for a3152 * path that a previously applied patch has already removed, or3153 * PATH_TO_BE_DELETED for a path that a later patch would remove.3154 *3155 * The latter is needed to deal with a case where two paths A and B3156 * are swapped by first renaming A to B and then renaming B to A;3157 * moving A to B should not be prevented due to presence of B as we3158 * will remove it in a later patch.3159 */3160#define PATH_TO_BE_DELETED ((struct patch *) -2)3161#define PATH_WAS_DELETED ((struct patch *) -1)31623163static intto_be_deleted(struct patch *patch)3164{3165return patch == PATH_TO_BE_DELETED;3166}31673168static intwas_deleted(struct patch *patch)3169{3170return patch == PATH_WAS_DELETED;3171}31723173static voidadd_to_fn_table(struct patch *patch)3174{3175struct string_list_item *item;31763177/*3178 * Always add new_name unless patch is a deletion3179 * This should cover the cases for normal diffs,3180 * file creations and copies3181 */3182if(patch->new_name != NULL) {3183 item =string_list_insert(&fn_table, patch->new_name);3184 item->util = patch;3185}31863187/*3188 * store a failure on rename/deletion cases because3189 * later chunks shouldn't patch old names3190 */3191if((patch->new_name == NULL) || (patch->is_rename)) {3192 item =string_list_insert(&fn_table, patch->old_name);3193 item->util = PATH_WAS_DELETED;3194}3195}31963197static voidprepare_fn_table(struct patch *patch)3198{3199/*3200 * store information about incoming file deletion3201 */3202while(patch) {3203if((patch->new_name == NULL) || (patch->is_rename)) {3204struct string_list_item *item;3205 item =string_list_insert(&fn_table, patch->old_name);3206 item->util = PATH_TO_BE_DELETED;3207}3208 patch = patch->next;3209}3210}32113212static intcheckout_target(struct index_state *istate,3213struct cache_entry *ce,struct stat *st)3214{3215struct checkout costate;32163217memset(&costate,0,sizeof(costate));3218 costate.base_dir ="";3219 costate.refresh_cache =1;3220 costate.istate = istate;3221if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3222returnerror(_("cannot checkout%s"), ce->name);3223return0;3224}32253226static struct patch *previous_patch(struct patch *patch,int*gone)3227{3228struct patch *previous;32293230*gone =0;3231if(patch->is_copy || patch->is_rename)3232return NULL;/* "git" patches do not depend on the order */32333234 previous =in_fn_table(patch->old_name);3235if(!previous)3236return NULL;32373238if(to_be_deleted(previous))3239return NULL;/* the deletion hasn't happened yet */32403241if(was_deleted(previous))3242*gone =1;32433244return previous;3245}32463247static intverify_index_match(const struct cache_entry *ce,struct stat *st)3248{3249if(S_ISGITLINK(ce->ce_mode)) {3250if(!S_ISDIR(st->st_mode))3251return-1;3252return0;3253}3254returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3255}32563257#define SUBMODULE_PATCH_WITHOUT_INDEX 132583259static intload_patch_target(struct apply_state *state,3260struct strbuf *buf,3261const struct cache_entry *ce,3262struct stat *st,3263const char*name,3264unsigned expected_mode)3265{3266if(state->cached || state->check_index) {3267if(read_file_or_gitlink(ce, buf))3268returnerror(_("read of%sfailed"), name);3269}else if(name) {3270if(S_ISGITLINK(expected_mode)) {3271if(ce)3272returnread_file_or_gitlink(ce, buf);3273else3274return SUBMODULE_PATCH_WITHOUT_INDEX;3275}else if(has_symlink_leading_path(name,strlen(name))) {3276returnerror(_("reading from '%s' beyond a symbolic link"), name);3277}else{3278if(read_old_data(st, name, buf))3279returnerror(_("read of%sfailed"), name);3280}3281}3282return0;3283}32843285/*3286 * We are about to apply "patch"; populate the "image" with the3287 * current version we have, from the working tree or from the index,3288 * depending on the situation e.g. --cached/--index. If we are3289 * applying a non-git patch that incrementally updates the tree,3290 * we read from the result of a previous diff.3291 */3292static intload_preimage(struct apply_state *state,3293struct image *image,3294struct patch *patch,struct stat *st,3295const struct cache_entry *ce)3296{3297struct strbuf buf = STRBUF_INIT;3298size_t len;3299char*img;3300struct patch *previous;3301int status;33023303 previous =previous_patch(patch, &status);3304if(status)3305returnerror(_("path%shas been renamed/deleted"),3306 patch->old_name);3307if(previous) {3308/* We have a patched copy in memory; use that. */3309strbuf_add(&buf, previous->result, previous->resultsize);3310}else{3311 status =load_patch_target(state, &buf, ce, st,3312 patch->old_name, patch->old_mode);3313if(status <0)3314return status;3315else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3316/*3317 * There is no way to apply subproject3318 * patch without looking at the index.3319 * NEEDSWORK: shouldn't this be flagged3320 * as an error???3321 */3322free_fragment_list(patch->fragments);3323 patch->fragments = NULL;3324}else if(status) {3325returnerror(_("read of%sfailed"), patch->old_name);3326}3327}33283329 img =strbuf_detach(&buf, &len);3330prepare_image(image, img, len, !patch->is_binary);3331return0;3332}33333334static intthree_way_merge(struct image *image,3335char*path,3336const unsigned char*base,3337const unsigned char*ours,3338const unsigned char*theirs)3339{3340 mmfile_t base_file, our_file, their_file;3341 mmbuffer_t result = { NULL };3342int status;33433344read_mmblob(&base_file, base);3345read_mmblob(&our_file, ours);3346read_mmblob(&their_file, theirs);3347 status =ll_merge(&result, path,3348&base_file,"base",3349&our_file,"ours",3350&their_file,"theirs", NULL);3351free(base_file.ptr);3352free(our_file.ptr);3353free(their_file.ptr);3354if(status <0|| !result.ptr) {3355free(result.ptr);3356return-1;3357}3358clear_image(image);3359 image->buf = result.ptr;3360 image->len = result.size;33613362return status;3363}33643365/*3366 * When directly falling back to add/add three-way merge, we read from3367 * the current contents of the new_name. In no cases other than that3368 * this function will be called.3369 */3370static intload_current(struct apply_state *state,3371struct image *image,3372struct patch *patch)3373{3374struct strbuf buf = STRBUF_INIT;3375int status, pos;3376size_t len;3377char*img;3378struct stat st;3379struct cache_entry *ce;3380char*name = patch->new_name;3381unsigned mode = patch->new_mode;33823383if(!patch->is_new)3384die("BUG: patch to%sis not a creation", patch->old_name);33853386 pos =cache_name_pos(name,strlen(name));3387if(pos <0)3388returnerror(_("%s: does not exist in index"), name);3389 ce = active_cache[pos];3390if(lstat(name, &st)) {3391if(errno != ENOENT)3392returnerror(_("%s:%s"), name,strerror(errno));3393if(checkout_target(&the_index, ce, &st))3394return-1;3395}3396if(verify_index_match(ce, &st))3397returnerror(_("%s: does not match index"), name);33983399 status =load_patch_target(state, &buf, ce, &st, name, mode);3400if(status <0)3401return status;3402else if(status)3403return-1;3404 img =strbuf_detach(&buf, &len);3405prepare_image(image, img, len, !patch->is_binary);3406return0;3407}34083409static inttry_threeway(struct apply_state *state,3410struct image *image,3411struct patch *patch,3412struct stat *st,3413const struct cache_entry *ce)3414{3415unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3416struct strbuf buf = STRBUF_INIT;3417size_t len;3418int status;3419char*img;3420struct image tmp_image;34213422/* No point falling back to 3-way merge in these cases */3423if(patch->is_delete ||3424S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3425return-1;34263427/* Preimage the patch was prepared for */3428if(patch->is_new)3429write_sha1_file("",0, blob_type, pre_sha1);3430else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3431read_blob_object(&buf, pre_sha1, patch->old_mode))3432returnerror("repository lacks the necessary blob to fall back on 3-way merge.");34333434fprintf(stderr,"Falling back to three-way merge...\n");34353436 img =strbuf_detach(&buf, &len);3437prepare_image(&tmp_image, img, len,1);3438/* Apply the patch to get the post image */3439if(apply_fragments(state, &tmp_image, patch) <0) {3440clear_image(&tmp_image);3441return-1;3442}3443/* post_sha1[] is theirs */3444write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3445clear_image(&tmp_image);34463447/* our_sha1[] is ours */3448if(patch->is_new) {3449if(load_current(state, &tmp_image, patch))3450returnerror("cannot read the current contents of '%s'",3451 patch->new_name);3452}else{3453if(load_preimage(state, &tmp_image, patch, st, ce))3454returnerror("cannot read the current contents of '%s'",3455 patch->old_name);3456}3457write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3458clear_image(&tmp_image);34593460/* in-core three-way merge between post and our using pre as base */3461 status =three_way_merge(image, patch->new_name,3462 pre_sha1, our_sha1, post_sha1);3463if(status <0) {3464fprintf(stderr,"Failed to fall back on three-way merge...\n");3465return status;3466}34673468if(status) {3469 patch->conflicted_threeway =1;3470if(patch->is_new)3471oidclr(&patch->threeway_stage[0]);3472else3473hashcpy(patch->threeway_stage[0].hash, pre_sha1);3474hashcpy(patch->threeway_stage[1].hash, our_sha1);3475hashcpy(patch->threeway_stage[2].hash, post_sha1);3476fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3477}else{3478fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3479}3480return0;3481}34823483static intapply_data(struct apply_state *state,struct patch *patch,3484struct stat *st,const struct cache_entry *ce)3485{3486struct image image;34873488if(load_preimage(state, &image, patch, st, ce) <0)3489return-1;34903491if(patch->direct_to_threeway ||3492apply_fragments(state, &image, patch) <0) {3493/* Note: with --reject, apply_fragments() returns 0 */3494if(!threeway ||try_threeway(state, &image, patch, st, ce) <0)3495return-1;3496}3497 patch->result = image.buf;3498 patch->resultsize = image.len;3499add_to_fn_table(patch);3500free(image.line_allocated);35013502if(0< patch->is_delete && patch->resultsize)3503returnerror(_("removal patch leaves file contents"));35043505return0;3506}35073508/*3509 * If "patch" that we are looking at modifies or deletes what we have,3510 * we would want it not to lose any local modification we have, either3511 * in the working tree or in the index.3512 *3513 * This also decides if a non-git patch is a creation patch or a3514 * modification to an existing empty file. We do not check the state3515 * of the current tree for a creation patch in this function; the caller3516 * check_patch() separately makes sure (and errors out otherwise) that3517 * the path the patch creates does not exist in the current tree.3518 */3519static intcheck_preimage(struct apply_state *state,3520struct patch *patch,3521struct cache_entry **ce,3522struct stat *st)3523{3524const char*old_name = patch->old_name;3525struct patch *previous = NULL;3526int stat_ret =0, status;3527unsigned st_mode =0;35283529if(!old_name)3530return0;35313532assert(patch->is_new <=0);3533 previous =previous_patch(patch, &status);35343535if(status)3536returnerror(_("path%shas been renamed/deleted"), old_name);3537if(previous) {3538 st_mode = previous->new_mode;3539}else if(!state->cached) {3540 stat_ret =lstat(old_name, st);3541if(stat_ret && errno != ENOENT)3542returnerror(_("%s:%s"), old_name,strerror(errno));3543}35443545if(state->check_index && !previous) {3546int pos =cache_name_pos(old_name,strlen(old_name));3547if(pos <0) {3548if(patch->is_new <0)3549goto is_new;3550returnerror(_("%s: does not exist in index"), old_name);3551}3552*ce = active_cache[pos];3553if(stat_ret <0) {3554if(checkout_target(&the_index, *ce, st))3555return-1;3556}3557if(!state->cached &&verify_index_match(*ce, st))3558returnerror(_("%s: does not match index"), old_name);3559if(state->cached)3560 st_mode = (*ce)->ce_mode;3561}else if(stat_ret <0) {3562if(patch->is_new <0)3563goto is_new;3564returnerror(_("%s:%s"), old_name,strerror(errno));3565}35663567if(!state->cached && !previous)3568 st_mode =ce_mode_from_stat(*ce, st->st_mode);35693570if(patch->is_new <0)3571 patch->is_new =0;3572if(!patch->old_mode)3573 patch->old_mode = st_mode;3574if((st_mode ^ patch->old_mode) & S_IFMT)3575returnerror(_("%s: wrong type"), old_name);3576if(st_mode != patch->old_mode)3577warning(_("%shas type%o, expected%o"),3578 old_name, st_mode, patch->old_mode);3579if(!patch->new_mode && !patch->is_delete)3580 patch->new_mode = st_mode;3581return0;35823583 is_new:3584 patch->is_new =1;3585 patch->is_delete =0;3586free(patch->old_name);3587 patch->old_name = NULL;3588return0;3589}359035913592#define EXISTS_IN_INDEX 13593#define EXISTS_IN_WORKTREE 235943595static intcheck_to_create(struct apply_state *state,3596const char*new_name,3597int ok_if_exists)3598{3599struct stat nst;36003601if(state->check_index &&3602cache_name_pos(new_name,strlen(new_name)) >=0&&3603!ok_if_exists)3604return EXISTS_IN_INDEX;3605if(state->cached)3606return0;36073608if(!lstat(new_name, &nst)) {3609if(S_ISDIR(nst.st_mode) || ok_if_exists)3610return0;3611/*3612 * A leading component of new_name might be a symlink3613 * that is going to be removed with this patch, but3614 * still pointing at somewhere that has the path.3615 * In such a case, path "new_name" does not exist as3616 * far as git is concerned.3617 */3618if(has_symlink_leading_path(new_name,strlen(new_name)))3619return0;36203621return EXISTS_IN_WORKTREE;3622}else if((errno != ENOENT) && (errno != ENOTDIR)) {3623returnerror("%s:%s", new_name,strerror(errno));3624}3625return0;3626}36273628/*3629 * We need to keep track of how symlinks in the preimage are3630 * manipulated by the patches. A patch to add a/b/c where a/b3631 * is a symlink should not be allowed to affect the directory3632 * the symlink points at, but if the same patch removes a/b,3633 * it is perfectly fine, as the patch removes a/b to make room3634 * to create a directory a/b so that a/b/c can be created.3635 */3636static struct string_list symlink_changes;3637#define SYMLINK_GOES_AWAY 013638#define SYMLINK_IN_RESULT 0236393640static uintptr_tregister_symlink_changes(const char*path,uintptr_t what)3641{3642struct string_list_item *ent;36433644 ent =string_list_lookup(&symlink_changes, path);3645if(!ent) {3646 ent =string_list_insert(&symlink_changes, path);3647 ent->util = (void*)0;3648}3649 ent->util = (void*)(what | ((uintptr_t)ent->util));3650return(uintptr_t)ent->util;3651}36523653static uintptr_tcheck_symlink_changes(const char*path)3654{3655struct string_list_item *ent;36563657 ent =string_list_lookup(&symlink_changes, path);3658if(!ent)3659return0;3660return(uintptr_t)ent->util;3661}36623663static voidprepare_symlink_changes(struct patch *patch)3664{3665for( ; patch; patch = patch->next) {3666if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3667(patch->is_rename || patch->is_delete))3668/* the symlink at patch->old_name is removed */3669register_symlink_changes(patch->old_name, SYMLINK_GOES_AWAY);36703671if(patch->new_name &&S_ISLNK(patch->new_mode))3672/* the symlink at patch->new_name is created or remains */3673register_symlink_changes(patch->new_name, SYMLINK_IN_RESULT);3674}3675}36763677static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3678{3679do{3680unsigned int change;36813682while(--name->len && name->buf[name->len] !='/')3683;/* scan backwards */3684if(!name->len)3685break;3686 name->buf[name->len] ='\0';3687 change =check_symlink_changes(name->buf);3688if(change & SYMLINK_IN_RESULT)3689return1;3690if(change & SYMLINK_GOES_AWAY)3691/*3692 * This cannot be "return 0", because we may3693 * see a new one created at a higher level.3694 */3695continue;36963697/* otherwise, check the preimage */3698if(state->check_index) {3699struct cache_entry *ce;37003701 ce =cache_file_exists(name->buf, name->len, ignore_case);3702if(ce &&S_ISLNK(ce->ce_mode))3703return1;3704}else{3705struct stat st;3706if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3707return1;3708}3709}while(1);3710return0;3711}37123713static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3714{3715int ret;3716struct strbuf name = STRBUF_INIT;37173718assert(*name_ !='\0');3719strbuf_addstr(&name, name_);3720 ret =path_is_beyond_symlink_1(state, &name);3721strbuf_release(&name);37223723return ret;3724}37253726static voiddie_on_unsafe_path(struct patch *patch)3727{3728const char*old_name = NULL;3729const char*new_name = NULL;3730if(patch->is_delete)3731 old_name = patch->old_name;3732else if(!patch->is_new && !patch->is_copy)3733 old_name = patch->old_name;3734if(!patch->is_delete)3735 new_name = patch->new_name;37363737if(old_name && !verify_path(old_name))3738die(_("invalid path '%s'"), old_name);3739if(new_name && !verify_path(new_name))3740die(_("invalid path '%s'"), new_name);3741}37423743/*3744 * Check and apply the patch in-core; leave the result in patch->result3745 * for the caller to write it out to the final destination.3746 */3747static intcheck_patch(struct apply_state *state,struct patch *patch)3748{3749struct stat st;3750const char*old_name = patch->old_name;3751const char*new_name = patch->new_name;3752const char*name = old_name ? old_name : new_name;3753struct cache_entry *ce = NULL;3754struct patch *tpatch;3755int ok_if_exists;3756int status;37573758 patch->rejected =1;/* we will drop this after we succeed */37593760 status =check_preimage(state, patch, &ce, &st);3761if(status)3762return status;3763 old_name = patch->old_name;37643765/*3766 * A type-change diff is always split into a patch to delete3767 * old, immediately followed by a patch to create new (see3768 * diff.c::run_diff()); in such a case it is Ok that the entry3769 * to be deleted by the previous patch is still in the working3770 * tree and in the index.3771 *3772 * A patch to swap-rename between A and B would first rename A3773 * to B and then rename B to A. While applying the first one,3774 * the presence of B should not stop A from getting renamed to3775 * B; ask to_be_deleted() about the later rename. Removal of3776 * B and rename from A to B is handled the same way by asking3777 * was_deleted().3778 */3779if((tpatch =in_fn_table(new_name)) &&3780(was_deleted(tpatch) ||to_be_deleted(tpatch)))3781 ok_if_exists =1;3782else3783 ok_if_exists =0;37843785if(new_name &&3786((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3787int err =check_to_create(state, new_name, ok_if_exists);37883789if(err && threeway) {3790 patch->direct_to_threeway =1;3791}else switch(err) {3792case0:3793break;/* happy */3794case EXISTS_IN_INDEX:3795returnerror(_("%s: already exists in index"), new_name);3796break;3797case EXISTS_IN_WORKTREE:3798returnerror(_("%s: already exists in working directory"),3799 new_name);3800default:3801return err;3802}38033804if(!patch->new_mode) {3805if(0< patch->is_new)3806 patch->new_mode = S_IFREG |0644;3807else3808 patch->new_mode = patch->old_mode;3809}3810}38113812if(new_name && old_name) {3813int same = !strcmp(old_name, new_name);3814if(!patch->new_mode)3815 patch->new_mode = patch->old_mode;3816if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3817if(same)3818returnerror(_("new mode (%o) of%sdoes not "3819"match old mode (%o)"),3820 patch->new_mode, new_name,3821 patch->old_mode);3822else3823returnerror(_("new mode (%o) of%sdoes not "3824"match old mode (%o) of%s"),3825 patch->new_mode, new_name,3826 patch->old_mode, old_name);3827}3828}38293830if(!unsafe_paths)3831die_on_unsafe_path(patch);38323833/*3834 * An attempt to read from or delete a path that is beyond a3835 * symbolic link will be prevented by load_patch_target() that3836 * is called at the beginning of apply_data() so we do not3837 * have to worry about a patch marked with "is_delete" bit3838 * here. We however need to make sure that the patch result3839 * is not deposited to a path that is beyond a symbolic link3840 * here.3841 */3842if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3843returnerror(_("affected file '%s' is beyond a symbolic link"),3844 patch->new_name);38453846if(apply_data(state, patch, &st, ce) <0)3847returnerror(_("%s: patch does not apply"), name);3848 patch->rejected =0;3849return0;3850}38513852static intcheck_patch_list(struct apply_state *state,struct patch *patch)3853{3854int err =0;38553856prepare_symlink_changes(patch);3857prepare_fn_table(patch);3858while(patch) {3859if(state->apply_verbosely)3860say_patch_name(stderr,3861_("Checking patch%s..."), patch);3862 err |=check_patch(state, patch);3863 patch = patch->next;3864}3865return err;3866}38673868/* This function tries to read the sha1 from the current index */3869static intget_current_sha1(const char*path,unsigned char*sha1)3870{3871int pos;38723873if(read_cache() <0)3874return-1;3875 pos =cache_name_pos(path,strlen(path));3876if(pos <0)3877return-1;3878hashcpy(sha1, active_cache[pos]->sha1);3879return0;3880}38813882static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3883{3884/*3885 * A usable gitlink patch has only one fragment (hunk) that looks like:3886 * @@ -1 +1 @@3887 * -Subproject commit <old sha1>3888 * +Subproject commit <new sha1>3889 * or3890 * @@ -1 +0,0 @@3891 * -Subproject commit <old sha1>3892 * for a removal patch.3893 */3894struct fragment *hunk = p->fragments;3895static const char heading[] ="-Subproject commit ";3896char*preimage;38973898if(/* does the patch have only one hunk? */3899 hunk && !hunk->next &&3900/* is its preimage one line? */3901 hunk->oldpos ==1&& hunk->oldlines ==1&&3902/* does preimage begin with the heading? */3903(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3904starts_with(++preimage, heading) &&3905/* does it record full SHA-1? */3906!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3907 preimage[sizeof(heading) +40-1] =='\n'&&3908/* does the abbreviated name on the index line agree with it? */3909starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3910return0;/* it all looks fine */39113912/* we may have full object name on the index line */3913returnget_sha1_hex(p->old_sha1_prefix, sha1);3914}39153916/* Build an index that contains the just the files needed for a 3way merge */3917static voidbuild_fake_ancestor(struct patch *list,const char*filename)3918{3919struct patch *patch;3920struct index_state result = { NULL };3921static struct lock_file lock;39223923/* Once we start supporting the reverse patch, it may be3924 * worth showing the new sha1 prefix, but until then...3925 */3926for(patch = list; patch; patch = patch->next) {3927unsigned char sha1[20];3928struct cache_entry *ce;3929const char*name;39303931 name = patch->old_name ? patch->old_name : patch->new_name;3932if(0< patch->is_new)3933continue;39343935if(S_ISGITLINK(patch->old_mode)) {3936if(!preimage_sha1_in_gitlink_patch(patch, sha1))3937;/* ok, the textual part looks sane */3938else3939die("sha1 information is lacking or useless for submodule%s",3940 name);3941}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {3942;/* ok */3943}else if(!patch->lines_added && !patch->lines_deleted) {3944/* mode-only change: update the current */3945if(get_current_sha1(patch->old_name, sha1))3946die("mode change for%s, which is not "3947"in current HEAD", name);3948}else3949die("sha1 information is lacking or useless "3950"(%s).", name);39513952 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);3953if(!ce)3954die(_("make_cache_entry failed for path '%s'"), name);3955if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3956die("Could not add%sto temporary index", name);3957}39583959hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);3960if(write_locked_index(&result, &lock, COMMIT_LOCK))3961die("Could not write temporary index to%s", filename);39623963discard_index(&result);3964}39653966static voidstat_patch_list(struct patch *patch)3967{3968int files, adds, dels;39693970for(files = adds = dels =0; patch ; patch = patch->next) {3971 files++;3972 adds += patch->lines_added;3973 dels += patch->lines_deleted;3974show_stats(patch);3975}39763977print_stat_summary(stdout, files, adds, dels);3978}39793980static voidnumstat_patch_list(struct patch *patch)3981{3982for( ; patch; patch = patch->next) {3983const char*name;3984 name = patch->new_name ? patch->new_name : patch->old_name;3985if(patch->is_binary)3986printf("-\t-\t");3987else3988printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3989write_name_quoted(name, stdout, line_termination);3990}3991}39923993static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3994{3995if(mode)3996printf("%smode%06o%s\n", newdelete, mode, name);3997else3998printf("%s %s\n", newdelete, name);3999}40004001static voidshow_mode_change(struct patch *p,int show_name)4002{4003if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4004if(show_name)4005printf(" mode change%06o =>%06o%s\n",4006 p->old_mode, p->new_mode, p->new_name);4007else4008printf(" mode change%06o =>%06o\n",4009 p->old_mode, p->new_mode);4010}4011}40124013static voidshow_rename_copy(struct patch *p)4014{4015const char*renamecopy = p->is_rename ?"rename":"copy";4016const char*old, *new;40174018/* Find common prefix */4019 old = p->old_name;4020new= p->new_name;4021while(1) {4022const char*slash_old, *slash_new;4023 slash_old =strchr(old,'/');4024 slash_new =strchr(new,'/');4025if(!slash_old ||4026!slash_new ||4027 slash_old - old != slash_new -new||4028memcmp(old,new, slash_new -new))4029break;4030 old = slash_old +1;4031new= slash_new +1;4032}4033/* p->old_name thru old is the common prefix, and old and new4034 * through the end of names are renames4035 */4036if(old != p->old_name)4037printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4038(int)(old - p->old_name), p->old_name,4039 old,new, p->score);4040else4041printf("%s %s=>%s(%d%%)\n", renamecopy,4042 p->old_name, p->new_name, p->score);4043show_mode_change(p,0);4044}40454046static voidsummary_patch_list(struct patch *patch)4047{4048struct patch *p;40494050for(p = patch; p; p = p->next) {4051if(p->is_new)4052show_file_mode_name("create", p->new_mode, p->new_name);4053else if(p->is_delete)4054show_file_mode_name("delete", p->old_mode, p->old_name);4055else{4056if(p->is_rename || p->is_copy)4057show_rename_copy(p);4058else{4059if(p->score) {4060printf(" rewrite%s(%d%%)\n",4061 p->new_name, p->score);4062show_mode_change(p,0);4063}4064else4065show_mode_change(p,1);4066}4067}4068}4069}40704071static voidpatch_stats(struct patch *patch)4072{4073int lines = patch->lines_added + patch->lines_deleted;40744075if(lines > max_change)4076 max_change = lines;4077if(patch->old_name) {4078int len =quote_c_style(patch->old_name, NULL, NULL,0);4079if(!len)4080 len =strlen(patch->old_name);4081if(len > max_len)4082 max_len = len;4083}4084if(patch->new_name) {4085int len =quote_c_style(patch->new_name, NULL, NULL,0);4086if(!len)4087 len =strlen(patch->new_name);4088if(len > max_len)4089 max_len = len;4090}4091}40924093static voidremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4094{4095if(state->update_index) {4096if(remove_file_from_cache(patch->old_name) <0)4097die(_("unable to remove%sfrom index"), patch->old_name);4098}4099if(!state->cached) {4100if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4101remove_path(patch->old_name);4102}4103}4104}41054106static voidadd_index_file(struct apply_state *state,4107const char*path,4108unsigned mode,4109void*buf,4110unsigned long size)4111{4112struct stat st;4113struct cache_entry *ce;4114int namelen =strlen(path);4115unsigned ce_size =cache_entry_size(namelen);41164117if(!state->update_index)4118return;41194120 ce =xcalloc(1, ce_size);4121memcpy(ce->name, path, namelen);4122 ce->ce_mode =create_ce_mode(mode);4123 ce->ce_flags =create_ce_flags(0);4124 ce->ce_namelen = namelen;4125if(S_ISGITLINK(mode)) {4126const char*s;41274128if(!skip_prefix(buf,"Subproject commit ", &s) ||4129get_sha1_hex(s, ce->sha1))4130die(_("corrupt patch for submodule%s"), path);4131}else{4132if(!state->cached) {4133if(lstat(path, &st) <0)4134die_errno(_("unable to stat newly created file '%s'"),4135 path);4136fill_stat_cache_info(ce, &st);4137}4138if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4139die(_("unable to create backing store for newly created file%s"), path);4140}4141if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4142die(_("unable to add cache entry for%s"), path);4143}41444145static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4146{4147int fd;4148struct strbuf nbuf = STRBUF_INIT;41494150if(S_ISGITLINK(mode)) {4151struct stat st;4152if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4153return0;4154returnmkdir(path,0777);4155}41564157if(has_symlinks &&S_ISLNK(mode))4158/* Although buf:size is counted string, it also is NUL4159 * terminated.4160 */4161returnsymlink(buf, path);41624163 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4164if(fd <0)4165return-1;41664167if(convert_to_working_tree(path, buf, size, &nbuf)) {4168 size = nbuf.len;4169 buf = nbuf.buf;4170}4171write_or_die(fd, buf, size);4172strbuf_release(&nbuf);41734174if(close(fd) <0)4175die_errno(_("closing file '%s'"), path);4176return0;4177}41784179/*4180 * We optimistically assume that the directories exist,4181 * which is true 99% of the time anyway. If they don't,4182 * we create them and try again.4183 */4184static voidcreate_one_file(struct apply_state *state,4185char*path,4186unsigned mode,4187const char*buf,4188unsigned long size)4189{4190if(state->cached)4191return;4192if(!try_create_file(path, mode, buf, size))4193return;41944195if(errno == ENOENT) {4196if(safe_create_leading_directories(path))4197return;4198if(!try_create_file(path, mode, buf, size))4199return;4200}42014202if(errno == EEXIST || errno == EACCES) {4203/* We may be trying to create a file where a directory4204 * used to be.4205 */4206struct stat st;4207if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4208 errno = EEXIST;4209}42104211if(errno == EEXIST) {4212unsigned int nr =getpid();42134214for(;;) {4215char newpath[PATH_MAX];4216mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4217if(!try_create_file(newpath, mode, buf, size)) {4218if(!rename(newpath, path))4219return;4220unlink_or_warn(newpath);4221break;4222}4223if(errno != EEXIST)4224break;4225++nr;4226}4227}4228die_errno(_("unable to write file '%s' mode%o"), path, mode);4229}42304231static voidadd_conflicted_stages_file(struct apply_state *state,4232struct patch *patch)4233{4234int stage, namelen;4235unsigned ce_size, mode;4236struct cache_entry *ce;42374238if(!state->update_index)4239return;4240 namelen =strlen(patch->new_name);4241 ce_size =cache_entry_size(namelen);4242 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);42434244remove_file_from_cache(patch->new_name);4245for(stage =1; stage <4; stage++) {4246if(is_null_oid(&patch->threeway_stage[stage -1]))4247continue;4248 ce =xcalloc(1, ce_size);4249memcpy(ce->name, patch->new_name, namelen);4250 ce->ce_mode =create_ce_mode(mode);4251 ce->ce_flags =create_ce_flags(stage);4252 ce->ce_namelen = namelen;4253hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4254if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4255die(_("unable to add cache entry for%s"), patch->new_name);4256}4257}42584259static voidcreate_file(struct apply_state *state,struct patch *patch)4260{4261char*path = patch->new_name;4262unsigned mode = patch->new_mode;4263unsigned long size = patch->resultsize;4264char*buf = patch->result;42654266if(!mode)4267 mode = S_IFREG |0644;4268create_one_file(state, path, mode, buf, size);42694270if(patch->conflicted_threeway)4271add_conflicted_stages_file(state, patch);4272else4273add_index_file(state, path, mode, buf, size);4274}42754276/* phase zero is to remove, phase one is to create */4277static voidwrite_out_one_result(struct apply_state *state,4278struct patch *patch,4279int phase)4280{4281if(patch->is_delete >0) {4282if(phase ==0)4283remove_file(state, patch,1);4284return;4285}4286if(patch->is_new >0|| patch->is_copy) {4287if(phase ==1)4288create_file(state, patch);4289return;4290}4291/*4292 * Rename or modification boils down to the same4293 * thing: remove the old, write the new4294 */4295if(phase ==0)4296remove_file(state, patch, patch->is_rename);4297if(phase ==1)4298create_file(state, patch);4299}43004301static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4302{4303FILE*rej;4304char namebuf[PATH_MAX];4305struct fragment *frag;4306int cnt =0;4307struct strbuf sb = STRBUF_INIT;43084309for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4310if(!frag->rejected)4311continue;4312 cnt++;4313}43144315if(!cnt) {4316if(state->apply_verbosely)4317say_patch_name(stderr,4318_("Applied patch%scleanly."), patch);4319return0;4320}43214322/* This should not happen, because a removal patch that leaves4323 * contents are marked "rejected" at the patch level.4324 */4325if(!patch->new_name)4326die(_("internal error"));43274328/* Say this even without --verbose */4329strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4330"Applying patch %%swith%drejects...",4331 cnt),4332 cnt);4333say_patch_name(stderr, sb.buf, patch);4334strbuf_release(&sb);43354336 cnt =strlen(patch->new_name);4337if(ARRAY_SIZE(namebuf) <= cnt +5) {4338 cnt =ARRAY_SIZE(namebuf) -5;4339warning(_("truncating .rej filename to %.*s.rej"),4340 cnt -1, patch->new_name);4341}4342memcpy(namebuf, patch->new_name, cnt);4343memcpy(namebuf + cnt,".rej",5);43444345 rej =fopen(namebuf,"w");4346if(!rej)4347returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));43484349/* Normal git tools never deal with .rej, so do not pretend4350 * this is a git patch by saying --git or giving extended4351 * headers. While at it, maybe please "kompare" that wants4352 * the trailing TAB and some garbage at the end of line ;-).4353 */4354fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4355 patch->new_name, patch->new_name);4356for(cnt =1, frag = patch->fragments;4357 frag;4358 cnt++, frag = frag->next) {4359if(!frag->rejected) {4360fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4361continue;4362}4363fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4364fprintf(rej,"%.*s", frag->size, frag->patch);4365if(frag->patch[frag->size-1] !='\n')4366fputc('\n', rej);4367}4368fclose(rej);4369return-1;4370}43714372static intwrite_out_results(struct apply_state *state,struct patch *list)4373{4374int phase;4375int errs =0;4376struct patch *l;4377struct string_list cpath = STRING_LIST_INIT_DUP;43784379for(phase =0; phase <2; phase++) {4380 l = list;4381while(l) {4382if(l->rejected)4383 errs =1;4384else{4385write_out_one_result(state, l, phase);4386if(phase ==1) {4387if(write_out_one_reject(state, l))4388 errs =1;4389if(l->conflicted_threeway) {4390string_list_append(&cpath, l->new_name);4391 errs =1;4392}4393}4394}4395 l = l->next;4396}4397}43984399if(cpath.nr) {4400struct string_list_item *item;44014402string_list_sort(&cpath);4403for_each_string_list_item(item, &cpath)4404fprintf(stderr,"U%s\n", item->string);4405string_list_clear(&cpath,0);44064407rerere(0);4408}44094410return errs;4411}44124413static struct lock_file lock_file;44144415#define INACCURATE_EOF (1<<0)4416#define RECOUNT (1<<1)44174418static intapply_patch(struct apply_state *state,4419int fd,4420const char*filename,4421int options)4422{4423size_t offset;4424struct strbuf buf = STRBUF_INIT;/* owns the patch text */4425struct patch *list = NULL, **listp = &list;4426int skipped_patch =0;44274428 patch_input_file = filename;4429read_patch_file(&buf, fd);4430 offset =0;4431while(offset < buf.len) {4432struct patch *patch;4433int nr;44344435 patch =xcalloc(1,sizeof(*patch));4436 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4437 patch->recount = !!(options & RECOUNT);4438 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4439if(nr <0) {4440free_patch(patch);4441break;4442}4443if(state->apply_in_reverse)4444reverse_patches(patch);4445if(use_patch(state, patch)) {4446patch_stats(patch);4447*listp = patch;4448 listp = &patch->next;4449}4450else{4451if(state->apply_verbosely)4452say_patch_name(stderr,_("Skipped patch '%s'."), patch);4453free_patch(patch);4454 skipped_patch++;4455}4456 offset += nr;4457}44584459if(!list && !skipped_patch)4460die(_("unrecognized input"));44614462if(whitespace_error && (ws_error_action == die_on_ws_error))4463 apply =0;44644465 state->update_index = state->check_index && apply;4466if(state->update_index && newfd <0)4467 newfd =hold_locked_index(&lock_file,1);44684469if(state->check_index) {4470if(read_cache() <0)4471die(_("unable to read index file"));4472}44734474if((state->check || apply) &&4475check_patch_list(state, list) <0&&4476!state->apply_with_reject)4477exit(1);44784479if(apply &&write_out_results(state, list)) {4480if(state->apply_with_reject)4481exit(1);4482/* with --3way, we still need to write the index out */4483return1;4484}44854486if(fake_ancestor)4487build_fake_ancestor(list, fake_ancestor);44884489if(diffstat)4490stat_patch_list(list);44914492if(numstat)4493numstat_patch_list(list);44944495if(summary)4496summary_patch_list(list);44974498free_patch_list(list);4499strbuf_release(&buf);4500string_list_clear(&fn_table,0);4501return0;4502}45034504static voidgit_apply_config(void)4505{4506git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4507git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4508git_config(git_default_config, NULL);4509}45104511static intoption_parse_exclude(const struct option *opt,4512const char*arg,int unset)4513{4514add_name_limit(arg,1);4515return0;4516}45174518static intoption_parse_include(const struct option *opt,4519const char*arg,int unset)4520{4521add_name_limit(arg,0);4522 has_include =1;4523return0;4524}45254526static intoption_parse_p(const struct option *opt,4527const char*arg,int unset)4528{4529 state_p_value =atoi(arg);4530 p_value_known =1;4531return0;4532}45334534static intoption_parse_space_change(const struct option *opt,4535const char*arg,int unset)4536{4537if(unset)4538 ws_ignore_action = ignore_ws_none;4539else4540 ws_ignore_action = ignore_ws_change;4541return0;4542}45434544static intoption_parse_whitespace(const struct option *opt,4545const char*arg,int unset)4546{4547const char**whitespace_option = opt->value;45484549*whitespace_option = arg;4550parse_whitespace_option(arg);4551return0;4552}45534554static intoption_parse_directory(const struct option *opt,4555const char*arg,int unset)4556{4557strbuf_reset(&root);4558strbuf_addstr(&root, arg);4559strbuf_complete(&root,'/');4560return0;4561}45624563static voidinit_apply_state(struct apply_state *state,const char*prefix)4564{4565memset(state,0,sizeof(*state));4566 state->prefix = prefix;4567 state->prefix_length = state->prefix ?strlen(state->prefix) :0;45684569git_apply_config();4570if(apply_default_whitespace)4571parse_whitespace_option(apply_default_whitespace);4572if(apply_default_ignorewhitespace)4573parse_ignorewhitespace_option(apply_default_ignorewhitespace);4574}45754576static voidclear_apply_state(struct apply_state *state)4577{4578/* empty for now */4579}45804581intcmd_apply(int argc,const char**argv,const char*prefix)4582{4583int i;4584int errs =0;4585int is_not_gitdir = !startup_info->have_repository;4586int force_apply =0;4587int options =0;4588int read_stdin =1;4589struct apply_state state;45904591const char*whitespace_option = NULL;45924593struct option builtin_apply_options[] = {4594{ OPTION_CALLBACK,0,"exclude", NULL,N_("path"),4595N_("don't apply changes matching the given path"),45960, option_parse_exclude },4597{ OPTION_CALLBACK,0,"include", NULL,N_("path"),4598N_("apply changes matching the given path"),45990, option_parse_include },4600{ OPTION_CALLBACK,'p', NULL, NULL,N_("num"),4601N_("remove <num> leading slashes from traditional diff paths"),46020, option_parse_p },4603OPT_BOOL(0,"no-add", &no_add,4604N_("ignore additions made by the patch")),4605OPT_BOOL(0,"stat", &diffstat,4606N_("instead of applying the patch, output diffstat for the input")),4607OPT_NOOP_NOARG(0,"allow-binary-replacement"),4608OPT_NOOP_NOARG(0,"binary"),4609OPT_BOOL(0,"numstat", &numstat,4610N_("show number of added and deleted lines in decimal notation")),4611OPT_BOOL(0,"summary", &summary,4612N_("instead of applying the patch, output a summary for the input")),4613OPT_BOOL(0,"check", &state.check,4614N_("instead of applying the patch, see if the patch is applicable")),4615OPT_BOOL(0,"index", &state.check_index,4616N_("make sure the patch is applicable to the current index")),4617OPT_BOOL(0,"cached", &state.cached,4618N_("apply a patch without touching the working tree")),4619OPT_BOOL(0,"unsafe-paths", &unsafe_paths,4620N_("accept a patch that touches outside the working area")),4621OPT_BOOL(0,"apply", &force_apply,4622N_("also apply the patch (use with --stat/--summary/--check)")),4623OPT_BOOL('3',"3way", &threeway,4624N_("attempt three-way merge if a patch does not apply")),4625OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,4626N_("build a temporary index based on embedded index information")),4627/* Think twice before adding "--nul" synonym to this */4628OPT_SET_INT('z', NULL, &line_termination,4629N_("paths are separated with NUL character"),'\0'),4630OPT_INTEGER('C', NULL, &p_context,4631N_("ensure at least <n> lines of context match")),4632{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,N_("action"),4633N_("detect new or modified lines that have whitespace errors"),46340, option_parse_whitespace },4635{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,4636N_("ignore changes in whitespace when finding context"),4637 PARSE_OPT_NOARG, option_parse_space_change },4638{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,4639N_("ignore changes in whitespace when finding context"),4640 PARSE_OPT_NOARG, option_parse_space_change },4641OPT_BOOL('R',"reverse", &state.apply_in_reverse,4642N_("apply the patch in reverse")),4643OPT_BOOL(0,"unidiff-zero", &state.unidiff_zero,4644N_("don't expect at least one line of context")),4645OPT_BOOL(0,"reject", &state.apply_with_reject,4646N_("leave the rejected hunks in corresponding *.rej files")),4647OPT_BOOL(0,"allow-overlap", &state.allow_overlap,4648N_("allow overlapping hunks")),4649OPT__VERBOSE(&state.apply_verbosely,N_("be verbose")),4650OPT_BIT(0,"inaccurate-eof", &options,4651N_("tolerate incorrectly detected missing new-line at the end of file"),4652 INACCURATE_EOF),4653OPT_BIT(0,"recount", &options,4654N_("do not trust the line counts in the hunk headers"),4655 RECOUNT),4656{ OPTION_CALLBACK,0,"directory", NULL,N_("root"),4657N_("prepend <root> to all filenames"),46580, option_parse_directory },4659OPT_END()4660};46614662init_apply_state(&state, prefix);46634664 argc =parse_options(argc, argv, state.prefix, builtin_apply_options,4665 apply_usage,0);46664667if(state.apply_with_reject && threeway)4668die("--reject and --3way cannot be used together.");4669if(state.cached && threeway)4670die("--cached and --3way cannot be used together.");4671if(threeway) {4672if(is_not_gitdir)4673die(_("--3way outside a repository"));4674 state.check_index =1;4675}4676if(state.apply_with_reject)4677 apply = state.apply_verbosely =1;4678if(!force_apply && (diffstat || numstat || summary || state.check || fake_ancestor))4679 apply =0;4680if(state.check_index && is_not_gitdir)4681die(_("--index outside a repository"));4682if(state.cached) {4683if(is_not_gitdir)4684die(_("--cached outside a repository"));4685 state.check_index =1;4686}4687if(state.check_index)4688 unsafe_paths =0;46894690for(i =0; i < argc; i++) {4691const char*arg = argv[i];4692int fd;46934694if(!strcmp(arg,"-")) {4695 errs |=apply_patch(&state,0,"<stdin>", options);4696 read_stdin =0;4697continue;4698}else if(0< state.prefix_length)4699 arg =prefix_filename(state.prefix,4700 state.prefix_length,4701 arg);47024703 fd =open(arg, O_RDONLY);4704if(fd <0)4705die_errno(_("can't open patch '%s'"), arg);4706 read_stdin =0;4707set_default_whitespace_mode(whitespace_option);4708 errs |=apply_patch(&state, fd, arg, options);4709close(fd);4710}4711set_default_whitespace_mode(whitespace_option);4712if(read_stdin)4713 errs |=apply_patch(&state,0,"<stdin>", options);4714if(whitespace_error) {4715if(squelch_whitespace_errors &&4716 squelch_whitespace_errors < whitespace_error) {4717int squelched =4718 whitespace_error - squelch_whitespace_errors;4719warning(Q_("squelched%dwhitespace error",4720"squelched%dwhitespace errors",4721 squelched),4722 squelched);4723}4724if(ws_error_action == die_on_ws_error)4725die(Q_("%dline adds whitespace errors.",4726"%dlines add whitespace errors.",4727 whitespace_error),4728 whitespace_error);4729if(applied_after_fixing_ws && apply)4730warning("%dline%sapplied after"4731" fixing whitespace errors.",4732 applied_after_fixing_ws,4733 applied_after_fixing_ws ==1?"":"s");4734else if(whitespace_error)4735warning(Q_("%dline adds whitespace errors.",4736"%dlines add whitespace errors.",4737 whitespace_error),4738 whitespace_error);4739}47404741if(state.update_index) {4742if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK))4743die(_("Unable to write new index file"));4744}47454746clear_apply_state(&state);47474748return!!errs;4749}