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 state_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 struct strbuf root = STRBUF_INIT; 81static int read_stdin =1; 82 83static voidparse_whitespace_option(const char*option) 84{ 85if(!option) { 86 ws_error_action = warn_on_ws_error; 87return; 88} 89if(!strcmp(option,"warn")) { 90 ws_error_action = warn_on_ws_error; 91return; 92} 93if(!strcmp(option,"nowarn")) { 94 ws_error_action = nowarn_ws_error; 95return; 96} 97if(!strcmp(option,"error")) { 98 ws_error_action = die_on_ws_error; 99return; 100} 101if(!strcmp(option,"error-all")) { 102 ws_error_action = die_on_ws_error; 103 squelch_whitespace_errors =0; 104return; 105} 106if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 107 ws_error_action = correct_ws_error; 108return; 109} 110die(_("unrecognized whitespace option '%s'"), option); 111} 112 113static voidparse_ignorewhitespace_option(const char*option) 114{ 115if(!option || !strcmp(option,"no") || 116!strcmp(option,"false") || !strcmp(option,"never") || 117!strcmp(option,"none")) { 118 ws_ignore_action = ignore_ws_none; 119return; 120} 121if(!strcmp(option,"change")) { 122 ws_ignore_action = ignore_ws_change; 123return; 124} 125die(_("unrecognized whitespace ignore option '%s'"), option); 126} 127 128static voidset_default_whitespace_mode(const char*whitespace_option) 129{ 130if(!whitespace_option && !apply_default_whitespace) 131 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 132} 133 134/* 135 * For "diff-stat" like behaviour, we keep track of the biggest change 136 * we've seen, and the longest filename. That allows us to do simple 137 * scaling. 138 */ 139static int max_change, max_len; 140 141/* 142 * Various "current state", notably line numbers and what 143 * file (and how) we're patching right now.. The "is_xxxx" 144 * things are flags, where -1 means "don't know yet". 145 */ 146static int state_linenr =1; 147 148/* 149 * This represents one "hunk" from a patch, starting with 150 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 151 * patch text is pointed at by patch, and its byte length 152 * is stored in size. leading and trailing are the number 153 * of context lines. 154 */ 155struct fragment { 156unsigned long leading, trailing; 157unsigned long oldpos, oldlines; 158unsigned long newpos, newlines; 159/* 160 * 'patch' is usually borrowed from buf in apply_patch(), 161 * but some codepaths store an allocated buffer. 162 */ 163const char*patch; 164unsigned free_patch:1, 165 rejected:1; 166int size; 167int linenr; 168struct fragment *next; 169}; 170 171/* 172 * When dealing with a binary patch, we reuse "leading" field 173 * to store the type of the binary hunk, either deflated "delta" 174 * or deflated "literal". 175 */ 176#define binary_patch_method leading 177#define BINARY_DELTA_DEFLATED 1 178#define BINARY_LITERAL_DEFLATED 2 179 180/* 181 * This represents a "patch" to a file, both metainfo changes 182 * such as creation/deletion, filemode and content changes represented 183 * as a series of fragments. 184 */ 185struct patch { 186char*new_name, *old_name, *def_name; 187unsigned int old_mode, new_mode; 188int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 189int rejected; 190unsigned ws_rule; 191int lines_added, lines_deleted; 192int score; 193unsigned int is_toplevel_relative:1; 194unsigned int inaccurate_eof:1; 195unsigned int is_binary:1; 196unsigned int is_copy:1; 197unsigned int is_rename:1; 198unsigned int recount:1; 199unsigned int conflicted_threeway:1; 200unsigned int direct_to_threeway:1; 201struct fragment *fragments; 202char*result; 203size_t resultsize; 204char old_sha1_prefix[41]; 205char new_sha1_prefix[41]; 206struct patch *next; 207 208/* three-way fallback result */ 209struct object_id threeway_stage[3]; 210}; 211 212static voidfree_fragment_list(struct fragment *list) 213{ 214while(list) { 215struct fragment *next = list->next; 216if(list->free_patch) 217free((char*)list->patch); 218free(list); 219 list = next; 220} 221} 222 223static voidfree_patch(struct patch *patch) 224{ 225free_fragment_list(patch->fragments); 226free(patch->def_name); 227free(patch->old_name); 228free(patch->new_name); 229free(patch->result); 230free(patch); 231} 232 233static voidfree_patch_list(struct patch *list) 234{ 235while(list) { 236struct patch *next = list->next; 237free_patch(list); 238 list = next; 239} 240} 241 242/* 243 * A line in a file, len-bytes long (includes the terminating LF, 244 * except for an incomplete line at the end if the file ends with 245 * one), and its contents hashes to 'hash'. 246 */ 247struct line { 248size_t len; 249unsigned hash :24; 250unsigned flag :8; 251#define LINE_COMMON 1 252#define LINE_PATCHED 2 253}; 254 255/* 256 * This represents a "file", which is an array of "lines". 257 */ 258struct image { 259char*buf; 260size_t len; 261size_t nr; 262size_t alloc; 263struct line *line_allocated; 264struct line *line; 265}; 266 267/* 268 * Records filenames that have been touched, in order to handle 269 * the case where more than one patches touch the same file. 270 */ 271 272static struct string_list fn_table; 273 274static uint32_thash_line(const char*cp,size_t len) 275{ 276size_t i; 277uint32_t h; 278for(i =0, h =0; i < len; i++) { 279if(!isspace(cp[i])) { 280 h = h *3+ (cp[i] &0xff); 281} 282} 283return h; 284} 285 286/* 287 * Compare lines s1 of length n1 and s2 of length n2, ignoring 288 * whitespace difference. Returns 1 if they match, 0 otherwise 289 */ 290static intfuzzy_matchlines(const char*s1,size_t n1, 291const char*s2,size_t n2) 292{ 293const char*last1 = s1 + n1 -1; 294const char*last2 = s2 + n2 -1; 295int result =0; 296 297/* ignore line endings */ 298while((*last1 =='\r') || (*last1 =='\n')) 299 last1--; 300while((*last2 =='\r') || (*last2 =='\n')) 301 last2--; 302 303/* skip leading whitespaces, if both begin with whitespace */ 304if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 305while(isspace(*s1) && (s1 <= last1)) 306 s1++; 307while(isspace(*s2) && (s2 <= last2)) 308 s2++; 309} 310/* early return if both lines are empty */ 311if((s1 > last1) && (s2 > last2)) 312return1; 313while(!result) { 314 result = *s1++ - *s2++; 315/* 316 * Skip whitespace inside. We check for whitespace on 317 * both buffers because we don't want "a b" to match 318 * "ab" 319 */ 320if(isspace(*s1) &&isspace(*s2)) { 321while(isspace(*s1) && s1 <= last1) 322 s1++; 323while(isspace(*s2) && s2 <= last2) 324 s2++; 325} 326/* 327 * If we reached the end on one side only, 328 * lines don't match 329 */ 330if( 331((s2 > last2) && (s1 <= last1)) || 332((s1 > last1) && (s2 <= last2))) 333return0; 334if((s1 > last1) && (s2 > last2)) 335break; 336} 337 338return!result; 339} 340 341static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 342{ 343ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 344 img->line_allocated[img->nr].len = len; 345 img->line_allocated[img->nr].hash =hash_line(bol, len); 346 img->line_allocated[img->nr].flag = flag; 347 img->nr++; 348} 349 350/* 351 * "buf" has the file contents to be patched (read from various sources). 352 * attach it to "image" and add line-based index to it. 353 * "image" now owns the "buf". 354 */ 355static voidprepare_image(struct image *image,char*buf,size_t len, 356int prepare_linetable) 357{ 358const char*cp, *ep; 359 360memset(image,0,sizeof(*image)); 361 image->buf = buf; 362 image->len = len; 363 364if(!prepare_linetable) 365return; 366 367 ep = image->buf + image->len; 368 cp = image->buf; 369while(cp < ep) { 370const char*next; 371for(next = cp; next < ep && *next !='\n'; next++) 372; 373if(next < ep) 374 next++; 375add_line_info(image, cp, next - cp,0); 376 cp = next; 377} 378 image->line = image->line_allocated; 379} 380 381static voidclear_image(struct image *image) 382{ 383free(image->buf); 384free(image->line_allocated); 385memset(image,0,sizeof(*image)); 386} 387 388/* fmt must contain _one_ %s and no other substitution */ 389static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 390{ 391struct strbuf sb = STRBUF_INIT; 392 393if(patch->old_name && patch->new_name && 394strcmp(patch->old_name, patch->new_name)) { 395quote_c_style(patch->old_name, &sb, NULL,0); 396strbuf_addstr(&sb," => "); 397quote_c_style(patch->new_name, &sb, NULL,0); 398}else{ 399const char*n = patch->new_name; 400if(!n) 401 n = patch->old_name; 402quote_c_style(n, &sb, NULL,0); 403} 404fprintf(output, fmt, sb.buf); 405fputc('\n', output); 406strbuf_release(&sb); 407} 408 409#define SLOP (16) 410 411static voidread_patch_file(struct strbuf *sb,int fd) 412{ 413if(strbuf_read(sb, fd,0) <0) 414die_errno("git apply: failed to read"); 415 416/* 417 * Make sure that we have some slop in the buffer 418 * so that we can do speculative "memcmp" etc, and 419 * see to it that it is NUL-filled. 420 */ 421strbuf_grow(sb, SLOP); 422memset(sb->buf + sb->len,0, SLOP); 423} 424 425static unsigned longlinelen(const char*buffer,unsigned long size) 426{ 427unsigned long len =0; 428while(size--) { 429 len++; 430if(*buffer++ =='\n') 431break; 432} 433return len; 434} 435 436static intis_dev_null(const char*str) 437{ 438returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 439} 440 441#define TERM_SPACE 1 442#define TERM_TAB 2 443 444static intname_terminate(const char*name,int namelen,int c,int terminate) 445{ 446if(c ==' '&& !(terminate & TERM_SPACE)) 447return0; 448if(c =='\t'&& !(terminate & TERM_TAB)) 449return0; 450 451return1; 452} 453 454/* remove double slashes to make --index work with such filenames */ 455static char*squash_slash(char*name) 456{ 457int i =0, j =0; 458 459if(!name) 460return NULL; 461 462while(name[i]) { 463if((name[j++] = name[i++]) =='/') 464while(name[i] =='/') 465 i++; 466} 467 name[j] ='\0'; 468return name; 469} 470 471static char*find_name_gnu(const char*line,const char*def,int p_value) 472{ 473struct strbuf name = STRBUF_INIT; 474char*cp; 475 476/* 477 * Proposed "new-style" GNU patch/diff format; see 478 * http://marc.info/?l=git&m=112927316408690&w=2 479 */ 480if(unquote_c_style(&name, line, NULL)) { 481strbuf_release(&name); 482return NULL; 483} 484 485for(cp = name.buf; p_value; p_value--) { 486 cp =strchr(cp,'/'); 487if(!cp) { 488strbuf_release(&name); 489return NULL; 490} 491 cp++; 492} 493 494strbuf_remove(&name,0, cp - name.buf); 495if(root.len) 496strbuf_insert(&name,0, root.buf, root.len); 497returnsquash_slash(strbuf_detach(&name, NULL)); 498} 499 500static size_tsane_tz_len(const char*line,size_t len) 501{ 502const char*tz, *p; 503 504if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 505return0; 506 tz = line + len -strlen(" +0500"); 507 508if(tz[1] !='+'&& tz[1] !='-') 509return0; 510 511for(p = tz +2; p != line + len; p++) 512if(!isdigit(*p)) 513return0; 514 515return line + len - tz; 516} 517 518static size_ttz_with_colon_len(const char*line,size_t len) 519{ 520const char*tz, *p; 521 522if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 523return0; 524 tz = line + len -strlen(" +08:00"); 525 526if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 527return0; 528 p = tz +2; 529if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 530!isdigit(*p++) || !isdigit(*p++)) 531return0; 532 533return line + len - tz; 534} 535 536static size_tdate_len(const char*line,size_t len) 537{ 538const char*date, *p; 539 540if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 541return0; 542 p = date = line + len -strlen("72-02-05"); 543 544if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 545!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 546!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 547return0; 548 549if(date - line >=strlen("19") && 550isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 551 date -=strlen("19"); 552 553return line + len - date; 554} 555 556static size_tshort_time_len(const char*line,size_t len) 557{ 558const char*time, *p; 559 560if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 561return0; 562 p = time = line + len -strlen(" 07:01:32"); 563 564/* Permit 1-digit hours? */ 565if(*p++ !=' '|| 566!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 567!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 568!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 569return0; 570 571return line + len - time; 572} 573 574static size_tfractional_time_len(const char*line,size_t len) 575{ 576const char*p; 577size_t n; 578 579/* Expected format: 19:41:17.620000023 */ 580if(!len || !isdigit(line[len -1])) 581return0; 582 p = line + len -1; 583 584/* Fractional seconds. */ 585while(p > line &&isdigit(*p)) 586 p--; 587if(*p !='.') 588return0; 589 590/* Hours, minutes, and whole seconds. */ 591 n =short_time_len(line, p - line); 592if(!n) 593return0; 594 595return line + len - p + n; 596} 597 598static size_ttrailing_spaces_len(const char*line,size_t len) 599{ 600const char*p; 601 602/* Expected format: ' ' x (1 or more) */ 603if(!len || line[len -1] !=' ') 604return0; 605 606 p = line + len; 607while(p != line) { 608 p--; 609if(*p !=' ') 610return line + len - (p +1); 611} 612 613/* All spaces! */ 614return len; 615} 616 617static size_tdiff_timestamp_len(const char*line,size_t len) 618{ 619const char*end = line + len; 620size_t n; 621 622/* 623 * Posix: 2010-07-05 19:41:17 624 * GNU: 2010-07-05 19:41:17.620000023 -0500 625 */ 626 627if(!isdigit(end[-1])) 628return0; 629 630 n =sane_tz_len(line, end - line); 631if(!n) 632 n =tz_with_colon_len(line, end - line); 633 end -= n; 634 635 n =short_time_len(line, end - line); 636if(!n) 637 n =fractional_time_len(line, end - line); 638 end -= n; 639 640 n =date_len(line, end - line); 641if(!n)/* No date. Too bad. */ 642return0; 643 end -= n; 644 645if(end == line)/* No space before date. */ 646return0; 647if(end[-1] =='\t') {/* Success! */ 648 end--; 649return line + len - end; 650} 651if(end[-1] !=' ')/* No space before date. */ 652return0; 653 654/* Whitespace damage. */ 655 end -=trailing_spaces_len(line, end - line); 656return line + len - end; 657} 658 659static char*find_name_common(const char*line,const char*def, 660int p_value,const char*end,int terminate) 661{ 662int len; 663const char*start = NULL; 664 665if(p_value ==0) 666 start = line; 667while(line != end) { 668char c = *line; 669 670if(!end &&isspace(c)) { 671if(c =='\n') 672break; 673if(name_terminate(start, line-start, c, terminate)) 674break; 675} 676 line++; 677if(c =='/'&& !--p_value) 678 start = line; 679} 680if(!start) 681returnsquash_slash(xstrdup_or_null(def)); 682 len = line - start; 683if(!len) 684returnsquash_slash(xstrdup_or_null(def)); 685 686/* 687 * Generally we prefer the shorter name, especially 688 * if the other one is just a variation of that with 689 * something else tacked on to the end (ie "file.orig" 690 * or "file~"). 691 */ 692if(def) { 693int deflen =strlen(def); 694if(deflen < len && !strncmp(start, def, deflen)) 695returnsquash_slash(xstrdup(def)); 696} 697 698if(root.len) { 699char*ret =xstrfmt("%s%.*s", root.buf, len, start); 700returnsquash_slash(ret); 701} 702 703returnsquash_slash(xmemdupz(start, len)); 704} 705 706static char*find_name(const char*line,char*def,int p_value,int terminate) 707{ 708if(*line =='"') { 709char*name =find_name_gnu(line, def, p_value); 710if(name) 711return name; 712} 713 714returnfind_name_common(line, def, p_value, NULL, terminate); 715} 716 717static char*find_name_traditional(const char*line,char*def,int p_value) 718{ 719size_t len; 720size_t date_len; 721 722if(*line =='"') { 723char*name =find_name_gnu(line, def, p_value); 724if(name) 725return name; 726} 727 728 len =strchrnul(line,'\n') - line; 729 date_len =diff_timestamp_len(line, len); 730if(!date_len) 731returnfind_name_common(line, def, p_value, NULL, TERM_TAB); 732 len -= date_len; 733 734returnfind_name_common(line, def, p_value, line + len,0); 735} 736 737static intcount_slashes(const char*cp) 738{ 739int cnt =0; 740char ch; 741 742while((ch = *cp++)) 743if(ch =='/') 744 cnt++; 745return cnt; 746} 747 748/* 749 * Given the string after "--- " or "+++ ", guess the appropriate 750 * p_value for the given patch. 751 */ 752static intguess_p_value(const char*nameline) 753{ 754char*name, *cp; 755int val = -1; 756 757if(is_dev_null(nameline)) 758return-1; 759 name =find_name_traditional(nameline, NULL,0); 760if(!name) 761return-1; 762 cp =strchr(name,'/'); 763if(!cp) 764 val =0; 765else if(prefix) { 766/* 767 * Does it begin with "a/$our-prefix" and such? Then this is 768 * very likely to apply to our directory. 769 */ 770if(!strncmp(name, prefix, prefix_length)) 771 val =count_slashes(prefix); 772else{ 773 cp++; 774if(!strncmp(cp, prefix, prefix_length)) 775 val =count_slashes(prefix) +1; 776} 777} 778free(name); 779return val; 780} 781 782/* 783 * Does the ---/+++ line have the POSIX timestamp after the last HT? 784 * GNU diff puts epoch there to signal a creation/deletion event. Is 785 * this such a timestamp? 786 */ 787static inthas_epoch_timestamp(const char*nameline) 788{ 789/* 790 * We are only interested in epoch timestamp; any non-zero 791 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 792 * For the same reason, the date must be either 1969-12-31 or 793 * 1970-01-01, and the seconds part must be "00". 794 */ 795const char stamp_regexp[] = 796"^(1969-12-31|1970-01-01)" 797" " 798"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 799" " 800"([-+][0-2][0-9]:?[0-5][0-9])\n"; 801const char*timestamp = NULL, *cp, *colon; 802static regex_t *stamp; 803 regmatch_t m[10]; 804int zoneoffset; 805int hourminute; 806int status; 807 808for(cp = nameline; *cp !='\n'; cp++) { 809if(*cp =='\t') 810 timestamp = cp +1; 811} 812if(!timestamp) 813return0; 814if(!stamp) { 815 stamp =xmalloc(sizeof(*stamp)); 816if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 817warning(_("Cannot prepare timestamp regexp%s"), 818 stamp_regexp); 819return0; 820} 821} 822 823 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 824if(status) { 825if(status != REG_NOMATCH) 826warning(_("regexec returned%dfor input:%s"), 827 status, timestamp); 828return0; 829} 830 831 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 832if(*colon ==':') 833 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 834else 835 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 836if(timestamp[m[3].rm_so] =='-') 837 zoneoffset = -zoneoffset; 838 839/* 840 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 841 * (west of GMT) or 1970-01-01 (east of GMT) 842 */ 843if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 844(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 845return0; 846 847 hourminute = (strtol(timestamp +11, NULL,10) *60+ 848strtol(timestamp +14, NULL,10) - 849 zoneoffset); 850 851return((zoneoffset <0&& hourminute ==1440) || 852(0<= zoneoffset && !hourminute)); 853} 854 855/* 856 * Get the name etc info from the ---/+++ lines of a traditional patch header 857 * 858 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 859 * files, we can happily check the index for a match, but for creating a 860 * new file we should try to match whatever "patch" does. I have no idea. 861 */ 862static voidparse_traditional_patch(const char*first,const char*second,struct patch *patch) 863{ 864char*name; 865 866 first +=4;/* skip "--- " */ 867 second +=4;/* skip "+++ " */ 868if(!p_value_known) { 869int p, q; 870 p =guess_p_value(first); 871 q =guess_p_value(second); 872if(p <0) p = q; 873if(0<= p && p == q) { 874 state_p_value = p; 875 p_value_known =1; 876} 877} 878if(is_dev_null(first)) { 879 patch->is_new =1; 880 patch->is_delete =0; 881 name =find_name_traditional(second, NULL, state_p_value); 882 patch->new_name = name; 883}else if(is_dev_null(second)) { 884 patch->is_new =0; 885 patch->is_delete =1; 886 name =find_name_traditional(first, NULL, state_p_value); 887 patch->old_name = name; 888}else{ 889char*first_name; 890 first_name =find_name_traditional(first, NULL, state_p_value); 891 name =find_name_traditional(second, first_name, state_p_value); 892free(first_name); 893if(has_epoch_timestamp(first)) { 894 patch->is_new =1; 895 patch->is_delete =0; 896 patch->new_name = name; 897}else if(has_epoch_timestamp(second)) { 898 patch->is_new =0; 899 patch->is_delete =1; 900 patch->old_name = name; 901}else{ 902 patch->old_name = name; 903 patch->new_name =xstrdup_or_null(name); 904} 905} 906if(!name) 907die(_("unable to find filename in patch at line%d"), state_linenr); 908} 909 910static intgitdiff_hdrend(const char*line,struct patch *patch) 911{ 912return-1; 913} 914 915/* 916 * We're anal about diff header consistency, to make 917 * sure that we don't end up having strange ambiguous 918 * patches floating around. 919 * 920 * As a result, gitdiff_{old|new}name() will check 921 * their names against any previous information, just 922 * to make sure.. 923 */ 924#define DIFF_OLD_NAME 0 925#define DIFF_NEW_NAME 1 926 927static voidgitdiff_verify_name(const char*line,int isnull,char**name,int side) 928{ 929if(!*name && !isnull) { 930*name =find_name(line, NULL, state_p_value, TERM_TAB); 931return; 932} 933 934if(*name) { 935int len =strlen(*name); 936char*another; 937if(isnull) 938die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 939*name, state_linenr); 940 another =find_name(line, NULL, state_p_value, TERM_TAB); 941if(!another ||memcmp(another, *name, len +1)) 942die((side == DIFF_NEW_NAME) ? 943_("git apply: bad git-diff - inconsistent new filename on line%d") : 944_("git apply: bad git-diff - inconsistent old filename on line%d"), state_linenr); 945free(another); 946}else{ 947/* expect "/dev/null" */ 948if(memcmp("/dev/null", line,9) || line[9] !='\n') 949die(_("git apply: bad git-diff - expected /dev/null on line%d"), state_linenr); 950} 951} 952 953static intgitdiff_oldname(const char*line,struct patch *patch) 954{ 955gitdiff_verify_name(line, patch->is_new, &patch->old_name, 956 DIFF_OLD_NAME); 957return0; 958} 959 960static intgitdiff_newname(const char*line,struct patch *patch) 961{ 962gitdiff_verify_name(line, patch->is_delete, &patch->new_name, 963 DIFF_NEW_NAME); 964return0; 965} 966 967static intgitdiff_oldmode(const char*line,struct patch *patch) 968{ 969 patch->old_mode =strtoul(line, NULL,8); 970return0; 971} 972 973static intgitdiff_newmode(const char*line,struct patch *patch) 974{ 975 patch->new_mode =strtoul(line, NULL,8); 976return0; 977} 978 979static intgitdiff_delete(const char*line,struct patch *patch) 980{ 981 patch->is_delete =1; 982free(patch->old_name); 983 patch->old_name =xstrdup_or_null(patch->def_name); 984returngitdiff_oldmode(line, patch); 985} 986 987static intgitdiff_newfile(const char*line,struct patch *patch) 988{ 989 patch->is_new =1; 990free(patch->new_name); 991 patch->new_name =xstrdup_or_null(patch->def_name); 992returngitdiff_newmode(line, patch); 993} 994 995static intgitdiff_copysrc(const char*line,struct patch *patch) 996{ 997 patch->is_copy =1; 998free(patch->old_name); 999 patch->old_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1000return0;1001}10021003static intgitdiff_copydst(const char*line,struct patch *patch)1004{1005 patch->is_copy =1;1006free(patch->new_name);1007 patch->new_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1008return0;1009}10101011static intgitdiff_renamesrc(const char*line,struct patch *patch)1012{1013 patch->is_rename =1;1014free(patch->old_name);1015 patch->old_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1016return0;1017}10181019static intgitdiff_renamedst(const char*line,struct patch *patch)1020{1021 patch->is_rename =1;1022free(patch->new_name);1023 patch->new_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1024return0;1025}10261027static intgitdiff_similarity(const char*line,struct patch *patch)1028{1029unsigned long val =strtoul(line, NULL,10);1030if(val <=100)1031 patch->score = val;1032return0;1033}10341035static intgitdiff_dissimilarity(const char*line,struct patch *patch)1036{1037unsigned long val =strtoul(line, NULL,10);1038if(val <=100)1039 patch->score = val;1040return0;1041}10421043static intgitdiff_index(const char*line,struct patch *patch)1044{1045/*1046 * index line is N hexadecimal, "..", N hexadecimal,1047 * and optional space with octal mode.1048 */1049const char*ptr, *eol;1050int len;10511052 ptr =strchr(line,'.');1053if(!ptr || ptr[1] !='.'||40< ptr - line)1054return0;1055 len = ptr - line;1056memcpy(patch->old_sha1_prefix, line, len);1057 patch->old_sha1_prefix[len] =0;10581059 line = ptr +2;1060 ptr =strchr(line,' ');1061 eol =strchrnul(line,'\n');10621063if(!ptr || eol < ptr)1064 ptr = eol;1065 len = ptr - line;10661067if(40< len)1068return0;1069memcpy(patch->new_sha1_prefix, line, len);1070 patch->new_sha1_prefix[len] =0;1071if(*ptr ==' ')1072 patch->old_mode =strtoul(ptr+1, NULL,8);1073return0;1074}10751076/*1077 * This is normal for a diff that doesn't change anything: we'll fall through1078 * into the next diff. Tell the parser to break out.1079 */1080static intgitdiff_unrecognized(const char*line,struct patch *patch)1081{1082return-1;1083}10841085/*1086 * Skip p_value leading components from "line"; as we do not accept1087 * absolute paths, return NULL in that case.1088 */1089static const char*skip_tree_prefix(const char*line,int llen)1090{1091int nslash;1092int i;10931094if(!state_p_value)1095return(llen && line[0] =='/') ? NULL : line;10961097 nslash = state_p_value;1098for(i =0; i < llen; i++) {1099int ch = line[i];1100if(ch =='/'&& --nslash <=0)1101return(i ==0) ? NULL : &line[i +1];1102}1103return NULL;1104}11051106/*1107 * This is to extract the same name that appears on "diff --git"1108 * line. We do not find and return anything if it is a rename1109 * patch, and it is OK because we will find the name elsewhere.1110 * We need to reliably find name only when it is mode-change only,1111 * creation or deletion of an empty file. In any of these cases,1112 * both sides are the same name under a/ and b/ respectively.1113 */1114static char*git_header_name(const char*line,int llen)1115{1116const char*name;1117const char*second = NULL;1118size_t len, line_len;11191120 line +=strlen("diff --git ");1121 llen -=strlen("diff --git ");11221123if(*line =='"') {1124const char*cp;1125struct strbuf first = STRBUF_INIT;1126struct strbuf sp = STRBUF_INIT;11271128if(unquote_c_style(&first, line, &second))1129goto free_and_fail1;11301131/* strip the a/b prefix including trailing slash */1132 cp =skip_tree_prefix(first.buf, first.len);1133if(!cp)1134goto free_and_fail1;1135strbuf_remove(&first,0, cp - first.buf);11361137/*1138 * second points at one past closing dq of name.1139 * find the second name.1140 */1141while((second < line + llen) &&isspace(*second))1142 second++;11431144if(line + llen <= second)1145goto free_and_fail1;1146if(*second =='"') {1147if(unquote_c_style(&sp, second, NULL))1148goto free_and_fail1;1149 cp =skip_tree_prefix(sp.buf, sp.len);1150if(!cp)1151goto free_and_fail1;1152/* They must match, otherwise ignore */1153if(strcmp(cp, first.buf))1154goto free_and_fail1;1155strbuf_release(&sp);1156returnstrbuf_detach(&first, NULL);1157}11581159/* unquoted second */1160 cp =skip_tree_prefix(second, line + llen - second);1161if(!cp)1162goto free_and_fail1;1163if(line + llen - cp != first.len ||1164memcmp(first.buf, cp, first.len))1165goto free_and_fail1;1166returnstrbuf_detach(&first, NULL);11671168 free_and_fail1:1169strbuf_release(&first);1170strbuf_release(&sp);1171return NULL;1172}11731174/* unquoted first name */1175 name =skip_tree_prefix(line, llen);1176if(!name)1177return NULL;11781179/*1180 * since the first name is unquoted, a dq if exists must be1181 * the beginning of the second name.1182 */1183for(second = name; second < line + llen; second++) {1184if(*second =='"') {1185struct strbuf sp = STRBUF_INIT;1186const char*np;11871188if(unquote_c_style(&sp, second, NULL))1189goto free_and_fail2;11901191 np =skip_tree_prefix(sp.buf, sp.len);1192if(!np)1193goto free_and_fail2;11941195 len = sp.buf + sp.len - np;1196if(len < second - name &&1197!strncmp(np, name, len) &&1198isspace(name[len])) {1199/* Good */1200strbuf_remove(&sp,0, np - sp.buf);1201returnstrbuf_detach(&sp, NULL);1202}12031204 free_and_fail2:1205strbuf_release(&sp);1206return NULL;1207}1208}12091210/*1211 * Accept a name only if it shows up twice, exactly the same1212 * form.1213 */1214 second =strchr(name,'\n');1215if(!second)1216return NULL;1217 line_len = second - name;1218for(len =0; ; len++) {1219switch(name[len]) {1220default:1221continue;1222case'\n':1223return NULL;1224case'\t':case' ':1225/*1226 * Is this the separator between the preimage1227 * and the postimage pathname? Again, we are1228 * only interested in the case where there is1229 * no rename, as this is only to set def_name1230 * and a rename patch has the names elsewhere1231 * in an unambiguous form.1232 */1233if(!name[len +1])1234return NULL;/* no postimage name */1235 second =skip_tree_prefix(name + len +1,1236 line_len - (len +1));1237if(!second)1238return NULL;1239/*1240 * Does len bytes starting at "name" and "second"1241 * (that are separated by one HT or SP we just1242 * found) exactly match?1243 */1244if(second[len] =='\n'&& !strncmp(name, second, len))1245returnxmemdupz(name, len);1246}1247}1248}12491250/* Verify that we recognize the lines following a git header */1251static intparse_git_header(const char*line,int len,unsigned int size,struct patch *patch)1252{1253unsigned long offset;12541255/* A git diff has explicit new/delete information, so we don't guess */1256 patch->is_new =0;1257 patch->is_delete =0;12581259/*1260 * Some things may not have the old name in the1261 * rest of the headers anywhere (pure mode changes,1262 * or removing or adding empty files), so we get1263 * the default name from the header.1264 */1265 patch->def_name =git_header_name(line, len);1266if(patch->def_name && root.len) {1267char*s =xstrfmt("%s%s", root.buf, patch->def_name);1268free(patch->def_name);1269 patch->def_name = s;1270}12711272 line += len;1273 size -= len;1274 state_linenr++;1275for(offset = len ; size >0; offset += len, size -= len, line += len, state_linenr++) {1276static const struct opentry {1277const char*str;1278int(*fn)(const char*,struct patch *);1279} optable[] = {1280{"@@ -", gitdiff_hdrend },1281{"--- ", gitdiff_oldname },1282{"+++ ", gitdiff_newname },1283{"old mode ", gitdiff_oldmode },1284{"new mode ", gitdiff_newmode },1285{"deleted file mode ", gitdiff_delete },1286{"new file mode ", gitdiff_newfile },1287{"copy from ", gitdiff_copysrc },1288{"copy to ", gitdiff_copydst },1289{"rename old ", gitdiff_renamesrc },1290{"rename new ", gitdiff_renamedst },1291{"rename from ", gitdiff_renamesrc },1292{"rename to ", gitdiff_renamedst },1293{"similarity index ", gitdiff_similarity },1294{"dissimilarity index ", gitdiff_dissimilarity },1295{"index ", gitdiff_index },1296{"", gitdiff_unrecognized },1297};1298int i;12991300 len =linelen(line, size);1301if(!len || line[len-1] !='\n')1302break;1303for(i =0; i <ARRAY_SIZE(optable); i++) {1304const struct opentry *p = optable + i;1305int oplen =strlen(p->str);1306if(len < oplen ||memcmp(p->str, line, oplen))1307continue;1308if(p->fn(line + oplen, patch) <0)1309return offset;1310break;1311}1312}13131314return offset;1315}13161317static intparse_num(const char*line,unsigned long*p)1318{1319char*ptr;13201321if(!isdigit(*line))1322return0;1323*p =strtoul(line, &ptr,10);1324return ptr - line;1325}13261327static intparse_range(const char*line,int len,int offset,const char*expect,1328unsigned long*p1,unsigned long*p2)1329{1330int digits, ex;13311332if(offset <0|| offset >= len)1333return-1;1334 line += offset;1335 len -= offset;13361337 digits =parse_num(line, p1);1338if(!digits)1339return-1;13401341 offset += digits;1342 line += digits;1343 len -= digits;13441345*p2 =1;1346if(*line ==',') {1347 digits =parse_num(line+1, p2);1348if(!digits)1349return-1;13501351 offset += digits+1;1352 line += digits+1;1353 len -= digits+1;1354}13551356 ex =strlen(expect);1357if(ex > len)1358return-1;1359if(memcmp(line, expect, ex))1360return-1;13611362return offset + ex;1363}13641365static voidrecount_diff(const char*line,int size,struct fragment *fragment)1366{1367int oldlines =0, newlines =0, ret =0;13681369if(size <1) {1370warning("recount: ignore empty hunk");1371return;1372}13731374for(;;) {1375int len =linelen(line, size);1376 size -= len;1377 line += len;13781379if(size <1)1380break;13811382switch(*line) {1383case' ':case'\n':1384 newlines++;1385/* fall through */1386case'-':1387 oldlines++;1388continue;1389case'+':1390 newlines++;1391continue;1392case'\\':1393continue;1394case'@':1395 ret = size <3|| !starts_with(line,"@@ ");1396break;1397case'd':1398 ret = size <5|| !starts_with(line,"diff ");1399break;1400default:1401 ret = -1;1402break;1403}1404if(ret) {1405warning(_("recount: unexpected line: %.*s"),1406(int)linelen(line, size), line);1407return;1408}1409break;1410}1411 fragment->oldlines = oldlines;1412 fragment->newlines = newlines;1413}14141415/*1416 * Parse a unified diff fragment header of the1417 * form "@@ -a,b +c,d @@"1418 */1419static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1420{1421int offset;14221423if(!len || line[len-1] !='\n')1424return-1;14251426/* Figure out the number of lines in a fragment */1427 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1428 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14291430return offset;1431}14321433static intfind_header(const char*line,unsigned long size,int*hdrsize,struct patch *patch)1434{1435unsigned long offset, len;14361437 patch->is_toplevel_relative =0;1438 patch->is_rename = patch->is_copy =0;1439 patch->is_new = patch->is_delete = -1;1440 patch->old_mode = patch->new_mode =0;1441 patch->old_name = patch->new_name = NULL;1442for(offset =0; size >0; offset += len, size -= len, line += len, state_linenr++) {1443unsigned long nextlen;14441445 len =linelen(line, size);1446if(!len)1447break;14481449/* Testing this early allows us to take a few shortcuts.. */1450if(len <6)1451continue;14521453/*1454 * Make sure we don't find any unconnected patch fragments.1455 * That's a sign that we didn't find a header, and that a1456 * patch has become corrupted/broken up.1457 */1458if(!memcmp("@@ -", line,4)) {1459struct fragment dummy;1460if(parse_fragment_header(line, len, &dummy) <0)1461continue;1462die(_("patch fragment without header at line%d: %.*s"),1463 state_linenr, (int)len-1, line);1464}14651466if(size < len +6)1467break;14681469/*1470 * Git patch? It might not have a real patch, just a rename1471 * or mode change, so we handle that specially1472 */1473if(!memcmp("diff --git ", line,11)) {1474int git_hdr_len =parse_git_header(line, len, size, patch);1475if(git_hdr_len <= len)1476continue;1477if(!patch->old_name && !patch->new_name) {1478if(!patch->def_name)1479die(Q_("git diff header lacks filename information when removing "1480"%dleading pathname component (line%d)",1481"git diff header lacks filename information when removing "1482"%dleading pathname components (line%d)",1483 state_p_value),1484 state_p_value, state_linenr);1485 patch->old_name =xstrdup(patch->def_name);1486 patch->new_name =xstrdup(patch->def_name);1487}1488if(!patch->is_delete && !patch->new_name)1489die("git diff header lacks filename information "1490"(line%d)", state_linenr);1491 patch->is_toplevel_relative =1;1492*hdrsize = git_hdr_len;1493return offset;1494}14951496/* --- followed by +++ ? */1497if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1498continue;14991500/*1501 * We only accept unified patches, so we want it to1502 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1503 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1504 */1505 nextlen =linelen(line + len, size - len);1506if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1507continue;15081509/* Ok, we'll consider it a patch */1510parse_traditional_patch(line, line+len, patch);1511*hdrsize = len + nextlen;1512 state_linenr +=2;1513return offset;1514}1515return-1;1516}15171518static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1519{1520char*err;15211522if(!result)1523return;15241525 whitespace_error++;1526if(squelch_whitespace_errors &&1527 squelch_whitespace_errors < whitespace_error)1528return;15291530 err =whitespace_error_string(result);1531fprintf(stderr,"%s:%d:%s.\n%.*s\n",1532 patch_input_file, linenr, err, len, line);1533free(err);1534}15351536static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1537{1538unsigned result =ws_check(line +1, len -1, ws_rule);15391540record_ws_error(result, line +1, len -2, state_linenr);1541}15421543/*1544 * Parse a unified diff. Note that this really needs to parse each1545 * fragment separately, since the only way to know the difference1546 * between a "---" that is part of a patch, and a "---" that starts1547 * the next patch is to look at the line counts..1548 */1549static intparse_fragment(const char*line,unsigned long size,1550struct patch *patch,struct fragment *fragment)1551{1552int added, deleted;1553int len =linelen(line, size), offset;1554unsigned long oldlines, newlines;1555unsigned long leading, trailing;15561557 offset =parse_fragment_header(line, len, fragment);1558if(offset <0)1559return-1;1560if(offset >0&& patch->recount)1561recount_diff(line + offset, size - offset, fragment);1562 oldlines = fragment->oldlines;1563 newlines = fragment->newlines;1564 leading =0;1565 trailing =0;15661567/* Parse the thing.. */1568 line += len;1569 size -= len;1570 state_linenr++;1571 added = deleted =0;1572for(offset = len;15730< size;1574 offset += len, size -= len, line += len, state_linenr++) {1575if(!oldlines && !newlines)1576break;1577 len =linelen(line, size);1578if(!len || line[len-1] !='\n')1579return-1;1580switch(*line) {1581default:1582return-1;1583case'\n':/* newer GNU diff, an empty context line */1584case' ':1585 oldlines--;1586 newlines--;1587if(!deleted && !added)1588 leading++;1589 trailing++;1590if(!apply_in_reverse &&1591 ws_error_action == correct_ws_error)1592check_whitespace(line, len, patch->ws_rule);1593break;1594case'-':1595if(apply_in_reverse &&1596 ws_error_action != nowarn_ws_error)1597check_whitespace(line, len, patch->ws_rule);1598 deleted++;1599 oldlines--;1600 trailing =0;1601break;1602case'+':1603if(!apply_in_reverse &&1604 ws_error_action != nowarn_ws_error)1605check_whitespace(line, len, patch->ws_rule);1606 added++;1607 newlines--;1608 trailing =0;1609break;16101611/*1612 * We allow "\ No newline at end of file". Depending1613 * on locale settings when the patch was produced we1614 * don't know what this line looks like. The only1615 * thing we do know is that it begins with "\ ".1616 * Checking for 12 is just for sanity check -- any1617 * l10n of "\ No newline..." is at least that long.1618 */1619case'\\':1620if(len <12||memcmp(line,"\\",2))1621return-1;1622break;1623}1624}1625if(oldlines || newlines)1626return-1;1627if(!deleted && !added)1628return-1;16291630 fragment->leading = leading;1631 fragment->trailing = trailing;16321633/*1634 * If a fragment ends with an incomplete line, we failed to include1635 * it in the above loop because we hit oldlines == newlines == 01636 * before seeing it.1637 */1638if(12< size && !memcmp(line,"\\",2))1639 offset +=linelen(line, size);16401641 patch->lines_added += added;1642 patch->lines_deleted += deleted;16431644if(0< patch->is_new && oldlines)1645returnerror(_("new file depends on old contents"));1646if(0< patch->is_delete && newlines)1647returnerror(_("deleted file still has contents"));1648return offset;1649}16501651/*1652 * We have seen "diff --git a/... b/..." header (or a traditional patch1653 * header). Read hunks that belong to this patch into fragments and hang1654 * them to the given patch structure.1655 *1656 * The (fragment->patch, fragment->size) pair points into the memory given1657 * by the caller, not a copy, when we return.1658 */1659static intparse_single_patch(const char*line,unsigned long size,struct patch *patch)1660{1661unsigned long offset =0;1662unsigned long oldlines =0, newlines =0, context =0;1663struct fragment **fragp = &patch->fragments;16641665while(size >4&& !memcmp(line,"@@ -",4)) {1666struct fragment *fragment;1667int len;16681669 fragment =xcalloc(1,sizeof(*fragment));1670 fragment->linenr = state_linenr;1671 len =parse_fragment(line, size, patch, fragment);1672if(len <=0)1673die(_("corrupt patch at line%d"), state_linenr);1674 fragment->patch = line;1675 fragment->size = len;1676 oldlines += fragment->oldlines;1677 newlines += fragment->newlines;1678 context += fragment->leading + fragment->trailing;16791680*fragp = fragment;1681 fragp = &fragment->next;16821683 offset += len;1684 line += len;1685 size -= len;1686}16871688/*1689 * If something was removed (i.e. we have old-lines) it cannot1690 * be creation, and if something was added it cannot be1691 * deletion. However, the reverse is not true; --unified=01692 * patches that only add are not necessarily creation even1693 * though they do not have any old lines, and ones that only1694 * delete are not necessarily deletion.1695 *1696 * Unfortunately, a real creation/deletion patch do _not_ have1697 * any context line by definition, so we cannot safely tell it1698 * apart with --unified=0 insanity. At least if the patch has1699 * more than one hunk it is not creation or deletion.1700 */1701if(patch->is_new <0&&1702(oldlines || (patch->fragments && patch->fragments->next)))1703 patch->is_new =0;1704if(patch->is_delete <0&&1705(newlines || (patch->fragments && patch->fragments->next)))1706 patch->is_delete =0;17071708if(0< patch->is_new && oldlines)1709die(_("new file%sdepends on old contents"), patch->new_name);1710if(0< patch->is_delete && newlines)1711die(_("deleted file%sstill has contents"), patch->old_name);1712if(!patch->is_delete && !newlines && context)1713fprintf_ln(stderr,1714_("** warning: "1715"file%sbecomes empty but is not deleted"),1716 patch->new_name);17171718return offset;1719}17201721staticinlineintmetadata_changes(struct patch *patch)1722{1723return patch->is_rename >0||1724 patch->is_copy >0||1725 patch->is_new >0||1726 patch->is_delete ||1727(patch->old_mode && patch->new_mode &&1728 patch->old_mode != patch->new_mode);1729}17301731static char*inflate_it(const void*data,unsigned long size,1732unsigned long inflated_size)1733{1734 git_zstream stream;1735void*out;1736int st;17371738memset(&stream,0,sizeof(stream));17391740 stream.next_in = (unsigned char*)data;1741 stream.avail_in = size;1742 stream.next_out = out =xmalloc(inflated_size);1743 stream.avail_out = inflated_size;1744git_inflate_init(&stream);1745 st =git_inflate(&stream, Z_FINISH);1746git_inflate_end(&stream);1747if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1748free(out);1749return NULL;1750}1751return out;1752}17531754/*1755 * Read a binary hunk and return a new fragment; fragment->patch1756 * points at an allocated memory that the caller must free, so1757 * it is marked as "->free_patch = 1".1758 */1759static struct fragment *parse_binary_hunk(char**buf_p,1760unsigned long*sz_p,1761int*status_p,1762int*used_p)1763{1764/*1765 * Expect a line that begins with binary patch method ("literal"1766 * or "delta"), followed by the length of data before deflating.1767 * a sequence of 'length-byte' followed by base-85 encoded data1768 * should follow, terminated by a newline.1769 *1770 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1771 * and we would limit the patch line to 66 characters,1772 * so one line can fit up to 13 groups that would decode1773 * to 52 bytes max. The length byte 'A'-'Z' corresponds1774 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1775 */1776int llen, used;1777unsigned long size = *sz_p;1778char*buffer = *buf_p;1779int patch_method;1780unsigned long origlen;1781char*data = NULL;1782int hunk_size =0;1783struct fragment *frag;17841785 llen =linelen(buffer, size);1786 used = llen;17871788*status_p =0;17891790if(starts_with(buffer,"delta ")) {1791 patch_method = BINARY_DELTA_DEFLATED;1792 origlen =strtoul(buffer +6, NULL,10);1793}1794else if(starts_with(buffer,"literal ")) {1795 patch_method = BINARY_LITERAL_DEFLATED;1796 origlen =strtoul(buffer +8, NULL,10);1797}1798else1799return NULL;18001801 state_linenr++;1802 buffer += llen;1803while(1) {1804int byte_length, max_byte_length, newsize;1805 llen =linelen(buffer, size);1806 used += llen;1807 state_linenr++;1808if(llen ==1) {1809/* consume the blank line */1810 buffer++;1811 size--;1812break;1813}1814/*1815 * Minimum line is "A00000\n" which is 7-byte long,1816 * and the line length must be multiple of 5 plus 2.1817 */1818if((llen <7) || (llen-2) %5)1819goto corrupt;1820 max_byte_length = (llen -2) /5*4;1821 byte_length = *buffer;1822if('A'<= byte_length && byte_length <='Z')1823 byte_length = byte_length -'A'+1;1824else if('a'<= byte_length && byte_length <='z')1825 byte_length = byte_length -'a'+27;1826else1827goto corrupt;1828/* if the input length was not multiple of 4, we would1829 * have filler at the end but the filler should never1830 * exceed 3 bytes1831 */1832if(max_byte_length < byte_length ||1833 byte_length <= max_byte_length -4)1834goto corrupt;1835 newsize = hunk_size + byte_length;1836 data =xrealloc(data, newsize);1837if(decode_85(data + hunk_size, buffer +1, byte_length))1838goto corrupt;1839 hunk_size = newsize;1840 buffer += llen;1841 size -= llen;1842}18431844 frag =xcalloc(1,sizeof(*frag));1845 frag->patch =inflate_it(data, hunk_size, origlen);1846 frag->free_patch =1;1847if(!frag->patch)1848goto corrupt;1849free(data);1850 frag->size = origlen;1851*buf_p = buffer;1852*sz_p = size;1853*used_p = used;1854 frag->binary_patch_method = patch_method;1855return frag;18561857 corrupt:1858free(data);1859*status_p = -1;1860error(_("corrupt binary patch at line%d: %.*s"),1861 state_linenr-1, llen-1, buffer);1862return NULL;1863}18641865/*1866 * Returns:1867 * -1 in case of error,1868 * the length of the parsed binary patch otherwise1869 */1870static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1871{1872/*1873 * We have read "GIT binary patch\n"; what follows is a line1874 * that says the patch method (currently, either "literal" or1875 * "delta") and the length of data before deflating; a1876 * sequence of 'length-byte' followed by base-85 encoded data1877 * follows.1878 *1879 * When a binary patch is reversible, there is another binary1880 * hunk in the same format, starting with patch method (either1881 * "literal" or "delta") with the length of data, and a sequence1882 * of length-byte + base-85 encoded data, terminated with another1883 * empty line. This data, when applied to the postimage, produces1884 * the preimage.1885 */1886struct fragment *forward;1887struct fragment *reverse;1888int status;1889int used, used_1;18901891 forward =parse_binary_hunk(&buffer, &size, &status, &used);1892if(!forward && !status)1893/* there has to be one hunk (forward hunk) */1894returnerror(_("unrecognized binary patch at line%d"), state_linenr-1);1895if(status)1896/* otherwise we already gave an error message */1897return status;18981899 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1900if(reverse)1901 used += used_1;1902else if(status) {1903/*1904 * Not having reverse hunk is not an error, but having1905 * a corrupt reverse hunk is.1906 */1907free((void*) forward->patch);1908free(forward);1909return status;1910}1911 forward->next = reverse;1912 patch->fragments = forward;1913 patch->is_binary =1;1914return used;1915}19161917static voidprefix_one(char**name)1918{1919char*old_name = *name;1920if(!old_name)1921return;1922*name =xstrdup(prefix_filename(prefix, prefix_length, *name));1923free(old_name);1924}19251926static voidprefix_patch(struct patch *p)1927{1928if(!prefix || p->is_toplevel_relative)1929return;1930prefix_one(&p->new_name);1931prefix_one(&p->old_name);1932}19331934/*1935 * include/exclude1936 */19371938static struct string_list limit_by_name;1939static int has_include;1940static voidadd_name_limit(const char*name,int exclude)1941{1942struct string_list_item *it;19431944 it =string_list_append(&limit_by_name, name);1945 it->util = exclude ? NULL : (void*)1;1946}19471948static intuse_patch(struct patch *p)1949{1950const char*pathname = p->new_name ? p->new_name : p->old_name;1951int i;19521953/* Paths outside are not touched regardless of "--include" */1954if(0< prefix_length) {1955int pathlen =strlen(pathname);1956if(pathlen <= prefix_length ||1957memcmp(prefix, pathname, prefix_length))1958return0;1959}19601961/* See if it matches any of exclude/include rule */1962for(i =0; i < limit_by_name.nr; i++) {1963struct string_list_item *it = &limit_by_name.items[i];1964if(!wildmatch(it->string, pathname,0, NULL))1965return(it->util != NULL);1966}19671968/*1969 * If we had any include, a path that does not match any rule is1970 * not used. Otherwise, we saw bunch of exclude rules (or none)1971 * and such a path is used.1972 */1973return!has_include;1974}197519761977/*1978 * Read the patch text in "buffer" that extends for "size" bytes; stop1979 * reading after seeing a single patch (i.e. changes to a single file).1980 * Create fragments (i.e. patch hunks) and hang them to the given patch.1981 * Return the number of bytes consumed, so that the caller can call us1982 * again for the next patch.1983 */1984static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1985{1986int hdrsize, patchsize;1987int offset =find_header(buffer, size, &hdrsize, patch);19881989if(offset <0)1990return offset;19911992prefix_patch(patch);19931994if(!use_patch(patch))1995 patch->ws_rule =0;1996else1997 patch->ws_rule =whitespace_rule(patch->new_name1998? patch->new_name1999: patch->old_name);20002001 patchsize =parse_single_patch(buffer + offset + hdrsize,2002 size - offset - hdrsize, patch);20032004if(!patchsize) {2005static const char git_binary[] ="GIT binary patch\n";2006int hd = hdrsize + offset;2007unsigned long llen =linelen(buffer + hd, size - hd);20082009if(llen ==sizeof(git_binary) -1&&2010!memcmp(git_binary, buffer + hd, llen)) {2011int used;2012 state_linenr++;2013 used =parse_binary(buffer + hd + llen,2014 size - hd - llen, patch);2015if(used <0)2016return-1;2017if(used)2018 patchsize = used + llen;2019else2020 patchsize =0;2021}2022else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2023static const char*binhdr[] = {2024"Binary files ",2025"Files ",2026 NULL,2027};2028int i;2029for(i =0; binhdr[i]; i++) {2030int len =strlen(binhdr[i]);2031if(len < size - hd &&2032!memcmp(binhdr[i], buffer + hd, len)) {2033 state_linenr++;2034 patch->is_binary =1;2035 patchsize = llen;2036break;2037}2038}2039}20402041/* Empty patch cannot be applied if it is a text patch2042 * without metadata change. A binary patch appears2043 * empty to us here.2044 */2045if((apply || check) &&2046(!patch->is_binary && !metadata_changes(patch)))2047die(_("patch with only garbage at line%d"), state_linenr);2048}20492050return offset + hdrsize + patchsize;2051}20522053#define swap(a,b) myswap((a),(b),sizeof(a))20542055#define myswap(a, b, size) do { \2056 unsigned char mytmp[size]; \2057 memcpy(mytmp, &a, size); \2058 memcpy(&a, &b, size); \2059 memcpy(&b, mytmp, size); \2060} while (0)20612062static voidreverse_patches(struct patch *p)2063{2064for(; p; p = p->next) {2065struct fragment *frag = p->fragments;20662067swap(p->new_name, p->old_name);2068swap(p->new_mode, p->old_mode);2069swap(p->is_new, p->is_delete);2070swap(p->lines_added, p->lines_deleted);2071swap(p->old_sha1_prefix, p->new_sha1_prefix);20722073for(; frag; frag = frag->next) {2074swap(frag->newpos, frag->oldpos);2075swap(frag->newlines, frag->oldlines);2076}2077}2078}20792080static const char pluses[] =2081"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2082static const char minuses[]=2083"----------------------------------------------------------------------";20842085static voidshow_stats(struct patch *patch)2086{2087struct strbuf qname = STRBUF_INIT;2088char*cp = patch->new_name ? patch->new_name : patch->old_name;2089int max, add, del;20902091quote_c_style(cp, &qname, NULL,0);20922093/*2094 * "scale" the filename2095 */2096 max = max_len;2097if(max >50)2098 max =50;20992100if(qname.len > max) {2101 cp =strchr(qname.buf + qname.len +3- max,'/');2102if(!cp)2103 cp = qname.buf + qname.len +3- max;2104strbuf_splice(&qname,0, cp - qname.buf,"...",3);2105}21062107if(patch->is_binary) {2108printf(" %-*s | Bin\n", max, qname.buf);2109strbuf_release(&qname);2110return;2111}21122113printf(" %-*s |", max, qname.buf);2114strbuf_release(&qname);21152116/*2117 * scale the add/delete2118 */2119 max = max + max_change >70?70- max : max_change;2120 add = patch->lines_added;2121 del = patch->lines_deleted;21222123if(max_change >0) {2124int total = ((add + del) * max + max_change /2) / max_change;2125 add = (add * max + max_change /2) / max_change;2126 del = total - add;2127}2128printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2129 add, pluses, del, minuses);2130}21312132static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2133{2134switch(st->st_mode & S_IFMT) {2135case S_IFLNK:2136if(strbuf_readlink(buf, path, st->st_size) <0)2137returnerror(_("unable to read symlink%s"), path);2138return0;2139case S_IFREG:2140if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2141returnerror(_("unable to open or read%s"), path);2142convert_to_git(path, buf->buf, buf->len, buf,0);2143return0;2144default:2145return-1;2146}2147}21482149/*2150 * Update the preimage, and the common lines in postimage,2151 * from buffer buf of length len. If postlen is 0 the postimage2152 * is updated in place, otherwise it's updated on a new buffer2153 * of length postlen2154 */21552156static voidupdate_pre_post_images(struct image *preimage,2157struct image *postimage,2158char*buf,2159size_t len,size_t postlen)2160{2161int i, ctx, reduced;2162char*new, *old, *fixed;2163struct image fixed_preimage;21642165/*2166 * Update the preimage with whitespace fixes. Note that we2167 * are not losing preimage->buf -- apply_one_fragment() will2168 * free "oldlines".2169 */2170prepare_image(&fixed_preimage, buf, len,1);2171assert(postlen2172? fixed_preimage.nr == preimage->nr2173: fixed_preimage.nr <= preimage->nr);2174for(i =0; i < fixed_preimage.nr; i++)2175 fixed_preimage.line[i].flag = preimage->line[i].flag;2176free(preimage->line_allocated);2177*preimage = fixed_preimage;21782179/*2180 * Adjust the common context lines in postimage. This can be2181 * done in-place when we are shrinking it with whitespace2182 * fixing, but needs a new buffer when ignoring whitespace or2183 * expanding leading tabs to spaces.2184 *2185 * We trust the caller to tell us if the update can be done2186 * in place (postlen==0) or not.2187 */2188 old = postimage->buf;2189if(postlen)2190new= postimage->buf =xmalloc(postlen);2191else2192new= old;2193 fixed = preimage->buf;21942195for(i = reduced = ctx =0; i < postimage->nr; i++) {2196size_t l_len = postimage->line[i].len;2197if(!(postimage->line[i].flag & LINE_COMMON)) {2198/* an added line -- no counterparts in preimage */2199memmove(new, old, l_len);2200 old += l_len;2201new+= l_len;2202continue;2203}22042205/* a common context -- skip it in the original postimage */2206 old += l_len;22072208/* and find the corresponding one in the fixed preimage */2209while(ctx < preimage->nr &&2210!(preimage->line[ctx].flag & LINE_COMMON)) {2211 fixed += preimage->line[ctx].len;2212 ctx++;2213}22142215/*2216 * preimage is expected to run out, if the caller2217 * fixed addition of trailing blank lines.2218 */2219if(preimage->nr <= ctx) {2220 reduced++;2221continue;2222}22232224/* and copy it in, while fixing the line length */2225 l_len = preimage->line[ctx].len;2226memcpy(new, fixed, l_len);2227new+= l_len;2228 fixed += l_len;2229 postimage->line[i].len = l_len;2230 ctx++;2231}22322233if(postlen2234? postlen <new- postimage->buf2235: postimage->len <new- postimage->buf)2236die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2237(int)postlen, (int) postimage->len, (int)(new- postimage->buf));22382239/* Fix the length of the whole thing */2240 postimage->len =new- postimage->buf;2241 postimage->nr -= reduced;2242}22432244static intline_by_line_fuzzy_match(struct image *img,2245struct image *preimage,2246struct image *postimage,2247unsigned longtry,2248int try_lno,2249int preimage_limit)2250{2251int i;2252size_t imgoff =0;2253size_t preoff =0;2254size_t postlen = postimage->len;2255size_t extra_chars;2256char*buf;2257char*preimage_eof;2258char*preimage_end;2259struct strbuf fixed;2260char*fixed_buf;2261size_t fixed_len;22622263for(i =0; i < preimage_limit; i++) {2264size_t prelen = preimage->line[i].len;2265size_t imglen = img->line[try_lno+i].len;22662267if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2268 preimage->buf + preoff, prelen))2269return0;2270if(preimage->line[i].flag & LINE_COMMON)2271 postlen += imglen - prelen;2272 imgoff += imglen;2273 preoff += prelen;2274}22752276/*2277 * Ok, the preimage matches with whitespace fuzz.2278 *2279 * imgoff now holds the true length of the target that2280 * matches the preimage before the end of the file.2281 *2282 * Count the number of characters in the preimage that fall2283 * beyond the end of the file and make sure that all of them2284 * are whitespace characters. (This can only happen if2285 * we are removing blank lines at the end of the file.)2286 */2287 buf = preimage_eof = preimage->buf + preoff;2288for( ; i < preimage->nr; i++)2289 preoff += preimage->line[i].len;2290 preimage_end = preimage->buf + preoff;2291for( ; buf < preimage_end; buf++)2292if(!isspace(*buf))2293return0;22942295/*2296 * Update the preimage and the common postimage context2297 * lines to use the same whitespace as the target.2298 * If whitespace is missing in the target (i.e.2299 * if the preimage extends beyond the end of the file),2300 * use the whitespace from the preimage.2301 */2302 extra_chars = preimage_end - preimage_eof;2303strbuf_init(&fixed, imgoff + extra_chars);2304strbuf_add(&fixed, img->buf +try, imgoff);2305strbuf_add(&fixed, preimage_eof, extra_chars);2306 fixed_buf =strbuf_detach(&fixed, &fixed_len);2307update_pre_post_images(preimage, postimage,2308 fixed_buf, fixed_len, postlen);2309return1;2310}23112312static intmatch_fragment(struct image *img,2313struct image *preimage,2314struct image *postimage,2315unsigned longtry,2316int try_lno,2317unsigned ws_rule,2318int match_beginning,int match_end)2319{2320int i;2321char*fixed_buf, *buf, *orig, *target;2322struct strbuf fixed;2323size_t fixed_len, postlen;2324int preimage_limit;23252326if(preimage->nr + try_lno <= img->nr) {2327/*2328 * The hunk falls within the boundaries of img.2329 */2330 preimage_limit = preimage->nr;2331if(match_end && (preimage->nr + try_lno != img->nr))2332return0;2333}else if(ws_error_action == correct_ws_error &&2334(ws_rule & WS_BLANK_AT_EOF)) {2335/*2336 * This hunk extends beyond the end of img, and we are2337 * removing blank lines at the end of the file. This2338 * many lines from the beginning of the preimage must2339 * match with img, and the remainder of the preimage2340 * must be blank.2341 */2342 preimage_limit = img->nr - try_lno;2343}else{2344/*2345 * The hunk extends beyond the end of the img and2346 * we are not removing blanks at the end, so we2347 * should reject the hunk at this position.2348 */2349return0;2350}23512352if(match_beginning && try_lno)2353return0;23542355/* Quick hash check */2356for(i =0; i < preimage_limit; i++)2357if((img->line[try_lno + i].flag & LINE_PATCHED) ||2358(preimage->line[i].hash != img->line[try_lno + i].hash))2359return0;23602361if(preimage_limit == preimage->nr) {2362/*2363 * Do we have an exact match? If we were told to match2364 * at the end, size must be exactly at try+fragsize,2365 * otherwise try+fragsize must be still within the preimage,2366 * and either case, the old piece should match the preimage2367 * exactly.2368 */2369if((match_end2370? (try+ preimage->len == img->len)2371: (try+ preimage->len <= img->len)) &&2372!memcmp(img->buf +try, preimage->buf, preimage->len))2373return1;2374}else{2375/*2376 * The preimage extends beyond the end of img, so2377 * there cannot be an exact match.2378 *2379 * There must be one non-blank context line that match2380 * a line before the end of img.2381 */2382char*buf_end;23832384 buf = preimage->buf;2385 buf_end = buf;2386for(i =0; i < preimage_limit; i++)2387 buf_end += preimage->line[i].len;23882389for( ; buf < buf_end; buf++)2390if(!isspace(*buf))2391break;2392if(buf == buf_end)2393return0;2394}23952396/*2397 * No exact match. If we are ignoring whitespace, run a line-by-line2398 * fuzzy matching. We collect all the line length information because2399 * we need it to adjust whitespace if we match.2400 */2401if(ws_ignore_action == ignore_ws_change)2402returnline_by_line_fuzzy_match(img, preimage, postimage,2403try, try_lno, preimage_limit);24042405if(ws_error_action != correct_ws_error)2406return0;24072408/*2409 * The hunk does not apply byte-by-byte, but the hash says2410 * it might with whitespace fuzz. We weren't asked to2411 * ignore whitespace, we were asked to correct whitespace2412 * errors, so let's try matching after whitespace correction.2413 *2414 * While checking the preimage against the target, whitespace2415 * errors in both fixed, we count how large the corresponding2416 * postimage needs to be. The postimage prepared by2417 * apply_one_fragment() has whitespace errors fixed on added2418 * lines already, but the common lines were propagated as-is,2419 * which may become longer when their whitespace errors are2420 * fixed.2421 */24222423/* First count added lines in postimage */2424 postlen =0;2425for(i =0; i < postimage->nr; i++) {2426if(!(postimage->line[i].flag & LINE_COMMON))2427 postlen += postimage->line[i].len;2428}24292430/*2431 * The preimage may extend beyond the end of the file,2432 * but in this loop we will only handle the part of the2433 * preimage that falls within the file.2434 */2435strbuf_init(&fixed, preimage->len +1);2436 orig = preimage->buf;2437 target = img->buf +try;2438for(i =0; i < preimage_limit; i++) {2439size_t oldlen = preimage->line[i].len;2440size_t tgtlen = img->line[try_lno + i].len;2441size_t fixstart = fixed.len;2442struct strbuf tgtfix;2443int match;24442445/* Try fixing the line in the preimage */2446ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24472448/* Try fixing the line in the target */2449strbuf_init(&tgtfix, tgtlen);2450ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);24512452/*2453 * If they match, either the preimage was based on2454 * a version before our tree fixed whitespace breakage,2455 * or we are lacking a whitespace-fix patch the tree2456 * the preimage was based on already had (i.e. target2457 * has whitespace breakage, the preimage doesn't).2458 * In either case, we are fixing the whitespace breakages2459 * so we might as well take the fix together with their2460 * real change.2461 */2462 match = (tgtfix.len == fixed.len - fixstart &&2463!memcmp(tgtfix.buf, fixed.buf + fixstart,2464 fixed.len - fixstart));24652466/* Add the length if this is common with the postimage */2467if(preimage->line[i].flag & LINE_COMMON)2468 postlen += tgtfix.len;24692470strbuf_release(&tgtfix);2471if(!match)2472goto unmatch_exit;24732474 orig += oldlen;2475 target += tgtlen;2476}247724782479/*2480 * Now handle the lines in the preimage that falls beyond the2481 * end of the file (if any). They will only match if they are2482 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2483 * false).2484 */2485for( ; i < preimage->nr; i++) {2486size_t fixstart = fixed.len;/* start of the fixed preimage */2487size_t oldlen = preimage->line[i].len;2488int j;24892490/* Try fixing the line in the preimage */2491ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24922493for(j = fixstart; j < fixed.len; j++)2494if(!isspace(fixed.buf[j]))2495goto unmatch_exit;24962497 orig += oldlen;2498}24992500/*2501 * Yes, the preimage is based on an older version that still2502 * has whitespace breakages unfixed, and fixing them makes the2503 * hunk match. Update the context lines in the postimage.2504 */2505 fixed_buf =strbuf_detach(&fixed, &fixed_len);2506if(postlen < postimage->len)2507 postlen =0;2508update_pre_post_images(preimage, postimage,2509 fixed_buf, fixed_len, postlen);2510return1;25112512 unmatch_exit:2513strbuf_release(&fixed);2514return0;2515}25162517static intfind_pos(struct image *img,2518struct image *preimage,2519struct image *postimage,2520int line,2521unsigned ws_rule,2522int match_beginning,int match_end)2523{2524int i;2525unsigned long backwards, forwards,try;2526int backwards_lno, forwards_lno, try_lno;25272528/*2529 * If match_beginning or match_end is specified, there is no2530 * point starting from a wrong line that will never match and2531 * wander around and wait for a match at the specified end.2532 */2533if(match_beginning)2534 line =0;2535else if(match_end)2536 line = img->nr - preimage->nr;25372538/*2539 * Because the comparison is unsigned, the following test2540 * will also take care of a negative line number that can2541 * result when match_end and preimage is larger than the target.2542 */2543if((size_t) line > img->nr)2544 line = img->nr;25452546try=0;2547for(i =0; i < line; i++)2548try+= img->line[i].len;25492550/*2551 * There's probably some smart way to do this, but I'll leave2552 * that to the smart and beautiful people. I'm simple and stupid.2553 */2554 backwards =try;2555 backwards_lno = line;2556 forwards =try;2557 forwards_lno = line;2558 try_lno = line;25592560for(i =0; ; i++) {2561if(match_fragment(img, preimage, postimage,2562try, try_lno, ws_rule,2563 match_beginning, match_end))2564return try_lno;25652566 again:2567if(backwards_lno ==0&& forwards_lno == img->nr)2568break;25692570if(i &1) {2571if(backwards_lno ==0) {2572 i++;2573goto again;2574}2575 backwards_lno--;2576 backwards -= img->line[backwards_lno].len;2577try= backwards;2578 try_lno = backwards_lno;2579}else{2580if(forwards_lno == img->nr) {2581 i++;2582goto again;2583}2584 forwards += img->line[forwards_lno].len;2585 forwards_lno++;2586try= forwards;2587 try_lno = forwards_lno;2588}25892590}2591return-1;2592}25932594static voidremove_first_line(struct image *img)2595{2596 img->buf += img->line[0].len;2597 img->len -= img->line[0].len;2598 img->line++;2599 img->nr--;2600}26012602static voidremove_last_line(struct image *img)2603{2604 img->len -= img->line[--img->nr].len;2605}26062607/*2608 * The change from "preimage" and "postimage" has been found to2609 * apply at applied_pos (counts in line numbers) in "img".2610 * Update "img" to remove "preimage" and replace it with "postimage".2611 */2612static voidupdate_image(struct image *img,2613int applied_pos,2614struct image *preimage,2615struct image *postimage)2616{2617/*2618 * remove the copy of preimage at offset in img2619 * and replace it with postimage2620 */2621int i, nr;2622size_t remove_count, insert_count, applied_at =0;2623char*result;2624int preimage_limit;26252626/*2627 * If we are removing blank lines at the end of img,2628 * the preimage may extend beyond the end.2629 * If that is the case, we must be careful only to2630 * remove the part of the preimage that falls within2631 * the boundaries of img. Initialize preimage_limit2632 * to the number of lines in the preimage that falls2633 * within the boundaries.2634 */2635 preimage_limit = preimage->nr;2636if(preimage_limit > img->nr - applied_pos)2637 preimage_limit = img->nr - applied_pos;26382639for(i =0; i < applied_pos; i++)2640 applied_at += img->line[i].len;26412642 remove_count =0;2643for(i =0; i < preimage_limit; i++)2644 remove_count += img->line[applied_pos + i].len;2645 insert_count = postimage->len;26462647/* Adjust the contents */2648 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2649memcpy(result, img->buf, applied_at);2650memcpy(result + applied_at, postimage->buf, postimage->len);2651memcpy(result + applied_at + postimage->len,2652 img->buf + (applied_at + remove_count),2653 img->len - (applied_at + remove_count));2654free(img->buf);2655 img->buf = result;2656 img->len += insert_count - remove_count;2657 result[img->len] ='\0';26582659/* Adjust the line table */2660 nr = img->nr + postimage->nr - preimage_limit;2661if(preimage_limit < postimage->nr) {2662/*2663 * NOTE: this knows that we never call remove_first_line()2664 * on anything other than pre/post image.2665 */2666REALLOC_ARRAY(img->line, nr);2667 img->line_allocated = img->line;2668}2669if(preimage_limit != postimage->nr)2670memmove(img->line + applied_pos + postimage->nr,2671 img->line + applied_pos + preimage_limit,2672(img->nr - (applied_pos + preimage_limit)) *2673sizeof(*img->line));2674memcpy(img->line + applied_pos,2675 postimage->line,2676 postimage->nr *sizeof(*img->line));2677if(!allow_overlap)2678for(i =0; i < postimage->nr; i++)2679 img->line[applied_pos + i].flag |= LINE_PATCHED;2680 img->nr = nr;2681}26822683/*2684 * Use the patch-hunk text in "frag" to prepare two images (preimage and2685 * postimage) for the hunk. Find lines that match "preimage" in "img" and2686 * replace the part of "img" with "postimage" text.2687 */2688static intapply_one_fragment(struct image *img,struct fragment *frag,2689int inaccurate_eof,unsigned ws_rule,2690int nth_fragment)2691{2692int match_beginning, match_end;2693const char*patch = frag->patch;2694int size = frag->size;2695char*old, *oldlines;2696struct strbuf newlines;2697int new_blank_lines_at_end =0;2698int found_new_blank_lines_at_end =0;2699int hunk_linenr = frag->linenr;2700unsigned long leading, trailing;2701int pos, applied_pos;2702struct image preimage;2703struct image postimage;27042705memset(&preimage,0,sizeof(preimage));2706memset(&postimage,0,sizeof(postimage));2707 oldlines =xmalloc(size);2708strbuf_init(&newlines, size);27092710 old = oldlines;2711while(size >0) {2712char first;2713int len =linelen(patch, size);2714int plen;2715int added_blank_line =0;2716int is_blank_context =0;2717size_t start;27182719if(!len)2720break;27212722/*2723 * "plen" is how much of the line we should use for2724 * the actual patch data. Normally we just remove the2725 * first character on the line, but if the line is2726 * followed by "\ No newline", then we also remove the2727 * last one (which is the newline, of course).2728 */2729 plen = len -1;2730if(len < size && patch[len] =='\\')2731 plen--;2732 first = *patch;2733if(apply_in_reverse) {2734if(first =='-')2735 first ='+';2736else if(first =='+')2737 first ='-';2738}27392740switch(first) {2741case'\n':2742/* Newer GNU diff, empty context line */2743if(plen <0)2744/* ... followed by '\No newline'; nothing */2745break;2746*old++ ='\n';2747strbuf_addch(&newlines,'\n');2748add_line_info(&preimage,"\n",1, LINE_COMMON);2749add_line_info(&postimage,"\n",1, LINE_COMMON);2750 is_blank_context =1;2751break;2752case' ':2753if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2754ws_blank_line(patch +1, plen, ws_rule))2755 is_blank_context =1;2756case'-':2757memcpy(old, patch +1, plen);2758add_line_info(&preimage, old, plen,2759(first ==' '? LINE_COMMON :0));2760 old += plen;2761if(first =='-')2762break;2763/* Fall-through for ' ' */2764case'+':2765/* --no-add does not add new lines */2766if(first =='+'&& no_add)2767break;27682769 start = newlines.len;2770if(first !='+'||2771!whitespace_error ||2772 ws_error_action != correct_ws_error) {2773strbuf_add(&newlines, patch +1, plen);2774}2775else{2776ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2777}2778add_line_info(&postimage, newlines.buf + start, newlines.len - start,2779(first =='+'?0: LINE_COMMON));2780if(first =='+'&&2781(ws_rule & WS_BLANK_AT_EOF) &&2782ws_blank_line(patch +1, plen, ws_rule))2783 added_blank_line =1;2784break;2785case'@':case'\\':2786/* Ignore it, we already handled it */2787break;2788default:2789if(apply_verbosely)2790error(_("invalid start of line: '%c'"), first);2791 applied_pos = -1;2792goto out;2793}2794if(added_blank_line) {2795if(!new_blank_lines_at_end)2796 found_new_blank_lines_at_end = hunk_linenr;2797 new_blank_lines_at_end++;2798}2799else if(is_blank_context)2800;2801else2802 new_blank_lines_at_end =0;2803 patch += len;2804 size -= len;2805 hunk_linenr++;2806}2807if(inaccurate_eof &&2808 old > oldlines && old[-1] =='\n'&&2809 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2810 old--;2811strbuf_setlen(&newlines, newlines.len -1);2812}28132814 leading = frag->leading;2815 trailing = frag->trailing;28162817/*2818 * A hunk to change lines at the beginning would begin with2819 * @@ -1,L +N,M @@2820 * but we need to be careful. -U0 that inserts before the second2821 * line also has this pattern.2822 *2823 * And a hunk to add to an empty file would begin with2824 * @@ -0,0 +N,M @@2825 *2826 * In other words, a hunk that is (frag->oldpos <= 1) with or2827 * without leading context must match at the beginning.2828 */2829 match_beginning = (!frag->oldpos ||2830(frag->oldpos ==1&& !unidiff_zero));28312832/*2833 * A hunk without trailing lines must match at the end.2834 * However, we simply cannot tell if a hunk must match end2835 * from the lack of trailing lines if the patch was generated2836 * with unidiff without any context.2837 */2838 match_end = !unidiff_zero && !trailing;28392840 pos = frag->newpos ? (frag->newpos -1) :0;2841 preimage.buf = oldlines;2842 preimage.len = old - oldlines;2843 postimage.buf = newlines.buf;2844 postimage.len = newlines.len;2845 preimage.line = preimage.line_allocated;2846 postimage.line = postimage.line_allocated;28472848for(;;) {28492850 applied_pos =find_pos(img, &preimage, &postimage, pos,2851 ws_rule, match_beginning, match_end);28522853if(applied_pos >=0)2854break;28552856/* Am I at my context limits? */2857if((leading <= p_context) && (trailing <= p_context))2858break;2859if(match_beginning || match_end) {2860 match_beginning = match_end =0;2861continue;2862}28632864/*2865 * Reduce the number of context lines; reduce both2866 * leading and trailing if they are equal otherwise2867 * just reduce the larger context.2868 */2869if(leading >= trailing) {2870remove_first_line(&preimage);2871remove_first_line(&postimage);2872 pos--;2873 leading--;2874}2875if(trailing > leading) {2876remove_last_line(&preimage);2877remove_last_line(&postimage);2878 trailing--;2879}2880}28812882if(applied_pos >=0) {2883if(new_blank_lines_at_end &&2884 preimage.nr + applied_pos >= img->nr &&2885(ws_rule & WS_BLANK_AT_EOF) &&2886 ws_error_action != nowarn_ws_error) {2887record_ws_error(WS_BLANK_AT_EOF,"+",1,2888 found_new_blank_lines_at_end);2889if(ws_error_action == correct_ws_error) {2890while(new_blank_lines_at_end--)2891remove_last_line(&postimage);2892}2893/*2894 * We would want to prevent write_out_results()2895 * from taking place in apply_patch() that follows2896 * the callchain led us here, which is:2897 * apply_patch->check_patch_list->check_patch->2898 * apply_data->apply_fragments->apply_one_fragment2899 */2900if(ws_error_action == die_on_ws_error)2901 apply =0;2902}29032904if(apply_verbosely && applied_pos != pos) {2905int offset = applied_pos - pos;2906if(apply_in_reverse)2907 offset =0- offset;2908fprintf_ln(stderr,2909Q_("Hunk #%dsucceeded at%d(offset%dline).",2910"Hunk #%dsucceeded at%d(offset%dlines).",2911 offset),2912 nth_fragment, applied_pos +1, offset);2913}29142915/*2916 * Warn if it was necessary to reduce the number2917 * of context lines.2918 */2919if((leading != frag->leading) ||2920(trailing != frag->trailing))2921fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2922" to apply fragment at%d"),2923 leading, trailing, applied_pos+1);2924update_image(img, applied_pos, &preimage, &postimage);2925}else{2926if(apply_verbosely)2927error(_("while searching for:\n%.*s"),2928(int)(old - oldlines), oldlines);2929}29302931out:2932free(oldlines);2933strbuf_release(&newlines);2934free(preimage.line_allocated);2935free(postimage.line_allocated);29362937return(applied_pos <0);2938}29392940static intapply_binary_fragment(struct image *img,struct patch *patch)2941{2942struct fragment *fragment = patch->fragments;2943unsigned long len;2944void*dst;29452946if(!fragment)2947returnerror(_("missing binary patch data for '%s'"),2948 patch->new_name ?2949 patch->new_name :2950 patch->old_name);29512952/* Binary patch is irreversible without the optional second hunk */2953if(apply_in_reverse) {2954if(!fragment->next)2955returnerror("cannot reverse-apply a binary patch "2956"without the reverse hunk to '%s'",2957 patch->new_name2958? patch->new_name : patch->old_name);2959 fragment = fragment->next;2960}2961switch(fragment->binary_patch_method) {2962case BINARY_DELTA_DEFLATED:2963 dst =patch_delta(img->buf, img->len, fragment->patch,2964 fragment->size, &len);2965if(!dst)2966return-1;2967clear_image(img);2968 img->buf = dst;2969 img->len = len;2970return0;2971case BINARY_LITERAL_DEFLATED:2972clear_image(img);2973 img->len = fragment->size;2974 img->buf =xmemdupz(fragment->patch, img->len);2975return0;2976}2977return-1;2978}29792980/*2981 * Replace "img" with the result of applying the binary patch.2982 * The binary patch data itself in patch->fragment is still kept2983 * but the preimage prepared by the caller in "img" is freed here2984 * or in the helper function apply_binary_fragment() this calls.2985 */2986static intapply_binary(struct image *img,struct patch *patch)2987{2988const char*name = patch->old_name ? patch->old_name : patch->new_name;2989unsigned char sha1[20];29902991/*2992 * For safety, we require patch index line to contain2993 * full 40-byte textual SHA1 for old and new, at least for now.2994 */2995if(strlen(patch->old_sha1_prefix) !=40||2996strlen(patch->new_sha1_prefix) !=40||2997get_sha1_hex(patch->old_sha1_prefix, sha1) ||2998get_sha1_hex(patch->new_sha1_prefix, sha1))2999returnerror("cannot apply binary patch to '%s' "3000"without full index line", name);30013002if(patch->old_name) {3003/*3004 * See if the old one matches what the patch3005 * applies to.3006 */3007hash_sha1_file(img->buf, img->len, blob_type, sha1);3008if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3009returnerror("the patch applies to '%s' (%s), "3010"which does not match the "3011"current contents.",3012 name,sha1_to_hex(sha1));3013}3014else{3015/* Otherwise, the old one must be empty. */3016if(img->len)3017returnerror("the patch applies to an empty "3018"'%s' but it is not empty", name);3019}30203021get_sha1_hex(patch->new_sha1_prefix, sha1);3022if(is_null_sha1(sha1)) {3023clear_image(img);3024return0;/* deletion patch */3025}30263027if(has_sha1_file(sha1)) {3028/* We already have the postimage */3029enum object_type type;3030unsigned long size;3031char*result;30323033 result =read_sha1_file(sha1, &type, &size);3034if(!result)3035returnerror("the necessary postimage%sfor "3036"'%s' cannot be read",3037 patch->new_sha1_prefix, name);3038clear_image(img);3039 img->buf = result;3040 img->len = size;3041}else{3042/*3043 * We have verified buf matches the preimage;3044 * apply the patch data to it, which is stored3045 * in the patch->fragments->{patch,size}.3046 */3047if(apply_binary_fragment(img, patch))3048returnerror(_("binary patch does not apply to '%s'"),3049 name);30503051/* verify that the result matches */3052hash_sha1_file(img->buf, img->len, blob_type, sha1);3053if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3054returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3055 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3056}30573058return0;3059}30603061static intapply_fragments(struct image *img,struct patch *patch)3062{3063struct fragment *frag = patch->fragments;3064const char*name = patch->old_name ? patch->old_name : patch->new_name;3065unsigned ws_rule = patch->ws_rule;3066unsigned inaccurate_eof = patch->inaccurate_eof;3067int nth =0;30683069if(patch->is_binary)3070returnapply_binary(img, patch);30713072while(frag) {3073 nth++;3074if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {3075error(_("patch failed:%s:%ld"), name, frag->oldpos);3076if(!apply_with_reject)3077return-1;3078 frag->rejected =1;3079}3080 frag = frag->next;3081}3082return0;3083}30843085static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3086{3087if(S_ISGITLINK(mode)) {3088strbuf_grow(buf,100);3089strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3090}else{3091enum object_type type;3092unsigned long sz;3093char*result;30943095 result =read_sha1_file(sha1, &type, &sz);3096if(!result)3097return-1;3098/* XXX read_sha1_file NUL-terminates */3099strbuf_attach(buf, result, sz, sz +1);3100}3101return0;3102}31033104static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3105{3106if(!ce)3107return0;3108returnread_blob_object(buf, ce->sha1, ce->ce_mode);3109}31103111static struct patch *in_fn_table(const char*name)3112{3113struct string_list_item *item;31143115if(name == NULL)3116return NULL;31173118 item =string_list_lookup(&fn_table, name);3119if(item != NULL)3120return(struct patch *)item->util;31213122return NULL;3123}31243125/*3126 * item->util in the filename table records the status of the path.3127 * Usually it points at a patch (whose result records the contents3128 * of it after applying it), but it could be PATH_WAS_DELETED for a3129 * path that a previously applied patch has already removed, or3130 * PATH_TO_BE_DELETED for a path that a later patch would remove.3131 *3132 * The latter is needed to deal with a case where two paths A and B3133 * are swapped by first renaming A to B and then renaming B to A;3134 * moving A to B should not be prevented due to presence of B as we3135 * will remove it in a later patch.3136 */3137#define PATH_TO_BE_DELETED ((struct patch *) -2)3138#define PATH_WAS_DELETED ((struct patch *) -1)31393140static intto_be_deleted(struct patch *patch)3141{3142return patch == PATH_TO_BE_DELETED;3143}31443145static intwas_deleted(struct patch *patch)3146{3147return patch == PATH_WAS_DELETED;3148}31493150static voidadd_to_fn_table(struct patch *patch)3151{3152struct string_list_item *item;31533154/*3155 * Always add new_name unless patch is a deletion3156 * This should cover the cases for normal diffs,3157 * file creations and copies3158 */3159if(patch->new_name != NULL) {3160 item =string_list_insert(&fn_table, patch->new_name);3161 item->util = patch;3162}31633164/*3165 * store a failure on rename/deletion cases because3166 * later chunks shouldn't patch old names3167 */3168if((patch->new_name == NULL) || (patch->is_rename)) {3169 item =string_list_insert(&fn_table, patch->old_name);3170 item->util = PATH_WAS_DELETED;3171}3172}31733174static voidprepare_fn_table(struct patch *patch)3175{3176/*3177 * store information about incoming file deletion3178 */3179while(patch) {3180if((patch->new_name == NULL) || (patch->is_rename)) {3181struct string_list_item *item;3182 item =string_list_insert(&fn_table, patch->old_name);3183 item->util = PATH_TO_BE_DELETED;3184}3185 patch = patch->next;3186}3187}31883189static intcheckout_target(struct index_state *istate,3190struct cache_entry *ce,struct stat *st)3191{3192struct checkout costate;31933194memset(&costate,0,sizeof(costate));3195 costate.base_dir ="";3196 costate.refresh_cache =1;3197 costate.istate = istate;3198if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3199returnerror(_("cannot checkout%s"), ce->name);3200return0;3201}32023203static struct patch *previous_patch(struct patch *patch,int*gone)3204{3205struct patch *previous;32063207*gone =0;3208if(patch->is_copy || patch->is_rename)3209return NULL;/* "git" patches do not depend on the order */32103211 previous =in_fn_table(patch->old_name);3212if(!previous)3213return NULL;32143215if(to_be_deleted(previous))3216return NULL;/* the deletion hasn't happened yet */32173218if(was_deleted(previous))3219*gone =1;32203221return previous;3222}32233224static intverify_index_match(const struct cache_entry *ce,struct stat *st)3225{3226if(S_ISGITLINK(ce->ce_mode)) {3227if(!S_ISDIR(st->st_mode))3228return-1;3229return0;3230}3231returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3232}32333234#define SUBMODULE_PATCH_WITHOUT_INDEX 132353236static intload_patch_target(struct strbuf *buf,3237const struct cache_entry *ce,3238struct stat *st,3239const char*name,3240unsigned expected_mode)3241{3242if(cached || check_index) {3243if(read_file_or_gitlink(ce, buf))3244returnerror(_("read of%sfailed"), name);3245}else if(name) {3246if(S_ISGITLINK(expected_mode)) {3247if(ce)3248returnread_file_or_gitlink(ce, buf);3249else3250return SUBMODULE_PATCH_WITHOUT_INDEX;3251}else if(has_symlink_leading_path(name,strlen(name))) {3252returnerror(_("reading from '%s' beyond a symbolic link"), name);3253}else{3254if(read_old_data(st, name, buf))3255returnerror(_("read of%sfailed"), name);3256}3257}3258return0;3259}32603261/*3262 * We are about to apply "patch"; populate the "image" with the3263 * current version we have, from the working tree or from the index,3264 * depending on the situation e.g. --cached/--index. If we are3265 * applying a non-git patch that incrementally updates the tree,3266 * we read from the result of a previous diff.3267 */3268static intload_preimage(struct image *image,3269struct patch *patch,struct stat *st,3270const struct cache_entry *ce)3271{3272struct strbuf buf = STRBUF_INIT;3273size_t len;3274char*img;3275struct patch *previous;3276int status;32773278 previous =previous_patch(patch, &status);3279if(status)3280returnerror(_("path%shas been renamed/deleted"),3281 patch->old_name);3282if(previous) {3283/* We have a patched copy in memory; use that. */3284strbuf_add(&buf, previous->result, previous->resultsize);3285}else{3286 status =load_patch_target(&buf, ce, st,3287 patch->old_name, patch->old_mode);3288if(status <0)3289return status;3290else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3291/*3292 * There is no way to apply subproject3293 * patch without looking at the index.3294 * NEEDSWORK: shouldn't this be flagged3295 * as an error???3296 */3297free_fragment_list(patch->fragments);3298 patch->fragments = NULL;3299}else if(status) {3300returnerror(_("read of%sfailed"), patch->old_name);3301}3302}33033304 img =strbuf_detach(&buf, &len);3305prepare_image(image, img, len, !patch->is_binary);3306return0;3307}33083309static intthree_way_merge(struct image *image,3310char*path,3311const unsigned char*base,3312const unsigned char*ours,3313const unsigned char*theirs)3314{3315 mmfile_t base_file, our_file, their_file;3316 mmbuffer_t result = { NULL };3317int status;33183319read_mmblob(&base_file, base);3320read_mmblob(&our_file, ours);3321read_mmblob(&their_file, theirs);3322 status =ll_merge(&result, path,3323&base_file,"base",3324&our_file,"ours",3325&their_file,"theirs", NULL);3326free(base_file.ptr);3327free(our_file.ptr);3328free(their_file.ptr);3329if(status <0|| !result.ptr) {3330free(result.ptr);3331return-1;3332}3333clear_image(image);3334 image->buf = result.ptr;3335 image->len = result.size;33363337return status;3338}33393340/*3341 * When directly falling back to add/add three-way merge, we read from3342 * the current contents of the new_name. In no cases other than that3343 * this function will be called.3344 */3345static intload_current(struct image *image,struct patch *patch)3346{3347struct strbuf buf = STRBUF_INIT;3348int status, pos;3349size_t len;3350char*img;3351struct stat st;3352struct cache_entry *ce;3353char*name = patch->new_name;3354unsigned mode = patch->new_mode;33553356if(!patch->is_new)3357die("BUG: patch to%sis not a creation", patch->old_name);33583359 pos =cache_name_pos(name,strlen(name));3360if(pos <0)3361returnerror(_("%s: does not exist in index"), name);3362 ce = active_cache[pos];3363if(lstat(name, &st)) {3364if(errno != ENOENT)3365returnerror(_("%s:%s"), name,strerror(errno));3366if(checkout_target(&the_index, ce, &st))3367return-1;3368}3369if(verify_index_match(ce, &st))3370returnerror(_("%s: does not match index"), name);33713372 status =load_patch_target(&buf, ce, &st, name, mode);3373if(status <0)3374return status;3375else if(status)3376return-1;3377 img =strbuf_detach(&buf, &len);3378prepare_image(image, img, len, !patch->is_binary);3379return0;3380}33813382static inttry_threeway(struct image *image,struct patch *patch,3383struct stat *st,const struct cache_entry *ce)3384{3385unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3386struct strbuf buf = STRBUF_INIT;3387size_t len;3388int status;3389char*img;3390struct image tmp_image;33913392/* No point falling back to 3-way merge in these cases */3393if(patch->is_delete ||3394S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3395return-1;33963397/* Preimage the patch was prepared for */3398if(patch->is_new)3399write_sha1_file("",0, blob_type, pre_sha1);3400else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3401read_blob_object(&buf, pre_sha1, patch->old_mode))3402returnerror("repository lacks the necessary blob to fall back on 3-way merge.");34033404fprintf(stderr,"Falling back to three-way merge...\n");34053406 img =strbuf_detach(&buf, &len);3407prepare_image(&tmp_image, img, len,1);3408/* Apply the patch to get the post image */3409if(apply_fragments(&tmp_image, patch) <0) {3410clear_image(&tmp_image);3411return-1;3412}3413/* post_sha1[] is theirs */3414write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3415clear_image(&tmp_image);34163417/* our_sha1[] is ours */3418if(patch->is_new) {3419if(load_current(&tmp_image, patch))3420returnerror("cannot read the current contents of '%s'",3421 patch->new_name);3422}else{3423if(load_preimage(&tmp_image, patch, st, ce))3424returnerror("cannot read the current contents of '%s'",3425 patch->old_name);3426}3427write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3428clear_image(&tmp_image);34293430/* in-core three-way merge between post and our using pre as base */3431 status =three_way_merge(image, patch->new_name,3432 pre_sha1, our_sha1, post_sha1);3433if(status <0) {3434fprintf(stderr,"Failed to fall back on three-way merge...\n");3435return status;3436}34373438if(status) {3439 patch->conflicted_threeway =1;3440if(patch->is_new)3441oidclr(&patch->threeway_stage[0]);3442else3443hashcpy(patch->threeway_stage[0].hash, pre_sha1);3444hashcpy(patch->threeway_stage[1].hash, our_sha1);3445hashcpy(patch->threeway_stage[2].hash, post_sha1);3446fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3447}else{3448fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3449}3450return0;3451}34523453static intapply_data(struct patch *patch,struct stat *st,const struct cache_entry *ce)3454{3455struct image image;34563457if(load_preimage(&image, patch, st, ce) <0)3458return-1;34593460if(patch->direct_to_threeway ||3461apply_fragments(&image, patch) <0) {3462/* Note: with --reject, apply_fragments() returns 0 */3463if(!threeway ||try_threeway(&image, patch, st, ce) <0)3464return-1;3465}3466 patch->result = image.buf;3467 patch->resultsize = image.len;3468add_to_fn_table(patch);3469free(image.line_allocated);34703471if(0< patch->is_delete && patch->resultsize)3472returnerror(_("removal patch leaves file contents"));34733474return0;3475}34763477/*3478 * If "patch" that we are looking at modifies or deletes what we have,3479 * we would want it not to lose any local modification we have, either3480 * in the working tree or in the index.3481 *3482 * This also decides if a non-git patch is a creation patch or a3483 * modification to an existing empty file. We do not check the state3484 * of the current tree for a creation patch in this function; the caller3485 * check_patch() separately makes sure (and errors out otherwise) that3486 * the path the patch creates does not exist in the current tree.3487 */3488static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)3489{3490const char*old_name = patch->old_name;3491struct patch *previous = NULL;3492int stat_ret =0, status;3493unsigned st_mode =0;34943495if(!old_name)3496return0;34973498assert(patch->is_new <=0);3499 previous =previous_patch(patch, &status);35003501if(status)3502returnerror(_("path%shas been renamed/deleted"), old_name);3503if(previous) {3504 st_mode = previous->new_mode;3505}else if(!cached) {3506 stat_ret =lstat(old_name, st);3507if(stat_ret && errno != ENOENT)3508returnerror(_("%s:%s"), old_name,strerror(errno));3509}35103511if(check_index && !previous) {3512int pos =cache_name_pos(old_name,strlen(old_name));3513if(pos <0) {3514if(patch->is_new <0)3515goto is_new;3516returnerror(_("%s: does not exist in index"), old_name);3517}3518*ce = active_cache[pos];3519if(stat_ret <0) {3520if(checkout_target(&the_index, *ce, st))3521return-1;3522}3523if(!cached &&verify_index_match(*ce, st))3524returnerror(_("%s: does not match index"), old_name);3525if(cached)3526 st_mode = (*ce)->ce_mode;3527}else if(stat_ret <0) {3528if(patch->is_new <0)3529goto is_new;3530returnerror(_("%s:%s"), old_name,strerror(errno));3531}35323533if(!cached && !previous)3534 st_mode =ce_mode_from_stat(*ce, st->st_mode);35353536if(patch->is_new <0)3537 patch->is_new =0;3538if(!patch->old_mode)3539 patch->old_mode = st_mode;3540if((st_mode ^ patch->old_mode) & S_IFMT)3541returnerror(_("%s: wrong type"), old_name);3542if(st_mode != patch->old_mode)3543warning(_("%shas type%o, expected%o"),3544 old_name, st_mode, patch->old_mode);3545if(!patch->new_mode && !patch->is_delete)3546 patch->new_mode = st_mode;3547return0;35483549 is_new:3550 patch->is_new =1;3551 patch->is_delete =0;3552free(patch->old_name);3553 patch->old_name = NULL;3554return0;3555}355635573558#define EXISTS_IN_INDEX 13559#define EXISTS_IN_WORKTREE 235603561static intcheck_to_create(const char*new_name,int ok_if_exists)3562{3563struct stat nst;35643565if(check_index &&3566cache_name_pos(new_name,strlen(new_name)) >=0&&3567!ok_if_exists)3568return EXISTS_IN_INDEX;3569if(cached)3570return0;35713572if(!lstat(new_name, &nst)) {3573if(S_ISDIR(nst.st_mode) || ok_if_exists)3574return0;3575/*3576 * A leading component of new_name might be a symlink3577 * that is going to be removed with this patch, but3578 * still pointing at somewhere that has the path.3579 * In such a case, path "new_name" does not exist as3580 * far as git is concerned.3581 */3582if(has_symlink_leading_path(new_name,strlen(new_name)))3583return0;35843585return EXISTS_IN_WORKTREE;3586}else if((errno != ENOENT) && (errno != ENOTDIR)) {3587returnerror("%s:%s", new_name,strerror(errno));3588}3589return0;3590}35913592/*3593 * We need to keep track of how symlinks in the preimage are3594 * manipulated by the patches. A patch to add a/b/c where a/b3595 * is a symlink should not be allowed to affect the directory3596 * the symlink points at, but if the same patch removes a/b,3597 * it is perfectly fine, as the patch removes a/b to make room3598 * to create a directory a/b so that a/b/c can be created.3599 */3600static struct string_list symlink_changes;3601#define SYMLINK_GOES_AWAY 013602#define SYMLINK_IN_RESULT 0236033604static uintptr_tregister_symlink_changes(const char*path,uintptr_t what)3605{3606struct string_list_item *ent;36073608 ent =string_list_lookup(&symlink_changes, path);3609if(!ent) {3610 ent =string_list_insert(&symlink_changes, path);3611 ent->util = (void*)0;3612}3613 ent->util = (void*)(what | ((uintptr_t)ent->util));3614return(uintptr_t)ent->util;3615}36163617static uintptr_tcheck_symlink_changes(const char*path)3618{3619struct string_list_item *ent;36203621 ent =string_list_lookup(&symlink_changes, path);3622if(!ent)3623return0;3624return(uintptr_t)ent->util;3625}36263627static voidprepare_symlink_changes(struct patch *patch)3628{3629for( ; patch; patch = patch->next) {3630if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3631(patch->is_rename || patch->is_delete))3632/* the symlink at patch->old_name is removed */3633register_symlink_changes(patch->old_name, SYMLINK_GOES_AWAY);36343635if(patch->new_name &&S_ISLNK(patch->new_mode))3636/* the symlink at patch->new_name is created or remains */3637register_symlink_changes(patch->new_name, SYMLINK_IN_RESULT);3638}3639}36403641static intpath_is_beyond_symlink_1(struct strbuf *name)3642{3643do{3644unsigned int change;36453646while(--name->len && name->buf[name->len] !='/')3647;/* scan backwards */3648if(!name->len)3649break;3650 name->buf[name->len] ='\0';3651 change =check_symlink_changes(name->buf);3652if(change & SYMLINK_IN_RESULT)3653return1;3654if(change & SYMLINK_GOES_AWAY)3655/*3656 * This cannot be "return 0", because we may3657 * see a new one created at a higher level.3658 */3659continue;36603661/* otherwise, check the preimage */3662if(check_index) {3663struct cache_entry *ce;36643665 ce =cache_file_exists(name->buf, name->len, ignore_case);3666if(ce &&S_ISLNK(ce->ce_mode))3667return1;3668}else{3669struct stat st;3670if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3671return1;3672}3673}while(1);3674return0;3675}36763677static intpath_is_beyond_symlink(const char*name_)3678{3679int ret;3680struct strbuf name = STRBUF_INIT;36813682assert(*name_ !='\0');3683strbuf_addstr(&name, name_);3684 ret =path_is_beyond_symlink_1(&name);3685strbuf_release(&name);36863687return ret;3688}36893690static voiddie_on_unsafe_path(struct patch *patch)3691{3692const char*old_name = NULL;3693const char*new_name = NULL;3694if(patch->is_delete)3695 old_name = patch->old_name;3696else if(!patch->is_new && !patch->is_copy)3697 old_name = patch->old_name;3698if(!patch->is_delete)3699 new_name = patch->new_name;37003701if(old_name && !verify_path(old_name))3702die(_("invalid path '%s'"), old_name);3703if(new_name && !verify_path(new_name))3704die(_("invalid path '%s'"), new_name);3705}37063707/*3708 * Check and apply the patch in-core; leave the result in patch->result3709 * for the caller to write it out to the final destination.3710 */3711static intcheck_patch(struct patch *patch)3712{3713struct stat st;3714const char*old_name = patch->old_name;3715const char*new_name = patch->new_name;3716const char*name = old_name ? old_name : new_name;3717struct cache_entry *ce = NULL;3718struct patch *tpatch;3719int ok_if_exists;3720int status;37213722 patch->rejected =1;/* we will drop this after we succeed */37233724 status =check_preimage(patch, &ce, &st);3725if(status)3726return status;3727 old_name = patch->old_name;37283729/*3730 * A type-change diff is always split into a patch to delete3731 * old, immediately followed by a patch to create new (see3732 * diff.c::run_diff()); in such a case it is Ok that the entry3733 * to be deleted by the previous patch is still in the working3734 * tree and in the index.3735 *3736 * A patch to swap-rename between A and B would first rename A3737 * to B and then rename B to A. While applying the first one,3738 * the presence of B should not stop A from getting renamed to3739 * B; ask to_be_deleted() about the later rename. Removal of3740 * B and rename from A to B is handled the same way by asking3741 * was_deleted().3742 */3743if((tpatch =in_fn_table(new_name)) &&3744(was_deleted(tpatch) ||to_be_deleted(tpatch)))3745 ok_if_exists =1;3746else3747 ok_if_exists =0;37483749if(new_name &&3750((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3751int err =check_to_create(new_name, ok_if_exists);37523753if(err && threeway) {3754 patch->direct_to_threeway =1;3755}else switch(err) {3756case0:3757break;/* happy */3758case EXISTS_IN_INDEX:3759returnerror(_("%s: already exists in index"), new_name);3760break;3761case EXISTS_IN_WORKTREE:3762returnerror(_("%s: already exists in working directory"),3763 new_name);3764default:3765return err;3766}37673768if(!patch->new_mode) {3769if(0< patch->is_new)3770 patch->new_mode = S_IFREG |0644;3771else3772 patch->new_mode = patch->old_mode;3773}3774}37753776if(new_name && old_name) {3777int same = !strcmp(old_name, new_name);3778if(!patch->new_mode)3779 patch->new_mode = patch->old_mode;3780if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3781if(same)3782returnerror(_("new mode (%o) of%sdoes not "3783"match old mode (%o)"),3784 patch->new_mode, new_name,3785 patch->old_mode);3786else3787returnerror(_("new mode (%o) of%sdoes not "3788"match old mode (%o) of%s"),3789 patch->new_mode, new_name,3790 patch->old_mode, old_name);3791}3792}37933794if(!unsafe_paths)3795die_on_unsafe_path(patch);37963797/*3798 * An attempt to read from or delete a path that is beyond a3799 * symbolic link will be prevented by load_patch_target() that3800 * is called at the beginning of apply_data() so we do not3801 * have to worry about a patch marked with "is_delete" bit3802 * here. We however need to make sure that the patch result3803 * is not deposited to a path that is beyond a symbolic link3804 * here.3805 */3806if(!patch->is_delete &&path_is_beyond_symlink(patch->new_name))3807returnerror(_("affected file '%s' is beyond a symbolic link"),3808 patch->new_name);38093810if(apply_data(patch, &st, ce) <0)3811returnerror(_("%s: patch does not apply"), name);3812 patch->rejected =0;3813return0;3814}38153816static intcheck_patch_list(struct patch *patch)3817{3818int err =0;38193820prepare_symlink_changes(patch);3821prepare_fn_table(patch);3822while(patch) {3823if(apply_verbosely)3824say_patch_name(stderr,3825_("Checking patch%s..."), patch);3826 err |=check_patch(patch);3827 patch = patch->next;3828}3829return err;3830}38313832/* This function tries to read the sha1 from the current index */3833static intget_current_sha1(const char*path,unsigned char*sha1)3834{3835int pos;38363837if(read_cache() <0)3838return-1;3839 pos =cache_name_pos(path,strlen(path));3840if(pos <0)3841return-1;3842hashcpy(sha1, active_cache[pos]->sha1);3843return0;3844}38453846static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3847{3848/*3849 * A usable gitlink patch has only one fragment (hunk) that looks like:3850 * @@ -1 +1 @@3851 * -Subproject commit <old sha1>3852 * +Subproject commit <new sha1>3853 * or3854 * @@ -1 +0,0 @@3855 * -Subproject commit <old sha1>3856 * for a removal patch.3857 */3858struct fragment *hunk = p->fragments;3859static const char heading[] ="-Subproject commit ";3860char*preimage;38613862if(/* does the patch have only one hunk? */3863 hunk && !hunk->next &&3864/* is its preimage one line? */3865 hunk->oldpos ==1&& hunk->oldlines ==1&&3866/* does preimage begin with the heading? */3867(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3868starts_with(++preimage, heading) &&3869/* does it record full SHA-1? */3870!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3871 preimage[sizeof(heading) +40-1] =='\n'&&3872/* does the abbreviated name on the index line agree with it? */3873starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3874return0;/* it all looks fine */38753876/* we may have full object name on the index line */3877returnget_sha1_hex(p->old_sha1_prefix, sha1);3878}38793880/* Build an index that contains the just the files needed for a 3way merge */3881static voidbuild_fake_ancestor(struct patch *list,const char*filename)3882{3883struct patch *patch;3884struct index_state result = { NULL };3885static struct lock_file lock;38863887/* Once we start supporting the reverse patch, it may be3888 * worth showing the new sha1 prefix, but until then...3889 */3890for(patch = list; patch; patch = patch->next) {3891unsigned char sha1[20];3892struct cache_entry *ce;3893const char*name;38943895 name = patch->old_name ? patch->old_name : patch->new_name;3896if(0< patch->is_new)3897continue;38983899if(S_ISGITLINK(patch->old_mode)) {3900if(!preimage_sha1_in_gitlink_patch(patch, sha1))3901;/* ok, the textual part looks sane */3902else3903die("sha1 information is lacking or useless for submodule%s",3904 name);3905}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {3906;/* ok */3907}else if(!patch->lines_added && !patch->lines_deleted) {3908/* mode-only change: update the current */3909if(get_current_sha1(patch->old_name, sha1))3910die("mode change for%s, which is not "3911"in current HEAD", name);3912}else3913die("sha1 information is lacking or useless "3914"(%s).", name);39153916 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);3917if(!ce)3918die(_("make_cache_entry failed for path '%s'"), name);3919if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3920die("Could not add%sto temporary index", name);3921}39223923hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);3924if(write_locked_index(&result, &lock, COMMIT_LOCK))3925die("Could not write temporary index to%s", filename);39263927discard_index(&result);3928}39293930static voidstat_patch_list(struct patch *patch)3931{3932int files, adds, dels;39333934for(files = adds = dels =0; patch ; patch = patch->next) {3935 files++;3936 adds += patch->lines_added;3937 dels += patch->lines_deleted;3938show_stats(patch);3939}39403941print_stat_summary(stdout, files, adds, dels);3942}39433944static voidnumstat_patch_list(struct patch *patch)3945{3946for( ; patch; patch = patch->next) {3947const char*name;3948 name = patch->new_name ? patch->new_name : patch->old_name;3949if(patch->is_binary)3950printf("-\t-\t");3951else3952printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3953write_name_quoted(name, stdout, line_termination);3954}3955}39563957static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3958{3959if(mode)3960printf("%smode%06o%s\n", newdelete, mode, name);3961else3962printf("%s %s\n", newdelete, name);3963}39643965static voidshow_mode_change(struct patch *p,int show_name)3966{3967if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3968if(show_name)3969printf(" mode change%06o =>%06o%s\n",3970 p->old_mode, p->new_mode, p->new_name);3971else3972printf(" mode change%06o =>%06o\n",3973 p->old_mode, p->new_mode);3974}3975}39763977static voidshow_rename_copy(struct patch *p)3978{3979const char*renamecopy = p->is_rename ?"rename":"copy";3980const char*old, *new;39813982/* Find common prefix */3983 old = p->old_name;3984new= p->new_name;3985while(1) {3986const char*slash_old, *slash_new;3987 slash_old =strchr(old,'/');3988 slash_new =strchr(new,'/');3989if(!slash_old ||3990!slash_new ||3991 slash_old - old != slash_new -new||3992memcmp(old,new, slash_new -new))3993break;3994 old = slash_old +1;3995new= slash_new +1;3996}3997/* p->old_name thru old is the common prefix, and old and new3998 * through the end of names are renames3999 */4000if(old != p->old_name)4001printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4002(int)(old - p->old_name), p->old_name,4003 old,new, p->score);4004else4005printf("%s %s=>%s(%d%%)\n", renamecopy,4006 p->old_name, p->new_name, p->score);4007show_mode_change(p,0);4008}40094010static voidsummary_patch_list(struct patch *patch)4011{4012struct patch *p;40134014for(p = patch; p; p = p->next) {4015if(p->is_new)4016show_file_mode_name("create", p->new_mode, p->new_name);4017else if(p->is_delete)4018show_file_mode_name("delete", p->old_mode, p->old_name);4019else{4020if(p->is_rename || p->is_copy)4021show_rename_copy(p);4022else{4023if(p->score) {4024printf(" rewrite%s(%d%%)\n",4025 p->new_name, p->score);4026show_mode_change(p,0);4027}4028else4029show_mode_change(p,1);4030}4031}4032}4033}40344035static voidpatch_stats(struct patch *patch)4036{4037int lines = patch->lines_added + patch->lines_deleted;40384039if(lines > max_change)4040 max_change = lines;4041if(patch->old_name) {4042int len =quote_c_style(patch->old_name, NULL, NULL,0);4043if(!len)4044 len =strlen(patch->old_name);4045if(len > max_len)4046 max_len = len;4047}4048if(patch->new_name) {4049int len =quote_c_style(patch->new_name, NULL, NULL,0);4050if(!len)4051 len =strlen(patch->new_name);4052if(len > max_len)4053 max_len = len;4054}4055}40564057static voidremove_file(struct patch *patch,int rmdir_empty)4058{4059if(update_index) {4060if(remove_file_from_cache(patch->old_name) <0)4061die(_("unable to remove%sfrom index"), patch->old_name);4062}4063if(!cached) {4064if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4065remove_path(patch->old_name);4066}4067}4068}40694070static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)4071{4072struct stat st;4073struct cache_entry *ce;4074int namelen =strlen(path);4075unsigned ce_size =cache_entry_size(namelen);40764077if(!update_index)4078return;40794080 ce =xcalloc(1, ce_size);4081memcpy(ce->name, path, namelen);4082 ce->ce_mode =create_ce_mode(mode);4083 ce->ce_flags =create_ce_flags(0);4084 ce->ce_namelen = namelen;4085if(S_ISGITLINK(mode)) {4086const char*s;40874088if(!skip_prefix(buf,"Subproject commit ", &s) ||4089get_sha1_hex(s, ce->sha1))4090die(_("corrupt patch for submodule%s"), path);4091}else{4092if(!cached) {4093if(lstat(path, &st) <0)4094die_errno(_("unable to stat newly created file '%s'"),4095 path);4096fill_stat_cache_info(ce, &st);4097}4098if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4099die(_("unable to create backing store for newly created file%s"), path);4100}4101if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4102die(_("unable to add cache entry for%s"), path);4103}41044105static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4106{4107int fd;4108struct strbuf nbuf = STRBUF_INIT;41094110if(S_ISGITLINK(mode)) {4111struct stat st;4112if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4113return0;4114returnmkdir(path,0777);4115}41164117if(has_symlinks &&S_ISLNK(mode))4118/* Although buf:size is counted string, it also is NUL4119 * terminated.4120 */4121returnsymlink(buf, path);41224123 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4124if(fd <0)4125return-1;41264127if(convert_to_working_tree(path, buf, size, &nbuf)) {4128 size = nbuf.len;4129 buf = nbuf.buf;4130}4131write_or_die(fd, buf, size);4132strbuf_release(&nbuf);41334134if(close(fd) <0)4135die_errno(_("closing file '%s'"), path);4136return0;4137}41384139/*4140 * We optimistically assume that the directories exist,4141 * which is true 99% of the time anyway. If they don't,4142 * we create them and try again.4143 */4144static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)4145{4146if(cached)4147return;4148if(!try_create_file(path, mode, buf, size))4149return;41504151if(errno == ENOENT) {4152if(safe_create_leading_directories(path))4153return;4154if(!try_create_file(path, mode, buf, size))4155return;4156}41574158if(errno == EEXIST || errno == EACCES) {4159/* We may be trying to create a file where a directory4160 * used to be.4161 */4162struct stat st;4163if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4164 errno = EEXIST;4165}41664167if(errno == EEXIST) {4168unsigned int nr =getpid();41694170for(;;) {4171char newpath[PATH_MAX];4172mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4173if(!try_create_file(newpath, mode, buf, size)) {4174if(!rename(newpath, path))4175return;4176unlink_or_warn(newpath);4177break;4178}4179if(errno != EEXIST)4180break;4181++nr;4182}4183}4184die_errno(_("unable to write file '%s' mode%o"), path, mode);4185}41864187static voidadd_conflicted_stages_file(struct patch *patch)4188{4189int stage, namelen;4190unsigned ce_size, mode;4191struct cache_entry *ce;41924193if(!update_index)4194return;4195 namelen =strlen(patch->new_name);4196 ce_size =cache_entry_size(namelen);4197 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);41984199remove_file_from_cache(patch->new_name);4200for(stage =1; stage <4; stage++) {4201if(is_null_oid(&patch->threeway_stage[stage -1]))4202continue;4203 ce =xcalloc(1, ce_size);4204memcpy(ce->name, patch->new_name, namelen);4205 ce->ce_mode =create_ce_mode(mode);4206 ce->ce_flags =create_ce_flags(stage);4207 ce->ce_namelen = namelen;4208hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4209if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4210die(_("unable to add cache entry for%s"), patch->new_name);4211}4212}42134214static voidcreate_file(struct patch *patch)4215{4216char*path = patch->new_name;4217unsigned mode = patch->new_mode;4218unsigned long size = patch->resultsize;4219char*buf = patch->result;42204221if(!mode)4222 mode = S_IFREG |0644;4223create_one_file(path, mode, buf, size);42244225if(patch->conflicted_threeway)4226add_conflicted_stages_file(patch);4227else4228add_index_file(path, mode, buf, size);4229}42304231/* phase zero is to remove, phase one is to create */4232static voidwrite_out_one_result(struct patch *patch,int phase)4233{4234if(patch->is_delete >0) {4235if(phase ==0)4236remove_file(patch,1);4237return;4238}4239if(patch->is_new >0|| patch->is_copy) {4240if(phase ==1)4241create_file(patch);4242return;4243}4244/*4245 * Rename or modification boils down to the same4246 * thing: remove the old, write the new4247 */4248if(phase ==0)4249remove_file(patch, patch->is_rename);4250if(phase ==1)4251create_file(patch);4252}42534254static intwrite_out_one_reject(struct patch *patch)4255{4256FILE*rej;4257char namebuf[PATH_MAX];4258struct fragment *frag;4259int cnt =0;4260struct strbuf sb = STRBUF_INIT;42614262for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4263if(!frag->rejected)4264continue;4265 cnt++;4266}42674268if(!cnt) {4269if(apply_verbosely)4270say_patch_name(stderr,4271_("Applied patch%scleanly."), patch);4272return0;4273}42744275/* This should not happen, because a removal patch that leaves4276 * contents are marked "rejected" at the patch level.4277 */4278if(!patch->new_name)4279die(_("internal error"));42804281/* Say this even without --verbose */4282strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4283"Applying patch %%swith%drejects...",4284 cnt),4285 cnt);4286say_patch_name(stderr, sb.buf, patch);4287strbuf_release(&sb);42884289 cnt =strlen(patch->new_name);4290if(ARRAY_SIZE(namebuf) <= cnt +5) {4291 cnt =ARRAY_SIZE(namebuf) -5;4292warning(_("truncating .rej filename to %.*s.rej"),4293 cnt -1, patch->new_name);4294}4295memcpy(namebuf, patch->new_name, cnt);4296memcpy(namebuf + cnt,".rej",5);42974298 rej =fopen(namebuf,"w");4299if(!rej)4300returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));43014302/* Normal git tools never deal with .rej, so do not pretend4303 * this is a git patch by saying --git or giving extended4304 * headers. While at it, maybe please "kompare" that wants4305 * the trailing TAB and some garbage at the end of line ;-).4306 */4307fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4308 patch->new_name, patch->new_name);4309for(cnt =1, frag = patch->fragments;4310 frag;4311 cnt++, frag = frag->next) {4312if(!frag->rejected) {4313fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4314continue;4315}4316fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4317fprintf(rej,"%.*s", frag->size, frag->patch);4318if(frag->patch[frag->size-1] !='\n')4319fputc('\n', rej);4320}4321fclose(rej);4322return-1;4323}43244325static intwrite_out_results(struct patch *list)4326{4327int phase;4328int errs =0;4329struct patch *l;4330struct string_list cpath = STRING_LIST_INIT_DUP;43314332for(phase =0; phase <2; phase++) {4333 l = list;4334while(l) {4335if(l->rejected)4336 errs =1;4337else{4338write_out_one_result(l, phase);4339if(phase ==1) {4340if(write_out_one_reject(l))4341 errs =1;4342if(l->conflicted_threeway) {4343string_list_append(&cpath, l->new_name);4344 errs =1;4345}4346}4347}4348 l = l->next;4349}4350}43514352if(cpath.nr) {4353struct string_list_item *item;43544355string_list_sort(&cpath);4356for_each_string_list_item(item, &cpath)4357fprintf(stderr,"U%s\n", item->string);4358string_list_clear(&cpath,0);43594360rerere(0);4361}43624363return errs;4364}43654366static struct lock_file lock_file;43674368#define INACCURATE_EOF (1<<0)4369#define RECOUNT (1<<1)43704371static intapply_patch(int fd,const char*filename,int options)4372{4373size_t offset;4374struct strbuf buf = STRBUF_INIT;/* owns the patch text */4375struct patch *list = NULL, **listp = &list;4376int skipped_patch =0;43774378 patch_input_file = filename;4379read_patch_file(&buf, fd);4380 offset =0;4381while(offset < buf.len) {4382struct patch *patch;4383int nr;43844385 patch =xcalloc(1,sizeof(*patch));4386 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4387 patch->recount = !!(options & RECOUNT);4388 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);4389if(nr <0) {4390free_patch(patch);4391break;4392}4393if(apply_in_reverse)4394reverse_patches(patch);4395if(use_patch(patch)) {4396patch_stats(patch);4397*listp = patch;4398 listp = &patch->next;4399}4400else{4401if(apply_verbosely)4402say_patch_name(stderr,_("Skipped patch '%s'."), patch);4403free_patch(patch);4404 skipped_patch++;4405}4406 offset += nr;4407}44084409if(!list && !skipped_patch)4410die(_("unrecognized input"));44114412if(whitespace_error && (ws_error_action == die_on_ws_error))4413 apply =0;44144415 update_index = check_index && apply;4416if(update_index && newfd <0)4417 newfd =hold_locked_index(&lock_file,1);44184419if(check_index) {4420if(read_cache() <0)4421die(_("unable to read index file"));4422}44234424if((check || apply) &&4425check_patch_list(list) <0&&4426!apply_with_reject)4427exit(1);44284429if(apply &&write_out_results(list)) {4430if(apply_with_reject)4431exit(1);4432/* with --3way, we still need to write the index out */4433return1;4434}44354436if(fake_ancestor)4437build_fake_ancestor(list, fake_ancestor);44384439if(diffstat)4440stat_patch_list(list);44414442if(numstat)4443numstat_patch_list(list);44444445if(summary)4446summary_patch_list(list);44474448free_patch_list(list);4449strbuf_release(&buf);4450string_list_clear(&fn_table,0);4451return0;4452}44534454static voidgit_apply_config(void)4455{4456git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4457git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4458git_config(git_default_config, NULL);4459}44604461static intoption_parse_exclude(const struct option *opt,4462const char*arg,int unset)4463{4464add_name_limit(arg,1);4465return0;4466}44674468static intoption_parse_include(const struct option *opt,4469const char*arg,int unset)4470{4471add_name_limit(arg,0);4472 has_include =1;4473return0;4474}44754476static intoption_parse_p(const struct option *opt,4477const char*arg,int unset)4478{4479 state_p_value =atoi(arg);4480 p_value_known =1;4481return0;4482}44834484static intoption_parse_space_change(const struct option *opt,4485const char*arg,int unset)4486{4487if(unset)4488 ws_ignore_action = ignore_ws_none;4489else4490 ws_ignore_action = ignore_ws_change;4491return0;4492}44934494static intoption_parse_whitespace(const struct option *opt,4495const char*arg,int unset)4496{4497const char**whitespace_option = opt->value;44984499*whitespace_option = arg;4500parse_whitespace_option(arg);4501return0;4502}45034504static intoption_parse_directory(const struct option *opt,4505const char*arg,int unset)4506{4507strbuf_reset(&root);4508strbuf_addstr(&root, arg);4509strbuf_complete(&root,'/');4510return0;4511}45124513intcmd_apply(int argc,const char**argv,const char*prefix_)4514{4515int i;4516int errs =0;4517int is_not_gitdir = !startup_info->have_repository;4518int force_apply =0;4519int options =0;45204521const char*whitespace_option = NULL;45224523struct option builtin_apply_options[] = {4524{ OPTION_CALLBACK,0,"exclude", NULL,N_("path"),4525N_("don't apply changes matching the given path"),45260, option_parse_exclude },4527{ OPTION_CALLBACK,0,"include", NULL,N_("path"),4528N_("apply changes matching the given path"),45290, option_parse_include },4530{ OPTION_CALLBACK,'p', NULL, NULL,N_("num"),4531N_("remove <num> leading slashes from traditional diff paths"),45320, option_parse_p },4533OPT_BOOL(0,"no-add", &no_add,4534N_("ignore additions made by the patch")),4535OPT_BOOL(0,"stat", &diffstat,4536N_("instead of applying the patch, output diffstat for the input")),4537OPT_NOOP_NOARG(0,"allow-binary-replacement"),4538OPT_NOOP_NOARG(0,"binary"),4539OPT_BOOL(0,"numstat", &numstat,4540N_("show number of added and deleted lines in decimal notation")),4541OPT_BOOL(0,"summary", &summary,4542N_("instead of applying the patch, output a summary for the input")),4543OPT_BOOL(0,"check", &check,4544N_("instead of applying the patch, see if the patch is applicable")),4545OPT_BOOL(0,"index", &check_index,4546N_("make sure the patch is applicable to the current index")),4547OPT_BOOL(0,"cached", &cached,4548N_("apply a patch without touching the working tree")),4549OPT_BOOL(0,"unsafe-paths", &unsafe_paths,4550N_("accept a patch that touches outside the working area")),4551OPT_BOOL(0,"apply", &force_apply,4552N_("also apply the patch (use with --stat/--summary/--check)")),4553OPT_BOOL('3',"3way", &threeway,4554N_("attempt three-way merge if a patch does not apply")),4555OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,4556N_("build a temporary index based on embedded index information")),4557/* Think twice before adding "--nul" synonym to this */4558OPT_SET_INT('z', NULL, &line_termination,4559N_("paths are separated with NUL character"),'\0'),4560OPT_INTEGER('C', NULL, &p_context,4561N_("ensure at least <n> lines of context match")),4562{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,N_("action"),4563N_("detect new or modified lines that have whitespace errors"),45640, option_parse_whitespace },4565{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,4566N_("ignore changes in whitespace when finding context"),4567 PARSE_OPT_NOARG, option_parse_space_change },4568{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,4569N_("ignore changes in whitespace when finding context"),4570 PARSE_OPT_NOARG, option_parse_space_change },4571OPT_BOOL('R',"reverse", &apply_in_reverse,4572N_("apply the patch in reverse")),4573OPT_BOOL(0,"unidiff-zero", &unidiff_zero,4574N_("don't expect at least one line of context")),4575OPT_BOOL(0,"reject", &apply_with_reject,4576N_("leave the rejected hunks in corresponding *.rej files")),4577OPT_BOOL(0,"allow-overlap", &allow_overlap,4578N_("allow overlapping hunks")),4579OPT__VERBOSE(&apply_verbosely,N_("be verbose")),4580OPT_BIT(0,"inaccurate-eof", &options,4581N_("tolerate incorrectly detected missing new-line at the end of file"),4582 INACCURATE_EOF),4583OPT_BIT(0,"recount", &options,4584N_("do not trust the line counts in the hunk headers"),4585 RECOUNT),4586{ OPTION_CALLBACK,0,"directory", NULL,N_("root"),4587N_("prepend <root> to all filenames"),45880, option_parse_directory },4589OPT_END()4590};45914592 prefix = prefix_;4593 prefix_length = prefix ?strlen(prefix) :0;4594git_apply_config();4595if(apply_default_whitespace)4596parse_whitespace_option(apply_default_whitespace);4597if(apply_default_ignorewhitespace)4598parse_ignorewhitespace_option(apply_default_ignorewhitespace);45994600 argc =parse_options(argc, argv, prefix, builtin_apply_options,4601 apply_usage,0);46024603if(apply_with_reject && threeway)4604die("--reject and --3way cannot be used together.");4605if(cached && threeway)4606die("--cached and --3way cannot be used together.");4607if(threeway) {4608if(is_not_gitdir)4609die(_("--3way outside a repository"));4610 check_index =1;4611}4612if(apply_with_reject)4613 apply = apply_verbosely =1;4614if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))4615 apply =0;4616if(check_index && is_not_gitdir)4617die(_("--index outside a repository"));4618if(cached) {4619if(is_not_gitdir)4620die(_("--cached outside a repository"));4621 check_index =1;4622}4623if(check_index)4624 unsafe_paths =0;46254626for(i =0; i < argc; i++) {4627const char*arg = argv[i];4628int fd;46294630if(!strcmp(arg,"-")) {4631 errs |=apply_patch(0,"<stdin>", options);4632 read_stdin =0;4633continue;4634}else if(0< prefix_length)4635 arg =prefix_filename(prefix, prefix_length, arg);46364637 fd =open(arg, O_RDONLY);4638if(fd <0)4639die_errno(_("can't open patch '%s'"), arg);4640 read_stdin =0;4641set_default_whitespace_mode(whitespace_option);4642 errs |=apply_patch(fd, arg, options);4643close(fd);4644}4645set_default_whitespace_mode(whitespace_option);4646if(read_stdin)4647 errs |=apply_patch(0,"<stdin>", options);4648if(whitespace_error) {4649if(squelch_whitespace_errors &&4650 squelch_whitespace_errors < whitespace_error) {4651int squelched =4652 whitespace_error - squelch_whitespace_errors;4653warning(Q_("squelched%dwhitespace error",4654"squelched%dwhitespace errors",4655 squelched),4656 squelched);4657}4658if(ws_error_action == die_on_ws_error)4659die(Q_("%dline adds whitespace errors.",4660"%dlines add whitespace errors.",4661 whitespace_error),4662 whitespace_error);4663if(applied_after_fixing_ws && apply)4664warning("%dline%sapplied after"4665" fixing whitespace errors.",4666 applied_after_fixing_ws,4667 applied_after_fixing_ws ==1?"":"s");4668else if(whitespace_error)4669warning(Q_("%dline adds whitespace errors.",4670"%dlines add whitespace errors.",4671 whitespace_error),4672 whitespace_error);4673}46744675if(update_index) {4676if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK))4677die(_("Unable to write new index file"));4678}46794680return!!errs;4681}