1/* 2 * apply.c 3 * 4 * Copyright (C) Linus Torvalds, 2005 5 * 6 * This applies patches on top of some (arbitrary) version of the SCM. 7 * 8 */ 9#include"cache.h" 10#include"lockfile.h" 11#include"cache-tree.h" 12#include"quote.h" 13#include"blob.h" 14#include"delta.h" 15#include"builtin.h" 16#include"string-list.h" 17#include"dir.h" 18#include"diff.h" 19#include"parse-options.h" 20#include"xdiff-interface.h" 21#include"ll-merge.h" 22#include"rerere.h" 23 24struct apply_state { 25const char*prefix; 26int prefix_length; 27 28/* These control what gets looked at and modified */ 29int apply;/* this is not a dry-run */ 30int cached;/* apply to the index only */ 31int check;/* preimage must match working tree, don't actually apply */ 32int check_index;/* preimage must match the indexed version */ 33int update_index;/* check_index && apply */ 34 35/* These control cosmetic aspect of the output */ 36int diffstat;/* just show a diffstat, and don't actually apply */ 37int numstat;/* just show a numeric diffstat, and don't actually apply */ 38int summary;/* just report creation, deletion, etc, and don't actually apply */ 39 40/* These boolean parameters control how the apply is done */ 41int allow_overlap; 42int apply_in_reverse; 43int apply_with_reject; 44int apply_verbosely; 45int no_add; 46int threeway; 47int unidiff_zero; 48int unsafe_paths; 49 50/* Other non boolean parameters */ 51const char*fake_ancestor; 52const char*patch_input_file; 53int line_termination; 54int p_value; 55int p_value_known; 56unsigned int p_context; 57 58/* Exclude and include path parameters */ 59struct string_list limit_by_name; 60int has_include; 61}; 62 63static int newfd = -1; 64 65static const char*const apply_usage[] = { 66N_("git apply [<options>] [<patch>...]"), 67 NULL 68}; 69 70static enum ws_error_action { 71 nowarn_ws_error, 72 warn_on_ws_error, 73 die_on_ws_error, 74 correct_ws_error 75} ws_error_action = warn_on_ws_error; 76static int whitespace_error; 77static int squelch_whitespace_errors =5; 78static int applied_after_fixing_ws; 79 80static enum ws_ignore { 81 ignore_ws_none, 82 ignore_ws_change 83} ws_ignore_action = ignore_ws_none; 84 85 86static struct strbuf root = STRBUF_INIT; 87 88static voidparse_whitespace_option(const char*option) 89{ 90if(!option) { 91 ws_error_action = warn_on_ws_error; 92return; 93} 94if(!strcmp(option,"warn")) { 95 ws_error_action = warn_on_ws_error; 96return; 97} 98if(!strcmp(option,"nowarn")) { 99 ws_error_action = nowarn_ws_error; 100return; 101} 102if(!strcmp(option,"error")) { 103 ws_error_action = die_on_ws_error; 104return; 105} 106if(!strcmp(option,"error-all")) { 107 ws_error_action = die_on_ws_error; 108 squelch_whitespace_errors =0; 109return; 110} 111if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 112 ws_error_action = correct_ws_error; 113return; 114} 115die(_("unrecognized whitespace option '%s'"), option); 116} 117 118static voidparse_ignorewhitespace_option(const char*option) 119{ 120if(!option || !strcmp(option,"no") || 121!strcmp(option,"false") || !strcmp(option,"never") || 122!strcmp(option,"none")) { 123 ws_ignore_action = ignore_ws_none; 124return; 125} 126if(!strcmp(option,"change")) { 127 ws_ignore_action = ignore_ws_change; 128return; 129} 130die(_("unrecognized whitespace ignore option '%s'"), option); 131} 132 133static voidset_default_whitespace_mode(struct apply_state *state, 134const char*whitespace_option) 135{ 136if(!whitespace_option && !apply_default_whitespace) 137 ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 138} 139 140/* 141 * For "diff-stat" like behaviour, we keep track of the biggest change 142 * we've seen, and the longest filename. That allows us to do simple 143 * scaling. 144 */ 145static int max_change, max_len; 146 147/* 148 * Various "current state", notably line numbers and what 149 * file (and how) we're patching right now.. The "is_xxxx" 150 * things are flags, where -1 means "don't know yet". 151 */ 152static int state_linenr =1; 153 154/* 155 * This represents one "hunk" from a patch, starting with 156 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 157 * patch text is pointed at by patch, and its byte length 158 * is stored in size. leading and trailing are the number 159 * of context lines. 160 */ 161struct fragment { 162unsigned long leading, trailing; 163unsigned long oldpos, oldlines; 164unsigned long newpos, newlines; 165/* 166 * 'patch' is usually borrowed from buf in apply_patch(), 167 * but some codepaths store an allocated buffer. 168 */ 169const char*patch; 170unsigned free_patch:1, 171 rejected:1; 172int size; 173int linenr; 174struct fragment *next; 175}; 176 177/* 178 * When dealing with a binary patch, we reuse "leading" field 179 * to store the type of the binary hunk, either deflated "delta" 180 * or deflated "literal". 181 */ 182#define binary_patch_method leading 183#define BINARY_DELTA_DEFLATED 1 184#define BINARY_LITERAL_DEFLATED 2 185 186/* 187 * This represents a "patch" to a file, both metainfo changes 188 * such as creation/deletion, filemode and content changes represented 189 * as a series of fragments. 190 */ 191struct patch { 192char*new_name, *old_name, *def_name; 193unsigned int old_mode, new_mode; 194int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 195int rejected; 196unsigned ws_rule; 197int lines_added, lines_deleted; 198int score; 199unsigned int is_toplevel_relative:1; 200unsigned int inaccurate_eof:1; 201unsigned int is_binary:1; 202unsigned int is_copy:1; 203unsigned int is_rename:1; 204unsigned int recount:1; 205unsigned int conflicted_threeway:1; 206unsigned int direct_to_threeway:1; 207struct fragment *fragments; 208char*result; 209size_t resultsize; 210char old_sha1_prefix[41]; 211char new_sha1_prefix[41]; 212struct patch *next; 213 214/* three-way fallback result */ 215struct object_id threeway_stage[3]; 216}; 217 218static voidfree_fragment_list(struct fragment *list) 219{ 220while(list) { 221struct fragment *next = list->next; 222if(list->free_patch) 223free((char*)list->patch); 224free(list); 225 list = next; 226} 227} 228 229static voidfree_patch(struct patch *patch) 230{ 231free_fragment_list(patch->fragments); 232free(patch->def_name); 233free(patch->old_name); 234free(patch->new_name); 235free(patch->result); 236free(patch); 237} 238 239static voidfree_patch_list(struct patch *list) 240{ 241while(list) { 242struct patch *next = list->next; 243free_patch(list); 244 list = next; 245} 246} 247 248/* 249 * A line in a file, len-bytes long (includes the terminating LF, 250 * except for an incomplete line at the end if the file ends with 251 * one), and its contents hashes to 'hash'. 252 */ 253struct line { 254size_t len; 255unsigned hash :24; 256unsigned flag :8; 257#define LINE_COMMON 1 258#define LINE_PATCHED 2 259}; 260 261/* 262 * This represents a "file", which is an array of "lines". 263 */ 264struct image { 265char*buf; 266size_t len; 267size_t nr; 268size_t alloc; 269struct line *line_allocated; 270struct line *line; 271}; 272 273/* 274 * Records filenames that have been touched, in order to handle 275 * the case where more than one patches touch the same file. 276 */ 277 278static struct string_list fn_table; 279 280static uint32_thash_line(const char*cp,size_t len) 281{ 282size_t i; 283uint32_t h; 284for(i =0, h =0; i < len; i++) { 285if(!isspace(cp[i])) { 286 h = h *3+ (cp[i] &0xff); 287} 288} 289return h; 290} 291 292/* 293 * Compare lines s1 of length n1 and s2 of length n2, ignoring 294 * whitespace difference. Returns 1 if they match, 0 otherwise 295 */ 296static intfuzzy_matchlines(const char*s1,size_t n1, 297const char*s2,size_t n2) 298{ 299const char*last1 = s1 + n1 -1; 300const char*last2 = s2 + n2 -1; 301int result =0; 302 303/* ignore line endings */ 304while((*last1 =='\r') || (*last1 =='\n')) 305 last1--; 306while((*last2 =='\r') || (*last2 =='\n')) 307 last2--; 308 309/* skip leading whitespaces, if both begin with whitespace */ 310if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 311while(isspace(*s1) && (s1 <= last1)) 312 s1++; 313while(isspace(*s2) && (s2 <= last2)) 314 s2++; 315} 316/* early return if both lines are empty */ 317if((s1 > last1) && (s2 > last2)) 318return1; 319while(!result) { 320 result = *s1++ - *s2++; 321/* 322 * Skip whitespace inside. We check for whitespace on 323 * both buffers because we don't want "a b" to match 324 * "ab" 325 */ 326if(isspace(*s1) &&isspace(*s2)) { 327while(isspace(*s1) && s1 <= last1) 328 s1++; 329while(isspace(*s2) && s2 <= last2) 330 s2++; 331} 332/* 333 * If we reached the end on one side only, 334 * lines don't match 335 */ 336if( 337((s2 > last2) && (s1 <= last1)) || 338((s1 > last1) && (s2 <= last2))) 339return0; 340if((s1 > last1) && (s2 > last2)) 341break; 342} 343 344return!result; 345} 346 347static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 348{ 349ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 350 img->line_allocated[img->nr].len = len; 351 img->line_allocated[img->nr].hash =hash_line(bol, len); 352 img->line_allocated[img->nr].flag = flag; 353 img->nr++; 354} 355 356/* 357 * "buf" has the file contents to be patched (read from various sources). 358 * attach it to "image" and add line-based index to it. 359 * "image" now owns the "buf". 360 */ 361static voidprepare_image(struct image *image,char*buf,size_t len, 362int prepare_linetable) 363{ 364const char*cp, *ep; 365 366memset(image,0,sizeof(*image)); 367 image->buf = buf; 368 image->len = len; 369 370if(!prepare_linetable) 371return; 372 373 ep = image->buf + image->len; 374 cp = image->buf; 375while(cp < ep) { 376const char*next; 377for(next = cp; next < ep && *next !='\n'; next++) 378; 379if(next < ep) 380 next++; 381add_line_info(image, cp, next - cp,0); 382 cp = next; 383} 384 image->line = image->line_allocated; 385} 386 387static voidclear_image(struct image *image) 388{ 389free(image->buf); 390free(image->line_allocated); 391memset(image,0,sizeof(*image)); 392} 393 394/* fmt must contain _one_ %s and no other substitution */ 395static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 396{ 397struct strbuf sb = STRBUF_INIT; 398 399if(patch->old_name && patch->new_name && 400strcmp(patch->old_name, patch->new_name)) { 401quote_c_style(patch->old_name, &sb, NULL,0); 402strbuf_addstr(&sb," => "); 403quote_c_style(patch->new_name, &sb, NULL,0); 404}else{ 405const char*n = patch->new_name; 406if(!n) 407 n = patch->old_name; 408quote_c_style(n, &sb, NULL,0); 409} 410fprintf(output, fmt, sb.buf); 411fputc('\n', output); 412strbuf_release(&sb); 413} 414 415#define SLOP (16) 416 417static voidread_patch_file(struct strbuf *sb,int fd) 418{ 419if(strbuf_read(sb, fd,0) <0) 420die_errno("git apply: failed to read"); 421 422/* 423 * Make sure that we have some slop in the buffer 424 * so that we can do speculative "memcmp" etc, and 425 * see to it that it is NUL-filled. 426 */ 427strbuf_grow(sb, SLOP); 428memset(sb->buf + sb->len,0, SLOP); 429} 430 431static unsigned longlinelen(const char*buffer,unsigned long size) 432{ 433unsigned long len =0; 434while(size--) { 435 len++; 436if(*buffer++ =='\n') 437break; 438} 439return len; 440} 441 442static intis_dev_null(const char*str) 443{ 444returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 445} 446 447#define TERM_SPACE 1 448#define TERM_TAB 2 449 450static intname_terminate(const char*name,int namelen,int c,int terminate) 451{ 452if(c ==' '&& !(terminate & TERM_SPACE)) 453return0; 454if(c =='\t'&& !(terminate & TERM_TAB)) 455return0; 456 457return1; 458} 459 460/* remove double slashes to make --index work with such filenames */ 461static char*squash_slash(char*name) 462{ 463int i =0, j =0; 464 465if(!name) 466return NULL; 467 468while(name[i]) { 469if((name[j++] = name[i++]) =='/') 470while(name[i] =='/') 471 i++; 472} 473 name[j] ='\0'; 474return name; 475} 476 477static char*find_name_gnu(const char*line,const char*def,int p_value) 478{ 479struct strbuf name = STRBUF_INIT; 480char*cp; 481 482/* 483 * Proposed "new-style" GNU patch/diff format; see 484 * http://marc.info/?l=git&m=112927316408690&w=2 485 */ 486if(unquote_c_style(&name, line, NULL)) { 487strbuf_release(&name); 488return NULL; 489} 490 491for(cp = name.buf; p_value; p_value--) { 492 cp =strchr(cp,'/'); 493if(!cp) { 494strbuf_release(&name); 495return NULL; 496} 497 cp++; 498} 499 500strbuf_remove(&name,0, cp - name.buf); 501if(root.len) 502strbuf_insert(&name,0, root.buf, root.len); 503returnsquash_slash(strbuf_detach(&name, NULL)); 504} 505 506static size_tsane_tz_len(const char*line,size_t len) 507{ 508const char*tz, *p; 509 510if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 511return0; 512 tz = line + len -strlen(" +0500"); 513 514if(tz[1] !='+'&& tz[1] !='-') 515return0; 516 517for(p = tz +2; p != line + len; p++) 518if(!isdigit(*p)) 519return0; 520 521return line + len - tz; 522} 523 524static size_ttz_with_colon_len(const char*line,size_t len) 525{ 526const char*tz, *p; 527 528if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 529return0; 530 tz = line + len -strlen(" +08:00"); 531 532if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 533return0; 534 p = tz +2; 535if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 536!isdigit(*p++) || !isdigit(*p++)) 537return0; 538 539return line + len - tz; 540} 541 542static size_tdate_len(const char*line,size_t len) 543{ 544const char*date, *p; 545 546if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 547return0; 548 p = date = line + len -strlen("72-02-05"); 549 550if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 551!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 552!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 553return0; 554 555if(date - line >=strlen("19") && 556isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 557 date -=strlen("19"); 558 559return line + len - date; 560} 561 562static size_tshort_time_len(const char*line,size_t len) 563{ 564const char*time, *p; 565 566if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 567return0; 568 p = time = line + len -strlen(" 07:01:32"); 569 570/* Permit 1-digit hours? */ 571if(*p++ !=' '|| 572!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 573!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 574!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 575return0; 576 577return line + len - time; 578} 579 580static size_tfractional_time_len(const char*line,size_t len) 581{ 582const char*p; 583size_t n; 584 585/* Expected format: 19:41:17.620000023 */ 586if(!len || !isdigit(line[len -1])) 587return0; 588 p = line + len -1; 589 590/* Fractional seconds. */ 591while(p > line &&isdigit(*p)) 592 p--; 593if(*p !='.') 594return0; 595 596/* Hours, minutes, and whole seconds. */ 597 n =short_time_len(line, p - line); 598if(!n) 599return0; 600 601return line + len - p + n; 602} 603 604static size_ttrailing_spaces_len(const char*line,size_t len) 605{ 606const char*p; 607 608/* Expected format: ' ' x (1 or more) */ 609if(!len || line[len -1] !=' ') 610return0; 611 612 p = line + len; 613while(p != line) { 614 p--; 615if(*p !=' ') 616return line + len - (p +1); 617} 618 619/* All spaces! */ 620return len; 621} 622 623static size_tdiff_timestamp_len(const char*line,size_t len) 624{ 625const char*end = line + len; 626size_t n; 627 628/* 629 * Posix: 2010-07-05 19:41:17 630 * GNU: 2010-07-05 19:41:17.620000023 -0500 631 */ 632 633if(!isdigit(end[-1])) 634return0; 635 636 n =sane_tz_len(line, end - line); 637if(!n) 638 n =tz_with_colon_len(line, end - line); 639 end -= n; 640 641 n =short_time_len(line, end - line); 642if(!n) 643 n =fractional_time_len(line, end - line); 644 end -= n; 645 646 n =date_len(line, end - line); 647if(!n)/* No date. Too bad. */ 648return0; 649 end -= n; 650 651if(end == line)/* No space before date. */ 652return0; 653if(end[-1] =='\t') {/* Success! */ 654 end--; 655return line + len - end; 656} 657if(end[-1] !=' ')/* No space before date. */ 658return0; 659 660/* Whitespace damage. */ 661 end -=trailing_spaces_len(line, end - line); 662return line + len - end; 663} 664 665static char*find_name_common(const char*line,const char*def, 666int p_value,const char*end,int terminate) 667{ 668int len; 669const char*start = NULL; 670 671if(p_value ==0) 672 start = line; 673while(line != end) { 674char c = *line; 675 676if(!end &&isspace(c)) { 677if(c =='\n') 678break; 679if(name_terminate(start, line-start, c, terminate)) 680break; 681} 682 line++; 683if(c =='/'&& !--p_value) 684 start = line; 685} 686if(!start) 687returnsquash_slash(xstrdup_or_null(def)); 688 len = line - start; 689if(!len) 690returnsquash_slash(xstrdup_or_null(def)); 691 692/* 693 * Generally we prefer the shorter name, especially 694 * if the other one is just a variation of that with 695 * something else tacked on to the end (ie "file.orig" 696 * or "file~"). 697 */ 698if(def) { 699int deflen =strlen(def); 700if(deflen < len && !strncmp(start, def, deflen)) 701returnsquash_slash(xstrdup(def)); 702} 703 704if(root.len) { 705char*ret =xstrfmt("%s%.*s", root.buf, len, start); 706returnsquash_slash(ret); 707} 708 709returnsquash_slash(xmemdupz(start, len)); 710} 711 712static char*find_name(const char*line,char*def,int p_value,int terminate) 713{ 714if(*line =='"') { 715char*name =find_name_gnu(line, def, p_value); 716if(name) 717return name; 718} 719 720returnfind_name_common(line, def, p_value, NULL, terminate); 721} 722 723static char*find_name_traditional(const char*line,char*def,int p_value) 724{ 725size_t len; 726size_t date_len; 727 728if(*line =='"') { 729char*name =find_name_gnu(line, def, p_value); 730if(name) 731return name; 732} 733 734 len =strchrnul(line,'\n') - line; 735 date_len =diff_timestamp_len(line, len); 736if(!date_len) 737returnfind_name_common(line, def, p_value, NULL, TERM_TAB); 738 len -= date_len; 739 740returnfind_name_common(line, def, p_value, line + len,0); 741} 742 743static intcount_slashes(const char*cp) 744{ 745int cnt =0; 746char ch; 747 748while((ch = *cp++)) 749if(ch =='/') 750 cnt++; 751return cnt; 752} 753 754/* 755 * Given the string after "--- " or "+++ ", guess the appropriate 756 * p_value for the given patch. 757 */ 758static intguess_p_value(struct apply_state *state,const char*nameline) 759{ 760char*name, *cp; 761int val = -1; 762 763if(is_dev_null(nameline)) 764return-1; 765 name =find_name_traditional(nameline, NULL,0); 766if(!name) 767return-1; 768 cp =strchr(name,'/'); 769if(!cp) 770 val =0; 771else if(state->prefix) { 772/* 773 * Does it begin with "a/$our-prefix" and such? Then this is 774 * very likely to apply to our directory. 775 */ 776if(!strncmp(name, state->prefix, state->prefix_length)) 777 val =count_slashes(state->prefix); 778else{ 779 cp++; 780if(!strncmp(cp, state->prefix, state->prefix_length)) 781 val =count_slashes(state->prefix) +1; 782} 783} 784free(name); 785return val; 786} 787 788/* 789 * Does the ---/+++ line have the POSIX timestamp after the last HT? 790 * GNU diff puts epoch there to signal a creation/deletion event. Is 791 * this such a timestamp? 792 */ 793static inthas_epoch_timestamp(const char*nameline) 794{ 795/* 796 * We are only interested in epoch timestamp; any non-zero 797 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 798 * For the same reason, the date must be either 1969-12-31 or 799 * 1970-01-01, and the seconds part must be "00". 800 */ 801const char stamp_regexp[] = 802"^(1969-12-31|1970-01-01)" 803" " 804"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 805" " 806"([-+][0-2][0-9]:?[0-5][0-9])\n"; 807const char*timestamp = NULL, *cp, *colon; 808static regex_t *stamp; 809 regmatch_t m[10]; 810int zoneoffset; 811int hourminute; 812int status; 813 814for(cp = nameline; *cp !='\n'; cp++) { 815if(*cp =='\t') 816 timestamp = cp +1; 817} 818if(!timestamp) 819return0; 820if(!stamp) { 821 stamp =xmalloc(sizeof(*stamp)); 822if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 823warning(_("Cannot prepare timestamp regexp%s"), 824 stamp_regexp); 825return0; 826} 827} 828 829 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 830if(status) { 831if(status != REG_NOMATCH) 832warning(_("regexec returned%dfor input:%s"), 833 status, timestamp); 834return0; 835} 836 837 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 838if(*colon ==':') 839 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 840else 841 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 842if(timestamp[m[3].rm_so] =='-') 843 zoneoffset = -zoneoffset; 844 845/* 846 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 847 * (west of GMT) or 1970-01-01 (east of GMT) 848 */ 849if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 850(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 851return0; 852 853 hourminute = (strtol(timestamp +11, NULL,10) *60+ 854strtol(timestamp +14, NULL,10) - 855 zoneoffset); 856 857return((zoneoffset <0&& hourminute ==1440) || 858(0<= zoneoffset && !hourminute)); 859} 860 861/* 862 * Get the name etc info from the ---/+++ lines of a traditional patch header 863 * 864 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 865 * files, we can happily check the index for a match, but for creating a 866 * new file we should try to match whatever "patch" does. I have no idea. 867 */ 868static voidparse_traditional_patch(struct apply_state *state, 869const char*first, 870const char*second, 871struct patch *patch) 872{ 873char*name; 874 875 first +=4;/* skip "--- " */ 876 second +=4;/* skip "+++ " */ 877if(!state->p_value_known) { 878int p, q; 879 p =guess_p_value(state, first); 880 q =guess_p_value(state, second); 881if(p <0) p = q; 882if(0<= p && p == q) { 883 state->p_value = p; 884 state->p_value_known =1; 885} 886} 887if(is_dev_null(first)) { 888 patch->is_new =1; 889 patch->is_delete =0; 890 name =find_name_traditional(second, NULL, state->p_value); 891 patch->new_name = name; 892}else if(is_dev_null(second)) { 893 patch->is_new =0; 894 patch->is_delete =1; 895 name =find_name_traditional(first, NULL, state->p_value); 896 patch->old_name = name; 897}else{ 898char*first_name; 899 first_name =find_name_traditional(first, NULL, state->p_value); 900 name =find_name_traditional(second, first_name, state->p_value); 901free(first_name); 902if(has_epoch_timestamp(first)) { 903 patch->is_new =1; 904 patch->is_delete =0; 905 patch->new_name = name; 906}else if(has_epoch_timestamp(second)) { 907 patch->is_new =0; 908 patch->is_delete =1; 909 patch->old_name = name; 910}else{ 911 patch->old_name = name; 912 patch->new_name =xstrdup_or_null(name); 913} 914} 915if(!name) 916die(_("unable to find filename in patch at line%d"), state_linenr); 917} 918 919static intgitdiff_hdrend(struct apply_state *state, 920const char*line, 921struct patch *patch) 922{ 923return-1; 924} 925 926/* 927 * We're anal about diff header consistency, to make 928 * sure that we don't end up having strange ambiguous 929 * patches floating around. 930 * 931 * As a result, gitdiff_{old|new}name() will check 932 * their names against any previous information, just 933 * to make sure.. 934 */ 935#define DIFF_OLD_NAME 0 936#define DIFF_NEW_NAME 1 937 938static voidgitdiff_verify_name(struct apply_state *state, 939const char*line, 940int isnull, 941char**name, 942int side) 943{ 944if(!*name && !isnull) { 945*name =find_name(line, NULL, state->p_value, TERM_TAB); 946return; 947} 948 949if(*name) { 950int len =strlen(*name); 951char*another; 952if(isnull) 953die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 954*name, state_linenr); 955 another =find_name(line, NULL, state->p_value, TERM_TAB); 956if(!another ||memcmp(another, *name, len +1)) 957die((side == DIFF_NEW_NAME) ? 958_("git apply: bad git-diff - inconsistent new filename on line%d") : 959_("git apply: bad git-diff - inconsistent old filename on line%d"), state_linenr); 960free(another); 961}else{ 962/* expect "/dev/null" */ 963if(memcmp("/dev/null", line,9) || line[9] !='\n') 964die(_("git apply: bad git-diff - expected /dev/null on line%d"), state_linenr); 965} 966} 967 968static intgitdiff_oldname(struct apply_state *state, 969const char*line, 970struct patch *patch) 971{ 972gitdiff_verify_name(state, line, 973 patch->is_new, &patch->old_name, 974 DIFF_OLD_NAME); 975return0; 976} 977 978static intgitdiff_newname(struct apply_state *state, 979const char*line, 980struct patch *patch) 981{ 982gitdiff_verify_name(state, line, 983 patch->is_delete, &patch->new_name, 984 DIFF_NEW_NAME); 985return0; 986} 987 988static intgitdiff_oldmode(struct apply_state *state, 989const char*line, 990struct patch *patch) 991{ 992 patch->old_mode =strtoul(line, NULL,8); 993return0; 994} 995 996static intgitdiff_newmode(struct apply_state *state, 997const char*line, 998struct patch *patch) 999{1000 patch->new_mode =strtoul(line, NULL,8);1001return0;1002}10031004static intgitdiff_delete(struct apply_state *state,1005const char*line,1006struct patch *patch)1007{1008 patch->is_delete =1;1009free(patch->old_name);1010 patch->old_name =xstrdup_or_null(patch->def_name);1011returngitdiff_oldmode(state, line, patch);1012}10131014static intgitdiff_newfile(struct apply_state *state,1015const char*line,1016struct patch *patch)1017{1018 patch->is_new =1;1019free(patch->new_name);1020 patch->new_name =xstrdup_or_null(patch->def_name);1021returngitdiff_newmode(state, line, patch);1022}10231024static intgitdiff_copysrc(struct apply_state *state,1025const char*line,1026struct patch *patch)1027{1028 patch->is_copy =1;1029free(patch->old_name);1030 patch->old_name =find_name(line, NULL, state->p_value ? state->p_value -1:0,0);1031return0;1032}10331034static intgitdiff_copydst(struct apply_state *state,1035const char*line,1036struct patch *patch)1037{1038 patch->is_copy =1;1039free(patch->new_name);1040 patch->new_name =find_name(line, NULL, state->p_value ? state->p_value -1:0,0);1041return0;1042}10431044static intgitdiff_renamesrc(struct apply_state *state,1045const char*line,1046struct patch *patch)1047{1048 patch->is_rename =1;1049free(patch->old_name);1050 patch->old_name =find_name(line, NULL, state->p_value ? state->p_value -1:0,0);1051return0;1052}10531054static intgitdiff_renamedst(struct apply_state *state,1055const char*line,1056struct patch *patch)1057{1058 patch->is_rename =1;1059free(patch->new_name);1060 patch->new_name =find_name(line, NULL, state->p_value ? state->p_value -1:0,0);1061return0;1062}10631064static intgitdiff_similarity(struct apply_state *state,1065const char*line,1066struct patch *patch)1067{1068unsigned long val =strtoul(line, NULL,10);1069if(val <=100)1070 patch->score = val;1071return0;1072}10731074static intgitdiff_dissimilarity(struct apply_state *state,1075const char*line,1076struct patch *patch)1077{1078unsigned long val =strtoul(line, NULL,10);1079if(val <=100)1080 patch->score = val;1081return0;1082}10831084static intgitdiff_index(struct apply_state *state,1085const char*line,1086struct patch *patch)1087{1088/*1089 * index line is N hexadecimal, "..", N hexadecimal,1090 * and optional space with octal mode.1091 */1092const char*ptr, *eol;1093int len;10941095 ptr =strchr(line,'.');1096if(!ptr || ptr[1] !='.'||40< ptr - line)1097return0;1098 len = ptr - line;1099memcpy(patch->old_sha1_prefix, line, len);1100 patch->old_sha1_prefix[len] =0;11011102 line = ptr +2;1103 ptr =strchr(line,' ');1104 eol =strchrnul(line,'\n');11051106if(!ptr || eol < ptr)1107 ptr = eol;1108 len = ptr - line;11091110if(40< len)1111return0;1112memcpy(patch->new_sha1_prefix, line, len);1113 patch->new_sha1_prefix[len] =0;1114if(*ptr ==' ')1115 patch->old_mode =strtoul(ptr+1, NULL,8);1116return0;1117}11181119/*1120 * This is normal for a diff that doesn't change anything: we'll fall through1121 * into the next diff. Tell the parser to break out.1122 */1123static intgitdiff_unrecognized(struct apply_state *state,1124const char*line,1125struct patch *patch)1126{1127return-1;1128}11291130/*1131 * Skip p_value leading components from "line"; as we do not accept1132 * absolute paths, return NULL in that case.1133 */1134static const char*skip_tree_prefix(struct apply_state *state,1135const char*line,1136int llen)1137{1138int nslash;1139int i;11401141if(!state->p_value)1142return(llen && line[0] =='/') ? NULL : line;11431144 nslash = state->p_value;1145for(i =0; i < llen; i++) {1146int ch = line[i];1147if(ch =='/'&& --nslash <=0)1148return(i ==0) ? NULL : &line[i +1];1149}1150return NULL;1151}11521153/*1154 * This is to extract the same name that appears on "diff --git"1155 * line. We do not find and return anything if it is a rename1156 * patch, and it is OK because we will find the name elsewhere.1157 * We need to reliably find name only when it is mode-change only,1158 * creation or deletion of an empty file. In any of these cases,1159 * both sides are the same name under a/ and b/ respectively.1160 */1161static char*git_header_name(struct apply_state *state,1162const char*line,1163int llen)1164{1165const char*name;1166const char*second = NULL;1167size_t len, line_len;11681169 line +=strlen("diff --git ");1170 llen -=strlen("diff --git ");11711172if(*line =='"') {1173const char*cp;1174struct strbuf first = STRBUF_INIT;1175struct strbuf sp = STRBUF_INIT;11761177if(unquote_c_style(&first, line, &second))1178goto free_and_fail1;11791180/* strip the a/b prefix including trailing slash */1181 cp =skip_tree_prefix(state, first.buf, first.len);1182if(!cp)1183goto free_and_fail1;1184strbuf_remove(&first,0, cp - first.buf);11851186/*1187 * second points at one past closing dq of name.1188 * find the second name.1189 */1190while((second < line + llen) &&isspace(*second))1191 second++;11921193if(line + llen <= second)1194goto free_and_fail1;1195if(*second =='"') {1196if(unquote_c_style(&sp, second, NULL))1197goto free_and_fail1;1198 cp =skip_tree_prefix(state, sp.buf, sp.len);1199if(!cp)1200goto free_and_fail1;1201/* They must match, otherwise ignore */1202if(strcmp(cp, first.buf))1203goto free_and_fail1;1204strbuf_release(&sp);1205returnstrbuf_detach(&first, NULL);1206}12071208/* unquoted second */1209 cp =skip_tree_prefix(state, second, line + llen - second);1210if(!cp)1211goto free_and_fail1;1212if(line + llen - cp != first.len ||1213memcmp(first.buf, cp, first.len))1214goto free_and_fail1;1215returnstrbuf_detach(&first, NULL);12161217 free_and_fail1:1218strbuf_release(&first);1219strbuf_release(&sp);1220return NULL;1221}12221223/* unquoted first name */1224 name =skip_tree_prefix(state, line, llen);1225if(!name)1226return NULL;12271228/*1229 * since the first name is unquoted, a dq if exists must be1230 * the beginning of the second name.1231 */1232for(second = name; second < line + llen; second++) {1233if(*second =='"') {1234struct strbuf sp = STRBUF_INIT;1235const char*np;12361237if(unquote_c_style(&sp, second, NULL))1238goto free_and_fail2;12391240 np =skip_tree_prefix(state, sp.buf, sp.len);1241if(!np)1242goto free_and_fail2;12431244 len = sp.buf + sp.len - np;1245if(len < second - name &&1246!strncmp(np, name, len) &&1247isspace(name[len])) {1248/* Good */1249strbuf_remove(&sp,0, np - sp.buf);1250returnstrbuf_detach(&sp, NULL);1251}12521253 free_and_fail2:1254strbuf_release(&sp);1255return NULL;1256}1257}12581259/*1260 * Accept a name only if it shows up twice, exactly the same1261 * form.1262 */1263 second =strchr(name,'\n');1264if(!second)1265return NULL;1266 line_len = second - name;1267for(len =0; ; len++) {1268switch(name[len]) {1269default:1270continue;1271case'\n':1272return NULL;1273case'\t':case' ':1274/*1275 * Is this the separator between the preimage1276 * and the postimage pathname? Again, we are1277 * only interested in the case where there is1278 * no rename, as this is only to set def_name1279 * and a rename patch has the names elsewhere1280 * in an unambiguous form.1281 */1282if(!name[len +1])1283return NULL;/* no postimage name */1284 second =skip_tree_prefix(state, name + len +1,1285 line_len - (len +1));1286if(!second)1287return NULL;1288/*1289 * Does len bytes starting at "name" and "second"1290 * (that are separated by one HT or SP we just1291 * found) exactly match?1292 */1293if(second[len] =='\n'&& !strncmp(name, second, len))1294returnxmemdupz(name, len);1295}1296}1297}12981299/* Verify that we recognize the lines following a git header */1300static intparse_git_header(struct apply_state *state,1301const char*line,1302int len,1303unsigned int size,1304struct patch *patch)1305{1306unsigned long offset;13071308/* A git diff has explicit new/delete information, so we don't guess */1309 patch->is_new =0;1310 patch->is_delete =0;13111312/*1313 * Some things may not have the old name in the1314 * rest of the headers anywhere (pure mode changes,1315 * or removing or adding empty files), so we get1316 * the default name from the header.1317 */1318 patch->def_name =git_header_name(state, line, len);1319if(patch->def_name && root.len) {1320char*s =xstrfmt("%s%s", root.buf, patch->def_name);1321free(patch->def_name);1322 patch->def_name = s;1323}13241325 line += len;1326 size -= len;1327 state_linenr++;1328for(offset = len ; size >0; offset += len, size -= len, line += len, state_linenr++) {1329static const struct opentry {1330const char*str;1331int(*fn)(struct apply_state *,const char*,struct patch *);1332} optable[] = {1333{"@@ -", gitdiff_hdrend },1334{"--- ", gitdiff_oldname },1335{"+++ ", gitdiff_newname },1336{"old mode ", gitdiff_oldmode },1337{"new mode ", gitdiff_newmode },1338{"deleted file mode ", gitdiff_delete },1339{"new file mode ", gitdiff_newfile },1340{"copy from ", gitdiff_copysrc },1341{"copy to ", gitdiff_copydst },1342{"rename old ", gitdiff_renamesrc },1343{"rename new ", gitdiff_renamedst },1344{"rename from ", gitdiff_renamesrc },1345{"rename to ", gitdiff_renamedst },1346{"similarity index ", gitdiff_similarity },1347{"dissimilarity index ", gitdiff_dissimilarity },1348{"index ", gitdiff_index },1349{"", gitdiff_unrecognized },1350};1351int i;13521353 len =linelen(line, size);1354if(!len || line[len-1] !='\n')1355break;1356for(i =0; i <ARRAY_SIZE(optable); i++) {1357const struct opentry *p = optable + i;1358int oplen =strlen(p->str);1359if(len < oplen ||memcmp(p->str, line, oplen))1360continue;1361if(p->fn(state, line + oplen, patch) <0)1362return offset;1363break;1364}1365}13661367return offset;1368}13691370static intparse_num(const char*line,unsigned long*p)1371{1372char*ptr;13731374if(!isdigit(*line))1375return0;1376*p =strtoul(line, &ptr,10);1377return ptr - line;1378}13791380static intparse_range(const char*line,int len,int offset,const char*expect,1381unsigned long*p1,unsigned long*p2)1382{1383int digits, ex;13841385if(offset <0|| offset >= len)1386return-1;1387 line += offset;1388 len -= offset;13891390 digits =parse_num(line, p1);1391if(!digits)1392return-1;13931394 offset += digits;1395 line += digits;1396 len -= digits;13971398*p2 =1;1399if(*line ==',') {1400 digits =parse_num(line+1, p2);1401if(!digits)1402return-1;14031404 offset += digits+1;1405 line += digits+1;1406 len -= digits+1;1407}14081409 ex =strlen(expect);1410if(ex > len)1411return-1;1412if(memcmp(line, expect, ex))1413return-1;14141415return offset + ex;1416}14171418static voidrecount_diff(const char*line,int size,struct fragment *fragment)1419{1420int oldlines =0, newlines =0, ret =0;14211422if(size <1) {1423warning("recount: ignore empty hunk");1424return;1425}14261427for(;;) {1428int len =linelen(line, size);1429 size -= len;1430 line += len;14311432if(size <1)1433break;14341435switch(*line) {1436case' ':case'\n':1437 newlines++;1438/* fall through */1439case'-':1440 oldlines++;1441continue;1442case'+':1443 newlines++;1444continue;1445case'\\':1446continue;1447case'@':1448 ret = size <3|| !starts_with(line,"@@ ");1449break;1450case'd':1451 ret = size <5|| !starts_with(line,"diff ");1452break;1453default:1454 ret = -1;1455break;1456}1457if(ret) {1458warning(_("recount: unexpected line: %.*s"),1459(int)linelen(line, size), line);1460return;1461}1462break;1463}1464 fragment->oldlines = oldlines;1465 fragment->newlines = newlines;1466}14671468/*1469 * Parse a unified diff fragment header of the1470 * form "@@ -a,b +c,d @@"1471 */1472static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1473{1474int offset;14751476if(!len || line[len-1] !='\n')1477return-1;14781479/* Figure out the number of lines in a fragment */1480 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1481 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14821483return offset;1484}14851486static intfind_header(struct apply_state *state,1487const char*line,1488unsigned long size,1489int*hdrsize,1490struct patch *patch)1491{1492unsigned long offset, len;14931494 patch->is_toplevel_relative =0;1495 patch->is_rename = patch->is_copy =0;1496 patch->is_new = patch->is_delete = -1;1497 patch->old_mode = patch->new_mode =0;1498 patch->old_name = patch->new_name = NULL;1499for(offset =0; size >0; offset += len, size -= len, line += len, state_linenr++) {1500unsigned long nextlen;15011502 len =linelen(line, size);1503if(!len)1504break;15051506/* Testing this early allows us to take a few shortcuts.. */1507if(len <6)1508continue;15091510/*1511 * Make sure we don't find any unconnected patch fragments.1512 * That's a sign that we didn't find a header, and that a1513 * patch has become corrupted/broken up.1514 */1515if(!memcmp("@@ -", line,4)) {1516struct fragment dummy;1517if(parse_fragment_header(line, len, &dummy) <0)1518continue;1519die(_("patch fragment without header at line%d: %.*s"),1520 state_linenr, (int)len-1, line);1521}15221523if(size < len +6)1524break;15251526/*1527 * Git patch? It might not have a real patch, just a rename1528 * or mode change, so we handle that specially1529 */1530if(!memcmp("diff --git ", line,11)) {1531int git_hdr_len =parse_git_header(state, line, len, size, patch);1532if(git_hdr_len <= len)1533continue;1534if(!patch->old_name && !patch->new_name) {1535if(!patch->def_name)1536die(Q_("git diff header lacks filename information when removing "1537"%dleading pathname component (line%d)",1538"git diff header lacks filename information when removing "1539"%dleading pathname components (line%d)",1540 state->p_value),1541 state->p_value, state_linenr);1542 patch->old_name =xstrdup(patch->def_name);1543 patch->new_name =xstrdup(patch->def_name);1544}1545if(!patch->is_delete && !patch->new_name)1546die("git diff header lacks filename information "1547"(line%d)", state_linenr);1548 patch->is_toplevel_relative =1;1549*hdrsize = git_hdr_len;1550return offset;1551}15521553/* --- followed by +++ ? */1554if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1555continue;15561557/*1558 * We only accept unified patches, so we want it to1559 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1560 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1561 */1562 nextlen =linelen(line + len, size - len);1563if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1564continue;15651566/* Ok, we'll consider it a patch */1567parse_traditional_patch(state, line, line+len, patch);1568*hdrsize = len + nextlen;1569 state_linenr +=2;1570return offset;1571}1572return-1;1573}15741575static voidrecord_ws_error(struct apply_state *state,1576unsigned result,1577const char*line,1578int len,1579int linenr)1580{1581char*err;15821583if(!result)1584return;15851586 whitespace_error++;1587if(squelch_whitespace_errors &&1588 squelch_whitespace_errors < whitespace_error)1589return;15901591 err =whitespace_error_string(result);1592fprintf(stderr,"%s:%d:%s.\n%.*s\n",1593 state->patch_input_file, linenr, err, len, line);1594free(err);1595}15961597static voidcheck_whitespace(struct apply_state *state,1598const char*line,1599int len,1600unsigned ws_rule)1601{1602unsigned result =ws_check(line +1, len -1, ws_rule);16031604record_ws_error(state, result, line +1, len -2, state_linenr);1605}16061607/*1608 * Parse a unified diff. Note that this really needs to parse each1609 * fragment separately, since the only way to know the difference1610 * between a "---" that is part of a patch, and a "---" that starts1611 * the next patch is to look at the line counts..1612 */1613static intparse_fragment(struct apply_state *state,1614const char*line,1615unsigned long size,1616struct patch *patch,1617struct fragment *fragment)1618{1619int added, deleted;1620int len =linelen(line, size), offset;1621unsigned long oldlines, newlines;1622unsigned long leading, trailing;16231624 offset =parse_fragment_header(line, len, fragment);1625if(offset <0)1626return-1;1627if(offset >0&& patch->recount)1628recount_diff(line + offset, size - offset, fragment);1629 oldlines = fragment->oldlines;1630 newlines = fragment->newlines;1631 leading =0;1632 trailing =0;16331634/* Parse the thing.. */1635 line += len;1636 size -= len;1637 state_linenr++;1638 added = deleted =0;1639for(offset = len;16400< size;1641 offset += len, size -= len, line += len, state_linenr++) {1642if(!oldlines && !newlines)1643break;1644 len =linelen(line, size);1645if(!len || line[len-1] !='\n')1646return-1;1647switch(*line) {1648default:1649return-1;1650case'\n':/* newer GNU diff, an empty context line */1651case' ':1652 oldlines--;1653 newlines--;1654if(!deleted && !added)1655 leading++;1656 trailing++;1657if(!state->apply_in_reverse &&1658 ws_error_action == correct_ws_error)1659check_whitespace(state, line, len, patch->ws_rule);1660break;1661case'-':1662if(state->apply_in_reverse &&1663 ws_error_action != nowarn_ws_error)1664check_whitespace(state, line, len, patch->ws_rule);1665 deleted++;1666 oldlines--;1667 trailing =0;1668break;1669case'+':1670if(!state->apply_in_reverse &&1671 ws_error_action != nowarn_ws_error)1672check_whitespace(state, line, len, patch->ws_rule);1673 added++;1674 newlines--;1675 trailing =0;1676break;16771678/*1679 * We allow "\ No newline at end of file". Depending1680 * on locale settings when the patch was produced we1681 * don't know what this line looks like. The only1682 * thing we do know is that it begins with "\ ".1683 * Checking for 12 is just for sanity check -- any1684 * l10n of "\ No newline..." is at least that long.1685 */1686case'\\':1687if(len <12||memcmp(line,"\\",2))1688return-1;1689break;1690}1691}1692if(oldlines || newlines)1693return-1;1694if(!deleted && !added)1695return-1;16961697 fragment->leading = leading;1698 fragment->trailing = trailing;16991700/*1701 * If a fragment ends with an incomplete line, we failed to include1702 * it in the above loop because we hit oldlines == newlines == 01703 * before seeing it.1704 */1705if(12< size && !memcmp(line,"\\",2))1706 offset +=linelen(line, size);17071708 patch->lines_added += added;1709 patch->lines_deleted += deleted;17101711if(0< patch->is_new && oldlines)1712returnerror(_("new file depends on old contents"));1713if(0< patch->is_delete && newlines)1714returnerror(_("deleted file still has contents"));1715return offset;1716}17171718/*1719 * We have seen "diff --git a/... b/..." header (or a traditional patch1720 * header). Read hunks that belong to this patch into fragments and hang1721 * them to the given patch structure.1722 *1723 * The (fragment->patch, fragment->size) pair points into the memory given1724 * by the caller, not a copy, when we return.1725 */1726static intparse_single_patch(struct apply_state *state,1727const char*line,1728unsigned long size,1729struct patch *patch)1730{1731unsigned long offset =0;1732unsigned long oldlines =0, newlines =0, context =0;1733struct fragment **fragp = &patch->fragments;17341735while(size >4&& !memcmp(line,"@@ -",4)) {1736struct fragment *fragment;1737int len;17381739 fragment =xcalloc(1,sizeof(*fragment));1740 fragment->linenr = state_linenr;1741 len =parse_fragment(state, line, size, patch, fragment);1742if(len <=0)1743die(_("corrupt patch at line%d"), state_linenr);1744 fragment->patch = line;1745 fragment->size = len;1746 oldlines += fragment->oldlines;1747 newlines += fragment->newlines;1748 context += fragment->leading + fragment->trailing;17491750*fragp = fragment;1751 fragp = &fragment->next;17521753 offset += len;1754 line += len;1755 size -= len;1756}17571758/*1759 * If something was removed (i.e. we have old-lines) it cannot1760 * be creation, and if something was added it cannot be1761 * deletion. However, the reverse is not true; --unified=01762 * patches that only add are not necessarily creation even1763 * though they do not have any old lines, and ones that only1764 * delete are not necessarily deletion.1765 *1766 * Unfortunately, a real creation/deletion patch do _not_ have1767 * any context line by definition, so we cannot safely tell it1768 * apart with --unified=0 insanity. At least if the patch has1769 * more than one hunk it is not creation or deletion.1770 */1771if(patch->is_new <0&&1772(oldlines || (patch->fragments && patch->fragments->next)))1773 patch->is_new =0;1774if(patch->is_delete <0&&1775(newlines || (patch->fragments && patch->fragments->next)))1776 patch->is_delete =0;17771778if(0< patch->is_new && oldlines)1779die(_("new file%sdepends on old contents"), patch->new_name);1780if(0< patch->is_delete && newlines)1781die(_("deleted file%sstill has contents"), patch->old_name);1782if(!patch->is_delete && !newlines && context)1783fprintf_ln(stderr,1784_("** warning: "1785"file%sbecomes empty but is not deleted"),1786 patch->new_name);17871788return offset;1789}17901791staticinlineintmetadata_changes(struct patch *patch)1792{1793return patch->is_rename >0||1794 patch->is_copy >0||1795 patch->is_new >0||1796 patch->is_delete ||1797(patch->old_mode && patch->new_mode &&1798 patch->old_mode != patch->new_mode);1799}18001801static char*inflate_it(const void*data,unsigned long size,1802unsigned long inflated_size)1803{1804 git_zstream stream;1805void*out;1806int st;18071808memset(&stream,0,sizeof(stream));18091810 stream.next_in = (unsigned char*)data;1811 stream.avail_in = size;1812 stream.next_out = out =xmalloc(inflated_size);1813 stream.avail_out = inflated_size;1814git_inflate_init(&stream);1815 st =git_inflate(&stream, Z_FINISH);1816git_inflate_end(&stream);1817if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1818free(out);1819return NULL;1820}1821return out;1822}18231824/*1825 * Read a binary hunk and return a new fragment; fragment->patch1826 * points at an allocated memory that the caller must free, so1827 * it is marked as "->free_patch = 1".1828 */1829static struct fragment *parse_binary_hunk(char**buf_p,1830unsigned long*sz_p,1831int*status_p,1832int*used_p)1833{1834/*1835 * Expect a line that begins with binary patch method ("literal"1836 * or "delta"), followed by the length of data before deflating.1837 * a sequence of 'length-byte' followed by base-85 encoded data1838 * should follow, terminated by a newline.1839 *1840 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1841 * and we would limit the patch line to 66 characters,1842 * so one line can fit up to 13 groups that would decode1843 * to 52 bytes max. The length byte 'A'-'Z' corresponds1844 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1845 */1846int llen, used;1847unsigned long size = *sz_p;1848char*buffer = *buf_p;1849int patch_method;1850unsigned long origlen;1851char*data = NULL;1852int hunk_size =0;1853struct fragment *frag;18541855 llen =linelen(buffer, size);1856 used = llen;18571858*status_p =0;18591860if(starts_with(buffer,"delta ")) {1861 patch_method = BINARY_DELTA_DEFLATED;1862 origlen =strtoul(buffer +6, NULL,10);1863}1864else if(starts_with(buffer,"literal ")) {1865 patch_method = BINARY_LITERAL_DEFLATED;1866 origlen =strtoul(buffer +8, NULL,10);1867}1868else1869return NULL;18701871 state_linenr++;1872 buffer += llen;1873while(1) {1874int byte_length, max_byte_length, newsize;1875 llen =linelen(buffer, size);1876 used += llen;1877 state_linenr++;1878if(llen ==1) {1879/* consume the blank line */1880 buffer++;1881 size--;1882break;1883}1884/*1885 * Minimum line is "A00000\n" which is 7-byte long,1886 * and the line length must be multiple of 5 plus 2.1887 */1888if((llen <7) || (llen-2) %5)1889goto corrupt;1890 max_byte_length = (llen -2) /5*4;1891 byte_length = *buffer;1892if('A'<= byte_length && byte_length <='Z')1893 byte_length = byte_length -'A'+1;1894else if('a'<= byte_length && byte_length <='z')1895 byte_length = byte_length -'a'+27;1896else1897goto corrupt;1898/* if the input length was not multiple of 4, we would1899 * have filler at the end but the filler should never1900 * exceed 3 bytes1901 */1902if(max_byte_length < byte_length ||1903 byte_length <= max_byte_length -4)1904goto corrupt;1905 newsize = hunk_size + byte_length;1906 data =xrealloc(data, newsize);1907if(decode_85(data + hunk_size, buffer +1, byte_length))1908goto corrupt;1909 hunk_size = newsize;1910 buffer += llen;1911 size -= llen;1912}19131914 frag =xcalloc(1,sizeof(*frag));1915 frag->patch =inflate_it(data, hunk_size, origlen);1916 frag->free_patch =1;1917if(!frag->patch)1918goto corrupt;1919free(data);1920 frag->size = origlen;1921*buf_p = buffer;1922*sz_p = size;1923*used_p = used;1924 frag->binary_patch_method = patch_method;1925return frag;19261927 corrupt:1928free(data);1929*status_p = -1;1930error(_("corrupt binary patch at line%d: %.*s"),1931 state_linenr-1, llen-1, buffer);1932return NULL;1933}19341935/*1936 * Returns:1937 * -1 in case of error,1938 * the length of the parsed binary patch otherwise1939 */1940static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1941{1942/*1943 * We have read "GIT binary patch\n"; what follows is a line1944 * that says the patch method (currently, either "literal" or1945 * "delta") and the length of data before deflating; a1946 * sequence of 'length-byte' followed by base-85 encoded data1947 * follows.1948 *1949 * When a binary patch is reversible, there is another binary1950 * hunk in the same format, starting with patch method (either1951 * "literal" or "delta") with the length of data, and a sequence1952 * of length-byte + base-85 encoded data, terminated with another1953 * empty line. This data, when applied to the postimage, produces1954 * the preimage.1955 */1956struct fragment *forward;1957struct fragment *reverse;1958int status;1959int used, used_1;19601961 forward =parse_binary_hunk(&buffer, &size, &status, &used);1962if(!forward && !status)1963/* there has to be one hunk (forward hunk) */1964returnerror(_("unrecognized binary patch at line%d"), state_linenr-1);1965if(status)1966/* otherwise we already gave an error message */1967return status;19681969 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1970if(reverse)1971 used += used_1;1972else if(status) {1973/*1974 * Not having reverse hunk is not an error, but having1975 * a corrupt reverse hunk is.1976 */1977free((void*) forward->patch);1978free(forward);1979return status;1980}1981 forward->next = reverse;1982 patch->fragments = forward;1983 patch->is_binary =1;1984return used;1985}19861987static voidprefix_one(struct apply_state *state,char**name)1988{1989char*old_name = *name;1990if(!old_name)1991return;1992*name =xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));1993free(old_name);1994}19951996static voidprefix_patch(struct apply_state *state,struct patch *p)1997{1998if(!state->prefix || p->is_toplevel_relative)1999return;2000prefix_one(state, &p->new_name);2001prefix_one(state, &p->old_name);2002}20032004/*2005 * include/exclude2006 */20072008static voidadd_name_limit(struct apply_state *state,2009const char*name,2010int exclude)2011{2012struct string_list_item *it;20132014 it =string_list_append(&state->limit_by_name, name);2015 it->util = exclude ? NULL : (void*)1;2016}20172018static intuse_patch(struct apply_state *state,struct patch *p)2019{2020const char*pathname = p->new_name ? p->new_name : p->old_name;2021int i;20222023/* Paths outside are not touched regardless of "--include" */2024if(0< state->prefix_length) {2025int pathlen =strlen(pathname);2026if(pathlen <= state->prefix_length ||2027memcmp(state->prefix, pathname, state->prefix_length))2028return0;2029}20302031/* See if it matches any of exclude/include rule */2032for(i =0; i < state->limit_by_name.nr; i++) {2033struct string_list_item *it = &state->limit_by_name.items[i];2034if(!wildmatch(it->string, pathname,0, NULL))2035return(it->util != NULL);2036}20372038/*2039 * If we had any include, a path that does not match any rule is2040 * not used. Otherwise, we saw bunch of exclude rules (or none)2041 * and such a path is used.2042 */2043return!state->has_include;2044}204520462047/*2048 * Read the patch text in "buffer" that extends for "size" bytes; stop2049 * reading after seeing a single patch (i.e. changes to a single file).2050 * Create fragments (i.e. patch hunks) and hang them to the given patch.2051 * Return the number of bytes consumed, so that the caller can call us2052 * again for the next patch.2053 */2054static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2055{2056int hdrsize, patchsize;2057int offset =find_header(state, buffer, size, &hdrsize, patch);20582059if(offset <0)2060return offset;20612062prefix_patch(state, patch);20632064if(!use_patch(state, patch))2065 patch->ws_rule =0;2066else2067 patch->ws_rule =whitespace_rule(patch->new_name2068? patch->new_name2069: patch->old_name);20702071 patchsize =parse_single_patch(state,2072 buffer + offset + hdrsize,2073 size - offset - hdrsize,2074 patch);20752076if(!patchsize) {2077static const char git_binary[] ="GIT binary patch\n";2078int hd = hdrsize + offset;2079unsigned long llen =linelen(buffer + hd, size - hd);20802081if(llen ==sizeof(git_binary) -1&&2082!memcmp(git_binary, buffer + hd, llen)) {2083int used;2084 state_linenr++;2085 used =parse_binary(buffer + hd + llen,2086 size - hd - llen, patch);2087if(used <0)2088return-1;2089if(used)2090 patchsize = used + llen;2091else2092 patchsize =0;2093}2094else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2095static const char*binhdr[] = {2096"Binary files ",2097"Files ",2098 NULL,2099};2100int i;2101for(i =0; binhdr[i]; i++) {2102int len =strlen(binhdr[i]);2103if(len < size - hd &&2104!memcmp(binhdr[i], buffer + hd, len)) {2105 state_linenr++;2106 patch->is_binary =1;2107 patchsize = llen;2108break;2109}2110}2111}21122113/* Empty patch cannot be applied if it is a text patch2114 * without metadata change. A binary patch appears2115 * empty to us here.2116 */2117if((state->apply || state->check) &&2118(!patch->is_binary && !metadata_changes(patch)))2119die(_("patch with only garbage at line%d"), state_linenr);2120}21212122return offset + hdrsize + patchsize;2123}21242125#define swap(a,b) myswap((a),(b),sizeof(a))21262127#define myswap(a, b, size) do { \2128 unsigned char mytmp[size]; \2129 memcpy(mytmp, &a, size); \2130 memcpy(&a, &b, size); \2131 memcpy(&b, mytmp, size); \2132} while (0)21332134static voidreverse_patches(struct patch *p)2135{2136for(; p; p = p->next) {2137struct fragment *frag = p->fragments;21382139swap(p->new_name, p->old_name);2140swap(p->new_mode, p->old_mode);2141swap(p->is_new, p->is_delete);2142swap(p->lines_added, p->lines_deleted);2143swap(p->old_sha1_prefix, p->new_sha1_prefix);21442145for(; frag; frag = frag->next) {2146swap(frag->newpos, frag->oldpos);2147swap(frag->newlines, frag->oldlines);2148}2149}2150}21512152static const char pluses[] =2153"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2154static const char minuses[]=2155"----------------------------------------------------------------------";21562157static voidshow_stats(struct patch *patch)2158{2159struct strbuf qname = STRBUF_INIT;2160char*cp = patch->new_name ? patch->new_name : patch->old_name;2161int max, add, del;21622163quote_c_style(cp, &qname, NULL,0);21642165/*2166 * "scale" the filename2167 */2168 max = max_len;2169if(max >50)2170 max =50;21712172if(qname.len > max) {2173 cp =strchr(qname.buf + qname.len +3- max,'/');2174if(!cp)2175 cp = qname.buf + qname.len +3- max;2176strbuf_splice(&qname,0, cp - qname.buf,"...",3);2177}21782179if(patch->is_binary) {2180printf(" %-*s | Bin\n", max, qname.buf);2181strbuf_release(&qname);2182return;2183}21842185printf(" %-*s |", max, qname.buf);2186strbuf_release(&qname);21872188/*2189 * scale the add/delete2190 */2191 max = max + max_change >70?70- max : max_change;2192 add = patch->lines_added;2193 del = patch->lines_deleted;21942195if(max_change >0) {2196int total = ((add + del) * max + max_change /2) / max_change;2197 add = (add * max + max_change /2) / max_change;2198 del = total - add;2199}2200printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2201 add, pluses, del, minuses);2202}22032204static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2205{2206switch(st->st_mode & S_IFMT) {2207case S_IFLNK:2208if(strbuf_readlink(buf, path, st->st_size) <0)2209returnerror(_("unable to read symlink%s"), path);2210return0;2211case S_IFREG:2212if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2213returnerror(_("unable to open or read%s"), path);2214convert_to_git(path, buf->buf, buf->len, buf,0);2215return0;2216default:2217return-1;2218}2219}22202221/*2222 * Update the preimage, and the common lines in postimage,2223 * from buffer buf of length len. If postlen is 0 the postimage2224 * is updated in place, otherwise it's updated on a new buffer2225 * of length postlen2226 */22272228static voidupdate_pre_post_images(struct image *preimage,2229struct image *postimage,2230char*buf,2231size_t len,size_t postlen)2232{2233int i, ctx, reduced;2234char*new, *old, *fixed;2235struct image fixed_preimage;22362237/*2238 * Update the preimage with whitespace fixes. Note that we2239 * are not losing preimage->buf -- apply_one_fragment() will2240 * free "oldlines".2241 */2242prepare_image(&fixed_preimage, buf, len,1);2243assert(postlen2244? fixed_preimage.nr == preimage->nr2245: fixed_preimage.nr <= preimage->nr);2246for(i =0; i < fixed_preimage.nr; i++)2247 fixed_preimage.line[i].flag = preimage->line[i].flag;2248free(preimage->line_allocated);2249*preimage = fixed_preimage;22502251/*2252 * Adjust the common context lines in postimage. This can be2253 * done in-place when we are shrinking it with whitespace2254 * fixing, but needs a new buffer when ignoring whitespace or2255 * expanding leading tabs to spaces.2256 *2257 * We trust the caller to tell us if the update can be done2258 * in place (postlen==0) or not.2259 */2260 old = postimage->buf;2261if(postlen)2262new= postimage->buf =xmalloc(postlen);2263else2264new= old;2265 fixed = preimage->buf;22662267for(i = reduced = ctx =0; i < postimage->nr; i++) {2268size_t l_len = postimage->line[i].len;2269if(!(postimage->line[i].flag & LINE_COMMON)) {2270/* an added line -- no counterparts in preimage */2271memmove(new, old, l_len);2272 old += l_len;2273new+= l_len;2274continue;2275}22762277/* a common context -- skip it in the original postimage */2278 old += l_len;22792280/* and find the corresponding one in the fixed preimage */2281while(ctx < preimage->nr &&2282!(preimage->line[ctx].flag & LINE_COMMON)) {2283 fixed += preimage->line[ctx].len;2284 ctx++;2285}22862287/*2288 * preimage is expected to run out, if the caller2289 * fixed addition of trailing blank lines.2290 */2291if(preimage->nr <= ctx) {2292 reduced++;2293continue;2294}22952296/* and copy it in, while fixing the line length */2297 l_len = preimage->line[ctx].len;2298memcpy(new, fixed, l_len);2299new+= l_len;2300 fixed += l_len;2301 postimage->line[i].len = l_len;2302 ctx++;2303}23042305if(postlen2306? postlen <new- postimage->buf2307: postimage->len <new- postimage->buf)2308die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2309(int)postlen, (int) postimage->len, (int)(new- postimage->buf));23102311/* Fix the length of the whole thing */2312 postimage->len =new- postimage->buf;2313 postimage->nr -= reduced;2314}23152316static intline_by_line_fuzzy_match(struct image *img,2317struct image *preimage,2318struct image *postimage,2319unsigned longtry,2320int try_lno,2321int preimage_limit)2322{2323int i;2324size_t imgoff =0;2325size_t preoff =0;2326size_t postlen = postimage->len;2327size_t extra_chars;2328char*buf;2329char*preimage_eof;2330char*preimage_end;2331struct strbuf fixed;2332char*fixed_buf;2333size_t fixed_len;23342335for(i =0; i < preimage_limit; i++) {2336size_t prelen = preimage->line[i].len;2337size_t imglen = img->line[try_lno+i].len;23382339if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2340 preimage->buf + preoff, prelen))2341return0;2342if(preimage->line[i].flag & LINE_COMMON)2343 postlen += imglen - prelen;2344 imgoff += imglen;2345 preoff += prelen;2346}23472348/*2349 * Ok, the preimage matches with whitespace fuzz.2350 *2351 * imgoff now holds the true length of the target that2352 * matches the preimage before the end of the file.2353 *2354 * Count the number of characters in the preimage that fall2355 * beyond the end of the file and make sure that all of them2356 * are whitespace characters. (This can only happen if2357 * we are removing blank lines at the end of the file.)2358 */2359 buf = preimage_eof = preimage->buf + preoff;2360for( ; i < preimage->nr; i++)2361 preoff += preimage->line[i].len;2362 preimage_end = preimage->buf + preoff;2363for( ; buf < preimage_end; buf++)2364if(!isspace(*buf))2365return0;23662367/*2368 * Update the preimage and the common postimage context2369 * lines to use the same whitespace as the target.2370 * If whitespace is missing in the target (i.e.2371 * if the preimage extends beyond the end of the file),2372 * use the whitespace from the preimage.2373 */2374 extra_chars = preimage_end - preimage_eof;2375strbuf_init(&fixed, imgoff + extra_chars);2376strbuf_add(&fixed, img->buf +try, imgoff);2377strbuf_add(&fixed, preimage_eof, extra_chars);2378 fixed_buf =strbuf_detach(&fixed, &fixed_len);2379update_pre_post_images(preimage, postimage,2380 fixed_buf, fixed_len, postlen);2381return1;2382}23832384static intmatch_fragment(struct image *img,2385struct image *preimage,2386struct image *postimage,2387unsigned longtry,2388int try_lno,2389unsigned ws_rule,2390int match_beginning,int match_end)2391{2392int i;2393char*fixed_buf, *buf, *orig, *target;2394struct strbuf fixed;2395size_t fixed_len, postlen;2396int preimage_limit;23972398if(preimage->nr + try_lno <= img->nr) {2399/*2400 * The hunk falls within the boundaries of img.2401 */2402 preimage_limit = preimage->nr;2403if(match_end && (preimage->nr + try_lno != img->nr))2404return0;2405}else if(ws_error_action == correct_ws_error &&2406(ws_rule & WS_BLANK_AT_EOF)) {2407/*2408 * This hunk extends beyond the end of img, and we are2409 * removing blank lines at the end of the file. This2410 * many lines from the beginning of the preimage must2411 * match with img, and the remainder of the preimage2412 * must be blank.2413 */2414 preimage_limit = img->nr - try_lno;2415}else{2416/*2417 * The hunk extends beyond the end of the img and2418 * we are not removing blanks at the end, so we2419 * should reject the hunk at this position.2420 */2421return0;2422}24232424if(match_beginning && try_lno)2425return0;24262427/* Quick hash check */2428for(i =0; i < preimage_limit; i++)2429if((img->line[try_lno + i].flag & LINE_PATCHED) ||2430(preimage->line[i].hash != img->line[try_lno + i].hash))2431return0;24322433if(preimage_limit == preimage->nr) {2434/*2435 * Do we have an exact match? If we were told to match2436 * at the end, size must be exactly at try+fragsize,2437 * otherwise try+fragsize must be still within the preimage,2438 * and either case, the old piece should match the preimage2439 * exactly.2440 */2441if((match_end2442? (try+ preimage->len == img->len)2443: (try+ preimage->len <= img->len)) &&2444!memcmp(img->buf +try, preimage->buf, preimage->len))2445return1;2446}else{2447/*2448 * The preimage extends beyond the end of img, so2449 * there cannot be an exact match.2450 *2451 * There must be one non-blank context line that match2452 * a line before the end of img.2453 */2454char*buf_end;24552456 buf = preimage->buf;2457 buf_end = buf;2458for(i =0; i < preimage_limit; i++)2459 buf_end += preimage->line[i].len;24602461for( ; buf < buf_end; buf++)2462if(!isspace(*buf))2463break;2464if(buf == buf_end)2465return0;2466}24672468/*2469 * No exact match. If we are ignoring whitespace, run a line-by-line2470 * fuzzy matching. We collect all the line length information because2471 * we need it to adjust whitespace if we match.2472 */2473if(ws_ignore_action == ignore_ws_change)2474returnline_by_line_fuzzy_match(img, preimage, postimage,2475try, try_lno, preimage_limit);24762477if(ws_error_action != correct_ws_error)2478return0;24792480/*2481 * The hunk does not apply byte-by-byte, but the hash says2482 * it might with whitespace fuzz. We weren't asked to2483 * ignore whitespace, we were asked to correct whitespace2484 * errors, so let's try matching after whitespace correction.2485 *2486 * While checking the preimage against the target, whitespace2487 * errors in both fixed, we count how large the corresponding2488 * postimage needs to be. The postimage prepared by2489 * apply_one_fragment() has whitespace errors fixed on added2490 * lines already, but the common lines were propagated as-is,2491 * which may become longer when their whitespace errors are2492 * fixed.2493 */24942495/* First count added lines in postimage */2496 postlen =0;2497for(i =0; i < postimage->nr; i++) {2498if(!(postimage->line[i].flag & LINE_COMMON))2499 postlen += postimage->line[i].len;2500}25012502/*2503 * The preimage may extend beyond the end of the file,2504 * but in this loop we will only handle the part of the2505 * preimage that falls within the file.2506 */2507strbuf_init(&fixed, preimage->len +1);2508 orig = preimage->buf;2509 target = img->buf +try;2510for(i =0; i < preimage_limit; i++) {2511size_t oldlen = preimage->line[i].len;2512size_t tgtlen = img->line[try_lno + i].len;2513size_t fixstart = fixed.len;2514struct strbuf tgtfix;2515int match;25162517/* Try fixing the line in the preimage */2518ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25192520/* Try fixing the line in the target */2521strbuf_init(&tgtfix, tgtlen);2522ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);25232524/*2525 * If they match, either the preimage was based on2526 * a version before our tree fixed whitespace breakage,2527 * or we are lacking a whitespace-fix patch the tree2528 * the preimage was based on already had (i.e. target2529 * has whitespace breakage, the preimage doesn't).2530 * In either case, we are fixing the whitespace breakages2531 * so we might as well take the fix together with their2532 * real change.2533 */2534 match = (tgtfix.len == fixed.len - fixstart &&2535!memcmp(tgtfix.buf, fixed.buf + fixstart,2536 fixed.len - fixstart));25372538/* Add the length if this is common with the postimage */2539if(preimage->line[i].flag & LINE_COMMON)2540 postlen += tgtfix.len;25412542strbuf_release(&tgtfix);2543if(!match)2544goto unmatch_exit;25452546 orig += oldlen;2547 target += tgtlen;2548}254925502551/*2552 * Now handle the lines in the preimage that falls beyond the2553 * end of the file (if any). They will only match if they are2554 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2555 * false).2556 */2557for( ; i < preimage->nr; i++) {2558size_t fixstart = fixed.len;/* start of the fixed preimage */2559size_t oldlen = preimage->line[i].len;2560int j;25612562/* Try fixing the line in the preimage */2563ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25642565for(j = fixstart; j < fixed.len; j++)2566if(!isspace(fixed.buf[j]))2567goto unmatch_exit;25682569 orig += oldlen;2570}25712572/*2573 * Yes, the preimage is based on an older version that still2574 * has whitespace breakages unfixed, and fixing them makes the2575 * hunk match. Update the context lines in the postimage.2576 */2577 fixed_buf =strbuf_detach(&fixed, &fixed_len);2578if(postlen < postimage->len)2579 postlen =0;2580update_pre_post_images(preimage, postimage,2581 fixed_buf, fixed_len, postlen);2582return1;25832584 unmatch_exit:2585strbuf_release(&fixed);2586return0;2587}25882589static intfind_pos(struct image *img,2590struct image *preimage,2591struct image *postimage,2592int line,2593unsigned ws_rule,2594int match_beginning,int match_end)2595{2596int i;2597unsigned long backwards, forwards,try;2598int backwards_lno, forwards_lno, try_lno;25992600/*2601 * If match_beginning or match_end is specified, there is no2602 * point starting from a wrong line that will never match and2603 * wander around and wait for a match at the specified end.2604 */2605if(match_beginning)2606 line =0;2607else if(match_end)2608 line = img->nr - preimage->nr;26092610/*2611 * Because the comparison is unsigned, the following test2612 * will also take care of a negative line number that can2613 * result when match_end and preimage is larger than the target.2614 */2615if((size_t) line > img->nr)2616 line = img->nr;26172618try=0;2619for(i =0; i < line; i++)2620try+= img->line[i].len;26212622/*2623 * There's probably some smart way to do this, but I'll leave2624 * that to the smart and beautiful people. I'm simple and stupid.2625 */2626 backwards =try;2627 backwards_lno = line;2628 forwards =try;2629 forwards_lno = line;2630 try_lno = line;26312632for(i =0; ; i++) {2633if(match_fragment(img, preimage, postimage,2634try, try_lno, ws_rule,2635 match_beginning, match_end))2636return try_lno;26372638 again:2639if(backwards_lno ==0&& forwards_lno == img->nr)2640break;26412642if(i &1) {2643if(backwards_lno ==0) {2644 i++;2645goto again;2646}2647 backwards_lno--;2648 backwards -= img->line[backwards_lno].len;2649try= backwards;2650 try_lno = backwards_lno;2651}else{2652if(forwards_lno == img->nr) {2653 i++;2654goto again;2655}2656 forwards += img->line[forwards_lno].len;2657 forwards_lno++;2658try= forwards;2659 try_lno = forwards_lno;2660}26612662}2663return-1;2664}26652666static voidremove_first_line(struct image *img)2667{2668 img->buf += img->line[0].len;2669 img->len -= img->line[0].len;2670 img->line++;2671 img->nr--;2672}26732674static voidremove_last_line(struct image *img)2675{2676 img->len -= img->line[--img->nr].len;2677}26782679/*2680 * The change from "preimage" and "postimage" has been found to2681 * apply at applied_pos (counts in line numbers) in "img".2682 * Update "img" to remove "preimage" and replace it with "postimage".2683 */2684static voidupdate_image(struct apply_state *state,2685struct image *img,2686int applied_pos,2687struct image *preimage,2688struct image *postimage)2689{2690/*2691 * remove the copy of preimage at offset in img2692 * and replace it with postimage2693 */2694int i, nr;2695size_t remove_count, insert_count, applied_at =0;2696char*result;2697int preimage_limit;26982699/*2700 * If we are removing blank lines at the end of img,2701 * the preimage may extend beyond the end.2702 * If that is the case, we must be careful only to2703 * remove the part of the preimage that falls within2704 * the boundaries of img. Initialize preimage_limit2705 * to the number of lines in the preimage that falls2706 * within the boundaries.2707 */2708 preimage_limit = preimage->nr;2709if(preimage_limit > img->nr - applied_pos)2710 preimage_limit = img->nr - applied_pos;27112712for(i =0; i < applied_pos; i++)2713 applied_at += img->line[i].len;27142715 remove_count =0;2716for(i =0; i < preimage_limit; i++)2717 remove_count += img->line[applied_pos + i].len;2718 insert_count = postimage->len;27192720/* Adjust the contents */2721 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2722memcpy(result, img->buf, applied_at);2723memcpy(result + applied_at, postimage->buf, postimage->len);2724memcpy(result + applied_at + postimage->len,2725 img->buf + (applied_at + remove_count),2726 img->len - (applied_at + remove_count));2727free(img->buf);2728 img->buf = result;2729 img->len += insert_count - remove_count;2730 result[img->len] ='\0';27312732/* Adjust the line table */2733 nr = img->nr + postimage->nr - preimage_limit;2734if(preimage_limit < postimage->nr) {2735/*2736 * NOTE: this knows that we never call remove_first_line()2737 * on anything other than pre/post image.2738 */2739REALLOC_ARRAY(img->line, nr);2740 img->line_allocated = img->line;2741}2742if(preimage_limit != postimage->nr)2743memmove(img->line + applied_pos + postimage->nr,2744 img->line + applied_pos + preimage_limit,2745(img->nr - (applied_pos + preimage_limit)) *2746sizeof(*img->line));2747memcpy(img->line + applied_pos,2748 postimage->line,2749 postimage->nr *sizeof(*img->line));2750if(!state->allow_overlap)2751for(i =0; i < postimage->nr; i++)2752 img->line[applied_pos + i].flag |= LINE_PATCHED;2753 img->nr = nr;2754}27552756/*2757 * Use the patch-hunk text in "frag" to prepare two images (preimage and2758 * postimage) for the hunk. Find lines that match "preimage" in "img" and2759 * replace the part of "img" with "postimage" text.2760 */2761static intapply_one_fragment(struct apply_state *state,2762struct image *img,struct fragment *frag,2763int inaccurate_eof,unsigned ws_rule,2764int nth_fragment)2765{2766int match_beginning, match_end;2767const char*patch = frag->patch;2768int size = frag->size;2769char*old, *oldlines;2770struct strbuf newlines;2771int new_blank_lines_at_end =0;2772int found_new_blank_lines_at_end =0;2773int hunk_linenr = frag->linenr;2774unsigned long leading, trailing;2775int pos, applied_pos;2776struct image preimage;2777struct image postimage;27782779memset(&preimage,0,sizeof(preimage));2780memset(&postimage,0,sizeof(postimage));2781 oldlines =xmalloc(size);2782strbuf_init(&newlines, size);27832784 old = oldlines;2785while(size >0) {2786char first;2787int len =linelen(patch, size);2788int plen;2789int added_blank_line =0;2790int is_blank_context =0;2791size_t start;27922793if(!len)2794break;27952796/*2797 * "plen" is how much of the line we should use for2798 * the actual patch data. Normally we just remove the2799 * first character on the line, but if the line is2800 * followed by "\ No newline", then we also remove the2801 * last one (which is the newline, of course).2802 */2803 plen = len -1;2804if(len < size && patch[len] =='\\')2805 plen--;2806 first = *patch;2807if(state->apply_in_reverse) {2808if(first =='-')2809 first ='+';2810else if(first =='+')2811 first ='-';2812}28132814switch(first) {2815case'\n':2816/* Newer GNU diff, empty context line */2817if(plen <0)2818/* ... followed by '\No newline'; nothing */2819break;2820*old++ ='\n';2821strbuf_addch(&newlines,'\n');2822add_line_info(&preimage,"\n",1, LINE_COMMON);2823add_line_info(&postimage,"\n",1, LINE_COMMON);2824 is_blank_context =1;2825break;2826case' ':2827if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2828ws_blank_line(patch +1, plen, ws_rule))2829 is_blank_context =1;2830case'-':2831memcpy(old, patch +1, plen);2832add_line_info(&preimage, old, plen,2833(first ==' '? LINE_COMMON :0));2834 old += plen;2835if(first =='-')2836break;2837/* Fall-through for ' ' */2838case'+':2839/* --no-add does not add new lines */2840if(first =='+'&& state->no_add)2841break;28422843 start = newlines.len;2844if(first !='+'||2845!whitespace_error ||2846 ws_error_action != correct_ws_error) {2847strbuf_add(&newlines, patch +1, plen);2848}2849else{2850ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2851}2852add_line_info(&postimage, newlines.buf + start, newlines.len - start,2853(first =='+'?0: LINE_COMMON));2854if(first =='+'&&2855(ws_rule & WS_BLANK_AT_EOF) &&2856ws_blank_line(patch +1, plen, ws_rule))2857 added_blank_line =1;2858break;2859case'@':case'\\':2860/* Ignore it, we already handled it */2861break;2862default:2863if(state->apply_verbosely)2864error(_("invalid start of line: '%c'"), first);2865 applied_pos = -1;2866goto out;2867}2868if(added_blank_line) {2869if(!new_blank_lines_at_end)2870 found_new_blank_lines_at_end = hunk_linenr;2871 new_blank_lines_at_end++;2872}2873else if(is_blank_context)2874;2875else2876 new_blank_lines_at_end =0;2877 patch += len;2878 size -= len;2879 hunk_linenr++;2880}2881if(inaccurate_eof &&2882 old > oldlines && old[-1] =='\n'&&2883 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2884 old--;2885strbuf_setlen(&newlines, newlines.len -1);2886}28872888 leading = frag->leading;2889 trailing = frag->trailing;28902891/*2892 * A hunk to change lines at the beginning would begin with2893 * @@ -1,L +N,M @@2894 * but we need to be careful. -U0 that inserts before the second2895 * line also has this pattern.2896 *2897 * And a hunk to add to an empty file would begin with2898 * @@ -0,0 +N,M @@2899 *2900 * In other words, a hunk that is (frag->oldpos <= 1) with or2901 * without leading context must match at the beginning.2902 */2903 match_beginning = (!frag->oldpos ||2904(frag->oldpos ==1&& !state->unidiff_zero));29052906/*2907 * A hunk without trailing lines must match at the end.2908 * However, we simply cannot tell if a hunk must match end2909 * from the lack of trailing lines if the patch was generated2910 * with unidiff without any context.2911 */2912 match_end = !state->unidiff_zero && !trailing;29132914 pos = frag->newpos ? (frag->newpos -1) :0;2915 preimage.buf = oldlines;2916 preimage.len = old - oldlines;2917 postimage.buf = newlines.buf;2918 postimage.len = newlines.len;2919 preimage.line = preimage.line_allocated;2920 postimage.line = postimage.line_allocated;29212922for(;;) {29232924 applied_pos =find_pos(img, &preimage, &postimage, pos,2925 ws_rule, match_beginning, match_end);29262927if(applied_pos >=0)2928break;29292930/* Am I at my context limits? */2931if((leading <= state->p_context) && (trailing <= state->p_context))2932break;2933if(match_beginning || match_end) {2934 match_beginning = match_end =0;2935continue;2936}29372938/*2939 * Reduce the number of context lines; reduce both2940 * leading and trailing if they are equal otherwise2941 * just reduce the larger context.2942 */2943if(leading >= trailing) {2944remove_first_line(&preimage);2945remove_first_line(&postimage);2946 pos--;2947 leading--;2948}2949if(trailing > leading) {2950remove_last_line(&preimage);2951remove_last_line(&postimage);2952 trailing--;2953}2954}29552956if(applied_pos >=0) {2957if(new_blank_lines_at_end &&2958 preimage.nr + applied_pos >= img->nr &&2959(ws_rule & WS_BLANK_AT_EOF) &&2960 ws_error_action != nowarn_ws_error) {2961record_ws_error(state, WS_BLANK_AT_EOF,"+",1,2962 found_new_blank_lines_at_end);2963if(ws_error_action == correct_ws_error) {2964while(new_blank_lines_at_end--)2965remove_last_line(&postimage);2966}2967/*2968 * We would want to prevent write_out_results()2969 * from taking place in apply_patch() that follows2970 * the callchain led us here, which is:2971 * apply_patch->check_patch_list->check_patch->2972 * apply_data->apply_fragments->apply_one_fragment2973 */2974if(ws_error_action == die_on_ws_error)2975 state->apply =0;2976}29772978if(state->apply_verbosely && applied_pos != pos) {2979int offset = applied_pos - pos;2980if(state->apply_in_reverse)2981 offset =0- offset;2982fprintf_ln(stderr,2983Q_("Hunk #%dsucceeded at%d(offset%dline).",2984"Hunk #%dsucceeded at%d(offset%dlines).",2985 offset),2986 nth_fragment, applied_pos +1, offset);2987}29882989/*2990 * Warn if it was necessary to reduce the number2991 * of context lines.2992 */2993if((leading != frag->leading) ||2994(trailing != frag->trailing))2995fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2996" to apply fragment at%d"),2997 leading, trailing, applied_pos+1);2998update_image(state, img, applied_pos, &preimage, &postimage);2999}else{3000if(state->apply_verbosely)3001error(_("while searching for:\n%.*s"),3002(int)(old - oldlines), oldlines);3003}30043005out:3006free(oldlines);3007strbuf_release(&newlines);3008free(preimage.line_allocated);3009free(postimage.line_allocated);30103011return(applied_pos <0);3012}30133014static intapply_binary_fragment(struct apply_state *state,3015struct image *img,3016struct patch *patch)3017{3018struct fragment *fragment = patch->fragments;3019unsigned long len;3020void*dst;30213022if(!fragment)3023returnerror(_("missing binary patch data for '%s'"),3024 patch->new_name ?3025 patch->new_name :3026 patch->old_name);30273028/* Binary patch is irreversible without the optional second hunk */3029if(state->apply_in_reverse) {3030if(!fragment->next)3031returnerror("cannot reverse-apply a binary patch "3032"without the reverse hunk to '%s'",3033 patch->new_name3034? patch->new_name : patch->old_name);3035 fragment = fragment->next;3036}3037switch(fragment->binary_patch_method) {3038case BINARY_DELTA_DEFLATED:3039 dst =patch_delta(img->buf, img->len, fragment->patch,3040 fragment->size, &len);3041if(!dst)3042return-1;3043clear_image(img);3044 img->buf = dst;3045 img->len = len;3046return0;3047case BINARY_LITERAL_DEFLATED:3048clear_image(img);3049 img->len = fragment->size;3050 img->buf =xmemdupz(fragment->patch, img->len);3051return0;3052}3053return-1;3054}30553056/*3057 * Replace "img" with the result of applying the binary patch.3058 * The binary patch data itself in patch->fragment is still kept3059 * but the preimage prepared by the caller in "img" is freed here3060 * or in the helper function apply_binary_fragment() this calls.3061 */3062static intapply_binary(struct apply_state *state,3063struct image *img,3064struct patch *patch)3065{3066const char*name = patch->old_name ? patch->old_name : patch->new_name;3067unsigned char sha1[20];30683069/*3070 * For safety, we require patch index line to contain3071 * full 40-byte textual SHA1 for old and new, at least for now.3072 */3073if(strlen(patch->old_sha1_prefix) !=40||3074strlen(patch->new_sha1_prefix) !=40||3075get_sha1_hex(patch->old_sha1_prefix, sha1) ||3076get_sha1_hex(patch->new_sha1_prefix, sha1))3077returnerror("cannot apply binary patch to '%s' "3078"without full index line", name);30793080if(patch->old_name) {3081/*3082 * See if the old one matches what the patch3083 * applies to.3084 */3085hash_sha1_file(img->buf, img->len, blob_type, sha1);3086if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3087returnerror("the patch applies to '%s' (%s), "3088"which does not match the "3089"current contents.",3090 name,sha1_to_hex(sha1));3091}3092else{3093/* Otherwise, the old one must be empty. */3094if(img->len)3095returnerror("the patch applies to an empty "3096"'%s' but it is not empty", name);3097}30983099get_sha1_hex(patch->new_sha1_prefix, sha1);3100if(is_null_sha1(sha1)) {3101clear_image(img);3102return0;/* deletion patch */3103}31043105if(has_sha1_file(sha1)) {3106/* We already have the postimage */3107enum object_type type;3108unsigned long size;3109char*result;31103111 result =read_sha1_file(sha1, &type, &size);3112if(!result)3113returnerror("the necessary postimage%sfor "3114"'%s' cannot be read",3115 patch->new_sha1_prefix, name);3116clear_image(img);3117 img->buf = result;3118 img->len = size;3119}else{3120/*3121 * We have verified buf matches the preimage;3122 * apply the patch data to it, which is stored3123 * in the patch->fragments->{patch,size}.3124 */3125if(apply_binary_fragment(state, img, patch))3126returnerror(_("binary patch does not apply to '%s'"),3127 name);31283129/* verify that the result matches */3130hash_sha1_file(img->buf, img->len, blob_type, sha1);3131if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3132returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3133 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3134}31353136return0;3137}31383139static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3140{3141struct fragment *frag = patch->fragments;3142const char*name = patch->old_name ? patch->old_name : patch->new_name;3143unsigned ws_rule = patch->ws_rule;3144unsigned inaccurate_eof = patch->inaccurate_eof;3145int nth =0;31463147if(patch->is_binary)3148returnapply_binary(state, img, patch);31493150while(frag) {3151 nth++;3152if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3153error(_("patch failed:%s:%ld"), name, frag->oldpos);3154if(!state->apply_with_reject)3155return-1;3156 frag->rejected =1;3157}3158 frag = frag->next;3159}3160return0;3161}31623163static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3164{3165if(S_ISGITLINK(mode)) {3166strbuf_grow(buf,100);3167strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3168}else{3169enum object_type type;3170unsigned long sz;3171char*result;31723173 result =read_sha1_file(sha1, &type, &sz);3174if(!result)3175return-1;3176/* XXX read_sha1_file NUL-terminates */3177strbuf_attach(buf, result, sz, sz +1);3178}3179return0;3180}31813182static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3183{3184if(!ce)3185return0;3186returnread_blob_object(buf, ce->sha1, ce->ce_mode);3187}31883189static struct patch *in_fn_table(const char*name)3190{3191struct string_list_item *item;31923193if(name == NULL)3194return NULL;31953196 item =string_list_lookup(&fn_table, name);3197if(item != NULL)3198return(struct patch *)item->util;31993200return NULL;3201}32023203/*3204 * item->util in the filename table records the status of the path.3205 * Usually it points at a patch (whose result records the contents3206 * of it after applying it), but it could be PATH_WAS_DELETED for a3207 * path that a previously applied patch has already removed, or3208 * PATH_TO_BE_DELETED for a path that a later patch would remove.3209 *3210 * The latter is needed to deal with a case where two paths A and B3211 * are swapped by first renaming A to B and then renaming B to A;3212 * moving A to B should not be prevented due to presence of B as we3213 * will remove it in a later patch.3214 */3215#define PATH_TO_BE_DELETED ((struct patch *) -2)3216#define PATH_WAS_DELETED ((struct patch *) -1)32173218static intto_be_deleted(struct patch *patch)3219{3220return patch == PATH_TO_BE_DELETED;3221}32223223static intwas_deleted(struct patch *patch)3224{3225return patch == PATH_WAS_DELETED;3226}32273228static voidadd_to_fn_table(struct patch *patch)3229{3230struct string_list_item *item;32313232/*3233 * Always add new_name unless patch is a deletion3234 * This should cover the cases for normal diffs,3235 * file creations and copies3236 */3237if(patch->new_name != NULL) {3238 item =string_list_insert(&fn_table, patch->new_name);3239 item->util = patch;3240}32413242/*3243 * store a failure on rename/deletion cases because3244 * later chunks shouldn't patch old names3245 */3246if((patch->new_name == NULL) || (patch->is_rename)) {3247 item =string_list_insert(&fn_table, patch->old_name);3248 item->util = PATH_WAS_DELETED;3249}3250}32513252static voidprepare_fn_table(struct patch *patch)3253{3254/*3255 * store information about incoming file deletion3256 */3257while(patch) {3258if((patch->new_name == NULL) || (patch->is_rename)) {3259struct string_list_item *item;3260 item =string_list_insert(&fn_table, patch->old_name);3261 item->util = PATH_TO_BE_DELETED;3262}3263 patch = patch->next;3264}3265}32663267static intcheckout_target(struct index_state *istate,3268struct cache_entry *ce,struct stat *st)3269{3270struct checkout costate;32713272memset(&costate,0,sizeof(costate));3273 costate.base_dir ="";3274 costate.refresh_cache =1;3275 costate.istate = istate;3276if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3277returnerror(_("cannot checkout%s"), ce->name);3278return0;3279}32803281static struct patch *previous_patch(struct patch *patch,int*gone)3282{3283struct patch *previous;32843285*gone =0;3286if(patch->is_copy || patch->is_rename)3287return NULL;/* "git" patches do not depend on the order */32883289 previous =in_fn_table(patch->old_name);3290if(!previous)3291return NULL;32923293if(to_be_deleted(previous))3294return NULL;/* the deletion hasn't happened yet */32953296if(was_deleted(previous))3297*gone =1;32983299return previous;3300}33013302static intverify_index_match(const struct cache_entry *ce,struct stat *st)3303{3304if(S_ISGITLINK(ce->ce_mode)) {3305if(!S_ISDIR(st->st_mode))3306return-1;3307return0;3308}3309returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3310}33113312#define SUBMODULE_PATCH_WITHOUT_INDEX 133133314static intload_patch_target(struct apply_state *state,3315struct strbuf *buf,3316const struct cache_entry *ce,3317struct stat *st,3318const char*name,3319unsigned expected_mode)3320{3321if(state->cached || state->check_index) {3322if(read_file_or_gitlink(ce, buf))3323returnerror(_("read of%sfailed"), name);3324}else if(name) {3325if(S_ISGITLINK(expected_mode)) {3326if(ce)3327returnread_file_or_gitlink(ce, buf);3328else3329return SUBMODULE_PATCH_WITHOUT_INDEX;3330}else if(has_symlink_leading_path(name,strlen(name))) {3331returnerror(_("reading from '%s' beyond a symbolic link"), name);3332}else{3333if(read_old_data(st, name, buf))3334returnerror(_("read of%sfailed"), name);3335}3336}3337return0;3338}33393340/*3341 * We are about to apply "patch"; populate the "image" with the3342 * current version we have, from the working tree or from the index,3343 * depending on the situation e.g. --cached/--index. If we are3344 * applying a non-git patch that incrementally updates the tree,3345 * we read from the result of a previous diff.3346 */3347static intload_preimage(struct apply_state *state,3348struct image *image,3349struct patch *patch,struct stat *st,3350const struct cache_entry *ce)3351{3352struct strbuf buf = STRBUF_INIT;3353size_t len;3354char*img;3355struct patch *previous;3356int status;33573358 previous =previous_patch(patch, &status);3359if(status)3360returnerror(_("path%shas been renamed/deleted"),3361 patch->old_name);3362if(previous) {3363/* We have a patched copy in memory; use that. */3364strbuf_add(&buf, previous->result, previous->resultsize);3365}else{3366 status =load_patch_target(state, &buf, ce, st,3367 patch->old_name, patch->old_mode);3368if(status <0)3369return status;3370else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3371/*3372 * There is no way to apply subproject3373 * patch without looking at the index.3374 * NEEDSWORK: shouldn't this be flagged3375 * as an error???3376 */3377free_fragment_list(patch->fragments);3378 patch->fragments = NULL;3379}else if(status) {3380returnerror(_("read of%sfailed"), patch->old_name);3381}3382}33833384 img =strbuf_detach(&buf, &len);3385prepare_image(image, img, len, !patch->is_binary);3386return0;3387}33883389static intthree_way_merge(struct image *image,3390char*path,3391const unsigned char*base,3392const unsigned char*ours,3393const unsigned char*theirs)3394{3395 mmfile_t base_file, our_file, their_file;3396 mmbuffer_t result = { NULL };3397int status;33983399read_mmblob(&base_file, base);3400read_mmblob(&our_file, ours);3401read_mmblob(&their_file, theirs);3402 status =ll_merge(&result, path,3403&base_file,"base",3404&our_file,"ours",3405&their_file,"theirs", NULL);3406free(base_file.ptr);3407free(our_file.ptr);3408free(their_file.ptr);3409if(status <0|| !result.ptr) {3410free(result.ptr);3411return-1;3412}3413clear_image(image);3414 image->buf = result.ptr;3415 image->len = result.size;34163417return status;3418}34193420/*3421 * When directly falling back to add/add three-way merge, we read from3422 * the current contents of the new_name. In no cases other than that3423 * this function will be called.3424 */3425static intload_current(struct apply_state *state,3426struct image *image,3427struct patch *patch)3428{3429struct strbuf buf = STRBUF_INIT;3430int status, pos;3431size_t len;3432char*img;3433struct stat st;3434struct cache_entry *ce;3435char*name = patch->new_name;3436unsigned mode = patch->new_mode;34373438if(!patch->is_new)3439die("BUG: patch to%sis not a creation", patch->old_name);34403441 pos =cache_name_pos(name,strlen(name));3442if(pos <0)3443returnerror(_("%s: does not exist in index"), name);3444 ce = active_cache[pos];3445if(lstat(name, &st)) {3446if(errno != ENOENT)3447returnerror(_("%s:%s"), name,strerror(errno));3448if(checkout_target(&the_index, ce, &st))3449return-1;3450}3451if(verify_index_match(ce, &st))3452returnerror(_("%s: does not match index"), name);34533454 status =load_patch_target(state, &buf, ce, &st, name, mode);3455if(status <0)3456return status;3457else if(status)3458return-1;3459 img =strbuf_detach(&buf, &len);3460prepare_image(image, img, len, !patch->is_binary);3461return0;3462}34633464static inttry_threeway(struct apply_state *state,3465struct image *image,3466struct patch *patch,3467struct stat *st,3468const struct cache_entry *ce)3469{3470unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3471struct strbuf buf = STRBUF_INIT;3472size_t len;3473int status;3474char*img;3475struct image tmp_image;34763477/* No point falling back to 3-way merge in these cases */3478if(patch->is_delete ||3479S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3480return-1;34813482/* Preimage the patch was prepared for */3483if(patch->is_new)3484write_sha1_file("",0, blob_type, pre_sha1);3485else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3486read_blob_object(&buf, pre_sha1, patch->old_mode))3487returnerror("repository lacks the necessary blob to fall back on 3-way merge.");34883489fprintf(stderr,"Falling back to three-way merge...\n");34903491 img =strbuf_detach(&buf, &len);3492prepare_image(&tmp_image, img, len,1);3493/* Apply the patch to get the post image */3494if(apply_fragments(state, &tmp_image, patch) <0) {3495clear_image(&tmp_image);3496return-1;3497}3498/* post_sha1[] is theirs */3499write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3500clear_image(&tmp_image);35013502/* our_sha1[] is ours */3503if(patch->is_new) {3504if(load_current(state, &tmp_image, patch))3505returnerror("cannot read the current contents of '%s'",3506 patch->new_name);3507}else{3508if(load_preimage(state, &tmp_image, patch, st, ce))3509returnerror("cannot read the current contents of '%s'",3510 patch->old_name);3511}3512write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3513clear_image(&tmp_image);35143515/* in-core three-way merge between post and our using pre as base */3516 status =three_way_merge(image, patch->new_name,3517 pre_sha1, our_sha1, post_sha1);3518if(status <0) {3519fprintf(stderr,"Failed to fall back on three-way merge...\n");3520return status;3521}35223523if(status) {3524 patch->conflicted_threeway =1;3525if(patch->is_new)3526oidclr(&patch->threeway_stage[0]);3527else3528hashcpy(patch->threeway_stage[0].hash, pre_sha1);3529hashcpy(patch->threeway_stage[1].hash, our_sha1);3530hashcpy(patch->threeway_stage[2].hash, post_sha1);3531fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3532}else{3533fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3534}3535return0;3536}35373538static intapply_data(struct apply_state *state,struct patch *patch,3539struct stat *st,const struct cache_entry *ce)3540{3541struct image image;35423543if(load_preimage(state, &image, patch, st, ce) <0)3544return-1;35453546if(patch->direct_to_threeway ||3547apply_fragments(state, &image, patch) <0) {3548/* Note: with --reject, apply_fragments() returns 0 */3549if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3550return-1;3551}3552 patch->result = image.buf;3553 patch->resultsize = image.len;3554add_to_fn_table(patch);3555free(image.line_allocated);35563557if(0< patch->is_delete && patch->resultsize)3558returnerror(_("removal patch leaves file contents"));35593560return0;3561}35623563/*3564 * If "patch" that we are looking at modifies or deletes what we have,3565 * we would want it not to lose any local modification we have, either3566 * in the working tree or in the index.3567 *3568 * This also decides if a non-git patch is a creation patch or a3569 * modification to an existing empty file. We do not check the state3570 * of the current tree for a creation patch in this function; the caller3571 * check_patch() separately makes sure (and errors out otherwise) that3572 * the path the patch creates does not exist in the current tree.3573 */3574static intcheck_preimage(struct apply_state *state,3575struct patch *patch,3576struct cache_entry **ce,3577struct stat *st)3578{3579const char*old_name = patch->old_name;3580struct patch *previous = NULL;3581int stat_ret =0, status;3582unsigned st_mode =0;35833584if(!old_name)3585return0;35863587assert(patch->is_new <=0);3588 previous =previous_patch(patch, &status);35893590if(status)3591returnerror(_("path%shas been renamed/deleted"), old_name);3592if(previous) {3593 st_mode = previous->new_mode;3594}else if(!state->cached) {3595 stat_ret =lstat(old_name, st);3596if(stat_ret && errno != ENOENT)3597returnerror(_("%s:%s"), old_name,strerror(errno));3598}35993600if(state->check_index && !previous) {3601int pos =cache_name_pos(old_name,strlen(old_name));3602if(pos <0) {3603if(patch->is_new <0)3604goto is_new;3605returnerror(_("%s: does not exist in index"), old_name);3606}3607*ce = active_cache[pos];3608if(stat_ret <0) {3609if(checkout_target(&the_index, *ce, st))3610return-1;3611}3612if(!state->cached &&verify_index_match(*ce, st))3613returnerror(_("%s: does not match index"), old_name);3614if(state->cached)3615 st_mode = (*ce)->ce_mode;3616}else if(stat_ret <0) {3617if(patch->is_new <0)3618goto is_new;3619returnerror(_("%s:%s"), old_name,strerror(errno));3620}36213622if(!state->cached && !previous)3623 st_mode =ce_mode_from_stat(*ce, st->st_mode);36243625if(patch->is_new <0)3626 patch->is_new =0;3627if(!patch->old_mode)3628 patch->old_mode = st_mode;3629if((st_mode ^ patch->old_mode) & S_IFMT)3630returnerror(_("%s: wrong type"), old_name);3631if(st_mode != patch->old_mode)3632warning(_("%shas type%o, expected%o"),3633 old_name, st_mode, patch->old_mode);3634if(!patch->new_mode && !patch->is_delete)3635 patch->new_mode = st_mode;3636return0;36373638 is_new:3639 patch->is_new =1;3640 patch->is_delete =0;3641free(patch->old_name);3642 patch->old_name = NULL;3643return0;3644}364536463647#define EXISTS_IN_INDEX 13648#define EXISTS_IN_WORKTREE 236493650static intcheck_to_create(struct apply_state *state,3651const char*new_name,3652int ok_if_exists)3653{3654struct stat nst;36553656if(state->check_index &&3657cache_name_pos(new_name,strlen(new_name)) >=0&&3658!ok_if_exists)3659return EXISTS_IN_INDEX;3660if(state->cached)3661return0;36623663if(!lstat(new_name, &nst)) {3664if(S_ISDIR(nst.st_mode) || ok_if_exists)3665return0;3666/*3667 * A leading component of new_name might be a symlink3668 * that is going to be removed with this patch, but3669 * still pointing at somewhere that has the path.3670 * In such a case, path "new_name" does not exist as3671 * far as git is concerned.3672 */3673if(has_symlink_leading_path(new_name,strlen(new_name)))3674return0;36753676return EXISTS_IN_WORKTREE;3677}else if((errno != ENOENT) && (errno != ENOTDIR)) {3678returnerror("%s:%s", new_name,strerror(errno));3679}3680return0;3681}36823683/*3684 * We need to keep track of how symlinks in the preimage are3685 * manipulated by the patches. A patch to add a/b/c where a/b3686 * is a symlink should not be allowed to affect the directory3687 * the symlink points at, but if the same patch removes a/b,3688 * it is perfectly fine, as the patch removes a/b to make room3689 * to create a directory a/b so that a/b/c can be created.3690 */3691static struct string_list symlink_changes;3692#define SYMLINK_GOES_AWAY 013693#define SYMLINK_IN_RESULT 0236943695static uintptr_tregister_symlink_changes(const char*path,uintptr_t what)3696{3697struct string_list_item *ent;36983699 ent =string_list_lookup(&symlink_changes, path);3700if(!ent) {3701 ent =string_list_insert(&symlink_changes, path);3702 ent->util = (void*)0;3703}3704 ent->util = (void*)(what | ((uintptr_t)ent->util));3705return(uintptr_t)ent->util;3706}37073708static uintptr_tcheck_symlink_changes(const char*path)3709{3710struct string_list_item *ent;37113712 ent =string_list_lookup(&symlink_changes, path);3713if(!ent)3714return0;3715return(uintptr_t)ent->util;3716}37173718static voidprepare_symlink_changes(struct patch *patch)3719{3720for( ; patch; patch = patch->next) {3721if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3722(patch->is_rename || patch->is_delete))3723/* the symlink at patch->old_name is removed */3724register_symlink_changes(patch->old_name, SYMLINK_GOES_AWAY);37253726if(patch->new_name &&S_ISLNK(patch->new_mode))3727/* the symlink at patch->new_name is created or remains */3728register_symlink_changes(patch->new_name, SYMLINK_IN_RESULT);3729}3730}37313732static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3733{3734do{3735unsigned int change;37363737while(--name->len && name->buf[name->len] !='/')3738;/* scan backwards */3739if(!name->len)3740break;3741 name->buf[name->len] ='\0';3742 change =check_symlink_changes(name->buf);3743if(change & SYMLINK_IN_RESULT)3744return1;3745if(change & SYMLINK_GOES_AWAY)3746/*3747 * This cannot be "return 0", because we may3748 * see a new one created at a higher level.3749 */3750continue;37513752/* otherwise, check the preimage */3753if(state->check_index) {3754struct cache_entry *ce;37553756 ce =cache_file_exists(name->buf, name->len, ignore_case);3757if(ce &&S_ISLNK(ce->ce_mode))3758return1;3759}else{3760struct stat st;3761if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3762return1;3763}3764}while(1);3765return0;3766}37673768static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3769{3770int ret;3771struct strbuf name = STRBUF_INIT;37723773assert(*name_ !='\0');3774strbuf_addstr(&name, name_);3775 ret =path_is_beyond_symlink_1(state, &name);3776strbuf_release(&name);37773778return ret;3779}37803781static voiddie_on_unsafe_path(struct patch *patch)3782{3783const char*old_name = NULL;3784const char*new_name = NULL;3785if(patch->is_delete)3786 old_name = patch->old_name;3787else if(!patch->is_new && !patch->is_copy)3788 old_name = patch->old_name;3789if(!patch->is_delete)3790 new_name = patch->new_name;37913792if(old_name && !verify_path(old_name))3793die(_("invalid path '%s'"), old_name);3794if(new_name && !verify_path(new_name))3795die(_("invalid path '%s'"), new_name);3796}37973798/*3799 * Check and apply the patch in-core; leave the result in patch->result3800 * for the caller to write it out to the final destination.3801 */3802static intcheck_patch(struct apply_state *state,struct patch *patch)3803{3804struct stat st;3805const char*old_name = patch->old_name;3806const char*new_name = patch->new_name;3807const char*name = old_name ? old_name : new_name;3808struct cache_entry *ce = NULL;3809struct patch *tpatch;3810int ok_if_exists;3811int status;38123813 patch->rejected =1;/* we will drop this after we succeed */38143815 status =check_preimage(state, patch, &ce, &st);3816if(status)3817return status;3818 old_name = patch->old_name;38193820/*3821 * A type-change diff is always split into a patch to delete3822 * old, immediately followed by a patch to create new (see3823 * diff.c::run_diff()); in such a case it is Ok that the entry3824 * to be deleted by the previous patch is still in the working3825 * tree and in the index.3826 *3827 * A patch to swap-rename between A and B would first rename A3828 * to B and then rename B to A. While applying the first one,3829 * the presence of B should not stop A from getting renamed to3830 * B; ask to_be_deleted() about the later rename. Removal of3831 * B and rename from A to B is handled the same way by asking3832 * was_deleted().3833 */3834if((tpatch =in_fn_table(new_name)) &&3835(was_deleted(tpatch) ||to_be_deleted(tpatch)))3836 ok_if_exists =1;3837else3838 ok_if_exists =0;38393840if(new_name &&3841((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3842int err =check_to_create(state, new_name, ok_if_exists);38433844if(err && state->threeway) {3845 patch->direct_to_threeway =1;3846}else switch(err) {3847case0:3848break;/* happy */3849case EXISTS_IN_INDEX:3850returnerror(_("%s: already exists in index"), new_name);3851break;3852case EXISTS_IN_WORKTREE:3853returnerror(_("%s: already exists in working directory"),3854 new_name);3855default:3856return err;3857}38583859if(!patch->new_mode) {3860if(0< patch->is_new)3861 patch->new_mode = S_IFREG |0644;3862else3863 patch->new_mode = patch->old_mode;3864}3865}38663867if(new_name && old_name) {3868int same = !strcmp(old_name, new_name);3869if(!patch->new_mode)3870 patch->new_mode = patch->old_mode;3871if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3872if(same)3873returnerror(_("new mode (%o) of%sdoes not "3874"match old mode (%o)"),3875 patch->new_mode, new_name,3876 patch->old_mode);3877else3878returnerror(_("new mode (%o) of%sdoes not "3879"match old mode (%o) of%s"),3880 patch->new_mode, new_name,3881 patch->old_mode, old_name);3882}3883}38843885if(!state->unsafe_paths)3886die_on_unsafe_path(patch);38873888/*3889 * An attempt to read from or delete a path that is beyond a3890 * symbolic link will be prevented by load_patch_target() that3891 * is called at the beginning of apply_data() so we do not3892 * have to worry about a patch marked with "is_delete" bit3893 * here. We however need to make sure that the patch result3894 * is not deposited to a path that is beyond a symbolic link3895 * here.3896 */3897if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3898returnerror(_("affected file '%s' is beyond a symbolic link"),3899 patch->new_name);39003901if(apply_data(state, patch, &st, ce) <0)3902returnerror(_("%s: patch does not apply"), name);3903 patch->rejected =0;3904return0;3905}39063907static intcheck_patch_list(struct apply_state *state,struct patch *patch)3908{3909int err =0;39103911prepare_symlink_changes(patch);3912prepare_fn_table(patch);3913while(patch) {3914if(state->apply_verbosely)3915say_patch_name(stderr,3916_("Checking patch%s..."), patch);3917 err |=check_patch(state, patch);3918 patch = patch->next;3919}3920return err;3921}39223923/* This function tries to read the sha1 from the current index */3924static intget_current_sha1(const char*path,unsigned char*sha1)3925{3926int pos;39273928if(read_cache() <0)3929return-1;3930 pos =cache_name_pos(path,strlen(path));3931if(pos <0)3932return-1;3933hashcpy(sha1, active_cache[pos]->sha1);3934return0;3935}39363937static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3938{3939/*3940 * A usable gitlink patch has only one fragment (hunk) that looks like:3941 * @@ -1 +1 @@3942 * -Subproject commit <old sha1>3943 * +Subproject commit <new sha1>3944 * or3945 * @@ -1 +0,0 @@3946 * -Subproject commit <old sha1>3947 * for a removal patch.3948 */3949struct fragment *hunk = p->fragments;3950static const char heading[] ="-Subproject commit ";3951char*preimage;39523953if(/* does the patch have only one hunk? */3954 hunk && !hunk->next &&3955/* is its preimage one line? */3956 hunk->oldpos ==1&& hunk->oldlines ==1&&3957/* does preimage begin with the heading? */3958(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3959starts_with(++preimage, heading) &&3960/* does it record full SHA-1? */3961!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3962 preimage[sizeof(heading) +40-1] =='\n'&&3963/* does the abbreviated name on the index line agree with it? */3964starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3965return0;/* it all looks fine */39663967/* we may have full object name on the index line */3968returnget_sha1_hex(p->old_sha1_prefix, sha1);3969}39703971/* Build an index that contains the just the files needed for a 3way merge */3972static voidbuild_fake_ancestor(struct patch *list,const char*filename)3973{3974struct patch *patch;3975struct index_state result = { NULL };3976static struct lock_file lock;39773978/* Once we start supporting the reverse patch, it may be3979 * worth showing the new sha1 prefix, but until then...3980 */3981for(patch = list; patch; patch = patch->next) {3982unsigned char sha1[20];3983struct cache_entry *ce;3984const char*name;39853986 name = patch->old_name ? patch->old_name : patch->new_name;3987if(0< patch->is_new)3988continue;39893990if(S_ISGITLINK(patch->old_mode)) {3991if(!preimage_sha1_in_gitlink_patch(patch, sha1))3992;/* ok, the textual part looks sane */3993else3994die("sha1 information is lacking or useless for submodule%s",3995 name);3996}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {3997;/* ok */3998}else if(!patch->lines_added && !patch->lines_deleted) {3999/* mode-only change: update the current */4000if(get_current_sha1(patch->old_name, sha1))4001die("mode change for%s, which is not "4002"in current HEAD", name);4003}else4004die("sha1 information is lacking or useless "4005"(%s).", name);40064007 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);4008if(!ce)4009die(_("make_cache_entry failed for path '%s'"), name);4010if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))4011die("Could not add%sto temporary index", name);4012}40134014hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);4015if(write_locked_index(&result, &lock, COMMIT_LOCK))4016die("Could not write temporary index to%s", filename);40174018discard_index(&result);4019}40204021static voidstat_patch_list(struct patch *patch)4022{4023int files, adds, dels;40244025for(files = adds = dels =0; patch ; patch = patch->next) {4026 files++;4027 adds += patch->lines_added;4028 dels += patch->lines_deleted;4029show_stats(patch);4030}40314032print_stat_summary(stdout, files, adds, dels);4033}40344035static voidnumstat_patch_list(struct apply_state *state,4036struct patch *patch)4037{4038for( ; patch; patch = patch->next) {4039const char*name;4040 name = patch->new_name ? patch->new_name : patch->old_name;4041if(patch->is_binary)4042printf("-\t-\t");4043else4044printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4045write_name_quoted(name, stdout, state->line_termination);4046}4047}40484049static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4050{4051if(mode)4052printf("%smode%06o%s\n", newdelete, mode, name);4053else4054printf("%s %s\n", newdelete, name);4055}40564057static voidshow_mode_change(struct patch *p,int show_name)4058{4059if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4060if(show_name)4061printf(" mode change%06o =>%06o%s\n",4062 p->old_mode, p->new_mode, p->new_name);4063else4064printf(" mode change%06o =>%06o\n",4065 p->old_mode, p->new_mode);4066}4067}40684069static voidshow_rename_copy(struct patch *p)4070{4071const char*renamecopy = p->is_rename ?"rename":"copy";4072const char*old, *new;40734074/* Find common prefix */4075 old = p->old_name;4076new= p->new_name;4077while(1) {4078const char*slash_old, *slash_new;4079 slash_old =strchr(old,'/');4080 slash_new =strchr(new,'/');4081if(!slash_old ||4082!slash_new ||4083 slash_old - old != slash_new -new||4084memcmp(old,new, slash_new -new))4085break;4086 old = slash_old +1;4087new= slash_new +1;4088}4089/* p->old_name thru old is the common prefix, and old and new4090 * through the end of names are renames4091 */4092if(old != p->old_name)4093printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4094(int)(old - p->old_name), p->old_name,4095 old,new, p->score);4096else4097printf("%s %s=>%s(%d%%)\n", renamecopy,4098 p->old_name, p->new_name, p->score);4099show_mode_change(p,0);4100}41014102static voidsummary_patch_list(struct patch *patch)4103{4104struct patch *p;41054106for(p = patch; p; p = p->next) {4107if(p->is_new)4108show_file_mode_name("create", p->new_mode, p->new_name);4109else if(p->is_delete)4110show_file_mode_name("delete", p->old_mode, p->old_name);4111else{4112if(p->is_rename || p->is_copy)4113show_rename_copy(p);4114else{4115if(p->score) {4116printf(" rewrite%s(%d%%)\n",4117 p->new_name, p->score);4118show_mode_change(p,0);4119}4120else4121show_mode_change(p,1);4122}4123}4124}4125}41264127static voidpatch_stats(struct patch *patch)4128{4129int lines = patch->lines_added + patch->lines_deleted;41304131if(lines > max_change)4132 max_change = lines;4133if(patch->old_name) {4134int len =quote_c_style(patch->old_name, NULL, NULL,0);4135if(!len)4136 len =strlen(patch->old_name);4137if(len > max_len)4138 max_len = len;4139}4140if(patch->new_name) {4141int len =quote_c_style(patch->new_name, NULL, NULL,0);4142if(!len)4143 len =strlen(patch->new_name);4144if(len > max_len)4145 max_len = len;4146}4147}41484149static voidremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4150{4151if(state->update_index) {4152if(remove_file_from_cache(patch->old_name) <0)4153die(_("unable to remove%sfrom index"), patch->old_name);4154}4155if(!state->cached) {4156if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4157remove_path(patch->old_name);4158}4159}4160}41614162static voidadd_index_file(struct apply_state *state,4163const char*path,4164unsigned mode,4165void*buf,4166unsigned long size)4167{4168struct stat st;4169struct cache_entry *ce;4170int namelen =strlen(path);4171unsigned ce_size =cache_entry_size(namelen);41724173if(!state->update_index)4174return;41754176 ce =xcalloc(1, ce_size);4177memcpy(ce->name, path, namelen);4178 ce->ce_mode =create_ce_mode(mode);4179 ce->ce_flags =create_ce_flags(0);4180 ce->ce_namelen = namelen;4181if(S_ISGITLINK(mode)) {4182const char*s;41834184if(!skip_prefix(buf,"Subproject commit ", &s) ||4185get_sha1_hex(s, ce->sha1))4186die(_("corrupt patch for submodule%s"), path);4187}else{4188if(!state->cached) {4189if(lstat(path, &st) <0)4190die_errno(_("unable to stat newly created file '%s'"),4191 path);4192fill_stat_cache_info(ce, &st);4193}4194if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4195die(_("unable to create backing store for newly created file%s"), path);4196}4197if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4198die(_("unable to add cache entry for%s"), path);4199}42004201static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4202{4203int fd;4204struct strbuf nbuf = STRBUF_INIT;42054206if(S_ISGITLINK(mode)) {4207struct stat st;4208if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4209return0;4210returnmkdir(path,0777);4211}42124213if(has_symlinks &&S_ISLNK(mode))4214/* Although buf:size is counted string, it also is NUL4215 * terminated.4216 */4217returnsymlink(buf, path);42184219 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4220if(fd <0)4221return-1;42224223if(convert_to_working_tree(path, buf, size, &nbuf)) {4224 size = nbuf.len;4225 buf = nbuf.buf;4226}4227write_or_die(fd, buf, size);4228strbuf_release(&nbuf);42294230if(close(fd) <0)4231die_errno(_("closing file '%s'"), path);4232return0;4233}42344235/*4236 * We optimistically assume that the directories exist,4237 * which is true 99% of the time anyway. If they don't,4238 * we create them and try again.4239 */4240static voidcreate_one_file(struct apply_state *state,4241char*path,4242unsigned mode,4243const char*buf,4244unsigned long size)4245{4246if(state->cached)4247return;4248if(!try_create_file(path, mode, buf, size))4249return;42504251if(errno == ENOENT) {4252if(safe_create_leading_directories(path))4253return;4254if(!try_create_file(path, mode, buf, size))4255return;4256}42574258if(errno == EEXIST || errno == EACCES) {4259/* We may be trying to create a file where a directory4260 * used to be.4261 */4262struct stat st;4263if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4264 errno = EEXIST;4265}42664267if(errno == EEXIST) {4268unsigned int nr =getpid();42694270for(;;) {4271char newpath[PATH_MAX];4272mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4273if(!try_create_file(newpath, mode, buf, size)) {4274if(!rename(newpath, path))4275return;4276unlink_or_warn(newpath);4277break;4278}4279if(errno != EEXIST)4280break;4281++nr;4282}4283}4284die_errno(_("unable to write file '%s' mode%o"), path, mode);4285}42864287static voidadd_conflicted_stages_file(struct apply_state *state,4288struct patch *patch)4289{4290int stage, namelen;4291unsigned ce_size, mode;4292struct cache_entry *ce;42934294if(!state->update_index)4295return;4296 namelen =strlen(patch->new_name);4297 ce_size =cache_entry_size(namelen);4298 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);42994300remove_file_from_cache(patch->new_name);4301for(stage =1; stage <4; stage++) {4302if(is_null_oid(&patch->threeway_stage[stage -1]))4303continue;4304 ce =xcalloc(1, ce_size);4305memcpy(ce->name, patch->new_name, namelen);4306 ce->ce_mode =create_ce_mode(mode);4307 ce->ce_flags =create_ce_flags(stage);4308 ce->ce_namelen = namelen;4309hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4310if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4311die(_("unable to add cache entry for%s"), patch->new_name);4312}4313}43144315static voidcreate_file(struct apply_state *state,struct patch *patch)4316{4317char*path = patch->new_name;4318unsigned mode = patch->new_mode;4319unsigned long size = patch->resultsize;4320char*buf = patch->result;43214322if(!mode)4323 mode = S_IFREG |0644;4324create_one_file(state, path, mode, buf, size);43254326if(patch->conflicted_threeway)4327add_conflicted_stages_file(state, patch);4328else4329add_index_file(state, path, mode, buf, size);4330}43314332/* phase zero is to remove, phase one is to create */4333static voidwrite_out_one_result(struct apply_state *state,4334struct patch *patch,4335int phase)4336{4337if(patch->is_delete >0) {4338if(phase ==0)4339remove_file(state, patch,1);4340return;4341}4342if(patch->is_new >0|| patch->is_copy) {4343if(phase ==1)4344create_file(state, patch);4345return;4346}4347/*4348 * Rename or modification boils down to the same4349 * thing: remove the old, write the new4350 */4351if(phase ==0)4352remove_file(state, patch, patch->is_rename);4353if(phase ==1)4354create_file(state, patch);4355}43564357static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4358{4359FILE*rej;4360char namebuf[PATH_MAX];4361struct fragment *frag;4362int cnt =0;4363struct strbuf sb = STRBUF_INIT;43644365for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4366if(!frag->rejected)4367continue;4368 cnt++;4369}43704371if(!cnt) {4372if(state->apply_verbosely)4373say_patch_name(stderr,4374_("Applied patch%scleanly."), patch);4375return0;4376}43774378/* This should not happen, because a removal patch that leaves4379 * contents are marked "rejected" at the patch level.4380 */4381if(!patch->new_name)4382die(_("internal error"));43834384/* Say this even without --verbose */4385strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4386"Applying patch %%swith%drejects...",4387 cnt),4388 cnt);4389say_patch_name(stderr, sb.buf, patch);4390strbuf_release(&sb);43914392 cnt =strlen(patch->new_name);4393if(ARRAY_SIZE(namebuf) <= cnt +5) {4394 cnt =ARRAY_SIZE(namebuf) -5;4395warning(_("truncating .rej filename to %.*s.rej"),4396 cnt -1, patch->new_name);4397}4398memcpy(namebuf, patch->new_name, cnt);4399memcpy(namebuf + cnt,".rej",5);44004401 rej =fopen(namebuf,"w");4402if(!rej)4403returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));44044405/* Normal git tools never deal with .rej, so do not pretend4406 * this is a git patch by saying --git or giving extended4407 * headers. While at it, maybe please "kompare" that wants4408 * the trailing TAB and some garbage at the end of line ;-).4409 */4410fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4411 patch->new_name, patch->new_name);4412for(cnt =1, frag = patch->fragments;4413 frag;4414 cnt++, frag = frag->next) {4415if(!frag->rejected) {4416fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4417continue;4418}4419fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4420fprintf(rej,"%.*s", frag->size, frag->patch);4421if(frag->patch[frag->size-1] !='\n')4422fputc('\n', rej);4423}4424fclose(rej);4425return-1;4426}44274428static intwrite_out_results(struct apply_state *state,struct patch *list)4429{4430int phase;4431int errs =0;4432struct patch *l;4433struct string_list cpath = STRING_LIST_INIT_DUP;44344435for(phase =0; phase <2; phase++) {4436 l = list;4437while(l) {4438if(l->rejected)4439 errs =1;4440else{4441write_out_one_result(state, l, phase);4442if(phase ==1) {4443if(write_out_one_reject(state, l))4444 errs =1;4445if(l->conflicted_threeway) {4446string_list_append(&cpath, l->new_name);4447 errs =1;4448}4449}4450}4451 l = l->next;4452}4453}44544455if(cpath.nr) {4456struct string_list_item *item;44574458string_list_sort(&cpath);4459for_each_string_list_item(item, &cpath)4460fprintf(stderr,"U%s\n", item->string);4461string_list_clear(&cpath,0);44624463rerere(0);4464}44654466return errs;4467}44684469static struct lock_file lock_file;44704471#define INACCURATE_EOF (1<<0)4472#define RECOUNT (1<<1)44734474static intapply_patch(struct apply_state *state,4475int fd,4476const char*filename,4477int options)4478{4479size_t offset;4480struct strbuf buf = STRBUF_INIT;/* owns the patch text */4481struct patch *list = NULL, **listp = &list;4482int skipped_patch =0;44834484 state->patch_input_file = filename;4485read_patch_file(&buf, fd);4486 offset =0;4487while(offset < buf.len) {4488struct patch *patch;4489int nr;44904491 patch =xcalloc(1,sizeof(*patch));4492 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4493 patch->recount = !!(options & RECOUNT);4494 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4495if(nr <0) {4496free_patch(patch);4497break;4498}4499if(state->apply_in_reverse)4500reverse_patches(patch);4501if(use_patch(state, patch)) {4502patch_stats(patch);4503*listp = patch;4504 listp = &patch->next;4505}4506else{4507if(state->apply_verbosely)4508say_patch_name(stderr,_("Skipped patch '%s'."), patch);4509free_patch(patch);4510 skipped_patch++;4511}4512 offset += nr;4513}45144515if(!list && !skipped_patch)4516die(_("unrecognized input"));45174518if(whitespace_error && (ws_error_action == die_on_ws_error))4519 state->apply =0;45204521 state->update_index = state->check_index && state->apply;4522if(state->update_index && newfd <0)4523 newfd =hold_locked_index(&lock_file,1);45244525if(state->check_index) {4526if(read_cache() <0)4527die(_("unable to read index file"));4528}45294530if((state->check || state->apply) &&4531check_patch_list(state, list) <0&&4532!state->apply_with_reject)4533exit(1);45344535if(state->apply &&write_out_results(state, list)) {4536if(state->apply_with_reject)4537exit(1);4538/* with --3way, we still need to write the index out */4539return1;4540}45414542if(state->fake_ancestor)4543build_fake_ancestor(list, state->fake_ancestor);45444545if(state->diffstat)4546stat_patch_list(list);45474548if(state->numstat)4549numstat_patch_list(state, list);45504551if(state->summary)4552summary_patch_list(list);45534554free_patch_list(list);4555strbuf_release(&buf);4556string_list_clear(&fn_table,0);4557return0;4558}45594560static voidgit_apply_config(void)4561{4562git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4563git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4564git_config(git_default_config, NULL);4565}45664567static intoption_parse_exclude(const struct option *opt,4568const char*arg,int unset)4569{4570struct apply_state *state = opt->value;4571add_name_limit(state, arg,1);4572return0;4573}45744575static intoption_parse_include(const struct option *opt,4576const char*arg,int unset)4577{4578struct apply_state *state = opt->value;4579add_name_limit(state, arg,0);4580 state->has_include =1;4581return0;4582}45834584static intoption_parse_p(const struct option *opt,4585const char*arg,4586int unset)4587{4588struct apply_state *state = opt->value;4589 state->p_value =atoi(arg);4590 state->p_value_known =1;4591return0;4592}45934594static intoption_parse_space_change(const struct option *opt,4595const char*arg,int unset)4596{4597if(unset)4598 ws_ignore_action = ignore_ws_none;4599else4600 ws_ignore_action = ignore_ws_change;4601return0;4602}46034604static intoption_parse_whitespace(const struct option *opt,4605const char*arg,int unset)4606{4607const char**whitespace_option = opt->value;46084609*whitespace_option = arg;4610parse_whitespace_option(arg);4611return0;4612}46134614static intoption_parse_directory(const struct option *opt,4615const char*arg,int unset)4616{4617strbuf_reset(&root);4618strbuf_addstr(&root, arg);4619strbuf_complete(&root,'/');4620return0;4621}46224623static voidinit_apply_state(struct apply_state *state,const char*prefix)4624{4625memset(state,0,sizeof(*state));4626 state->prefix = prefix;4627 state->prefix_length = state->prefix ?strlen(state->prefix) :0;4628 state->apply =1;4629 state->line_termination ='\n';4630 state->p_value =1;4631 state->p_context = UINT_MAX;46324633git_apply_config();4634if(apply_default_whitespace)4635parse_whitespace_option(apply_default_whitespace);4636if(apply_default_ignorewhitespace)4637parse_ignorewhitespace_option(apply_default_ignorewhitespace);4638}46394640static voidclear_apply_state(struct apply_state *state)4641{4642string_list_clear(&state->limit_by_name,0);4643}46444645intcmd_apply(int argc,const char**argv,const char*prefix)4646{4647int i;4648int errs =0;4649int is_not_gitdir = !startup_info->have_repository;4650int force_apply =0;4651int options =0;4652int read_stdin =1;4653struct apply_state state;46544655const char*whitespace_option = NULL;46564657struct option builtin_apply_options[] = {4658{ OPTION_CALLBACK,0,"exclude", &state,N_("path"),4659N_("don't apply changes matching the given path"),46600, option_parse_exclude },4661{ OPTION_CALLBACK,0,"include", &state,N_("path"),4662N_("apply changes matching the given path"),46630, option_parse_include },4664{ OPTION_CALLBACK,'p', NULL, &state,N_("num"),4665N_("remove <num> leading slashes from traditional diff paths"),46660, option_parse_p },4667OPT_BOOL(0,"no-add", &state.no_add,4668N_("ignore additions made by the patch")),4669OPT_BOOL(0,"stat", &state.diffstat,4670N_("instead of applying the patch, output diffstat for the input")),4671OPT_NOOP_NOARG(0,"allow-binary-replacement"),4672OPT_NOOP_NOARG(0,"binary"),4673OPT_BOOL(0,"numstat", &state.numstat,4674N_("show number of added and deleted lines in decimal notation")),4675OPT_BOOL(0,"summary", &state.summary,4676N_("instead of applying the patch, output a summary for the input")),4677OPT_BOOL(0,"check", &state.check,4678N_("instead of applying the patch, see if the patch is applicable")),4679OPT_BOOL(0,"index", &state.check_index,4680N_("make sure the patch is applicable to the current index")),4681OPT_BOOL(0,"cached", &state.cached,4682N_("apply a patch without touching the working tree")),4683OPT_BOOL(0,"unsafe-paths", &state.unsafe_paths,4684N_("accept a patch that touches outside the working area")),4685OPT_BOOL(0,"apply", &force_apply,4686N_("also apply the patch (use with --stat/--summary/--check)")),4687OPT_BOOL('3',"3way", &state.threeway,4688N_("attempt three-way merge if a patch does not apply")),4689OPT_FILENAME(0,"build-fake-ancestor", &state.fake_ancestor,4690N_("build a temporary index based on embedded index information")),4691/* Think twice before adding "--nul" synonym to this */4692OPT_SET_INT('z', NULL, &state.line_termination,4693N_("paths are separated with NUL character"),'\0'),4694OPT_INTEGER('C', NULL, &state.p_context,4695N_("ensure at least <n> lines of context match")),4696{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,N_("action"),4697N_("detect new or modified lines that have whitespace errors"),46980, option_parse_whitespace },4699{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,4700N_("ignore changes in whitespace when finding context"),4701 PARSE_OPT_NOARG, option_parse_space_change },4702{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,4703N_("ignore changes in whitespace when finding context"),4704 PARSE_OPT_NOARG, option_parse_space_change },4705OPT_BOOL('R',"reverse", &state.apply_in_reverse,4706N_("apply the patch in reverse")),4707OPT_BOOL(0,"unidiff-zero", &state.unidiff_zero,4708N_("don't expect at least one line of context")),4709OPT_BOOL(0,"reject", &state.apply_with_reject,4710N_("leave the rejected hunks in corresponding *.rej files")),4711OPT_BOOL(0,"allow-overlap", &state.allow_overlap,4712N_("allow overlapping hunks")),4713OPT__VERBOSE(&state.apply_verbosely,N_("be verbose")),4714OPT_BIT(0,"inaccurate-eof", &options,4715N_("tolerate incorrectly detected missing new-line at the end of file"),4716 INACCURATE_EOF),4717OPT_BIT(0,"recount", &options,4718N_("do not trust the line counts in the hunk headers"),4719 RECOUNT),4720{ OPTION_CALLBACK,0,"directory", NULL,N_("root"),4721N_("prepend <root> to all filenames"),47220, option_parse_directory },4723OPT_END()4724};47254726init_apply_state(&state, prefix);47274728 argc =parse_options(argc, argv, state.prefix, builtin_apply_options,4729 apply_usage,0);47304731if(state.apply_with_reject && state.threeway)4732die("--reject and --3way cannot be used together.");4733if(state.cached && state.threeway)4734die("--cached and --3way cannot be used together.");4735if(state.threeway) {4736if(is_not_gitdir)4737die(_("--3way outside a repository"));4738 state.check_index =1;4739}4740if(state.apply_with_reject)4741 state.apply = state.apply_verbosely =1;4742if(!force_apply && (state.diffstat || state.numstat || state.summary || state.check || state.fake_ancestor))4743 state.apply =0;4744if(state.check_index && is_not_gitdir)4745die(_("--index outside a repository"));4746if(state.cached) {4747if(is_not_gitdir)4748die(_("--cached outside a repository"));4749 state.check_index =1;4750}4751if(state.check_index)4752 state.unsafe_paths =0;47534754for(i =0; i < argc; i++) {4755const char*arg = argv[i];4756int fd;47574758if(!strcmp(arg,"-")) {4759 errs |=apply_patch(&state,0,"<stdin>", options);4760 read_stdin =0;4761continue;4762}else if(0< state.prefix_length)4763 arg =prefix_filename(state.prefix,4764 state.prefix_length,4765 arg);47664767 fd =open(arg, O_RDONLY);4768if(fd <0)4769die_errno(_("can't open patch '%s'"), arg);4770 read_stdin =0;4771set_default_whitespace_mode(&state, whitespace_option);4772 errs |=apply_patch(&state, fd, arg, options);4773close(fd);4774}4775set_default_whitespace_mode(&state, whitespace_option);4776if(read_stdin)4777 errs |=apply_patch(&state,0,"<stdin>", options);4778if(whitespace_error) {4779if(squelch_whitespace_errors &&4780 squelch_whitespace_errors < whitespace_error) {4781int squelched =4782 whitespace_error - squelch_whitespace_errors;4783warning(Q_("squelched%dwhitespace error",4784"squelched%dwhitespace errors",4785 squelched),4786 squelched);4787}4788if(ws_error_action == die_on_ws_error)4789die(Q_("%dline adds whitespace errors.",4790"%dlines add whitespace errors.",4791 whitespace_error),4792 whitespace_error);4793if(applied_after_fixing_ws && state.apply)4794warning("%dline%sapplied after"4795" fixing whitespace errors.",4796 applied_after_fixing_ws,4797 applied_after_fixing_ws ==1?"":"s");4798else if(whitespace_error)4799warning(Q_("%dline adds whitespace errors.",4800"%dlines add whitespace errors.",4801 whitespace_error),4802 whitespace_error);4803}48044805if(state.update_index) {4806if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK))4807die(_("Unable to write new index file"));4808}48094810clear_apply_state(&state);48114812return!!errs;4813}