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; 81 82static voidparse_whitespace_option(const char*option) 83{ 84if(!option) { 85 ws_error_action = warn_on_ws_error; 86return; 87} 88if(!strcmp(option,"warn")) { 89 ws_error_action = warn_on_ws_error; 90return; 91} 92if(!strcmp(option,"nowarn")) { 93 ws_error_action = nowarn_ws_error; 94return; 95} 96if(!strcmp(option,"error")) { 97 ws_error_action = die_on_ws_error; 98return; 99} 100if(!strcmp(option,"error-all")) { 101 ws_error_action = die_on_ws_error; 102 squelch_whitespace_errors =0; 103return; 104} 105if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 106 ws_error_action = correct_ws_error; 107return; 108} 109die(_("unrecognized whitespace option '%s'"), option); 110} 111 112static voidparse_ignorewhitespace_option(const char*option) 113{ 114if(!option || !strcmp(option,"no") || 115!strcmp(option,"false") || !strcmp(option,"never") || 116!strcmp(option,"none")) { 117 ws_ignore_action = ignore_ws_none; 118return; 119} 120if(!strcmp(option,"change")) { 121 ws_ignore_action = ignore_ws_change; 122return; 123} 124die(_("unrecognized whitespace ignore option '%s'"), option); 125} 126 127static voidset_default_whitespace_mode(const char*whitespace_option) 128{ 129if(!whitespace_option && !apply_default_whitespace) 130 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 131} 132 133/* 134 * For "diff-stat" like behaviour, we keep track of the biggest change 135 * we've seen, and the longest filename. That allows us to do simple 136 * scaling. 137 */ 138static int max_change, max_len; 139 140/* 141 * Various "current state", notably line numbers and what 142 * file (and how) we're patching right now.. The "is_xxxx" 143 * things are flags, where -1 means "don't know yet". 144 */ 145static int state_linenr =1; 146 147/* 148 * This represents one "hunk" from a patch, starting with 149 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 150 * patch text is pointed at by patch, and its byte length 151 * is stored in size. leading and trailing are the number 152 * of context lines. 153 */ 154struct fragment { 155unsigned long leading, trailing; 156unsigned long oldpos, oldlines; 157unsigned long newpos, newlines; 158/* 159 * 'patch' is usually borrowed from buf in apply_patch(), 160 * but some codepaths store an allocated buffer. 161 */ 162const char*patch; 163unsigned free_patch:1, 164 rejected:1; 165int size; 166int linenr; 167struct fragment *next; 168}; 169 170/* 171 * When dealing with a binary patch, we reuse "leading" field 172 * to store the type of the binary hunk, either deflated "delta" 173 * or deflated "literal". 174 */ 175#define binary_patch_method leading 176#define BINARY_DELTA_DEFLATED 1 177#define BINARY_LITERAL_DEFLATED 2 178 179/* 180 * This represents a "patch" to a file, both metainfo changes 181 * such as creation/deletion, filemode and content changes represented 182 * as a series of fragments. 183 */ 184struct patch { 185char*new_name, *old_name, *def_name; 186unsigned int old_mode, new_mode; 187int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 188int rejected; 189unsigned ws_rule; 190int lines_added, lines_deleted; 191int score; 192unsigned int is_toplevel_relative:1; 193unsigned int inaccurate_eof:1; 194unsigned int is_binary:1; 195unsigned int is_copy:1; 196unsigned int is_rename:1; 197unsigned int recount:1; 198unsigned int conflicted_threeway:1; 199unsigned int direct_to_threeway:1; 200struct fragment *fragments; 201char*result; 202size_t resultsize; 203char old_sha1_prefix[41]; 204char new_sha1_prefix[41]; 205struct patch *next; 206 207/* three-way fallback result */ 208struct object_id threeway_stage[3]; 209}; 210 211static voidfree_fragment_list(struct fragment *list) 212{ 213while(list) { 214struct fragment *next = list->next; 215if(list->free_patch) 216free((char*)list->patch); 217free(list); 218 list = next; 219} 220} 221 222static voidfree_patch(struct patch *patch) 223{ 224free_fragment_list(patch->fragments); 225free(patch->def_name); 226free(patch->old_name); 227free(patch->new_name); 228free(patch->result); 229free(patch); 230} 231 232static voidfree_patch_list(struct patch *list) 233{ 234while(list) { 235struct patch *next = list->next; 236free_patch(list); 237 list = next; 238} 239} 240 241/* 242 * A line in a file, len-bytes long (includes the terminating LF, 243 * except for an incomplete line at the end if the file ends with 244 * one), and its contents hashes to 'hash'. 245 */ 246struct line { 247size_t len; 248unsigned hash :24; 249unsigned flag :8; 250#define LINE_COMMON 1 251#define LINE_PATCHED 2 252}; 253 254/* 255 * This represents a "file", which is an array of "lines". 256 */ 257struct image { 258char*buf; 259size_t len; 260size_t nr; 261size_t alloc; 262struct line *line_allocated; 263struct line *line; 264}; 265 266/* 267 * Records filenames that have been touched, in order to handle 268 * the case where more than one patches touch the same file. 269 */ 270 271static struct string_list fn_table; 272 273static uint32_thash_line(const char*cp,size_t len) 274{ 275size_t i; 276uint32_t h; 277for(i =0, h =0; i < len; i++) { 278if(!isspace(cp[i])) { 279 h = h *3+ (cp[i] &0xff); 280} 281} 282return h; 283} 284 285/* 286 * Compare lines s1 of length n1 and s2 of length n2, ignoring 287 * whitespace difference. Returns 1 if they match, 0 otherwise 288 */ 289static intfuzzy_matchlines(const char*s1,size_t n1, 290const char*s2,size_t n2) 291{ 292const char*last1 = s1 + n1 -1; 293const char*last2 = s2 + n2 -1; 294int result =0; 295 296/* ignore line endings */ 297while((*last1 =='\r') || (*last1 =='\n')) 298 last1--; 299while((*last2 =='\r') || (*last2 =='\n')) 300 last2--; 301 302/* skip leading whitespaces, if both begin with whitespace */ 303if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 304while(isspace(*s1) && (s1 <= last1)) 305 s1++; 306while(isspace(*s2) && (s2 <= last2)) 307 s2++; 308} 309/* early return if both lines are empty */ 310if((s1 > last1) && (s2 > last2)) 311return1; 312while(!result) { 313 result = *s1++ - *s2++; 314/* 315 * Skip whitespace inside. We check for whitespace on 316 * both buffers because we don't want "a b" to match 317 * "ab" 318 */ 319if(isspace(*s1) &&isspace(*s2)) { 320while(isspace(*s1) && s1 <= last1) 321 s1++; 322while(isspace(*s2) && s2 <= last2) 323 s2++; 324} 325/* 326 * If we reached the end on one side only, 327 * lines don't match 328 */ 329if( 330((s2 > last2) && (s1 <= last1)) || 331((s1 > last1) && (s2 <= last2))) 332return0; 333if((s1 > last1) && (s2 > last2)) 334break; 335} 336 337return!result; 338} 339 340static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 341{ 342ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 343 img->line_allocated[img->nr].len = len; 344 img->line_allocated[img->nr].hash =hash_line(bol, len); 345 img->line_allocated[img->nr].flag = flag; 346 img->nr++; 347} 348 349/* 350 * "buf" has the file contents to be patched (read from various sources). 351 * attach it to "image" and add line-based index to it. 352 * "image" now owns the "buf". 353 */ 354static voidprepare_image(struct image *image,char*buf,size_t len, 355int prepare_linetable) 356{ 357const char*cp, *ep; 358 359memset(image,0,sizeof(*image)); 360 image->buf = buf; 361 image->len = len; 362 363if(!prepare_linetable) 364return; 365 366 ep = image->buf + image->len; 367 cp = image->buf; 368while(cp < ep) { 369const char*next; 370for(next = cp; next < ep && *next !='\n'; next++) 371; 372if(next < ep) 373 next++; 374add_line_info(image, cp, next - cp,0); 375 cp = next; 376} 377 image->line = image->line_allocated; 378} 379 380static voidclear_image(struct image *image) 381{ 382free(image->buf); 383free(image->line_allocated); 384memset(image,0,sizeof(*image)); 385} 386 387/* fmt must contain _one_ %s and no other substitution */ 388static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 389{ 390struct strbuf sb = STRBUF_INIT; 391 392if(patch->old_name && patch->new_name && 393strcmp(patch->old_name, patch->new_name)) { 394quote_c_style(patch->old_name, &sb, NULL,0); 395strbuf_addstr(&sb," => "); 396quote_c_style(patch->new_name, &sb, NULL,0); 397}else{ 398const char*n = patch->new_name; 399if(!n) 400 n = patch->old_name; 401quote_c_style(n, &sb, NULL,0); 402} 403fprintf(output, fmt, sb.buf); 404fputc('\n', output); 405strbuf_release(&sb); 406} 407 408#define SLOP (16) 409 410static voidread_patch_file(struct strbuf *sb,int fd) 411{ 412if(strbuf_read(sb, fd,0) <0) 413die_errno("git apply: failed to read"); 414 415/* 416 * Make sure that we have some slop in the buffer 417 * so that we can do speculative "memcmp" etc, and 418 * see to it that it is NUL-filled. 419 */ 420strbuf_grow(sb, SLOP); 421memset(sb->buf + sb->len,0, SLOP); 422} 423 424static unsigned longlinelen(const char*buffer,unsigned long size) 425{ 426unsigned long len =0; 427while(size--) { 428 len++; 429if(*buffer++ =='\n') 430break; 431} 432return len; 433} 434 435static intis_dev_null(const char*str) 436{ 437returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 438} 439 440#define TERM_SPACE 1 441#define TERM_TAB 2 442 443static intname_terminate(const char*name,int namelen,int c,int terminate) 444{ 445if(c ==' '&& !(terminate & TERM_SPACE)) 446return0; 447if(c =='\t'&& !(terminate & TERM_TAB)) 448return0; 449 450return1; 451} 452 453/* remove double slashes to make --index work with such filenames */ 454static char*squash_slash(char*name) 455{ 456int i =0, j =0; 457 458if(!name) 459return NULL; 460 461while(name[i]) { 462if((name[j++] = name[i++]) =='/') 463while(name[i] =='/') 464 i++; 465} 466 name[j] ='\0'; 467return name; 468} 469 470static char*find_name_gnu(const char*line,const char*def,int p_value) 471{ 472struct strbuf name = STRBUF_INIT; 473char*cp; 474 475/* 476 * Proposed "new-style" GNU patch/diff format; see 477 * http://marc.info/?l=git&m=112927316408690&w=2 478 */ 479if(unquote_c_style(&name, line, NULL)) { 480strbuf_release(&name); 481return NULL; 482} 483 484for(cp = name.buf; p_value; p_value--) { 485 cp =strchr(cp,'/'); 486if(!cp) { 487strbuf_release(&name); 488return NULL; 489} 490 cp++; 491} 492 493strbuf_remove(&name,0, cp - name.buf); 494if(root.len) 495strbuf_insert(&name,0, root.buf, root.len); 496returnsquash_slash(strbuf_detach(&name, NULL)); 497} 498 499static size_tsane_tz_len(const char*line,size_t len) 500{ 501const char*tz, *p; 502 503if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 504return0; 505 tz = line + len -strlen(" +0500"); 506 507if(tz[1] !='+'&& tz[1] !='-') 508return0; 509 510for(p = tz +2; p != line + len; p++) 511if(!isdigit(*p)) 512return0; 513 514return line + len - tz; 515} 516 517static size_ttz_with_colon_len(const char*line,size_t len) 518{ 519const char*tz, *p; 520 521if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 522return0; 523 tz = line + len -strlen(" +08:00"); 524 525if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 526return0; 527 p = tz +2; 528if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 529!isdigit(*p++) || !isdigit(*p++)) 530return0; 531 532return line + len - tz; 533} 534 535static size_tdate_len(const char*line,size_t len) 536{ 537const char*date, *p; 538 539if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 540return0; 541 p = date = line + len -strlen("72-02-05"); 542 543if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 544!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 545!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 546return0; 547 548if(date - line >=strlen("19") && 549isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 550 date -=strlen("19"); 551 552return line + len - date; 553} 554 555static size_tshort_time_len(const char*line,size_t len) 556{ 557const char*time, *p; 558 559if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 560return0; 561 p = time = line + len -strlen(" 07:01:32"); 562 563/* Permit 1-digit hours? */ 564if(*p++ !=' '|| 565!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 566!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 567!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 568return0; 569 570return line + len - time; 571} 572 573static size_tfractional_time_len(const char*line,size_t len) 574{ 575const char*p; 576size_t n; 577 578/* Expected format: 19:41:17.620000023 */ 579if(!len || !isdigit(line[len -1])) 580return0; 581 p = line + len -1; 582 583/* Fractional seconds. */ 584while(p > line &&isdigit(*p)) 585 p--; 586if(*p !='.') 587return0; 588 589/* Hours, minutes, and whole seconds. */ 590 n =short_time_len(line, p - line); 591if(!n) 592return0; 593 594return line + len - p + n; 595} 596 597static size_ttrailing_spaces_len(const char*line,size_t len) 598{ 599const char*p; 600 601/* Expected format: ' ' x (1 or more) */ 602if(!len || line[len -1] !=' ') 603return0; 604 605 p = line + len; 606while(p != line) { 607 p--; 608if(*p !=' ') 609return line + len - (p +1); 610} 611 612/* All spaces! */ 613return len; 614} 615 616static size_tdiff_timestamp_len(const char*line,size_t len) 617{ 618const char*end = line + len; 619size_t n; 620 621/* 622 * Posix: 2010-07-05 19:41:17 623 * GNU: 2010-07-05 19:41:17.620000023 -0500 624 */ 625 626if(!isdigit(end[-1])) 627return0; 628 629 n =sane_tz_len(line, end - line); 630if(!n) 631 n =tz_with_colon_len(line, end - line); 632 end -= n; 633 634 n =short_time_len(line, end - line); 635if(!n) 636 n =fractional_time_len(line, end - line); 637 end -= n; 638 639 n =date_len(line, end - line); 640if(!n)/* No date. Too bad. */ 641return0; 642 end -= n; 643 644if(end == line)/* No space before date. */ 645return0; 646if(end[-1] =='\t') {/* Success! */ 647 end--; 648return line + len - end; 649} 650if(end[-1] !=' ')/* No space before date. */ 651return0; 652 653/* Whitespace damage. */ 654 end -=trailing_spaces_len(line, end - line); 655return line + len - end; 656} 657 658static char*find_name_common(const char*line,const char*def, 659int p_value,const char*end,int terminate) 660{ 661int len; 662const char*start = NULL; 663 664if(p_value ==0) 665 start = line; 666while(line != end) { 667char c = *line; 668 669if(!end &&isspace(c)) { 670if(c =='\n') 671break; 672if(name_terminate(start, line-start, c, terminate)) 673break; 674} 675 line++; 676if(c =='/'&& !--p_value) 677 start = line; 678} 679if(!start) 680returnsquash_slash(xstrdup_or_null(def)); 681 len = line - start; 682if(!len) 683returnsquash_slash(xstrdup_or_null(def)); 684 685/* 686 * Generally we prefer the shorter name, especially 687 * if the other one is just a variation of that with 688 * something else tacked on to the end (ie "file.orig" 689 * or "file~"). 690 */ 691if(def) { 692int deflen =strlen(def); 693if(deflen < len && !strncmp(start, def, deflen)) 694returnsquash_slash(xstrdup(def)); 695} 696 697if(root.len) { 698char*ret =xstrfmt("%s%.*s", root.buf, len, start); 699returnsquash_slash(ret); 700} 701 702returnsquash_slash(xmemdupz(start, len)); 703} 704 705static char*find_name(const char*line,char*def,int p_value,int terminate) 706{ 707if(*line =='"') { 708char*name =find_name_gnu(line, def, p_value); 709if(name) 710return name; 711} 712 713returnfind_name_common(line, def, p_value, NULL, terminate); 714} 715 716static char*find_name_traditional(const char*line,char*def,int p_value) 717{ 718size_t len; 719size_t date_len; 720 721if(*line =='"') { 722char*name =find_name_gnu(line, def, p_value); 723if(name) 724return name; 725} 726 727 len =strchrnul(line,'\n') - line; 728 date_len =diff_timestamp_len(line, len); 729if(!date_len) 730returnfind_name_common(line, def, p_value, NULL, TERM_TAB); 731 len -= date_len; 732 733returnfind_name_common(line, def, p_value, line + len,0); 734} 735 736static intcount_slashes(const char*cp) 737{ 738int cnt =0; 739char ch; 740 741while((ch = *cp++)) 742if(ch =='/') 743 cnt++; 744return cnt; 745} 746 747/* 748 * Given the string after "--- " or "+++ ", guess the appropriate 749 * p_value for the given patch. 750 */ 751static intguess_p_value(const char*nameline) 752{ 753char*name, *cp; 754int val = -1; 755 756if(is_dev_null(nameline)) 757return-1; 758 name =find_name_traditional(nameline, NULL,0); 759if(!name) 760return-1; 761 cp =strchr(name,'/'); 762if(!cp) 763 val =0; 764else if(prefix) { 765/* 766 * Does it begin with "a/$our-prefix" and such? Then this is 767 * very likely to apply to our directory. 768 */ 769if(!strncmp(name, prefix, prefix_length)) 770 val =count_slashes(prefix); 771else{ 772 cp++; 773if(!strncmp(cp, prefix, prefix_length)) 774 val =count_slashes(prefix) +1; 775} 776} 777free(name); 778return val; 779} 780 781/* 782 * Does the ---/+++ line have the POSIX timestamp after the last HT? 783 * GNU diff puts epoch there to signal a creation/deletion event. Is 784 * this such a timestamp? 785 */ 786static inthas_epoch_timestamp(const char*nameline) 787{ 788/* 789 * We are only interested in epoch timestamp; any non-zero 790 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 791 * For the same reason, the date must be either 1969-12-31 or 792 * 1970-01-01, and the seconds part must be "00". 793 */ 794const char stamp_regexp[] = 795"^(1969-12-31|1970-01-01)" 796" " 797"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 798" " 799"([-+][0-2][0-9]:?[0-5][0-9])\n"; 800const char*timestamp = NULL, *cp, *colon; 801static regex_t *stamp; 802 regmatch_t m[10]; 803int zoneoffset; 804int hourminute; 805int status; 806 807for(cp = nameline; *cp !='\n'; cp++) { 808if(*cp =='\t') 809 timestamp = cp +1; 810} 811if(!timestamp) 812return0; 813if(!stamp) { 814 stamp =xmalloc(sizeof(*stamp)); 815if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 816warning(_("Cannot prepare timestamp regexp%s"), 817 stamp_regexp); 818return0; 819} 820} 821 822 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 823if(status) { 824if(status != REG_NOMATCH) 825warning(_("regexec returned%dfor input:%s"), 826 status, timestamp); 827return0; 828} 829 830 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 831if(*colon ==':') 832 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 833else 834 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 835if(timestamp[m[3].rm_so] =='-') 836 zoneoffset = -zoneoffset; 837 838/* 839 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 840 * (west of GMT) or 1970-01-01 (east of GMT) 841 */ 842if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 843(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 844return0; 845 846 hourminute = (strtol(timestamp +11, NULL,10) *60+ 847strtol(timestamp +14, NULL,10) - 848 zoneoffset); 849 850return((zoneoffset <0&& hourminute ==1440) || 851(0<= zoneoffset && !hourminute)); 852} 853 854/* 855 * Get the name etc info from the ---/+++ lines of a traditional patch header 856 * 857 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 858 * files, we can happily check the index for a match, but for creating a 859 * new file we should try to match whatever "patch" does. I have no idea. 860 */ 861static voidparse_traditional_patch(const char*first,const char*second,struct patch *patch) 862{ 863char*name; 864 865 first +=4;/* skip "--- " */ 866 second +=4;/* skip "+++ " */ 867if(!p_value_known) { 868int p, q; 869 p =guess_p_value(first); 870 q =guess_p_value(second); 871if(p <0) p = q; 872if(0<= p && p == q) { 873 state_p_value = p; 874 p_value_known =1; 875} 876} 877if(is_dev_null(first)) { 878 patch->is_new =1; 879 patch->is_delete =0; 880 name =find_name_traditional(second, NULL, state_p_value); 881 patch->new_name = name; 882}else if(is_dev_null(second)) { 883 patch->is_new =0; 884 patch->is_delete =1; 885 name =find_name_traditional(first, NULL, state_p_value); 886 patch->old_name = name; 887}else{ 888char*first_name; 889 first_name =find_name_traditional(first, NULL, state_p_value); 890 name =find_name_traditional(second, first_name, state_p_value); 891free(first_name); 892if(has_epoch_timestamp(first)) { 893 patch->is_new =1; 894 patch->is_delete =0; 895 patch->new_name = name; 896}else if(has_epoch_timestamp(second)) { 897 patch->is_new =0; 898 patch->is_delete =1; 899 patch->old_name = name; 900}else{ 901 patch->old_name = name; 902 patch->new_name =xstrdup_or_null(name); 903} 904} 905if(!name) 906die(_("unable to find filename in patch at line%d"), state_linenr); 907} 908 909static intgitdiff_hdrend(const char*line,struct patch *patch) 910{ 911return-1; 912} 913 914/* 915 * We're anal about diff header consistency, to make 916 * sure that we don't end up having strange ambiguous 917 * patches floating around. 918 * 919 * As a result, gitdiff_{old|new}name() will check 920 * their names against any previous information, just 921 * to make sure.. 922 */ 923#define DIFF_OLD_NAME 0 924#define DIFF_NEW_NAME 1 925 926static voidgitdiff_verify_name(const char*line,int isnull,char**name,int side) 927{ 928if(!*name && !isnull) { 929*name =find_name(line, NULL, state_p_value, TERM_TAB); 930return; 931} 932 933if(*name) { 934int len =strlen(*name); 935char*another; 936if(isnull) 937die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 938*name, state_linenr); 939 another =find_name(line, NULL, state_p_value, TERM_TAB); 940if(!another ||memcmp(another, *name, len +1)) 941die((side == DIFF_NEW_NAME) ? 942_("git apply: bad git-diff - inconsistent new filename on line%d") : 943_("git apply: bad git-diff - inconsistent old filename on line%d"), state_linenr); 944free(another); 945}else{ 946/* expect "/dev/null" */ 947if(memcmp("/dev/null", line,9) || line[9] !='\n') 948die(_("git apply: bad git-diff - expected /dev/null on line%d"), state_linenr); 949} 950} 951 952static intgitdiff_oldname(const char*line,struct patch *patch) 953{ 954gitdiff_verify_name(line, patch->is_new, &patch->old_name, 955 DIFF_OLD_NAME); 956return0; 957} 958 959static intgitdiff_newname(const char*line,struct patch *patch) 960{ 961gitdiff_verify_name(line, patch->is_delete, &patch->new_name, 962 DIFF_NEW_NAME); 963return0; 964} 965 966static intgitdiff_oldmode(const char*line,struct patch *patch) 967{ 968 patch->old_mode =strtoul(line, NULL,8); 969return0; 970} 971 972static intgitdiff_newmode(const char*line,struct patch *patch) 973{ 974 patch->new_mode =strtoul(line, NULL,8); 975return0; 976} 977 978static intgitdiff_delete(const char*line,struct patch *patch) 979{ 980 patch->is_delete =1; 981free(patch->old_name); 982 patch->old_name =xstrdup_or_null(patch->def_name); 983returngitdiff_oldmode(line, patch); 984} 985 986static intgitdiff_newfile(const char*line,struct patch *patch) 987{ 988 patch->is_new =1; 989free(patch->new_name); 990 patch->new_name =xstrdup_or_null(patch->def_name); 991returngitdiff_newmode(line, patch); 992} 993 994static intgitdiff_copysrc(const char*line,struct patch *patch) 995{ 996 patch->is_copy =1; 997free(patch->old_name); 998 patch->old_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0); 999return0;1000}10011002static intgitdiff_copydst(const char*line,struct patch *patch)1003{1004 patch->is_copy =1;1005free(patch->new_name);1006 patch->new_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1007return0;1008}10091010static intgitdiff_renamesrc(const char*line,struct patch *patch)1011{1012 patch->is_rename =1;1013free(patch->old_name);1014 patch->old_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1015return0;1016}10171018static intgitdiff_renamedst(const char*line,struct patch *patch)1019{1020 patch->is_rename =1;1021free(patch->new_name);1022 patch->new_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1023return0;1024}10251026static intgitdiff_similarity(const char*line,struct patch *patch)1027{1028unsigned long val =strtoul(line, NULL,10);1029if(val <=100)1030 patch->score = val;1031return0;1032}10331034static intgitdiff_dissimilarity(const char*line,struct patch *patch)1035{1036unsigned long val =strtoul(line, NULL,10);1037if(val <=100)1038 patch->score = val;1039return0;1040}10411042static intgitdiff_index(const char*line,struct patch *patch)1043{1044/*1045 * index line is N hexadecimal, "..", N hexadecimal,1046 * and optional space with octal mode.1047 */1048const char*ptr, *eol;1049int len;10501051 ptr =strchr(line,'.');1052if(!ptr || ptr[1] !='.'||40< ptr - line)1053return0;1054 len = ptr - line;1055memcpy(patch->old_sha1_prefix, line, len);1056 patch->old_sha1_prefix[len] =0;10571058 line = ptr +2;1059 ptr =strchr(line,' ');1060 eol =strchrnul(line,'\n');10611062if(!ptr || eol < ptr)1063 ptr = eol;1064 len = ptr - line;10651066if(40< len)1067return0;1068memcpy(patch->new_sha1_prefix, line, len);1069 patch->new_sha1_prefix[len] =0;1070if(*ptr ==' ')1071 patch->old_mode =strtoul(ptr+1, NULL,8);1072return0;1073}10741075/*1076 * This is normal for a diff that doesn't change anything: we'll fall through1077 * into the next diff. Tell the parser to break out.1078 */1079static intgitdiff_unrecognized(const char*line,struct patch *patch)1080{1081return-1;1082}10831084/*1085 * Skip p_value leading components from "line"; as we do not accept1086 * absolute paths, return NULL in that case.1087 */1088static const char*skip_tree_prefix(const char*line,int llen)1089{1090int nslash;1091int i;10921093if(!state_p_value)1094return(llen && line[0] =='/') ? NULL : line;10951096 nslash = state_p_value;1097for(i =0; i < llen; i++) {1098int ch = line[i];1099if(ch =='/'&& --nslash <=0)1100return(i ==0) ? NULL : &line[i +1];1101}1102return NULL;1103}11041105/*1106 * This is to extract the same name that appears on "diff --git"1107 * line. We do not find and return anything if it is a rename1108 * patch, and it is OK because we will find the name elsewhere.1109 * We need to reliably find name only when it is mode-change only,1110 * creation or deletion of an empty file. In any of these cases,1111 * both sides are the same name under a/ and b/ respectively.1112 */1113static char*git_header_name(const char*line,int llen)1114{1115const char*name;1116const char*second = NULL;1117size_t len, line_len;11181119 line +=strlen("diff --git ");1120 llen -=strlen("diff --git ");11211122if(*line =='"') {1123const char*cp;1124struct strbuf first = STRBUF_INIT;1125struct strbuf sp = STRBUF_INIT;11261127if(unquote_c_style(&first, line, &second))1128goto free_and_fail1;11291130/* strip the a/b prefix including trailing slash */1131 cp =skip_tree_prefix(first.buf, first.len);1132if(!cp)1133goto free_and_fail1;1134strbuf_remove(&first,0, cp - first.buf);11351136/*1137 * second points at one past closing dq of name.1138 * find the second name.1139 */1140while((second < line + llen) &&isspace(*second))1141 second++;11421143if(line + llen <= second)1144goto free_and_fail1;1145if(*second =='"') {1146if(unquote_c_style(&sp, second, NULL))1147goto free_and_fail1;1148 cp =skip_tree_prefix(sp.buf, sp.len);1149if(!cp)1150goto free_and_fail1;1151/* They must match, otherwise ignore */1152if(strcmp(cp, first.buf))1153goto free_and_fail1;1154strbuf_release(&sp);1155returnstrbuf_detach(&first, NULL);1156}11571158/* unquoted second */1159 cp =skip_tree_prefix(second, line + llen - second);1160if(!cp)1161goto free_and_fail1;1162if(line + llen - cp != first.len ||1163memcmp(first.buf, cp, first.len))1164goto free_and_fail1;1165returnstrbuf_detach(&first, NULL);11661167 free_and_fail1:1168strbuf_release(&first);1169strbuf_release(&sp);1170return NULL;1171}11721173/* unquoted first name */1174 name =skip_tree_prefix(line, llen);1175if(!name)1176return NULL;11771178/*1179 * since the first name is unquoted, a dq if exists must be1180 * the beginning of the second name.1181 */1182for(second = name; second < line + llen; second++) {1183if(*second =='"') {1184struct strbuf sp = STRBUF_INIT;1185const char*np;11861187if(unquote_c_style(&sp, second, NULL))1188goto free_and_fail2;11891190 np =skip_tree_prefix(sp.buf, sp.len);1191if(!np)1192goto free_and_fail2;11931194 len = sp.buf + sp.len - np;1195if(len < second - name &&1196!strncmp(np, name, len) &&1197isspace(name[len])) {1198/* Good */1199strbuf_remove(&sp,0, np - sp.buf);1200returnstrbuf_detach(&sp, NULL);1201}12021203 free_and_fail2:1204strbuf_release(&sp);1205return NULL;1206}1207}12081209/*1210 * Accept a name only if it shows up twice, exactly the same1211 * form.1212 */1213 second =strchr(name,'\n');1214if(!second)1215return NULL;1216 line_len = second - name;1217for(len =0; ; len++) {1218switch(name[len]) {1219default:1220continue;1221case'\n':1222return NULL;1223case'\t':case' ':1224/*1225 * Is this the separator between the preimage1226 * and the postimage pathname? Again, we are1227 * only interested in the case where there is1228 * no rename, as this is only to set def_name1229 * and a rename patch has the names elsewhere1230 * in an unambiguous form.1231 */1232if(!name[len +1])1233return NULL;/* no postimage name */1234 second =skip_tree_prefix(name + len +1,1235 line_len - (len +1));1236if(!second)1237return NULL;1238/*1239 * Does len bytes starting at "name" and "second"1240 * (that are separated by one HT or SP we just1241 * found) exactly match?1242 */1243if(second[len] =='\n'&& !strncmp(name, second, len))1244returnxmemdupz(name, len);1245}1246}1247}12481249/* Verify that we recognize the lines following a git header */1250static intparse_git_header(const char*line,int len,unsigned int size,struct patch *patch)1251{1252unsigned long offset;12531254/* A git diff has explicit new/delete information, so we don't guess */1255 patch->is_new =0;1256 patch->is_delete =0;12571258/*1259 * Some things may not have the old name in the1260 * rest of the headers anywhere (pure mode changes,1261 * or removing or adding empty files), so we get1262 * the default name from the header.1263 */1264 patch->def_name =git_header_name(line, len);1265if(patch->def_name && root.len) {1266char*s =xstrfmt("%s%s", root.buf, patch->def_name);1267free(patch->def_name);1268 patch->def_name = s;1269}12701271 line += len;1272 size -= len;1273 state_linenr++;1274for(offset = len ; size >0; offset += len, size -= len, line += len, state_linenr++) {1275static const struct opentry {1276const char*str;1277int(*fn)(const char*,struct patch *);1278} optable[] = {1279{"@@ -", gitdiff_hdrend },1280{"--- ", gitdiff_oldname },1281{"+++ ", gitdiff_newname },1282{"old mode ", gitdiff_oldmode },1283{"new mode ", gitdiff_newmode },1284{"deleted file mode ", gitdiff_delete },1285{"new file mode ", gitdiff_newfile },1286{"copy from ", gitdiff_copysrc },1287{"copy to ", gitdiff_copydst },1288{"rename old ", gitdiff_renamesrc },1289{"rename new ", gitdiff_renamedst },1290{"rename from ", gitdiff_renamesrc },1291{"rename to ", gitdiff_renamedst },1292{"similarity index ", gitdiff_similarity },1293{"dissimilarity index ", gitdiff_dissimilarity },1294{"index ", gitdiff_index },1295{"", gitdiff_unrecognized },1296};1297int i;12981299 len =linelen(line, size);1300if(!len || line[len-1] !='\n')1301break;1302for(i =0; i <ARRAY_SIZE(optable); i++) {1303const struct opentry *p = optable + i;1304int oplen =strlen(p->str);1305if(len < oplen ||memcmp(p->str, line, oplen))1306continue;1307if(p->fn(line + oplen, patch) <0)1308return offset;1309break;1310}1311}13121313return offset;1314}13151316static intparse_num(const char*line,unsigned long*p)1317{1318char*ptr;13191320if(!isdigit(*line))1321return0;1322*p =strtoul(line, &ptr,10);1323return ptr - line;1324}13251326static intparse_range(const char*line,int len,int offset,const char*expect,1327unsigned long*p1,unsigned long*p2)1328{1329int digits, ex;13301331if(offset <0|| offset >= len)1332return-1;1333 line += offset;1334 len -= offset;13351336 digits =parse_num(line, p1);1337if(!digits)1338return-1;13391340 offset += digits;1341 line += digits;1342 len -= digits;13431344*p2 =1;1345if(*line ==',') {1346 digits =parse_num(line+1, p2);1347if(!digits)1348return-1;13491350 offset += digits+1;1351 line += digits+1;1352 len -= digits+1;1353}13541355 ex =strlen(expect);1356if(ex > len)1357return-1;1358if(memcmp(line, expect, ex))1359return-1;13601361return offset + ex;1362}13631364static voidrecount_diff(const char*line,int size,struct fragment *fragment)1365{1366int oldlines =0, newlines =0, ret =0;13671368if(size <1) {1369warning("recount: ignore empty hunk");1370return;1371}13721373for(;;) {1374int len =linelen(line, size);1375 size -= len;1376 line += len;13771378if(size <1)1379break;13801381switch(*line) {1382case' ':case'\n':1383 newlines++;1384/* fall through */1385case'-':1386 oldlines++;1387continue;1388case'+':1389 newlines++;1390continue;1391case'\\':1392continue;1393case'@':1394 ret = size <3|| !starts_with(line,"@@ ");1395break;1396case'd':1397 ret = size <5|| !starts_with(line,"diff ");1398break;1399default:1400 ret = -1;1401break;1402}1403if(ret) {1404warning(_("recount: unexpected line: %.*s"),1405(int)linelen(line, size), line);1406return;1407}1408break;1409}1410 fragment->oldlines = oldlines;1411 fragment->newlines = newlines;1412}14131414/*1415 * Parse a unified diff fragment header of the1416 * form "@@ -a,b +c,d @@"1417 */1418static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1419{1420int offset;14211422if(!len || line[len-1] !='\n')1423return-1;14241425/* Figure out the number of lines in a fragment */1426 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1427 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14281429return offset;1430}14311432static intfind_header(const char*line,unsigned long size,int*hdrsize,struct patch *patch)1433{1434unsigned long offset, len;14351436 patch->is_toplevel_relative =0;1437 patch->is_rename = patch->is_copy =0;1438 patch->is_new = patch->is_delete = -1;1439 patch->old_mode = patch->new_mode =0;1440 patch->old_name = patch->new_name = NULL;1441for(offset =0; size >0; offset += len, size -= len, line += len, state_linenr++) {1442unsigned long nextlen;14431444 len =linelen(line, size);1445if(!len)1446break;14471448/* Testing this early allows us to take a few shortcuts.. */1449if(len <6)1450continue;14511452/*1453 * Make sure we don't find any unconnected patch fragments.1454 * That's a sign that we didn't find a header, and that a1455 * patch has become corrupted/broken up.1456 */1457if(!memcmp("@@ -", line,4)) {1458struct fragment dummy;1459if(parse_fragment_header(line, len, &dummy) <0)1460continue;1461die(_("patch fragment without header at line%d: %.*s"),1462 state_linenr, (int)len-1, line);1463}14641465if(size < len +6)1466break;14671468/*1469 * Git patch? It might not have a real patch, just a rename1470 * or mode change, so we handle that specially1471 */1472if(!memcmp("diff --git ", line,11)) {1473int git_hdr_len =parse_git_header(line, len, size, patch);1474if(git_hdr_len <= len)1475continue;1476if(!patch->old_name && !patch->new_name) {1477if(!patch->def_name)1478die(Q_("git diff header lacks filename information when removing "1479"%dleading pathname component (line%d)",1480"git diff header lacks filename information when removing "1481"%dleading pathname components (line%d)",1482 state_p_value),1483 state_p_value, state_linenr);1484 patch->old_name =xstrdup(patch->def_name);1485 patch->new_name =xstrdup(patch->def_name);1486}1487if(!patch->is_delete && !patch->new_name)1488die("git diff header lacks filename information "1489"(line%d)", state_linenr);1490 patch->is_toplevel_relative =1;1491*hdrsize = git_hdr_len;1492return offset;1493}14941495/* --- followed by +++ ? */1496if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1497continue;14981499/*1500 * We only accept unified patches, so we want it to1501 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1502 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1503 */1504 nextlen =linelen(line + len, size - len);1505if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1506continue;15071508/* Ok, we'll consider it a patch */1509parse_traditional_patch(line, line+len, patch);1510*hdrsize = len + nextlen;1511 state_linenr +=2;1512return offset;1513}1514return-1;1515}15161517static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1518{1519char*err;15201521if(!result)1522return;15231524 whitespace_error++;1525if(squelch_whitespace_errors &&1526 squelch_whitespace_errors < whitespace_error)1527return;15281529 err =whitespace_error_string(result);1530fprintf(stderr,"%s:%d:%s.\n%.*s\n",1531 patch_input_file, linenr, err, len, line);1532free(err);1533}15341535static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1536{1537unsigned result =ws_check(line +1, len -1, ws_rule);15381539record_ws_error(result, line +1, len -2, state_linenr);1540}15411542/*1543 * Parse a unified diff. Note that this really needs to parse each1544 * fragment separately, since the only way to know the difference1545 * between a "---" that is part of a patch, and a "---" that starts1546 * the next patch is to look at the line counts..1547 */1548static intparse_fragment(const char*line,unsigned long size,1549struct patch *patch,struct fragment *fragment)1550{1551int added, deleted;1552int len =linelen(line, size), offset;1553unsigned long oldlines, newlines;1554unsigned long leading, trailing;15551556 offset =parse_fragment_header(line, len, fragment);1557if(offset <0)1558return-1;1559if(offset >0&& patch->recount)1560recount_diff(line + offset, size - offset, fragment);1561 oldlines = fragment->oldlines;1562 newlines = fragment->newlines;1563 leading =0;1564 trailing =0;15651566/* Parse the thing.. */1567 line += len;1568 size -= len;1569 state_linenr++;1570 added = deleted =0;1571for(offset = len;15720< size;1573 offset += len, size -= len, line += len, state_linenr++) {1574if(!oldlines && !newlines)1575break;1576 len =linelen(line, size);1577if(!len || line[len-1] !='\n')1578return-1;1579switch(*line) {1580default:1581return-1;1582case'\n':/* newer GNU diff, an empty context line */1583case' ':1584 oldlines--;1585 newlines--;1586if(!deleted && !added)1587 leading++;1588 trailing++;1589if(!apply_in_reverse &&1590 ws_error_action == correct_ws_error)1591check_whitespace(line, len, patch->ws_rule);1592break;1593case'-':1594if(apply_in_reverse &&1595 ws_error_action != nowarn_ws_error)1596check_whitespace(line, len, patch->ws_rule);1597 deleted++;1598 oldlines--;1599 trailing =0;1600break;1601case'+':1602if(!apply_in_reverse &&1603 ws_error_action != nowarn_ws_error)1604check_whitespace(line, len, patch->ws_rule);1605 added++;1606 newlines--;1607 trailing =0;1608break;16091610/*1611 * We allow "\ No newline at end of file". Depending1612 * on locale settings when the patch was produced we1613 * don't know what this line looks like. The only1614 * thing we do know is that it begins with "\ ".1615 * Checking for 12 is just for sanity check -- any1616 * l10n of "\ No newline..." is at least that long.1617 */1618case'\\':1619if(len <12||memcmp(line,"\\",2))1620return-1;1621break;1622}1623}1624if(oldlines || newlines)1625return-1;1626if(!deleted && !added)1627return-1;16281629 fragment->leading = leading;1630 fragment->trailing = trailing;16311632/*1633 * If a fragment ends with an incomplete line, we failed to include1634 * it in the above loop because we hit oldlines == newlines == 01635 * before seeing it.1636 */1637if(12< size && !memcmp(line,"\\",2))1638 offset +=linelen(line, size);16391640 patch->lines_added += added;1641 patch->lines_deleted += deleted;16421643if(0< patch->is_new && oldlines)1644returnerror(_("new file depends on old contents"));1645if(0< patch->is_delete && newlines)1646returnerror(_("deleted file still has contents"));1647return offset;1648}16491650/*1651 * We have seen "diff --git a/... b/..." header (or a traditional patch1652 * header). Read hunks that belong to this patch into fragments and hang1653 * them to the given patch structure.1654 *1655 * The (fragment->patch, fragment->size) pair points into the memory given1656 * by the caller, not a copy, when we return.1657 */1658static intparse_single_patch(const char*line,unsigned long size,struct patch *patch)1659{1660unsigned long offset =0;1661unsigned long oldlines =0, newlines =0, context =0;1662struct fragment **fragp = &patch->fragments;16631664while(size >4&& !memcmp(line,"@@ -",4)) {1665struct fragment *fragment;1666int len;16671668 fragment =xcalloc(1,sizeof(*fragment));1669 fragment->linenr = state_linenr;1670 len =parse_fragment(line, size, patch, fragment);1671if(len <=0)1672die(_("corrupt patch at line%d"), state_linenr);1673 fragment->patch = line;1674 fragment->size = len;1675 oldlines += fragment->oldlines;1676 newlines += fragment->newlines;1677 context += fragment->leading + fragment->trailing;16781679*fragp = fragment;1680 fragp = &fragment->next;16811682 offset += len;1683 line += len;1684 size -= len;1685}16861687/*1688 * If something was removed (i.e. we have old-lines) it cannot1689 * be creation, and if something was added it cannot be1690 * deletion. However, the reverse is not true; --unified=01691 * patches that only add are not necessarily creation even1692 * though they do not have any old lines, and ones that only1693 * delete are not necessarily deletion.1694 *1695 * Unfortunately, a real creation/deletion patch do _not_ have1696 * any context line by definition, so we cannot safely tell it1697 * apart with --unified=0 insanity. At least if the patch has1698 * more than one hunk it is not creation or deletion.1699 */1700if(patch->is_new <0&&1701(oldlines || (patch->fragments && patch->fragments->next)))1702 patch->is_new =0;1703if(patch->is_delete <0&&1704(newlines || (patch->fragments && patch->fragments->next)))1705 patch->is_delete =0;17061707if(0< patch->is_new && oldlines)1708die(_("new file%sdepends on old contents"), patch->new_name);1709if(0< patch->is_delete && newlines)1710die(_("deleted file%sstill has contents"), patch->old_name);1711if(!patch->is_delete && !newlines && context)1712fprintf_ln(stderr,1713_("** warning: "1714"file%sbecomes empty but is not deleted"),1715 patch->new_name);17161717return offset;1718}17191720staticinlineintmetadata_changes(struct patch *patch)1721{1722return patch->is_rename >0||1723 patch->is_copy >0||1724 patch->is_new >0||1725 patch->is_delete ||1726(patch->old_mode && patch->new_mode &&1727 patch->old_mode != patch->new_mode);1728}17291730static char*inflate_it(const void*data,unsigned long size,1731unsigned long inflated_size)1732{1733 git_zstream stream;1734void*out;1735int st;17361737memset(&stream,0,sizeof(stream));17381739 stream.next_in = (unsigned char*)data;1740 stream.avail_in = size;1741 stream.next_out = out =xmalloc(inflated_size);1742 stream.avail_out = inflated_size;1743git_inflate_init(&stream);1744 st =git_inflate(&stream, Z_FINISH);1745git_inflate_end(&stream);1746if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1747free(out);1748return NULL;1749}1750return out;1751}17521753/*1754 * Read a binary hunk and return a new fragment; fragment->patch1755 * points at an allocated memory that the caller must free, so1756 * it is marked as "->free_patch = 1".1757 */1758static struct fragment *parse_binary_hunk(char**buf_p,1759unsigned long*sz_p,1760int*status_p,1761int*used_p)1762{1763/*1764 * Expect a line that begins with binary patch method ("literal"1765 * or "delta"), followed by the length of data before deflating.1766 * a sequence of 'length-byte' followed by base-85 encoded data1767 * should follow, terminated by a newline.1768 *1769 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1770 * and we would limit the patch line to 66 characters,1771 * so one line can fit up to 13 groups that would decode1772 * to 52 bytes max. The length byte 'A'-'Z' corresponds1773 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1774 */1775int llen, used;1776unsigned long size = *sz_p;1777char*buffer = *buf_p;1778int patch_method;1779unsigned long origlen;1780char*data = NULL;1781int hunk_size =0;1782struct fragment *frag;17831784 llen =linelen(buffer, size);1785 used = llen;17861787*status_p =0;17881789if(starts_with(buffer,"delta ")) {1790 patch_method = BINARY_DELTA_DEFLATED;1791 origlen =strtoul(buffer +6, NULL,10);1792}1793else if(starts_with(buffer,"literal ")) {1794 patch_method = BINARY_LITERAL_DEFLATED;1795 origlen =strtoul(buffer +8, NULL,10);1796}1797else1798return NULL;17991800 state_linenr++;1801 buffer += llen;1802while(1) {1803int byte_length, max_byte_length, newsize;1804 llen =linelen(buffer, size);1805 used += llen;1806 state_linenr++;1807if(llen ==1) {1808/* consume the blank line */1809 buffer++;1810 size--;1811break;1812}1813/*1814 * Minimum line is "A00000\n" which is 7-byte long,1815 * and the line length must be multiple of 5 plus 2.1816 */1817if((llen <7) || (llen-2) %5)1818goto corrupt;1819 max_byte_length = (llen -2) /5*4;1820 byte_length = *buffer;1821if('A'<= byte_length && byte_length <='Z')1822 byte_length = byte_length -'A'+1;1823else if('a'<= byte_length && byte_length <='z')1824 byte_length = byte_length -'a'+27;1825else1826goto corrupt;1827/* if the input length was not multiple of 4, we would1828 * have filler at the end but the filler should never1829 * exceed 3 bytes1830 */1831if(max_byte_length < byte_length ||1832 byte_length <= max_byte_length -4)1833goto corrupt;1834 newsize = hunk_size + byte_length;1835 data =xrealloc(data, newsize);1836if(decode_85(data + hunk_size, buffer +1, byte_length))1837goto corrupt;1838 hunk_size = newsize;1839 buffer += llen;1840 size -= llen;1841}18421843 frag =xcalloc(1,sizeof(*frag));1844 frag->patch =inflate_it(data, hunk_size, origlen);1845 frag->free_patch =1;1846if(!frag->patch)1847goto corrupt;1848free(data);1849 frag->size = origlen;1850*buf_p = buffer;1851*sz_p = size;1852*used_p = used;1853 frag->binary_patch_method = patch_method;1854return frag;18551856 corrupt:1857free(data);1858*status_p = -1;1859error(_("corrupt binary patch at line%d: %.*s"),1860 state_linenr-1, llen-1, buffer);1861return NULL;1862}18631864/*1865 * Returns:1866 * -1 in case of error,1867 * the length of the parsed binary patch otherwise1868 */1869static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1870{1871/*1872 * We have read "GIT binary patch\n"; what follows is a line1873 * that says the patch method (currently, either "literal" or1874 * "delta") and the length of data before deflating; a1875 * sequence of 'length-byte' followed by base-85 encoded data1876 * follows.1877 *1878 * When a binary patch is reversible, there is another binary1879 * hunk in the same format, starting with patch method (either1880 * "literal" or "delta") with the length of data, and a sequence1881 * of length-byte + base-85 encoded data, terminated with another1882 * empty line. This data, when applied to the postimage, produces1883 * the preimage.1884 */1885struct fragment *forward;1886struct fragment *reverse;1887int status;1888int used, used_1;18891890 forward =parse_binary_hunk(&buffer, &size, &status, &used);1891if(!forward && !status)1892/* there has to be one hunk (forward hunk) */1893returnerror(_("unrecognized binary patch at line%d"), state_linenr-1);1894if(status)1895/* otherwise we already gave an error message */1896return status;18971898 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1899if(reverse)1900 used += used_1;1901else if(status) {1902/*1903 * Not having reverse hunk is not an error, but having1904 * a corrupt reverse hunk is.1905 */1906free((void*) forward->patch);1907free(forward);1908return status;1909}1910 forward->next = reverse;1911 patch->fragments = forward;1912 patch->is_binary =1;1913return used;1914}19151916static voidprefix_one(char**name)1917{1918char*old_name = *name;1919if(!old_name)1920return;1921*name =xstrdup(prefix_filename(prefix, prefix_length, *name));1922free(old_name);1923}19241925static voidprefix_patch(struct patch *p)1926{1927if(!prefix || p->is_toplevel_relative)1928return;1929prefix_one(&p->new_name);1930prefix_one(&p->old_name);1931}19321933/*1934 * include/exclude1935 */19361937static struct string_list limit_by_name;1938static int has_include;1939static voidadd_name_limit(const char*name,int exclude)1940{1941struct string_list_item *it;19421943 it =string_list_append(&limit_by_name, name);1944 it->util = exclude ? NULL : (void*)1;1945}19461947static intuse_patch(struct patch *p)1948{1949const char*pathname = p->new_name ? p->new_name : p->old_name;1950int i;19511952/* Paths outside are not touched regardless of "--include" */1953if(0< prefix_length) {1954int pathlen =strlen(pathname);1955if(pathlen <= prefix_length ||1956memcmp(prefix, pathname, prefix_length))1957return0;1958}19591960/* See if it matches any of exclude/include rule */1961for(i =0; i < limit_by_name.nr; i++) {1962struct string_list_item *it = &limit_by_name.items[i];1963if(!wildmatch(it->string, pathname,0, NULL))1964return(it->util != NULL);1965}19661967/*1968 * If we had any include, a path that does not match any rule is1969 * not used. Otherwise, we saw bunch of exclude rules (or none)1970 * and such a path is used.1971 */1972return!has_include;1973}197419751976/*1977 * Read the patch text in "buffer" that extends for "size" bytes; stop1978 * reading after seeing a single patch (i.e. changes to a single file).1979 * Create fragments (i.e. patch hunks) and hang them to the given patch.1980 * Return the number of bytes consumed, so that the caller can call us1981 * again for the next patch.1982 */1983static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1984{1985int hdrsize, patchsize;1986int offset =find_header(buffer, size, &hdrsize, patch);19871988if(offset <0)1989return offset;19901991prefix_patch(patch);19921993if(!use_patch(patch))1994 patch->ws_rule =0;1995else1996 patch->ws_rule =whitespace_rule(patch->new_name1997? patch->new_name1998: patch->old_name);19992000 patchsize =parse_single_patch(buffer + offset + hdrsize,2001 size - offset - hdrsize, patch);20022003if(!patchsize) {2004static const char git_binary[] ="GIT binary patch\n";2005int hd = hdrsize + offset;2006unsigned long llen =linelen(buffer + hd, size - hd);20072008if(llen ==sizeof(git_binary) -1&&2009!memcmp(git_binary, buffer + hd, llen)) {2010int used;2011 state_linenr++;2012 used =parse_binary(buffer + hd + llen,2013 size - hd - llen, patch);2014if(used <0)2015return-1;2016if(used)2017 patchsize = used + llen;2018else2019 patchsize =0;2020}2021else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2022static const char*binhdr[] = {2023"Binary files ",2024"Files ",2025 NULL,2026};2027int i;2028for(i =0; binhdr[i]; i++) {2029int len =strlen(binhdr[i]);2030if(len < size - hd &&2031!memcmp(binhdr[i], buffer + hd, len)) {2032 state_linenr++;2033 patch->is_binary =1;2034 patchsize = llen;2035break;2036}2037}2038}20392040/* Empty patch cannot be applied if it is a text patch2041 * without metadata change. A binary patch appears2042 * empty to us here.2043 */2044if((apply || check) &&2045(!patch->is_binary && !metadata_changes(patch)))2046die(_("patch with only garbage at line%d"), state_linenr);2047}20482049return offset + hdrsize + patchsize;2050}20512052#define swap(a,b) myswap((a),(b),sizeof(a))20532054#define myswap(a, b, size) do { \2055 unsigned char mytmp[size]; \2056 memcpy(mytmp, &a, size); \2057 memcpy(&a, &b, size); \2058 memcpy(&b, mytmp, size); \2059} while (0)20602061static voidreverse_patches(struct patch *p)2062{2063for(; p; p = p->next) {2064struct fragment *frag = p->fragments;20652066swap(p->new_name, p->old_name);2067swap(p->new_mode, p->old_mode);2068swap(p->is_new, p->is_delete);2069swap(p->lines_added, p->lines_deleted);2070swap(p->old_sha1_prefix, p->new_sha1_prefix);20712072for(; frag; frag = frag->next) {2073swap(frag->newpos, frag->oldpos);2074swap(frag->newlines, frag->oldlines);2075}2076}2077}20782079static const char pluses[] =2080"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2081static const char minuses[]=2082"----------------------------------------------------------------------";20832084static voidshow_stats(struct patch *patch)2085{2086struct strbuf qname = STRBUF_INIT;2087char*cp = patch->new_name ? patch->new_name : patch->old_name;2088int max, add, del;20892090quote_c_style(cp, &qname, NULL,0);20912092/*2093 * "scale" the filename2094 */2095 max = max_len;2096if(max >50)2097 max =50;20982099if(qname.len > max) {2100 cp =strchr(qname.buf + qname.len +3- max,'/');2101if(!cp)2102 cp = qname.buf + qname.len +3- max;2103strbuf_splice(&qname,0, cp - qname.buf,"...",3);2104}21052106if(patch->is_binary) {2107printf(" %-*s | Bin\n", max, qname.buf);2108strbuf_release(&qname);2109return;2110}21112112printf(" %-*s |", max, qname.buf);2113strbuf_release(&qname);21142115/*2116 * scale the add/delete2117 */2118 max = max + max_change >70?70- max : max_change;2119 add = patch->lines_added;2120 del = patch->lines_deleted;21212122if(max_change >0) {2123int total = ((add + del) * max + max_change /2) / max_change;2124 add = (add * max + max_change /2) / max_change;2125 del = total - add;2126}2127printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2128 add, pluses, del, minuses);2129}21302131static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2132{2133switch(st->st_mode & S_IFMT) {2134case S_IFLNK:2135if(strbuf_readlink(buf, path, st->st_size) <0)2136returnerror(_("unable to read symlink%s"), path);2137return0;2138case S_IFREG:2139if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2140returnerror(_("unable to open or read%s"), path);2141convert_to_git(path, buf->buf, buf->len, buf,0);2142return0;2143default:2144return-1;2145}2146}21472148/*2149 * Update the preimage, and the common lines in postimage,2150 * from buffer buf of length len. If postlen is 0 the postimage2151 * is updated in place, otherwise it's updated on a new buffer2152 * of length postlen2153 */21542155static voidupdate_pre_post_images(struct image *preimage,2156struct image *postimage,2157char*buf,2158size_t len,size_t postlen)2159{2160int i, ctx, reduced;2161char*new, *old, *fixed;2162struct image fixed_preimage;21632164/*2165 * Update the preimage with whitespace fixes. Note that we2166 * are not losing preimage->buf -- apply_one_fragment() will2167 * free "oldlines".2168 */2169prepare_image(&fixed_preimage, buf, len,1);2170assert(postlen2171? fixed_preimage.nr == preimage->nr2172: fixed_preimage.nr <= preimage->nr);2173for(i =0; i < fixed_preimage.nr; i++)2174 fixed_preimage.line[i].flag = preimage->line[i].flag;2175free(preimage->line_allocated);2176*preimage = fixed_preimage;21772178/*2179 * Adjust the common context lines in postimage. This can be2180 * done in-place when we are shrinking it with whitespace2181 * fixing, but needs a new buffer when ignoring whitespace or2182 * expanding leading tabs to spaces.2183 *2184 * We trust the caller to tell us if the update can be done2185 * in place (postlen==0) or not.2186 */2187 old = postimage->buf;2188if(postlen)2189new= postimage->buf =xmalloc(postlen);2190else2191new= old;2192 fixed = preimage->buf;21932194for(i = reduced = ctx =0; i < postimage->nr; i++) {2195size_t l_len = postimage->line[i].len;2196if(!(postimage->line[i].flag & LINE_COMMON)) {2197/* an added line -- no counterparts in preimage */2198memmove(new, old, l_len);2199 old += l_len;2200new+= l_len;2201continue;2202}22032204/* a common context -- skip it in the original postimage */2205 old += l_len;22062207/* and find the corresponding one in the fixed preimage */2208while(ctx < preimage->nr &&2209!(preimage->line[ctx].flag & LINE_COMMON)) {2210 fixed += preimage->line[ctx].len;2211 ctx++;2212}22132214/*2215 * preimage is expected to run out, if the caller2216 * fixed addition of trailing blank lines.2217 */2218if(preimage->nr <= ctx) {2219 reduced++;2220continue;2221}22222223/* and copy it in, while fixing the line length */2224 l_len = preimage->line[ctx].len;2225memcpy(new, fixed, l_len);2226new+= l_len;2227 fixed += l_len;2228 postimage->line[i].len = l_len;2229 ctx++;2230}22312232if(postlen2233? postlen <new- postimage->buf2234: postimage->len <new- postimage->buf)2235die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2236(int)postlen, (int) postimage->len, (int)(new- postimage->buf));22372238/* Fix the length of the whole thing */2239 postimage->len =new- postimage->buf;2240 postimage->nr -= reduced;2241}22422243static intline_by_line_fuzzy_match(struct image *img,2244struct image *preimage,2245struct image *postimage,2246unsigned longtry,2247int try_lno,2248int preimage_limit)2249{2250int i;2251size_t imgoff =0;2252size_t preoff =0;2253size_t postlen = postimage->len;2254size_t extra_chars;2255char*buf;2256char*preimage_eof;2257char*preimage_end;2258struct strbuf fixed;2259char*fixed_buf;2260size_t fixed_len;22612262for(i =0; i < preimage_limit; i++) {2263size_t prelen = preimage->line[i].len;2264size_t imglen = img->line[try_lno+i].len;22652266if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2267 preimage->buf + preoff, prelen))2268return0;2269if(preimage->line[i].flag & LINE_COMMON)2270 postlen += imglen - prelen;2271 imgoff += imglen;2272 preoff += prelen;2273}22742275/*2276 * Ok, the preimage matches with whitespace fuzz.2277 *2278 * imgoff now holds the true length of the target that2279 * matches the preimage before the end of the file.2280 *2281 * Count the number of characters in the preimage that fall2282 * beyond the end of the file and make sure that all of them2283 * are whitespace characters. (This can only happen if2284 * we are removing blank lines at the end of the file.)2285 */2286 buf = preimage_eof = preimage->buf + preoff;2287for( ; i < preimage->nr; i++)2288 preoff += preimage->line[i].len;2289 preimage_end = preimage->buf + preoff;2290for( ; buf < preimage_end; buf++)2291if(!isspace(*buf))2292return0;22932294/*2295 * Update the preimage and the common postimage context2296 * lines to use the same whitespace as the target.2297 * If whitespace is missing in the target (i.e.2298 * if the preimage extends beyond the end of the file),2299 * use the whitespace from the preimage.2300 */2301 extra_chars = preimage_end - preimage_eof;2302strbuf_init(&fixed, imgoff + extra_chars);2303strbuf_add(&fixed, img->buf +try, imgoff);2304strbuf_add(&fixed, preimage_eof, extra_chars);2305 fixed_buf =strbuf_detach(&fixed, &fixed_len);2306update_pre_post_images(preimage, postimage,2307 fixed_buf, fixed_len, postlen);2308return1;2309}23102311static intmatch_fragment(struct image *img,2312struct image *preimage,2313struct image *postimage,2314unsigned longtry,2315int try_lno,2316unsigned ws_rule,2317int match_beginning,int match_end)2318{2319int i;2320char*fixed_buf, *buf, *orig, *target;2321struct strbuf fixed;2322size_t fixed_len, postlen;2323int preimage_limit;23242325if(preimage->nr + try_lno <= img->nr) {2326/*2327 * The hunk falls within the boundaries of img.2328 */2329 preimage_limit = preimage->nr;2330if(match_end && (preimage->nr + try_lno != img->nr))2331return0;2332}else if(ws_error_action == correct_ws_error &&2333(ws_rule & WS_BLANK_AT_EOF)) {2334/*2335 * This hunk extends beyond the end of img, and we are2336 * removing blank lines at the end of the file. This2337 * many lines from the beginning of the preimage must2338 * match with img, and the remainder of the preimage2339 * must be blank.2340 */2341 preimage_limit = img->nr - try_lno;2342}else{2343/*2344 * The hunk extends beyond the end of the img and2345 * we are not removing blanks at the end, so we2346 * should reject the hunk at this position.2347 */2348return0;2349}23502351if(match_beginning && try_lno)2352return0;23532354/* Quick hash check */2355for(i =0; i < preimage_limit; i++)2356if((img->line[try_lno + i].flag & LINE_PATCHED) ||2357(preimage->line[i].hash != img->line[try_lno + i].hash))2358return0;23592360if(preimage_limit == preimage->nr) {2361/*2362 * Do we have an exact match? If we were told to match2363 * at the end, size must be exactly at try+fragsize,2364 * otherwise try+fragsize must be still within the preimage,2365 * and either case, the old piece should match the preimage2366 * exactly.2367 */2368if((match_end2369? (try+ preimage->len == img->len)2370: (try+ preimage->len <= img->len)) &&2371!memcmp(img->buf +try, preimage->buf, preimage->len))2372return1;2373}else{2374/*2375 * The preimage extends beyond the end of img, so2376 * there cannot be an exact match.2377 *2378 * There must be one non-blank context line that match2379 * a line before the end of img.2380 */2381char*buf_end;23822383 buf = preimage->buf;2384 buf_end = buf;2385for(i =0; i < preimage_limit; i++)2386 buf_end += preimage->line[i].len;23872388for( ; buf < buf_end; buf++)2389if(!isspace(*buf))2390break;2391if(buf == buf_end)2392return0;2393}23942395/*2396 * No exact match. If we are ignoring whitespace, run a line-by-line2397 * fuzzy matching. We collect all the line length information because2398 * we need it to adjust whitespace if we match.2399 */2400if(ws_ignore_action == ignore_ws_change)2401returnline_by_line_fuzzy_match(img, preimage, postimage,2402try, try_lno, preimage_limit);24032404if(ws_error_action != correct_ws_error)2405return0;24062407/*2408 * The hunk does not apply byte-by-byte, but the hash says2409 * it might with whitespace fuzz. We weren't asked to2410 * ignore whitespace, we were asked to correct whitespace2411 * errors, so let's try matching after whitespace correction.2412 *2413 * While checking the preimage against the target, whitespace2414 * errors in both fixed, we count how large the corresponding2415 * postimage needs to be. The postimage prepared by2416 * apply_one_fragment() has whitespace errors fixed on added2417 * lines already, but the common lines were propagated as-is,2418 * which may become longer when their whitespace errors are2419 * fixed.2420 */24212422/* First count added lines in postimage */2423 postlen =0;2424for(i =0; i < postimage->nr; i++) {2425if(!(postimage->line[i].flag & LINE_COMMON))2426 postlen += postimage->line[i].len;2427}24282429/*2430 * The preimage may extend beyond the end of the file,2431 * but in this loop we will only handle the part of the2432 * preimage that falls within the file.2433 */2434strbuf_init(&fixed, preimage->len +1);2435 orig = preimage->buf;2436 target = img->buf +try;2437for(i =0; i < preimage_limit; i++) {2438size_t oldlen = preimage->line[i].len;2439size_t tgtlen = img->line[try_lno + i].len;2440size_t fixstart = fixed.len;2441struct strbuf tgtfix;2442int match;24432444/* Try fixing the line in the preimage */2445ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24462447/* Try fixing the line in the target */2448strbuf_init(&tgtfix, tgtlen);2449ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);24502451/*2452 * If they match, either the preimage was based on2453 * a version before our tree fixed whitespace breakage,2454 * or we are lacking a whitespace-fix patch the tree2455 * the preimage was based on already had (i.e. target2456 * has whitespace breakage, the preimage doesn't).2457 * In either case, we are fixing the whitespace breakages2458 * so we might as well take the fix together with their2459 * real change.2460 */2461 match = (tgtfix.len == fixed.len - fixstart &&2462!memcmp(tgtfix.buf, fixed.buf + fixstart,2463 fixed.len - fixstart));24642465/* Add the length if this is common with the postimage */2466if(preimage->line[i].flag & LINE_COMMON)2467 postlen += tgtfix.len;24682469strbuf_release(&tgtfix);2470if(!match)2471goto unmatch_exit;24722473 orig += oldlen;2474 target += tgtlen;2475}247624772478/*2479 * Now handle the lines in the preimage that falls beyond the2480 * end of the file (if any). They will only match if they are2481 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2482 * false).2483 */2484for( ; i < preimage->nr; i++) {2485size_t fixstart = fixed.len;/* start of the fixed preimage */2486size_t oldlen = preimage->line[i].len;2487int j;24882489/* Try fixing the line in the preimage */2490ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24912492for(j = fixstart; j < fixed.len; j++)2493if(!isspace(fixed.buf[j]))2494goto unmatch_exit;24952496 orig += oldlen;2497}24982499/*2500 * Yes, the preimage is based on an older version that still2501 * has whitespace breakages unfixed, and fixing them makes the2502 * hunk match. Update the context lines in the postimage.2503 */2504 fixed_buf =strbuf_detach(&fixed, &fixed_len);2505if(postlen < postimage->len)2506 postlen =0;2507update_pre_post_images(preimage, postimage,2508 fixed_buf, fixed_len, postlen);2509return1;25102511 unmatch_exit:2512strbuf_release(&fixed);2513return0;2514}25152516static intfind_pos(struct image *img,2517struct image *preimage,2518struct image *postimage,2519int line,2520unsigned ws_rule,2521int match_beginning,int match_end)2522{2523int i;2524unsigned long backwards, forwards,try;2525int backwards_lno, forwards_lno, try_lno;25262527/*2528 * If match_beginning or match_end is specified, there is no2529 * point starting from a wrong line that will never match and2530 * wander around and wait for a match at the specified end.2531 */2532if(match_beginning)2533 line =0;2534else if(match_end)2535 line = img->nr - preimage->nr;25362537/*2538 * Because the comparison is unsigned, the following test2539 * will also take care of a negative line number that can2540 * result when match_end and preimage is larger than the target.2541 */2542if((size_t) line > img->nr)2543 line = img->nr;25442545try=0;2546for(i =0; i < line; i++)2547try+= img->line[i].len;25482549/*2550 * There's probably some smart way to do this, but I'll leave2551 * that to the smart and beautiful people. I'm simple and stupid.2552 */2553 backwards =try;2554 backwards_lno = line;2555 forwards =try;2556 forwards_lno = line;2557 try_lno = line;25582559for(i =0; ; i++) {2560if(match_fragment(img, preimage, postimage,2561try, try_lno, ws_rule,2562 match_beginning, match_end))2563return try_lno;25642565 again:2566if(backwards_lno ==0&& forwards_lno == img->nr)2567break;25682569if(i &1) {2570if(backwards_lno ==0) {2571 i++;2572goto again;2573}2574 backwards_lno--;2575 backwards -= img->line[backwards_lno].len;2576try= backwards;2577 try_lno = backwards_lno;2578}else{2579if(forwards_lno == img->nr) {2580 i++;2581goto again;2582}2583 forwards += img->line[forwards_lno].len;2584 forwards_lno++;2585try= forwards;2586 try_lno = forwards_lno;2587}25882589}2590return-1;2591}25922593static voidremove_first_line(struct image *img)2594{2595 img->buf += img->line[0].len;2596 img->len -= img->line[0].len;2597 img->line++;2598 img->nr--;2599}26002601static voidremove_last_line(struct image *img)2602{2603 img->len -= img->line[--img->nr].len;2604}26052606/*2607 * The change from "preimage" and "postimage" has been found to2608 * apply at applied_pos (counts in line numbers) in "img".2609 * Update "img" to remove "preimage" and replace it with "postimage".2610 */2611static voidupdate_image(struct image *img,2612int applied_pos,2613struct image *preimage,2614struct image *postimage)2615{2616/*2617 * remove the copy of preimage at offset in img2618 * and replace it with postimage2619 */2620int i, nr;2621size_t remove_count, insert_count, applied_at =0;2622char*result;2623int preimage_limit;26242625/*2626 * If we are removing blank lines at the end of img,2627 * the preimage may extend beyond the end.2628 * If that is the case, we must be careful only to2629 * remove the part of the preimage that falls within2630 * the boundaries of img. Initialize preimage_limit2631 * to the number of lines in the preimage that falls2632 * within the boundaries.2633 */2634 preimage_limit = preimage->nr;2635if(preimage_limit > img->nr - applied_pos)2636 preimage_limit = img->nr - applied_pos;26372638for(i =0; i < applied_pos; i++)2639 applied_at += img->line[i].len;26402641 remove_count =0;2642for(i =0; i < preimage_limit; i++)2643 remove_count += img->line[applied_pos + i].len;2644 insert_count = postimage->len;26452646/* Adjust the contents */2647 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2648memcpy(result, img->buf, applied_at);2649memcpy(result + applied_at, postimage->buf, postimage->len);2650memcpy(result + applied_at + postimage->len,2651 img->buf + (applied_at + remove_count),2652 img->len - (applied_at + remove_count));2653free(img->buf);2654 img->buf = result;2655 img->len += insert_count - remove_count;2656 result[img->len] ='\0';26572658/* Adjust the line table */2659 nr = img->nr + postimage->nr - preimage_limit;2660if(preimage_limit < postimage->nr) {2661/*2662 * NOTE: this knows that we never call remove_first_line()2663 * on anything other than pre/post image.2664 */2665REALLOC_ARRAY(img->line, nr);2666 img->line_allocated = img->line;2667}2668if(preimage_limit != postimage->nr)2669memmove(img->line + applied_pos + postimage->nr,2670 img->line + applied_pos + preimage_limit,2671(img->nr - (applied_pos + preimage_limit)) *2672sizeof(*img->line));2673memcpy(img->line + applied_pos,2674 postimage->line,2675 postimage->nr *sizeof(*img->line));2676if(!allow_overlap)2677for(i =0; i < postimage->nr; i++)2678 img->line[applied_pos + i].flag |= LINE_PATCHED;2679 img->nr = nr;2680}26812682/*2683 * Use the patch-hunk text in "frag" to prepare two images (preimage and2684 * postimage) for the hunk. Find lines that match "preimage" in "img" and2685 * replace the part of "img" with "postimage" text.2686 */2687static intapply_one_fragment(struct image *img,struct fragment *frag,2688int inaccurate_eof,unsigned ws_rule,2689int nth_fragment)2690{2691int match_beginning, match_end;2692const char*patch = frag->patch;2693int size = frag->size;2694char*old, *oldlines;2695struct strbuf newlines;2696int new_blank_lines_at_end =0;2697int found_new_blank_lines_at_end =0;2698int hunk_linenr = frag->linenr;2699unsigned long leading, trailing;2700int pos, applied_pos;2701struct image preimage;2702struct image postimage;27032704memset(&preimage,0,sizeof(preimage));2705memset(&postimage,0,sizeof(postimage));2706 oldlines =xmalloc(size);2707strbuf_init(&newlines, size);27082709 old = oldlines;2710while(size >0) {2711char first;2712int len =linelen(patch, size);2713int plen;2714int added_blank_line =0;2715int is_blank_context =0;2716size_t start;27172718if(!len)2719break;27202721/*2722 * "plen" is how much of the line we should use for2723 * the actual patch data. Normally we just remove the2724 * first character on the line, but if the line is2725 * followed by "\ No newline", then we also remove the2726 * last one (which is the newline, of course).2727 */2728 plen = len -1;2729if(len < size && patch[len] =='\\')2730 plen--;2731 first = *patch;2732if(apply_in_reverse) {2733if(first =='-')2734 first ='+';2735else if(first =='+')2736 first ='-';2737}27382739switch(first) {2740case'\n':2741/* Newer GNU diff, empty context line */2742if(plen <0)2743/* ... followed by '\No newline'; nothing */2744break;2745*old++ ='\n';2746strbuf_addch(&newlines,'\n');2747add_line_info(&preimage,"\n",1, LINE_COMMON);2748add_line_info(&postimage,"\n",1, LINE_COMMON);2749 is_blank_context =1;2750break;2751case' ':2752if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2753ws_blank_line(patch +1, plen, ws_rule))2754 is_blank_context =1;2755case'-':2756memcpy(old, patch +1, plen);2757add_line_info(&preimage, old, plen,2758(first ==' '? LINE_COMMON :0));2759 old += plen;2760if(first =='-')2761break;2762/* Fall-through for ' ' */2763case'+':2764/* --no-add does not add new lines */2765if(first =='+'&& no_add)2766break;27672768 start = newlines.len;2769if(first !='+'||2770!whitespace_error ||2771 ws_error_action != correct_ws_error) {2772strbuf_add(&newlines, patch +1, plen);2773}2774else{2775ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2776}2777add_line_info(&postimage, newlines.buf + start, newlines.len - start,2778(first =='+'?0: LINE_COMMON));2779if(first =='+'&&2780(ws_rule & WS_BLANK_AT_EOF) &&2781ws_blank_line(patch +1, plen, ws_rule))2782 added_blank_line =1;2783break;2784case'@':case'\\':2785/* Ignore it, we already handled it */2786break;2787default:2788if(apply_verbosely)2789error(_("invalid start of line: '%c'"), first);2790 applied_pos = -1;2791goto out;2792}2793if(added_blank_line) {2794if(!new_blank_lines_at_end)2795 found_new_blank_lines_at_end = hunk_linenr;2796 new_blank_lines_at_end++;2797}2798else if(is_blank_context)2799;2800else2801 new_blank_lines_at_end =0;2802 patch += len;2803 size -= len;2804 hunk_linenr++;2805}2806if(inaccurate_eof &&2807 old > oldlines && old[-1] =='\n'&&2808 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2809 old--;2810strbuf_setlen(&newlines, newlines.len -1);2811}28122813 leading = frag->leading;2814 trailing = frag->trailing;28152816/*2817 * A hunk to change lines at the beginning would begin with2818 * @@ -1,L +N,M @@2819 * but we need to be careful. -U0 that inserts before the second2820 * line also has this pattern.2821 *2822 * And a hunk to add to an empty file would begin with2823 * @@ -0,0 +N,M @@2824 *2825 * In other words, a hunk that is (frag->oldpos <= 1) with or2826 * without leading context must match at the beginning.2827 */2828 match_beginning = (!frag->oldpos ||2829(frag->oldpos ==1&& !unidiff_zero));28302831/*2832 * A hunk without trailing lines must match at the end.2833 * However, we simply cannot tell if a hunk must match end2834 * from the lack of trailing lines if the patch was generated2835 * with unidiff without any context.2836 */2837 match_end = !unidiff_zero && !trailing;28382839 pos = frag->newpos ? (frag->newpos -1) :0;2840 preimage.buf = oldlines;2841 preimage.len = old - oldlines;2842 postimage.buf = newlines.buf;2843 postimage.len = newlines.len;2844 preimage.line = preimage.line_allocated;2845 postimage.line = postimage.line_allocated;28462847for(;;) {28482849 applied_pos =find_pos(img, &preimage, &postimage, pos,2850 ws_rule, match_beginning, match_end);28512852if(applied_pos >=0)2853break;28542855/* Am I at my context limits? */2856if((leading <= p_context) && (trailing <= p_context))2857break;2858if(match_beginning || match_end) {2859 match_beginning = match_end =0;2860continue;2861}28622863/*2864 * Reduce the number of context lines; reduce both2865 * leading and trailing if they are equal otherwise2866 * just reduce the larger context.2867 */2868if(leading >= trailing) {2869remove_first_line(&preimage);2870remove_first_line(&postimage);2871 pos--;2872 leading--;2873}2874if(trailing > leading) {2875remove_last_line(&preimage);2876remove_last_line(&postimage);2877 trailing--;2878}2879}28802881if(applied_pos >=0) {2882if(new_blank_lines_at_end &&2883 preimage.nr + applied_pos >= img->nr &&2884(ws_rule & WS_BLANK_AT_EOF) &&2885 ws_error_action != nowarn_ws_error) {2886record_ws_error(WS_BLANK_AT_EOF,"+",1,2887 found_new_blank_lines_at_end);2888if(ws_error_action == correct_ws_error) {2889while(new_blank_lines_at_end--)2890remove_last_line(&postimage);2891}2892/*2893 * We would want to prevent write_out_results()2894 * from taking place in apply_patch() that follows2895 * the callchain led us here, which is:2896 * apply_patch->check_patch_list->check_patch->2897 * apply_data->apply_fragments->apply_one_fragment2898 */2899if(ws_error_action == die_on_ws_error)2900 apply =0;2901}29022903if(apply_verbosely && applied_pos != pos) {2904int offset = applied_pos - pos;2905if(apply_in_reverse)2906 offset =0- offset;2907fprintf_ln(stderr,2908Q_("Hunk #%dsucceeded at%d(offset%dline).",2909"Hunk #%dsucceeded at%d(offset%dlines).",2910 offset),2911 nth_fragment, applied_pos +1, offset);2912}29132914/*2915 * Warn if it was necessary to reduce the number2916 * of context lines.2917 */2918if((leading != frag->leading) ||2919(trailing != frag->trailing))2920fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2921" to apply fragment at%d"),2922 leading, trailing, applied_pos+1);2923update_image(img, applied_pos, &preimage, &postimage);2924}else{2925if(apply_verbosely)2926error(_("while searching for:\n%.*s"),2927(int)(old - oldlines), oldlines);2928}29292930out:2931free(oldlines);2932strbuf_release(&newlines);2933free(preimage.line_allocated);2934free(postimage.line_allocated);29352936return(applied_pos <0);2937}29382939static intapply_binary_fragment(struct image *img,struct patch *patch)2940{2941struct fragment *fragment = patch->fragments;2942unsigned long len;2943void*dst;29442945if(!fragment)2946returnerror(_("missing binary patch data for '%s'"),2947 patch->new_name ?2948 patch->new_name :2949 patch->old_name);29502951/* Binary patch is irreversible without the optional second hunk */2952if(apply_in_reverse) {2953if(!fragment->next)2954returnerror("cannot reverse-apply a binary patch "2955"without the reverse hunk to '%s'",2956 patch->new_name2957? patch->new_name : patch->old_name);2958 fragment = fragment->next;2959}2960switch(fragment->binary_patch_method) {2961case BINARY_DELTA_DEFLATED:2962 dst =patch_delta(img->buf, img->len, fragment->patch,2963 fragment->size, &len);2964if(!dst)2965return-1;2966clear_image(img);2967 img->buf = dst;2968 img->len = len;2969return0;2970case BINARY_LITERAL_DEFLATED:2971clear_image(img);2972 img->len = fragment->size;2973 img->buf =xmemdupz(fragment->patch, img->len);2974return0;2975}2976return-1;2977}29782979/*2980 * Replace "img" with the result of applying the binary patch.2981 * The binary patch data itself in patch->fragment is still kept2982 * but the preimage prepared by the caller in "img" is freed here2983 * or in the helper function apply_binary_fragment() this calls.2984 */2985static intapply_binary(struct image *img,struct patch *patch)2986{2987const char*name = patch->old_name ? patch->old_name : patch->new_name;2988unsigned char sha1[20];29892990/*2991 * For safety, we require patch index line to contain2992 * full 40-byte textual SHA1 for old and new, at least for now.2993 */2994if(strlen(patch->old_sha1_prefix) !=40||2995strlen(patch->new_sha1_prefix) !=40||2996get_sha1_hex(patch->old_sha1_prefix, sha1) ||2997get_sha1_hex(patch->new_sha1_prefix, sha1))2998returnerror("cannot apply binary patch to '%s' "2999"without full index line", name);30003001if(patch->old_name) {3002/*3003 * See if the old one matches what the patch3004 * applies to.3005 */3006hash_sha1_file(img->buf, img->len, blob_type, sha1);3007if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3008returnerror("the patch applies to '%s' (%s), "3009"which does not match the "3010"current contents.",3011 name,sha1_to_hex(sha1));3012}3013else{3014/* Otherwise, the old one must be empty. */3015if(img->len)3016returnerror("the patch applies to an empty "3017"'%s' but it is not empty", name);3018}30193020get_sha1_hex(patch->new_sha1_prefix, sha1);3021if(is_null_sha1(sha1)) {3022clear_image(img);3023return0;/* deletion patch */3024}30253026if(has_sha1_file(sha1)) {3027/* We already have the postimage */3028enum object_type type;3029unsigned long size;3030char*result;30313032 result =read_sha1_file(sha1, &type, &size);3033if(!result)3034returnerror("the necessary postimage%sfor "3035"'%s' cannot be read",3036 patch->new_sha1_prefix, name);3037clear_image(img);3038 img->buf = result;3039 img->len = size;3040}else{3041/*3042 * We have verified buf matches the preimage;3043 * apply the patch data to it, which is stored3044 * in the patch->fragments->{patch,size}.3045 */3046if(apply_binary_fragment(img, patch))3047returnerror(_("binary patch does not apply to '%s'"),3048 name);30493050/* verify that the result matches */3051hash_sha1_file(img->buf, img->len, blob_type, sha1);3052if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3053returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3054 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3055}30563057return0;3058}30593060static intapply_fragments(struct image *img,struct patch *patch)3061{3062struct fragment *frag = patch->fragments;3063const char*name = patch->old_name ? patch->old_name : patch->new_name;3064unsigned ws_rule = patch->ws_rule;3065unsigned inaccurate_eof = patch->inaccurate_eof;3066int nth =0;30673068if(patch->is_binary)3069returnapply_binary(img, patch);30703071while(frag) {3072 nth++;3073if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {3074error(_("patch failed:%s:%ld"), name, frag->oldpos);3075if(!apply_with_reject)3076return-1;3077 frag->rejected =1;3078}3079 frag = frag->next;3080}3081return0;3082}30833084static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3085{3086if(S_ISGITLINK(mode)) {3087strbuf_grow(buf,100);3088strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3089}else{3090enum object_type type;3091unsigned long sz;3092char*result;30933094 result =read_sha1_file(sha1, &type, &sz);3095if(!result)3096return-1;3097/* XXX read_sha1_file NUL-terminates */3098strbuf_attach(buf, result, sz, sz +1);3099}3100return0;3101}31023103static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3104{3105if(!ce)3106return0;3107returnread_blob_object(buf, ce->sha1, ce->ce_mode);3108}31093110static struct patch *in_fn_table(const char*name)3111{3112struct string_list_item *item;31133114if(name == NULL)3115return NULL;31163117 item =string_list_lookup(&fn_table, name);3118if(item != NULL)3119return(struct patch *)item->util;31203121return NULL;3122}31233124/*3125 * item->util in the filename table records the status of the path.3126 * Usually it points at a patch (whose result records the contents3127 * of it after applying it), but it could be PATH_WAS_DELETED for a3128 * path that a previously applied patch has already removed, or3129 * PATH_TO_BE_DELETED for a path that a later patch would remove.3130 *3131 * The latter is needed to deal with a case where two paths A and B3132 * are swapped by first renaming A to B and then renaming B to A;3133 * moving A to B should not be prevented due to presence of B as we3134 * will remove it in a later patch.3135 */3136#define PATH_TO_BE_DELETED ((struct patch *) -2)3137#define PATH_WAS_DELETED ((struct patch *) -1)31383139static intto_be_deleted(struct patch *patch)3140{3141return patch == PATH_TO_BE_DELETED;3142}31433144static intwas_deleted(struct patch *patch)3145{3146return patch == PATH_WAS_DELETED;3147}31483149static voidadd_to_fn_table(struct patch *patch)3150{3151struct string_list_item *item;31523153/*3154 * Always add new_name unless patch is a deletion3155 * This should cover the cases for normal diffs,3156 * file creations and copies3157 */3158if(patch->new_name != NULL) {3159 item =string_list_insert(&fn_table, patch->new_name);3160 item->util = patch;3161}31623163/*3164 * store a failure on rename/deletion cases because3165 * later chunks shouldn't patch old names3166 */3167if((patch->new_name == NULL) || (patch->is_rename)) {3168 item =string_list_insert(&fn_table, patch->old_name);3169 item->util = PATH_WAS_DELETED;3170}3171}31723173static voidprepare_fn_table(struct patch *patch)3174{3175/*3176 * store information about incoming file deletion3177 */3178while(patch) {3179if((patch->new_name == NULL) || (patch->is_rename)) {3180struct string_list_item *item;3181 item =string_list_insert(&fn_table, patch->old_name);3182 item->util = PATH_TO_BE_DELETED;3183}3184 patch = patch->next;3185}3186}31873188static intcheckout_target(struct index_state *istate,3189struct cache_entry *ce,struct stat *st)3190{3191struct checkout costate;31923193memset(&costate,0,sizeof(costate));3194 costate.base_dir ="";3195 costate.refresh_cache =1;3196 costate.istate = istate;3197if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3198returnerror(_("cannot checkout%s"), ce->name);3199return0;3200}32013202static struct patch *previous_patch(struct patch *patch,int*gone)3203{3204struct patch *previous;32053206*gone =0;3207if(patch->is_copy || patch->is_rename)3208return NULL;/* "git" patches do not depend on the order */32093210 previous =in_fn_table(patch->old_name);3211if(!previous)3212return NULL;32133214if(to_be_deleted(previous))3215return NULL;/* the deletion hasn't happened yet */32163217if(was_deleted(previous))3218*gone =1;32193220return previous;3221}32223223static intverify_index_match(const struct cache_entry *ce,struct stat *st)3224{3225if(S_ISGITLINK(ce->ce_mode)) {3226if(!S_ISDIR(st->st_mode))3227return-1;3228return0;3229}3230returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3231}32323233#define SUBMODULE_PATCH_WITHOUT_INDEX 132343235static intload_patch_target(struct strbuf *buf,3236const struct cache_entry *ce,3237struct stat *st,3238const char*name,3239unsigned expected_mode)3240{3241if(cached || check_index) {3242if(read_file_or_gitlink(ce, buf))3243returnerror(_("read of%sfailed"), name);3244}else if(name) {3245if(S_ISGITLINK(expected_mode)) {3246if(ce)3247returnread_file_or_gitlink(ce, buf);3248else3249return SUBMODULE_PATCH_WITHOUT_INDEX;3250}else if(has_symlink_leading_path(name,strlen(name))) {3251returnerror(_("reading from '%s' beyond a symbolic link"), name);3252}else{3253if(read_old_data(st, name, buf))3254returnerror(_("read of%sfailed"), name);3255}3256}3257return0;3258}32593260/*3261 * We are about to apply "patch"; populate the "image" with the3262 * current version we have, from the working tree or from the index,3263 * depending on the situation e.g. --cached/--index. If we are3264 * applying a non-git patch that incrementally updates the tree,3265 * we read from the result of a previous diff.3266 */3267static intload_preimage(struct image *image,3268struct patch *patch,struct stat *st,3269const struct cache_entry *ce)3270{3271struct strbuf buf = STRBUF_INIT;3272size_t len;3273char*img;3274struct patch *previous;3275int status;32763277 previous =previous_patch(patch, &status);3278if(status)3279returnerror(_("path%shas been renamed/deleted"),3280 patch->old_name);3281if(previous) {3282/* We have a patched copy in memory; use that. */3283strbuf_add(&buf, previous->result, previous->resultsize);3284}else{3285 status =load_patch_target(&buf, ce, st,3286 patch->old_name, patch->old_mode);3287if(status <0)3288return status;3289else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3290/*3291 * There is no way to apply subproject3292 * patch without looking at the index.3293 * NEEDSWORK: shouldn't this be flagged3294 * as an error???3295 */3296free_fragment_list(patch->fragments);3297 patch->fragments = NULL;3298}else if(status) {3299returnerror(_("read of%sfailed"), patch->old_name);3300}3301}33023303 img =strbuf_detach(&buf, &len);3304prepare_image(image, img, len, !patch->is_binary);3305return0;3306}33073308static intthree_way_merge(struct image *image,3309char*path,3310const unsigned char*base,3311const unsigned char*ours,3312const unsigned char*theirs)3313{3314 mmfile_t base_file, our_file, their_file;3315 mmbuffer_t result = { NULL };3316int status;33173318read_mmblob(&base_file, base);3319read_mmblob(&our_file, ours);3320read_mmblob(&their_file, theirs);3321 status =ll_merge(&result, path,3322&base_file,"base",3323&our_file,"ours",3324&their_file,"theirs", NULL);3325free(base_file.ptr);3326free(our_file.ptr);3327free(their_file.ptr);3328if(status <0|| !result.ptr) {3329free(result.ptr);3330return-1;3331}3332clear_image(image);3333 image->buf = result.ptr;3334 image->len = result.size;33353336return status;3337}33383339/*3340 * When directly falling back to add/add three-way merge, we read from3341 * the current contents of the new_name. In no cases other than that3342 * this function will be called.3343 */3344static intload_current(struct image *image,struct patch *patch)3345{3346struct strbuf buf = STRBUF_INIT;3347int status, pos;3348size_t len;3349char*img;3350struct stat st;3351struct cache_entry *ce;3352char*name = patch->new_name;3353unsigned mode = patch->new_mode;33543355if(!patch->is_new)3356die("BUG: patch to%sis not a creation", patch->old_name);33573358 pos =cache_name_pos(name,strlen(name));3359if(pos <0)3360returnerror(_("%s: does not exist in index"), name);3361 ce = active_cache[pos];3362if(lstat(name, &st)) {3363if(errno != ENOENT)3364returnerror(_("%s:%s"), name,strerror(errno));3365if(checkout_target(&the_index, ce, &st))3366return-1;3367}3368if(verify_index_match(ce, &st))3369returnerror(_("%s: does not match index"), name);33703371 status =load_patch_target(&buf, ce, &st, name, mode);3372if(status <0)3373return status;3374else if(status)3375return-1;3376 img =strbuf_detach(&buf, &len);3377prepare_image(image, img, len, !patch->is_binary);3378return0;3379}33803381static inttry_threeway(struct image *image,struct patch *patch,3382struct stat *st,const struct cache_entry *ce)3383{3384unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3385struct strbuf buf = STRBUF_INIT;3386size_t len;3387int status;3388char*img;3389struct image tmp_image;33903391/* No point falling back to 3-way merge in these cases */3392if(patch->is_delete ||3393S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3394return-1;33953396/* Preimage the patch was prepared for */3397if(patch->is_new)3398write_sha1_file("",0, blob_type, pre_sha1);3399else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3400read_blob_object(&buf, pre_sha1, patch->old_mode))3401returnerror("repository lacks the necessary blob to fall back on 3-way merge.");34023403fprintf(stderr,"Falling back to three-way merge...\n");34043405 img =strbuf_detach(&buf, &len);3406prepare_image(&tmp_image, img, len,1);3407/* Apply the patch to get the post image */3408if(apply_fragments(&tmp_image, patch) <0) {3409clear_image(&tmp_image);3410return-1;3411}3412/* post_sha1[] is theirs */3413write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3414clear_image(&tmp_image);34153416/* our_sha1[] is ours */3417if(patch->is_new) {3418if(load_current(&tmp_image, patch))3419returnerror("cannot read the current contents of '%s'",3420 patch->new_name);3421}else{3422if(load_preimage(&tmp_image, patch, st, ce))3423returnerror("cannot read the current contents of '%s'",3424 patch->old_name);3425}3426write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3427clear_image(&tmp_image);34283429/* in-core three-way merge between post and our using pre as base */3430 status =three_way_merge(image, patch->new_name,3431 pre_sha1, our_sha1, post_sha1);3432if(status <0) {3433fprintf(stderr,"Failed to fall back on three-way merge...\n");3434return status;3435}34363437if(status) {3438 patch->conflicted_threeway =1;3439if(patch->is_new)3440oidclr(&patch->threeway_stage[0]);3441else3442hashcpy(patch->threeway_stage[0].hash, pre_sha1);3443hashcpy(patch->threeway_stage[1].hash, our_sha1);3444hashcpy(patch->threeway_stage[2].hash, post_sha1);3445fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3446}else{3447fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3448}3449return0;3450}34513452static intapply_data(struct patch *patch,struct stat *st,const struct cache_entry *ce)3453{3454struct image image;34553456if(load_preimage(&image, patch, st, ce) <0)3457return-1;34583459if(patch->direct_to_threeway ||3460apply_fragments(&image, patch) <0) {3461/* Note: with --reject, apply_fragments() returns 0 */3462if(!threeway ||try_threeway(&image, patch, st, ce) <0)3463return-1;3464}3465 patch->result = image.buf;3466 patch->resultsize = image.len;3467add_to_fn_table(patch);3468free(image.line_allocated);34693470if(0< patch->is_delete && patch->resultsize)3471returnerror(_("removal patch leaves file contents"));34723473return0;3474}34753476/*3477 * If "patch" that we are looking at modifies or deletes what we have,3478 * we would want it not to lose any local modification we have, either3479 * in the working tree or in the index.3480 *3481 * This also decides if a non-git patch is a creation patch or a3482 * modification to an existing empty file. We do not check the state3483 * of the current tree for a creation patch in this function; the caller3484 * check_patch() separately makes sure (and errors out otherwise) that3485 * the path the patch creates does not exist in the current tree.3486 */3487static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)3488{3489const char*old_name = patch->old_name;3490struct patch *previous = NULL;3491int stat_ret =0, status;3492unsigned st_mode =0;34933494if(!old_name)3495return0;34963497assert(patch->is_new <=0);3498 previous =previous_patch(patch, &status);34993500if(status)3501returnerror(_("path%shas been renamed/deleted"), old_name);3502if(previous) {3503 st_mode = previous->new_mode;3504}else if(!cached) {3505 stat_ret =lstat(old_name, st);3506if(stat_ret && errno != ENOENT)3507returnerror(_("%s:%s"), old_name,strerror(errno));3508}35093510if(check_index && !previous) {3511int pos =cache_name_pos(old_name,strlen(old_name));3512if(pos <0) {3513if(patch->is_new <0)3514goto is_new;3515returnerror(_("%s: does not exist in index"), old_name);3516}3517*ce = active_cache[pos];3518if(stat_ret <0) {3519if(checkout_target(&the_index, *ce, st))3520return-1;3521}3522if(!cached &&verify_index_match(*ce, st))3523returnerror(_("%s: does not match index"), old_name);3524if(cached)3525 st_mode = (*ce)->ce_mode;3526}else if(stat_ret <0) {3527if(patch->is_new <0)3528goto is_new;3529returnerror(_("%s:%s"), old_name,strerror(errno));3530}35313532if(!cached && !previous)3533 st_mode =ce_mode_from_stat(*ce, st->st_mode);35343535if(patch->is_new <0)3536 patch->is_new =0;3537if(!patch->old_mode)3538 patch->old_mode = st_mode;3539if((st_mode ^ patch->old_mode) & S_IFMT)3540returnerror(_("%s: wrong type"), old_name);3541if(st_mode != patch->old_mode)3542warning(_("%shas type%o, expected%o"),3543 old_name, st_mode, patch->old_mode);3544if(!patch->new_mode && !patch->is_delete)3545 patch->new_mode = st_mode;3546return0;35473548 is_new:3549 patch->is_new =1;3550 patch->is_delete =0;3551free(patch->old_name);3552 patch->old_name = NULL;3553return0;3554}355535563557#define EXISTS_IN_INDEX 13558#define EXISTS_IN_WORKTREE 235593560static intcheck_to_create(const char*new_name,int ok_if_exists)3561{3562struct stat nst;35633564if(check_index &&3565cache_name_pos(new_name,strlen(new_name)) >=0&&3566!ok_if_exists)3567return EXISTS_IN_INDEX;3568if(cached)3569return0;35703571if(!lstat(new_name, &nst)) {3572if(S_ISDIR(nst.st_mode) || ok_if_exists)3573return0;3574/*3575 * A leading component of new_name might be a symlink3576 * that is going to be removed with this patch, but3577 * still pointing at somewhere that has the path.3578 * In such a case, path "new_name" does not exist as3579 * far as git is concerned.3580 */3581if(has_symlink_leading_path(new_name,strlen(new_name)))3582return0;35833584return EXISTS_IN_WORKTREE;3585}else if((errno != ENOENT) && (errno != ENOTDIR)) {3586returnerror("%s:%s", new_name,strerror(errno));3587}3588return0;3589}35903591/*3592 * We need to keep track of how symlinks in the preimage are3593 * manipulated by the patches. A patch to add a/b/c where a/b3594 * is a symlink should not be allowed to affect the directory3595 * the symlink points at, but if the same patch removes a/b,3596 * it is perfectly fine, as the patch removes a/b to make room3597 * to create a directory a/b so that a/b/c can be created.3598 */3599static struct string_list symlink_changes;3600#define SYMLINK_GOES_AWAY 013601#define SYMLINK_IN_RESULT 0236023603static uintptr_tregister_symlink_changes(const char*path,uintptr_t what)3604{3605struct string_list_item *ent;36063607 ent =string_list_lookup(&symlink_changes, path);3608if(!ent) {3609 ent =string_list_insert(&symlink_changes, path);3610 ent->util = (void*)0;3611}3612 ent->util = (void*)(what | ((uintptr_t)ent->util));3613return(uintptr_t)ent->util;3614}36153616static uintptr_tcheck_symlink_changes(const char*path)3617{3618struct string_list_item *ent;36193620 ent =string_list_lookup(&symlink_changes, path);3621if(!ent)3622return0;3623return(uintptr_t)ent->util;3624}36253626static voidprepare_symlink_changes(struct patch *patch)3627{3628for( ; patch; patch = patch->next) {3629if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3630(patch->is_rename || patch->is_delete))3631/* the symlink at patch->old_name is removed */3632register_symlink_changes(patch->old_name, SYMLINK_GOES_AWAY);36333634if(patch->new_name &&S_ISLNK(patch->new_mode))3635/* the symlink at patch->new_name is created or remains */3636register_symlink_changes(patch->new_name, SYMLINK_IN_RESULT);3637}3638}36393640static intpath_is_beyond_symlink_1(struct strbuf *name)3641{3642do{3643unsigned int change;36443645while(--name->len && name->buf[name->len] !='/')3646;/* scan backwards */3647if(!name->len)3648break;3649 name->buf[name->len] ='\0';3650 change =check_symlink_changes(name->buf);3651if(change & SYMLINK_IN_RESULT)3652return1;3653if(change & SYMLINK_GOES_AWAY)3654/*3655 * This cannot be "return 0", because we may3656 * see a new one created at a higher level.3657 */3658continue;36593660/* otherwise, check the preimage */3661if(check_index) {3662struct cache_entry *ce;36633664 ce =cache_file_exists(name->buf, name->len, ignore_case);3665if(ce &&S_ISLNK(ce->ce_mode))3666return1;3667}else{3668struct stat st;3669if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3670return1;3671}3672}while(1);3673return0;3674}36753676static intpath_is_beyond_symlink(const char*name_)3677{3678int ret;3679struct strbuf name = STRBUF_INIT;36803681assert(*name_ !='\0');3682strbuf_addstr(&name, name_);3683 ret =path_is_beyond_symlink_1(&name);3684strbuf_release(&name);36853686return ret;3687}36883689static voiddie_on_unsafe_path(struct patch *patch)3690{3691const char*old_name = NULL;3692const char*new_name = NULL;3693if(patch->is_delete)3694 old_name = patch->old_name;3695else if(!patch->is_new && !patch->is_copy)3696 old_name = patch->old_name;3697if(!patch->is_delete)3698 new_name = patch->new_name;36993700if(old_name && !verify_path(old_name))3701die(_("invalid path '%s'"), old_name);3702if(new_name && !verify_path(new_name))3703die(_("invalid path '%s'"), new_name);3704}37053706/*3707 * Check and apply the patch in-core; leave the result in patch->result3708 * for the caller to write it out to the final destination.3709 */3710static intcheck_patch(struct patch *patch)3711{3712struct stat st;3713const char*old_name = patch->old_name;3714const char*new_name = patch->new_name;3715const char*name = old_name ? old_name : new_name;3716struct cache_entry *ce = NULL;3717struct patch *tpatch;3718int ok_if_exists;3719int status;37203721 patch->rejected =1;/* we will drop this after we succeed */37223723 status =check_preimage(patch, &ce, &st);3724if(status)3725return status;3726 old_name = patch->old_name;37273728/*3729 * A type-change diff is always split into a patch to delete3730 * old, immediately followed by a patch to create new (see3731 * diff.c::run_diff()); in such a case it is Ok that the entry3732 * to be deleted by the previous patch is still in the working3733 * tree and in the index.3734 *3735 * A patch to swap-rename between A and B would first rename A3736 * to B and then rename B to A. While applying the first one,3737 * the presence of B should not stop A from getting renamed to3738 * B; ask to_be_deleted() about the later rename. Removal of3739 * B and rename from A to B is handled the same way by asking3740 * was_deleted().3741 */3742if((tpatch =in_fn_table(new_name)) &&3743(was_deleted(tpatch) ||to_be_deleted(tpatch)))3744 ok_if_exists =1;3745else3746 ok_if_exists =0;37473748if(new_name &&3749((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3750int err =check_to_create(new_name, ok_if_exists);37513752if(err && threeway) {3753 patch->direct_to_threeway =1;3754}else switch(err) {3755case0:3756break;/* happy */3757case EXISTS_IN_INDEX:3758returnerror(_("%s: already exists in index"), new_name);3759break;3760case EXISTS_IN_WORKTREE:3761returnerror(_("%s: already exists in working directory"),3762 new_name);3763default:3764return err;3765}37663767if(!patch->new_mode) {3768if(0< patch->is_new)3769 patch->new_mode = S_IFREG |0644;3770else3771 patch->new_mode = patch->old_mode;3772}3773}37743775if(new_name && old_name) {3776int same = !strcmp(old_name, new_name);3777if(!patch->new_mode)3778 patch->new_mode = patch->old_mode;3779if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3780if(same)3781returnerror(_("new mode (%o) of%sdoes not "3782"match old mode (%o)"),3783 patch->new_mode, new_name,3784 patch->old_mode);3785else3786returnerror(_("new mode (%o) of%sdoes not "3787"match old mode (%o) of%s"),3788 patch->new_mode, new_name,3789 patch->old_mode, old_name);3790}3791}37923793if(!unsafe_paths)3794die_on_unsafe_path(patch);37953796/*3797 * An attempt to read from or delete a path that is beyond a3798 * symbolic link will be prevented by load_patch_target() that3799 * is called at the beginning of apply_data() so we do not3800 * have to worry about a patch marked with "is_delete" bit3801 * here. We however need to make sure that the patch result3802 * is not deposited to a path that is beyond a symbolic link3803 * here.3804 */3805if(!patch->is_delete &&path_is_beyond_symlink(patch->new_name))3806returnerror(_("affected file '%s' is beyond a symbolic link"),3807 patch->new_name);38083809if(apply_data(patch, &st, ce) <0)3810returnerror(_("%s: patch does not apply"), name);3811 patch->rejected =0;3812return0;3813}38143815static intcheck_patch_list(struct patch *patch)3816{3817int err =0;38183819prepare_symlink_changes(patch);3820prepare_fn_table(patch);3821while(patch) {3822if(apply_verbosely)3823say_patch_name(stderr,3824_("Checking patch%s..."), patch);3825 err |=check_patch(patch);3826 patch = patch->next;3827}3828return err;3829}38303831/* This function tries to read the sha1 from the current index */3832static intget_current_sha1(const char*path,unsigned char*sha1)3833{3834int pos;38353836if(read_cache() <0)3837return-1;3838 pos =cache_name_pos(path,strlen(path));3839if(pos <0)3840return-1;3841hashcpy(sha1, active_cache[pos]->sha1);3842return0;3843}38443845static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3846{3847/*3848 * A usable gitlink patch has only one fragment (hunk) that looks like:3849 * @@ -1 +1 @@3850 * -Subproject commit <old sha1>3851 * +Subproject commit <new sha1>3852 * or3853 * @@ -1 +0,0 @@3854 * -Subproject commit <old sha1>3855 * for a removal patch.3856 */3857struct fragment *hunk = p->fragments;3858static const char heading[] ="-Subproject commit ";3859char*preimage;38603861if(/* does the patch have only one hunk? */3862 hunk && !hunk->next &&3863/* is its preimage one line? */3864 hunk->oldpos ==1&& hunk->oldlines ==1&&3865/* does preimage begin with the heading? */3866(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3867starts_with(++preimage, heading) &&3868/* does it record full SHA-1? */3869!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3870 preimage[sizeof(heading) +40-1] =='\n'&&3871/* does the abbreviated name on the index line agree with it? */3872starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3873return0;/* it all looks fine */38743875/* we may have full object name on the index line */3876returnget_sha1_hex(p->old_sha1_prefix, sha1);3877}38783879/* Build an index that contains the just the files needed for a 3way merge */3880static voidbuild_fake_ancestor(struct patch *list,const char*filename)3881{3882struct patch *patch;3883struct index_state result = { NULL };3884static struct lock_file lock;38853886/* Once we start supporting the reverse patch, it may be3887 * worth showing the new sha1 prefix, but until then...3888 */3889for(patch = list; patch; patch = patch->next) {3890unsigned char sha1[20];3891struct cache_entry *ce;3892const char*name;38933894 name = patch->old_name ? patch->old_name : patch->new_name;3895if(0< patch->is_new)3896continue;38973898if(S_ISGITLINK(patch->old_mode)) {3899if(!preimage_sha1_in_gitlink_patch(patch, sha1))3900;/* ok, the textual part looks sane */3901else3902die("sha1 information is lacking or useless for submodule%s",3903 name);3904}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {3905;/* ok */3906}else if(!patch->lines_added && !patch->lines_deleted) {3907/* mode-only change: update the current */3908if(get_current_sha1(patch->old_name, sha1))3909die("mode change for%s, which is not "3910"in current HEAD", name);3911}else3912die("sha1 information is lacking or useless "3913"(%s).", name);39143915 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);3916if(!ce)3917die(_("make_cache_entry failed for path '%s'"), name);3918if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3919die("Could not add%sto temporary index", name);3920}39213922hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);3923if(write_locked_index(&result, &lock, COMMIT_LOCK))3924die("Could not write temporary index to%s", filename);39253926discard_index(&result);3927}39283929static voidstat_patch_list(struct patch *patch)3930{3931int files, adds, dels;39323933for(files = adds = dels =0; patch ; patch = patch->next) {3934 files++;3935 adds += patch->lines_added;3936 dels += patch->lines_deleted;3937show_stats(patch);3938}39393940print_stat_summary(stdout, files, adds, dels);3941}39423943static voidnumstat_patch_list(struct patch *patch)3944{3945for( ; patch; patch = patch->next) {3946const char*name;3947 name = patch->new_name ? patch->new_name : patch->old_name;3948if(patch->is_binary)3949printf("-\t-\t");3950else3951printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3952write_name_quoted(name, stdout, line_termination);3953}3954}39553956static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3957{3958if(mode)3959printf("%smode%06o%s\n", newdelete, mode, name);3960else3961printf("%s %s\n", newdelete, name);3962}39633964static voidshow_mode_change(struct patch *p,int show_name)3965{3966if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3967if(show_name)3968printf(" mode change%06o =>%06o%s\n",3969 p->old_mode, p->new_mode, p->new_name);3970else3971printf(" mode change%06o =>%06o\n",3972 p->old_mode, p->new_mode);3973}3974}39753976static voidshow_rename_copy(struct patch *p)3977{3978const char*renamecopy = p->is_rename ?"rename":"copy";3979const char*old, *new;39803981/* Find common prefix */3982 old = p->old_name;3983new= p->new_name;3984while(1) {3985const char*slash_old, *slash_new;3986 slash_old =strchr(old,'/');3987 slash_new =strchr(new,'/');3988if(!slash_old ||3989!slash_new ||3990 slash_old - old != slash_new -new||3991memcmp(old,new, slash_new -new))3992break;3993 old = slash_old +1;3994new= slash_new +1;3995}3996/* p->old_name thru old is the common prefix, and old and new3997 * through the end of names are renames3998 */3999if(old != p->old_name)4000printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4001(int)(old - p->old_name), p->old_name,4002 old,new, p->score);4003else4004printf("%s %s=>%s(%d%%)\n", renamecopy,4005 p->old_name, p->new_name, p->score);4006show_mode_change(p,0);4007}40084009static voidsummary_patch_list(struct patch *patch)4010{4011struct patch *p;40124013for(p = patch; p; p = p->next) {4014if(p->is_new)4015show_file_mode_name("create", p->new_mode, p->new_name);4016else if(p->is_delete)4017show_file_mode_name("delete", p->old_mode, p->old_name);4018else{4019if(p->is_rename || p->is_copy)4020show_rename_copy(p);4021else{4022if(p->score) {4023printf(" rewrite%s(%d%%)\n",4024 p->new_name, p->score);4025show_mode_change(p,0);4026}4027else4028show_mode_change(p,1);4029}4030}4031}4032}40334034static voidpatch_stats(struct patch *patch)4035{4036int lines = patch->lines_added + patch->lines_deleted;40374038if(lines > max_change)4039 max_change = lines;4040if(patch->old_name) {4041int len =quote_c_style(patch->old_name, NULL, NULL,0);4042if(!len)4043 len =strlen(patch->old_name);4044if(len > max_len)4045 max_len = len;4046}4047if(patch->new_name) {4048int len =quote_c_style(patch->new_name, NULL, NULL,0);4049if(!len)4050 len =strlen(patch->new_name);4051if(len > max_len)4052 max_len = len;4053}4054}40554056static voidremove_file(struct patch *patch,int rmdir_empty)4057{4058if(update_index) {4059if(remove_file_from_cache(patch->old_name) <0)4060die(_("unable to remove%sfrom index"), patch->old_name);4061}4062if(!cached) {4063if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4064remove_path(patch->old_name);4065}4066}4067}40684069static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)4070{4071struct stat st;4072struct cache_entry *ce;4073int namelen =strlen(path);4074unsigned ce_size =cache_entry_size(namelen);40754076if(!update_index)4077return;40784079 ce =xcalloc(1, ce_size);4080memcpy(ce->name, path, namelen);4081 ce->ce_mode =create_ce_mode(mode);4082 ce->ce_flags =create_ce_flags(0);4083 ce->ce_namelen = namelen;4084if(S_ISGITLINK(mode)) {4085const char*s;40864087if(!skip_prefix(buf,"Subproject commit ", &s) ||4088get_sha1_hex(s, ce->sha1))4089die(_("corrupt patch for submodule%s"), path);4090}else{4091if(!cached) {4092if(lstat(path, &st) <0)4093die_errno(_("unable to stat newly created file '%s'"),4094 path);4095fill_stat_cache_info(ce, &st);4096}4097if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4098die(_("unable to create backing store for newly created file%s"), path);4099}4100if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4101die(_("unable to add cache entry for%s"), path);4102}41034104static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4105{4106int fd;4107struct strbuf nbuf = STRBUF_INIT;41084109if(S_ISGITLINK(mode)) {4110struct stat st;4111if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4112return0;4113returnmkdir(path,0777);4114}41154116if(has_symlinks &&S_ISLNK(mode))4117/* Although buf:size is counted string, it also is NUL4118 * terminated.4119 */4120returnsymlink(buf, path);41214122 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4123if(fd <0)4124return-1;41254126if(convert_to_working_tree(path, buf, size, &nbuf)) {4127 size = nbuf.len;4128 buf = nbuf.buf;4129}4130write_or_die(fd, buf, size);4131strbuf_release(&nbuf);41324133if(close(fd) <0)4134die_errno(_("closing file '%s'"), path);4135return0;4136}41374138/*4139 * We optimistically assume that the directories exist,4140 * which is true 99% of the time anyway. If they don't,4141 * we create them and try again.4142 */4143static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)4144{4145if(cached)4146return;4147if(!try_create_file(path, mode, buf, size))4148return;41494150if(errno == ENOENT) {4151if(safe_create_leading_directories(path))4152return;4153if(!try_create_file(path, mode, buf, size))4154return;4155}41564157if(errno == EEXIST || errno == EACCES) {4158/* We may be trying to create a file where a directory4159 * used to be.4160 */4161struct stat st;4162if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4163 errno = EEXIST;4164}41654166if(errno == EEXIST) {4167unsigned int nr =getpid();41684169for(;;) {4170char newpath[PATH_MAX];4171mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4172if(!try_create_file(newpath, mode, buf, size)) {4173if(!rename(newpath, path))4174return;4175unlink_or_warn(newpath);4176break;4177}4178if(errno != EEXIST)4179break;4180++nr;4181}4182}4183die_errno(_("unable to write file '%s' mode%o"), path, mode);4184}41854186static voidadd_conflicted_stages_file(struct patch *patch)4187{4188int stage, namelen;4189unsigned ce_size, mode;4190struct cache_entry *ce;41914192if(!update_index)4193return;4194 namelen =strlen(patch->new_name);4195 ce_size =cache_entry_size(namelen);4196 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);41974198remove_file_from_cache(patch->new_name);4199for(stage =1; stage <4; stage++) {4200if(is_null_oid(&patch->threeway_stage[stage -1]))4201continue;4202 ce =xcalloc(1, ce_size);4203memcpy(ce->name, patch->new_name, namelen);4204 ce->ce_mode =create_ce_mode(mode);4205 ce->ce_flags =create_ce_flags(stage);4206 ce->ce_namelen = namelen;4207hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4208if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4209die(_("unable to add cache entry for%s"), patch->new_name);4210}4211}42124213static voidcreate_file(struct patch *patch)4214{4215char*path = patch->new_name;4216unsigned mode = patch->new_mode;4217unsigned long size = patch->resultsize;4218char*buf = patch->result;42194220if(!mode)4221 mode = S_IFREG |0644;4222create_one_file(path, mode, buf, size);42234224if(patch->conflicted_threeway)4225add_conflicted_stages_file(patch);4226else4227add_index_file(path, mode, buf, size);4228}42294230/* phase zero is to remove, phase one is to create */4231static voidwrite_out_one_result(struct patch *patch,int phase)4232{4233if(patch->is_delete >0) {4234if(phase ==0)4235remove_file(patch,1);4236return;4237}4238if(patch->is_new >0|| patch->is_copy) {4239if(phase ==1)4240create_file(patch);4241return;4242}4243/*4244 * Rename or modification boils down to the same4245 * thing: remove the old, write the new4246 */4247if(phase ==0)4248remove_file(patch, patch->is_rename);4249if(phase ==1)4250create_file(patch);4251}42524253static intwrite_out_one_reject(struct patch *patch)4254{4255FILE*rej;4256char namebuf[PATH_MAX];4257struct fragment *frag;4258int cnt =0;4259struct strbuf sb = STRBUF_INIT;42604261for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4262if(!frag->rejected)4263continue;4264 cnt++;4265}42664267if(!cnt) {4268if(apply_verbosely)4269say_patch_name(stderr,4270_("Applied patch%scleanly."), patch);4271return0;4272}42734274/* This should not happen, because a removal patch that leaves4275 * contents are marked "rejected" at the patch level.4276 */4277if(!patch->new_name)4278die(_("internal error"));42794280/* Say this even without --verbose */4281strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4282"Applying patch %%swith%drejects...",4283 cnt),4284 cnt);4285say_patch_name(stderr, sb.buf, patch);4286strbuf_release(&sb);42874288 cnt =strlen(patch->new_name);4289if(ARRAY_SIZE(namebuf) <= cnt +5) {4290 cnt =ARRAY_SIZE(namebuf) -5;4291warning(_("truncating .rej filename to %.*s.rej"),4292 cnt -1, patch->new_name);4293}4294memcpy(namebuf, patch->new_name, cnt);4295memcpy(namebuf + cnt,".rej",5);42964297 rej =fopen(namebuf,"w");4298if(!rej)4299returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));43004301/* Normal git tools never deal with .rej, so do not pretend4302 * this is a git patch by saying --git or giving extended4303 * headers. While at it, maybe please "kompare" that wants4304 * the trailing TAB and some garbage at the end of line ;-).4305 */4306fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4307 patch->new_name, patch->new_name);4308for(cnt =1, frag = patch->fragments;4309 frag;4310 cnt++, frag = frag->next) {4311if(!frag->rejected) {4312fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4313continue;4314}4315fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4316fprintf(rej,"%.*s", frag->size, frag->patch);4317if(frag->patch[frag->size-1] !='\n')4318fputc('\n', rej);4319}4320fclose(rej);4321return-1;4322}43234324static intwrite_out_results(struct patch *list)4325{4326int phase;4327int errs =0;4328struct patch *l;4329struct string_list cpath = STRING_LIST_INIT_DUP;43304331for(phase =0; phase <2; phase++) {4332 l = list;4333while(l) {4334if(l->rejected)4335 errs =1;4336else{4337write_out_one_result(l, phase);4338if(phase ==1) {4339if(write_out_one_reject(l))4340 errs =1;4341if(l->conflicted_threeway) {4342string_list_append(&cpath, l->new_name);4343 errs =1;4344}4345}4346}4347 l = l->next;4348}4349}43504351if(cpath.nr) {4352struct string_list_item *item;43534354string_list_sort(&cpath);4355for_each_string_list_item(item, &cpath)4356fprintf(stderr,"U%s\n", item->string);4357string_list_clear(&cpath,0);43584359rerere(0);4360}43614362return errs;4363}43644365static struct lock_file lock_file;43664367#define INACCURATE_EOF (1<<0)4368#define RECOUNT (1<<1)43694370static intapply_patch(int fd,const char*filename,int options)4371{4372size_t offset;4373struct strbuf buf = STRBUF_INIT;/* owns the patch text */4374struct patch *list = NULL, **listp = &list;4375int skipped_patch =0;43764377 patch_input_file = filename;4378read_patch_file(&buf, fd);4379 offset =0;4380while(offset < buf.len) {4381struct patch *patch;4382int nr;43834384 patch =xcalloc(1,sizeof(*patch));4385 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4386 patch->recount = !!(options & RECOUNT);4387 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);4388if(nr <0) {4389free_patch(patch);4390break;4391}4392if(apply_in_reverse)4393reverse_patches(patch);4394if(use_patch(patch)) {4395patch_stats(patch);4396*listp = patch;4397 listp = &patch->next;4398}4399else{4400if(apply_verbosely)4401say_patch_name(stderr,_("Skipped patch '%s'."), patch);4402free_patch(patch);4403 skipped_patch++;4404}4405 offset += nr;4406}44074408if(!list && !skipped_patch)4409die(_("unrecognized input"));44104411if(whitespace_error && (ws_error_action == die_on_ws_error))4412 apply =0;44134414 update_index = check_index && apply;4415if(update_index && newfd <0)4416 newfd =hold_locked_index(&lock_file,1);44174418if(check_index) {4419if(read_cache() <0)4420die(_("unable to read index file"));4421}44224423if((check || apply) &&4424check_patch_list(list) <0&&4425!apply_with_reject)4426exit(1);44274428if(apply &&write_out_results(list)) {4429if(apply_with_reject)4430exit(1);4431/* with --3way, we still need to write the index out */4432return1;4433}44344435if(fake_ancestor)4436build_fake_ancestor(list, fake_ancestor);44374438if(diffstat)4439stat_patch_list(list);44404441if(numstat)4442numstat_patch_list(list);44434444if(summary)4445summary_patch_list(list);44464447free_patch_list(list);4448strbuf_release(&buf);4449string_list_clear(&fn_table,0);4450return0;4451}44524453static voidgit_apply_config(void)4454{4455git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4456git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4457git_config(git_default_config, NULL);4458}44594460static intoption_parse_exclude(const struct option *opt,4461const char*arg,int unset)4462{4463add_name_limit(arg,1);4464return0;4465}44664467static intoption_parse_include(const struct option *opt,4468const char*arg,int unset)4469{4470add_name_limit(arg,0);4471 has_include =1;4472return0;4473}44744475static intoption_parse_p(const struct option *opt,4476const char*arg,int unset)4477{4478 state_p_value =atoi(arg);4479 p_value_known =1;4480return0;4481}44824483static intoption_parse_space_change(const struct option *opt,4484const char*arg,int unset)4485{4486if(unset)4487 ws_ignore_action = ignore_ws_none;4488else4489 ws_ignore_action = ignore_ws_change;4490return0;4491}44924493static intoption_parse_whitespace(const struct option *opt,4494const char*arg,int unset)4495{4496const char**whitespace_option = opt->value;44974498*whitespace_option = arg;4499parse_whitespace_option(arg);4500return0;4501}45024503static intoption_parse_directory(const struct option *opt,4504const char*arg,int unset)4505{4506strbuf_reset(&root);4507strbuf_addstr(&root, arg);4508strbuf_complete(&root,'/');4509return0;4510}45114512intcmd_apply(int argc,const char**argv,const char*prefix_)4513{4514int i;4515int errs =0;4516int is_not_gitdir = !startup_info->have_repository;4517int force_apply =0;4518int options =0;4519int read_stdin =1;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}