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 voidparse_whitespace_option(struct apply_state *state,const char*option) 31{ 32if(!option) { 33 state->ws_error_action = warn_on_ws_error; 34return; 35} 36if(!strcmp(option,"warn")) { 37 state->ws_error_action = warn_on_ws_error; 38return; 39} 40if(!strcmp(option,"nowarn")) { 41 state->ws_error_action = nowarn_ws_error; 42return; 43} 44if(!strcmp(option,"error")) { 45 state->ws_error_action = die_on_ws_error; 46return; 47} 48if(!strcmp(option,"error-all")) { 49 state->ws_error_action = die_on_ws_error; 50 state->squelch_whitespace_errors =0; 51return; 52} 53if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 54 state->ws_error_action = correct_ws_error; 55return; 56} 57die(_("unrecognized whitespace option '%s'"), option); 58} 59 60static voidparse_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; 67return; 68} 69if(!strcmp(option,"change")) { 70 state->ws_ignore_action = ignore_ws_change; 71return; 72} 73die(_("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 */1675static intparse_single_patch(struct apply_state *state,1676const char*line,1677unsigned long size,1678struct patch *patch)1679{1680unsigned long offset =0;1681unsigned long oldlines =0, newlines =0, context =0;1682struct fragment **fragp = &patch->fragments;16831684while(size >4&& !memcmp(line,"@@ -",4)) {1685struct fragment *fragment;1686int len;16871688 fragment =xcalloc(1,sizeof(*fragment));1689 fragment->linenr = state->linenr;1690 len =parse_fragment(state, line, size, patch, fragment);1691if(len <=0)1692die(_("corrupt patch at line%d"), state->linenr);1693 fragment->patch = line;1694 fragment->size = len;1695 oldlines += fragment->oldlines;1696 newlines += fragment->newlines;1697 context += fragment->leading + fragment->trailing;16981699*fragp = fragment;1700 fragp = &fragment->next;17011702 offset += len;1703 line += len;1704 size -= len;1705}17061707/*1708 * If something was removed (i.e. we have old-lines) it cannot1709 * be creation, and if something was added it cannot be1710 * deletion. However, the reverse is not true; --unified=01711 * patches that only add are not necessarily creation even1712 * though they do not have any old lines, and ones that only1713 * delete are not necessarily deletion.1714 *1715 * Unfortunately, a real creation/deletion patch do _not_ have1716 * any context line by definition, so we cannot safely tell it1717 * apart with --unified=0 insanity. At least if the patch has1718 * more than one hunk it is not creation or deletion.1719 */1720if(patch->is_new <0&&1721(oldlines || (patch->fragments && patch->fragments->next)))1722 patch->is_new =0;1723if(patch->is_delete <0&&1724(newlines || (patch->fragments && patch->fragments->next)))1725 patch->is_delete =0;17261727if(0< patch->is_new && oldlines)1728die(_("new file%sdepends on old contents"), patch->new_name);1729if(0< patch->is_delete && newlines)1730die(_("deleted file%sstill has contents"), patch->old_name);1731if(!patch->is_delete && !newlines && context)1732fprintf_ln(stderr,1733_("** warning: "1734"file%sbecomes empty but is not deleted"),1735 patch->new_name);17361737return offset;1738}17391740staticinlineintmetadata_changes(struct patch *patch)1741{1742return patch->is_rename >0||1743 patch->is_copy >0||1744 patch->is_new >0||1745 patch->is_delete ||1746(patch->old_mode && patch->new_mode &&1747 patch->old_mode != patch->new_mode);1748}17491750static char*inflate_it(const void*data,unsigned long size,1751unsigned long inflated_size)1752{1753 git_zstream stream;1754void*out;1755int st;17561757memset(&stream,0,sizeof(stream));17581759 stream.next_in = (unsigned char*)data;1760 stream.avail_in = size;1761 stream.next_out = out =xmalloc(inflated_size);1762 stream.avail_out = inflated_size;1763git_inflate_init(&stream);1764 st =git_inflate(&stream, Z_FINISH);1765git_inflate_end(&stream);1766if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1767free(out);1768return NULL;1769}1770return out;1771}17721773/*1774 * Read a binary hunk and return a new fragment; fragment->patch1775 * points at an allocated memory that the caller must free, so1776 * it is marked as "->free_patch = 1".1777 */1778static struct fragment *parse_binary_hunk(struct apply_state *state,1779char**buf_p,1780unsigned long*sz_p,1781int*status_p,1782int*used_p)1783{1784/*1785 * Expect a line that begins with binary patch method ("literal"1786 * or "delta"), followed by the length of data before deflating.1787 * a sequence of 'length-byte' followed by base-85 encoded data1788 * should follow, terminated by a newline.1789 *1790 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1791 * and we would limit the patch line to 66 characters,1792 * so one line can fit up to 13 groups that would decode1793 * to 52 bytes max. The length byte 'A'-'Z' corresponds1794 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1795 */1796int llen, used;1797unsigned long size = *sz_p;1798char*buffer = *buf_p;1799int patch_method;1800unsigned long origlen;1801char*data = NULL;1802int hunk_size =0;1803struct fragment *frag;18041805 llen =linelen(buffer, size);1806 used = llen;18071808*status_p =0;18091810if(starts_with(buffer,"delta ")) {1811 patch_method = BINARY_DELTA_DEFLATED;1812 origlen =strtoul(buffer +6, NULL,10);1813}1814else if(starts_with(buffer,"literal ")) {1815 patch_method = BINARY_LITERAL_DEFLATED;1816 origlen =strtoul(buffer +8, NULL,10);1817}1818else1819return NULL;18201821 state->linenr++;1822 buffer += llen;1823while(1) {1824int byte_length, max_byte_length, newsize;1825 llen =linelen(buffer, size);1826 used += llen;1827 state->linenr++;1828if(llen ==1) {1829/* consume the blank line */1830 buffer++;1831 size--;1832break;1833}1834/*1835 * Minimum line is "A00000\n" which is 7-byte long,1836 * and the line length must be multiple of 5 plus 2.1837 */1838if((llen <7) || (llen-2) %5)1839goto corrupt;1840 max_byte_length = (llen -2) /5*4;1841 byte_length = *buffer;1842if('A'<= byte_length && byte_length <='Z')1843 byte_length = byte_length -'A'+1;1844else if('a'<= byte_length && byte_length <='z')1845 byte_length = byte_length -'a'+27;1846else1847goto corrupt;1848/* if the input length was not multiple of 4, we would1849 * have filler at the end but the filler should never1850 * exceed 3 bytes1851 */1852if(max_byte_length < byte_length ||1853 byte_length <= max_byte_length -4)1854goto corrupt;1855 newsize = hunk_size + byte_length;1856 data =xrealloc(data, newsize);1857if(decode_85(data + hunk_size, buffer +1, byte_length))1858goto corrupt;1859 hunk_size = newsize;1860 buffer += llen;1861 size -= llen;1862}18631864 frag =xcalloc(1,sizeof(*frag));1865 frag->patch =inflate_it(data, hunk_size, origlen);1866 frag->free_patch =1;1867if(!frag->patch)1868goto corrupt;1869free(data);1870 frag->size = origlen;1871*buf_p = buffer;1872*sz_p = size;1873*used_p = used;1874 frag->binary_patch_method = patch_method;1875return frag;18761877 corrupt:1878free(data);1879*status_p = -1;1880error(_("corrupt binary patch at line%d: %.*s"),1881 state->linenr-1, llen-1, buffer);1882return NULL;1883}18841885/*1886 * Returns:1887 * -1 in case of error,1888 * the length of the parsed binary patch otherwise1889 */1890static intparse_binary(struct apply_state *state,1891char*buffer,1892unsigned long size,1893struct patch *patch)1894{1895/*1896 * We have read "GIT binary patch\n"; what follows is a line1897 * that says the patch method (currently, either "literal" or1898 * "delta") and the length of data before deflating; a1899 * sequence of 'length-byte' followed by base-85 encoded data1900 * follows.1901 *1902 * When a binary patch is reversible, there is another binary1903 * hunk in the same format, starting with patch method (either1904 * "literal" or "delta") with the length of data, and a sequence1905 * of length-byte + base-85 encoded data, terminated with another1906 * empty line. This data, when applied to the postimage, produces1907 * the preimage.1908 */1909struct fragment *forward;1910struct fragment *reverse;1911int status;1912int used, used_1;19131914 forward =parse_binary_hunk(state, &buffer, &size, &status, &used);1915if(!forward && !status)1916/* there has to be one hunk (forward hunk) */1917returnerror(_("unrecognized binary patch at line%d"), state->linenr-1);1918if(status)1919/* otherwise we already gave an error message */1920return status;19211922 reverse =parse_binary_hunk(state, &buffer, &size, &status, &used_1);1923if(reverse)1924 used += used_1;1925else if(status) {1926/*1927 * Not having reverse hunk is not an error, but having1928 * a corrupt reverse hunk is.1929 */1930free((void*) forward->patch);1931free(forward);1932return status;1933}1934 forward->next = reverse;1935 patch->fragments = forward;1936 patch->is_binary =1;1937return used;1938}19391940static voidprefix_one(struct apply_state *state,char**name)1941{1942char*old_name = *name;1943if(!old_name)1944return;1945*name =xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));1946free(old_name);1947}19481949static voidprefix_patch(struct apply_state *state,struct patch *p)1950{1951if(!state->prefix || p->is_toplevel_relative)1952return;1953prefix_one(state, &p->new_name);1954prefix_one(state, &p->old_name);1955}19561957/*1958 * include/exclude1959 */19601961static voidadd_name_limit(struct apply_state *state,1962const char*name,1963int exclude)1964{1965struct string_list_item *it;19661967 it =string_list_append(&state->limit_by_name, name);1968 it->util = exclude ? NULL : (void*)1;1969}19701971static intuse_patch(struct apply_state *state,struct patch *p)1972{1973const char*pathname = p->new_name ? p->new_name : p->old_name;1974int i;19751976/* Paths outside are not touched regardless of "--include" */1977if(0< state->prefix_length) {1978int pathlen =strlen(pathname);1979if(pathlen <= state->prefix_length ||1980memcmp(state->prefix, pathname, state->prefix_length))1981return0;1982}19831984/* See if it matches any of exclude/include rule */1985for(i =0; i < state->limit_by_name.nr; i++) {1986struct string_list_item *it = &state->limit_by_name.items[i];1987if(!wildmatch(it->string, pathname,0, NULL))1988return(it->util != NULL);1989}19901991/*1992 * If we had any include, a path that does not match any rule is1993 * not used. Otherwise, we saw bunch of exclude rules (or none)1994 * and such a path is used.1995 */1996return!state->has_include;1997}19981999/*2000 * Read the patch text in "buffer" that extends for "size" bytes; stop2001 * reading after seeing a single patch (i.e. changes to a single file).2002 * Create fragments (i.e. patch hunks) and hang them to the given patch.2003 *2004 * Returns:2005 * -1 if no header was found or parse_binary() failed,2006 * -128 on another error,2007 * the number of bytes consumed otherwise,2008 * so that the caller can call us again for the next patch.2009 */2010static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2011{2012int hdrsize, patchsize;2013int offset =find_header(state, buffer, size, &hdrsize, patch);20142015if(offset <0)2016return offset;20172018prefix_patch(state, patch);20192020if(!use_patch(state, patch))2021 patch->ws_rule =0;2022else2023 patch->ws_rule =whitespace_rule(patch->new_name2024? patch->new_name2025: patch->old_name);20262027 patchsize =parse_single_patch(state,2028 buffer + offset + hdrsize,2029 size - offset - hdrsize,2030 patch);20312032if(!patchsize) {2033static const char git_binary[] ="GIT binary patch\n";2034int hd = hdrsize + offset;2035unsigned long llen =linelen(buffer + hd, size - hd);20362037if(llen ==sizeof(git_binary) -1&&2038!memcmp(git_binary, buffer + hd, llen)) {2039int used;2040 state->linenr++;2041 used =parse_binary(state, buffer + hd + llen,2042 size - hd - llen, patch);2043if(used <0)2044return-1;2045if(used)2046 patchsize = used + llen;2047else2048 patchsize =0;2049}2050else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2051static const char*binhdr[] = {2052"Binary files ",2053"Files ",2054 NULL,2055};2056int i;2057for(i =0; binhdr[i]; i++) {2058int len =strlen(binhdr[i]);2059if(len < size - hd &&2060!memcmp(binhdr[i], buffer + hd, len)) {2061 state->linenr++;2062 patch->is_binary =1;2063 patchsize = llen;2064break;2065}2066}2067}20682069/* Empty patch cannot be applied if it is a text patch2070 * without metadata change. A binary patch appears2071 * empty to us here.2072 */2073if((state->apply || state->check) &&2074(!patch->is_binary && !metadata_changes(patch))) {2075error(_("patch with only garbage at line%d"), state->linenr);2076return-128;2077}2078}20792080return offset + hdrsize + patchsize;2081}20822083#define swap(a,b) myswap((a),(b),sizeof(a))20842085#define myswap(a, b, size) do { \2086 unsigned char mytmp[size]; \2087 memcpy(mytmp, &a, size); \2088 memcpy(&a, &b, size); \2089 memcpy(&b, mytmp, size); \2090} while (0)20912092static voidreverse_patches(struct patch *p)2093{2094for(; p; p = p->next) {2095struct fragment *frag = p->fragments;20962097swap(p->new_name, p->old_name);2098swap(p->new_mode, p->old_mode);2099swap(p->is_new, p->is_delete);2100swap(p->lines_added, p->lines_deleted);2101swap(p->old_sha1_prefix, p->new_sha1_prefix);21022103for(; frag; frag = frag->next) {2104swap(frag->newpos, frag->oldpos);2105swap(frag->newlines, frag->oldlines);2106}2107}2108}21092110static const char pluses[] =2111"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2112static const char minuses[]=2113"----------------------------------------------------------------------";21142115static voidshow_stats(struct apply_state *state,struct patch *patch)2116{2117struct strbuf qname = STRBUF_INIT;2118char*cp = patch->new_name ? patch->new_name : patch->old_name;2119int max, add, del;21202121quote_c_style(cp, &qname, NULL,0);21222123/*2124 * "scale" the filename2125 */2126 max = state->max_len;2127if(max >50)2128 max =50;21292130if(qname.len > max) {2131 cp =strchr(qname.buf + qname.len +3- max,'/');2132if(!cp)2133 cp = qname.buf + qname.len +3- max;2134strbuf_splice(&qname,0, cp - qname.buf,"...",3);2135}21362137if(patch->is_binary) {2138printf(" %-*s | Bin\n", max, qname.buf);2139strbuf_release(&qname);2140return;2141}21422143printf(" %-*s |", max, qname.buf);2144strbuf_release(&qname);21452146/*2147 * scale the add/delete2148 */2149 max = max + state->max_change >70?70- max : state->max_change;2150 add = patch->lines_added;2151 del = patch->lines_deleted;21522153if(state->max_change >0) {2154int total = ((add + del) * max + state->max_change /2) / state->max_change;2155 add = (add * max + state->max_change /2) / state->max_change;2156 del = total - add;2157}2158printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2159 add, pluses, del, minuses);2160}21612162static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2163{2164switch(st->st_mode & S_IFMT) {2165case S_IFLNK:2166if(strbuf_readlink(buf, path, st->st_size) <0)2167returnerror(_("unable to read symlink%s"), path);2168return0;2169case S_IFREG:2170if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2171returnerror(_("unable to open or read%s"), path);2172convert_to_git(path, buf->buf, buf->len, buf,0);2173return0;2174default:2175return-1;2176}2177}21782179/*2180 * Update the preimage, and the common lines in postimage,2181 * from buffer buf of length len. If postlen is 0 the postimage2182 * is updated in place, otherwise it's updated on a new buffer2183 * of length postlen2184 */21852186static voidupdate_pre_post_images(struct image *preimage,2187struct image *postimage,2188char*buf,2189size_t len,size_t postlen)2190{2191int i, ctx, reduced;2192char*new, *old, *fixed;2193struct image fixed_preimage;21942195/*2196 * Update the preimage with whitespace fixes. Note that we2197 * are not losing preimage->buf -- apply_one_fragment() will2198 * free "oldlines".2199 */2200prepare_image(&fixed_preimage, buf, len,1);2201assert(postlen2202? fixed_preimage.nr == preimage->nr2203: fixed_preimage.nr <= preimage->nr);2204for(i =0; i < fixed_preimage.nr; i++)2205 fixed_preimage.line[i].flag = preimage->line[i].flag;2206free(preimage->line_allocated);2207*preimage = fixed_preimage;22082209/*2210 * Adjust the common context lines in postimage. This can be2211 * done in-place when we are shrinking it with whitespace2212 * fixing, but needs a new buffer when ignoring whitespace or2213 * expanding leading tabs to spaces.2214 *2215 * We trust the caller to tell us if the update can be done2216 * in place (postlen==0) or not.2217 */2218 old = postimage->buf;2219if(postlen)2220new= postimage->buf =xmalloc(postlen);2221else2222new= old;2223 fixed = preimage->buf;22242225for(i = reduced = ctx =0; i < postimage->nr; i++) {2226size_t l_len = postimage->line[i].len;2227if(!(postimage->line[i].flag & LINE_COMMON)) {2228/* an added line -- no counterparts in preimage */2229memmove(new, old, l_len);2230 old += l_len;2231new+= l_len;2232continue;2233}22342235/* a common context -- skip it in the original postimage */2236 old += l_len;22372238/* and find the corresponding one in the fixed preimage */2239while(ctx < preimage->nr &&2240!(preimage->line[ctx].flag & LINE_COMMON)) {2241 fixed += preimage->line[ctx].len;2242 ctx++;2243}22442245/*2246 * preimage is expected to run out, if the caller2247 * fixed addition of trailing blank lines.2248 */2249if(preimage->nr <= ctx) {2250 reduced++;2251continue;2252}22532254/* and copy it in, while fixing the line length */2255 l_len = preimage->line[ctx].len;2256memcpy(new, fixed, l_len);2257new+= l_len;2258 fixed += l_len;2259 postimage->line[i].len = l_len;2260 ctx++;2261}22622263if(postlen2264? postlen <new- postimage->buf2265: postimage->len <new- postimage->buf)2266die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2267(int)postlen, (int) postimage->len, (int)(new- postimage->buf));22682269/* Fix the length of the whole thing */2270 postimage->len =new- postimage->buf;2271 postimage->nr -= reduced;2272}22732274static intline_by_line_fuzzy_match(struct image *img,2275struct image *preimage,2276struct image *postimage,2277unsigned longtry,2278int try_lno,2279int preimage_limit)2280{2281int i;2282size_t imgoff =0;2283size_t preoff =0;2284size_t postlen = postimage->len;2285size_t extra_chars;2286char*buf;2287char*preimage_eof;2288char*preimage_end;2289struct strbuf fixed;2290char*fixed_buf;2291size_t fixed_len;22922293for(i =0; i < preimage_limit; i++) {2294size_t prelen = preimage->line[i].len;2295size_t imglen = img->line[try_lno+i].len;22962297if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2298 preimage->buf + preoff, prelen))2299return0;2300if(preimage->line[i].flag & LINE_COMMON)2301 postlen += imglen - prelen;2302 imgoff += imglen;2303 preoff += prelen;2304}23052306/*2307 * Ok, the preimage matches with whitespace fuzz.2308 *2309 * imgoff now holds the true length of the target that2310 * matches the preimage before the end of the file.2311 *2312 * Count the number of characters in the preimage that fall2313 * beyond the end of the file and make sure that all of them2314 * are whitespace characters. (This can only happen if2315 * we are removing blank lines at the end of the file.)2316 */2317 buf = preimage_eof = preimage->buf + preoff;2318for( ; i < preimage->nr; i++)2319 preoff += preimage->line[i].len;2320 preimage_end = preimage->buf + preoff;2321for( ; buf < preimage_end; buf++)2322if(!isspace(*buf))2323return0;23242325/*2326 * Update the preimage and the common postimage context2327 * lines to use the same whitespace as the target.2328 * If whitespace is missing in the target (i.e.2329 * if the preimage extends beyond the end of the file),2330 * use the whitespace from the preimage.2331 */2332 extra_chars = preimage_end - preimage_eof;2333strbuf_init(&fixed, imgoff + extra_chars);2334strbuf_add(&fixed, img->buf +try, imgoff);2335strbuf_add(&fixed, preimage_eof, extra_chars);2336 fixed_buf =strbuf_detach(&fixed, &fixed_len);2337update_pre_post_images(preimage, postimage,2338 fixed_buf, fixed_len, postlen);2339return1;2340}23412342static intmatch_fragment(struct apply_state *state,2343struct image *img,2344struct image *preimage,2345struct image *postimage,2346unsigned longtry,2347int try_lno,2348unsigned ws_rule,2349int match_beginning,int match_end)2350{2351int i;2352char*fixed_buf, *buf, *orig, *target;2353struct strbuf fixed;2354size_t fixed_len, postlen;2355int preimage_limit;23562357if(preimage->nr + try_lno <= img->nr) {2358/*2359 * The hunk falls within the boundaries of img.2360 */2361 preimage_limit = preimage->nr;2362if(match_end && (preimage->nr + try_lno != img->nr))2363return0;2364}else if(state->ws_error_action == correct_ws_error &&2365(ws_rule & WS_BLANK_AT_EOF)) {2366/*2367 * This hunk extends beyond the end of img, and we are2368 * removing blank lines at the end of the file. This2369 * many lines from the beginning of the preimage must2370 * match with img, and the remainder of the preimage2371 * must be blank.2372 */2373 preimage_limit = img->nr - try_lno;2374}else{2375/*2376 * The hunk extends beyond the end of the img and2377 * we are not removing blanks at the end, so we2378 * should reject the hunk at this position.2379 */2380return0;2381}23822383if(match_beginning && try_lno)2384return0;23852386/* Quick hash check */2387for(i =0; i < preimage_limit; i++)2388if((img->line[try_lno + i].flag & LINE_PATCHED) ||2389(preimage->line[i].hash != img->line[try_lno + i].hash))2390return0;23912392if(preimage_limit == preimage->nr) {2393/*2394 * Do we have an exact match? If we were told to match2395 * at the end, size must be exactly at try+fragsize,2396 * otherwise try+fragsize must be still within the preimage,2397 * and either case, the old piece should match the preimage2398 * exactly.2399 */2400if((match_end2401? (try+ preimage->len == img->len)2402: (try+ preimage->len <= img->len)) &&2403!memcmp(img->buf +try, preimage->buf, preimage->len))2404return1;2405}else{2406/*2407 * The preimage extends beyond the end of img, so2408 * there cannot be an exact match.2409 *2410 * There must be one non-blank context line that match2411 * a line before the end of img.2412 */2413char*buf_end;24142415 buf = preimage->buf;2416 buf_end = buf;2417for(i =0; i < preimage_limit; i++)2418 buf_end += preimage->line[i].len;24192420for( ; buf < buf_end; buf++)2421if(!isspace(*buf))2422break;2423if(buf == buf_end)2424return0;2425}24262427/*2428 * No exact match. If we are ignoring whitespace, run a line-by-line2429 * fuzzy matching. We collect all the line length information because2430 * we need it to adjust whitespace if we match.2431 */2432if(state->ws_ignore_action == ignore_ws_change)2433returnline_by_line_fuzzy_match(img, preimage, postimage,2434try, try_lno, preimage_limit);24352436if(state->ws_error_action != correct_ws_error)2437return0;24382439/*2440 * The hunk does not apply byte-by-byte, but the hash says2441 * it might with whitespace fuzz. We weren't asked to2442 * ignore whitespace, we were asked to correct whitespace2443 * errors, so let's try matching after whitespace correction.2444 *2445 * While checking the preimage against the target, whitespace2446 * errors in both fixed, we count how large the corresponding2447 * postimage needs to be. The postimage prepared by2448 * apply_one_fragment() has whitespace errors fixed on added2449 * lines already, but the common lines were propagated as-is,2450 * which may become longer when their whitespace errors are2451 * fixed.2452 */24532454/* First count added lines in postimage */2455 postlen =0;2456for(i =0; i < postimage->nr; i++) {2457if(!(postimage->line[i].flag & LINE_COMMON))2458 postlen += postimage->line[i].len;2459}24602461/*2462 * The preimage may extend beyond the end of the file,2463 * but in this loop we will only handle the part of the2464 * preimage that falls within the file.2465 */2466strbuf_init(&fixed, preimage->len +1);2467 orig = preimage->buf;2468 target = img->buf +try;2469for(i =0; i < preimage_limit; i++) {2470size_t oldlen = preimage->line[i].len;2471size_t tgtlen = img->line[try_lno + i].len;2472size_t fixstart = fixed.len;2473struct strbuf tgtfix;2474int match;24752476/* Try fixing the line in the preimage */2477ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24782479/* Try fixing the line in the target */2480strbuf_init(&tgtfix, tgtlen);2481ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);24822483/*2484 * If they match, either the preimage was based on2485 * a version before our tree fixed whitespace breakage,2486 * or we are lacking a whitespace-fix patch the tree2487 * the preimage was based on already had (i.e. target2488 * has whitespace breakage, the preimage doesn't).2489 * In either case, we are fixing the whitespace breakages2490 * so we might as well take the fix together with their2491 * real change.2492 */2493 match = (tgtfix.len == fixed.len - fixstart &&2494!memcmp(tgtfix.buf, fixed.buf + fixstart,2495 fixed.len - fixstart));24962497/* Add the length if this is common with the postimage */2498if(preimage->line[i].flag & LINE_COMMON)2499 postlen += tgtfix.len;25002501strbuf_release(&tgtfix);2502if(!match)2503goto unmatch_exit;25042505 orig += oldlen;2506 target += tgtlen;2507}250825092510/*2511 * Now handle the lines in the preimage that falls beyond the2512 * end of the file (if any). They will only match if they are2513 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2514 * false).2515 */2516for( ; i < preimage->nr; i++) {2517size_t fixstart = fixed.len;/* start of the fixed preimage */2518size_t oldlen = preimage->line[i].len;2519int j;25202521/* Try fixing the line in the preimage */2522ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25232524for(j = fixstart; j < fixed.len; j++)2525if(!isspace(fixed.buf[j]))2526goto unmatch_exit;25272528 orig += oldlen;2529}25302531/*2532 * Yes, the preimage is based on an older version that still2533 * has whitespace breakages unfixed, and fixing them makes the2534 * hunk match. Update the context lines in the postimage.2535 */2536 fixed_buf =strbuf_detach(&fixed, &fixed_len);2537if(postlen < postimage->len)2538 postlen =0;2539update_pre_post_images(preimage, postimage,2540 fixed_buf, fixed_len, postlen);2541return1;25422543 unmatch_exit:2544strbuf_release(&fixed);2545return0;2546}25472548static intfind_pos(struct apply_state *state,2549struct image *img,2550struct image *preimage,2551struct image *postimage,2552int line,2553unsigned ws_rule,2554int match_beginning,int match_end)2555{2556int i;2557unsigned long backwards, forwards,try;2558int backwards_lno, forwards_lno, try_lno;25592560/*2561 * If match_beginning or match_end is specified, there is no2562 * point starting from a wrong line that will never match and2563 * wander around and wait for a match at the specified end.2564 */2565if(match_beginning)2566 line =0;2567else if(match_end)2568 line = img->nr - preimage->nr;25692570/*2571 * Because the comparison is unsigned, the following test2572 * will also take care of a negative line number that can2573 * result when match_end and preimage is larger than the target.2574 */2575if((size_t) line > img->nr)2576 line = img->nr;25772578try=0;2579for(i =0; i < line; i++)2580try+= img->line[i].len;25812582/*2583 * There's probably some smart way to do this, but I'll leave2584 * that to the smart and beautiful people. I'm simple and stupid.2585 */2586 backwards =try;2587 backwards_lno = line;2588 forwards =try;2589 forwards_lno = line;2590 try_lno = line;25912592for(i =0; ; i++) {2593if(match_fragment(state, img, preimage, postimage,2594try, try_lno, ws_rule,2595 match_beginning, match_end))2596return try_lno;25972598 again:2599if(backwards_lno ==0&& forwards_lno == img->nr)2600break;26012602if(i &1) {2603if(backwards_lno ==0) {2604 i++;2605goto again;2606}2607 backwards_lno--;2608 backwards -= img->line[backwards_lno].len;2609try= backwards;2610 try_lno = backwards_lno;2611}else{2612if(forwards_lno == img->nr) {2613 i++;2614goto again;2615}2616 forwards += img->line[forwards_lno].len;2617 forwards_lno++;2618try= forwards;2619 try_lno = forwards_lno;2620}26212622}2623return-1;2624}26252626static voidremove_first_line(struct image *img)2627{2628 img->buf += img->line[0].len;2629 img->len -= img->line[0].len;2630 img->line++;2631 img->nr--;2632}26332634static voidremove_last_line(struct image *img)2635{2636 img->len -= img->line[--img->nr].len;2637}26382639/*2640 * The change from "preimage" and "postimage" has been found to2641 * apply at applied_pos (counts in line numbers) in "img".2642 * Update "img" to remove "preimage" and replace it with "postimage".2643 */2644static voidupdate_image(struct apply_state *state,2645struct image *img,2646int applied_pos,2647struct image *preimage,2648struct image *postimage)2649{2650/*2651 * remove the copy of preimage at offset in img2652 * and replace it with postimage2653 */2654int i, nr;2655size_t remove_count, insert_count, applied_at =0;2656char*result;2657int preimage_limit;26582659/*2660 * If we are removing blank lines at the end of img,2661 * the preimage may extend beyond the end.2662 * If that is the case, we must be careful only to2663 * remove the part of the preimage that falls within2664 * the boundaries of img. Initialize preimage_limit2665 * to the number of lines in the preimage that falls2666 * within the boundaries.2667 */2668 preimage_limit = preimage->nr;2669if(preimage_limit > img->nr - applied_pos)2670 preimage_limit = img->nr - applied_pos;26712672for(i =0; i < applied_pos; i++)2673 applied_at += img->line[i].len;26742675 remove_count =0;2676for(i =0; i < preimage_limit; i++)2677 remove_count += img->line[applied_pos + i].len;2678 insert_count = postimage->len;26792680/* Adjust the contents */2681 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2682memcpy(result, img->buf, applied_at);2683memcpy(result + applied_at, postimage->buf, postimage->len);2684memcpy(result + applied_at + postimage->len,2685 img->buf + (applied_at + remove_count),2686 img->len - (applied_at + remove_count));2687free(img->buf);2688 img->buf = result;2689 img->len += insert_count - remove_count;2690 result[img->len] ='\0';26912692/* Adjust the line table */2693 nr = img->nr + postimage->nr - preimage_limit;2694if(preimage_limit < postimage->nr) {2695/*2696 * NOTE: this knows that we never call remove_first_line()2697 * on anything other than pre/post image.2698 */2699REALLOC_ARRAY(img->line, nr);2700 img->line_allocated = img->line;2701}2702if(preimage_limit != postimage->nr)2703memmove(img->line + applied_pos + postimage->nr,2704 img->line + applied_pos + preimage_limit,2705(img->nr - (applied_pos + preimage_limit)) *2706sizeof(*img->line));2707memcpy(img->line + applied_pos,2708 postimage->line,2709 postimage->nr *sizeof(*img->line));2710if(!state->allow_overlap)2711for(i =0; i < postimage->nr; i++)2712 img->line[applied_pos + i].flag |= LINE_PATCHED;2713 img->nr = nr;2714}27152716/*2717 * Use the patch-hunk text in "frag" to prepare two images (preimage and2718 * postimage) for the hunk. Find lines that match "preimage" in "img" and2719 * replace the part of "img" with "postimage" text.2720 */2721static intapply_one_fragment(struct apply_state *state,2722struct image *img,struct fragment *frag,2723int inaccurate_eof,unsigned ws_rule,2724int nth_fragment)2725{2726int match_beginning, match_end;2727const char*patch = frag->patch;2728int size = frag->size;2729char*old, *oldlines;2730struct strbuf newlines;2731int new_blank_lines_at_end =0;2732int found_new_blank_lines_at_end =0;2733int hunk_linenr = frag->linenr;2734unsigned long leading, trailing;2735int pos, applied_pos;2736struct image preimage;2737struct image postimage;27382739memset(&preimage,0,sizeof(preimage));2740memset(&postimage,0,sizeof(postimage));2741 oldlines =xmalloc(size);2742strbuf_init(&newlines, size);27432744 old = oldlines;2745while(size >0) {2746char first;2747int len =linelen(patch, size);2748int plen;2749int added_blank_line =0;2750int is_blank_context =0;2751size_t start;27522753if(!len)2754break;27552756/*2757 * "plen" is how much of the line we should use for2758 * the actual patch data. Normally we just remove the2759 * first character on the line, but if the line is2760 * followed by "\ No newline", then we also remove the2761 * last one (which is the newline, of course).2762 */2763 plen = len -1;2764if(len < size && patch[len] =='\\')2765 plen--;2766 first = *patch;2767if(state->apply_in_reverse) {2768if(first =='-')2769 first ='+';2770else if(first =='+')2771 first ='-';2772}27732774switch(first) {2775case'\n':2776/* Newer GNU diff, empty context line */2777if(plen <0)2778/* ... followed by '\No newline'; nothing */2779break;2780*old++ ='\n';2781strbuf_addch(&newlines,'\n');2782add_line_info(&preimage,"\n",1, LINE_COMMON);2783add_line_info(&postimage,"\n",1, LINE_COMMON);2784 is_blank_context =1;2785break;2786case' ':2787if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2788ws_blank_line(patch +1, plen, ws_rule))2789 is_blank_context =1;2790case'-':2791memcpy(old, patch +1, plen);2792add_line_info(&preimage, old, plen,2793(first ==' '? LINE_COMMON :0));2794 old += plen;2795if(first =='-')2796break;2797/* Fall-through for ' ' */2798case'+':2799/* --no-add does not add new lines */2800if(first =='+'&& state->no_add)2801break;28022803 start = newlines.len;2804if(first !='+'||2805!state->whitespace_error ||2806 state->ws_error_action != correct_ws_error) {2807strbuf_add(&newlines, patch +1, plen);2808}2809else{2810ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2811}2812add_line_info(&postimage, newlines.buf + start, newlines.len - start,2813(first =='+'?0: LINE_COMMON));2814if(first =='+'&&2815(ws_rule & WS_BLANK_AT_EOF) &&2816ws_blank_line(patch +1, plen, ws_rule))2817 added_blank_line =1;2818break;2819case'@':case'\\':2820/* Ignore it, we already handled it */2821break;2822default:2823if(state->apply_verbosely)2824error(_("invalid start of line: '%c'"), first);2825 applied_pos = -1;2826goto out;2827}2828if(added_blank_line) {2829if(!new_blank_lines_at_end)2830 found_new_blank_lines_at_end = hunk_linenr;2831 new_blank_lines_at_end++;2832}2833else if(is_blank_context)2834;2835else2836 new_blank_lines_at_end =0;2837 patch += len;2838 size -= len;2839 hunk_linenr++;2840}2841if(inaccurate_eof &&2842 old > oldlines && old[-1] =='\n'&&2843 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2844 old--;2845strbuf_setlen(&newlines, newlines.len -1);2846}28472848 leading = frag->leading;2849 trailing = frag->trailing;28502851/*2852 * A hunk to change lines at the beginning would begin with2853 * @@ -1,L +N,M @@2854 * but we need to be careful. -U0 that inserts before the second2855 * line also has this pattern.2856 *2857 * And a hunk to add to an empty file would begin with2858 * @@ -0,0 +N,M @@2859 *2860 * In other words, a hunk that is (frag->oldpos <= 1) with or2861 * without leading context must match at the beginning.2862 */2863 match_beginning = (!frag->oldpos ||2864(frag->oldpos ==1&& !state->unidiff_zero));28652866/*2867 * A hunk without trailing lines must match at the end.2868 * However, we simply cannot tell if a hunk must match end2869 * from the lack of trailing lines if the patch was generated2870 * with unidiff without any context.2871 */2872 match_end = !state->unidiff_zero && !trailing;28732874 pos = frag->newpos ? (frag->newpos -1) :0;2875 preimage.buf = oldlines;2876 preimage.len = old - oldlines;2877 postimage.buf = newlines.buf;2878 postimage.len = newlines.len;2879 preimage.line = preimage.line_allocated;2880 postimage.line = postimage.line_allocated;28812882for(;;) {28832884 applied_pos =find_pos(state, img, &preimage, &postimage, pos,2885 ws_rule, match_beginning, match_end);28862887if(applied_pos >=0)2888break;28892890/* Am I at my context limits? */2891if((leading <= state->p_context) && (trailing <= state->p_context))2892break;2893if(match_beginning || match_end) {2894 match_beginning = match_end =0;2895continue;2896}28972898/*2899 * Reduce the number of context lines; reduce both2900 * leading and trailing if they are equal otherwise2901 * just reduce the larger context.2902 */2903if(leading >= trailing) {2904remove_first_line(&preimage);2905remove_first_line(&postimage);2906 pos--;2907 leading--;2908}2909if(trailing > leading) {2910remove_last_line(&preimage);2911remove_last_line(&postimage);2912 trailing--;2913}2914}29152916if(applied_pos >=0) {2917if(new_blank_lines_at_end &&2918 preimage.nr + applied_pos >= img->nr &&2919(ws_rule & WS_BLANK_AT_EOF) &&2920 state->ws_error_action != nowarn_ws_error) {2921record_ws_error(state, WS_BLANK_AT_EOF,"+",1,2922 found_new_blank_lines_at_end);2923if(state->ws_error_action == correct_ws_error) {2924while(new_blank_lines_at_end--)2925remove_last_line(&postimage);2926}2927/*2928 * We would want to prevent write_out_results()2929 * from taking place in apply_patch() that follows2930 * the callchain led us here, which is:2931 * apply_patch->check_patch_list->check_patch->2932 * apply_data->apply_fragments->apply_one_fragment2933 */2934if(state->ws_error_action == die_on_ws_error)2935 state->apply =0;2936}29372938if(state->apply_verbosely && applied_pos != pos) {2939int offset = applied_pos - pos;2940if(state->apply_in_reverse)2941 offset =0- offset;2942fprintf_ln(stderr,2943Q_("Hunk #%dsucceeded at%d(offset%dline).",2944"Hunk #%dsucceeded at%d(offset%dlines).",2945 offset),2946 nth_fragment, applied_pos +1, offset);2947}29482949/*2950 * Warn if it was necessary to reduce the number2951 * of context lines.2952 */2953if((leading != frag->leading) ||2954(trailing != frag->trailing))2955fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2956" to apply fragment at%d"),2957 leading, trailing, applied_pos+1);2958update_image(state, img, applied_pos, &preimage, &postimage);2959}else{2960if(state->apply_verbosely)2961error(_("while searching for:\n%.*s"),2962(int)(old - oldlines), oldlines);2963}29642965out:2966free(oldlines);2967strbuf_release(&newlines);2968free(preimage.line_allocated);2969free(postimage.line_allocated);29702971return(applied_pos <0);2972}29732974static intapply_binary_fragment(struct apply_state *state,2975struct image *img,2976struct patch *patch)2977{2978struct fragment *fragment = patch->fragments;2979unsigned long len;2980void*dst;29812982if(!fragment)2983returnerror(_("missing binary patch data for '%s'"),2984 patch->new_name ?2985 patch->new_name :2986 patch->old_name);29872988/* Binary patch is irreversible without the optional second hunk */2989if(state->apply_in_reverse) {2990if(!fragment->next)2991returnerror("cannot reverse-apply a binary patch "2992"without the reverse hunk to '%s'",2993 patch->new_name2994? patch->new_name : patch->old_name);2995 fragment = fragment->next;2996}2997switch(fragment->binary_patch_method) {2998case BINARY_DELTA_DEFLATED:2999 dst =patch_delta(img->buf, img->len, fragment->patch,3000 fragment->size, &len);3001if(!dst)3002return-1;3003clear_image(img);3004 img->buf = dst;3005 img->len = len;3006return0;3007case BINARY_LITERAL_DEFLATED:3008clear_image(img);3009 img->len = fragment->size;3010 img->buf =xmemdupz(fragment->patch, img->len);3011return0;3012}3013return-1;3014}30153016/*3017 * Replace "img" with the result of applying the binary patch.3018 * The binary patch data itself in patch->fragment is still kept3019 * but the preimage prepared by the caller in "img" is freed here3020 * or in the helper function apply_binary_fragment() this calls.3021 */3022static intapply_binary(struct apply_state *state,3023struct image *img,3024struct patch *patch)3025{3026const char*name = patch->old_name ? patch->old_name : patch->new_name;3027unsigned char sha1[20];30283029/*3030 * For safety, we require patch index line to contain3031 * full 40-byte textual SHA1 for old and new, at least for now.3032 */3033if(strlen(patch->old_sha1_prefix) !=40||3034strlen(patch->new_sha1_prefix) !=40||3035get_sha1_hex(patch->old_sha1_prefix, sha1) ||3036get_sha1_hex(patch->new_sha1_prefix, sha1))3037returnerror("cannot apply binary patch to '%s' "3038"without full index line", name);30393040if(patch->old_name) {3041/*3042 * See if the old one matches what the patch3043 * applies to.3044 */3045hash_sha1_file(img->buf, img->len, blob_type, sha1);3046if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3047returnerror("the patch applies to '%s' (%s), "3048"which does not match the "3049"current contents.",3050 name,sha1_to_hex(sha1));3051}3052else{3053/* Otherwise, the old one must be empty. */3054if(img->len)3055returnerror("the patch applies to an empty "3056"'%s' but it is not empty", name);3057}30583059get_sha1_hex(patch->new_sha1_prefix, sha1);3060if(is_null_sha1(sha1)) {3061clear_image(img);3062return0;/* deletion patch */3063}30643065if(has_sha1_file(sha1)) {3066/* We already have the postimage */3067enum object_type type;3068unsigned long size;3069char*result;30703071 result =read_sha1_file(sha1, &type, &size);3072if(!result)3073returnerror("the necessary postimage%sfor "3074"'%s' cannot be read",3075 patch->new_sha1_prefix, name);3076clear_image(img);3077 img->buf = result;3078 img->len = size;3079}else{3080/*3081 * We have verified buf matches the preimage;3082 * apply the patch data to it, which is stored3083 * in the patch->fragments->{patch,size}.3084 */3085if(apply_binary_fragment(state, img, patch))3086returnerror(_("binary patch does not apply to '%s'"),3087 name);30883089/* verify that the result matches */3090hash_sha1_file(img->buf, img->len, blob_type, sha1);3091if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3092returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3093 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3094}30953096return0;3097}30983099static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3100{3101struct fragment *frag = patch->fragments;3102const char*name = patch->old_name ? patch->old_name : patch->new_name;3103unsigned ws_rule = patch->ws_rule;3104unsigned inaccurate_eof = patch->inaccurate_eof;3105int nth =0;31063107if(patch->is_binary)3108returnapply_binary(state, img, patch);31093110while(frag) {3111 nth++;3112if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3113error(_("patch failed:%s:%ld"), name, frag->oldpos);3114if(!state->apply_with_reject)3115return-1;3116 frag->rejected =1;3117}3118 frag = frag->next;3119}3120return0;3121}31223123static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3124{3125if(S_ISGITLINK(mode)) {3126strbuf_grow(buf,100);3127strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3128}else{3129enum object_type type;3130unsigned long sz;3131char*result;31323133 result =read_sha1_file(sha1, &type, &sz);3134if(!result)3135return-1;3136/* XXX read_sha1_file NUL-terminates */3137strbuf_attach(buf, result, sz, sz +1);3138}3139return0;3140}31413142static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3143{3144if(!ce)3145return0;3146returnread_blob_object(buf, ce->sha1, ce->ce_mode);3147}31483149static struct patch *in_fn_table(struct apply_state *state,const char*name)3150{3151struct string_list_item *item;31523153if(name == NULL)3154return NULL;31553156 item =string_list_lookup(&state->fn_table, name);3157if(item != NULL)3158return(struct patch *)item->util;31593160return NULL;3161}31623163/*3164 * item->util in the filename table records the status of the path.3165 * Usually it points at a patch (whose result records the contents3166 * of it after applying it), but it could be PATH_WAS_DELETED for a3167 * path that a previously applied patch has already removed, or3168 * PATH_TO_BE_DELETED for a path that a later patch would remove.3169 *3170 * The latter is needed to deal with a case where two paths A and B3171 * are swapped by first renaming A to B and then renaming B to A;3172 * moving A to B should not be prevented due to presence of B as we3173 * will remove it in a later patch.3174 */3175#define PATH_TO_BE_DELETED ((struct patch *) -2)3176#define PATH_WAS_DELETED ((struct patch *) -1)31773178static intto_be_deleted(struct patch *patch)3179{3180return patch == PATH_TO_BE_DELETED;3181}31823183static intwas_deleted(struct patch *patch)3184{3185return patch == PATH_WAS_DELETED;3186}31873188static voidadd_to_fn_table(struct apply_state *state,struct patch *patch)3189{3190struct string_list_item *item;31913192/*3193 * Always add new_name unless patch is a deletion3194 * This should cover the cases for normal diffs,3195 * file creations and copies3196 */3197if(patch->new_name != NULL) {3198 item =string_list_insert(&state->fn_table, patch->new_name);3199 item->util = patch;3200}32013202/*3203 * store a failure on rename/deletion cases because3204 * later chunks shouldn't patch old names3205 */3206if((patch->new_name == NULL) || (patch->is_rename)) {3207 item =string_list_insert(&state->fn_table, patch->old_name);3208 item->util = PATH_WAS_DELETED;3209}3210}32113212static voidprepare_fn_table(struct apply_state *state,struct patch *patch)3213{3214/*3215 * store information about incoming file deletion3216 */3217while(patch) {3218if((patch->new_name == NULL) || (patch->is_rename)) {3219struct string_list_item *item;3220 item =string_list_insert(&state->fn_table, patch->old_name);3221 item->util = PATH_TO_BE_DELETED;3222}3223 patch = patch->next;3224}3225}32263227static intcheckout_target(struct index_state *istate,3228struct cache_entry *ce,struct stat *st)3229{3230struct checkout costate;32313232memset(&costate,0,sizeof(costate));3233 costate.base_dir ="";3234 costate.refresh_cache =1;3235 costate.istate = istate;3236if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3237returnerror(_("cannot checkout%s"), ce->name);3238return0;3239}32403241static struct patch *previous_patch(struct apply_state *state,3242struct patch *patch,3243int*gone)3244{3245struct patch *previous;32463247*gone =0;3248if(patch->is_copy || patch->is_rename)3249return NULL;/* "git" patches do not depend on the order */32503251 previous =in_fn_table(state, patch->old_name);3252if(!previous)3253return NULL;32543255if(to_be_deleted(previous))3256return NULL;/* the deletion hasn't happened yet */32573258if(was_deleted(previous))3259*gone =1;32603261return previous;3262}32633264static intverify_index_match(const struct cache_entry *ce,struct stat *st)3265{3266if(S_ISGITLINK(ce->ce_mode)) {3267if(!S_ISDIR(st->st_mode))3268return-1;3269return0;3270}3271returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3272}32733274#define SUBMODULE_PATCH_WITHOUT_INDEX 132753276static intload_patch_target(struct apply_state *state,3277struct strbuf *buf,3278const struct cache_entry *ce,3279struct stat *st,3280const char*name,3281unsigned expected_mode)3282{3283if(state->cached || state->check_index) {3284if(read_file_or_gitlink(ce, buf))3285returnerror(_("failed to read%s"), name);3286}else if(name) {3287if(S_ISGITLINK(expected_mode)) {3288if(ce)3289returnread_file_or_gitlink(ce, buf);3290else3291return SUBMODULE_PATCH_WITHOUT_INDEX;3292}else if(has_symlink_leading_path(name,strlen(name))) {3293returnerror(_("reading from '%s' beyond a symbolic link"), name);3294}else{3295if(read_old_data(st, name, buf))3296returnerror(_("failed to read%s"), name);3297}3298}3299return0;3300}33013302/*3303 * We are about to apply "patch"; populate the "image" with the3304 * current version we have, from the working tree or from the index,3305 * depending on the situation e.g. --cached/--index. If we are3306 * applying a non-git patch that incrementally updates the tree,3307 * we read from the result of a previous diff.3308 */3309static intload_preimage(struct apply_state *state,3310struct image *image,3311struct patch *patch,struct stat *st,3312const struct cache_entry *ce)3313{3314struct strbuf buf = STRBUF_INIT;3315size_t len;3316char*img;3317struct patch *previous;3318int status;33193320 previous =previous_patch(state, patch, &status);3321if(status)3322returnerror(_("path%shas been renamed/deleted"),3323 patch->old_name);3324if(previous) {3325/* We have a patched copy in memory; use that. */3326strbuf_add(&buf, previous->result, previous->resultsize);3327}else{3328 status =load_patch_target(state, &buf, ce, st,3329 patch->old_name, patch->old_mode);3330if(status <0)3331return status;3332else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3333/*3334 * There is no way to apply subproject3335 * patch without looking at the index.3336 * NEEDSWORK: shouldn't this be flagged3337 * as an error???3338 */3339free_fragment_list(patch->fragments);3340 patch->fragments = NULL;3341}else if(status) {3342returnerror(_("failed to read%s"), patch->old_name);3343}3344}33453346 img =strbuf_detach(&buf, &len);3347prepare_image(image, img, len, !patch->is_binary);3348return0;3349}33503351static intthree_way_merge(struct image *image,3352char*path,3353const unsigned char*base,3354const unsigned char*ours,3355const unsigned char*theirs)3356{3357 mmfile_t base_file, our_file, their_file;3358 mmbuffer_t result = { NULL };3359int status;33603361read_mmblob(&base_file, base);3362read_mmblob(&our_file, ours);3363read_mmblob(&their_file, theirs);3364 status =ll_merge(&result, path,3365&base_file,"base",3366&our_file,"ours",3367&their_file,"theirs", NULL);3368free(base_file.ptr);3369free(our_file.ptr);3370free(their_file.ptr);3371if(status <0|| !result.ptr) {3372free(result.ptr);3373return-1;3374}3375clear_image(image);3376 image->buf = result.ptr;3377 image->len = result.size;33783379return status;3380}33813382/*3383 * When directly falling back to add/add three-way merge, we read from3384 * the current contents of the new_name. In no cases other than that3385 * this function will be called.3386 */3387static intload_current(struct apply_state *state,3388struct image *image,3389struct patch *patch)3390{3391struct strbuf buf = STRBUF_INIT;3392int status, pos;3393size_t len;3394char*img;3395struct stat st;3396struct cache_entry *ce;3397char*name = patch->new_name;3398unsigned mode = patch->new_mode;33993400if(!patch->is_new)3401die("BUG: patch to%sis not a creation", patch->old_name);34023403 pos =cache_name_pos(name,strlen(name));3404if(pos <0)3405returnerror(_("%s: does not exist in index"), name);3406 ce = active_cache[pos];3407if(lstat(name, &st)) {3408if(errno != ENOENT)3409returnerror(_("%s:%s"), name,strerror(errno));3410if(checkout_target(&the_index, ce, &st))3411return-1;3412}3413if(verify_index_match(ce, &st))3414returnerror(_("%s: does not match index"), name);34153416 status =load_patch_target(state, &buf, ce, &st, name, mode);3417if(status <0)3418return status;3419else if(status)3420return-1;3421 img =strbuf_detach(&buf, &len);3422prepare_image(image, img, len, !patch->is_binary);3423return0;3424}34253426static inttry_threeway(struct apply_state *state,3427struct image *image,3428struct patch *patch,3429struct stat *st,3430const struct cache_entry *ce)3431{3432unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3433struct strbuf buf = STRBUF_INIT;3434size_t len;3435int status;3436char*img;3437struct image tmp_image;34383439/* No point falling back to 3-way merge in these cases */3440if(patch->is_delete ||3441S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3442return-1;34433444/* Preimage the patch was prepared for */3445if(patch->is_new)3446write_sha1_file("",0, blob_type, pre_sha1);3447else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3448read_blob_object(&buf, pre_sha1, patch->old_mode))3449returnerror("repository lacks the necessary blob to fall back on 3-way merge.");34503451fprintf(stderr,"Falling back to three-way merge...\n");34523453 img =strbuf_detach(&buf, &len);3454prepare_image(&tmp_image, img, len,1);3455/* Apply the patch to get the post image */3456if(apply_fragments(state, &tmp_image, patch) <0) {3457clear_image(&tmp_image);3458return-1;3459}3460/* post_sha1[] is theirs */3461write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3462clear_image(&tmp_image);34633464/* our_sha1[] is ours */3465if(patch->is_new) {3466if(load_current(state, &tmp_image, patch))3467returnerror("cannot read the current contents of '%s'",3468 patch->new_name);3469}else{3470if(load_preimage(state, &tmp_image, patch, st, ce))3471returnerror("cannot read the current contents of '%s'",3472 patch->old_name);3473}3474write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3475clear_image(&tmp_image);34763477/* in-core three-way merge between post and our using pre as base */3478 status =three_way_merge(image, patch->new_name,3479 pre_sha1, our_sha1, post_sha1);3480if(status <0) {3481fprintf(stderr,"Failed to fall back on three-way merge...\n");3482return status;3483}34843485if(status) {3486 patch->conflicted_threeway =1;3487if(patch->is_new)3488oidclr(&patch->threeway_stage[0]);3489else3490hashcpy(patch->threeway_stage[0].hash, pre_sha1);3491hashcpy(patch->threeway_stage[1].hash, our_sha1);3492hashcpy(patch->threeway_stage[2].hash, post_sha1);3493fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3494}else{3495fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3496}3497return0;3498}34993500static intapply_data(struct apply_state *state,struct patch *patch,3501struct stat *st,const struct cache_entry *ce)3502{3503struct image image;35043505if(load_preimage(state, &image, patch, st, ce) <0)3506return-1;35073508if(patch->direct_to_threeway ||3509apply_fragments(state, &image, patch) <0) {3510/* Note: with --reject, apply_fragments() returns 0 */3511if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3512return-1;3513}3514 patch->result = image.buf;3515 patch->resultsize = image.len;3516add_to_fn_table(state, patch);3517free(image.line_allocated);35183519if(0< patch->is_delete && patch->resultsize)3520returnerror(_("removal patch leaves file contents"));35213522return0;3523}35243525/*3526 * If "patch" that we are looking at modifies or deletes what we have,3527 * we would want it not to lose any local modification we have, either3528 * in the working tree or in the index.3529 *3530 * This also decides if a non-git patch is a creation patch or a3531 * modification to an existing empty file. We do not check the state3532 * of the current tree for a creation patch in this function; the caller3533 * check_patch() separately makes sure (and errors out otherwise) that3534 * the path the patch creates does not exist in the current tree.3535 */3536static intcheck_preimage(struct apply_state *state,3537struct patch *patch,3538struct cache_entry **ce,3539struct stat *st)3540{3541const char*old_name = patch->old_name;3542struct patch *previous = NULL;3543int stat_ret =0, status;3544unsigned st_mode =0;35453546if(!old_name)3547return0;35483549assert(patch->is_new <=0);3550 previous =previous_patch(state, patch, &status);35513552if(status)3553returnerror(_("path%shas been renamed/deleted"), old_name);3554if(previous) {3555 st_mode = previous->new_mode;3556}else if(!state->cached) {3557 stat_ret =lstat(old_name, st);3558if(stat_ret && errno != ENOENT)3559returnerror(_("%s:%s"), old_name,strerror(errno));3560}35613562if(state->check_index && !previous) {3563int pos =cache_name_pos(old_name,strlen(old_name));3564if(pos <0) {3565if(patch->is_new <0)3566goto is_new;3567returnerror(_("%s: does not exist in index"), old_name);3568}3569*ce = active_cache[pos];3570if(stat_ret <0) {3571if(checkout_target(&the_index, *ce, st))3572return-1;3573}3574if(!state->cached &&verify_index_match(*ce, st))3575returnerror(_("%s: does not match index"), old_name);3576if(state->cached)3577 st_mode = (*ce)->ce_mode;3578}else if(stat_ret <0) {3579if(patch->is_new <0)3580goto is_new;3581returnerror(_("%s:%s"), old_name,strerror(errno));3582}35833584if(!state->cached && !previous)3585 st_mode =ce_mode_from_stat(*ce, st->st_mode);35863587if(patch->is_new <0)3588 patch->is_new =0;3589if(!patch->old_mode)3590 patch->old_mode = st_mode;3591if((st_mode ^ patch->old_mode) & S_IFMT)3592returnerror(_("%s: wrong type"), old_name);3593if(st_mode != patch->old_mode)3594warning(_("%shas type%o, expected%o"),3595 old_name, st_mode, patch->old_mode);3596if(!patch->new_mode && !patch->is_delete)3597 patch->new_mode = st_mode;3598return0;35993600 is_new:3601 patch->is_new =1;3602 patch->is_delete =0;3603free(patch->old_name);3604 patch->old_name = NULL;3605return0;3606}360736083609#define EXISTS_IN_INDEX 13610#define EXISTS_IN_WORKTREE 236113612static intcheck_to_create(struct apply_state *state,3613const char*new_name,3614int ok_if_exists)3615{3616struct stat nst;36173618if(state->check_index &&3619cache_name_pos(new_name,strlen(new_name)) >=0&&3620!ok_if_exists)3621return EXISTS_IN_INDEX;3622if(state->cached)3623return0;36243625if(!lstat(new_name, &nst)) {3626if(S_ISDIR(nst.st_mode) || ok_if_exists)3627return0;3628/*3629 * A leading component of new_name might be a symlink3630 * that is going to be removed with this patch, but3631 * still pointing at somewhere that has the path.3632 * In such a case, path "new_name" does not exist as3633 * far as git is concerned.3634 */3635if(has_symlink_leading_path(new_name,strlen(new_name)))3636return0;36373638return EXISTS_IN_WORKTREE;3639}else if((errno != ENOENT) && (errno != ENOTDIR)) {3640returnerror("%s:%s", new_name,strerror(errno));3641}3642return0;3643}36443645static uintptr_tregister_symlink_changes(struct apply_state *state,3646const char*path,3647uintptr_t what)3648{3649struct string_list_item *ent;36503651 ent =string_list_lookup(&state->symlink_changes, path);3652if(!ent) {3653 ent =string_list_insert(&state->symlink_changes, path);3654 ent->util = (void*)0;3655}3656 ent->util = (void*)(what | ((uintptr_t)ent->util));3657return(uintptr_t)ent->util;3658}36593660static uintptr_tcheck_symlink_changes(struct apply_state *state,const char*path)3661{3662struct string_list_item *ent;36633664 ent =string_list_lookup(&state->symlink_changes, path);3665if(!ent)3666return0;3667return(uintptr_t)ent->util;3668}36693670static voidprepare_symlink_changes(struct apply_state *state,struct patch *patch)3671{3672for( ; patch; patch = patch->next) {3673if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3674(patch->is_rename || patch->is_delete))3675/* the symlink at patch->old_name is removed */3676register_symlink_changes(state, patch->old_name, APPLY_SYMLINK_GOES_AWAY);36773678if(patch->new_name &&S_ISLNK(patch->new_mode))3679/* the symlink at patch->new_name is created or remains */3680register_symlink_changes(state, patch->new_name, APPLY_SYMLINK_IN_RESULT);3681}3682}36833684static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3685{3686do{3687unsigned int change;36883689while(--name->len && name->buf[name->len] !='/')3690;/* scan backwards */3691if(!name->len)3692break;3693 name->buf[name->len] ='\0';3694 change =check_symlink_changes(state, name->buf);3695if(change & APPLY_SYMLINK_IN_RESULT)3696return1;3697if(change & APPLY_SYMLINK_GOES_AWAY)3698/*3699 * This cannot be "return 0", because we may3700 * see a new one created at a higher level.3701 */3702continue;37033704/* otherwise, check the preimage */3705if(state->check_index) {3706struct cache_entry *ce;37073708 ce =cache_file_exists(name->buf, name->len, ignore_case);3709if(ce &&S_ISLNK(ce->ce_mode))3710return1;3711}else{3712struct stat st;3713if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3714return1;3715}3716}while(1);3717return0;3718}37193720static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3721{3722int ret;3723struct strbuf name = STRBUF_INIT;37243725assert(*name_ !='\0');3726strbuf_addstr(&name, name_);3727 ret =path_is_beyond_symlink_1(state, &name);3728strbuf_release(&name);37293730return ret;3731}37323733static voiddie_on_unsafe_path(struct patch *patch)3734{3735const char*old_name = NULL;3736const char*new_name = NULL;3737if(patch->is_delete)3738 old_name = patch->old_name;3739else if(!patch->is_new && !patch->is_copy)3740 old_name = patch->old_name;3741if(!patch->is_delete)3742 new_name = patch->new_name;37433744if(old_name && !verify_path(old_name))3745die(_("invalid path '%s'"), old_name);3746if(new_name && !verify_path(new_name))3747die(_("invalid path '%s'"), new_name);3748}37493750/*3751 * Check and apply the patch in-core; leave the result in patch->result3752 * for the caller to write it out to the final destination.3753 */3754static intcheck_patch(struct apply_state *state,struct patch *patch)3755{3756struct stat st;3757const char*old_name = patch->old_name;3758const char*new_name = patch->new_name;3759const char*name = old_name ? old_name : new_name;3760struct cache_entry *ce = NULL;3761struct patch *tpatch;3762int ok_if_exists;3763int status;37643765 patch->rejected =1;/* we will drop this after we succeed */37663767 status =check_preimage(state, patch, &ce, &st);3768if(status)3769return status;3770 old_name = patch->old_name;37713772/*3773 * A type-change diff is always split into a patch to delete3774 * old, immediately followed by a patch to create new (see3775 * diff.c::run_diff()); in such a case it is Ok that the entry3776 * to be deleted by the previous patch is still in the working3777 * tree and in the index.3778 *3779 * A patch to swap-rename between A and B would first rename A3780 * to B and then rename B to A. While applying the first one,3781 * the presence of B should not stop A from getting renamed to3782 * B; ask to_be_deleted() about the later rename. Removal of3783 * B and rename from A to B is handled the same way by asking3784 * was_deleted().3785 */3786if((tpatch =in_fn_table(state, new_name)) &&3787(was_deleted(tpatch) ||to_be_deleted(tpatch)))3788 ok_if_exists =1;3789else3790 ok_if_exists =0;37913792if(new_name &&3793((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3794int err =check_to_create(state, new_name, ok_if_exists);37953796if(err && state->threeway) {3797 patch->direct_to_threeway =1;3798}else switch(err) {3799case0:3800break;/* happy */3801case EXISTS_IN_INDEX:3802returnerror(_("%s: already exists in index"), new_name);3803break;3804case EXISTS_IN_WORKTREE:3805returnerror(_("%s: already exists in working directory"),3806 new_name);3807default:3808return err;3809}38103811if(!patch->new_mode) {3812if(0< patch->is_new)3813 patch->new_mode = S_IFREG |0644;3814else3815 patch->new_mode = patch->old_mode;3816}3817}38183819if(new_name && old_name) {3820int same = !strcmp(old_name, new_name);3821if(!patch->new_mode)3822 patch->new_mode = patch->old_mode;3823if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3824if(same)3825returnerror(_("new mode (%o) of%sdoes not "3826"match old mode (%o)"),3827 patch->new_mode, new_name,3828 patch->old_mode);3829else3830returnerror(_("new mode (%o) of%sdoes not "3831"match old mode (%o) of%s"),3832 patch->new_mode, new_name,3833 patch->old_mode, old_name);3834}3835}38363837if(!state->unsafe_paths)3838die_on_unsafe_path(patch);38393840/*3841 * An attempt to read from or delete a path that is beyond a3842 * symbolic link will be prevented by load_patch_target() that3843 * is called at the beginning of apply_data() so we do not3844 * have to worry about a patch marked with "is_delete" bit3845 * here. We however need to make sure that the patch result3846 * is not deposited to a path that is beyond a symbolic link3847 * here.3848 */3849if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3850returnerror(_("affected file '%s' is beyond a symbolic link"),3851 patch->new_name);38523853if(apply_data(state, patch, &st, ce) <0)3854returnerror(_("%s: patch does not apply"), name);3855 patch->rejected =0;3856return0;3857}38583859static intcheck_patch_list(struct apply_state *state,struct patch *patch)3860{3861int err =0;38623863prepare_symlink_changes(state, patch);3864prepare_fn_table(state, patch);3865while(patch) {3866if(state->apply_verbosely)3867say_patch_name(stderr,3868_("Checking patch%s..."), patch);3869 err |=check_patch(state, patch);3870 patch = patch->next;3871}3872return err;3873}38743875/* This function tries to read the sha1 from the current index */3876static intget_current_sha1(const char*path,unsigned char*sha1)3877{3878int pos;38793880if(read_cache() <0)3881return-1;3882 pos =cache_name_pos(path,strlen(path));3883if(pos <0)3884return-1;3885hashcpy(sha1, active_cache[pos]->sha1);3886return0;3887}38883889static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3890{3891/*3892 * A usable gitlink patch has only one fragment (hunk) that looks like:3893 * @@ -1 +1 @@3894 * -Subproject commit <old sha1>3895 * +Subproject commit <new sha1>3896 * or3897 * @@ -1 +0,0 @@3898 * -Subproject commit <old sha1>3899 * for a removal patch.3900 */3901struct fragment *hunk = p->fragments;3902static const char heading[] ="-Subproject commit ";3903char*preimage;39043905if(/* does the patch have only one hunk? */3906 hunk && !hunk->next &&3907/* is its preimage one line? */3908 hunk->oldpos ==1&& hunk->oldlines ==1&&3909/* does preimage begin with the heading? */3910(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3911starts_with(++preimage, heading) &&3912/* does it record full SHA-1? */3913!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3914 preimage[sizeof(heading) +40-1] =='\n'&&3915/* does the abbreviated name on the index line agree with it? */3916starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3917return0;/* it all looks fine */39183919/* we may have full object name on the index line */3920returnget_sha1_hex(p->old_sha1_prefix, sha1);3921}39223923/* Build an index that contains the just the files needed for a 3way merge */3924static voidbuild_fake_ancestor(struct patch *list,const char*filename)3925{3926struct patch *patch;3927struct index_state result = { NULL };3928static struct lock_file lock;39293930/* Once we start supporting the reverse patch, it may be3931 * worth showing the new sha1 prefix, but until then...3932 */3933for(patch = list; patch; patch = patch->next) {3934unsigned char sha1[20];3935struct cache_entry *ce;3936const char*name;39373938 name = patch->old_name ? patch->old_name : patch->new_name;3939if(0< patch->is_new)3940continue;39413942if(S_ISGITLINK(patch->old_mode)) {3943if(!preimage_sha1_in_gitlink_patch(patch, sha1))3944;/* ok, the textual part looks sane */3945else3946die("sha1 information is lacking or useless for submodule%s",3947 name);3948}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {3949;/* ok */3950}else if(!patch->lines_added && !patch->lines_deleted) {3951/* mode-only change: update the current */3952if(get_current_sha1(patch->old_name, sha1))3953die("mode change for%s, which is not "3954"in current HEAD", name);3955}else3956die("sha1 information is lacking or useless "3957"(%s).", name);39583959 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);3960if(!ce)3961die(_("make_cache_entry failed for path '%s'"), name);3962if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3963die("Could not add%sto temporary index", name);3964}39653966hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);3967if(write_locked_index(&result, &lock, COMMIT_LOCK))3968die("Could not write temporary index to%s", filename);39693970discard_index(&result);3971}39723973static voidstat_patch_list(struct apply_state *state,struct patch *patch)3974{3975int files, adds, dels;39763977for(files = adds = dels =0; patch ; patch = patch->next) {3978 files++;3979 adds += patch->lines_added;3980 dels += patch->lines_deleted;3981show_stats(state, patch);3982}39833984print_stat_summary(stdout, files, adds, dels);3985}39863987static voidnumstat_patch_list(struct apply_state *state,3988struct patch *patch)3989{3990for( ; patch; patch = patch->next) {3991const char*name;3992 name = patch->new_name ? patch->new_name : patch->old_name;3993if(patch->is_binary)3994printf("-\t-\t");3995else3996printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3997write_name_quoted(name, stdout, state->line_termination);3998}3999}40004001static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4002{4003if(mode)4004printf("%smode%06o%s\n", newdelete, mode, name);4005else4006printf("%s %s\n", newdelete, name);4007}40084009static voidshow_mode_change(struct patch *p,int show_name)4010{4011if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4012if(show_name)4013printf(" mode change%06o =>%06o%s\n",4014 p->old_mode, p->new_mode, p->new_name);4015else4016printf(" mode change%06o =>%06o\n",4017 p->old_mode, p->new_mode);4018}4019}40204021static voidshow_rename_copy(struct patch *p)4022{4023const char*renamecopy = p->is_rename ?"rename":"copy";4024const char*old, *new;40254026/* Find common prefix */4027 old = p->old_name;4028new= p->new_name;4029while(1) {4030const char*slash_old, *slash_new;4031 slash_old =strchr(old,'/');4032 slash_new =strchr(new,'/');4033if(!slash_old ||4034!slash_new ||4035 slash_old - old != slash_new -new||4036memcmp(old,new, slash_new -new))4037break;4038 old = slash_old +1;4039new= slash_new +1;4040}4041/* p->old_name thru old is the common prefix, and old and new4042 * through the end of names are renames4043 */4044if(old != p->old_name)4045printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4046(int)(old - p->old_name), p->old_name,4047 old,new, p->score);4048else4049printf("%s %s=>%s(%d%%)\n", renamecopy,4050 p->old_name, p->new_name, p->score);4051show_mode_change(p,0);4052}40534054static voidsummary_patch_list(struct patch *patch)4055{4056struct patch *p;40574058for(p = patch; p; p = p->next) {4059if(p->is_new)4060show_file_mode_name("create", p->new_mode, p->new_name);4061else if(p->is_delete)4062show_file_mode_name("delete", p->old_mode, p->old_name);4063else{4064if(p->is_rename || p->is_copy)4065show_rename_copy(p);4066else{4067if(p->score) {4068printf(" rewrite%s(%d%%)\n",4069 p->new_name, p->score);4070show_mode_change(p,0);4071}4072else4073show_mode_change(p,1);4074}4075}4076}4077}40784079static voidpatch_stats(struct apply_state *state,struct patch *patch)4080{4081int lines = patch->lines_added + patch->lines_deleted;40824083if(lines > state->max_change)4084 state->max_change = lines;4085if(patch->old_name) {4086int len =quote_c_style(patch->old_name, NULL, NULL,0);4087if(!len)4088 len =strlen(patch->old_name);4089if(len > state->max_len)4090 state->max_len = len;4091}4092if(patch->new_name) {4093int len =quote_c_style(patch->new_name, NULL, NULL,0);4094if(!len)4095 len =strlen(patch->new_name);4096if(len > state->max_len)4097 state->max_len = len;4098}4099}41004101static voidremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4102{4103if(state->update_index) {4104if(remove_file_from_cache(patch->old_name) <0)4105die(_("unable to remove%sfrom index"), patch->old_name);4106}4107if(!state->cached) {4108if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4109remove_path(patch->old_name);4110}4111}4112}41134114static voidadd_index_file(struct apply_state *state,4115const char*path,4116unsigned mode,4117void*buf,4118unsigned long size)4119{4120struct stat st;4121struct cache_entry *ce;4122int namelen =strlen(path);4123unsigned ce_size =cache_entry_size(namelen);41244125if(!state->update_index)4126return;41274128 ce =xcalloc(1, ce_size);4129memcpy(ce->name, path, namelen);4130 ce->ce_mode =create_ce_mode(mode);4131 ce->ce_flags =create_ce_flags(0);4132 ce->ce_namelen = namelen;4133if(S_ISGITLINK(mode)) {4134const char*s;41354136if(!skip_prefix(buf,"Subproject commit ", &s) ||4137get_sha1_hex(s, ce->sha1))4138die(_("corrupt patch for submodule%s"), path);4139}else{4140if(!state->cached) {4141if(lstat(path, &st) <0)4142die_errno(_("unable to stat newly created file '%s'"),4143 path);4144fill_stat_cache_info(ce, &st);4145}4146if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4147die(_("unable to create backing store for newly created file%s"), path);4148}4149if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4150die(_("unable to add cache entry for%s"), path);4151}41524153static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4154{4155int fd;4156struct strbuf nbuf = STRBUF_INIT;41574158if(S_ISGITLINK(mode)) {4159struct stat st;4160if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4161return0;4162returnmkdir(path,0777);4163}41644165if(has_symlinks &&S_ISLNK(mode))4166/* Although buf:size is counted string, it also is NUL4167 * terminated.4168 */4169returnsymlink(buf, path);41704171 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4172if(fd <0)4173return-1;41744175if(convert_to_working_tree(path, buf, size, &nbuf)) {4176 size = nbuf.len;4177 buf = nbuf.buf;4178}4179write_or_die(fd, buf, size);4180strbuf_release(&nbuf);41814182if(close(fd) <0)4183die_errno(_("closing file '%s'"), path);4184return0;4185}41864187/*4188 * We optimistically assume that the directories exist,4189 * which is true 99% of the time anyway. If they don't,4190 * we create them and try again.4191 */4192static voidcreate_one_file(struct apply_state *state,4193char*path,4194unsigned mode,4195const char*buf,4196unsigned long size)4197{4198if(state->cached)4199return;4200if(!try_create_file(path, mode, buf, size))4201return;42024203if(errno == ENOENT) {4204if(safe_create_leading_directories(path))4205return;4206if(!try_create_file(path, mode, buf, size))4207return;4208}42094210if(errno == EEXIST || errno == EACCES) {4211/* We may be trying to create a file where a directory4212 * used to be.4213 */4214struct stat st;4215if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4216 errno = EEXIST;4217}42184219if(errno == EEXIST) {4220unsigned int nr =getpid();42214222for(;;) {4223char newpath[PATH_MAX];4224mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4225if(!try_create_file(newpath, mode, buf, size)) {4226if(!rename(newpath, path))4227return;4228unlink_or_warn(newpath);4229break;4230}4231if(errno != EEXIST)4232break;4233++nr;4234}4235}4236die_errno(_("unable to write file '%s' mode%o"), path, mode);4237}42384239static voidadd_conflicted_stages_file(struct apply_state *state,4240struct patch *patch)4241{4242int stage, namelen;4243unsigned ce_size, mode;4244struct cache_entry *ce;42454246if(!state->update_index)4247return;4248 namelen =strlen(patch->new_name);4249 ce_size =cache_entry_size(namelen);4250 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);42514252remove_file_from_cache(patch->new_name);4253for(stage =1; stage <4; stage++) {4254if(is_null_oid(&patch->threeway_stage[stage -1]))4255continue;4256 ce =xcalloc(1, ce_size);4257memcpy(ce->name, patch->new_name, namelen);4258 ce->ce_mode =create_ce_mode(mode);4259 ce->ce_flags =create_ce_flags(stage);4260 ce->ce_namelen = namelen;4261hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4262if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4263die(_("unable to add cache entry for%s"), patch->new_name);4264}4265}42664267static voidcreate_file(struct apply_state *state,struct patch *patch)4268{4269char*path = patch->new_name;4270unsigned mode = patch->new_mode;4271unsigned long size = patch->resultsize;4272char*buf = patch->result;42734274if(!mode)4275 mode = S_IFREG |0644;4276create_one_file(state, path, mode, buf, size);42774278if(patch->conflicted_threeway)4279add_conflicted_stages_file(state, patch);4280else4281add_index_file(state, path, mode, buf, size);4282}42834284/* phase zero is to remove, phase one is to create */4285static voidwrite_out_one_result(struct apply_state *state,4286struct patch *patch,4287int phase)4288{4289if(patch->is_delete >0) {4290if(phase ==0)4291remove_file(state, patch,1);4292return;4293}4294if(patch->is_new >0|| patch->is_copy) {4295if(phase ==1)4296create_file(state, patch);4297return;4298}4299/*4300 * Rename or modification boils down to the same4301 * thing: remove the old, write the new4302 */4303if(phase ==0)4304remove_file(state, patch, patch->is_rename);4305if(phase ==1)4306create_file(state, patch);4307}43084309static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4310{4311FILE*rej;4312char namebuf[PATH_MAX];4313struct fragment *frag;4314int cnt =0;4315struct strbuf sb = STRBUF_INIT;43164317for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4318if(!frag->rejected)4319continue;4320 cnt++;4321}43224323if(!cnt) {4324if(state->apply_verbosely)4325say_patch_name(stderr,4326_("Applied patch%scleanly."), patch);4327return0;4328}43294330/* This should not happen, because a removal patch that leaves4331 * contents are marked "rejected" at the patch level.4332 */4333if(!patch->new_name)4334die(_("internal error"));43354336/* Say this even without --verbose */4337strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4338"Applying patch %%swith%drejects...",4339 cnt),4340 cnt);4341say_patch_name(stderr, sb.buf, patch);4342strbuf_release(&sb);43434344 cnt =strlen(patch->new_name);4345if(ARRAY_SIZE(namebuf) <= cnt +5) {4346 cnt =ARRAY_SIZE(namebuf) -5;4347warning(_("truncating .rej filename to %.*s.rej"),4348 cnt -1, patch->new_name);4349}4350memcpy(namebuf, patch->new_name, cnt);4351memcpy(namebuf + cnt,".rej",5);43524353 rej =fopen(namebuf,"w");4354if(!rej)4355returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));43564357/* Normal git tools never deal with .rej, so do not pretend4358 * this is a git patch by saying --git or giving extended4359 * headers. While at it, maybe please "kompare" that wants4360 * the trailing TAB and some garbage at the end of line ;-).4361 */4362fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4363 patch->new_name, patch->new_name);4364for(cnt =1, frag = patch->fragments;4365 frag;4366 cnt++, frag = frag->next) {4367if(!frag->rejected) {4368fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4369continue;4370}4371fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4372fprintf(rej,"%.*s", frag->size, frag->patch);4373if(frag->patch[frag->size-1] !='\n')4374fputc('\n', rej);4375}4376fclose(rej);4377return-1;4378}43794380static intwrite_out_results(struct apply_state *state,struct patch *list)4381{4382int phase;4383int errs =0;4384struct patch *l;4385struct string_list cpath = STRING_LIST_INIT_DUP;43864387for(phase =0; phase <2; phase++) {4388 l = list;4389while(l) {4390if(l->rejected)4391 errs =1;4392else{4393write_out_one_result(state, l, phase);4394if(phase ==1) {4395if(write_out_one_reject(state, l))4396 errs =1;4397if(l->conflicted_threeway) {4398string_list_append(&cpath, l->new_name);4399 errs =1;4400}4401}4402}4403 l = l->next;4404}4405}44064407if(cpath.nr) {4408struct string_list_item *item;44094410string_list_sort(&cpath);4411for_each_string_list_item(item, &cpath)4412fprintf(stderr,"U%s\n", item->string);4413string_list_clear(&cpath,0);44144415rerere(0);4416}44174418return errs;4419}44204421static struct lock_file lock_file;44224423#define INACCURATE_EOF (1<<0)4424#define RECOUNT (1<<1)44254426/*4427 * Try to apply a patch.4428 *4429 * Returns:4430 * -128 if a bad error happened (like patch unreadable)4431 * -1 if patch did not apply and user cannot deal with it4432 * 0 if the patch applied4433 * 1 if the patch did not apply but user might fix it4434 */4435static intapply_patch(struct apply_state *state,4436int fd,4437const char*filename,4438int options)4439{4440size_t offset;4441struct strbuf buf = STRBUF_INIT;/* owns the patch text */4442struct patch *list = NULL, **listp = &list;4443int skipped_patch =0;4444int res =0;44454446 state->patch_input_file = filename;4447if(read_patch_file(&buf, fd) <0)4448return-128;4449 offset =0;4450while(offset < buf.len) {4451struct patch *patch;4452int nr;44534454 patch =xcalloc(1,sizeof(*patch));4455 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4456 patch->recount = !!(options & RECOUNT);4457 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4458if(nr <0) {4459free_patch(patch);4460if(nr == -128) {4461 res = -128;4462goto end;4463}4464break;4465}4466if(state->apply_in_reverse)4467reverse_patches(patch);4468if(use_patch(state, patch)) {4469patch_stats(state, patch);4470*listp = patch;4471 listp = &patch->next;4472}4473else{4474if(state->apply_verbosely)4475say_patch_name(stderr,_("Skipped patch '%s'."), patch);4476free_patch(patch);4477 skipped_patch++;4478}4479 offset += nr;4480}44814482if(!list && !skipped_patch) {4483error(_("unrecognized input"));4484 res = -128;4485goto end;4486}44874488if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4489 state->apply =0;44904491 state->update_index = state->check_index && state->apply;4492if(state->update_index && state->newfd <0)4493 state->newfd =hold_locked_index(state->lock_file,1);44944495if(state->check_index &&read_cache() <0) {4496error(_("unable to read index file"));4497 res = -128;4498goto end;4499}45004501if((state->check || state->apply) &&4502check_patch_list(state, list) <0&&4503!state->apply_with_reject) {4504 res = -1;4505goto end;4506}45074508if(state->apply &&write_out_results(state, list)) {4509/* with --3way, we still need to write the index out */4510 res = state->apply_with_reject ? -1:1;4511goto end;4512}45134514if(state->fake_ancestor)4515build_fake_ancestor(list, state->fake_ancestor);45164517if(state->diffstat)4518stat_patch_list(state, list);45194520if(state->numstat)4521numstat_patch_list(state, list);45224523if(state->summary)4524summary_patch_list(list);45254526end:4527free_patch_list(list);4528strbuf_release(&buf);4529string_list_clear(&state->fn_table,0);4530return res;4531}45324533static voidgit_apply_config(void)4534{4535git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4536git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4537git_config(git_default_config, NULL);4538}45394540static intoption_parse_exclude(const struct option *opt,4541const char*arg,int unset)4542{4543struct apply_state *state = opt->value;4544add_name_limit(state, arg,1);4545return0;4546}45474548static intoption_parse_include(const struct option *opt,4549const char*arg,int unset)4550{4551struct apply_state *state = opt->value;4552add_name_limit(state, arg,0);4553 state->has_include =1;4554return0;4555}45564557static intoption_parse_p(const struct option *opt,4558const char*arg,4559int unset)4560{4561struct apply_state *state = opt->value;4562 state->p_value =atoi(arg);4563 state->p_value_known =1;4564return0;4565}45664567static intoption_parse_space_change(const struct option *opt,4568const char*arg,int unset)4569{4570struct apply_state *state = opt->value;4571if(unset)4572 state->ws_ignore_action = ignore_ws_none;4573else4574 state->ws_ignore_action = ignore_ws_change;4575return0;4576}45774578static intoption_parse_whitespace(const struct option *opt,4579const char*arg,int unset)4580{4581struct apply_state *state = opt->value;4582 state->whitespace_option = arg;4583parse_whitespace_option(state, arg);4584return0;4585}45864587static intoption_parse_directory(const struct option *opt,4588const char*arg,int unset)4589{4590struct apply_state *state = opt->value;4591strbuf_reset(&state->root);4592strbuf_addstr(&state->root, arg);4593strbuf_complete(&state->root,'/');4594return0;4595}45964597static voidinit_apply_state(struct apply_state *state,4598const char*prefix,4599struct lock_file *lock_file)4600{4601memset(state,0,sizeof(*state));4602 state->prefix = prefix;4603 state->prefix_length = state->prefix ?strlen(state->prefix) :0;4604 state->lock_file = lock_file;4605 state->newfd = -1;4606 state->apply =1;4607 state->line_termination ='\n';4608 state->p_value =1;4609 state->p_context = UINT_MAX;4610 state->squelch_whitespace_errors =5;4611 state->ws_error_action = warn_on_ws_error;4612 state->ws_ignore_action = ignore_ws_none;4613 state->linenr =1;4614string_list_init(&state->fn_table,0);4615string_list_init(&state->limit_by_name,0);4616string_list_init(&state->symlink_changes,0);4617strbuf_init(&state->root,0);46184619git_apply_config();4620if(apply_default_whitespace)4621parse_whitespace_option(state, apply_default_whitespace);4622if(apply_default_ignorewhitespace)4623parse_ignorewhitespace_option(state, apply_default_ignorewhitespace);4624}46254626static voidclear_apply_state(struct apply_state *state)4627{4628string_list_clear(&state->limit_by_name,0);4629string_list_clear(&state->symlink_changes,0);4630strbuf_release(&state->root);46314632/* &state->fn_table is cleared at the end of apply_patch() */4633}46344635static voidcheck_apply_state(struct apply_state *state,int force_apply)4636{4637int is_not_gitdir = !startup_info->have_repository;46384639if(state->apply_with_reject && state->threeway)4640die("--reject and --3way cannot be used together.");4641if(state->cached && state->threeway)4642die("--cached and --3way cannot be used together.");4643if(state->threeway) {4644if(is_not_gitdir)4645die(_("--3way outside a repository"));4646 state->check_index =1;4647}4648if(state->apply_with_reject)4649 state->apply = state->apply_verbosely =1;4650if(!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor))4651 state->apply =0;4652if(state->check_index && is_not_gitdir)4653die(_("--index outside a repository"));4654if(state->cached) {4655if(is_not_gitdir)4656die(_("--cached outside a repository"));4657 state->check_index =1;4658}4659if(state->check_index)4660 state->unsafe_paths =0;4661if(!state->lock_file)4662die("BUG: state->lock_file should not be NULL");4663}46644665static intapply_all_patches(struct apply_state *state,4666int argc,4667const char**argv,4668int options)4669{4670int i;4671int res;4672int errs =0;4673int read_stdin =1;46744675for(i =0; i < argc; i++) {4676const char*arg = argv[i];4677int fd;46784679if(!strcmp(arg,"-")) {4680 res =apply_patch(state,0,"<stdin>", options);4681if(res <0)4682goto end;4683 errs |= res;4684 read_stdin =0;4685continue;4686}else if(0< state->prefix_length)4687 arg =prefix_filename(state->prefix,4688 state->prefix_length,4689 arg);46904691 fd =open(arg, O_RDONLY);4692if(fd <0)4693die_errno(_("can't open patch '%s'"), arg);4694 read_stdin =0;4695set_default_whitespace_mode(state);4696 res =apply_patch(state, fd, arg, options);4697if(res <0)4698goto end;4699 errs |= res;4700close(fd);4701}4702set_default_whitespace_mode(state);4703if(read_stdin) {4704 res =apply_patch(state,0,"<stdin>", options);4705if(res <0)4706goto end;4707 errs |= res;4708}47094710if(state->whitespace_error) {4711if(state->squelch_whitespace_errors &&4712 state->squelch_whitespace_errors < state->whitespace_error) {4713int squelched =4714 state->whitespace_error - state->squelch_whitespace_errors;4715warning(Q_("squelched%dwhitespace error",4716"squelched%dwhitespace errors",4717 squelched),4718 squelched);4719}4720if(state->ws_error_action == die_on_ws_error)4721die(Q_("%dline adds whitespace errors.",4722"%dlines add whitespace errors.",4723 state->whitespace_error),4724 state->whitespace_error);4725if(state->applied_after_fixing_ws && state->apply)4726warning("%dline%sapplied after"4727" fixing whitespace errors.",4728 state->applied_after_fixing_ws,4729 state->applied_after_fixing_ws ==1?"":"s");4730else if(state->whitespace_error)4731warning(Q_("%dline adds whitespace errors.",4732"%dlines add whitespace errors.",4733 state->whitespace_error),4734 state->whitespace_error);4735}47364737if(state->update_index) {4738if(write_locked_index(&the_index, state->lock_file, COMMIT_LOCK))4739die(_("Unable to write new index file"));4740 state->newfd = -1;4741}47424743return!!errs;47444745end:4746exit(res == -1?1:128);4747}47484749intcmd_apply(int argc,const char**argv,const char*prefix)4750{4751int force_apply =0;4752int options =0;4753int ret;4754struct apply_state state;47554756struct option builtin_apply_options[] = {4757{ OPTION_CALLBACK,0,"exclude", &state,N_("path"),4758N_("don't apply changes matching the given path"),47590, option_parse_exclude },4760{ OPTION_CALLBACK,0,"include", &state,N_("path"),4761N_("apply changes matching the given path"),47620, option_parse_include },4763{ OPTION_CALLBACK,'p', NULL, &state,N_("num"),4764N_("remove <num> leading slashes from traditional diff paths"),47650, option_parse_p },4766OPT_BOOL(0,"no-add", &state.no_add,4767N_("ignore additions made by the patch")),4768OPT_BOOL(0,"stat", &state.diffstat,4769N_("instead of applying the patch, output diffstat for the input")),4770OPT_NOOP_NOARG(0,"allow-binary-replacement"),4771OPT_NOOP_NOARG(0,"binary"),4772OPT_BOOL(0,"numstat", &state.numstat,4773N_("show number of added and deleted lines in decimal notation")),4774OPT_BOOL(0,"summary", &state.summary,4775N_("instead of applying the patch, output a summary for the input")),4776OPT_BOOL(0,"check", &state.check,4777N_("instead of applying the patch, see if the patch is applicable")),4778OPT_BOOL(0,"index", &state.check_index,4779N_("make sure the patch is applicable to the current index")),4780OPT_BOOL(0,"cached", &state.cached,4781N_("apply a patch without touching the working tree")),4782OPT_BOOL(0,"unsafe-paths", &state.unsafe_paths,4783N_("accept a patch that touches outside the working area")),4784OPT_BOOL(0,"apply", &force_apply,4785N_("also apply the patch (use with --stat/--summary/--check)")),4786OPT_BOOL('3',"3way", &state.threeway,4787N_("attempt three-way merge if a patch does not apply")),4788OPT_FILENAME(0,"build-fake-ancestor", &state.fake_ancestor,4789N_("build a temporary index based on embedded index information")),4790/* Think twice before adding "--nul" synonym to this */4791OPT_SET_INT('z', NULL, &state.line_termination,4792N_("paths are separated with NUL character"),'\0'),4793OPT_INTEGER('C', NULL, &state.p_context,4794N_("ensure at least <n> lines of context match")),4795{ OPTION_CALLBACK,0,"whitespace", &state,N_("action"),4796N_("detect new or modified lines that have whitespace errors"),47970, option_parse_whitespace },4798{ OPTION_CALLBACK,0,"ignore-space-change", &state, NULL,4799N_("ignore changes in whitespace when finding context"),4800 PARSE_OPT_NOARG, option_parse_space_change },4801{ OPTION_CALLBACK,0,"ignore-whitespace", &state, NULL,4802N_("ignore changes in whitespace when finding context"),4803 PARSE_OPT_NOARG, option_parse_space_change },4804OPT_BOOL('R',"reverse", &state.apply_in_reverse,4805N_("apply the patch in reverse")),4806OPT_BOOL(0,"unidiff-zero", &state.unidiff_zero,4807N_("don't expect at least one line of context")),4808OPT_BOOL(0,"reject", &state.apply_with_reject,4809N_("leave the rejected hunks in corresponding *.rej files")),4810OPT_BOOL(0,"allow-overlap", &state.allow_overlap,4811N_("allow overlapping hunks")),4812OPT__VERBOSE(&state.apply_verbosely,N_("be verbose")),4813OPT_BIT(0,"inaccurate-eof", &options,4814N_("tolerate incorrectly detected missing new-line at the end of file"),4815 INACCURATE_EOF),4816OPT_BIT(0,"recount", &options,4817N_("do not trust the line counts in the hunk headers"),4818 RECOUNT),4819{ OPTION_CALLBACK,0,"directory", &state,N_("root"),4820N_("prepend <root> to all filenames"),48210, option_parse_directory },4822OPT_END()4823};48244825init_apply_state(&state, prefix, &lock_file);48264827 argc =parse_options(argc, argv, state.prefix, builtin_apply_options,4828 apply_usage,0);48294830check_apply_state(&state, force_apply);48314832 ret =apply_all_patches(&state, argc, argv, options);48334834clear_apply_state(&state);48354836return ret;4837}