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 24/* 25 * --check turns on checking that the working tree matches the 26 * files that are being modified, but doesn't apply the patch 27 * --stat does just a diffstat, and doesn't actually apply 28 * --numstat does numeric diffstat, and doesn't actually apply 29 * --index-info shows the old and new index info for paths if available. 30 * --index updates the cache as well. 31 * --cached updates only the cache without ever touching the working tree. 32 */ 33static const char*prefix; 34static int prefix_length = -1; 35static int newfd = -1; 36 37static int unidiff_zero; 38static int p_value =1; 39static int p_value_known; 40static int check_index; 41static int update_index; 42static int cached; 43static int diffstat; 44static int numstat; 45static int summary; 46static int check; 47static int apply =1; 48static int apply_in_reverse; 49static int apply_with_reject; 50static int apply_verbosely; 51static int allow_overlap; 52static int no_add; 53static int threeway; 54static int unsafe_paths; 55static const char*fake_ancestor; 56static int line_termination ='\n'; 57static unsigned int p_context = UINT_MAX; 58static const char*const apply_usage[] = { 59N_("git apply [options] [<patch>...]"), 60 NULL 61}; 62 63static enum ws_error_action { 64 nowarn_ws_error, 65 warn_on_ws_error, 66 die_on_ws_error, 67 correct_ws_error 68} ws_error_action = warn_on_ws_error; 69static int whitespace_error; 70static int squelch_whitespace_errors =5; 71static int applied_after_fixing_ws; 72 73static enum ws_ignore { 74 ignore_ws_none, 75 ignore_ws_change 76} ws_ignore_action = ignore_ws_none; 77 78 79static const char*patch_input_file; 80static const char*root; 81static int root_len; 82static int read_stdin =1; 83static int options; 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 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 */ 211unsigned char threeway_stage[3][20]; 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) 498strbuf_insert(&name,0, root, 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) { 701char*ret =xmalloc(root_len + len +1); 702strcpy(ret, root); 703memcpy(ret + root_len, start, len); 704 ret[root_len + len] ='\0'; 705returnsquash_slash(ret); 706} 707 708returnsquash_slash(xmemdupz(start, len)); 709} 710 711static char*find_name(const char*line,char*def,int p_value,int terminate) 712{ 713if(*line =='"') { 714char*name =find_name_gnu(line, def, p_value); 715if(name) 716return name; 717} 718 719returnfind_name_common(line, def, p_value, NULL, terminate); 720} 721 722static char*find_name_traditional(const char*line,char*def,int p_value) 723{ 724size_t len; 725size_t date_len; 726 727if(*line =='"') { 728char*name =find_name_gnu(line, def, p_value); 729if(name) 730return name; 731} 732 733 len =strchrnul(line,'\n') - line; 734 date_len =diff_timestamp_len(line, len); 735if(!date_len) 736returnfind_name_common(line, def, p_value, NULL, TERM_TAB); 737 len -= date_len; 738 739returnfind_name_common(line, def, p_value, line + len,0); 740} 741 742static intcount_slashes(const char*cp) 743{ 744int cnt =0; 745char ch; 746 747while((ch = *cp++)) 748if(ch =='/') 749 cnt++; 750return cnt; 751} 752 753/* 754 * Given the string after "--- " or "+++ ", guess the appropriate 755 * p_value for the given patch. 756 */ 757static intguess_p_value(const char*nameline) 758{ 759char*name, *cp; 760int val = -1; 761 762if(is_dev_null(nameline)) 763return-1; 764 name =find_name_traditional(nameline, NULL,0); 765if(!name) 766return-1; 767 cp =strchr(name,'/'); 768if(!cp) 769 val =0; 770else if(prefix) { 771/* 772 * Does it begin with "a/$our-prefix" and such? Then this is 773 * very likely to apply to our directory. 774 */ 775if(!strncmp(name, prefix, prefix_length)) 776 val =count_slashes(prefix); 777else{ 778 cp++; 779if(!strncmp(cp, prefix, prefix_length)) 780 val =count_slashes(prefix) +1; 781} 782} 783free(name); 784return val; 785} 786 787/* 788 * Does the ---/+++ line has the POSIX timestamp after the last HT? 789 * GNU diff puts epoch there to signal a creation/deletion event. Is 790 * this such a timestamp? 791 */ 792static inthas_epoch_timestamp(const char*nameline) 793{ 794/* 795 * We are only interested in epoch timestamp; any non-zero 796 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 797 * For the same reason, the date must be either 1969-12-31 or 798 * 1970-01-01, and the seconds part must be "00". 799 */ 800const char stamp_regexp[] = 801"^(1969-12-31|1970-01-01)" 802" " 803"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 804" " 805"([-+][0-2][0-9]:?[0-5][0-9])\n"; 806const char*timestamp = NULL, *cp, *colon; 807static regex_t *stamp; 808 regmatch_t m[10]; 809int zoneoffset; 810int hourminute; 811int status; 812 813for(cp = nameline; *cp !='\n'; cp++) { 814if(*cp =='\t') 815 timestamp = cp +1; 816} 817if(!timestamp) 818return0; 819if(!stamp) { 820 stamp =xmalloc(sizeof(*stamp)); 821if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 822warning(_("Cannot prepare timestamp regexp%s"), 823 stamp_regexp); 824return0; 825} 826} 827 828 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 829if(status) { 830if(status != REG_NOMATCH) 831warning(_("regexec returned%dfor input:%s"), 832 status, timestamp); 833return0; 834} 835 836 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 837if(*colon ==':') 838 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 839else 840 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 841if(timestamp[m[3].rm_so] =='-') 842 zoneoffset = -zoneoffset; 843 844/* 845 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 846 * (west of GMT) or 1970-01-01 (east of GMT) 847 */ 848if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 849(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 850return0; 851 852 hourminute = (strtol(timestamp +11, NULL,10) *60+ 853strtol(timestamp +14, NULL,10) - 854 zoneoffset); 855 856return((zoneoffset <0&& hourminute ==1440) || 857(0<= zoneoffset && !hourminute)); 858} 859 860/* 861 * Get the name etc info from the ---/+++ lines of a traditional patch header 862 * 863 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 864 * files, we can happily check the index for a match, but for creating a 865 * new file we should try to match whatever "patch" does. I have no idea. 866 */ 867static voidparse_traditional_patch(const char*first,const char*second,struct 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(first); 876 q =guess_p_value(second); 877if(p <0) p = q; 878if(0<= p && p == q) { 879 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, 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, p_value); 892 patch->old_name = name; 893}else{ 894char*first_name; 895 first_name =find_name_traditional(first, NULL, p_value); 896 name =find_name_traditional(second, first_name, 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"), 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 char*gitdiff_verify_name(const char*line,int isnull,char*orig_name,int side) 933{ 934if(!orig_name && !isnull) 935returnfind_name(line, NULL, p_value, TERM_TAB); 936 937if(orig_name) { 938int len; 939const char*name; 940char*another; 941 name = orig_name; 942 len =strlen(name); 943if(isnull) 944die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), name, linenr); 945 another =find_name(line, NULL, 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"), linenr); 950free(another); 951return orig_name; 952} 953else{ 954/* expect "/dev/null" */ 955if(memcmp("/dev/null", line,9) || line[9] !='\n') 956die(_("git apply: bad git-diff - expected /dev/null on line%d"), linenr); 957return NULL; 958} 959} 960 961static intgitdiff_oldname(const char*line,struct patch *patch) 962{ 963char*orig = patch->old_name; 964 patch->old_name =gitdiff_verify_name(line, patch->is_new, patch->old_name, 965 DIFF_OLD_NAME); 966if(orig != patch->old_name) 967free(orig); 968return0; 969} 970 971static intgitdiff_newname(const char*line,struct patch *patch) 972{ 973char*orig = patch->new_name; 974 patch->new_name =gitdiff_verify_name(line, patch->is_delete, patch->new_name, 975 DIFF_NEW_NAME); 976if(orig != patch->new_name) 977free(orig); 978return0; 979} 980 981static intgitdiff_oldmode(const char*line,struct patch *patch) 982{ 983 patch->old_mode =strtoul(line, NULL,8); 984return0; 985} 986 987static intgitdiff_newmode(const char*line,struct patch *patch) 988{ 989 patch->new_mode =strtoul(line, NULL,8); 990return0; 991} 992 993static intgitdiff_delete(const char*line,struct patch *patch) 994{ 995 patch->is_delete =1; 996free(patch->old_name); 997 patch->old_name =xstrdup_or_null(patch->def_name); 998returngitdiff_oldmode(line, patch); 999}10001001static intgitdiff_newfile(const char*line,struct patch *patch)1002{1003 patch->is_new =1;1004free(patch->new_name);1005 patch->new_name =xstrdup_or_null(patch->def_name);1006returngitdiff_newmode(line, patch);1007}10081009static intgitdiff_copysrc(const char*line,struct patch *patch)1010{1011 patch->is_copy =1;1012free(patch->old_name);1013 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0);1014return0;1015}10161017static intgitdiff_copydst(const char*line,struct patch *patch)1018{1019 patch->is_copy =1;1020free(patch->new_name);1021 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0);1022return0;1023}10241025static intgitdiff_renamesrc(const char*line,struct patch *patch)1026{1027 patch->is_rename =1;1028free(patch->old_name);1029 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0);1030return0;1031}10321033static intgitdiff_renamedst(const char*line,struct patch *patch)1034{1035 patch->is_rename =1;1036free(patch->new_name);1037 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0);1038return0;1039}10401041static intgitdiff_similarity(const char*line,struct patch *patch)1042{1043unsigned long val =strtoul(line, NULL,10);1044if(val <=100)1045 patch->score = val;1046return0;1047}10481049static intgitdiff_dissimilarity(const char*line,struct patch *patch)1050{1051unsigned long val =strtoul(line, NULL,10);1052if(val <=100)1053 patch->score = val;1054return0;1055}10561057static intgitdiff_index(const char*line,struct patch *patch)1058{1059/*1060 * index line is N hexadecimal, "..", N hexadecimal,1061 * and optional space with octal mode.1062 */1063const char*ptr, *eol;1064int len;10651066 ptr =strchr(line,'.');1067if(!ptr || ptr[1] !='.'||40< ptr - line)1068return0;1069 len = ptr - line;1070memcpy(patch->old_sha1_prefix, line, len);1071 patch->old_sha1_prefix[len] =0;10721073 line = ptr +2;1074 ptr =strchr(line,' ');1075 eol =strchrnul(line,'\n');10761077if(!ptr || eol < ptr)1078 ptr = eol;1079 len = ptr - line;10801081if(40< len)1082return0;1083memcpy(patch->new_sha1_prefix, line, len);1084 patch->new_sha1_prefix[len] =0;1085if(*ptr ==' ')1086 patch->old_mode =strtoul(ptr+1, NULL,8);1087return0;1088}10891090/*1091 * This is normal for a diff that doesn't change anything: we'll fall through1092 * into the next diff. Tell the parser to break out.1093 */1094static intgitdiff_unrecognized(const char*line,struct patch *patch)1095{1096return-1;1097}10981099/*1100 * Skip p_value leading components from "line"; as we do not accept1101 * absolute paths, return NULL in that case.1102 */1103static const char*skip_tree_prefix(const char*line,int llen)1104{1105int nslash;1106int i;11071108if(!p_value)1109return(llen && line[0] =='/') ? NULL : line;11101111 nslash = p_value;1112for(i =0; i < llen; i++) {1113int ch = line[i];1114if(ch =='/'&& --nslash <=0)1115return(i ==0) ? NULL : &line[i +1];1116}1117return NULL;1118}11191120/*1121 * This is to extract the same name that appears on "diff --git"1122 * line. We do not find and return anything if it is a rename1123 * patch, and it is OK because we will find the name elsewhere.1124 * We need to reliably find name only when it is mode-change only,1125 * creation or deletion of an empty file. In any of these cases,1126 * both sides are the same name under a/ and b/ respectively.1127 */1128static char*git_header_name(const char*line,int llen)1129{1130const char*name;1131const char*second = NULL;1132size_t len, line_len;11331134 line +=strlen("diff --git ");1135 llen -=strlen("diff --git ");11361137if(*line =='"') {1138const char*cp;1139struct strbuf first = STRBUF_INIT;1140struct strbuf sp = STRBUF_INIT;11411142if(unquote_c_style(&first, line, &second))1143goto free_and_fail1;11441145/* strip the a/b prefix including trailing slash */1146 cp =skip_tree_prefix(first.buf, first.len);1147if(!cp)1148goto free_and_fail1;1149strbuf_remove(&first,0, cp - first.buf);11501151/*1152 * second points at one past closing dq of name.1153 * find the second name.1154 */1155while((second < line + llen) &&isspace(*second))1156 second++;11571158if(line + llen <= second)1159goto free_and_fail1;1160if(*second =='"') {1161if(unquote_c_style(&sp, second, NULL))1162goto free_and_fail1;1163 cp =skip_tree_prefix(sp.buf, sp.len);1164if(!cp)1165goto free_and_fail1;1166/* They must match, otherwise ignore */1167if(strcmp(cp, first.buf))1168goto free_and_fail1;1169strbuf_release(&sp);1170returnstrbuf_detach(&first, NULL);1171}11721173/* unquoted second */1174 cp =skip_tree_prefix(second, line + llen - second);1175if(!cp)1176goto free_and_fail1;1177if(line + llen - cp != first.len ||1178memcmp(first.buf, cp, first.len))1179goto free_and_fail1;1180returnstrbuf_detach(&first, NULL);11811182 free_and_fail1:1183strbuf_release(&first);1184strbuf_release(&sp);1185return NULL;1186}11871188/* unquoted first name */1189 name =skip_tree_prefix(line, llen);1190if(!name)1191return NULL;11921193/*1194 * since the first name is unquoted, a dq if exists must be1195 * the beginning of the second name.1196 */1197for(second = name; second < line + llen; second++) {1198if(*second =='"') {1199struct strbuf sp = STRBUF_INIT;1200const char*np;12011202if(unquote_c_style(&sp, second, NULL))1203goto free_and_fail2;12041205 np =skip_tree_prefix(sp.buf, sp.len);1206if(!np)1207goto free_and_fail2;12081209 len = sp.buf + sp.len - np;1210if(len < second - name &&1211!strncmp(np, name, len) &&1212isspace(name[len])) {1213/* Good */1214strbuf_remove(&sp,0, np - sp.buf);1215returnstrbuf_detach(&sp, NULL);1216}12171218 free_and_fail2:1219strbuf_release(&sp);1220return NULL;1221}1222}12231224/*1225 * Accept a name only if it shows up twice, exactly the same1226 * form.1227 */1228 second =strchr(name,'\n');1229if(!second)1230return NULL;1231 line_len = second - name;1232for(len =0; ; len++) {1233switch(name[len]) {1234default:1235continue;1236case'\n':1237return NULL;1238case'\t':case' ':1239/*1240 * Is this the separator between the preimage1241 * and the postimage pathname? Again, we are1242 * only interested in the case where there is1243 * no rename, as this is only to set def_name1244 * and a rename patch has the names elsewhere1245 * in an unambiguous form.1246 */1247if(!name[len +1])1248return NULL;/* no postimage name */1249 second =skip_tree_prefix(name + len +1,1250 line_len - (len +1));1251if(!second)1252return NULL;1253/*1254 * Does len bytes starting at "name" and "second"1255 * (that are separated by one HT or SP we just1256 * found) exactly match?1257 */1258if(second[len] =='\n'&& !strncmp(name, second, len))1259returnxmemdupz(name, len);1260}1261}1262}12631264/* Verify that we recognize the lines following a git header */1265static intparse_git_header(const char*line,int len,unsigned int size,struct patch *patch)1266{1267unsigned long offset;12681269/* A git diff has explicit new/delete information, so we don't guess */1270 patch->is_new =0;1271 patch->is_delete =0;12721273/*1274 * Some things may not have the old name in the1275 * rest of the headers anywhere (pure mode changes,1276 * or removing or adding empty files), so we get1277 * the default name from the header.1278 */1279 patch->def_name =git_header_name(line, len);1280if(patch->def_name && root) {1281char*s =xstrfmt("%s%s", root, patch->def_name);1282free(patch->def_name);1283 patch->def_name = s;1284}12851286 line += len;1287 size -= len;1288 linenr++;1289for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) {1290static const struct opentry {1291const char*str;1292int(*fn)(const char*,struct patch *);1293} optable[] = {1294{"@@ -", gitdiff_hdrend },1295{"--- ", gitdiff_oldname },1296{"+++ ", gitdiff_newname },1297{"old mode ", gitdiff_oldmode },1298{"new mode ", gitdiff_newmode },1299{"deleted file mode ", gitdiff_delete },1300{"new file mode ", gitdiff_newfile },1301{"copy from ", gitdiff_copysrc },1302{"copy to ", gitdiff_copydst },1303{"rename old ", gitdiff_renamesrc },1304{"rename new ", gitdiff_renamedst },1305{"rename from ", gitdiff_renamesrc },1306{"rename to ", gitdiff_renamedst },1307{"similarity index ", gitdiff_similarity },1308{"dissimilarity index ", gitdiff_dissimilarity },1309{"index ", gitdiff_index },1310{"", gitdiff_unrecognized },1311};1312int i;13131314 len =linelen(line, size);1315if(!len || line[len-1] !='\n')1316break;1317for(i =0; i <ARRAY_SIZE(optable); i++) {1318const struct opentry *p = optable + i;1319int oplen =strlen(p->str);1320if(len < oplen ||memcmp(p->str, line, oplen))1321continue;1322if(p->fn(line + oplen, patch) <0)1323return offset;1324break;1325}1326}13271328return offset;1329}13301331static intparse_num(const char*line,unsigned long*p)1332{1333char*ptr;13341335if(!isdigit(*line))1336return0;1337*p =strtoul(line, &ptr,10);1338return ptr - line;1339}13401341static intparse_range(const char*line,int len,int offset,const char*expect,1342unsigned long*p1,unsigned long*p2)1343{1344int digits, ex;13451346if(offset <0|| offset >= len)1347return-1;1348 line += offset;1349 len -= offset;13501351 digits =parse_num(line, p1);1352if(!digits)1353return-1;13541355 offset += digits;1356 line += digits;1357 len -= digits;13581359*p2 =1;1360if(*line ==',') {1361 digits =parse_num(line+1, p2);1362if(!digits)1363return-1;13641365 offset += digits+1;1366 line += digits+1;1367 len -= digits+1;1368}13691370 ex =strlen(expect);1371if(ex > len)1372return-1;1373if(memcmp(line, expect, ex))1374return-1;13751376return offset + ex;1377}13781379static voidrecount_diff(const char*line,int size,struct fragment *fragment)1380{1381int oldlines =0, newlines =0, ret =0;13821383if(size <1) {1384warning("recount: ignore empty hunk");1385return;1386}13871388for(;;) {1389int len =linelen(line, size);1390 size -= len;1391 line += len;13921393if(size <1)1394break;13951396switch(*line) {1397case' ':case'\n':1398 newlines++;1399/* fall through */1400case'-':1401 oldlines++;1402continue;1403case'+':1404 newlines++;1405continue;1406case'\\':1407continue;1408case'@':1409 ret = size <3|| !starts_with(line,"@@ ");1410break;1411case'd':1412 ret = size <5|| !starts_with(line,"diff ");1413break;1414default:1415 ret = -1;1416break;1417}1418if(ret) {1419warning(_("recount: unexpected line: %.*s"),1420(int)linelen(line, size), line);1421return;1422}1423break;1424}1425 fragment->oldlines = oldlines;1426 fragment->newlines = newlines;1427}14281429/*1430 * Parse a unified diff fragment header of the1431 * form "@@ -a,b +c,d @@"1432 */1433static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1434{1435int offset;14361437if(!len || line[len-1] !='\n')1438return-1;14391440/* Figure out the number of lines in a fragment */1441 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1442 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14431444return offset;1445}14461447static intfind_header(const char*line,unsigned long size,int*hdrsize,struct patch *patch)1448{1449unsigned long offset, len;14501451 patch->is_toplevel_relative =0;1452 patch->is_rename = patch->is_copy =0;1453 patch->is_new = patch->is_delete = -1;1454 patch->old_mode = patch->new_mode =0;1455 patch->old_name = patch->new_name = NULL;1456for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) {1457unsigned long nextlen;14581459 len =linelen(line, size);1460if(!len)1461break;14621463/* Testing this early allows us to take a few shortcuts.. */1464if(len <6)1465continue;14661467/*1468 * Make sure we don't find any unconnected patch fragments.1469 * That's a sign that we didn't find a header, and that a1470 * patch has become corrupted/broken up.1471 */1472if(!memcmp("@@ -", line,4)) {1473struct fragment dummy;1474if(parse_fragment_header(line, len, &dummy) <0)1475continue;1476die(_("patch fragment without header at line%d: %.*s"),1477 linenr, (int)len-1, line);1478}14791480if(size < len +6)1481break;14821483/*1484 * Git patch? It might not have a real patch, just a rename1485 * or mode change, so we handle that specially1486 */1487if(!memcmp("diff --git ", line,11)) {1488int git_hdr_len =parse_git_header(line, len, size, patch);1489if(git_hdr_len <= len)1490continue;1491if(!patch->old_name && !patch->new_name) {1492if(!patch->def_name)1493die(Q_("git diff header lacks filename information when removing "1494"%dleading pathname component (line%d)",1495"git diff header lacks filename information when removing "1496"%dleading pathname components (line%d)",1497 p_value),1498 p_value, linenr);1499 patch->old_name =xstrdup(patch->def_name);1500 patch->new_name =xstrdup(patch->def_name);1501}1502if(!patch->is_delete && !patch->new_name)1503die("git diff header lacks filename information "1504"(line%d)", linenr);1505 patch->is_toplevel_relative =1;1506*hdrsize = git_hdr_len;1507return offset;1508}15091510/* --- followed by +++ ? */1511if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1512continue;15131514/*1515 * We only accept unified patches, so we want it to1516 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1517 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1518 */1519 nextlen =linelen(line + len, size - len);1520if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1521continue;15221523/* Ok, we'll consider it a patch */1524parse_traditional_patch(line, line+len, patch);1525*hdrsize = len + nextlen;1526 linenr +=2;1527return offset;1528}1529return-1;1530}15311532static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1533{1534char*err;15351536if(!result)1537return;15381539 whitespace_error++;1540if(squelch_whitespace_errors &&1541 squelch_whitespace_errors < whitespace_error)1542return;15431544 err =whitespace_error_string(result);1545fprintf(stderr,"%s:%d:%s.\n%.*s\n",1546 patch_input_file, linenr, err, len, line);1547free(err);1548}15491550static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1551{1552unsigned result =ws_check(line +1, len -1, ws_rule);15531554record_ws_error(result, line +1, len -2, linenr);1555}15561557/*1558 * Parse a unified diff. Note that this really needs to parse each1559 * fragment separately, since the only way to know the difference1560 * between a "---" that is part of a patch, and a "---" that starts1561 * the next patch is to look at the line counts..1562 */1563static intparse_fragment(const char*line,unsigned long size,1564struct patch *patch,struct fragment *fragment)1565{1566int added, deleted;1567int len =linelen(line, size), offset;1568unsigned long oldlines, newlines;1569unsigned long leading, trailing;15701571 offset =parse_fragment_header(line, len, fragment);1572if(offset <0)1573return-1;1574if(offset >0&& patch->recount)1575recount_diff(line + offset, size - offset, fragment);1576 oldlines = fragment->oldlines;1577 newlines = fragment->newlines;1578 leading =0;1579 trailing =0;15801581/* Parse the thing.. */1582 line += len;1583 size -= len;1584 linenr++;1585 added = deleted =0;1586for(offset = len;15870< size;1588 offset += len, size -= len, line += len, linenr++) {1589if(!oldlines && !newlines)1590break;1591 len =linelen(line, size);1592if(!len || line[len-1] !='\n')1593return-1;1594switch(*line) {1595default:1596return-1;1597case'\n':/* newer GNU diff, an empty context line */1598case' ':1599 oldlines--;1600 newlines--;1601if(!deleted && !added)1602 leading++;1603 trailing++;1604break;1605case'-':1606if(apply_in_reverse &&1607 ws_error_action != nowarn_ws_error)1608check_whitespace(line, len, patch->ws_rule);1609 deleted++;1610 oldlines--;1611 trailing =0;1612break;1613case'+':1614if(!apply_in_reverse &&1615 ws_error_action != nowarn_ws_error)1616check_whitespace(line, len, patch->ws_rule);1617 added++;1618 newlines--;1619 trailing =0;1620break;16211622/*1623 * We allow "\ No newline at end of file". Depending1624 * on locale settings when the patch was produced we1625 * don't know what this line looks like. The only1626 * thing we do know is that it begins with "\ ".1627 * Checking for 12 is just for sanity check -- any1628 * l10n of "\ No newline..." is at least that long.1629 */1630case'\\':1631if(len <12||memcmp(line,"\\",2))1632return-1;1633break;1634}1635}1636if(oldlines || newlines)1637return-1;1638 fragment->leading = leading;1639 fragment->trailing = trailing;16401641/*1642 * If a fragment ends with an incomplete line, we failed to include1643 * it in the above loop because we hit oldlines == newlines == 01644 * before seeing it.1645 */1646if(12< size && !memcmp(line,"\\",2))1647 offset +=linelen(line, size);16481649 patch->lines_added += added;1650 patch->lines_deleted += deleted;16511652if(0< patch->is_new && oldlines)1653returnerror(_("new file depends on old contents"));1654if(0< patch->is_delete && newlines)1655returnerror(_("deleted file still has contents"));1656return offset;1657}16581659/*1660 * We have seen "diff --git a/... b/..." header (or a traditional patch1661 * header). Read hunks that belong to this patch into fragments and hang1662 * them to the given patch structure.1663 *1664 * The (fragment->patch, fragment->size) pair points into the memory given1665 * by the caller, not a copy, when we return.1666 */1667static intparse_single_patch(const char*line,unsigned long size,struct patch *patch)1668{1669unsigned long offset =0;1670unsigned long oldlines =0, newlines =0, context =0;1671struct fragment **fragp = &patch->fragments;16721673while(size >4&& !memcmp(line,"@@ -",4)) {1674struct fragment *fragment;1675int len;16761677 fragment =xcalloc(1,sizeof(*fragment));1678 fragment->linenr = linenr;1679 len =parse_fragment(line, size, patch, fragment);1680if(len <=0)1681die(_("corrupt patch at line%d"), linenr);1682 fragment->patch = line;1683 fragment->size = len;1684 oldlines += fragment->oldlines;1685 newlines += fragment->newlines;1686 context += fragment->leading + fragment->trailing;16871688*fragp = fragment;1689 fragp = &fragment->next;16901691 offset += len;1692 line += len;1693 size -= len;1694}16951696/*1697 * If something was removed (i.e. we have old-lines) it cannot1698 * be creation, and if something was added it cannot be1699 * deletion. However, the reverse is not true; --unified=01700 * patches that only add are not necessarily creation even1701 * though they do not have any old lines, and ones that only1702 * delete are not necessarily deletion.1703 *1704 * Unfortunately, a real creation/deletion patch do _not_ have1705 * any context line by definition, so we cannot safely tell it1706 * apart with --unified=0 insanity. At least if the patch has1707 * more than one hunk it is not creation or deletion.1708 */1709if(patch->is_new <0&&1710(oldlines || (patch->fragments && patch->fragments->next)))1711 patch->is_new =0;1712if(patch->is_delete <0&&1713(newlines || (patch->fragments && patch->fragments->next)))1714 patch->is_delete =0;17151716if(0< patch->is_new && oldlines)1717die(_("new file%sdepends on old contents"), patch->new_name);1718if(0< patch->is_delete && newlines)1719die(_("deleted file%sstill has contents"), patch->old_name);1720if(!patch->is_delete && !newlines && context)1721fprintf_ln(stderr,1722_("** warning: "1723"file%sbecomes empty but is not deleted"),1724 patch->new_name);17251726return offset;1727}17281729staticinlineintmetadata_changes(struct patch *patch)1730{1731return patch->is_rename >0||1732 patch->is_copy >0||1733 patch->is_new >0||1734 patch->is_delete ||1735(patch->old_mode && patch->new_mode &&1736 patch->old_mode != patch->new_mode);1737}17381739static char*inflate_it(const void*data,unsigned long size,1740unsigned long inflated_size)1741{1742 git_zstream stream;1743void*out;1744int st;17451746memset(&stream,0,sizeof(stream));17471748 stream.next_in = (unsigned char*)data;1749 stream.avail_in = size;1750 stream.next_out = out =xmalloc(inflated_size);1751 stream.avail_out = inflated_size;1752git_inflate_init(&stream);1753 st =git_inflate(&stream, Z_FINISH);1754git_inflate_end(&stream);1755if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1756free(out);1757return NULL;1758}1759return out;1760}17611762/*1763 * Read a binary hunk and return a new fragment; fragment->patch1764 * points at an allocated memory that the caller must free, so1765 * it is marked as "->free_patch = 1".1766 */1767static struct fragment *parse_binary_hunk(char**buf_p,1768unsigned long*sz_p,1769int*status_p,1770int*used_p)1771{1772/*1773 * Expect a line that begins with binary patch method ("literal"1774 * or "delta"), followed by the length of data before deflating.1775 * a sequence of 'length-byte' followed by base-85 encoded data1776 * should follow, terminated by a newline.1777 *1778 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1779 * and we would limit the patch line to 66 characters,1780 * so one line can fit up to 13 groups that would decode1781 * to 52 bytes max. The length byte 'A'-'Z' corresponds1782 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1783 */1784int llen, used;1785unsigned long size = *sz_p;1786char*buffer = *buf_p;1787int patch_method;1788unsigned long origlen;1789char*data = NULL;1790int hunk_size =0;1791struct fragment *frag;17921793 llen =linelen(buffer, size);1794 used = llen;17951796*status_p =0;17971798if(starts_with(buffer,"delta ")) {1799 patch_method = BINARY_DELTA_DEFLATED;1800 origlen =strtoul(buffer +6, NULL,10);1801}1802else if(starts_with(buffer,"literal ")) {1803 patch_method = BINARY_LITERAL_DEFLATED;1804 origlen =strtoul(buffer +8, NULL,10);1805}1806else1807return NULL;18081809 linenr++;1810 buffer += llen;1811while(1) {1812int byte_length, max_byte_length, newsize;1813 llen =linelen(buffer, size);1814 used += llen;1815 linenr++;1816if(llen ==1) {1817/* consume the blank line */1818 buffer++;1819 size--;1820break;1821}1822/*1823 * Minimum line is "A00000\n" which is 7-byte long,1824 * and the line length must be multiple of 5 plus 2.1825 */1826if((llen <7) || (llen-2) %5)1827goto corrupt;1828 max_byte_length = (llen -2) /5*4;1829 byte_length = *buffer;1830if('A'<= byte_length && byte_length <='Z')1831 byte_length = byte_length -'A'+1;1832else if('a'<= byte_length && byte_length <='z')1833 byte_length = byte_length -'a'+27;1834else1835goto corrupt;1836/* if the input length was not multiple of 4, we would1837 * have filler at the end but the filler should never1838 * exceed 3 bytes1839 */1840if(max_byte_length < byte_length ||1841 byte_length <= max_byte_length -4)1842goto corrupt;1843 newsize = hunk_size + byte_length;1844 data =xrealloc(data, newsize);1845if(decode_85(data + hunk_size, buffer +1, byte_length))1846goto corrupt;1847 hunk_size = newsize;1848 buffer += llen;1849 size -= llen;1850}18511852 frag =xcalloc(1,sizeof(*frag));1853 frag->patch =inflate_it(data, hunk_size, origlen);1854 frag->free_patch =1;1855if(!frag->patch)1856goto corrupt;1857free(data);1858 frag->size = origlen;1859*buf_p = buffer;1860*sz_p = size;1861*used_p = used;1862 frag->binary_patch_method = patch_method;1863return frag;18641865 corrupt:1866free(data);1867*status_p = -1;1868error(_("corrupt binary patch at line%d: %.*s"),1869 linenr-1, llen-1, buffer);1870return NULL;1871}18721873static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1874{1875/*1876 * We have read "GIT binary patch\n"; what follows is a line1877 * that says the patch method (currently, either "literal" or1878 * "delta") and the length of data before deflating; a1879 * sequence of 'length-byte' followed by base-85 encoded data1880 * follows.1881 *1882 * When a binary patch is reversible, there is another binary1883 * hunk in the same format, starting with patch method (either1884 * "literal" or "delta") with the length of data, and a sequence1885 * of length-byte + base-85 encoded data, terminated with another1886 * empty line. This data, when applied to the postimage, produces1887 * the preimage.1888 */1889struct fragment *forward;1890struct fragment *reverse;1891int status;1892int used, used_1;18931894 forward =parse_binary_hunk(&buffer, &size, &status, &used);1895if(!forward && !status)1896/* there has to be one hunk (forward hunk) */1897returnerror(_("unrecognized binary patch at line%d"), linenr-1);1898if(status)1899/* otherwise we already gave an error message */1900return status;19011902 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1903if(reverse)1904 used += used_1;1905else if(status) {1906/*1907 * Not having reverse hunk is not an error, but having1908 * a corrupt reverse hunk is.1909 */1910free((void*) forward->patch);1911free(forward);1912return status;1913}1914 forward->next = reverse;1915 patch->fragments = forward;1916 patch->is_binary =1;1917return used;1918}19191920static voidprefix_one(char**name)1921{1922char*old_name = *name;1923if(!old_name)1924return;1925*name =xstrdup(prefix_filename(prefix, prefix_length, *name));1926free(old_name);1927}19281929static voidprefix_patch(struct patch *p)1930{1931if(!prefix || p->is_toplevel_relative)1932return;1933prefix_one(&p->new_name);1934prefix_one(&p->old_name);1935}19361937/*1938 * include/exclude1939 */19401941static struct string_list limit_by_name;1942static int has_include;1943static voidadd_name_limit(const char*name,int exclude)1944{1945struct string_list_item *it;19461947 it =string_list_append(&limit_by_name, name);1948 it->util = exclude ? NULL : (void*)1;1949}19501951static intuse_patch(struct patch *p)1952{1953const char*pathname = p->new_name ? p->new_name : p->old_name;1954int i;19551956/* Paths outside are not touched regardless of "--include" */1957if(0< prefix_length) {1958int pathlen =strlen(pathname);1959if(pathlen <= prefix_length ||1960memcmp(prefix, pathname, prefix_length))1961return0;1962}19631964/* See if it matches any of exclude/include rule */1965for(i =0; i < limit_by_name.nr; i++) {1966struct string_list_item *it = &limit_by_name.items[i];1967if(!wildmatch(it->string, pathname,0, NULL))1968return(it->util != NULL);1969}19701971/*1972 * If we had any include, a path that does not match any rule is1973 * not used. Otherwise, we saw bunch of exclude rules (or none)1974 * and such a path is used.1975 */1976return!has_include;1977}197819791980/*1981 * Read the patch text in "buffer" that extends for "size" bytes; stop1982 * reading after seeing a single patch (i.e. changes to a single file).1983 * Create fragments (i.e. patch hunks) and hang them to the given patch.1984 * Return the number of bytes consumed, so that the caller can call us1985 * again for the next patch.1986 */1987static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1988{1989int hdrsize, patchsize;1990int offset =find_header(buffer, size, &hdrsize, patch);19911992if(offset <0)1993return offset;19941995prefix_patch(patch);19961997if(!use_patch(patch))1998 patch->ws_rule =0;1999else2000 patch->ws_rule =whitespace_rule(patch->new_name2001? patch->new_name2002: patch->old_name);20032004 patchsize =parse_single_patch(buffer + offset + hdrsize,2005 size - offset - hdrsize, patch);20062007if(!patchsize) {2008static const char git_binary[] ="GIT binary patch\n";2009int hd = hdrsize + offset;2010unsigned long llen =linelen(buffer + hd, size - hd);20112012if(llen ==sizeof(git_binary) -1&&2013!memcmp(git_binary, buffer + hd, llen)) {2014int used;2015 linenr++;2016 used =parse_binary(buffer + hd + llen,2017 size - hd - llen, patch);2018if(used)2019 patchsize = used + llen;2020else2021 patchsize =0;2022}2023else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2024static const char*binhdr[] = {2025"Binary files ",2026"Files ",2027 NULL,2028};2029int i;2030for(i =0; binhdr[i]; i++) {2031int len =strlen(binhdr[i]);2032if(len < size - hd &&2033!memcmp(binhdr[i], buffer + hd, len)) {2034 linenr++;2035 patch->is_binary =1;2036 patchsize = llen;2037break;2038}2039}2040}20412042/* Empty patch cannot be applied if it is a text patch2043 * without metadata change. A binary patch appears2044 * empty to us here.2045 */2046if((apply || check) &&2047(!patch->is_binary && !metadata_changes(patch)))2048die(_("patch with only garbage at line%d"), linenr);2049}20502051return offset + hdrsize + patchsize;2052}20532054#define swap(a,b) myswap((a),(b),sizeof(a))20552056#define myswap(a, b, size) do { \2057 unsigned char mytmp[size]; \2058 memcpy(mytmp, &a, size); \2059 memcpy(&a, &b, size); \2060 memcpy(&b, mytmp, size); \2061} while (0)20622063static voidreverse_patches(struct patch *p)2064{2065for(; p; p = p->next) {2066struct fragment *frag = p->fragments;20672068swap(p->new_name, p->old_name);2069swap(p->new_mode, p->old_mode);2070swap(p->is_new, p->is_delete);2071swap(p->lines_added, p->lines_deleted);2072swap(p->old_sha1_prefix, p->new_sha1_prefix);20732074for(; frag; frag = frag->next) {2075swap(frag->newpos, frag->oldpos);2076swap(frag->newlines, frag->oldlines);2077}2078}2079}20802081static const char pluses[] =2082"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2083static const char minuses[]=2084"----------------------------------------------------------------------";20852086static voidshow_stats(struct patch *patch)2087{2088struct strbuf qname = STRBUF_INIT;2089char*cp = patch->new_name ? patch->new_name : patch->old_name;2090int max, add, del;20912092quote_c_style(cp, &qname, NULL,0);20932094/*2095 * "scale" the filename2096 */2097 max = max_len;2098if(max >50)2099 max =50;21002101if(qname.len > max) {2102 cp =strchr(qname.buf + qname.len +3- max,'/');2103if(!cp)2104 cp = qname.buf + qname.len +3- max;2105strbuf_splice(&qname,0, cp - qname.buf,"...",3);2106}21072108if(patch->is_binary) {2109printf(" %-*s | Bin\n", max, qname.buf);2110strbuf_release(&qname);2111return;2112}21132114printf(" %-*s |", max, qname.buf);2115strbuf_release(&qname);21162117/*2118 * scale the add/delete2119 */2120 max = max + max_change >70?70- max : max_change;2121 add = patch->lines_added;2122 del = patch->lines_deleted;21232124if(max_change >0) {2125int total = ((add + del) * max + max_change /2) / max_change;2126 add = (add * max + max_change /2) / max_change;2127 del = total - add;2128}2129printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2130 add, pluses, del, minuses);2131}21322133static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2134{2135switch(st->st_mode & S_IFMT) {2136case S_IFLNK:2137if(strbuf_readlink(buf, path, st->st_size) <0)2138returnerror(_("unable to read symlink%s"), path);2139return0;2140case S_IFREG:2141if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2142returnerror(_("unable to open or read%s"), path);2143convert_to_git(path, buf->buf, buf->len, buf,0);2144return0;2145default:2146return-1;2147}2148}21492150/*2151 * Update the preimage, and the common lines in postimage,2152 * from buffer buf of length len. If postlen is 0 the postimage2153 * is updated in place, otherwise it's updated on a new buffer2154 * of length postlen2155 */21562157static voidupdate_pre_post_images(struct image *preimage,2158struct image *postimage,2159char*buf,2160size_t len,size_t postlen)2161{2162int i, ctx, reduced;2163char*new, *old, *fixed;2164struct image fixed_preimage;21652166/*2167 * Update the preimage with whitespace fixes. Note that we2168 * are not losing preimage->buf -- apply_one_fragment() will2169 * free "oldlines".2170 */2171prepare_image(&fixed_preimage, buf, len,1);2172assert(postlen2173? fixed_preimage.nr == preimage->nr2174: fixed_preimage.nr <= preimage->nr);2175for(i =0; i < fixed_preimage.nr; i++)2176 fixed_preimage.line[i].flag = preimage->line[i].flag;2177free(preimage->line_allocated);2178*preimage = fixed_preimage;21792180/*2181 * Adjust the common context lines in postimage. This can be2182 * done in-place when we are shrinking it with whitespace2183 * fixing, but needs a new buffer when ignoring whitespace or2184 * expanding leading tabs to spaces.2185 *2186 * We trust the caller to tell us if the update can be done2187 * in place (postlen==0) or not.2188 */2189 old = postimage->buf;2190if(postlen)2191new= postimage->buf =xmalloc(postlen);2192else2193new= old;2194 fixed = preimage->buf;21952196for(i = reduced = ctx =0; i < postimage->nr; i++) {2197size_t len = postimage->line[i].len;2198if(!(postimage->line[i].flag & LINE_COMMON)) {2199/* an added line -- no counterparts in preimage */2200memmove(new, old, len);2201 old += len;2202new+= len;2203continue;2204}22052206/* a common context -- skip it in the original postimage */2207 old += len;22082209/* and find the corresponding one in the fixed preimage */2210while(ctx < preimage->nr &&2211!(preimage->line[ctx].flag & LINE_COMMON)) {2212 fixed += preimage->line[ctx].len;2213 ctx++;2214}22152216/*2217 * preimage is expected to run out, if the caller2218 * fixed addition of trailing blank lines.2219 */2220if(preimage->nr <= ctx) {2221 reduced++;2222continue;2223}22242225/* and copy it in, while fixing the line length */2226 len = preimage->line[ctx].len;2227memcpy(new, fixed, len);2228new+= len;2229 fixed += len;2230 postimage->line[i].len = len;2231 ctx++;2232}22332234if(postlen2235? postlen <new- postimage->buf2236: postimage->len <new- postimage->buf)2237die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2238(int)postlen, (int) postimage->len, (int)(new- postimage->buf));22392240/* Fix the length of the whole thing */2241 postimage->len =new- postimage->buf;2242 postimage->nr -= reduced;2243}22442245static intmatch_fragment(struct image *img,2246struct image *preimage,2247struct image *postimage,2248unsigned longtry,2249int try_lno,2250unsigned ws_rule,2251int match_beginning,int match_end)2252{2253int i;2254char*fixed_buf, *buf, *orig, *target;2255struct strbuf fixed;2256size_t fixed_len, postlen;2257int preimage_limit;22582259if(preimage->nr + try_lno <= img->nr) {2260/*2261 * The hunk falls within the boundaries of img.2262 */2263 preimage_limit = preimage->nr;2264if(match_end && (preimage->nr + try_lno != img->nr))2265return0;2266}else if(ws_error_action == correct_ws_error &&2267(ws_rule & WS_BLANK_AT_EOF)) {2268/*2269 * This hunk extends beyond the end of img, and we are2270 * removing blank lines at the end of the file. This2271 * many lines from the beginning of the preimage must2272 * match with img, and the remainder of the preimage2273 * must be blank.2274 */2275 preimage_limit = img->nr - try_lno;2276}else{2277/*2278 * The hunk extends beyond the end of the img and2279 * we are not removing blanks at the end, so we2280 * should reject the hunk at this position.2281 */2282return0;2283}22842285if(match_beginning && try_lno)2286return0;22872288/* Quick hash check */2289for(i =0; i < preimage_limit; i++)2290if((img->line[try_lno + i].flag & LINE_PATCHED) ||2291(preimage->line[i].hash != img->line[try_lno + i].hash))2292return0;22932294if(preimage_limit == preimage->nr) {2295/*2296 * Do we have an exact match? If we were told to match2297 * at the end, size must be exactly at try+fragsize,2298 * otherwise try+fragsize must be still within the preimage,2299 * and either case, the old piece should match the preimage2300 * exactly.2301 */2302if((match_end2303? (try+ preimage->len == img->len)2304: (try+ preimage->len <= img->len)) &&2305!memcmp(img->buf +try, preimage->buf, preimage->len))2306return1;2307}else{2308/*2309 * The preimage extends beyond the end of img, so2310 * there cannot be an exact match.2311 *2312 * There must be one non-blank context line that match2313 * a line before the end of img.2314 */2315char*buf_end;23162317 buf = preimage->buf;2318 buf_end = buf;2319for(i =0; i < preimage_limit; i++)2320 buf_end += preimage->line[i].len;23212322for( ; buf < buf_end; buf++)2323if(!isspace(*buf))2324break;2325if(buf == buf_end)2326return0;2327}23282329/*2330 * No exact match. If we are ignoring whitespace, run a line-by-line2331 * fuzzy matching. We collect all the line length information because2332 * we need it to adjust whitespace if we match.2333 */2334if(ws_ignore_action == ignore_ws_change) {2335size_t imgoff =0;2336size_t preoff =0;2337size_t postlen = postimage->len;2338size_t extra_chars;2339char*preimage_eof;2340char*preimage_end;2341for(i =0; i < preimage_limit; i++) {2342size_t prelen = preimage->line[i].len;2343size_t imglen = img->line[try_lno+i].len;23442345if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2346 preimage->buf + preoff, prelen))2347return0;2348if(preimage->line[i].flag & LINE_COMMON)2349 postlen += imglen - prelen;2350 imgoff += imglen;2351 preoff += prelen;2352}23532354/*2355 * Ok, the preimage matches with whitespace fuzz.2356 *2357 * imgoff now holds the true length of the target that2358 * matches the preimage before the end of the file.2359 *2360 * Count the number of characters in the preimage that fall2361 * beyond the end of the file and make sure that all of them2362 * are whitespace characters. (This can only happen if2363 * we are removing blank lines at the end of the file.)2364 */2365 buf = preimage_eof = preimage->buf + preoff;2366for( ; i < preimage->nr; i++)2367 preoff += preimage->line[i].len;2368 preimage_end = preimage->buf + preoff;2369for( ; buf < preimage_end; buf++)2370if(!isspace(*buf))2371return0;23722373/*2374 * Update the preimage and the common postimage context2375 * lines to use the same whitespace as the target.2376 * If whitespace is missing in the target (i.e.2377 * if the preimage extends beyond the end of the file),2378 * use the whitespace from the preimage.2379 */2380 extra_chars = preimage_end - preimage_eof;2381strbuf_init(&fixed, imgoff + extra_chars);2382strbuf_add(&fixed, img->buf +try, imgoff);2383strbuf_add(&fixed, preimage_eof, extra_chars);2384 fixed_buf =strbuf_detach(&fixed, &fixed_len);2385update_pre_post_images(preimage, postimage,2386 fixed_buf, fixed_len, postlen);2387return1;2388}23892390if(ws_error_action != correct_ws_error)2391return0;23922393/*2394 * The hunk does not apply byte-by-byte, but the hash says2395 * it might with whitespace fuzz. We weren't asked to2396 * ignore whitespace, we were asked to correct whitespace2397 * errors, so let's try matching after whitespace correction.2398 *2399 * While checking the preimage against the target, whitespace2400 * errors in both fixed, we count how large the corresponding2401 * postimage needs to be. The postimage prepared by2402 * apply_one_fragment() has whitespace errors fixed on added2403 * lines already, but the common lines were propagated as-is,2404 * which may become longer when their whitespace errors are2405 * fixed.2406 */24072408/* First count added lines in postimage */2409 postlen =0;2410for(i =0; i < postimage->nr; i++) {2411if(!(postimage->line[i].flag & LINE_COMMON))2412 postlen += postimage->line[i].len;2413}24142415/*2416 * The preimage may extend beyond the end of the file,2417 * but in this loop we will only handle the part of the2418 * preimage that falls within the file.2419 */2420strbuf_init(&fixed, preimage->len +1);2421 orig = preimage->buf;2422 target = img->buf +try;2423for(i =0; i < preimage_limit; i++) {2424size_t oldlen = preimage->line[i].len;2425size_t tgtlen = img->line[try_lno + i].len;2426size_t fixstart = fixed.len;2427struct strbuf tgtfix;2428int match;24292430/* Try fixing the line in the preimage */2431ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24322433/* Try fixing the line in the target */2434strbuf_init(&tgtfix, tgtlen);2435ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);24362437/*2438 * If they match, either the preimage was based on2439 * a version before our tree fixed whitespace breakage,2440 * or we are lacking a whitespace-fix patch the tree2441 * the preimage was based on already had (i.e. target2442 * has whitespace breakage, the preimage doesn't).2443 * In either case, we are fixing the whitespace breakages2444 * so we might as well take the fix together with their2445 * real change.2446 */2447 match = (tgtfix.len == fixed.len - fixstart &&2448!memcmp(tgtfix.buf, fixed.buf + fixstart,2449 fixed.len - fixstart));24502451/* Add the length if this is common with the postimage */2452if(preimage->line[i].flag & LINE_COMMON)2453 postlen += tgtfix.len;24542455strbuf_release(&tgtfix);2456if(!match)2457goto unmatch_exit;24582459 orig += oldlen;2460 target += tgtlen;2461}246224632464/*2465 * Now handle the lines in the preimage that falls beyond the2466 * end of the file (if any). They will only match if they are2467 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2468 * false).2469 */2470for( ; i < preimage->nr; i++) {2471size_t fixstart = fixed.len;/* start of the fixed preimage */2472size_t oldlen = preimage->line[i].len;2473int j;24742475/* Try fixing the line in the preimage */2476ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24772478for(j = fixstart; j < fixed.len; j++)2479if(!isspace(fixed.buf[j]))2480goto unmatch_exit;24812482 orig += oldlen;2483}24842485/*2486 * Yes, the preimage is based on an older version that still2487 * has whitespace breakages unfixed, and fixing them makes the2488 * hunk match. Update the context lines in the postimage.2489 */2490 fixed_buf =strbuf_detach(&fixed, &fixed_len);2491if(postlen < postimage->len)2492 postlen =0;2493update_pre_post_images(preimage, postimage,2494 fixed_buf, fixed_len, postlen);2495return1;24962497 unmatch_exit:2498strbuf_release(&fixed);2499return0;2500}25012502static intfind_pos(struct image *img,2503struct image *preimage,2504struct image *postimage,2505int line,2506unsigned ws_rule,2507int match_beginning,int match_end)2508{2509int i;2510unsigned long backwards, forwards,try;2511int backwards_lno, forwards_lno, try_lno;25122513/*2514 * If match_beginning or match_end is specified, there is no2515 * point starting from a wrong line that will never match and2516 * wander around and wait for a match at the specified end.2517 */2518if(match_beginning)2519 line =0;2520else if(match_end)2521 line = img->nr - preimage->nr;25222523/*2524 * Because the comparison is unsigned, the following test2525 * will also take care of a negative line number that can2526 * result when match_end and preimage is larger than the target.2527 */2528if((size_t) line > img->nr)2529 line = img->nr;25302531try=0;2532for(i =0; i < line; i++)2533try+= img->line[i].len;25342535/*2536 * There's probably some smart way to do this, but I'll leave2537 * that to the smart and beautiful people. I'm simple and stupid.2538 */2539 backwards =try;2540 backwards_lno = line;2541 forwards =try;2542 forwards_lno = line;2543 try_lno = line;25442545for(i =0; ; i++) {2546if(match_fragment(img, preimage, postimage,2547try, try_lno, ws_rule,2548 match_beginning, match_end))2549return try_lno;25502551 again:2552if(backwards_lno ==0&& forwards_lno == img->nr)2553break;25542555if(i &1) {2556if(backwards_lno ==0) {2557 i++;2558goto again;2559}2560 backwards_lno--;2561 backwards -= img->line[backwards_lno].len;2562try= backwards;2563 try_lno = backwards_lno;2564}else{2565if(forwards_lno == img->nr) {2566 i++;2567goto again;2568}2569 forwards += img->line[forwards_lno].len;2570 forwards_lno++;2571try= forwards;2572 try_lno = forwards_lno;2573}25742575}2576return-1;2577}25782579static voidremove_first_line(struct image *img)2580{2581 img->buf += img->line[0].len;2582 img->len -= img->line[0].len;2583 img->line++;2584 img->nr--;2585}25862587static voidremove_last_line(struct image *img)2588{2589 img->len -= img->line[--img->nr].len;2590}25912592/*2593 * The change from "preimage" and "postimage" has been found to2594 * apply at applied_pos (counts in line numbers) in "img".2595 * Update "img" to remove "preimage" and replace it with "postimage".2596 */2597static voidupdate_image(struct image *img,2598int applied_pos,2599struct image *preimage,2600struct image *postimage)2601{2602/*2603 * remove the copy of preimage at offset in img2604 * and replace it with postimage2605 */2606int i, nr;2607size_t remove_count, insert_count, applied_at =0;2608char*result;2609int preimage_limit;26102611/*2612 * If we are removing blank lines at the end of img,2613 * the preimage may extend beyond the end.2614 * If that is the case, we must be careful only to2615 * remove the part of the preimage that falls within2616 * the boundaries of img. Initialize preimage_limit2617 * to the number of lines in the preimage that falls2618 * within the boundaries.2619 */2620 preimage_limit = preimage->nr;2621if(preimage_limit > img->nr - applied_pos)2622 preimage_limit = img->nr - applied_pos;26232624for(i =0; i < applied_pos; i++)2625 applied_at += img->line[i].len;26262627 remove_count =0;2628for(i =0; i < preimage_limit; i++)2629 remove_count += img->line[applied_pos + i].len;2630 insert_count = postimage->len;26312632/* Adjust the contents */2633 result =xmalloc(img->len + insert_count - remove_count +1);2634memcpy(result, img->buf, applied_at);2635memcpy(result + applied_at, postimage->buf, postimage->len);2636memcpy(result + applied_at + postimage->len,2637 img->buf + (applied_at + remove_count),2638 img->len - (applied_at + remove_count));2639free(img->buf);2640 img->buf = result;2641 img->len += insert_count - remove_count;2642 result[img->len] ='\0';26432644/* Adjust the line table */2645 nr = img->nr + postimage->nr - preimage_limit;2646if(preimage_limit < postimage->nr) {2647/*2648 * NOTE: this knows that we never call remove_first_line()2649 * on anything other than pre/post image.2650 */2651REALLOC_ARRAY(img->line, nr);2652 img->line_allocated = img->line;2653}2654if(preimage_limit != postimage->nr)2655memmove(img->line + applied_pos + postimage->nr,2656 img->line + applied_pos + preimage_limit,2657(img->nr - (applied_pos + preimage_limit)) *2658sizeof(*img->line));2659memcpy(img->line + applied_pos,2660 postimage->line,2661 postimage->nr *sizeof(*img->line));2662if(!allow_overlap)2663for(i =0; i < postimage->nr; i++)2664 img->line[applied_pos + i].flag |= LINE_PATCHED;2665 img->nr = nr;2666}26672668/*2669 * Use the patch-hunk text in "frag" to prepare two images (preimage and2670 * postimage) for the hunk. Find lines that match "preimage" in "img" and2671 * replace the part of "img" with "postimage" text.2672 */2673static intapply_one_fragment(struct image *img,struct fragment *frag,2674int inaccurate_eof,unsigned ws_rule,2675int nth_fragment)2676{2677int match_beginning, match_end;2678const char*patch = frag->patch;2679int size = frag->size;2680char*old, *oldlines;2681struct strbuf newlines;2682int new_blank_lines_at_end =0;2683int found_new_blank_lines_at_end =0;2684int hunk_linenr = frag->linenr;2685unsigned long leading, trailing;2686int pos, applied_pos;2687struct image preimage;2688struct image postimage;26892690memset(&preimage,0,sizeof(preimage));2691memset(&postimage,0,sizeof(postimage));2692 oldlines =xmalloc(size);2693strbuf_init(&newlines, size);26942695 old = oldlines;2696while(size >0) {2697char first;2698int len =linelen(patch, size);2699int plen;2700int added_blank_line =0;2701int is_blank_context =0;2702size_t start;27032704if(!len)2705break;27062707/*2708 * "plen" is how much of the line we should use for2709 * the actual patch data. Normally we just remove the2710 * first character on the line, but if the line is2711 * followed by "\ No newline", then we also remove the2712 * last one (which is the newline, of course).2713 */2714 plen = len -1;2715if(len < size && patch[len] =='\\')2716 plen--;2717 first = *patch;2718if(apply_in_reverse) {2719if(first =='-')2720 first ='+';2721else if(first =='+')2722 first ='-';2723}27242725switch(first) {2726case'\n':2727/* Newer GNU diff, empty context line */2728if(plen <0)2729/* ... followed by '\No newline'; nothing */2730break;2731*old++ ='\n';2732strbuf_addch(&newlines,'\n');2733add_line_info(&preimage,"\n",1, LINE_COMMON);2734add_line_info(&postimage,"\n",1, LINE_COMMON);2735 is_blank_context =1;2736break;2737case' ':2738if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2739ws_blank_line(patch +1, plen, ws_rule))2740 is_blank_context =1;2741case'-':2742memcpy(old, patch +1, plen);2743add_line_info(&preimage, old, plen,2744(first ==' '? LINE_COMMON :0));2745 old += plen;2746if(first =='-')2747break;2748/* Fall-through for ' ' */2749case'+':2750/* --no-add does not add new lines */2751if(first =='+'&& no_add)2752break;27532754 start = newlines.len;2755if(first !='+'||2756!whitespace_error ||2757 ws_error_action != correct_ws_error) {2758strbuf_add(&newlines, patch +1, plen);2759}2760else{2761ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2762}2763add_line_info(&postimage, newlines.buf + start, newlines.len - start,2764(first =='+'?0: LINE_COMMON));2765if(first =='+'&&2766(ws_rule & WS_BLANK_AT_EOF) &&2767ws_blank_line(patch +1, plen, ws_rule))2768 added_blank_line =1;2769break;2770case'@':case'\\':2771/* Ignore it, we already handled it */2772break;2773default:2774if(apply_verbosely)2775error(_("invalid start of line: '%c'"), first);2776return-1;2777}2778if(added_blank_line) {2779if(!new_blank_lines_at_end)2780 found_new_blank_lines_at_end = hunk_linenr;2781 new_blank_lines_at_end++;2782}2783else if(is_blank_context)2784;2785else2786 new_blank_lines_at_end =0;2787 patch += len;2788 size -= len;2789 hunk_linenr++;2790}2791if(inaccurate_eof &&2792 old > oldlines && old[-1] =='\n'&&2793 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2794 old--;2795strbuf_setlen(&newlines, newlines.len -1);2796}27972798 leading = frag->leading;2799 trailing = frag->trailing;28002801/*2802 * A hunk to change lines at the beginning would begin with2803 * @@ -1,L +N,M @@2804 * but we need to be careful. -U0 that inserts before the second2805 * line also has this pattern.2806 *2807 * And a hunk to add to an empty file would begin with2808 * @@ -0,0 +N,M @@2809 *2810 * In other words, a hunk that is (frag->oldpos <= 1) with or2811 * without leading context must match at the beginning.2812 */2813 match_beginning = (!frag->oldpos ||2814(frag->oldpos ==1&& !unidiff_zero));28152816/*2817 * A hunk without trailing lines must match at the end.2818 * However, we simply cannot tell if a hunk must match end2819 * from the lack of trailing lines if the patch was generated2820 * with unidiff without any context.2821 */2822 match_end = !unidiff_zero && !trailing;28232824 pos = frag->newpos ? (frag->newpos -1) :0;2825 preimage.buf = oldlines;2826 preimage.len = old - oldlines;2827 postimage.buf = newlines.buf;2828 postimage.len = newlines.len;2829 preimage.line = preimage.line_allocated;2830 postimage.line = postimage.line_allocated;28312832for(;;) {28332834 applied_pos =find_pos(img, &preimage, &postimage, pos,2835 ws_rule, match_beginning, match_end);28362837if(applied_pos >=0)2838break;28392840/* Am I at my context limits? */2841if((leading <= p_context) && (trailing <= p_context))2842break;2843if(match_beginning || match_end) {2844 match_beginning = match_end =0;2845continue;2846}28472848/*2849 * Reduce the number of context lines; reduce both2850 * leading and trailing if they are equal otherwise2851 * just reduce the larger context.2852 */2853if(leading >= trailing) {2854remove_first_line(&preimage);2855remove_first_line(&postimage);2856 pos--;2857 leading--;2858}2859if(trailing > leading) {2860remove_last_line(&preimage);2861remove_last_line(&postimage);2862 trailing--;2863}2864}28652866if(applied_pos >=0) {2867if(new_blank_lines_at_end &&2868 preimage.nr + applied_pos >= img->nr &&2869(ws_rule & WS_BLANK_AT_EOF) &&2870 ws_error_action != nowarn_ws_error) {2871record_ws_error(WS_BLANK_AT_EOF,"+",1,2872 found_new_blank_lines_at_end);2873if(ws_error_action == correct_ws_error) {2874while(new_blank_lines_at_end--)2875remove_last_line(&postimage);2876}2877/*2878 * We would want to prevent write_out_results()2879 * from taking place in apply_patch() that follows2880 * the callchain led us here, which is:2881 * apply_patch->check_patch_list->check_patch->2882 * apply_data->apply_fragments->apply_one_fragment2883 */2884if(ws_error_action == die_on_ws_error)2885 apply =0;2886}28872888if(apply_verbosely && applied_pos != pos) {2889int offset = applied_pos - pos;2890if(apply_in_reverse)2891 offset =0- offset;2892fprintf_ln(stderr,2893Q_("Hunk #%dsucceeded at%d(offset%dline).",2894"Hunk #%dsucceeded at%d(offset%dlines).",2895 offset),2896 nth_fragment, applied_pos +1, offset);2897}28982899/*2900 * Warn if it was necessary to reduce the number2901 * of context lines.2902 */2903if((leading != frag->leading) ||2904(trailing != frag->trailing))2905fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2906" to apply fragment at%d"),2907 leading, trailing, applied_pos+1);2908update_image(img, applied_pos, &preimage, &postimage);2909}else{2910if(apply_verbosely)2911error(_("while searching for:\n%.*s"),2912(int)(old - oldlines), oldlines);2913}29142915free(oldlines);2916strbuf_release(&newlines);2917free(preimage.line_allocated);2918free(postimage.line_allocated);29192920return(applied_pos <0);2921}29222923static intapply_binary_fragment(struct image *img,struct patch *patch)2924{2925struct fragment *fragment = patch->fragments;2926unsigned long len;2927void*dst;29282929if(!fragment)2930returnerror(_("missing binary patch data for '%s'"),2931 patch->new_name ?2932 patch->new_name :2933 patch->old_name);29342935/* Binary patch is irreversible without the optional second hunk */2936if(apply_in_reverse) {2937if(!fragment->next)2938returnerror("cannot reverse-apply a binary patch "2939"without the reverse hunk to '%s'",2940 patch->new_name2941? patch->new_name : patch->old_name);2942 fragment = fragment->next;2943}2944switch(fragment->binary_patch_method) {2945case BINARY_DELTA_DEFLATED:2946 dst =patch_delta(img->buf, img->len, fragment->patch,2947 fragment->size, &len);2948if(!dst)2949return-1;2950clear_image(img);2951 img->buf = dst;2952 img->len = len;2953return0;2954case BINARY_LITERAL_DEFLATED:2955clear_image(img);2956 img->len = fragment->size;2957 img->buf =xmemdupz(fragment->patch, img->len);2958return0;2959}2960return-1;2961}29622963/*2964 * Replace "img" with the result of applying the binary patch.2965 * The binary patch data itself in patch->fragment is still kept2966 * but the preimage prepared by the caller in "img" is freed here2967 * or in the helper function apply_binary_fragment() this calls.2968 */2969static intapply_binary(struct image *img,struct patch *patch)2970{2971const char*name = patch->old_name ? patch->old_name : patch->new_name;2972unsigned char sha1[20];29732974/*2975 * For safety, we require patch index line to contain2976 * full 40-byte textual SHA1 for old and new, at least for now.2977 */2978if(strlen(patch->old_sha1_prefix) !=40||2979strlen(patch->new_sha1_prefix) !=40||2980get_sha1_hex(patch->old_sha1_prefix, sha1) ||2981get_sha1_hex(patch->new_sha1_prefix, sha1))2982returnerror("cannot apply binary patch to '%s' "2983"without full index line", name);29842985if(patch->old_name) {2986/*2987 * See if the old one matches what the patch2988 * applies to.2989 */2990hash_sha1_file(img->buf, img->len, blob_type, sha1);2991if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2992returnerror("the patch applies to '%s' (%s), "2993"which does not match the "2994"current contents.",2995 name,sha1_to_hex(sha1));2996}2997else{2998/* Otherwise, the old one must be empty. */2999if(img->len)3000returnerror("the patch applies to an empty "3001"'%s' but it is not empty", name);3002}30033004get_sha1_hex(patch->new_sha1_prefix, sha1);3005if(is_null_sha1(sha1)) {3006clear_image(img);3007return0;/* deletion patch */3008}30093010if(has_sha1_file(sha1)) {3011/* We already have the postimage */3012enum object_type type;3013unsigned long size;3014char*result;30153016 result =read_sha1_file(sha1, &type, &size);3017if(!result)3018returnerror("the necessary postimage%sfor "3019"'%s' cannot be read",3020 patch->new_sha1_prefix, name);3021clear_image(img);3022 img->buf = result;3023 img->len = size;3024}else{3025/*3026 * We have verified buf matches the preimage;3027 * apply the patch data to it, which is stored3028 * in the patch->fragments->{patch,size}.3029 */3030if(apply_binary_fragment(img, patch))3031returnerror(_("binary patch does not apply to '%s'"),3032 name);30333034/* verify that the result matches */3035hash_sha1_file(img->buf, img->len, blob_type, sha1);3036if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3037returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3038 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3039}30403041return0;3042}30433044static intapply_fragments(struct image *img,struct patch *patch)3045{3046struct fragment *frag = patch->fragments;3047const char*name = patch->old_name ? patch->old_name : patch->new_name;3048unsigned ws_rule = patch->ws_rule;3049unsigned inaccurate_eof = patch->inaccurate_eof;3050int nth =0;30513052if(patch->is_binary)3053returnapply_binary(img, patch);30543055while(frag) {3056 nth++;3057if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {3058error(_("patch failed:%s:%ld"), name, frag->oldpos);3059if(!apply_with_reject)3060return-1;3061 frag->rejected =1;3062}3063 frag = frag->next;3064}3065return0;3066}30673068static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3069{3070if(S_ISGITLINK(mode)) {3071strbuf_grow(buf,100);3072strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3073}else{3074enum object_type type;3075unsigned long sz;3076char*result;30773078 result =read_sha1_file(sha1, &type, &sz);3079if(!result)3080return-1;3081/* XXX read_sha1_file NUL-terminates */3082strbuf_attach(buf, result, sz, sz +1);3083}3084return0;3085}30863087static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3088{3089if(!ce)3090return0;3091returnread_blob_object(buf, ce->sha1, ce->ce_mode);3092}30933094static struct patch *in_fn_table(const char*name)3095{3096struct string_list_item *item;30973098if(name == NULL)3099return NULL;31003101 item =string_list_lookup(&fn_table, name);3102if(item != NULL)3103return(struct patch *)item->util;31043105return NULL;3106}31073108/*3109 * item->util in the filename table records the status of the path.3110 * Usually it points at a patch (whose result records the contents3111 * of it after applying it), but it could be PATH_WAS_DELETED for a3112 * path that a previously applied patch has already removed, or3113 * PATH_TO_BE_DELETED for a path that a later patch would remove.3114 *3115 * The latter is needed to deal with a case where two paths A and B3116 * are swapped by first renaming A to B and then renaming B to A;3117 * moving A to B should not be prevented due to presence of B as we3118 * will remove it in a later patch.3119 */3120#define PATH_TO_BE_DELETED ((struct patch *) -2)3121#define PATH_WAS_DELETED ((struct patch *) -1)31223123static intto_be_deleted(struct patch *patch)3124{3125return patch == PATH_TO_BE_DELETED;3126}31273128static intwas_deleted(struct patch *patch)3129{3130return patch == PATH_WAS_DELETED;3131}31323133static voidadd_to_fn_table(struct patch *patch)3134{3135struct string_list_item *item;31363137/*3138 * Always add new_name unless patch is a deletion3139 * This should cover the cases for normal diffs,3140 * file creations and copies3141 */3142if(patch->new_name != NULL) {3143 item =string_list_insert(&fn_table, patch->new_name);3144 item->util = patch;3145}31463147/*3148 * store a failure on rename/deletion cases because3149 * later chunks shouldn't patch old names3150 */3151if((patch->new_name == NULL) || (patch->is_rename)) {3152 item =string_list_insert(&fn_table, patch->old_name);3153 item->util = PATH_WAS_DELETED;3154}3155}31563157static voidprepare_fn_table(struct patch *patch)3158{3159/*3160 * store information about incoming file deletion3161 */3162while(patch) {3163if((patch->new_name == NULL) || (patch->is_rename)) {3164struct string_list_item *item;3165 item =string_list_insert(&fn_table, patch->old_name);3166 item->util = PATH_TO_BE_DELETED;3167}3168 patch = patch->next;3169}3170}31713172static intcheckout_target(struct index_state *istate,3173struct cache_entry *ce,struct stat *st)3174{3175struct checkout costate;31763177memset(&costate,0,sizeof(costate));3178 costate.base_dir ="";3179 costate.refresh_cache =1;3180 costate.istate = istate;3181if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3182returnerror(_("cannot checkout%s"), ce->name);3183return0;3184}31853186static struct patch *previous_patch(struct patch *patch,int*gone)3187{3188struct patch *previous;31893190*gone =0;3191if(patch->is_copy || patch->is_rename)3192return NULL;/* "git" patches do not depend on the order */31933194 previous =in_fn_table(patch->old_name);3195if(!previous)3196return NULL;31973198if(to_be_deleted(previous))3199return NULL;/* the deletion hasn't happened yet */32003201if(was_deleted(previous))3202*gone =1;32033204return previous;3205}32063207static intverify_index_match(const struct cache_entry *ce,struct stat *st)3208{3209if(S_ISGITLINK(ce->ce_mode)) {3210if(!S_ISDIR(st->st_mode))3211return-1;3212return0;3213}3214returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3215}32163217#define SUBMODULE_PATCH_WITHOUT_INDEX 132183219static intload_patch_target(struct strbuf *buf,3220const struct cache_entry *ce,3221struct stat *st,3222const char*name,3223unsigned expected_mode)3224{3225if(cached || check_index) {3226if(read_file_or_gitlink(ce, buf))3227returnerror(_("read of%sfailed"), name);3228}else if(name) {3229if(S_ISGITLINK(expected_mode)) {3230if(ce)3231returnread_file_or_gitlink(ce, buf);3232else3233return SUBMODULE_PATCH_WITHOUT_INDEX;3234}else if(has_symlink_leading_path(name,strlen(name))) {3235returnerror(_("reading from '%s' beyond a symbolic link"), name);3236}else{3237if(read_old_data(st, name, buf))3238returnerror(_("read of%sfailed"), name);3239}3240}3241return0;3242}32433244/*3245 * We are about to apply "patch"; populate the "image" with the3246 * current version we have, from the working tree or from the index,3247 * depending on the situation e.g. --cached/--index. If we are3248 * applying a non-git patch that incrementally updates the tree,3249 * we read from the result of a previous diff.3250 */3251static intload_preimage(struct image *image,3252struct patch *patch,struct stat *st,3253const struct cache_entry *ce)3254{3255struct strbuf buf = STRBUF_INIT;3256size_t len;3257char*img;3258struct patch *previous;3259int status;32603261 previous =previous_patch(patch, &status);3262if(status)3263returnerror(_("path%shas been renamed/deleted"),3264 patch->old_name);3265if(previous) {3266/* We have a patched copy in memory; use that. */3267strbuf_add(&buf, previous->result, previous->resultsize);3268}else{3269 status =load_patch_target(&buf, ce, st,3270 patch->old_name, patch->old_mode);3271if(status <0)3272return status;3273else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3274/*3275 * There is no way to apply subproject3276 * patch without looking at the index.3277 * NEEDSWORK: shouldn't this be flagged3278 * as an error???3279 */3280free_fragment_list(patch->fragments);3281 patch->fragments = NULL;3282}else if(status) {3283returnerror(_("read of%sfailed"), patch->old_name);3284}3285}32863287 img =strbuf_detach(&buf, &len);3288prepare_image(image, img, len, !patch->is_binary);3289return0;3290}32913292static intthree_way_merge(struct image *image,3293char*path,3294const unsigned char*base,3295const unsigned char*ours,3296const unsigned char*theirs)3297{3298 mmfile_t base_file, our_file, their_file;3299 mmbuffer_t result = { NULL };3300int status;33013302read_mmblob(&base_file, base);3303read_mmblob(&our_file, ours);3304read_mmblob(&their_file, theirs);3305 status =ll_merge(&result, path,3306&base_file,"base",3307&our_file,"ours",3308&their_file,"theirs", NULL);3309free(base_file.ptr);3310free(our_file.ptr);3311free(their_file.ptr);3312if(status <0|| !result.ptr) {3313free(result.ptr);3314return-1;3315}3316clear_image(image);3317 image->buf = result.ptr;3318 image->len = result.size;33193320return status;3321}33223323/*3324 * When directly falling back to add/add three-way merge, we read from3325 * the current contents of the new_name. In no cases other than that3326 * this function will be called.3327 */3328static intload_current(struct image *image,struct patch *patch)3329{3330struct strbuf buf = STRBUF_INIT;3331int status, pos;3332size_t len;3333char*img;3334struct stat st;3335struct cache_entry *ce;3336char*name = patch->new_name;3337unsigned mode = patch->new_mode;33383339if(!patch->is_new)3340die("BUG: patch to%sis not a creation", patch->old_name);33413342 pos =cache_name_pos(name,strlen(name));3343if(pos <0)3344returnerror(_("%s: does not exist in index"), name);3345 ce = active_cache[pos];3346if(lstat(name, &st)) {3347if(errno != ENOENT)3348returnerror(_("%s:%s"), name,strerror(errno));3349if(checkout_target(&the_index, ce, &st))3350return-1;3351}3352if(verify_index_match(ce, &st))3353returnerror(_("%s: does not match index"), name);33543355 status =load_patch_target(&buf, ce, &st, name, mode);3356if(status <0)3357return status;3358else if(status)3359return-1;3360 img =strbuf_detach(&buf, &len);3361prepare_image(image, img, len, !patch->is_binary);3362return0;3363}33643365static inttry_threeway(struct image *image,struct patch *patch,3366struct stat *st,const struct cache_entry *ce)3367{3368unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3369struct strbuf buf = STRBUF_INIT;3370size_t len;3371int status;3372char*img;3373struct image tmp_image;33743375/* No point falling back to 3-way merge in these cases */3376if(patch->is_delete ||3377S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3378return-1;33793380/* Preimage the patch was prepared for */3381if(patch->is_new)3382write_sha1_file("",0, blob_type, pre_sha1);3383else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3384read_blob_object(&buf, pre_sha1, patch->old_mode))3385returnerror("repository lacks the necessary blob to fall back on 3-way merge.");33863387fprintf(stderr,"Falling back to three-way merge...\n");33883389 img =strbuf_detach(&buf, &len);3390prepare_image(&tmp_image, img, len,1);3391/* Apply the patch to get the post image */3392if(apply_fragments(&tmp_image, patch) <0) {3393clear_image(&tmp_image);3394return-1;3395}3396/* post_sha1[] is theirs */3397write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3398clear_image(&tmp_image);33993400/* our_sha1[] is ours */3401if(patch->is_new) {3402if(load_current(&tmp_image, patch))3403returnerror("cannot read the current contents of '%s'",3404 patch->new_name);3405}else{3406if(load_preimage(&tmp_image, patch, st, ce))3407returnerror("cannot read the current contents of '%s'",3408 patch->old_name);3409}3410write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3411clear_image(&tmp_image);34123413/* in-core three-way merge between post and our using pre as base */3414 status =three_way_merge(image, patch->new_name,3415 pre_sha1, our_sha1, post_sha1);3416if(status <0) {3417fprintf(stderr,"Failed to fall back on three-way merge...\n");3418return status;3419}34203421if(status) {3422 patch->conflicted_threeway =1;3423if(patch->is_new)3424hashclr(patch->threeway_stage[0]);3425else3426hashcpy(patch->threeway_stage[0], pre_sha1);3427hashcpy(patch->threeway_stage[1], our_sha1);3428hashcpy(patch->threeway_stage[2], post_sha1);3429fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3430}else{3431fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3432}3433return0;3434}34353436static intapply_data(struct patch *patch,struct stat *st,const struct cache_entry *ce)3437{3438struct image image;34393440if(load_preimage(&image, patch, st, ce) <0)3441return-1;34423443if(patch->direct_to_threeway ||3444apply_fragments(&image, patch) <0) {3445/* Note: with --reject, apply_fragments() returns 0 */3446if(!threeway ||try_threeway(&image, patch, st, ce) <0)3447return-1;3448}3449 patch->result = image.buf;3450 patch->resultsize = image.len;3451add_to_fn_table(patch);3452free(image.line_allocated);34533454if(0< patch->is_delete && patch->resultsize)3455returnerror(_("removal patch leaves file contents"));34563457return0;3458}34593460/*3461 * If "patch" that we are looking at modifies or deletes what we have,3462 * we would want it not to lose any local modification we have, either3463 * in the working tree or in the index.3464 *3465 * This also decides if a non-git patch is a creation patch or a3466 * modification to an existing empty file. We do not check the state3467 * of the current tree for a creation patch in this function; the caller3468 * check_patch() separately makes sure (and errors out otherwise) that3469 * the path the patch creates does not exist in the current tree.3470 */3471static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)3472{3473const char*old_name = patch->old_name;3474struct patch *previous = NULL;3475int stat_ret =0, status;3476unsigned st_mode =0;34773478if(!old_name)3479return0;34803481assert(patch->is_new <=0);3482 previous =previous_patch(patch, &status);34833484if(status)3485returnerror(_("path%shas been renamed/deleted"), old_name);3486if(previous) {3487 st_mode = previous->new_mode;3488}else if(!cached) {3489 stat_ret =lstat(old_name, st);3490if(stat_ret && errno != ENOENT)3491returnerror(_("%s:%s"), old_name,strerror(errno));3492}34933494if(check_index && !previous) {3495int pos =cache_name_pos(old_name,strlen(old_name));3496if(pos <0) {3497if(patch->is_new <0)3498goto is_new;3499returnerror(_("%s: does not exist in index"), old_name);3500}3501*ce = active_cache[pos];3502if(stat_ret <0) {3503if(checkout_target(&the_index, *ce, st))3504return-1;3505}3506if(!cached &&verify_index_match(*ce, st))3507returnerror(_("%s: does not match index"), old_name);3508if(cached)3509 st_mode = (*ce)->ce_mode;3510}else if(stat_ret <0) {3511if(patch->is_new <0)3512goto is_new;3513returnerror(_("%s:%s"), old_name,strerror(errno));3514}35153516if(!cached && !previous)3517 st_mode =ce_mode_from_stat(*ce, st->st_mode);35183519if(patch->is_new <0)3520 patch->is_new =0;3521if(!patch->old_mode)3522 patch->old_mode = st_mode;3523if((st_mode ^ patch->old_mode) & S_IFMT)3524returnerror(_("%s: wrong type"), old_name);3525if(st_mode != patch->old_mode)3526warning(_("%shas type%o, expected%o"),3527 old_name, st_mode, patch->old_mode);3528if(!patch->new_mode && !patch->is_delete)3529 patch->new_mode = st_mode;3530return0;35313532 is_new:3533 patch->is_new =1;3534 patch->is_delete =0;3535free(patch->old_name);3536 patch->old_name = NULL;3537return0;3538}353935403541#define EXISTS_IN_INDEX 13542#define EXISTS_IN_WORKTREE 235433544static intcheck_to_create(const char*new_name,int ok_if_exists)3545{3546struct stat nst;35473548if(check_index &&3549cache_name_pos(new_name,strlen(new_name)) >=0&&3550!ok_if_exists)3551return EXISTS_IN_INDEX;3552if(cached)3553return0;35543555if(!lstat(new_name, &nst)) {3556if(S_ISDIR(nst.st_mode) || ok_if_exists)3557return0;3558/*3559 * A leading component of new_name might be a symlink3560 * that is going to be removed with this patch, but3561 * still pointing at somewhere that has the path.3562 * In such a case, path "new_name" does not exist as3563 * far as git is concerned.3564 */3565if(has_symlink_leading_path(new_name,strlen(new_name)))3566return0;35673568return EXISTS_IN_WORKTREE;3569}else if((errno != ENOENT) && (errno != ENOTDIR)) {3570returnerror("%s:%s", new_name,strerror(errno));3571}3572return0;3573}35743575/*3576 * We need to keep track of how symlinks in the preimage are3577 * manipulated by the patches. A patch to add a/b/c where a/b3578 * is a symlink should not be allowed to affect the directory3579 * the symlink points at, but if the same patch removes a/b,3580 * it is perfectly fine, as the patch removes a/b to make room3581 * to create a directory a/b so that a/b/c can be created.3582 */3583static struct string_list symlink_changes;3584#define SYMLINK_GOES_AWAY 013585#define SYMLINK_IN_RESULT 0235863587static uintptr_tregister_symlink_changes(const char*path,uintptr_t what)3588{3589struct string_list_item *ent;35903591 ent =string_list_lookup(&symlink_changes, path);3592if(!ent) {3593 ent =string_list_insert(&symlink_changes, path);3594 ent->util = (void*)0;3595}3596 ent->util = (void*)(what | ((uintptr_t)ent->util));3597return(uintptr_t)ent->util;3598}35993600static uintptr_tcheck_symlink_changes(const char*path)3601{3602struct string_list_item *ent;36033604 ent =string_list_lookup(&symlink_changes, path);3605if(!ent)3606return0;3607return(uintptr_t)ent->util;3608}36093610static voidprepare_symlink_changes(struct patch *patch)3611{3612for( ; patch; patch = patch->next) {3613if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3614(patch->is_rename || patch->is_delete))3615/* the symlink at patch->old_name is removed */3616register_symlink_changes(patch->old_name, SYMLINK_GOES_AWAY);36173618if(patch->new_name &&S_ISLNK(patch->new_mode))3619/* the symlink at patch->new_name is created or remains */3620register_symlink_changes(patch->new_name, SYMLINK_IN_RESULT);3621}3622}36233624static intpath_is_beyond_symlink_1(struct strbuf *name)3625{3626do{3627unsigned int change;36283629while(--name->len && name->buf[name->len] !='/')3630;/* scan backwards */3631if(!name->len)3632break;3633 name->buf[name->len] ='\0';3634 change =check_symlink_changes(name->buf);3635if(change & SYMLINK_IN_RESULT)3636return1;3637if(change & SYMLINK_GOES_AWAY)3638/*3639 * This cannot be "return 0", because we may3640 * see a new one created at a higher level.3641 */3642continue;36433644/* otherwise, check the preimage */3645if(check_index) {3646struct cache_entry *ce;36473648 ce =cache_file_exists(name->buf, name->len, ignore_case);3649if(ce &&S_ISLNK(ce->ce_mode))3650return1;3651}else{3652struct stat st;3653if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3654return1;3655}3656}while(1);3657return0;3658}36593660static intpath_is_beyond_symlink(const char*name_)3661{3662int ret;3663struct strbuf name = STRBUF_INIT;36643665assert(*name_ !='\0');3666strbuf_addstr(&name, name_);3667 ret =path_is_beyond_symlink_1(&name);3668strbuf_release(&name);36693670return ret;3671}36723673static voiddie_on_unsafe_path(struct patch *patch)3674{3675const char*old_name = NULL;3676const char*new_name = NULL;3677if(patch->is_delete)3678 old_name = patch->old_name;3679else if(!patch->is_new && !patch->is_copy)3680 old_name = patch->old_name;3681if(!patch->is_delete)3682 new_name = patch->new_name;36833684if(old_name && !verify_path(old_name))3685die(_("invalid path '%s'"), old_name);3686if(new_name && !verify_path(new_name))3687die(_("invalid path '%s'"), new_name);3688}36893690/*3691 * Check and apply the patch in-core; leave the result in patch->result3692 * for the caller to write it out to the final destination.3693 */3694static intcheck_patch(struct patch *patch)3695{3696struct stat st;3697const char*old_name = patch->old_name;3698const char*new_name = patch->new_name;3699const char*name = old_name ? old_name : new_name;3700struct cache_entry *ce = NULL;3701struct patch *tpatch;3702int ok_if_exists;3703int status;37043705 patch->rejected =1;/* we will drop this after we succeed */37063707 status =check_preimage(patch, &ce, &st);3708if(status)3709return status;3710 old_name = patch->old_name;37113712/*3713 * A type-change diff is always split into a patch to delete3714 * old, immediately followed by a patch to create new (see3715 * diff.c::run_diff()); in such a case it is Ok that the entry3716 * to be deleted by the previous patch is still in the working3717 * tree and in the index.3718 *3719 * A patch to swap-rename between A and B would first rename A3720 * to B and then rename B to A. While applying the first one,3721 * the presence of B should not stop A from getting renamed to3722 * B; ask to_be_deleted() about the later rename. Removal of3723 * B and rename from A to B is handled the same way by asking3724 * was_deleted().3725 */3726if((tpatch =in_fn_table(new_name)) &&3727(was_deleted(tpatch) ||to_be_deleted(tpatch)))3728 ok_if_exists =1;3729else3730 ok_if_exists =0;37313732if(new_name &&3733((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3734int err =check_to_create(new_name, ok_if_exists);37353736if(err && threeway) {3737 patch->direct_to_threeway =1;3738}else switch(err) {3739case0:3740break;/* happy */3741case EXISTS_IN_INDEX:3742returnerror(_("%s: already exists in index"), new_name);3743break;3744case EXISTS_IN_WORKTREE:3745returnerror(_("%s: already exists in working directory"),3746 new_name);3747default:3748return err;3749}37503751if(!patch->new_mode) {3752if(0< patch->is_new)3753 patch->new_mode = S_IFREG |0644;3754else3755 patch->new_mode = patch->old_mode;3756}3757}37583759if(new_name && old_name) {3760int same = !strcmp(old_name, new_name);3761if(!patch->new_mode)3762 patch->new_mode = patch->old_mode;3763if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3764if(same)3765returnerror(_("new mode (%o) of%sdoes not "3766"match old mode (%o)"),3767 patch->new_mode, new_name,3768 patch->old_mode);3769else3770returnerror(_("new mode (%o) of%sdoes not "3771"match old mode (%o) of%s"),3772 patch->new_mode, new_name,3773 patch->old_mode, old_name);3774}3775}37763777if(!unsafe_paths)3778die_on_unsafe_path(patch);37793780/*3781 * An attempt to read from or delete a path that is beyond a3782 * symbolic link will be prevented by load_patch_target() that3783 * is called at the beginning of apply_data() so we do not3784 * have to worry about a patch marked with "is_delete" bit3785 * here. We however need to make sure that the patch result3786 * is not deposited to a path that is beyond a symbolic link3787 * here.3788 */3789if(!patch->is_delete &&path_is_beyond_symlink(patch->new_name))3790returnerror(_("affected file '%s' is beyond a symbolic link"),3791 patch->new_name);37923793if(apply_data(patch, &st, ce) <0)3794returnerror(_("%s: patch does not apply"), name);3795 patch->rejected =0;3796return0;3797}37983799static intcheck_patch_list(struct patch *patch)3800{3801int err =0;38023803prepare_symlink_changes(patch);3804prepare_fn_table(patch);3805while(patch) {3806if(apply_verbosely)3807say_patch_name(stderr,3808_("Checking patch%s..."), patch);3809 err |=check_patch(patch);3810 patch = patch->next;3811}3812return err;3813}38143815/* This function tries to read the sha1 from the current index */3816static intget_current_sha1(const char*path,unsigned char*sha1)3817{3818int pos;38193820if(read_cache() <0)3821return-1;3822 pos =cache_name_pos(path,strlen(path));3823if(pos <0)3824return-1;3825hashcpy(sha1, active_cache[pos]->sha1);3826return0;3827}38283829static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3830{3831/*3832 * A usable gitlink patch has only one fragment (hunk) that looks like:3833 * @@ -1 +1 @@3834 * -Subproject commit <old sha1>3835 * +Subproject commit <new sha1>3836 * or3837 * @@ -1 +0,0 @@3838 * -Subproject commit <old sha1>3839 * for a removal patch.3840 */3841struct fragment *hunk = p->fragments;3842static const char heading[] ="-Subproject commit ";3843char*preimage;38443845if(/* does the patch have only one hunk? */3846 hunk && !hunk->next &&3847/* is its preimage one line? */3848 hunk->oldpos ==1&& hunk->oldlines ==1&&3849/* does preimage begin with the heading? */3850(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3851starts_with(++preimage, heading) &&3852/* does it record full SHA-1? */3853!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3854 preimage[sizeof(heading) +40-1] =='\n'&&3855/* does the abbreviated name on the index line agree with it? */3856starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3857return0;/* it all looks fine */38583859/* we may have full object name on the index line */3860returnget_sha1_hex(p->old_sha1_prefix, sha1);3861}38623863/* Build an index that contains the just the files needed for a 3way merge */3864static voidbuild_fake_ancestor(struct patch *list,const char*filename)3865{3866struct patch *patch;3867struct index_state result = { NULL };3868static struct lock_file lock;38693870/* Once we start supporting the reverse patch, it may be3871 * worth showing the new sha1 prefix, but until then...3872 */3873for(patch = list; patch; patch = patch->next) {3874unsigned char sha1[20];3875struct cache_entry *ce;3876const char*name;38773878 name = patch->old_name ? patch->old_name : patch->new_name;3879if(0< patch->is_new)3880continue;38813882if(S_ISGITLINK(patch->old_mode)) {3883if(!preimage_sha1_in_gitlink_patch(patch, sha1))3884;/* ok, the textual part looks sane */3885else3886die("sha1 information is lacking or useless for submodule%s",3887 name);3888}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {3889;/* ok */3890}else if(!patch->lines_added && !patch->lines_deleted) {3891/* mode-only change: update the current */3892if(get_current_sha1(patch->old_name, sha1))3893die("mode change for%s, which is not "3894"in current HEAD", name);3895}else3896die("sha1 information is lacking or useless "3897"(%s).", name);38983899 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);3900if(!ce)3901die(_("make_cache_entry failed for path '%s'"), name);3902if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3903die("Could not add%sto temporary index", name);3904}39053906hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);3907if(write_locked_index(&result, &lock, COMMIT_LOCK))3908die("Could not write temporary index to%s", filename);39093910discard_index(&result);3911}39123913static voidstat_patch_list(struct patch *patch)3914{3915int files, adds, dels;39163917for(files = adds = dels =0; patch ; patch = patch->next) {3918 files++;3919 adds += patch->lines_added;3920 dels += patch->lines_deleted;3921show_stats(patch);3922}39233924print_stat_summary(stdout, files, adds, dels);3925}39263927static voidnumstat_patch_list(struct patch *patch)3928{3929for( ; patch; patch = patch->next) {3930const char*name;3931 name = patch->new_name ? patch->new_name : patch->old_name;3932if(patch->is_binary)3933printf("-\t-\t");3934else3935printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3936write_name_quoted(name, stdout, line_termination);3937}3938}39393940static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3941{3942if(mode)3943printf("%smode%06o%s\n", newdelete, mode, name);3944else3945printf("%s %s\n", newdelete, name);3946}39473948static voidshow_mode_change(struct patch *p,int show_name)3949{3950if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3951if(show_name)3952printf(" mode change%06o =>%06o%s\n",3953 p->old_mode, p->new_mode, p->new_name);3954else3955printf(" mode change%06o =>%06o\n",3956 p->old_mode, p->new_mode);3957}3958}39593960static voidshow_rename_copy(struct patch *p)3961{3962const char*renamecopy = p->is_rename ?"rename":"copy";3963const char*old, *new;39643965/* Find common prefix */3966 old = p->old_name;3967new= p->new_name;3968while(1) {3969const char*slash_old, *slash_new;3970 slash_old =strchr(old,'/');3971 slash_new =strchr(new,'/');3972if(!slash_old ||3973!slash_new ||3974 slash_old - old != slash_new -new||3975memcmp(old,new, slash_new -new))3976break;3977 old = slash_old +1;3978new= slash_new +1;3979}3980/* p->old_name thru old is the common prefix, and old and new3981 * through the end of names are renames3982 */3983if(old != p->old_name)3984printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,3985(int)(old - p->old_name), p->old_name,3986 old,new, p->score);3987else3988printf("%s %s=>%s(%d%%)\n", renamecopy,3989 p->old_name, p->new_name, p->score);3990show_mode_change(p,0);3991}39923993static voidsummary_patch_list(struct patch *patch)3994{3995struct patch *p;39963997for(p = patch; p; p = p->next) {3998if(p->is_new)3999show_file_mode_name("create", p->new_mode, p->new_name);4000else if(p->is_delete)4001show_file_mode_name("delete", p->old_mode, p->old_name);4002else{4003if(p->is_rename || p->is_copy)4004show_rename_copy(p);4005else{4006if(p->score) {4007printf(" rewrite%s(%d%%)\n",4008 p->new_name, p->score);4009show_mode_change(p,0);4010}4011else4012show_mode_change(p,1);4013}4014}4015}4016}40174018static voidpatch_stats(struct patch *patch)4019{4020int lines = patch->lines_added + patch->lines_deleted;40214022if(lines > max_change)4023 max_change = lines;4024if(patch->old_name) {4025int len =quote_c_style(patch->old_name, NULL, NULL,0);4026if(!len)4027 len =strlen(patch->old_name);4028if(len > max_len)4029 max_len = len;4030}4031if(patch->new_name) {4032int len =quote_c_style(patch->new_name, NULL, NULL,0);4033if(!len)4034 len =strlen(patch->new_name);4035if(len > max_len)4036 max_len = len;4037}4038}40394040static voidremove_file(struct patch *patch,int rmdir_empty)4041{4042if(update_index) {4043if(remove_file_from_cache(patch->old_name) <0)4044die(_("unable to remove%sfrom index"), patch->old_name);4045}4046if(!cached) {4047if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4048remove_path(patch->old_name);4049}4050}4051}40524053static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)4054{4055struct stat st;4056struct cache_entry *ce;4057int namelen =strlen(path);4058unsigned ce_size =cache_entry_size(namelen);40594060if(!update_index)4061return;40624063 ce =xcalloc(1, ce_size);4064memcpy(ce->name, path, namelen);4065 ce->ce_mode =create_ce_mode(mode);4066 ce->ce_flags =create_ce_flags(0);4067 ce->ce_namelen = namelen;4068if(S_ISGITLINK(mode)) {4069const char*s;40704071if(!skip_prefix(buf,"Subproject commit ", &s) ||4072get_sha1_hex(s, ce->sha1))4073die(_("corrupt patch for submodule%s"), path);4074}else{4075if(!cached) {4076if(lstat(path, &st) <0)4077die_errno(_("unable to stat newly created file '%s'"),4078 path);4079fill_stat_cache_info(ce, &st);4080}4081if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4082die(_("unable to create backing store for newly created file%s"), path);4083}4084if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4085die(_("unable to add cache entry for%s"), path);4086}40874088static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4089{4090int fd;4091struct strbuf nbuf = STRBUF_INIT;40924093if(S_ISGITLINK(mode)) {4094struct stat st;4095if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4096return0;4097returnmkdir(path,0777);4098}40994100if(has_symlinks &&S_ISLNK(mode))4101/* Although buf:size is counted string, it also is NUL4102 * terminated.4103 */4104returnsymlink(buf, path);41054106 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4107if(fd <0)4108return-1;41094110if(convert_to_working_tree(path, buf, size, &nbuf)) {4111 size = nbuf.len;4112 buf = nbuf.buf;4113}4114write_or_die(fd, buf, size);4115strbuf_release(&nbuf);41164117if(close(fd) <0)4118die_errno(_("closing file '%s'"), path);4119return0;4120}41214122/*4123 * We optimistically assume that the directories exist,4124 * which is true 99% of the time anyway. If they don't,4125 * we create them and try again.4126 */4127static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)4128{4129if(cached)4130return;4131if(!try_create_file(path, mode, buf, size))4132return;41334134if(errno == ENOENT) {4135if(safe_create_leading_directories(path))4136return;4137if(!try_create_file(path, mode, buf, size))4138return;4139}41404141if(errno == EEXIST || errno == EACCES) {4142/* We may be trying to create a file where a directory4143 * used to be.4144 */4145struct stat st;4146if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4147 errno = EEXIST;4148}41494150if(errno == EEXIST) {4151unsigned int nr =getpid();41524153for(;;) {4154char newpath[PATH_MAX];4155mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4156if(!try_create_file(newpath, mode, buf, size)) {4157if(!rename(newpath, path))4158return;4159unlink_or_warn(newpath);4160break;4161}4162if(errno != EEXIST)4163break;4164++nr;4165}4166}4167die_errno(_("unable to write file '%s' mode%o"), path, mode);4168}41694170static voidadd_conflicted_stages_file(struct patch *patch)4171{4172int stage, namelen;4173unsigned ce_size, mode;4174struct cache_entry *ce;41754176if(!update_index)4177return;4178 namelen =strlen(patch->new_name);4179 ce_size =cache_entry_size(namelen);4180 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);41814182remove_file_from_cache(patch->new_name);4183for(stage =1; stage <4; stage++) {4184if(is_null_sha1(patch->threeway_stage[stage -1]))4185continue;4186 ce =xcalloc(1, ce_size);4187memcpy(ce->name, patch->new_name, namelen);4188 ce->ce_mode =create_ce_mode(mode);4189 ce->ce_flags =create_ce_flags(stage);4190 ce->ce_namelen = namelen;4191hashcpy(ce->sha1, patch->threeway_stage[stage -1]);4192if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4193die(_("unable to add cache entry for%s"), patch->new_name);4194}4195}41964197static voidcreate_file(struct patch *patch)4198{4199char*path = patch->new_name;4200unsigned mode = patch->new_mode;4201unsigned long size = patch->resultsize;4202char*buf = patch->result;42034204if(!mode)4205 mode = S_IFREG |0644;4206create_one_file(path, mode, buf, size);42074208if(patch->conflicted_threeway)4209add_conflicted_stages_file(patch);4210else4211add_index_file(path, mode, buf, size);4212}42134214/* phase zero is to remove, phase one is to create */4215static voidwrite_out_one_result(struct patch *patch,int phase)4216{4217if(patch->is_delete >0) {4218if(phase ==0)4219remove_file(patch,1);4220return;4221}4222if(patch->is_new >0|| patch->is_copy) {4223if(phase ==1)4224create_file(patch);4225return;4226}4227/*4228 * Rename or modification boils down to the same4229 * thing: remove the old, write the new4230 */4231if(phase ==0)4232remove_file(patch, patch->is_rename);4233if(phase ==1)4234create_file(patch);4235}42364237static intwrite_out_one_reject(struct patch *patch)4238{4239FILE*rej;4240char namebuf[PATH_MAX];4241struct fragment *frag;4242int cnt =0;4243struct strbuf sb = STRBUF_INIT;42444245for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4246if(!frag->rejected)4247continue;4248 cnt++;4249}42504251if(!cnt) {4252if(apply_verbosely)4253say_patch_name(stderr,4254_("Applied patch%scleanly."), patch);4255return0;4256}42574258/* This should not happen, because a removal patch that leaves4259 * contents are marked "rejected" at the patch level.4260 */4261if(!patch->new_name)4262die(_("internal error"));42634264/* Say this even without --verbose */4265strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4266"Applying patch %%swith%drejects...",4267 cnt),4268 cnt);4269say_patch_name(stderr, sb.buf, patch);4270strbuf_release(&sb);42714272 cnt =strlen(patch->new_name);4273if(ARRAY_SIZE(namebuf) <= cnt +5) {4274 cnt =ARRAY_SIZE(namebuf) -5;4275warning(_("truncating .rej filename to %.*s.rej"),4276 cnt -1, patch->new_name);4277}4278memcpy(namebuf, patch->new_name, cnt);4279memcpy(namebuf + cnt,".rej",5);42804281 rej =fopen(namebuf,"w");4282if(!rej)4283returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));42844285/* Normal git tools never deal with .rej, so do not pretend4286 * this is a git patch by saying --git or giving extended4287 * headers. While at it, maybe please "kompare" that wants4288 * the trailing TAB and some garbage at the end of line ;-).4289 */4290fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4291 patch->new_name, patch->new_name);4292for(cnt =1, frag = patch->fragments;4293 frag;4294 cnt++, frag = frag->next) {4295if(!frag->rejected) {4296fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4297continue;4298}4299fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4300fprintf(rej,"%.*s", frag->size, frag->patch);4301if(frag->patch[frag->size-1] !='\n')4302fputc('\n', rej);4303}4304fclose(rej);4305return-1;4306}43074308static intwrite_out_results(struct patch *list)4309{4310int phase;4311int errs =0;4312struct patch *l;4313struct string_list cpath = STRING_LIST_INIT_DUP;43144315for(phase =0; phase <2; phase++) {4316 l = list;4317while(l) {4318if(l->rejected)4319 errs =1;4320else{4321write_out_one_result(l, phase);4322if(phase ==1) {4323if(write_out_one_reject(l))4324 errs =1;4325if(l->conflicted_threeway) {4326string_list_append(&cpath, l->new_name);4327 errs =1;4328}4329}4330}4331 l = l->next;4332}4333}43344335if(cpath.nr) {4336struct string_list_item *item;43374338string_list_sort(&cpath);4339for_each_string_list_item(item, &cpath)4340fprintf(stderr,"U%s\n", item->string);4341string_list_clear(&cpath,0);43424343rerere(0);4344}43454346return errs;4347}43484349static struct lock_file lock_file;43504351#define INACCURATE_EOF (1<<0)4352#define RECOUNT (1<<1)43534354static intapply_patch(int fd,const char*filename,int options)4355{4356size_t offset;4357struct strbuf buf = STRBUF_INIT;/* owns the patch text */4358struct patch *list = NULL, **listp = &list;4359int skipped_patch =0;43604361 patch_input_file = filename;4362read_patch_file(&buf, fd);4363 offset =0;4364while(offset < buf.len) {4365struct patch *patch;4366int nr;43674368 patch =xcalloc(1,sizeof(*patch));4369 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4370 patch->recount = !!(options & RECOUNT);4371 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);4372if(nr <0)4373break;4374if(apply_in_reverse)4375reverse_patches(patch);4376if(use_patch(patch)) {4377patch_stats(patch);4378*listp = patch;4379 listp = &patch->next;4380}4381else{4382free_patch(patch);4383 skipped_patch++;4384}4385 offset += nr;4386}43874388if(!list && !skipped_patch)4389die(_("unrecognized input"));43904391if(whitespace_error && (ws_error_action == die_on_ws_error))4392 apply =0;43934394 update_index = check_index && apply;4395if(update_index && newfd <0)4396 newfd =hold_locked_index(&lock_file,1);43974398if(check_index) {4399if(read_cache() <0)4400die(_("unable to read index file"));4401}44024403if((check || apply) &&4404check_patch_list(list) <0&&4405!apply_with_reject)4406exit(1);44074408if(apply &&write_out_results(list)) {4409if(apply_with_reject)4410exit(1);4411/* with --3way, we still need to write the index out */4412return1;4413}44144415if(fake_ancestor)4416build_fake_ancestor(list, fake_ancestor);44174418if(diffstat)4419stat_patch_list(list);44204421if(numstat)4422numstat_patch_list(list);44234424if(summary)4425summary_patch_list(list);44264427free_patch_list(list);4428strbuf_release(&buf);4429string_list_clear(&fn_table,0);4430return0;4431}44324433static voidgit_apply_config(void)4434{4435git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4436git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4437git_config(git_default_config, NULL);4438}44394440static intoption_parse_exclude(const struct option *opt,4441const char*arg,int unset)4442{4443add_name_limit(arg,1);4444return0;4445}44464447static intoption_parse_include(const struct option *opt,4448const char*arg,int unset)4449{4450add_name_limit(arg,0);4451 has_include =1;4452return0;4453}44544455static intoption_parse_p(const struct option *opt,4456const char*arg,int unset)4457{4458 p_value =atoi(arg);4459 p_value_known =1;4460return0;4461}44624463static intoption_parse_z(const struct option *opt,4464const char*arg,int unset)4465{4466if(unset)4467 line_termination ='\n';4468else4469 line_termination =0;4470return0;4471}44724473static intoption_parse_space_change(const struct option *opt,4474const char*arg,int unset)4475{4476if(unset)4477 ws_ignore_action = ignore_ws_none;4478else4479 ws_ignore_action = ignore_ws_change;4480return0;4481}44824483static intoption_parse_whitespace(const struct option *opt,4484const char*arg,int unset)4485{4486const char**whitespace_option = opt->value;44874488*whitespace_option = arg;4489parse_whitespace_option(arg);4490return0;4491}44924493static intoption_parse_directory(const struct option *opt,4494const char*arg,int unset)4495{4496 root_len =strlen(arg);4497if(root_len && arg[root_len -1] !='/') {4498char*new_root;4499 root = new_root =xmalloc(root_len +2);4500strcpy(new_root, arg);4501strcpy(new_root + root_len++,"/");4502}else4503 root = arg;4504return0;4505}45064507intcmd_apply(int argc,const char**argv,const char*prefix_)4508{4509int i;4510int errs =0;4511int is_not_gitdir = !startup_info->have_repository;4512int force_apply =0;45134514const char*whitespace_option = NULL;45154516struct option builtin_apply_options[] = {4517{ OPTION_CALLBACK,0,"exclude", NULL,N_("path"),4518N_("don't apply changes matching the given path"),45190, option_parse_exclude },4520{ OPTION_CALLBACK,0,"include", NULL,N_("path"),4521N_("apply changes matching the given path"),45220, option_parse_include },4523{ OPTION_CALLBACK,'p', NULL, NULL,N_("num"),4524N_("remove <num> leading slashes from traditional diff paths"),45250, option_parse_p },4526OPT_BOOL(0,"no-add", &no_add,4527N_("ignore additions made by the patch")),4528OPT_BOOL(0,"stat", &diffstat,4529N_("instead of applying the patch, output diffstat for the input")),4530OPT_NOOP_NOARG(0,"allow-binary-replacement"),4531OPT_NOOP_NOARG(0,"binary"),4532OPT_BOOL(0,"numstat", &numstat,4533N_("show number of added and deleted lines in decimal notation")),4534OPT_BOOL(0,"summary", &summary,4535N_("instead of applying the patch, output a summary for the input")),4536OPT_BOOL(0,"check", &check,4537N_("instead of applying the patch, see if the patch is applicable")),4538OPT_BOOL(0,"index", &check_index,4539N_("make sure the patch is applicable to the current index")),4540OPT_BOOL(0,"cached", &cached,4541N_("apply a patch without touching the working tree")),4542OPT_BOOL(0,"unsafe-paths", &unsafe_paths,4543N_("accept a patch that touches outside the working area")),4544OPT_BOOL(0,"apply", &force_apply,4545N_("also apply the patch (use with --stat/--summary/--check)")),4546OPT_BOOL('3',"3way", &threeway,4547N_("attempt three-way merge if a patch does not apply")),4548OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,4549N_("build a temporary index based on embedded index information")),4550{ OPTION_CALLBACK,'z', NULL, NULL, NULL,4551N_("paths are separated with NUL character"),4552 PARSE_OPT_NOARG, option_parse_z },4553OPT_INTEGER('C', NULL, &p_context,4554N_("ensure at least <n> lines of context match")),4555{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,N_("action"),4556N_("detect new or modified lines that have whitespace errors"),45570, option_parse_whitespace },4558{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,4559N_("ignore changes in whitespace when finding context"),4560 PARSE_OPT_NOARG, option_parse_space_change },4561{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,4562N_("ignore changes in whitespace when finding context"),4563 PARSE_OPT_NOARG, option_parse_space_change },4564OPT_BOOL('R',"reverse", &apply_in_reverse,4565N_("apply the patch in reverse")),4566OPT_BOOL(0,"unidiff-zero", &unidiff_zero,4567N_("don't expect at least one line of context")),4568OPT_BOOL(0,"reject", &apply_with_reject,4569N_("leave the rejected hunks in corresponding *.rej files")),4570OPT_BOOL(0,"allow-overlap", &allow_overlap,4571N_("allow overlapping hunks")),4572OPT__VERBOSE(&apply_verbosely,N_("be verbose")),4573OPT_BIT(0,"inaccurate-eof", &options,4574N_("tolerate incorrectly detected missing new-line at the end of file"),4575 INACCURATE_EOF),4576OPT_BIT(0,"recount", &options,4577N_("do not trust the line counts in the hunk headers"),4578 RECOUNT),4579{ OPTION_CALLBACK,0,"directory", NULL,N_("root"),4580N_("prepend <root> to all filenames"),45810, option_parse_directory },4582OPT_END()4583};45844585 prefix = prefix_;4586 prefix_length = prefix ?strlen(prefix) :0;4587git_apply_config();4588if(apply_default_whitespace)4589parse_whitespace_option(apply_default_whitespace);4590if(apply_default_ignorewhitespace)4591parse_ignorewhitespace_option(apply_default_ignorewhitespace);45924593 argc =parse_options(argc, argv, prefix, builtin_apply_options,4594 apply_usage,0);45954596if(apply_with_reject && threeway)4597die("--reject and --3way cannot be used together.");4598if(cached && threeway)4599die("--cached and --3way cannot be used together.");4600if(threeway) {4601if(is_not_gitdir)4602die(_("--3way outside a repository"));4603 check_index =1;4604}4605if(apply_with_reject)4606 apply = apply_verbosely =1;4607if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))4608 apply =0;4609if(check_index && is_not_gitdir)4610die(_("--index outside a repository"));4611if(cached) {4612if(is_not_gitdir)4613die(_("--cached outside a repository"));4614 check_index =1;4615}4616if(check_index)4617 unsafe_paths =0;46184619for(i =0; i < argc; i++) {4620const char*arg = argv[i];4621int fd;46224623if(!strcmp(arg,"-")) {4624 errs |=apply_patch(0,"<stdin>", options);4625 read_stdin =0;4626continue;4627}else if(0< prefix_length)4628 arg =prefix_filename(prefix, prefix_length, arg);46294630 fd =open(arg, O_RDONLY);4631if(fd <0)4632die_errno(_("can't open patch '%s'"), arg);4633 read_stdin =0;4634set_default_whitespace_mode(whitespace_option);4635 errs |=apply_patch(fd, arg, options);4636close(fd);4637}4638set_default_whitespace_mode(whitespace_option);4639if(read_stdin)4640 errs |=apply_patch(0,"<stdin>", options);4641if(whitespace_error) {4642if(squelch_whitespace_errors &&4643 squelch_whitespace_errors < whitespace_error) {4644int squelched =4645 whitespace_error - squelch_whitespace_errors;4646warning(Q_("squelched%dwhitespace error",4647"squelched%dwhitespace errors",4648 squelched),4649 squelched);4650}4651if(ws_error_action == die_on_ws_error)4652die(Q_("%dline adds whitespace errors.",4653"%dlines add whitespace errors.",4654 whitespace_error),4655 whitespace_error);4656if(applied_after_fixing_ws && apply)4657warning("%dline%sapplied after"4658" fixing whitespace errors.",4659 applied_after_fixing_ws,4660 applied_after_fixing_ws ==1?"":"s");4661else if(whitespace_error)4662warning(Q_("%dline adds whitespace errors.",4663"%dlines add whitespace errors.",4664 whitespace_error),4665 whitespace_error);4666}46674668if(update_index) {4669if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK))4670die(_("Unable to write new index file"));4671}46724673return!!errs;4674}