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#include"apply.h" 24 25static const char*const apply_usage[] = { 26N_("git apply [<options>] [<patch>...]"), 27 NULL 28}; 29 30static intparse_whitespace_option(struct apply_state *state,const char*option) 31{ 32if(!option) { 33 state->ws_error_action = warn_on_ws_error; 34return0; 35} 36if(!strcmp(option,"warn")) { 37 state->ws_error_action = warn_on_ws_error; 38return0; 39} 40if(!strcmp(option,"nowarn")) { 41 state->ws_error_action = nowarn_ws_error; 42return0; 43} 44if(!strcmp(option,"error")) { 45 state->ws_error_action = die_on_ws_error; 46return0; 47} 48if(!strcmp(option,"error-all")) { 49 state->ws_error_action = die_on_ws_error; 50 state->squelch_whitespace_errors =0; 51return0; 52} 53if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 54 state->ws_error_action = correct_ws_error; 55return0; 56} 57returnerror(_("unrecognized whitespace option '%s'"), option); 58} 59 60static intparse_ignorewhitespace_option(struct apply_state *state, 61const char*option) 62{ 63if(!option || !strcmp(option,"no") || 64!strcmp(option,"false") || !strcmp(option,"never") || 65!strcmp(option,"none")) { 66 state->ws_ignore_action = ignore_ws_none; 67return0; 68} 69if(!strcmp(option,"change")) { 70 state->ws_ignore_action = ignore_ws_change; 71return0; 72} 73returnerror(_("unrecognized whitespace ignore option '%s'"), option); 74} 75 76static voidset_default_whitespace_mode(struct apply_state *state) 77{ 78if(!state->whitespace_option && !apply_default_whitespace) 79 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 80} 81 82/* 83 * This represents one "hunk" from a patch, starting with 84 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 85 * patch text is pointed at by patch, and its byte length 86 * is stored in size. leading and trailing are the number 87 * of context lines. 88 */ 89struct fragment { 90unsigned long leading, trailing; 91unsigned long oldpos, oldlines; 92unsigned long newpos, newlines; 93/* 94 * 'patch' is usually borrowed from buf in apply_patch(), 95 * but some codepaths store an allocated buffer. 96 */ 97const char*patch; 98unsigned free_patch:1, 99 rejected:1; 100int size; 101int linenr; 102struct fragment *next; 103}; 104 105/* 106 * When dealing with a binary patch, we reuse "leading" field 107 * to store the type of the binary hunk, either deflated "delta" 108 * or deflated "literal". 109 */ 110#define binary_patch_method leading 111#define BINARY_DELTA_DEFLATED 1 112#define BINARY_LITERAL_DEFLATED 2 113 114/* 115 * This represents a "patch" to a file, both metainfo changes 116 * such as creation/deletion, filemode and content changes represented 117 * as a series of fragments. 118 */ 119struct patch { 120char*new_name, *old_name, *def_name; 121unsigned int old_mode, new_mode; 122int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 123int rejected; 124unsigned ws_rule; 125int lines_added, lines_deleted; 126int score; 127unsigned int is_toplevel_relative:1; 128unsigned int inaccurate_eof:1; 129unsigned int is_binary:1; 130unsigned int is_copy:1; 131unsigned int is_rename:1; 132unsigned int recount:1; 133unsigned int conflicted_threeway:1; 134unsigned int direct_to_threeway:1; 135struct fragment *fragments; 136char*result; 137size_t resultsize; 138char old_sha1_prefix[41]; 139char new_sha1_prefix[41]; 140struct patch *next; 141 142/* three-way fallback result */ 143struct object_id threeway_stage[3]; 144}; 145 146static voidfree_fragment_list(struct fragment *list) 147{ 148while(list) { 149struct fragment *next = list->next; 150if(list->free_patch) 151free((char*)list->patch); 152free(list); 153 list = next; 154} 155} 156 157static voidfree_patch(struct patch *patch) 158{ 159free_fragment_list(patch->fragments); 160free(patch->def_name); 161free(patch->old_name); 162free(patch->new_name); 163free(patch->result); 164free(patch); 165} 166 167static voidfree_patch_list(struct patch *list) 168{ 169while(list) { 170struct patch *next = list->next; 171free_patch(list); 172 list = next; 173} 174} 175 176/* 177 * A line in a file, len-bytes long (includes the terminating LF, 178 * except for an incomplete line at the end if the file ends with 179 * one), and its contents hashes to 'hash'. 180 */ 181struct line { 182size_t len; 183unsigned hash :24; 184unsigned flag :8; 185#define LINE_COMMON 1 186#define LINE_PATCHED 2 187}; 188 189/* 190 * This represents a "file", which is an array of "lines". 191 */ 192struct image { 193char*buf; 194size_t len; 195size_t nr; 196size_t alloc; 197struct line *line_allocated; 198struct line *line; 199}; 200 201static uint32_thash_line(const char*cp,size_t len) 202{ 203size_t i; 204uint32_t h; 205for(i =0, h =0; i < len; i++) { 206if(!isspace(cp[i])) { 207 h = h *3+ (cp[i] &0xff); 208} 209} 210return h; 211} 212 213/* 214 * Compare lines s1 of length n1 and s2 of length n2, ignoring 215 * whitespace difference. Returns 1 if they match, 0 otherwise 216 */ 217static intfuzzy_matchlines(const char*s1,size_t n1, 218const char*s2,size_t n2) 219{ 220const char*last1 = s1 + n1 -1; 221const char*last2 = s2 + n2 -1; 222int result =0; 223 224/* ignore line endings */ 225while((*last1 =='\r') || (*last1 =='\n')) 226 last1--; 227while((*last2 =='\r') || (*last2 =='\n')) 228 last2--; 229 230/* skip leading whitespaces, if both begin with whitespace */ 231if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 232while(isspace(*s1) && (s1 <= last1)) 233 s1++; 234while(isspace(*s2) && (s2 <= last2)) 235 s2++; 236} 237/* early return if both lines are empty */ 238if((s1 > last1) && (s2 > last2)) 239return1; 240while(!result) { 241 result = *s1++ - *s2++; 242/* 243 * Skip whitespace inside. We check for whitespace on 244 * both buffers because we don't want "a b" to match 245 * "ab" 246 */ 247if(isspace(*s1) &&isspace(*s2)) { 248while(isspace(*s1) && s1 <= last1) 249 s1++; 250while(isspace(*s2) && s2 <= last2) 251 s2++; 252} 253/* 254 * If we reached the end on one side only, 255 * lines don't match 256 */ 257if( 258((s2 > last2) && (s1 <= last1)) || 259((s1 > last1) && (s2 <= last2))) 260return0; 261if((s1 > last1) && (s2 > last2)) 262break; 263} 264 265return!result; 266} 267 268static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 269{ 270ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 271 img->line_allocated[img->nr].len = len; 272 img->line_allocated[img->nr].hash =hash_line(bol, len); 273 img->line_allocated[img->nr].flag = flag; 274 img->nr++; 275} 276 277/* 278 * "buf" has the file contents to be patched (read from various sources). 279 * attach it to "image" and add line-based index to it. 280 * "image" now owns the "buf". 281 */ 282static voidprepare_image(struct image *image,char*buf,size_t len, 283int prepare_linetable) 284{ 285const char*cp, *ep; 286 287memset(image,0,sizeof(*image)); 288 image->buf = buf; 289 image->len = len; 290 291if(!prepare_linetable) 292return; 293 294 ep = image->buf + image->len; 295 cp = image->buf; 296while(cp < ep) { 297const char*next; 298for(next = cp; next < ep && *next !='\n'; next++) 299; 300if(next < ep) 301 next++; 302add_line_info(image, cp, next - cp,0); 303 cp = next; 304} 305 image->line = image->line_allocated; 306} 307 308static voidclear_image(struct image *image) 309{ 310free(image->buf); 311free(image->line_allocated); 312memset(image,0,sizeof(*image)); 313} 314 315/* fmt must contain _one_ %s and no other substitution */ 316static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 317{ 318struct strbuf sb = STRBUF_INIT; 319 320if(patch->old_name && patch->new_name && 321strcmp(patch->old_name, patch->new_name)) { 322quote_c_style(patch->old_name, &sb, NULL,0); 323strbuf_addstr(&sb," => "); 324quote_c_style(patch->new_name, &sb, NULL,0); 325}else{ 326const char*n = patch->new_name; 327if(!n) 328 n = patch->old_name; 329quote_c_style(n, &sb, NULL,0); 330} 331fprintf(output, fmt, sb.buf); 332fputc('\n', output); 333strbuf_release(&sb); 334} 335 336#define SLOP (16) 337 338static intread_patch_file(struct strbuf *sb,int fd) 339{ 340if(strbuf_read(sb, fd,0) <0) 341returnerror_errno("git apply: failed to read"); 342 343/* 344 * Make sure that we have some slop in the buffer 345 * so that we can do speculative "memcmp" etc, and 346 * see to it that it is NUL-filled. 347 */ 348strbuf_grow(sb, SLOP); 349memset(sb->buf + sb->len,0, SLOP); 350return0; 351} 352 353static unsigned longlinelen(const char*buffer,unsigned long size) 354{ 355unsigned long len =0; 356while(size--) { 357 len++; 358if(*buffer++ =='\n') 359break; 360} 361return len; 362} 363 364static intis_dev_null(const char*str) 365{ 366returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 367} 368 369#define TERM_SPACE 1 370#define TERM_TAB 2 371 372static intname_terminate(int c,int terminate) 373{ 374if(c ==' '&& !(terminate & TERM_SPACE)) 375return0; 376if(c =='\t'&& !(terminate & TERM_TAB)) 377return0; 378 379return1; 380} 381 382/* remove double slashes to make --index work with such filenames */ 383static char*squash_slash(char*name) 384{ 385int i =0, j =0; 386 387if(!name) 388return NULL; 389 390while(name[i]) { 391if((name[j++] = name[i++]) =='/') 392while(name[i] =='/') 393 i++; 394} 395 name[j] ='\0'; 396return name; 397} 398 399static char*find_name_gnu(struct apply_state *state, 400const char*line, 401const char*def, 402int p_value) 403{ 404struct strbuf name = STRBUF_INIT; 405char*cp; 406 407/* 408 * Proposed "new-style" GNU patch/diff format; see 409 * http://marc.info/?l=git&m=112927316408690&w=2 410 */ 411if(unquote_c_style(&name, line, NULL)) { 412strbuf_release(&name); 413return NULL; 414} 415 416for(cp = name.buf; p_value; p_value--) { 417 cp =strchr(cp,'/'); 418if(!cp) { 419strbuf_release(&name); 420return NULL; 421} 422 cp++; 423} 424 425strbuf_remove(&name,0, cp - name.buf); 426if(state->root.len) 427strbuf_insert(&name,0, state->root.buf, state->root.len); 428returnsquash_slash(strbuf_detach(&name, NULL)); 429} 430 431static size_tsane_tz_len(const char*line,size_t len) 432{ 433const char*tz, *p; 434 435if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 436return0; 437 tz = line + len -strlen(" +0500"); 438 439if(tz[1] !='+'&& tz[1] !='-') 440return0; 441 442for(p = tz +2; p != line + len; p++) 443if(!isdigit(*p)) 444return0; 445 446return line + len - tz; 447} 448 449static size_ttz_with_colon_len(const char*line,size_t len) 450{ 451const char*tz, *p; 452 453if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 454return0; 455 tz = line + len -strlen(" +08:00"); 456 457if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 458return0; 459 p = tz +2; 460if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 461!isdigit(*p++) || !isdigit(*p++)) 462return0; 463 464return line + len - tz; 465} 466 467static size_tdate_len(const char*line,size_t len) 468{ 469const char*date, *p; 470 471if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 472return0; 473 p = date = line + len -strlen("72-02-05"); 474 475if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 476!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 477!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 478return0; 479 480if(date - line >=strlen("19") && 481isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 482 date -=strlen("19"); 483 484return line + len - date; 485} 486 487static size_tshort_time_len(const char*line,size_t len) 488{ 489const char*time, *p; 490 491if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 492return0; 493 p = time = line + len -strlen(" 07:01:32"); 494 495/* Permit 1-digit hours? */ 496if(*p++ !=' '|| 497!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 498!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 499!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 500return0; 501 502return line + len - time; 503} 504 505static size_tfractional_time_len(const char*line,size_t len) 506{ 507const char*p; 508size_t n; 509 510/* Expected format: 19:41:17.620000023 */ 511if(!len || !isdigit(line[len -1])) 512return0; 513 p = line + len -1; 514 515/* Fractional seconds. */ 516while(p > line &&isdigit(*p)) 517 p--; 518if(*p !='.') 519return0; 520 521/* Hours, minutes, and whole seconds. */ 522 n =short_time_len(line, p - line); 523if(!n) 524return0; 525 526return line + len - p + n; 527} 528 529static size_ttrailing_spaces_len(const char*line,size_t len) 530{ 531const char*p; 532 533/* Expected format: ' ' x (1 or more) */ 534if(!len || line[len -1] !=' ') 535return0; 536 537 p = line + len; 538while(p != line) { 539 p--; 540if(*p !=' ') 541return line + len - (p +1); 542} 543 544/* All spaces! */ 545return len; 546} 547 548static size_tdiff_timestamp_len(const char*line,size_t len) 549{ 550const char*end = line + len; 551size_t n; 552 553/* 554 * Posix: 2010-07-05 19:41:17 555 * GNU: 2010-07-05 19:41:17.620000023 -0500 556 */ 557 558if(!isdigit(end[-1])) 559return0; 560 561 n =sane_tz_len(line, end - line); 562if(!n) 563 n =tz_with_colon_len(line, end - line); 564 end -= n; 565 566 n =short_time_len(line, end - line); 567if(!n) 568 n =fractional_time_len(line, end - line); 569 end -= n; 570 571 n =date_len(line, end - line); 572if(!n)/* No date. Too bad. */ 573return0; 574 end -= n; 575 576if(end == line)/* No space before date. */ 577return0; 578if(end[-1] =='\t') {/* Success! */ 579 end--; 580return line + len - end; 581} 582if(end[-1] !=' ')/* No space before date. */ 583return0; 584 585/* Whitespace damage. */ 586 end -=trailing_spaces_len(line, end - line); 587return line + len - end; 588} 589 590static char*find_name_common(struct apply_state *state, 591const char*line, 592const char*def, 593int p_value, 594const char*end, 595int terminate) 596{ 597int len; 598const char*start = NULL; 599 600if(p_value ==0) 601 start = line; 602while(line != end) { 603char c = *line; 604 605if(!end &&isspace(c)) { 606if(c =='\n') 607break; 608if(name_terminate(c, terminate)) 609break; 610} 611 line++; 612if(c =='/'&& !--p_value) 613 start = line; 614} 615if(!start) 616returnsquash_slash(xstrdup_or_null(def)); 617 len = line - start; 618if(!len) 619returnsquash_slash(xstrdup_or_null(def)); 620 621/* 622 * Generally we prefer the shorter name, especially 623 * if the other one is just a variation of that with 624 * something else tacked on to the end (ie "file.orig" 625 * or "file~"). 626 */ 627if(def) { 628int deflen =strlen(def); 629if(deflen < len && !strncmp(start, def, deflen)) 630returnsquash_slash(xstrdup(def)); 631} 632 633if(state->root.len) { 634char*ret =xstrfmt("%s%.*s", state->root.buf, len, start); 635returnsquash_slash(ret); 636} 637 638returnsquash_slash(xmemdupz(start, len)); 639} 640 641static char*find_name(struct apply_state *state, 642const char*line, 643char*def, 644int p_value, 645int terminate) 646{ 647if(*line =='"') { 648char*name =find_name_gnu(state, line, def, p_value); 649if(name) 650return name; 651} 652 653returnfind_name_common(state, line, def, p_value, NULL, terminate); 654} 655 656static char*find_name_traditional(struct apply_state *state, 657const char*line, 658char*def, 659int p_value) 660{ 661size_t len; 662size_t date_len; 663 664if(*line =='"') { 665char*name =find_name_gnu(state, line, def, p_value); 666if(name) 667return name; 668} 669 670 len =strchrnul(line,'\n') - line; 671 date_len =diff_timestamp_len(line, len); 672if(!date_len) 673returnfind_name_common(state, line, def, p_value, NULL, TERM_TAB); 674 len -= date_len; 675 676returnfind_name_common(state, line, def, p_value, line + len,0); 677} 678 679static intcount_slashes(const char*cp) 680{ 681int cnt =0; 682char ch; 683 684while((ch = *cp++)) 685if(ch =='/') 686 cnt++; 687return cnt; 688} 689 690/* 691 * Given the string after "--- " or "+++ ", guess the appropriate 692 * p_value for the given patch. 693 */ 694static intguess_p_value(struct apply_state *state,const char*nameline) 695{ 696char*name, *cp; 697int val = -1; 698 699if(is_dev_null(nameline)) 700return-1; 701 name =find_name_traditional(state, nameline, NULL,0); 702if(!name) 703return-1; 704 cp =strchr(name,'/'); 705if(!cp) 706 val =0; 707else if(state->prefix) { 708/* 709 * Does it begin with "a/$our-prefix" and such? Then this is 710 * very likely to apply to our directory. 711 */ 712if(!strncmp(name, state->prefix, state->prefix_length)) 713 val =count_slashes(state->prefix); 714else{ 715 cp++; 716if(!strncmp(cp, state->prefix, state->prefix_length)) 717 val =count_slashes(state->prefix) +1; 718} 719} 720free(name); 721return val; 722} 723 724/* 725 * Does the ---/+++ line have the POSIX timestamp after the last HT? 726 * GNU diff puts epoch there to signal a creation/deletion event. Is 727 * this such a timestamp? 728 */ 729static inthas_epoch_timestamp(const char*nameline) 730{ 731/* 732 * We are only interested in epoch timestamp; any non-zero 733 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 734 * For the same reason, the date must be either 1969-12-31 or 735 * 1970-01-01, and the seconds part must be "00". 736 */ 737const char stamp_regexp[] = 738"^(1969-12-31|1970-01-01)" 739" " 740"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 741" " 742"([-+][0-2][0-9]:?[0-5][0-9])\n"; 743const char*timestamp = NULL, *cp, *colon; 744static regex_t *stamp; 745 regmatch_t m[10]; 746int zoneoffset; 747int hourminute; 748int status; 749 750for(cp = nameline; *cp !='\n'; cp++) { 751if(*cp =='\t') 752 timestamp = cp +1; 753} 754if(!timestamp) 755return0; 756if(!stamp) { 757 stamp =xmalloc(sizeof(*stamp)); 758if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 759warning(_("Cannot prepare timestamp regexp%s"), 760 stamp_regexp); 761return0; 762} 763} 764 765 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 766if(status) { 767if(status != REG_NOMATCH) 768warning(_("regexec returned%dfor input:%s"), 769 status, timestamp); 770return0; 771} 772 773 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 774if(*colon ==':') 775 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 776else 777 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 778if(timestamp[m[3].rm_so] =='-') 779 zoneoffset = -zoneoffset; 780 781/* 782 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 783 * (west of GMT) or 1970-01-01 (east of GMT) 784 */ 785if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 786(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 787return0; 788 789 hourminute = (strtol(timestamp +11, NULL,10) *60+ 790strtol(timestamp +14, NULL,10) - 791 zoneoffset); 792 793return((zoneoffset <0&& hourminute ==1440) || 794(0<= zoneoffset && !hourminute)); 795} 796 797/* 798 * Get the name etc info from the ---/+++ lines of a traditional patch header 799 * 800 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 801 * files, we can happily check the index for a match, but for creating a 802 * new file we should try to match whatever "patch" does. I have no idea. 803 */ 804static voidparse_traditional_patch(struct apply_state *state, 805const char*first, 806const char*second, 807struct patch *patch) 808{ 809char*name; 810 811 first +=4;/* skip "--- " */ 812 second +=4;/* skip "+++ " */ 813if(!state->p_value_known) { 814int p, q; 815 p =guess_p_value(state, first); 816 q =guess_p_value(state, second); 817if(p <0) p = q; 818if(0<= p && p == q) { 819 state->p_value = p; 820 state->p_value_known =1; 821} 822} 823if(is_dev_null(first)) { 824 patch->is_new =1; 825 patch->is_delete =0; 826 name =find_name_traditional(state, second, NULL, state->p_value); 827 patch->new_name = name; 828}else if(is_dev_null(second)) { 829 patch->is_new =0; 830 patch->is_delete =1; 831 name =find_name_traditional(state, first, NULL, state->p_value); 832 patch->old_name = name; 833}else{ 834char*first_name; 835 first_name =find_name_traditional(state, first, NULL, state->p_value); 836 name =find_name_traditional(state, second, first_name, state->p_value); 837free(first_name); 838if(has_epoch_timestamp(first)) { 839 patch->is_new =1; 840 patch->is_delete =0; 841 patch->new_name = name; 842}else if(has_epoch_timestamp(second)) { 843 patch->is_new =0; 844 patch->is_delete =1; 845 patch->old_name = name; 846}else{ 847 patch->old_name = name; 848 patch->new_name =xstrdup_or_null(name); 849} 850} 851if(!name) 852die(_("unable to find filename in patch at line%d"), state->linenr); 853} 854 855static intgitdiff_hdrend(struct apply_state *state, 856const char*line, 857struct patch *patch) 858{ 859return-1; 860} 861 862/* 863 * We're anal about diff header consistency, to make 864 * sure that we don't end up having strange ambiguous 865 * patches floating around. 866 * 867 * As a result, gitdiff_{old|new}name() will check 868 * their names against any previous information, just 869 * to make sure.. 870 */ 871#define DIFF_OLD_NAME 0 872#define DIFF_NEW_NAME 1 873 874static voidgitdiff_verify_name(struct apply_state *state, 875const char*line, 876int isnull, 877char**name, 878int side) 879{ 880if(!*name && !isnull) { 881*name =find_name(state, line, NULL, state->p_value, TERM_TAB); 882return; 883} 884 885if(*name) { 886int len =strlen(*name); 887char*another; 888if(isnull) 889die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 890*name, state->linenr); 891 another =find_name(state, line, NULL, state->p_value, TERM_TAB); 892if(!another ||memcmp(another, *name, len +1)) 893die((side == DIFF_NEW_NAME) ? 894_("git apply: bad git-diff - inconsistent new filename on line%d") : 895_("git apply: bad git-diff - inconsistent old filename on line%d"), state->linenr); 896free(another); 897}else{ 898/* expect "/dev/null" */ 899if(memcmp("/dev/null", line,9) || line[9] !='\n') 900die(_("git apply: bad git-diff - expected /dev/null on line%d"), state->linenr); 901} 902} 903 904static intgitdiff_oldname(struct apply_state *state, 905const char*line, 906struct patch *patch) 907{ 908gitdiff_verify_name(state, line, 909 patch->is_new, &patch->old_name, 910 DIFF_OLD_NAME); 911return0; 912} 913 914static intgitdiff_newname(struct apply_state *state, 915const char*line, 916struct patch *patch) 917{ 918gitdiff_verify_name(state, line, 919 patch->is_delete, &patch->new_name, 920 DIFF_NEW_NAME); 921return0; 922} 923 924static intgitdiff_oldmode(struct apply_state *state, 925const char*line, 926struct patch *patch) 927{ 928 patch->old_mode =strtoul(line, NULL,8); 929return0; 930} 931 932static intgitdiff_newmode(struct apply_state *state, 933const char*line, 934struct patch *patch) 935{ 936 patch->new_mode =strtoul(line, NULL,8); 937return0; 938} 939 940static intgitdiff_delete(struct apply_state *state, 941const char*line, 942struct patch *patch) 943{ 944 patch->is_delete =1; 945free(patch->old_name); 946 patch->old_name =xstrdup_or_null(patch->def_name); 947returngitdiff_oldmode(state, line, patch); 948} 949 950static intgitdiff_newfile(struct apply_state *state, 951const char*line, 952struct patch *patch) 953{ 954 patch->is_new =1; 955free(patch->new_name); 956 patch->new_name =xstrdup_or_null(patch->def_name); 957returngitdiff_newmode(state, line, patch); 958} 959 960static intgitdiff_copysrc(struct apply_state *state, 961const char*line, 962struct patch *patch) 963{ 964 patch->is_copy =1; 965free(patch->old_name); 966 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0); 967return0; 968} 969 970static intgitdiff_copydst(struct apply_state *state, 971const char*line, 972struct patch *patch) 973{ 974 patch->is_copy =1; 975free(patch->new_name); 976 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0); 977return0; 978} 979 980static intgitdiff_renamesrc(struct apply_state *state, 981const char*line, 982struct patch *patch) 983{ 984 patch->is_rename =1; 985free(patch->old_name); 986 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0); 987return0; 988} 989 990static intgitdiff_renamedst(struct apply_state *state, 991const char*line, 992struct patch *patch) 993{ 994 patch->is_rename =1; 995free(patch->new_name); 996 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0); 997return0; 998} 9991000static intgitdiff_similarity(struct apply_state *state,1001const char*line,1002struct patch *patch)1003{1004unsigned long val =strtoul(line, NULL,10);1005if(val <=100)1006 patch->score = val;1007return0;1008}10091010static intgitdiff_dissimilarity(struct apply_state *state,1011const char*line,1012struct patch *patch)1013{1014unsigned long val =strtoul(line, NULL,10);1015if(val <=100)1016 patch->score = val;1017return0;1018}10191020static intgitdiff_index(struct apply_state *state,1021const char*line,1022struct patch *patch)1023{1024/*1025 * index line is N hexadecimal, "..", N hexadecimal,1026 * and optional space with octal mode.1027 */1028const char*ptr, *eol;1029int len;10301031 ptr =strchr(line,'.');1032if(!ptr || ptr[1] !='.'||40< ptr - line)1033return0;1034 len = ptr - line;1035memcpy(patch->old_sha1_prefix, line, len);1036 patch->old_sha1_prefix[len] =0;10371038 line = ptr +2;1039 ptr =strchr(line,' ');1040 eol =strchrnul(line,'\n');10411042if(!ptr || eol < ptr)1043 ptr = eol;1044 len = ptr - line;10451046if(40< len)1047return0;1048memcpy(patch->new_sha1_prefix, line, len);1049 patch->new_sha1_prefix[len] =0;1050if(*ptr ==' ')1051 patch->old_mode =strtoul(ptr+1, NULL,8);1052return0;1053}10541055/*1056 * This is normal for a diff that doesn't change anything: we'll fall through1057 * into the next diff. Tell the parser to break out.1058 */1059static intgitdiff_unrecognized(struct apply_state *state,1060const char*line,1061struct patch *patch)1062{1063return-1;1064}10651066/*1067 * Skip p_value leading components from "line"; as we do not accept1068 * absolute paths, return NULL in that case.1069 */1070static const char*skip_tree_prefix(struct apply_state *state,1071const char*line,1072int llen)1073{1074int nslash;1075int i;10761077if(!state->p_value)1078return(llen && line[0] =='/') ? NULL : line;10791080 nslash = state->p_value;1081for(i =0; i < llen; i++) {1082int ch = line[i];1083if(ch =='/'&& --nslash <=0)1084return(i ==0) ? NULL : &line[i +1];1085}1086return NULL;1087}10881089/*1090 * This is to extract the same name that appears on "diff --git"1091 * line. We do not find and return anything if it is a rename1092 * patch, and it is OK because we will find the name elsewhere.1093 * We need to reliably find name only when it is mode-change only,1094 * creation or deletion of an empty file. In any of these cases,1095 * both sides are the same name under a/ and b/ respectively.1096 */1097static char*git_header_name(struct apply_state *state,1098const char*line,1099int llen)1100{1101const char*name;1102const char*second = NULL;1103size_t len, line_len;11041105 line +=strlen("diff --git ");1106 llen -=strlen("diff --git ");11071108if(*line =='"') {1109const char*cp;1110struct strbuf first = STRBUF_INIT;1111struct strbuf sp = STRBUF_INIT;11121113if(unquote_c_style(&first, line, &second))1114goto free_and_fail1;11151116/* strip the a/b prefix including trailing slash */1117 cp =skip_tree_prefix(state, first.buf, first.len);1118if(!cp)1119goto free_and_fail1;1120strbuf_remove(&first,0, cp - first.buf);11211122/*1123 * second points at one past closing dq of name.1124 * find the second name.1125 */1126while((second < line + llen) &&isspace(*second))1127 second++;11281129if(line + llen <= second)1130goto free_and_fail1;1131if(*second =='"') {1132if(unquote_c_style(&sp, second, NULL))1133goto free_and_fail1;1134 cp =skip_tree_prefix(state, sp.buf, sp.len);1135if(!cp)1136goto free_and_fail1;1137/* They must match, otherwise ignore */1138if(strcmp(cp, first.buf))1139goto free_and_fail1;1140strbuf_release(&sp);1141returnstrbuf_detach(&first, NULL);1142}11431144/* unquoted second */1145 cp =skip_tree_prefix(state, second, line + llen - second);1146if(!cp)1147goto free_and_fail1;1148if(line + llen - cp != first.len ||1149memcmp(first.buf, cp, first.len))1150goto free_and_fail1;1151returnstrbuf_detach(&first, NULL);11521153 free_and_fail1:1154strbuf_release(&first);1155strbuf_release(&sp);1156return NULL;1157}11581159/* unquoted first name */1160 name =skip_tree_prefix(state, line, llen);1161if(!name)1162return NULL;11631164/*1165 * since the first name is unquoted, a dq if exists must be1166 * the beginning of the second name.1167 */1168for(second = name; second < line + llen; second++) {1169if(*second =='"') {1170struct strbuf sp = STRBUF_INIT;1171const char*np;11721173if(unquote_c_style(&sp, second, NULL))1174goto free_and_fail2;11751176 np =skip_tree_prefix(state, sp.buf, sp.len);1177if(!np)1178goto free_and_fail2;11791180 len = sp.buf + sp.len - np;1181if(len < second - name &&1182!strncmp(np, name, len) &&1183isspace(name[len])) {1184/* Good */1185strbuf_remove(&sp,0, np - sp.buf);1186returnstrbuf_detach(&sp, NULL);1187}11881189 free_and_fail2:1190strbuf_release(&sp);1191return NULL;1192}1193}11941195/*1196 * Accept a name only if it shows up twice, exactly the same1197 * form.1198 */1199 second =strchr(name,'\n');1200if(!second)1201return NULL;1202 line_len = second - name;1203for(len =0; ; len++) {1204switch(name[len]) {1205default:1206continue;1207case'\n':1208return NULL;1209case'\t':case' ':1210/*1211 * Is this the separator between the preimage1212 * and the postimage pathname? Again, we are1213 * only interested in the case where there is1214 * no rename, as this is only to set def_name1215 * and a rename patch has the names elsewhere1216 * in an unambiguous form.1217 */1218if(!name[len +1])1219return NULL;/* no postimage name */1220 second =skip_tree_prefix(state, name + len +1,1221 line_len - (len +1));1222if(!second)1223return NULL;1224/*1225 * Does len bytes starting at "name" and "second"1226 * (that are separated by one HT or SP we just1227 * found) exactly match?1228 */1229if(second[len] =='\n'&& !strncmp(name, second, len))1230returnxmemdupz(name, len);1231}1232}1233}12341235/* Verify that we recognize the lines following a git header */1236static intparse_git_header(struct apply_state *state,1237const char*line,1238int len,1239unsigned int size,1240struct patch *patch)1241{1242unsigned long offset;12431244/* A git diff has explicit new/delete information, so we don't guess */1245 patch->is_new =0;1246 patch->is_delete =0;12471248/*1249 * Some things may not have the old name in the1250 * rest of the headers anywhere (pure mode changes,1251 * or removing or adding empty files), so we get1252 * the default name from the header.1253 */1254 patch->def_name =git_header_name(state, line, len);1255if(patch->def_name && state->root.len) {1256char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1257free(patch->def_name);1258 patch->def_name = s;1259}12601261 line += len;1262 size -= len;1263 state->linenr++;1264for(offset = len ; size >0; offset += len, size -= len, line += len, state->linenr++) {1265static const struct opentry {1266const char*str;1267int(*fn)(struct apply_state *,const char*,struct patch *);1268} optable[] = {1269{"@@ -", gitdiff_hdrend },1270{"--- ", gitdiff_oldname },1271{"+++ ", gitdiff_newname },1272{"old mode ", gitdiff_oldmode },1273{"new mode ", gitdiff_newmode },1274{"deleted file mode ", gitdiff_delete },1275{"new file mode ", gitdiff_newfile },1276{"copy from ", gitdiff_copysrc },1277{"copy to ", gitdiff_copydst },1278{"rename old ", gitdiff_renamesrc },1279{"rename new ", gitdiff_renamedst },1280{"rename from ", gitdiff_renamesrc },1281{"rename to ", gitdiff_renamedst },1282{"similarity index ", gitdiff_similarity },1283{"dissimilarity index ", gitdiff_dissimilarity },1284{"index ", gitdiff_index },1285{"", gitdiff_unrecognized },1286};1287int i;12881289 len =linelen(line, size);1290if(!len || line[len-1] !='\n')1291break;1292for(i =0; i <ARRAY_SIZE(optable); i++) {1293const struct opentry *p = optable + i;1294int oplen =strlen(p->str);1295if(len < oplen ||memcmp(p->str, line, oplen))1296continue;1297if(p->fn(state, line + oplen, patch) <0)1298return offset;1299break;1300}1301}13021303return offset;1304}13051306static intparse_num(const char*line,unsigned long*p)1307{1308char*ptr;13091310if(!isdigit(*line))1311return0;1312*p =strtoul(line, &ptr,10);1313return ptr - line;1314}13151316static intparse_range(const char*line,int len,int offset,const char*expect,1317unsigned long*p1,unsigned long*p2)1318{1319int digits, ex;13201321if(offset <0|| offset >= len)1322return-1;1323 line += offset;1324 len -= offset;13251326 digits =parse_num(line, p1);1327if(!digits)1328return-1;13291330 offset += digits;1331 line += digits;1332 len -= digits;13331334*p2 =1;1335if(*line ==',') {1336 digits =parse_num(line+1, p2);1337if(!digits)1338return-1;13391340 offset += digits+1;1341 line += digits+1;1342 len -= digits+1;1343}13441345 ex =strlen(expect);1346if(ex > len)1347return-1;1348if(memcmp(line, expect, ex))1349return-1;13501351return offset + ex;1352}13531354static voidrecount_diff(const char*line,int size,struct fragment *fragment)1355{1356int oldlines =0, newlines =0, ret =0;13571358if(size <1) {1359warning("recount: ignore empty hunk");1360return;1361}13621363for(;;) {1364int len =linelen(line, size);1365 size -= len;1366 line += len;13671368if(size <1)1369break;13701371switch(*line) {1372case' ':case'\n':1373 newlines++;1374/* fall through */1375case'-':1376 oldlines++;1377continue;1378case'+':1379 newlines++;1380continue;1381case'\\':1382continue;1383case'@':1384 ret = size <3|| !starts_with(line,"@@ ");1385break;1386case'd':1387 ret = size <5|| !starts_with(line,"diff ");1388break;1389default:1390 ret = -1;1391break;1392}1393if(ret) {1394warning(_("recount: unexpected line: %.*s"),1395(int)linelen(line, size), line);1396return;1397}1398break;1399}1400 fragment->oldlines = oldlines;1401 fragment->newlines = newlines;1402}14031404/*1405 * Parse a unified diff fragment header of the1406 * form "@@ -a,b +c,d @@"1407 */1408static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1409{1410int offset;14111412if(!len || line[len-1] !='\n')1413return-1;14141415/* Figure out the number of lines in a fragment */1416 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1417 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14181419return offset;1420}14211422/*1423 * Find file diff header1424 *1425 * Returns:1426 * -1 if no header was found1427 * -128 in case of error1428 * the size of the header in bytes (called "offset") otherwise1429 */1430static intfind_header(struct apply_state *state,1431const char*line,1432unsigned long size,1433int*hdrsize,1434struct patch *patch)1435{1436unsigned long offset, len;14371438 patch->is_toplevel_relative =0;1439 patch->is_rename = patch->is_copy =0;1440 patch->is_new = patch->is_delete = -1;1441 patch->old_mode = patch->new_mode =0;1442 patch->old_name = patch->new_name = NULL;1443for(offset =0; size >0; offset += len, size -= len, line += len, state->linenr++) {1444unsigned long nextlen;14451446 len =linelen(line, size);1447if(!len)1448break;14491450/* Testing this early allows us to take a few shortcuts.. */1451if(len <6)1452continue;14531454/*1455 * Make sure we don't find any unconnected patch fragments.1456 * That's a sign that we didn't find a header, and that a1457 * patch has become corrupted/broken up.1458 */1459if(!memcmp("@@ -", line,4)) {1460struct fragment dummy;1461if(parse_fragment_header(line, len, &dummy) <0)1462continue;1463error(_("patch fragment without header at line%d: %.*s"),1464 state->linenr, (int)len-1, line);1465return-128;1466}14671468if(size < len +6)1469break;14701471/*1472 * Git patch? It might not have a real patch, just a rename1473 * or mode change, so we handle that specially1474 */1475if(!memcmp("diff --git ", line,11)) {1476int git_hdr_len =parse_git_header(state, line, len, size, patch);1477if(git_hdr_len <= len)1478continue;1479if(!patch->old_name && !patch->new_name) {1480if(!patch->def_name) {1481error(Q_("git diff header lacks filename information when removing "1482"%dleading pathname component (line%d)",1483"git diff header lacks filename information when removing "1484"%dleading pathname components (line%d)",1485 state->p_value),1486 state->p_value, state->linenr);1487return-128;1488}1489 patch->old_name =xstrdup(patch->def_name);1490 patch->new_name =xstrdup(patch->def_name);1491}1492if(!patch->is_delete && !patch->new_name) {1493error("git diff header lacks filename information "1494"(line%d)", state->linenr);1495return-128;1496}1497 patch->is_toplevel_relative =1;1498*hdrsize = git_hdr_len;1499return offset;1500}15011502/* --- followed by +++ ? */1503if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1504continue;15051506/*1507 * We only accept unified patches, so we want it to1508 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1509 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1510 */1511 nextlen =linelen(line + len, size - len);1512if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1513continue;15141515/* Ok, we'll consider it a patch */1516parse_traditional_patch(state, line, line+len, patch);1517*hdrsize = len + nextlen;1518 state->linenr +=2;1519return offset;1520}1521return-1;1522}15231524static voidrecord_ws_error(struct apply_state *state,1525unsigned result,1526const char*line,1527int len,1528int linenr)1529{1530char*err;15311532if(!result)1533return;15341535 state->whitespace_error++;1536if(state->squelch_whitespace_errors &&1537 state->squelch_whitespace_errors < state->whitespace_error)1538return;15391540 err =whitespace_error_string(result);1541fprintf(stderr,"%s:%d:%s.\n%.*s\n",1542 state->patch_input_file, linenr, err, len, line);1543free(err);1544}15451546static voidcheck_whitespace(struct apply_state *state,1547const char*line,1548int len,1549unsigned ws_rule)1550{1551unsigned result =ws_check(line +1, len -1, ws_rule);15521553record_ws_error(state, result, line +1, len -2, state->linenr);1554}15551556/*1557 * Parse a unified diff. Note that this really needs to parse each1558 * fragment separately, since the only way to know the difference1559 * between a "---" that is part of a patch, and a "---" that starts1560 * the next patch is to look at the line counts..1561 */1562static intparse_fragment(struct apply_state *state,1563const char*line,1564unsigned long size,1565struct patch *patch,1566struct fragment *fragment)1567{1568int added, deleted;1569int len =linelen(line, size), offset;1570unsigned long oldlines, newlines;1571unsigned long leading, trailing;15721573 offset =parse_fragment_header(line, len, fragment);1574if(offset <0)1575return-1;1576if(offset >0&& patch->recount)1577recount_diff(line + offset, size - offset, fragment);1578 oldlines = fragment->oldlines;1579 newlines = fragment->newlines;1580 leading =0;1581 trailing =0;15821583/* Parse the thing.. */1584 line += len;1585 size -= len;1586 state->linenr++;1587 added = deleted =0;1588for(offset = len;15890< size;1590 offset += len, size -= len, line += len, state->linenr++) {1591if(!oldlines && !newlines)1592break;1593 len =linelen(line, size);1594if(!len || line[len-1] !='\n')1595return-1;1596switch(*line) {1597default:1598return-1;1599case'\n':/* newer GNU diff, an empty context line */1600case' ':1601 oldlines--;1602 newlines--;1603if(!deleted && !added)1604 leading++;1605 trailing++;1606if(!state->apply_in_reverse &&1607 state->ws_error_action == correct_ws_error)1608check_whitespace(state, line, len, patch->ws_rule);1609break;1610case'-':1611if(state->apply_in_reverse &&1612 state->ws_error_action != nowarn_ws_error)1613check_whitespace(state, line, len, patch->ws_rule);1614 deleted++;1615 oldlines--;1616 trailing =0;1617break;1618case'+':1619if(!state->apply_in_reverse &&1620 state->ws_error_action != nowarn_ws_error)1621check_whitespace(state, line, len, patch->ws_rule);1622 added++;1623 newlines--;1624 trailing =0;1625break;16261627/*1628 * We allow "\ No newline at end of file". Depending1629 * on locale settings when the patch was produced we1630 * don't know what this line looks like. The only1631 * thing we do know is that it begins with "\ ".1632 * Checking for 12 is just for sanity check -- any1633 * l10n of "\ No newline..." is at least that long.1634 */1635case'\\':1636if(len <12||memcmp(line,"\\",2))1637return-1;1638break;1639}1640}1641if(oldlines || newlines)1642return-1;1643if(!deleted && !added)1644return-1;16451646 fragment->leading = leading;1647 fragment->trailing = trailing;16481649/*1650 * If a fragment ends with an incomplete line, we failed to include1651 * it in the above loop because we hit oldlines == newlines == 01652 * before seeing it.1653 */1654if(12< size && !memcmp(line,"\\",2))1655 offset +=linelen(line, size);16561657 patch->lines_added += added;1658 patch->lines_deleted += deleted;16591660if(0< patch->is_new && oldlines)1661returnerror(_("new file depends on old contents"));1662if(0< patch->is_delete && newlines)1663returnerror(_("deleted file still has contents"));1664return offset;1665}16661667/*1668 * We have seen "diff --git a/... b/..." header (or a traditional patch1669 * header). Read hunks that belong to this patch into fragments and hang1670 * them to the given patch structure.1671 *1672 * The (fragment->patch, fragment->size) pair points into the memory given1673 * by the caller, not a copy, when we return.1674 *1675 * Returns:1676 * -1 in case of error,1677 * the number of bytes in the patch otherwise.1678 */1679static intparse_single_patch(struct apply_state *state,1680const char*line,1681unsigned long size,1682struct patch *patch)1683{1684unsigned long offset =0;1685unsigned long oldlines =0, newlines =0, context =0;1686struct fragment **fragp = &patch->fragments;16871688while(size >4&& !memcmp(line,"@@ -",4)) {1689struct fragment *fragment;1690int len;16911692 fragment =xcalloc(1,sizeof(*fragment));1693 fragment->linenr = state->linenr;1694 len =parse_fragment(state, line, size, patch, fragment);1695if(len <=0) {1696free(fragment);1697returnerror(_("corrupt patch at line%d"), state->linenr);1698}1699 fragment->patch = line;1700 fragment->size = len;1701 oldlines += fragment->oldlines;1702 newlines += fragment->newlines;1703 context += fragment->leading + fragment->trailing;17041705*fragp = fragment;1706 fragp = &fragment->next;17071708 offset += len;1709 line += len;1710 size -= len;1711}17121713/*1714 * If something was removed (i.e. we have old-lines) it cannot1715 * be creation, and if something was added it cannot be1716 * deletion. However, the reverse is not true; --unified=01717 * patches that only add are not necessarily creation even1718 * though they do not have any old lines, and ones that only1719 * delete are not necessarily deletion.1720 *1721 * Unfortunately, a real creation/deletion patch do _not_ have1722 * any context line by definition, so we cannot safely tell it1723 * apart with --unified=0 insanity. At least if the patch has1724 * more than one hunk it is not creation or deletion.1725 */1726if(patch->is_new <0&&1727(oldlines || (patch->fragments && patch->fragments->next)))1728 patch->is_new =0;1729if(patch->is_delete <0&&1730(newlines || (patch->fragments && patch->fragments->next)))1731 patch->is_delete =0;17321733if(0< patch->is_new && oldlines)1734returnerror(_("new file%sdepends on old contents"), patch->new_name);1735if(0< patch->is_delete && newlines)1736returnerror(_("deleted file%sstill has contents"), patch->old_name);1737if(!patch->is_delete && !newlines && context)1738fprintf_ln(stderr,1739_("** warning: "1740"file%sbecomes empty but is not deleted"),1741 patch->new_name);17421743return offset;1744}17451746staticinlineintmetadata_changes(struct patch *patch)1747{1748return patch->is_rename >0||1749 patch->is_copy >0||1750 patch->is_new >0||1751 patch->is_delete ||1752(patch->old_mode && patch->new_mode &&1753 patch->old_mode != patch->new_mode);1754}17551756static char*inflate_it(const void*data,unsigned long size,1757unsigned long inflated_size)1758{1759 git_zstream stream;1760void*out;1761int st;17621763memset(&stream,0,sizeof(stream));17641765 stream.next_in = (unsigned char*)data;1766 stream.avail_in = size;1767 stream.next_out = out =xmalloc(inflated_size);1768 stream.avail_out = inflated_size;1769git_inflate_init(&stream);1770 st =git_inflate(&stream, Z_FINISH);1771git_inflate_end(&stream);1772if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1773free(out);1774return NULL;1775}1776return out;1777}17781779/*1780 * Read a binary hunk and return a new fragment; fragment->patch1781 * points at an allocated memory that the caller must free, so1782 * it is marked as "->free_patch = 1".1783 */1784static struct fragment *parse_binary_hunk(struct apply_state *state,1785char**buf_p,1786unsigned long*sz_p,1787int*status_p,1788int*used_p)1789{1790/*1791 * Expect a line that begins with binary patch method ("literal"1792 * or "delta"), followed by the length of data before deflating.1793 * a sequence of 'length-byte' followed by base-85 encoded data1794 * should follow, terminated by a newline.1795 *1796 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1797 * and we would limit the patch line to 66 characters,1798 * so one line can fit up to 13 groups that would decode1799 * to 52 bytes max. The length byte 'A'-'Z' corresponds1800 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1801 */1802int llen, used;1803unsigned long size = *sz_p;1804char*buffer = *buf_p;1805int patch_method;1806unsigned long origlen;1807char*data = NULL;1808int hunk_size =0;1809struct fragment *frag;18101811 llen =linelen(buffer, size);1812 used = llen;18131814*status_p =0;18151816if(starts_with(buffer,"delta ")) {1817 patch_method = BINARY_DELTA_DEFLATED;1818 origlen =strtoul(buffer +6, NULL,10);1819}1820else if(starts_with(buffer,"literal ")) {1821 patch_method = BINARY_LITERAL_DEFLATED;1822 origlen =strtoul(buffer +8, NULL,10);1823}1824else1825return NULL;18261827 state->linenr++;1828 buffer += llen;1829while(1) {1830int byte_length, max_byte_length, newsize;1831 llen =linelen(buffer, size);1832 used += llen;1833 state->linenr++;1834if(llen ==1) {1835/* consume the blank line */1836 buffer++;1837 size--;1838break;1839}1840/*1841 * Minimum line is "A00000\n" which is 7-byte long,1842 * and the line length must be multiple of 5 plus 2.1843 */1844if((llen <7) || (llen-2) %5)1845goto corrupt;1846 max_byte_length = (llen -2) /5*4;1847 byte_length = *buffer;1848if('A'<= byte_length && byte_length <='Z')1849 byte_length = byte_length -'A'+1;1850else if('a'<= byte_length && byte_length <='z')1851 byte_length = byte_length -'a'+27;1852else1853goto corrupt;1854/* if the input length was not multiple of 4, we would1855 * have filler at the end but the filler should never1856 * exceed 3 bytes1857 */1858if(max_byte_length < byte_length ||1859 byte_length <= max_byte_length -4)1860goto corrupt;1861 newsize = hunk_size + byte_length;1862 data =xrealloc(data, newsize);1863if(decode_85(data + hunk_size, buffer +1, byte_length))1864goto corrupt;1865 hunk_size = newsize;1866 buffer += llen;1867 size -= llen;1868}18691870 frag =xcalloc(1,sizeof(*frag));1871 frag->patch =inflate_it(data, hunk_size, origlen);1872 frag->free_patch =1;1873if(!frag->patch)1874goto corrupt;1875free(data);1876 frag->size = origlen;1877*buf_p = buffer;1878*sz_p = size;1879*used_p = used;1880 frag->binary_patch_method = patch_method;1881return frag;18821883 corrupt:1884free(data);1885*status_p = -1;1886error(_("corrupt binary patch at line%d: %.*s"),1887 state->linenr-1, llen-1, buffer);1888return NULL;1889}18901891/*1892 * Returns:1893 * -1 in case of error,1894 * the length of the parsed binary patch otherwise1895 */1896static intparse_binary(struct apply_state *state,1897char*buffer,1898unsigned long size,1899struct patch *patch)1900{1901/*1902 * We have read "GIT binary patch\n"; what follows is a line1903 * that says the patch method (currently, either "literal" or1904 * "delta") and the length of data before deflating; a1905 * sequence of 'length-byte' followed by base-85 encoded data1906 * follows.1907 *1908 * When a binary patch is reversible, there is another binary1909 * hunk in the same format, starting with patch method (either1910 * "literal" or "delta") with the length of data, and a sequence1911 * of length-byte + base-85 encoded data, terminated with another1912 * empty line. This data, when applied to the postimage, produces1913 * the preimage.1914 */1915struct fragment *forward;1916struct fragment *reverse;1917int status;1918int used, used_1;19191920 forward =parse_binary_hunk(state, &buffer, &size, &status, &used);1921if(!forward && !status)1922/* there has to be one hunk (forward hunk) */1923returnerror(_("unrecognized binary patch at line%d"), state->linenr-1);1924if(status)1925/* otherwise we already gave an error message */1926return status;19271928 reverse =parse_binary_hunk(state, &buffer, &size, &status, &used_1);1929if(reverse)1930 used += used_1;1931else if(status) {1932/*1933 * Not having reverse hunk is not an error, but having1934 * a corrupt reverse hunk is.1935 */1936free((void*) forward->patch);1937free(forward);1938return status;1939}1940 forward->next = reverse;1941 patch->fragments = forward;1942 patch->is_binary =1;1943return used;1944}19451946static voidprefix_one(struct apply_state *state,char**name)1947{1948char*old_name = *name;1949if(!old_name)1950return;1951*name =xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));1952free(old_name);1953}19541955static voidprefix_patch(struct apply_state *state,struct patch *p)1956{1957if(!state->prefix || p->is_toplevel_relative)1958return;1959prefix_one(state, &p->new_name);1960prefix_one(state, &p->old_name);1961}19621963/*1964 * include/exclude1965 */19661967static voidadd_name_limit(struct apply_state *state,1968const char*name,1969int exclude)1970{1971struct string_list_item *it;19721973 it =string_list_append(&state->limit_by_name, name);1974 it->util = exclude ? NULL : (void*)1;1975}19761977static intuse_patch(struct apply_state *state,struct patch *p)1978{1979const char*pathname = p->new_name ? p->new_name : p->old_name;1980int i;19811982/* Paths outside are not touched regardless of "--include" */1983if(0< state->prefix_length) {1984int pathlen =strlen(pathname);1985if(pathlen <= state->prefix_length ||1986memcmp(state->prefix, pathname, state->prefix_length))1987return0;1988}19891990/* See if it matches any of exclude/include rule */1991for(i =0; i < state->limit_by_name.nr; i++) {1992struct string_list_item *it = &state->limit_by_name.items[i];1993if(!wildmatch(it->string, pathname,0, NULL))1994return(it->util != NULL);1995}19961997/*1998 * If we had any include, a path that does not match any rule is1999 * not used. Otherwise, we saw bunch of exclude rules (or none)2000 * and such a path is used.2001 */2002return!state->has_include;2003}20042005/*2006 * Read the patch text in "buffer" that extends for "size" bytes; stop2007 * reading after seeing a single patch (i.e. changes to a single file).2008 * Create fragments (i.e. patch hunks) and hang them to the given patch.2009 *2010 * Returns:2011 * -1 if no header was found or parse_binary() failed,2012 * -128 on another error,2013 * the number of bytes consumed otherwise,2014 * so that the caller can call us again for the next patch.2015 */2016static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2017{2018int hdrsize, patchsize;2019int offset =find_header(state, buffer, size, &hdrsize, patch);20202021if(offset <0)2022return offset;20232024prefix_patch(state, patch);20252026if(!use_patch(state, patch))2027 patch->ws_rule =0;2028else2029 patch->ws_rule =whitespace_rule(patch->new_name2030? patch->new_name2031: patch->old_name);20322033 patchsize =parse_single_patch(state,2034 buffer + offset + hdrsize,2035 size - offset - hdrsize,2036 patch);20372038if(patchsize <0)2039return-128;20402041if(!patchsize) {2042static const char git_binary[] ="GIT binary patch\n";2043int hd = hdrsize + offset;2044unsigned long llen =linelen(buffer + hd, size - hd);20452046if(llen ==sizeof(git_binary) -1&&2047!memcmp(git_binary, buffer + hd, llen)) {2048int used;2049 state->linenr++;2050 used =parse_binary(state, buffer + hd + llen,2051 size - hd - llen, patch);2052if(used <0)2053return-1;2054if(used)2055 patchsize = used + llen;2056else2057 patchsize =0;2058}2059else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2060static const char*binhdr[] = {2061"Binary files ",2062"Files ",2063 NULL,2064};2065int i;2066for(i =0; binhdr[i]; i++) {2067int len =strlen(binhdr[i]);2068if(len < size - hd &&2069!memcmp(binhdr[i], buffer + hd, len)) {2070 state->linenr++;2071 patch->is_binary =1;2072 patchsize = llen;2073break;2074}2075}2076}20772078/* Empty patch cannot be applied if it is a text patch2079 * without metadata change. A binary patch appears2080 * empty to us here.2081 */2082if((state->apply || state->check) &&2083(!patch->is_binary && !metadata_changes(patch))) {2084error(_("patch with only garbage at line%d"), state->linenr);2085return-128;2086}2087}20882089return offset + hdrsize + patchsize;2090}20912092#define swap(a,b) myswap((a),(b),sizeof(a))20932094#define myswap(a, b, size) do { \2095 unsigned char mytmp[size]; \2096 memcpy(mytmp, &a, size); \2097 memcpy(&a, &b, size); \2098 memcpy(&b, mytmp, size); \2099} while (0)21002101static voidreverse_patches(struct patch *p)2102{2103for(; p; p = p->next) {2104struct fragment *frag = p->fragments;21052106swap(p->new_name, p->old_name);2107swap(p->new_mode, p->old_mode);2108swap(p->is_new, p->is_delete);2109swap(p->lines_added, p->lines_deleted);2110swap(p->old_sha1_prefix, p->new_sha1_prefix);21112112for(; frag; frag = frag->next) {2113swap(frag->newpos, frag->oldpos);2114swap(frag->newlines, frag->oldlines);2115}2116}2117}21182119static const char pluses[] =2120"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2121static const char minuses[]=2122"----------------------------------------------------------------------";21232124static voidshow_stats(struct apply_state *state,struct patch *patch)2125{2126struct strbuf qname = STRBUF_INIT;2127char*cp = patch->new_name ? patch->new_name : patch->old_name;2128int max, add, del;21292130quote_c_style(cp, &qname, NULL,0);21312132/*2133 * "scale" the filename2134 */2135 max = state->max_len;2136if(max >50)2137 max =50;21382139if(qname.len > max) {2140 cp =strchr(qname.buf + qname.len +3- max,'/');2141if(!cp)2142 cp = qname.buf + qname.len +3- max;2143strbuf_splice(&qname,0, cp - qname.buf,"...",3);2144}21452146if(patch->is_binary) {2147printf(" %-*s | Bin\n", max, qname.buf);2148strbuf_release(&qname);2149return;2150}21512152printf(" %-*s |", max, qname.buf);2153strbuf_release(&qname);21542155/*2156 * scale the add/delete2157 */2158 max = max + state->max_change >70?70- max : state->max_change;2159 add = patch->lines_added;2160 del = patch->lines_deleted;21612162if(state->max_change >0) {2163int total = ((add + del) * max + state->max_change /2) / state->max_change;2164 add = (add * max + state->max_change /2) / state->max_change;2165 del = total - add;2166}2167printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2168 add, pluses, del, minuses);2169}21702171static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2172{2173switch(st->st_mode & S_IFMT) {2174case S_IFLNK:2175if(strbuf_readlink(buf, path, st->st_size) <0)2176returnerror(_("unable to read symlink%s"), path);2177return0;2178case S_IFREG:2179if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2180returnerror(_("unable to open or read%s"), path);2181convert_to_git(path, buf->buf, buf->len, buf,0);2182return0;2183default:2184return-1;2185}2186}21872188/*2189 * Update the preimage, and the common lines in postimage,2190 * from buffer buf of length len. If postlen is 0 the postimage2191 * is updated in place, otherwise it's updated on a new buffer2192 * of length postlen2193 */21942195static voidupdate_pre_post_images(struct image *preimage,2196struct image *postimage,2197char*buf,2198size_t len,size_t postlen)2199{2200int i, ctx, reduced;2201char*new, *old, *fixed;2202struct image fixed_preimage;22032204/*2205 * Update the preimage with whitespace fixes. Note that we2206 * are not losing preimage->buf -- apply_one_fragment() will2207 * free "oldlines".2208 */2209prepare_image(&fixed_preimage, buf, len,1);2210assert(postlen2211? fixed_preimage.nr == preimage->nr2212: fixed_preimage.nr <= preimage->nr);2213for(i =0; i < fixed_preimage.nr; i++)2214 fixed_preimage.line[i].flag = preimage->line[i].flag;2215free(preimage->line_allocated);2216*preimage = fixed_preimage;22172218/*2219 * Adjust the common context lines in postimage. This can be2220 * done in-place when we are shrinking it with whitespace2221 * fixing, but needs a new buffer when ignoring whitespace or2222 * expanding leading tabs to spaces.2223 *2224 * We trust the caller to tell us if the update can be done2225 * in place (postlen==0) or not.2226 */2227 old = postimage->buf;2228if(postlen)2229new= postimage->buf =xmalloc(postlen);2230else2231new= old;2232 fixed = preimage->buf;22332234for(i = reduced = ctx =0; i < postimage->nr; i++) {2235size_t l_len = postimage->line[i].len;2236if(!(postimage->line[i].flag & LINE_COMMON)) {2237/* an added line -- no counterparts in preimage */2238memmove(new, old, l_len);2239 old += l_len;2240new+= l_len;2241continue;2242}22432244/* a common context -- skip it in the original postimage */2245 old += l_len;22462247/* and find the corresponding one in the fixed preimage */2248while(ctx < preimage->nr &&2249!(preimage->line[ctx].flag & LINE_COMMON)) {2250 fixed += preimage->line[ctx].len;2251 ctx++;2252}22532254/*2255 * preimage is expected to run out, if the caller2256 * fixed addition of trailing blank lines.2257 */2258if(preimage->nr <= ctx) {2259 reduced++;2260continue;2261}22622263/* and copy it in, while fixing the line length */2264 l_len = preimage->line[ctx].len;2265memcpy(new, fixed, l_len);2266new+= l_len;2267 fixed += l_len;2268 postimage->line[i].len = l_len;2269 ctx++;2270}22712272if(postlen2273? postlen <new- postimage->buf2274: postimage->len <new- postimage->buf)2275die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2276(int)postlen, (int) postimage->len, (int)(new- postimage->buf));22772278/* Fix the length of the whole thing */2279 postimage->len =new- postimage->buf;2280 postimage->nr -= reduced;2281}22822283static intline_by_line_fuzzy_match(struct image *img,2284struct image *preimage,2285struct image *postimage,2286unsigned longtry,2287int try_lno,2288int preimage_limit)2289{2290int i;2291size_t imgoff =0;2292size_t preoff =0;2293size_t postlen = postimage->len;2294size_t extra_chars;2295char*buf;2296char*preimage_eof;2297char*preimage_end;2298struct strbuf fixed;2299char*fixed_buf;2300size_t fixed_len;23012302for(i =0; i < preimage_limit; i++) {2303size_t prelen = preimage->line[i].len;2304size_t imglen = img->line[try_lno+i].len;23052306if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2307 preimage->buf + preoff, prelen))2308return0;2309if(preimage->line[i].flag & LINE_COMMON)2310 postlen += imglen - prelen;2311 imgoff += imglen;2312 preoff += prelen;2313}23142315/*2316 * Ok, the preimage matches with whitespace fuzz.2317 *2318 * imgoff now holds the true length of the target that2319 * matches the preimage before the end of the file.2320 *2321 * Count the number of characters in the preimage that fall2322 * beyond the end of the file and make sure that all of them2323 * are whitespace characters. (This can only happen if2324 * we are removing blank lines at the end of the file.)2325 */2326 buf = preimage_eof = preimage->buf + preoff;2327for( ; i < preimage->nr; i++)2328 preoff += preimage->line[i].len;2329 preimage_end = preimage->buf + preoff;2330for( ; buf < preimage_end; buf++)2331if(!isspace(*buf))2332return0;23332334/*2335 * Update the preimage and the common postimage context2336 * lines to use the same whitespace as the target.2337 * If whitespace is missing in the target (i.e.2338 * if the preimage extends beyond the end of the file),2339 * use the whitespace from the preimage.2340 */2341 extra_chars = preimage_end - preimage_eof;2342strbuf_init(&fixed, imgoff + extra_chars);2343strbuf_add(&fixed, img->buf +try, imgoff);2344strbuf_add(&fixed, preimage_eof, extra_chars);2345 fixed_buf =strbuf_detach(&fixed, &fixed_len);2346update_pre_post_images(preimage, postimage,2347 fixed_buf, fixed_len, postlen);2348return1;2349}23502351static intmatch_fragment(struct apply_state *state,2352struct image *img,2353struct image *preimage,2354struct image *postimage,2355unsigned longtry,2356int try_lno,2357unsigned ws_rule,2358int match_beginning,int match_end)2359{2360int i;2361char*fixed_buf, *buf, *orig, *target;2362struct strbuf fixed;2363size_t fixed_len, postlen;2364int preimage_limit;23652366if(preimage->nr + try_lno <= img->nr) {2367/*2368 * The hunk falls within the boundaries of img.2369 */2370 preimage_limit = preimage->nr;2371if(match_end && (preimage->nr + try_lno != img->nr))2372return0;2373}else if(state->ws_error_action == correct_ws_error &&2374(ws_rule & WS_BLANK_AT_EOF)) {2375/*2376 * This hunk extends beyond the end of img, and we are2377 * removing blank lines at the end of the file. This2378 * many lines from the beginning of the preimage must2379 * match with img, and the remainder of the preimage2380 * must be blank.2381 */2382 preimage_limit = img->nr - try_lno;2383}else{2384/*2385 * The hunk extends beyond the end of the img and2386 * we are not removing blanks at the end, so we2387 * should reject the hunk at this position.2388 */2389return0;2390}23912392if(match_beginning && try_lno)2393return0;23942395/* Quick hash check */2396for(i =0; i < preimage_limit; i++)2397if((img->line[try_lno + i].flag & LINE_PATCHED) ||2398(preimage->line[i].hash != img->line[try_lno + i].hash))2399return0;24002401if(preimage_limit == preimage->nr) {2402/*2403 * Do we have an exact match? If we were told to match2404 * at the end, size must be exactly at try+fragsize,2405 * otherwise try+fragsize must be still within the preimage,2406 * and either case, the old piece should match the preimage2407 * exactly.2408 */2409if((match_end2410? (try+ preimage->len == img->len)2411: (try+ preimage->len <= img->len)) &&2412!memcmp(img->buf +try, preimage->buf, preimage->len))2413return1;2414}else{2415/*2416 * The preimage extends beyond the end of img, so2417 * there cannot be an exact match.2418 *2419 * There must be one non-blank context line that match2420 * a line before the end of img.2421 */2422char*buf_end;24232424 buf = preimage->buf;2425 buf_end = buf;2426for(i =0; i < preimage_limit; i++)2427 buf_end += preimage->line[i].len;24282429for( ; buf < buf_end; buf++)2430if(!isspace(*buf))2431break;2432if(buf == buf_end)2433return0;2434}24352436/*2437 * No exact match. If we are ignoring whitespace, run a line-by-line2438 * fuzzy matching. We collect all the line length information because2439 * we need it to adjust whitespace if we match.2440 */2441if(state->ws_ignore_action == ignore_ws_change)2442returnline_by_line_fuzzy_match(img, preimage, postimage,2443try, try_lno, preimage_limit);24442445if(state->ws_error_action != correct_ws_error)2446return0;24472448/*2449 * The hunk does not apply byte-by-byte, but the hash says2450 * it might with whitespace fuzz. We weren't asked to2451 * ignore whitespace, we were asked to correct whitespace2452 * errors, so let's try matching after whitespace correction.2453 *2454 * While checking the preimage against the target, whitespace2455 * errors in both fixed, we count how large the corresponding2456 * postimage needs to be. The postimage prepared by2457 * apply_one_fragment() has whitespace errors fixed on added2458 * lines already, but the common lines were propagated as-is,2459 * which may become longer when their whitespace errors are2460 * fixed.2461 */24622463/* First count added lines in postimage */2464 postlen =0;2465for(i =0; i < postimage->nr; i++) {2466if(!(postimage->line[i].flag & LINE_COMMON))2467 postlen += postimage->line[i].len;2468}24692470/*2471 * The preimage may extend beyond the end of the file,2472 * but in this loop we will only handle the part of the2473 * preimage that falls within the file.2474 */2475strbuf_init(&fixed, preimage->len +1);2476 orig = preimage->buf;2477 target = img->buf +try;2478for(i =0; i < preimage_limit; i++) {2479size_t oldlen = preimage->line[i].len;2480size_t tgtlen = img->line[try_lno + i].len;2481size_t fixstart = fixed.len;2482struct strbuf tgtfix;2483int match;24842485/* Try fixing the line in the preimage */2486ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24872488/* Try fixing the line in the target */2489strbuf_init(&tgtfix, tgtlen);2490ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);24912492/*2493 * If they match, either the preimage was based on2494 * a version before our tree fixed whitespace breakage,2495 * or we are lacking a whitespace-fix patch the tree2496 * the preimage was based on already had (i.e. target2497 * has whitespace breakage, the preimage doesn't).2498 * In either case, we are fixing the whitespace breakages2499 * so we might as well take the fix together with their2500 * real change.2501 */2502 match = (tgtfix.len == fixed.len - fixstart &&2503!memcmp(tgtfix.buf, fixed.buf + fixstart,2504 fixed.len - fixstart));25052506/* Add the length if this is common with the postimage */2507if(preimage->line[i].flag & LINE_COMMON)2508 postlen += tgtfix.len;25092510strbuf_release(&tgtfix);2511if(!match)2512goto unmatch_exit;25132514 orig += oldlen;2515 target += tgtlen;2516}251725182519/*2520 * Now handle the lines in the preimage that falls beyond the2521 * end of the file (if any). They will only match if they are2522 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2523 * false).2524 */2525for( ; i < preimage->nr; i++) {2526size_t fixstart = fixed.len;/* start of the fixed preimage */2527size_t oldlen = preimage->line[i].len;2528int j;25292530/* Try fixing the line in the preimage */2531ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25322533for(j = fixstart; j < fixed.len; j++)2534if(!isspace(fixed.buf[j]))2535goto unmatch_exit;25362537 orig += oldlen;2538}25392540/*2541 * Yes, the preimage is based on an older version that still2542 * has whitespace breakages unfixed, and fixing them makes the2543 * hunk match. Update the context lines in the postimage.2544 */2545 fixed_buf =strbuf_detach(&fixed, &fixed_len);2546if(postlen < postimage->len)2547 postlen =0;2548update_pre_post_images(preimage, postimage,2549 fixed_buf, fixed_len, postlen);2550return1;25512552 unmatch_exit:2553strbuf_release(&fixed);2554return0;2555}25562557static intfind_pos(struct apply_state *state,2558struct image *img,2559struct image *preimage,2560struct image *postimage,2561int line,2562unsigned ws_rule,2563int match_beginning,int match_end)2564{2565int i;2566unsigned long backwards, forwards,try;2567int backwards_lno, forwards_lno, try_lno;25682569/*2570 * If match_beginning or match_end is specified, there is no2571 * point starting from a wrong line that will never match and2572 * wander around and wait for a match at the specified end.2573 */2574if(match_beginning)2575 line =0;2576else if(match_end)2577 line = img->nr - preimage->nr;25782579/*2580 * Because the comparison is unsigned, the following test2581 * will also take care of a negative line number that can2582 * result when match_end and preimage is larger than the target.2583 */2584if((size_t) line > img->nr)2585 line = img->nr;25862587try=0;2588for(i =0; i < line; i++)2589try+= img->line[i].len;25902591/*2592 * There's probably some smart way to do this, but I'll leave2593 * that to the smart and beautiful people. I'm simple and stupid.2594 */2595 backwards =try;2596 backwards_lno = line;2597 forwards =try;2598 forwards_lno = line;2599 try_lno = line;26002601for(i =0; ; i++) {2602if(match_fragment(state, img, preimage, postimage,2603try, try_lno, ws_rule,2604 match_beginning, match_end))2605return try_lno;26062607 again:2608if(backwards_lno ==0&& forwards_lno == img->nr)2609break;26102611if(i &1) {2612if(backwards_lno ==0) {2613 i++;2614goto again;2615}2616 backwards_lno--;2617 backwards -= img->line[backwards_lno].len;2618try= backwards;2619 try_lno = backwards_lno;2620}else{2621if(forwards_lno == img->nr) {2622 i++;2623goto again;2624}2625 forwards += img->line[forwards_lno].len;2626 forwards_lno++;2627try= forwards;2628 try_lno = forwards_lno;2629}26302631}2632return-1;2633}26342635static voidremove_first_line(struct image *img)2636{2637 img->buf += img->line[0].len;2638 img->len -= img->line[0].len;2639 img->line++;2640 img->nr--;2641}26422643static voidremove_last_line(struct image *img)2644{2645 img->len -= img->line[--img->nr].len;2646}26472648/*2649 * The change from "preimage" and "postimage" has been found to2650 * apply at applied_pos (counts in line numbers) in "img".2651 * Update "img" to remove "preimage" and replace it with "postimage".2652 */2653static voidupdate_image(struct apply_state *state,2654struct image *img,2655int applied_pos,2656struct image *preimage,2657struct image *postimage)2658{2659/*2660 * remove the copy of preimage at offset in img2661 * and replace it with postimage2662 */2663int i, nr;2664size_t remove_count, insert_count, applied_at =0;2665char*result;2666int preimage_limit;26672668/*2669 * If we are removing blank lines at the end of img,2670 * the preimage may extend beyond the end.2671 * If that is the case, we must be careful only to2672 * remove the part of the preimage that falls within2673 * the boundaries of img. Initialize preimage_limit2674 * to the number of lines in the preimage that falls2675 * within the boundaries.2676 */2677 preimage_limit = preimage->nr;2678if(preimage_limit > img->nr - applied_pos)2679 preimage_limit = img->nr - applied_pos;26802681for(i =0; i < applied_pos; i++)2682 applied_at += img->line[i].len;26832684 remove_count =0;2685for(i =0; i < preimage_limit; i++)2686 remove_count += img->line[applied_pos + i].len;2687 insert_count = postimage->len;26882689/* Adjust the contents */2690 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2691memcpy(result, img->buf, applied_at);2692memcpy(result + applied_at, postimage->buf, postimage->len);2693memcpy(result + applied_at + postimage->len,2694 img->buf + (applied_at + remove_count),2695 img->len - (applied_at + remove_count));2696free(img->buf);2697 img->buf = result;2698 img->len += insert_count - remove_count;2699 result[img->len] ='\0';27002701/* Adjust the line table */2702 nr = img->nr + postimage->nr - preimage_limit;2703if(preimage_limit < postimage->nr) {2704/*2705 * NOTE: this knows that we never call remove_first_line()2706 * on anything other than pre/post image.2707 */2708REALLOC_ARRAY(img->line, nr);2709 img->line_allocated = img->line;2710}2711if(preimage_limit != postimage->nr)2712memmove(img->line + applied_pos + postimage->nr,2713 img->line + applied_pos + preimage_limit,2714(img->nr - (applied_pos + preimage_limit)) *2715sizeof(*img->line));2716memcpy(img->line + applied_pos,2717 postimage->line,2718 postimage->nr *sizeof(*img->line));2719if(!state->allow_overlap)2720for(i =0; i < postimage->nr; i++)2721 img->line[applied_pos + i].flag |= LINE_PATCHED;2722 img->nr = nr;2723}27242725/*2726 * Use the patch-hunk text in "frag" to prepare two images (preimage and2727 * postimage) for the hunk. Find lines that match "preimage" in "img" and2728 * replace the part of "img" with "postimage" text.2729 */2730static intapply_one_fragment(struct apply_state *state,2731struct image *img,struct fragment *frag,2732int inaccurate_eof,unsigned ws_rule,2733int nth_fragment)2734{2735int match_beginning, match_end;2736const char*patch = frag->patch;2737int size = frag->size;2738char*old, *oldlines;2739struct strbuf newlines;2740int new_blank_lines_at_end =0;2741int found_new_blank_lines_at_end =0;2742int hunk_linenr = frag->linenr;2743unsigned long leading, trailing;2744int pos, applied_pos;2745struct image preimage;2746struct image postimage;27472748memset(&preimage,0,sizeof(preimage));2749memset(&postimage,0,sizeof(postimage));2750 oldlines =xmalloc(size);2751strbuf_init(&newlines, size);27522753 old = oldlines;2754while(size >0) {2755char first;2756int len =linelen(patch, size);2757int plen;2758int added_blank_line =0;2759int is_blank_context =0;2760size_t start;27612762if(!len)2763break;27642765/*2766 * "plen" is how much of the line we should use for2767 * the actual patch data. Normally we just remove the2768 * first character on the line, but if the line is2769 * followed by "\ No newline", then we also remove the2770 * last one (which is the newline, of course).2771 */2772 plen = len -1;2773if(len < size && patch[len] =='\\')2774 plen--;2775 first = *patch;2776if(state->apply_in_reverse) {2777if(first =='-')2778 first ='+';2779else if(first =='+')2780 first ='-';2781}27822783switch(first) {2784case'\n':2785/* Newer GNU diff, empty context line */2786if(plen <0)2787/* ... followed by '\No newline'; nothing */2788break;2789*old++ ='\n';2790strbuf_addch(&newlines,'\n');2791add_line_info(&preimage,"\n",1, LINE_COMMON);2792add_line_info(&postimage,"\n",1, LINE_COMMON);2793 is_blank_context =1;2794break;2795case' ':2796if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2797ws_blank_line(patch +1, plen, ws_rule))2798 is_blank_context =1;2799case'-':2800memcpy(old, patch +1, plen);2801add_line_info(&preimage, old, plen,2802(first ==' '? LINE_COMMON :0));2803 old += plen;2804if(first =='-')2805break;2806/* Fall-through for ' ' */2807case'+':2808/* --no-add does not add new lines */2809if(first =='+'&& state->no_add)2810break;28112812 start = newlines.len;2813if(first !='+'||2814!state->whitespace_error ||2815 state->ws_error_action != correct_ws_error) {2816strbuf_add(&newlines, patch +1, plen);2817}2818else{2819ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2820}2821add_line_info(&postimage, newlines.buf + start, newlines.len - start,2822(first =='+'?0: LINE_COMMON));2823if(first =='+'&&2824(ws_rule & WS_BLANK_AT_EOF) &&2825ws_blank_line(patch +1, plen, ws_rule))2826 added_blank_line =1;2827break;2828case'@':case'\\':2829/* Ignore it, we already handled it */2830break;2831default:2832if(state->apply_verbosely)2833error(_("invalid start of line: '%c'"), first);2834 applied_pos = -1;2835goto out;2836}2837if(added_blank_line) {2838if(!new_blank_lines_at_end)2839 found_new_blank_lines_at_end = hunk_linenr;2840 new_blank_lines_at_end++;2841}2842else if(is_blank_context)2843;2844else2845 new_blank_lines_at_end =0;2846 patch += len;2847 size -= len;2848 hunk_linenr++;2849}2850if(inaccurate_eof &&2851 old > oldlines && old[-1] =='\n'&&2852 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2853 old--;2854strbuf_setlen(&newlines, newlines.len -1);2855}28562857 leading = frag->leading;2858 trailing = frag->trailing;28592860/*2861 * A hunk to change lines at the beginning would begin with2862 * @@ -1,L +N,M @@2863 * but we need to be careful. -U0 that inserts before the second2864 * line also has this pattern.2865 *2866 * And a hunk to add to an empty file would begin with2867 * @@ -0,0 +N,M @@2868 *2869 * In other words, a hunk that is (frag->oldpos <= 1) with or2870 * without leading context must match at the beginning.2871 */2872 match_beginning = (!frag->oldpos ||2873(frag->oldpos ==1&& !state->unidiff_zero));28742875/*2876 * A hunk without trailing lines must match at the end.2877 * However, we simply cannot tell if a hunk must match end2878 * from the lack of trailing lines if the patch was generated2879 * with unidiff without any context.2880 */2881 match_end = !state->unidiff_zero && !trailing;28822883 pos = frag->newpos ? (frag->newpos -1) :0;2884 preimage.buf = oldlines;2885 preimage.len = old - oldlines;2886 postimage.buf = newlines.buf;2887 postimage.len = newlines.len;2888 preimage.line = preimage.line_allocated;2889 postimage.line = postimage.line_allocated;28902891for(;;) {28922893 applied_pos =find_pos(state, img, &preimage, &postimage, pos,2894 ws_rule, match_beginning, match_end);28952896if(applied_pos >=0)2897break;28982899/* Am I at my context limits? */2900if((leading <= state->p_context) && (trailing <= state->p_context))2901break;2902if(match_beginning || match_end) {2903 match_beginning = match_end =0;2904continue;2905}29062907/*2908 * Reduce the number of context lines; reduce both2909 * leading and trailing if they are equal otherwise2910 * just reduce the larger context.2911 */2912if(leading >= trailing) {2913remove_first_line(&preimage);2914remove_first_line(&postimage);2915 pos--;2916 leading--;2917}2918if(trailing > leading) {2919remove_last_line(&preimage);2920remove_last_line(&postimage);2921 trailing--;2922}2923}29242925if(applied_pos >=0) {2926if(new_blank_lines_at_end &&2927 preimage.nr + applied_pos >= img->nr &&2928(ws_rule & WS_BLANK_AT_EOF) &&2929 state->ws_error_action != nowarn_ws_error) {2930record_ws_error(state, WS_BLANK_AT_EOF,"+",1,2931 found_new_blank_lines_at_end);2932if(state->ws_error_action == correct_ws_error) {2933while(new_blank_lines_at_end--)2934remove_last_line(&postimage);2935}2936/*2937 * We would want to prevent write_out_results()2938 * from taking place in apply_patch() that follows2939 * the callchain led us here, which is:2940 * apply_patch->check_patch_list->check_patch->2941 * apply_data->apply_fragments->apply_one_fragment2942 */2943if(state->ws_error_action == die_on_ws_error)2944 state->apply =0;2945}29462947if(state->apply_verbosely && applied_pos != pos) {2948int offset = applied_pos - pos;2949if(state->apply_in_reverse)2950 offset =0- offset;2951fprintf_ln(stderr,2952Q_("Hunk #%dsucceeded at%d(offset%dline).",2953"Hunk #%dsucceeded at%d(offset%dlines).",2954 offset),2955 nth_fragment, applied_pos +1, offset);2956}29572958/*2959 * Warn if it was necessary to reduce the number2960 * of context lines.2961 */2962if((leading != frag->leading) ||2963(trailing != frag->trailing))2964fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2965" to apply fragment at%d"),2966 leading, trailing, applied_pos+1);2967update_image(state, img, applied_pos, &preimage, &postimage);2968}else{2969if(state->apply_verbosely)2970error(_("while searching for:\n%.*s"),2971(int)(old - oldlines), oldlines);2972}29732974out:2975free(oldlines);2976strbuf_release(&newlines);2977free(preimage.line_allocated);2978free(postimage.line_allocated);29792980return(applied_pos <0);2981}29822983static intapply_binary_fragment(struct apply_state *state,2984struct image *img,2985struct patch *patch)2986{2987struct fragment *fragment = patch->fragments;2988unsigned long len;2989void*dst;29902991if(!fragment)2992returnerror(_("missing binary patch data for '%s'"),2993 patch->new_name ?2994 patch->new_name :2995 patch->old_name);29962997/* Binary patch is irreversible without the optional second hunk */2998if(state->apply_in_reverse) {2999if(!fragment->next)3000returnerror("cannot reverse-apply a binary patch "3001"without the reverse hunk to '%s'",3002 patch->new_name3003? patch->new_name : patch->old_name);3004 fragment = fragment->next;3005}3006switch(fragment->binary_patch_method) {3007case BINARY_DELTA_DEFLATED:3008 dst =patch_delta(img->buf, img->len, fragment->patch,3009 fragment->size, &len);3010if(!dst)3011return-1;3012clear_image(img);3013 img->buf = dst;3014 img->len = len;3015return0;3016case BINARY_LITERAL_DEFLATED:3017clear_image(img);3018 img->len = fragment->size;3019 img->buf =xmemdupz(fragment->patch, img->len);3020return0;3021}3022return-1;3023}30243025/*3026 * Replace "img" with the result of applying the binary patch.3027 * The binary patch data itself in patch->fragment is still kept3028 * but the preimage prepared by the caller in "img" is freed here3029 * or in the helper function apply_binary_fragment() this calls.3030 */3031static intapply_binary(struct apply_state *state,3032struct image *img,3033struct patch *patch)3034{3035const char*name = patch->old_name ? patch->old_name : patch->new_name;3036unsigned char sha1[20];30373038/*3039 * For safety, we require patch index line to contain3040 * full 40-byte textual SHA1 for old and new, at least for now.3041 */3042if(strlen(patch->old_sha1_prefix) !=40||3043strlen(patch->new_sha1_prefix) !=40||3044get_sha1_hex(patch->old_sha1_prefix, sha1) ||3045get_sha1_hex(patch->new_sha1_prefix, sha1))3046returnerror("cannot apply binary patch to '%s' "3047"without full index line", name);30483049if(patch->old_name) {3050/*3051 * See if the old one matches what the patch3052 * applies to.3053 */3054hash_sha1_file(img->buf, img->len, blob_type, sha1);3055if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3056returnerror("the patch applies to '%s' (%s), "3057"which does not match the "3058"current contents.",3059 name,sha1_to_hex(sha1));3060}3061else{3062/* Otherwise, the old one must be empty. */3063if(img->len)3064returnerror("the patch applies to an empty "3065"'%s' but it is not empty", name);3066}30673068get_sha1_hex(patch->new_sha1_prefix, sha1);3069if(is_null_sha1(sha1)) {3070clear_image(img);3071return0;/* deletion patch */3072}30733074if(has_sha1_file(sha1)) {3075/* We already have the postimage */3076enum object_type type;3077unsigned long size;3078char*result;30793080 result =read_sha1_file(sha1, &type, &size);3081if(!result)3082returnerror("the necessary postimage%sfor "3083"'%s' cannot be read",3084 patch->new_sha1_prefix, name);3085clear_image(img);3086 img->buf = result;3087 img->len = size;3088}else{3089/*3090 * We have verified buf matches the preimage;3091 * apply the patch data to it, which is stored3092 * in the patch->fragments->{patch,size}.3093 */3094if(apply_binary_fragment(state, img, patch))3095returnerror(_("binary patch does not apply to '%s'"),3096 name);30973098/* verify that the result matches */3099hash_sha1_file(img->buf, img->len, blob_type, sha1);3100if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3101returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3102 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3103}31043105return0;3106}31073108static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3109{3110struct fragment *frag = patch->fragments;3111const char*name = patch->old_name ? patch->old_name : patch->new_name;3112unsigned ws_rule = patch->ws_rule;3113unsigned inaccurate_eof = patch->inaccurate_eof;3114int nth =0;31153116if(patch->is_binary)3117returnapply_binary(state, img, patch);31183119while(frag) {3120 nth++;3121if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3122error(_("patch failed:%s:%ld"), name, frag->oldpos);3123if(!state->apply_with_reject)3124return-1;3125 frag->rejected =1;3126}3127 frag = frag->next;3128}3129return0;3130}31313132static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3133{3134if(S_ISGITLINK(mode)) {3135strbuf_grow(buf,100);3136strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3137}else{3138enum object_type type;3139unsigned long sz;3140char*result;31413142 result =read_sha1_file(sha1, &type, &sz);3143if(!result)3144return-1;3145/* XXX read_sha1_file NUL-terminates */3146strbuf_attach(buf, result, sz, sz +1);3147}3148return0;3149}31503151static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3152{3153if(!ce)3154return0;3155returnread_blob_object(buf, ce->sha1, ce->ce_mode);3156}31573158static struct patch *in_fn_table(struct apply_state *state,const char*name)3159{3160struct string_list_item *item;31613162if(name == NULL)3163return NULL;31643165 item =string_list_lookup(&state->fn_table, name);3166if(item != NULL)3167return(struct patch *)item->util;31683169return NULL;3170}31713172/*3173 * item->util in the filename table records the status of the path.3174 * Usually it points at a patch (whose result records the contents3175 * of it after applying it), but it could be PATH_WAS_DELETED for a3176 * path that a previously applied patch has already removed, or3177 * PATH_TO_BE_DELETED for a path that a later patch would remove.3178 *3179 * The latter is needed to deal with a case where two paths A and B3180 * are swapped by first renaming A to B and then renaming B to A;3181 * moving A to B should not be prevented due to presence of B as we3182 * will remove it in a later patch.3183 */3184#define PATH_TO_BE_DELETED ((struct patch *) -2)3185#define PATH_WAS_DELETED ((struct patch *) -1)31863187static intto_be_deleted(struct patch *patch)3188{3189return patch == PATH_TO_BE_DELETED;3190}31913192static intwas_deleted(struct patch *patch)3193{3194return patch == PATH_WAS_DELETED;3195}31963197static voidadd_to_fn_table(struct apply_state *state,struct patch *patch)3198{3199struct string_list_item *item;32003201/*3202 * Always add new_name unless patch is a deletion3203 * This should cover the cases for normal diffs,3204 * file creations and copies3205 */3206if(patch->new_name != NULL) {3207 item =string_list_insert(&state->fn_table, patch->new_name);3208 item->util = patch;3209}32103211/*3212 * store a failure on rename/deletion cases because3213 * later chunks shouldn't patch old names3214 */3215if((patch->new_name == NULL) || (patch->is_rename)) {3216 item =string_list_insert(&state->fn_table, patch->old_name);3217 item->util = PATH_WAS_DELETED;3218}3219}32203221static voidprepare_fn_table(struct apply_state *state,struct patch *patch)3222{3223/*3224 * store information about incoming file deletion3225 */3226while(patch) {3227if((patch->new_name == NULL) || (patch->is_rename)) {3228struct string_list_item *item;3229 item =string_list_insert(&state->fn_table, patch->old_name);3230 item->util = PATH_TO_BE_DELETED;3231}3232 patch = patch->next;3233}3234}32353236static intcheckout_target(struct index_state *istate,3237struct cache_entry *ce,struct stat *st)3238{3239struct checkout costate;32403241memset(&costate,0,sizeof(costate));3242 costate.base_dir ="";3243 costate.refresh_cache =1;3244 costate.istate = istate;3245if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3246returnerror(_("cannot checkout%s"), ce->name);3247return0;3248}32493250static struct patch *previous_patch(struct apply_state *state,3251struct patch *patch,3252int*gone)3253{3254struct patch *previous;32553256*gone =0;3257if(patch->is_copy || patch->is_rename)3258return NULL;/* "git" patches do not depend on the order */32593260 previous =in_fn_table(state, patch->old_name);3261if(!previous)3262return NULL;32633264if(to_be_deleted(previous))3265return NULL;/* the deletion hasn't happened yet */32663267if(was_deleted(previous))3268*gone =1;32693270return previous;3271}32723273static intverify_index_match(const struct cache_entry *ce,struct stat *st)3274{3275if(S_ISGITLINK(ce->ce_mode)) {3276if(!S_ISDIR(st->st_mode))3277return-1;3278return0;3279}3280returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3281}32823283#define SUBMODULE_PATCH_WITHOUT_INDEX 132843285static intload_patch_target(struct apply_state *state,3286struct strbuf *buf,3287const struct cache_entry *ce,3288struct stat *st,3289const char*name,3290unsigned expected_mode)3291{3292if(state->cached || state->check_index) {3293if(read_file_or_gitlink(ce, buf))3294returnerror(_("failed to read%s"), name);3295}else if(name) {3296if(S_ISGITLINK(expected_mode)) {3297if(ce)3298returnread_file_or_gitlink(ce, buf);3299else3300return SUBMODULE_PATCH_WITHOUT_INDEX;3301}else if(has_symlink_leading_path(name,strlen(name))) {3302returnerror(_("reading from '%s' beyond a symbolic link"), name);3303}else{3304if(read_old_data(st, name, buf))3305returnerror(_("failed to read%s"), name);3306}3307}3308return0;3309}33103311/*3312 * We are about to apply "patch"; populate the "image" with the3313 * current version we have, from the working tree or from the index,3314 * depending on the situation e.g. --cached/--index. If we are3315 * applying a non-git patch that incrementally updates the tree,3316 * we read from the result of a previous diff.3317 */3318static intload_preimage(struct apply_state *state,3319struct image *image,3320struct patch *patch,struct stat *st,3321const struct cache_entry *ce)3322{3323struct strbuf buf = STRBUF_INIT;3324size_t len;3325char*img;3326struct patch *previous;3327int status;33283329 previous =previous_patch(state, patch, &status);3330if(status)3331returnerror(_("path%shas been renamed/deleted"),3332 patch->old_name);3333if(previous) {3334/* We have a patched copy in memory; use that. */3335strbuf_add(&buf, previous->result, previous->resultsize);3336}else{3337 status =load_patch_target(state, &buf, ce, st,3338 patch->old_name, patch->old_mode);3339if(status <0)3340return status;3341else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3342/*3343 * There is no way to apply subproject3344 * patch without looking at the index.3345 * NEEDSWORK: shouldn't this be flagged3346 * as an error???3347 */3348free_fragment_list(patch->fragments);3349 patch->fragments = NULL;3350}else if(status) {3351returnerror(_("failed to read%s"), patch->old_name);3352}3353}33543355 img =strbuf_detach(&buf, &len);3356prepare_image(image, img, len, !patch->is_binary);3357return0;3358}33593360static intthree_way_merge(struct image *image,3361char*path,3362const unsigned char*base,3363const unsigned char*ours,3364const unsigned char*theirs)3365{3366 mmfile_t base_file, our_file, their_file;3367 mmbuffer_t result = { NULL };3368int status;33693370read_mmblob(&base_file, base);3371read_mmblob(&our_file, ours);3372read_mmblob(&their_file, theirs);3373 status =ll_merge(&result, path,3374&base_file,"base",3375&our_file,"ours",3376&their_file,"theirs", NULL);3377free(base_file.ptr);3378free(our_file.ptr);3379free(their_file.ptr);3380if(status <0|| !result.ptr) {3381free(result.ptr);3382return-1;3383}3384clear_image(image);3385 image->buf = result.ptr;3386 image->len = result.size;33873388return status;3389}33903391/*3392 * When directly falling back to add/add three-way merge, we read from3393 * the current contents of the new_name. In no cases other than that3394 * this function will be called.3395 */3396static intload_current(struct apply_state *state,3397struct image *image,3398struct patch *patch)3399{3400struct strbuf buf = STRBUF_INIT;3401int status, pos;3402size_t len;3403char*img;3404struct stat st;3405struct cache_entry *ce;3406char*name = patch->new_name;3407unsigned mode = patch->new_mode;34083409if(!patch->is_new)3410die("BUG: patch to%sis not a creation", patch->old_name);34113412 pos =cache_name_pos(name,strlen(name));3413if(pos <0)3414returnerror(_("%s: does not exist in index"), name);3415 ce = active_cache[pos];3416if(lstat(name, &st)) {3417if(errno != ENOENT)3418returnerror(_("%s:%s"), name,strerror(errno));3419if(checkout_target(&the_index, ce, &st))3420return-1;3421}3422if(verify_index_match(ce, &st))3423returnerror(_("%s: does not match index"), name);34243425 status =load_patch_target(state, &buf, ce, &st, name, mode);3426if(status <0)3427return status;3428else if(status)3429return-1;3430 img =strbuf_detach(&buf, &len);3431prepare_image(image, img, len, !patch->is_binary);3432return0;3433}34343435static inttry_threeway(struct apply_state *state,3436struct image *image,3437struct patch *patch,3438struct stat *st,3439const struct cache_entry *ce)3440{3441unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3442struct strbuf buf = STRBUF_INIT;3443size_t len;3444int status;3445char*img;3446struct image tmp_image;34473448/* No point falling back to 3-way merge in these cases */3449if(patch->is_delete ||3450S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3451return-1;34523453/* Preimage the patch was prepared for */3454if(patch->is_new)3455write_sha1_file("",0, blob_type, pre_sha1);3456else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3457read_blob_object(&buf, pre_sha1, patch->old_mode))3458returnerror("repository lacks the necessary blob to fall back on 3-way merge.");34593460fprintf(stderr,"Falling back to three-way merge...\n");34613462 img =strbuf_detach(&buf, &len);3463prepare_image(&tmp_image, img, len,1);3464/* Apply the patch to get the post image */3465if(apply_fragments(state, &tmp_image, patch) <0) {3466clear_image(&tmp_image);3467return-1;3468}3469/* post_sha1[] is theirs */3470write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3471clear_image(&tmp_image);34723473/* our_sha1[] is ours */3474if(patch->is_new) {3475if(load_current(state, &tmp_image, patch))3476returnerror("cannot read the current contents of '%s'",3477 patch->new_name);3478}else{3479if(load_preimage(state, &tmp_image, patch, st, ce))3480returnerror("cannot read the current contents of '%s'",3481 patch->old_name);3482}3483write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3484clear_image(&tmp_image);34853486/* in-core three-way merge between post and our using pre as base */3487 status =three_way_merge(image, patch->new_name,3488 pre_sha1, our_sha1, post_sha1);3489if(status <0) {3490fprintf(stderr,"Failed to fall back on three-way merge...\n");3491return status;3492}34933494if(status) {3495 patch->conflicted_threeway =1;3496if(patch->is_new)3497oidclr(&patch->threeway_stage[0]);3498else3499hashcpy(patch->threeway_stage[0].hash, pre_sha1);3500hashcpy(patch->threeway_stage[1].hash, our_sha1);3501hashcpy(patch->threeway_stage[2].hash, post_sha1);3502fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3503}else{3504fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3505}3506return0;3507}35083509static intapply_data(struct apply_state *state,struct patch *patch,3510struct stat *st,const struct cache_entry *ce)3511{3512struct image image;35133514if(load_preimage(state, &image, patch, st, ce) <0)3515return-1;35163517if(patch->direct_to_threeway ||3518apply_fragments(state, &image, patch) <0) {3519/* Note: with --reject, apply_fragments() returns 0 */3520if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3521return-1;3522}3523 patch->result = image.buf;3524 patch->resultsize = image.len;3525add_to_fn_table(state, patch);3526free(image.line_allocated);35273528if(0< patch->is_delete && patch->resultsize)3529returnerror(_("removal patch leaves file contents"));35303531return0;3532}35333534/*3535 * If "patch" that we are looking at modifies or deletes what we have,3536 * we would want it not to lose any local modification we have, either3537 * in the working tree or in the index.3538 *3539 * This also decides if a non-git patch is a creation patch or a3540 * modification to an existing empty file. We do not check the state3541 * of the current tree for a creation patch in this function; the caller3542 * check_patch() separately makes sure (and errors out otherwise) that3543 * the path the patch creates does not exist in the current tree.3544 */3545static intcheck_preimage(struct apply_state *state,3546struct patch *patch,3547struct cache_entry **ce,3548struct stat *st)3549{3550const char*old_name = patch->old_name;3551struct patch *previous = NULL;3552int stat_ret =0, status;3553unsigned st_mode =0;35543555if(!old_name)3556return0;35573558assert(patch->is_new <=0);3559 previous =previous_patch(state, patch, &status);35603561if(status)3562returnerror(_("path%shas been renamed/deleted"), old_name);3563if(previous) {3564 st_mode = previous->new_mode;3565}else if(!state->cached) {3566 stat_ret =lstat(old_name, st);3567if(stat_ret && errno != ENOENT)3568returnerror(_("%s:%s"), old_name,strerror(errno));3569}35703571if(state->check_index && !previous) {3572int pos =cache_name_pos(old_name,strlen(old_name));3573if(pos <0) {3574if(patch->is_new <0)3575goto is_new;3576returnerror(_("%s: does not exist in index"), old_name);3577}3578*ce = active_cache[pos];3579if(stat_ret <0) {3580if(checkout_target(&the_index, *ce, st))3581return-1;3582}3583if(!state->cached &&verify_index_match(*ce, st))3584returnerror(_("%s: does not match index"), old_name);3585if(state->cached)3586 st_mode = (*ce)->ce_mode;3587}else if(stat_ret <0) {3588if(patch->is_new <0)3589goto is_new;3590returnerror(_("%s:%s"), old_name,strerror(errno));3591}35923593if(!state->cached && !previous)3594 st_mode =ce_mode_from_stat(*ce, st->st_mode);35953596if(patch->is_new <0)3597 patch->is_new =0;3598if(!patch->old_mode)3599 patch->old_mode = st_mode;3600if((st_mode ^ patch->old_mode) & S_IFMT)3601returnerror(_("%s: wrong type"), old_name);3602if(st_mode != patch->old_mode)3603warning(_("%shas type%o, expected%o"),3604 old_name, st_mode, patch->old_mode);3605if(!patch->new_mode && !patch->is_delete)3606 patch->new_mode = st_mode;3607return0;36083609 is_new:3610 patch->is_new =1;3611 patch->is_delete =0;3612free(patch->old_name);3613 patch->old_name = NULL;3614return0;3615}361636173618#define EXISTS_IN_INDEX 13619#define EXISTS_IN_WORKTREE 236203621static intcheck_to_create(struct apply_state *state,3622const char*new_name,3623int ok_if_exists)3624{3625struct stat nst;36263627if(state->check_index &&3628cache_name_pos(new_name,strlen(new_name)) >=0&&3629!ok_if_exists)3630return EXISTS_IN_INDEX;3631if(state->cached)3632return0;36333634if(!lstat(new_name, &nst)) {3635if(S_ISDIR(nst.st_mode) || ok_if_exists)3636return0;3637/*3638 * A leading component of new_name might be a symlink3639 * that is going to be removed with this patch, but3640 * still pointing at somewhere that has the path.3641 * In such a case, path "new_name" does not exist as3642 * far as git is concerned.3643 */3644if(has_symlink_leading_path(new_name,strlen(new_name)))3645return0;36463647return EXISTS_IN_WORKTREE;3648}else if((errno != ENOENT) && (errno != ENOTDIR)) {3649returnerror("%s:%s", new_name,strerror(errno));3650}3651return0;3652}36533654static uintptr_tregister_symlink_changes(struct apply_state *state,3655const char*path,3656uintptr_t what)3657{3658struct string_list_item *ent;36593660 ent =string_list_lookup(&state->symlink_changes, path);3661if(!ent) {3662 ent =string_list_insert(&state->symlink_changes, path);3663 ent->util = (void*)0;3664}3665 ent->util = (void*)(what | ((uintptr_t)ent->util));3666return(uintptr_t)ent->util;3667}36683669static uintptr_tcheck_symlink_changes(struct apply_state *state,const char*path)3670{3671struct string_list_item *ent;36723673 ent =string_list_lookup(&state->symlink_changes, path);3674if(!ent)3675return0;3676return(uintptr_t)ent->util;3677}36783679static voidprepare_symlink_changes(struct apply_state *state,struct patch *patch)3680{3681for( ; patch; patch = patch->next) {3682if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3683(patch->is_rename || patch->is_delete))3684/* the symlink at patch->old_name is removed */3685register_symlink_changes(state, patch->old_name, APPLY_SYMLINK_GOES_AWAY);36863687if(patch->new_name &&S_ISLNK(patch->new_mode))3688/* the symlink at patch->new_name is created or remains */3689register_symlink_changes(state, patch->new_name, APPLY_SYMLINK_IN_RESULT);3690}3691}36923693static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3694{3695do{3696unsigned int change;36973698while(--name->len && name->buf[name->len] !='/')3699;/* scan backwards */3700if(!name->len)3701break;3702 name->buf[name->len] ='\0';3703 change =check_symlink_changes(state, name->buf);3704if(change & APPLY_SYMLINK_IN_RESULT)3705return1;3706if(change & APPLY_SYMLINK_GOES_AWAY)3707/*3708 * This cannot be "return 0", because we may3709 * see a new one created at a higher level.3710 */3711continue;37123713/* otherwise, check the preimage */3714if(state->check_index) {3715struct cache_entry *ce;37163717 ce =cache_file_exists(name->buf, name->len, ignore_case);3718if(ce &&S_ISLNK(ce->ce_mode))3719return1;3720}else{3721struct stat st;3722if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3723return1;3724}3725}while(1);3726return0;3727}37283729static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3730{3731int ret;3732struct strbuf name = STRBUF_INIT;37333734assert(*name_ !='\0');3735strbuf_addstr(&name, name_);3736 ret =path_is_beyond_symlink_1(state, &name);3737strbuf_release(&name);37383739return ret;3740}37413742static voiddie_on_unsafe_path(struct patch *patch)3743{3744const char*old_name = NULL;3745const char*new_name = NULL;3746if(patch->is_delete)3747 old_name = patch->old_name;3748else if(!patch->is_new && !patch->is_copy)3749 old_name = patch->old_name;3750if(!patch->is_delete)3751 new_name = patch->new_name;37523753if(old_name && !verify_path(old_name))3754die(_("invalid path '%s'"), old_name);3755if(new_name && !verify_path(new_name))3756die(_("invalid path '%s'"), new_name);3757}37583759/*3760 * Check and apply the patch in-core; leave the result in patch->result3761 * for the caller to write it out to the final destination.3762 */3763static intcheck_patch(struct apply_state *state,struct patch *patch)3764{3765struct stat st;3766const char*old_name = patch->old_name;3767const char*new_name = patch->new_name;3768const char*name = old_name ? old_name : new_name;3769struct cache_entry *ce = NULL;3770struct patch *tpatch;3771int ok_if_exists;3772int status;37733774 patch->rejected =1;/* we will drop this after we succeed */37753776 status =check_preimage(state, patch, &ce, &st);3777if(status)3778return status;3779 old_name = patch->old_name;37803781/*3782 * A type-change diff is always split into a patch to delete3783 * old, immediately followed by a patch to create new (see3784 * diff.c::run_diff()); in such a case it is Ok that the entry3785 * to be deleted by the previous patch is still in the working3786 * tree and in the index.3787 *3788 * A patch to swap-rename between A and B would first rename A3789 * to B and then rename B to A. While applying the first one,3790 * the presence of B should not stop A from getting renamed to3791 * B; ask to_be_deleted() about the later rename. Removal of3792 * B and rename from A to B is handled the same way by asking3793 * was_deleted().3794 */3795if((tpatch =in_fn_table(state, new_name)) &&3796(was_deleted(tpatch) ||to_be_deleted(tpatch)))3797 ok_if_exists =1;3798else3799 ok_if_exists =0;38003801if(new_name &&3802((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3803int err =check_to_create(state, new_name, ok_if_exists);38043805if(err && state->threeway) {3806 patch->direct_to_threeway =1;3807}else switch(err) {3808case0:3809break;/* happy */3810case EXISTS_IN_INDEX:3811returnerror(_("%s: already exists in index"), new_name);3812break;3813case EXISTS_IN_WORKTREE:3814returnerror(_("%s: already exists in working directory"),3815 new_name);3816default:3817return err;3818}38193820if(!patch->new_mode) {3821if(0< patch->is_new)3822 patch->new_mode = S_IFREG |0644;3823else3824 patch->new_mode = patch->old_mode;3825}3826}38273828if(new_name && old_name) {3829int same = !strcmp(old_name, new_name);3830if(!patch->new_mode)3831 patch->new_mode = patch->old_mode;3832if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3833if(same)3834returnerror(_("new mode (%o) of%sdoes not "3835"match old mode (%o)"),3836 patch->new_mode, new_name,3837 patch->old_mode);3838else3839returnerror(_("new mode (%o) of%sdoes not "3840"match old mode (%o) of%s"),3841 patch->new_mode, new_name,3842 patch->old_mode, old_name);3843}3844}38453846if(!state->unsafe_paths)3847die_on_unsafe_path(patch);38483849/*3850 * An attempt to read from or delete a path that is beyond a3851 * symbolic link will be prevented by load_patch_target() that3852 * is called at the beginning of apply_data() so we do not3853 * have to worry about a patch marked with "is_delete" bit3854 * here. We however need to make sure that the patch result3855 * is not deposited to a path that is beyond a symbolic link3856 * here.3857 */3858if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3859returnerror(_("affected file '%s' is beyond a symbolic link"),3860 patch->new_name);38613862if(apply_data(state, patch, &st, ce) <0)3863returnerror(_("%s: patch does not apply"), name);3864 patch->rejected =0;3865return0;3866}38673868static intcheck_patch_list(struct apply_state *state,struct patch *patch)3869{3870int err =0;38713872prepare_symlink_changes(state, patch);3873prepare_fn_table(state, patch);3874while(patch) {3875if(state->apply_verbosely)3876say_patch_name(stderr,3877_("Checking patch%s..."), patch);3878 err |=check_patch(state, patch);3879 patch = patch->next;3880}3881return err;3882}38833884/* This function tries to read the sha1 from the current index */3885static intget_current_sha1(const char*path,unsigned char*sha1)3886{3887int pos;38883889if(read_cache() <0)3890return-1;3891 pos =cache_name_pos(path,strlen(path));3892if(pos <0)3893return-1;3894hashcpy(sha1, active_cache[pos]->sha1);3895return0;3896}38973898static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3899{3900/*3901 * A usable gitlink patch has only one fragment (hunk) that looks like:3902 * @@ -1 +1 @@3903 * -Subproject commit <old sha1>3904 * +Subproject commit <new sha1>3905 * or3906 * @@ -1 +0,0 @@3907 * -Subproject commit <old sha1>3908 * for a removal patch.3909 */3910struct fragment *hunk = p->fragments;3911static const char heading[] ="-Subproject commit ";3912char*preimage;39133914if(/* does the patch have only one hunk? */3915 hunk && !hunk->next &&3916/* is its preimage one line? */3917 hunk->oldpos ==1&& hunk->oldlines ==1&&3918/* does preimage begin with the heading? */3919(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3920starts_with(++preimage, heading) &&3921/* does it record full SHA-1? */3922!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3923 preimage[sizeof(heading) +40-1] =='\n'&&3924/* does the abbreviated name on the index line agree with it? */3925starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3926return0;/* it all looks fine */39273928/* we may have full object name on the index line */3929returnget_sha1_hex(p->old_sha1_prefix, sha1);3930}39313932/* Build an index that contains the just the files needed for a 3way merge */3933static voidbuild_fake_ancestor(struct patch *list,const char*filename)3934{3935struct patch *patch;3936struct index_state result = { NULL };3937static struct lock_file lock;39383939/* Once we start supporting the reverse patch, it may be3940 * worth showing the new sha1 prefix, but until then...3941 */3942for(patch = list; patch; patch = patch->next) {3943unsigned char sha1[20];3944struct cache_entry *ce;3945const char*name;39463947 name = patch->old_name ? patch->old_name : patch->new_name;3948if(0< patch->is_new)3949continue;39503951if(S_ISGITLINK(patch->old_mode)) {3952if(!preimage_sha1_in_gitlink_patch(patch, sha1))3953;/* ok, the textual part looks sane */3954else3955die("sha1 information is lacking or useless for submodule%s",3956 name);3957}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {3958;/* ok */3959}else if(!patch->lines_added && !patch->lines_deleted) {3960/* mode-only change: update the current */3961if(get_current_sha1(patch->old_name, sha1))3962die("mode change for%s, which is not "3963"in current HEAD", name);3964}else3965die("sha1 information is lacking or useless "3966"(%s).", name);39673968 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);3969if(!ce)3970die(_("make_cache_entry failed for path '%s'"), name);3971if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3972die("Could not add%sto temporary index", name);3973}39743975hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);3976if(write_locked_index(&result, &lock, COMMIT_LOCK))3977die("Could not write temporary index to%s", filename);39783979discard_index(&result);3980}39813982static voidstat_patch_list(struct apply_state *state,struct patch *patch)3983{3984int files, adds, dels;39853986for(files = adds = dels =0; patch ; patch = patch->next) {3987 files++;3988 adds += patch->lines_added;3989 dels += patch->lines_deleted;3990show_stats(state, patch);3991}39923993print_stat_summary(stdout, files, adds, dels);3994}39953996static voidnumstat_patch_list(struct apply_state *state,3997struct patch *patch)3998{3999for( ; patch; patch = patch->next) {4000const char*name;4001 name = patch->new_name ? patch->new_name : patch->old_name;4002if(patch->is_binary)4003printf("-\t-\t");4004else4005printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4006write_name_quoted(name, stdout, state->line_termination);4007}4008}40094010static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4011{4012if(mode)4013printf("%smode%06o%s\n", newdelete, mode, name);4014else4015printf("%s %s\n", newdelete, name);4016}40174018static voidshow_mode_change(struct patch *p,int show_name)4019{4020if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4021if(show_name)4022printf(" mode change%06o =>%06o%s\n",4023 p->old_mode, p->new_mode, p->new_name);4024else4025printf(" mode change%06o =>%06o\n",4026 p->old_mode, p->new_mode);4027}4028}40294030static voidshow_rename_copy(struct patch *p)4031{4032const char*renamecopy = p->is_rename ?"rename":"copy";4033const char*old, *new;40344035/* Find common prefix */4036 old = p->old_name;4037new= p->new_name;4038while(1) {4039const char*slash_old, *slash_new;4040 slash_old =strchr(old,'/');4041 slash_new =strchr(new,'/');4042if(!slash_old ||4043!slash_new ||4044 slash_old - old != slash_new -new||4045memcmp(old,new, slash_new -new))4046break;4047 old = slash_old +1;4048new= slash_new +1;4049}4050/* p->old_name thru old is the common prefix, and old and new4051 * through the end of names are renames4052 */4053if(old != p->old_name)4054printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4055(int)(old - p->old_name), p->old_name,4056 old,new, p->score);4057else4058printf("%s %s=>%s(%d%%)\n", renamecopy,4059 p->old_name, p->new_name, p->score);4060show_mode_change(p,0);4061}40624063static voidsummary_patch_list(struct patch *patch)4064{4065struct patch *p;40664067for(p = patch; p; p = p->next) {4068if(p->is_new)4069show_file_mode_name("create", p->new_mode, p->new_name);4070else if(p->is_delete)4071show_file_mode_name("delete", p->old_mode, p->old_name);4072else{4073if(p->is_rename || p->is_copy)4074show_rename_copy(p);4075else{4076if(p->score) {4077printf(" rewrite%s(%d%%)\n",4078 p->new_name, p->score);4079show_mode_change(p,0);4080}4081else4082show_mode_change(p,1);4083}4084}4085}4086}40874088static voidpatch_stats(struct apply_state *state,struct patch *patch)4089{4090int lines = patch->lines_added + patch->lines_deleted;40914092if(lines > state->max_change)4093 state->max_change = lines;4094if(patch->old_name) {4095int len =quote_c_style(patch->old_name, NULL, NULL,0);4096if(!len)4097 len =strlen(patch->old_name);4098if(len > state->max_len)4099 state->max_len = len;4100}4101if(patch->new_name) {4102int len =quote_c_style(patch->new_name, NULL, NULL,0);4103if(!len)4104 len =strlen(patch->new_name);4105if(len > state->max_len)4106 state->max_len = len;4107}4108}41094110static voidremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4111{4112if(state->update_index) {4113if(remove_file_from_cache(patch->old_name) <0)4114die(_("unable to remove%sfrom index"), patch->old_name);4115}4116if(!state->cached) {4117if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4118remove_path(patch->old_name);4119}4120}4121}41224123static voidadd_index_file(struct apply_state *state,4124const char*path,4125unsigned mode,4126void*buf,4127unsigned long size)4128{4129struct stat st;4130struct cache_entry *ce;4131int namelen =strlen(path);4132unsigned ce_size =cache_entry_size(namelen);41334134if(!state->update_index)4135return;41364137 ce =xcalloc(1, ce_size);4138memcpy(ce->name, path, namelen);4139 ce->ce_mode =create_ce_mode(mode);4140 ce->ce_flags =create_ce_flags(0);4141 ce->ce_namelen = namelen;4142if(S_ISGITLINK(mode)) {4143const char*s;41444145if(!skip_prefix(buf,"Subproject commit ", &s) ||4146get_sha1_hex(s, ce->sha1))4147die(_("corrupt patch for submodule%s"), path);4148}else{4149if(!state->cached) {4150if(lstat(path, &st) <0)4151die_errno(_("unable to stat newly created file '%s'"),4152 path);4153fill_stat_cache_info(ce, &st);4154}4155if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4156die(_("unable to create backing store for newly created file%s"), path);4157}4158if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4159die(_("unable to add cache entry for%s"), path);4160}41614162static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4163{4164int fd;4165struct strbuf nbuf = STRBUF_INIT;41664167if(S_ISGITLINK(mode)) {4168struct stat st;4169if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4170return0;4171returnmkdir(path,0777);4172}41734174if(has_symlinks &&S_ISLNK(mode))4175/* Although buf:size is counted string, it also is NUL4176 * terminated.4177 */4178returnsymlink(buf, path);41794180 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4181if(fd <0)4182return-1;41834184if(convert_to_working_tree(path, buf, size, &nbuf)) {4185 size = nbuf.len;4186 buf = nbuf.buf;4187}4188write_or_die(fd, buf, size);4189strbuf_release(&nbuf);41904191if(close(fd) <0)4192die_errno(_("closing file '%s'"), path);4193return0;4194}41954196/*4197 * We optimistically assume that the directories exist,4198 * which is true 99% of the time anyway. If they don't,4199 * we create them and try again.4200 */4201static voidcreate_one_file(struct apply_state *state,4202char*path,4203unsigned mode,4204const char*buf,4205unsigned long size)4206{4207if(state->cached)4208return;4209if(!try_create_file(path, mode, buf, size))4210return;42114212if(errno == ENOENT) {4213if(safe_create_leading_directories(path))4214return;4215if(!try_create_file(path, mode, buf, size))4216return;4217}42184219if(errno == EEXIST || errno == EACCES) {4220/* We may be trying to create a file where a directory4221 * used to be.4222 */4223struct stat st;4224if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4225 errno = EEXIST;4226}42274228if(errno == EEXIST) {4229unsigned int nr =getpid();42304231for(;;) {4232char newpath[PATH_MAX];4233mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4234if(!try_create_file(newpath, mode, buf, size)) {4235if(!rename(newpath, path))4236return;4237unlink_or_warn(newpath);4238break;4239}4240if(errno != EEXIST)4241break;4242++nr;4243}4244}4245die_errno(_("unable to write file '%s' mode%o"), path, mode);4246}42474248static voidadd_conflicted_stages_file(struct apply_state *state,4249struct patch *patch)4250{4251int stage, namelen;4252unsigned ce_size, mode;4253struct cache_entry *ce;42544255if(!state->update_index)4256return;4257 namelen =strlen(patch->new_name);4258 ce_size =cache_entry_size(namelen);4259 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);42604261remove_file_from_cache(patch->new_name);4262for(stage =1; stage <4; stage++) {4263if(is_null_oid(&patch->threeway_stage[stage -1]))4264continue;4265 ce =xcalloc(1, ce_size);4266memcpy(ce->name, patch->new_name, namelen);4267 ce->ce_mode =create_ce_mode(mode);4268 ce->ce_flags =create_ce_flags(stage);4269 ce->ce_namelen = namelen;4270hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4271if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4272die(_("unable to add cache entry for%s"), patch->new_name);4273}4274}42754276static voidcreate_file(struct apply_state *state,struct patch *patch)4277{4278char*path = patch->new_name;4279unsigned mode = patch->new_mode;4280unsigned long size = patch->resultsize;4281char*buf = patch->result;42824283if(!mode)4284 mode = S_IFREG |0644;4285create_one_file(state, path, mode, buf, size);42864287if(patch->conflicted_threeway)4288add_conflicted_stages_file(state, patch);4289else4290add_index_file(state, path, mode, buf, size);4291}42924293/* phase zero is to remove, phase one is to create */4294static voidwrite_out_one_result(struct apply_state *state,4295struct patch *patch,4296int phase)4297{4298if(patch->is_delete >0) {4299if(phase ==0)4300remove_file(state, patch,1);4301return;4302}4303if(patch->is_new >0|| patch->is_copy) {4304if(phase ==1)4305create_file(state, patch);4306return;4307}4308/*4309 * Rename or modification boils down to the same4310 * thing: remove the old, write the new4311 */4312if(phase ==0)4313remove_file(state, patch, patch->is_rename);4314if(phase ==1)4315create_file(state, patch);4316}43174318static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4319{4320FILE*rej;4321char namebuf[PATH_MAX];4322struct fragment *frag;4323int cnt =0;4324struct strbuf sb = STRBUF_INIT;43254326for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4327if(!frag->rejected)4328continue;4329 cnt++;4330}43314332if(!cnt) {4333if(state->apply_verbosely)4334say_patch_name(stderr,4335_("Applied patch%scleanly."), patch);4336return0;4337}43384339/* This should not happen, because a removal patch that leaves4340 * contents are marked "rejected" at the patch level.4341 */4342if(!patch->new_name)4343die(_("internal error"));43444345/* Say this even without --verbose */4346strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4347"Applying patch %%swith%drejects...",4348 cnt),4349 cnt);4350say_patch_name(stderr, sb.buf, patch);4351strbuf_release(&sb);43524353 cnt =strlen(patch->new_name);4354if(ARRAY_SIZE(namebuf) <= cnt +5) {4355 cnt =ARRAY_SIZE(namebuf) -5;4356warning(_("truncating .rej filename to %.*s.rej"),4357 cnt -1, patch->new_name);4358}4359memcpy(namebuf, patch->new_name, cnt);4360memcpy(namebuf + cnt,".rej",5);43614362 rej =fopen(namebuf,"w");4363if(!rej)4364returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));43654366/* Normal git tools never deal with .rej, so do not pretend4367 * this is a git patch by saying --git or giving extended4368 * headers. While at it, maybe please "kompare" that wants4369 * the trailing TAB and some garbage at the end of line ;-).4370 */4371fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4372 patch->new_name, patch->new_name);4373for(cnt =1, frag = patch->fragments;4374 frag;4375 cnt++, frag = frag->next) {4376if(!frag->rejected) {4377fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4378continue;4379}4380fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4381fprintf(rej,"%.*s", frag->size, frag->patch);4382if(frag->patch[frag->size-1] !='\n')4383fputc('\n', rej);4384}4385fclose(rej);4386return-1;4387}43884389static intwrite_out_results(struct apply_state *state,struct patch *list)4390{4391int phase;4392int errs =0;4393struct patch *l;4394struct string_list cpath = STRING_LIST_INIT_DUP;43954396for(phase =0; phase <2; phase++) {4397 l = list;4398while(l) {4399if(l->rejected)4400 errs =1;4401else{4402write_out_one_result(state, l, phase);4403if(phase ==1) {4404if(write_out_one_reject(state, l))4405 errs =1;4406if(l->conflicted_threeway) {4407string_list_append(&cpath, l->new_name);4408 errs =1;4409}4410}4411}4412 l = l->next;4413}4414}44154416if(cpath.nr) {4417struct string_list_item *item;44184419string_list_sort(&cpath);4420for_each_string_list_item(item, &cpath)4421fprintf(stderr,"U%s\n", item->string);4422string_list_clear(&cpath,0);44234424rerere(0);4425}44264427return errs;4428}44294430static struct lock_file lock_file;44314432#define INACCURATE_EOF (1<<0)4433#define RECOUNT (1<<1)44344435/*4436 * Try to apply a patch.4437 *4438 * Returns:4439 * -128 if a bad error happened (like patch unreadable)4440 * -1 if patch did not apply and user cannot deal with it4441 * 0 if the patch applied4442 * 1 if the patch did not apply but user might fix it4443 */4444static intapply_patch(struct apply_state *state,4445int fd,4446const char*filename,4447int options)4448{4449size_t offset;4450struct strbuf buf = STRBUF_INIT;/* owns the patch text */4451struct patch *list = NULL, **listp = &list;4452int skipped_patch =0;4453int res =0;44544455 state->patch_input_file = filename;4456if(read_patch_file(&buf, fd) <0)4457return-128;4458 offset =0;4459while(offset < buf.len) {4460struct patch *patch;4461int nr;44624463 patch =xcalloc(1,sizeof(*patch));4464 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4465 patch->recount = !!(options & RECOUNT);4466 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4467if(nr <0) {4468free_patch(patch);4469if(nr == -128) {4470 res = -128;4471goto end;4472}4473break;4474}4475if(state->apply_in_reverse)4476reverse_patches(patch);4477if(use_patch(state, patch)) {4478patch_stats(state, patch);4479*listp = patch;4480 listp = &patch->next;4481}4482else{4483if(state->apply_verbosely)4484say_patch_name(stderr,_("Skipped patch '%s'."), patch);4485free_patch(patch);4486 skipped_patch++;4487}4488 offset += nr;4489}44904491if(!list && !skipped_patch) {4492error(_("unrecognized input"));4493 res = -128;4494goto end;4495}44964497if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4498 state->apply =0;44994500 state->update_index = state->check_index && state->apply;4501if(state->update_index && state->newfd <0)4502 state->newfd =hold_locked_index(state->lock_file,1);45034504if(state->check_index &&read_cache() <0) {4505error(_("unable to read index file"));4506 res = -128;4507goto end;4508}45094510if((state->check || state->apply) &&4511check_patch_list(state, list) <0&&4512!state->apply_with_reject) {4513 res = -1;4514goto end;4515}45164517if(state->apply &&write_out_results(state, list)) {4518/* with --3way, we still need to write the index out */4519 res = state->apply_with_reject ? -1:1;4520goto end;4521}45224523if(state->fake_ancestor)4524build_fake_ancestor(list, state->fake_ancestor);45254526if(state->diffstat)4527stat_patch_list(state, list);45284529if(state->numstat)4530numstat_patch_list(state, list);45314532if(state->summary)4533summary_patch_list(list);45344535end:4536free_patch_list(list);4537strbuf_release(&buf);4538string_list_clear(&state->fn_table,0);4539return res;4540}45414542static voidgit_apply_config(void)4543{4544git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4545git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4546git_config(git_default_config, NULL);4547}45484549static intoption_parse_exclude(const struct option *opt,4550const char*arg,int unset)4551{4552struct apply_state *state = opt->value;4553add_name_limit(state, arg,1);4554return0;4555}45564557static intoption_parse_include(const struct option *opt,4558const char*arg,int unset)4559{4560struct apply_state *state = opt->value;4561add_name_limit(state, arg,0);4562 state->has_include =1;4563return0;4564}45654566static intoption_parse_p(const struct option *opt,4567const char*arg,4568int unset)4569{4570struct apply_state *state = opt->value;4571 state->p_value =atoi(arg);4572 state->p_value_known =1;4573return0;4574}45754576static intoption_parse_space_change(const struct option *opt,4577const char*arg,int unset)4578{4579struct apply_state *state = opt->value;4580if(unset)4581 state->ws_ignore_action = ignore_ws_none;4582else4583 state->ws_ignore_action = ignore_ws_change;4584return0;4585}45864587static intoption_parse_whitespace(const struct option *opt,4588const char*arg,int unset)4589{4590struct apply_state *state = opt->value;4591 state->whitespace_option = arg;4592if(parse_whitespace_option(state, arg))4593exit(1);4594return0;4595}45964597static intoption_parse_directory(const struct option *opt,4598const char*arg,int unset)4599{4600struct apply_state *state = opt->value;4601strbuf_reset(&state->root);4602strbuf_addstr(&state->root, arg);4603strbuf_complete(&state->root,'/');4604return0;4605}46064607static voidinit_apply_state(struct apply_state *state,4608const char*prefix,4609struct lock_file *lock_file)4610{4611memset(state,0,sizeof(*state));4612 state->prefix = prefix;4613 state->prefix_length = state->prefix ?strlen(state->prefix) :0;4614 state->lock_file = lock_file;4615 state->newfd = -1;4616 state->apply =1;4617 state->line_termination ='\n';4618 state->p_value =1;4619 state->p_context = UINT_MAX;4620 state->squelch_whitespace_errors =5;4621 state->ws_error_action = warn_on_ws_error;4622 state->ws_ignore_action = ignore_ws_none;4623 state->linenr =1;4624string_list_init(&state->fn_table,0);4625string_list_init(&state->limit_by_name,0);4626string_list_init(&state->symlink_changes,0);4627strbuf_init(&state->root,0);46284629git_apply_config();4630if(apply_default_whitespace &&parse_whitespace_option(state, apply_default_whitespace))4631exit(1);4632if(apply_default_ignorewhitespace &&parse_ignorewhitespace_option(state, apply_default_ignorewhitespace))4633exit(1);4634}46354636static voidclear_apply_state(struct apply_state *state)4637{4638string_list_clear(&state->limit_by_name,0);4639string_list_clear(&state->symlink_changes,0);4640strbuf_release(&state->root);46414642/* &state->fn_table is cleared at the end of apply_patch() */4643}46444645static voidcheck_apply_state(struct apply_state *state,int force_apply)4646{4647int is_not_gitdir = !startup_info->have_repository;46484649if(state->apply_with_reject && state->threeway)4650die("--reject and --3way cannot be used together.");4651if(state->cached && state->threeway)4652die("--cached and --3way cannot be used together.");4653if(state->threeway) {4654if(is_not_gitdir)4655die(_("--3way outside a repository"));4656 state->check_index =1;4657}4658if(state->apply_with_reject)4659 state->apply = state->apply_verbosely =1;4660if(!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor))4661 state->apply =0;4662if(state->check_index && is_not_gitdir)4663die(_("--index outside a repository"));4664if(state->cached) {4665if(is_not_gitdir)4666die(_("--cached outside a repository"));4667 state->check_index =1;4668}4669if(state->check_index)4670 state->unsafe_paths =0;4671if(!state->lock_file)4672die("BUG: state->lock_file should not be NULL");4673}46744675static intapply_all_patches(struct apply_state *state,4676int argc,4677const char**argv,4678int options)4679{4680int i;4681int res;4682int errs =0;4683int read_stdin =1;46844685for(i =0; i < argc; i++) {4686const char*arg = argv[i];4687int fd;46884689if(!strcmp(arg,"-")) {4690 res =apply_patch(state,0,"<stdin>", options);4691if(res <0)4692goto end;4693 errs |= res;4694 read_stdin =0;4695continue;4696}else if(0< state->prefix_length)4697 arg =prefix_filename(state->prefix,4698 state->prefix_length,4699 arg);47004701 fd =open(arg, O_RDONLY);4702if(fd <0)4703die_errno(_("can't open patch '%s'"), arg);4704 read_stdin =0;4705set_default_whitespace_mode(state);4706 res =apply_patch(state, fd, arg, options);4707if(res <0)4708goto end;4709 errs |= res;4710close(fd);4711}4712set_default_whitespace_mode(state);4713if(read_stdin) {4714 res =apply_patch(state,0,"<stdin>", options);4715if(res <0)4716goto end;4717 errs |= res;4718}47194720if(state->whitespace_error) {4721if(state->squelch_whitespace_errors &&4722 state->squelch_whitespace_errors < state->whitespace_error) {4723int squelched =4724 state->whitespace_error - state->squelch_whitespace_errors;4725warning(Q_("squelched%dwhitespace error",4726"squelched%dwhitespace errors",4727 squelched),4728 squelched);4729}4730if(state->ws_error_action == die_on_ws_error)4731die(Q_("%dline adds whitespace errors.",4732"%dlines add whitespace errors.",4733 state->whitespace_error),4734 state->whitespace_error);4735if(state->applied_after_fixing_ws && state->apply)4736warning("%dline%sapplied after"4737" fixing whitespace errors.",4738 state->applied_after_fixing_ws,4739 state->applied_after_fixing_ws ==1?"":"s");4740else if(state->whitespace_error)4741warning(Q_("%dline adds whitespace errors.",4742"%dlines add whitespace errors.",4743 state->whitespace_error),4744 state->whitespace_error);4745}47464747if(state->update_index) {4748if(write_locked_index(&the_index, state->lock_file, COMMIT_LOCK))4749die(_("Unable to write new index file"));4750 state->newfd = -1;4751}47524753return!!errs;47544755end:4756exit(res == -1?1:128);4757}47584759intcmd_apply(int argc,const char**argv,const char*prefix)4760{4761int force_apply =0;4762int options =0;4763int ret;4764struct apply_state state;47654766struct option builtin_apply_options[] = {4767{ OPTION_CALLBACK,0,"exclude", &state,N_("path"),4768N_("don't apply changes matching the given path"),47690, option_parse_exclude },4770{ OPTION_CALLBACK,0,"include", &state,N_("path"),4771N_("apply changes matching the given path"),47720, option_parse_include },4773{ OPTION_CALLBACK,'p', NULL, &state,N_("num"),4774N_("remove <num> leading slashes from traditional diff paths"),47750, option_parse_p },4776OPT_BOOL(0,"no-add", &state.no_add,4777N_("ignore additions made by the patch")),4778OPT_BOOL(0,"stat", &state.diffstat,4779N_("instead of applying the patch, output diffstat for the input")),4780OPT_NOOP_NOARG(0,"allow-binary-replacement"),4781OPT_NOOP_NOARG(0,"binary"),4782OPT_BOOL(0,"numstat", &state.numstat,4783N_("show number of added and deleted lines in decimal notation")),4784OPT_BOOL(0,"summary", &state.summary,4785N_("instead of applying the patch, output a summary for the input")),4786OPT_BOOL(0,"check", &state.check,4787N_("instead of applying the patch, see if the patch is applicable")),4788OPT_BOOL(0,"index", &state.check_index,4789N_("make sure the patch is applicable to the current index")),4790OPT_BOOL(0,"cached", &state.cached,4791N_("apply a patch without touching the working tree")),4792OPT_BOOL(0,"unsafe-paths", &state.unsafe_paths,4793N_("accept a patch that touches outside the working area")),4794OPT_BOOL(0,"apply", &force_apply,4795N_("also apply the patch (use with --stat/--summary/--check)")),4796OPT_BOOL('3',"3way", &state.threeway,4797N_("attempt three-way merge if a patch does not apply")),4798OPT_FILENAME(0,"build-fake-ancestor", &state.fake_ancestor,4799N_("build a temporary index based on embedded index information")),4800/* Think twice before adding "--nul" synonym to this */4801OPT_SET_INT('z', NULL, &state.line_termination,4802N_("paths are separated with NUL character"),'\0'),4803OPT_INTEGER('C', NULL, &state.p_context,4804N_("ensure at least <n> lines of context match")),4805{ OPTION_CALLBACK,0,"whitespace", &state,N_("action"),4806N_("detect new or modified lines that have whitespace errors"),48070, option_parse_whitespace },4808{ OPTION_CALLBACK,0,"ignore-space-change", &state, NULL,4809N_("ignore changes in whitespace when finding context"),4810 PARSE_OPT_NOARG, option_parse_space_change },4811{ OPTION_CALLBACK,0,"ignore-whitespace", &state, NULL,4812N_("ignore changes in whitespace when finding context"),4813 PARSE_OPT_NOARG, option_parse_space_change },4814OPT_BOOL('R',"reverse", &state.apply_in_reverse,4815N_("apply the patch in reverse")),4816OPT_BOOL(0,"unidiff-zero", &state.unidiff_zero,4817N_("don't expect at least one line of context")),4818OPT_BOOL(0,"reject", &state.apply_with_reject,4819N_("leave the rejected hunks in corresponding *.rej files")),4820OPT_BOOL(0,"allow-overlap", &state.allow_overlap,4821N_("allow overlapping hunks")),4822OPT__VERBOSE(&state.apply_verbosely,N_("be verbose")),4823OPT_BIT(0,"inaccurate-eof", &options,4824N_("tolerate incorrectly detected missing new-line at the end of file"),4825 INACCURATE_EOF),4826OPT_BIT(0,"recount", &options,4827N_("do not trust the line counts in the hunk headers"),4828 RECOUNT),4829{ OPTION_CALLBACK,0,"directory", &state,N_("root"),4830N_("prepend <root> to all filenames"),48310, option_parse_directory },4832OPT_END()4833};48344835init_apply_state(&state, prefix, &lock_file);48364837 argc =parse_options(argc, argv, state.prefix, builtin_apply_options,4838 apply_usage,0);48394840check_apply_state(&state, force_apply);48414842 ret =apply_all_patches(&state, argc, argv, options);48434844clear_apply_state(&state);48454846return ret;4847}