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 24enum ws_error_action { 25 nowarn_ws_error, 26 warn_on_ws_error, 27 die_on_ws_error, 28 correct_ws_error 29}; 30 31 32enum ws_ignore { 33 ignore_ws_none, 34 ignore_ws_change 35}; 36 37struct apply_state { 38const char*prefix; 39int prefix_length; 40 41/* These control what gets looked at and modified */ 42int apply;/* this is not a dry-run */ 43int cached;/* apply to the index only */ 44int check;/* preimage must match working tree, don't actually apply */ 45int check_index;/* preimage must match the indexed version */ 46int update_index;/* check_index && apply */ 47 48/* These control cosmetic aspect of the output */ 49int diffstat;/* just show a diffstat, and don't actually apply */ 50int numstat;/* just show a numeric diffstat, and don't actually apply */ 51int summary;/* just report creation, deletion, etc, and don't actually apply */ 52 53/* These boolean parameters control how the apply is done */ 54int allow_overlap; 55int apply_in_reverse; 56int apply_with_reject; 57int apply_verbosely; 58int no_add; 59int threeway; 60int unidiff_zero; 61int unsafe_paths; 62 63/* Other non boolean parameters */ 64const char*fake_ancestor; 65const char*patch_input_file; 66int line_termination; 67struct strbuf root; 68int p_value; 69int p_value_known; 70unsigned int p_context; 71 72/* Exclude and include path parameters */ 73struct string_list limit_by_name; 74int has_include; 75 76/* Various "current state" */ 77int linenr;/* current line number */ 78 79/* 80 * For "diff-stat" like behaviour, we keep track of the biggest change 81 * we've seen, and the longest filename. That allows us to do simple 82 * scaling. 83 */ 84int max_change; 85int max_len; 86 87/* 88 * Records filenames that have been touched, in order to handle 89 * the case where more than one patches touch the same file. 90 */ 91struct string_list fn_table; 92 93/* These control whitespace errors */ 94enum ws_error_action ws_error_action; 95enum ws_ignore ws_ignore_action; 96const char*whitespace_option; 97int whitespace_error; 98int squelch_whitespace_errors; 99int applied_after_fixing_ws; 100}; 101 102static int newfd = -1; 103 104static const char*const apply_usage[] = { 105N_("git apply [<options>] [<patch>...]"), 106 NULL 107}; 108 109static voidparse_whitespace_option(struct apply_state *state,const char*option) 110{ 111if(!option) { 112 state->ws_error_action = warn_on_ws_error; 113return; 114} 115if(!strcmp(option,"warn")) { 116 state->ws_error_action = warn_on_ws_error; 117return; 118} 119if(!strcmp(option,"nowarn")) { 120 state->ws_error_action = nowarn_ws_error; 121return; 122} 123if(!strcmp(option,"error")) { 124 state->ws_error_action = die_on_ws_error; 125return; 126} 127if(!strcmp(option,"error-all")) { 128 state->ws_error_action = die_on_ws_error; 129 state->squelch_whitespace_errors =0; 130return; 131} 132if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 133 state->ws_error_action = correct_ws_error; 134return; 135} 136die(_("unrecognized whitespace option '%s'"), option); 137} 138 139static voidparse_ignorewhitespace_option(struct apply_state *state, 140const char*option) 141{ 142if(!option || !strcmp(option,"no") || 143!strcmp(option,"false") || !strcmp(option,"never") || 144!strcmp(option,"none")) { 145 state->ws_ignore_action = ignore_ws_none; 146return; 147} 148if(!strcmp(option,"change")) { 149 state->ws_ignore_action = ignore_ws_change; 150return; 151} 152die(_("unrecognized whitespace ignore option '%s'"), option); 153} 154 155static voidset_default_whitespace_mode(struct apply_state *state) 156{ 157if(!state->whitespace_option && !apply_default_whitespace) 158 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 159} 160 161/* 162 * This represents one "hunk" from a patch, starting with 163 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 164 * patch text is pointed at by patch, and its byte length 165 * is stored in size. leading and trailing are the number 166 * of context lines. 167 */ 168struct fragment { 169unsigned long leading, trailing; 170unsigned long oldpos, oldlines; 171unsigned long newpos, newlines; 172/* 173 * 'patch' is usually borrowed from buf in apply_patch(), 174 * but some codepaths store an allocated buffer. 175 */ 176const char*patch; 177unsigned free_patch:1, 178 rejected:1; 179int size; 180int linenr; 181struct fragment *next; 182}; 183 184/* 185 * When dealing with a binary patch, we reuse "leading" field 186 * to store the type of the binary hunk, either deflated "delta" 187 * or deflated "literal". 188 */ 189#define binary_patch_method leading 190#define BINARY_DELTA_DEFLATED 1 191#define BINARY_LITERAL_DEFLATED 2 192 193/* 194 * This represents a "patch" to a file, both metainfo changes 195 * such as creation/deletion, filemode and content changes represented 196 * as a series of fragments. 197 */ 198struct patch { 199char*new_name, *old_name, *def_name; 200unsigned int old_mode, new_mode; 201int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 202int rejected; 203unsigned ws_rule; 204int lines_added, lines_deleted; 205int score; 206unsigned int is_toplevel_relative:1; 207unsigned int inaccurate_eof:1; 208unsigned int is_binary:1; 209unsigned int is_copy:1; 210unsigned int is_rename:1; 211unsigned int recount:1; 212unsigned int conflicted_threeway:1; 213unsigned int direct_to_threeway:1; 214struct fragment *fragments; 215char*result; 216size_t resultsize; 217char old_sha1_prefix[41]; 218char new_sha1_prefix[41]; 219struct patch *next; 220 221/* three-way fallback result */ 222struct object_id threeway_stage[3]; 223}; 224 225static voidfree_fragment_list(struct fragment *list) 226{ 227while(list) { 228struct fragment *next = list->next; 229if(list->free_patch) 230free((char*)list->patch); 231free(list); 232 list = next; 233} 234} 235 236static voidfree_patch(struct patch *patch) 237{ 238free_fragment_list(patch->fragments); 239free(patch->def_name); 240free(patch->old_name); 241free(patch->new_name); 242free(patch->result); 243free(patch); 244} 245 246static voidfree_patch_list(struct patch *list) 247{ 248while(list) { 249struct patch *next = list->next; 250free_patch(list); 251 list = next; 252} 253} 254 255/* 256 * A line in a file, len-bytes long (includes the terminating LF, 257 * except for an incomplete line at the end if the file ends with 258 * one), and its contents hashes to 'hash'. 259 */ 260struct line { 261size_t len; 262unsigned hash :24; 263unsigned flag :8; 264#define LINE_COMMON 1 265#define LINE_PATCHED 2 266}; 267 268/* 269 * This represents a "file", which is an array of "lines". 270 */ 271struct image { 272char*buf; 273size_t len; 274size_t nr; 275size_t alloc; 276struct line *line_allocated; 277struct line *line; 278}; 279 280static uint32_thash_line(const char*cp,size_t len) 281{ 282size_t i; 283uint32_t h; 284for(i =0, h =0; i < len; i++) { 285if(!isspace(cp[i])) { 286 h = h *3+ (cp[i] &0xff); 287} 288} 289return h; 290} 291 292/* 293 * Compare lines s1 of length n1 and s2 of length n2, ignoring 294 * whitespace difference. Returns 1 if they match, 0 otherwise 295 */ 296static intfuzzy_matchlines(const char*s1,size_t n1, 297const char*s2,size_t n2) 298{ 299const char*last1 = s1 + n1 -1; 300const char*last2 = s2 + n2 -1; 301int result =0; 302 303/* ignore line endings */ 304while((*last1 =='\r') || (*last1 =='\n')) 305 last1--; 306while((*last2 =='\r') || (*last2 =='\n')) 307 last2--; 308 309/* skip leading whitespaces, if both begin with whitespace */ 310if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 311while(isspace(*s1) && (s1 <= last1)) 312 s1++; 313while(isspace(*s2) && (s2 <= last2)) 314 s2++; 315} 316/* early return if both lines are empty */ 317if((s1 > last1) && (s2 > last2)) 318return1; 319while(!result) { 320 result = *s1++ - *s2++; 321/* 322 * Skip whitespace inside. We check for whitespace on 323 * both buffers because we don't want "a b" to match 324 * "ab" 325 */ 326if(isspace(*s1) &&isspace(*s2)) { 327while(isspace(*s1) && s1 <= last1) 328 s1++; 329while(isspace(*s2) && s2 <= last2) 330 s2++; 331} 332/* 333 * If we reached the end on one side only, 334 * lines don't match 335 */ 336if( 337((s2 > last2) && (s1 <= last1)) || 338((s1 > last1) && (s2 <= last2))) 339return0; 340if((s1 > last1) && (s2 > last2)) 341break; 342} 343 344return!result; 345} 346 347static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 348{ 349ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 350 img->line_allocated[img->nr].len = len; 351 img->line_allocated[img->nr].hash =hash_line(bol, len); 352 img->line_allocated[img->nr].flag = flag; 353 img->nr++; 354} 355 356/* 357 * "buf" has the file contents to be patched (read from various sources). 358 * attach it to "image" and add line-based index to it. 359 * "image" now owns the "buf". 360 */ 361static voidprepare_image(struct image *image,char*buf,size_t len, 362int prepare_linetable) 363{ 364const char*cp, *ep; 365 366memset(image,0,sizeof(*image)); 367 image->buf = buf; 368 image->len = len; 369 370if(!prepare_linetable) 371return; 372 373 ep = image->buf + image->len; 374 cp = image->buf; 375while(cp < ep) { 376const char*next; 377for(next = cp; next < ep && *next !='\n'; next++) 378; 379if(next < ep) 380 next++; 381add_line_info(image, cp, next - cp,0); 382 cp = next; 383} 384 image->line = image->line_allocated; 385} 386 387static voidclear_image(struct image *image) 388{ 389free(image->buf); 390free(image->line_allocated); 391memset(image,0,sizeof(*image)); 392} 393 394/* fmt must contain _one_ %s and no other substitution */ 395static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 396{ 397struct strbuf sb = STRBUF_INIT; 398 399if(patch->old_name && patch->new_name && 400strcmp(patch->old_name, patch->new_name)) { 401quote_c_style(patch->old_name, &sb, NULL,0); 402strbuf_addstr(&sb," => "); 403quote_c_style(patch->new_name, &sb, NULL,0); 404}else{ 405const char*n = patch->new_name; 406if(!n) 407 n = patch->old_name; 408quote_c_style(n, &sb, NULL,0); 409} 410fprintf(output, fmt, sb.buf); 411fputc('\n', output); 412strbuf_release(&sb); 413} 414 415#define SLOP (16) 416 417static voidread_patch_file(struct strbuf *sb,int fd) 418{ 419if(strbuf_read(sb, fd,0) <0) 420die_errno("git apply: failed to read"); 421 422/* 423 * Make sure that we have some slop in the buffer 424 * so that we can do speculative "memcmp" etc, and 425 * see to it that it is NUL-filled. 426 */ 427strbuf_grow(sb, SLOP); 428memset(sb->buf + sb->len,0, SLOP); 429} 430 431static unsigned longlinelen(const char*buffer,unsigned long size) 432{ 433unsigned long len =0; 434while(size--) { 435 len++; 436if(*buffer++ =='\n') 437break; 438} 439return len; 440} 441 442static intis_dev_null(const char*str) 443{ 444returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 445} 446 447#define TERM_SPACE 1 448#define TERM_TAB 2 449 450static intname_terminate(const char*name,int namelen,int c,int terminate) 451{ 452if(c ==' '&& !(terminate & TERM_SPACE)) 453return0; 454if(c =='\t'&& !(terminate & TERM_TAB)) 455return0; 456 457return1; 458} 459 460/* remove double slashes to make --index work with such filenames */ 461static char*squash_slash(char*name) 462{ 463int i =0, j =0; 464 465if(!name) 466return NULL; 467 468while(name[i]) { 469if((name[j++] = name[i++]) =='/') 470while(name[i] =='/') 471 i++; 472} 473 name[j] ='\0'; 474return name; 475} 476 477static char*find_name_gnu(struct apply_state *state, 478const char*line, 479const char*def, 480int p_value) 481{ 482struct strbuf name = STRBUF_INIT; 483char*cp; 484 485/* 486 * Proposed "new-style" GNU patch/diff format; see 487 * http://marc.info/?l=git&m=112927316408690&w=2 488 */ 489if(unquote_c_style(&name, line, NULL)) { 490strbuf_release(&name); 491return NULL; 492} 493 494for(cp = name.buf; p_value; p_value--) { 495 cp =strchr(cp,'/'); 496if(!cp) { 497strbuf_release(&name); 498return NULL; 499} 500 cp++; 501} 502 503strbuf_remove(&name,0, cp - name.buf); 504if(state->root.len) 505strbuf_insert(&name,0, state->root.buf, state->root.len); 506returnsquash_slash(strbuf_detach(&name, NULL)); 507} 508 509static size_tsane_tz_len(const char*line,size_t len) 510{ 511const char*tz, *p; 512 513if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 514return0; 515 tz = line + len -strlen(" +0500"); 516 517if(tz[1] !='+'&& tz[1] !='-') 518return0; 519 520for(p = tz +2; p != line + len; p++) 521if(!isdigit(*p)) 522return0; 523 524return line + len - tz; 525} 526 527static size_ttz_with_colon_len(const char*line,size_t len) 528{ 529const char*tz, *p; 530 531if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 532return0; 533 tz = line + len -strlen(" +08:00"); 534 535if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 536return0; 537 p = tz +2; 538if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 539!isdigit(*p++) || !isdigit(*p++)) 540return0; 541 542return line + len - tz; 543} 544 545static size_tdate_len(const char*line,size_t len) 546{ 547const char*date, *p; 548 549if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 550return0; 551 p = date = line + len -strlen("72-02-05"); 552 553if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 554!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 555!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 556return0; 557 558if(date - line >=strlen("19") && 559isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 560 date -=strlen("19"); 561 562return line + len - date; 563} 564 565static size_tshort_time_len(const char*line,size_t len) 566{ 567const char*time, *p; 568 569if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 570return0; 571 p = time = line + len -strlen(" 07:01:32"); 572 573/* Permit 1-digit hours? */ 574if(*p++ !=' '|| 575!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 576!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 577!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 578return0; 579 580return line + len - time; 581} 582 583static size_tfractional_time_len(const char*line,size_t len) 584{ 585const char*p; 586size_t n; 587 588/* Expected format: 19:41:17.620000023 */ 589if(!len || !isdigit(line[len -1])) 590return0; 591 p = line + len -1; 592 593/* Fractional seconds. */ 594while(p > line &&isdigit(*p)) 595 p--; 596if(*p !='.') 597return0; 598 599/* Hours, minutes, and whole seconds. */ 600 n =short_time_len(line, p - line); 601if(!n) 602return0; 603 604return line + len - p + n; 605} 606 607static size_ttrailing_spaces_len(const char*line,size_t len) 608{ 609const char*p; 610 611/* Expected format: ' ' x (1 or more) */ 612if(!len || line[len -1] !=' ') 613return0; 614 615 p = line + len; 616while(p != line) { 617 p--; 618if(*p !=' ') 619return line + len - (p +1); 620} 621 622/* All spaces! */ 623return len; 624} 625 626static size_tdiff_timestamp_len(const char*line,size_t len) 627{ 628const char*end = line + len; 629size_t n; 630 631/* 632 * Posix: 2010-07-05 19:41:17 633 * GNU: 2010-07-05 19:41:17.620000023 -0500 634 */ 635 636if(!isdigit(end[-1])) 637return0; 638 639 n =sane_tz_len(line, end - line); 640if(!n) 641 n =tz_with_colon_len(line, end - line); 642 end -= n; 643 644 n =short_time_len(line, end - line); 645if(!n) 646 n =fractional_time_len(line, end - line); 647 end -= n; 648 649 n =date_len(line, end - line); 650if(!n)/* No date. Too bad. */ 651return0; 652 end -= n; 653 654if(end == line)/* No space before date. */ 655return0; 656if(end[-1] =='\t') {/* Success! */ 657 end--; 658return line + len - end; 659} 660if(end[-1] !=' ')/* No space before date. */ 661return0; 662 663/* Whitespace damage. */ 664 end -=trailing_spaces_len(line, end - line); 665return line + len - end; 666} 667 668static char*find_name_common(struct apply_state *state, 669const char*line, 670const char*def, 671int p_value, 672const char*end, 673int terminate) 674{ 675int len; 676const char*start = NULL; 677 678if(p_value ==0) 679 start = line; 680while(line != end) { 681char c = *line; 682 683if(!end &&isspace(c)) { 684if(c =='\n') 685break; 686if(name_terminate(start, line-start, c, terminate)) 687break; 688} 689 line++; 690if(c =='/'&& !--p_value) 691 start = line; 692} 693if(!start) 694returnsquash_slash(xstrdup_or_null(def)); 695 len = line - start; 696if(!len) 697returnsquash_slash(xstrdup_or_null(def)); 698 699/* 700 * Generally we prefer the shorter name, especially 701 * if the other one is just a variation of that with 702 * something else tacked on to the end (ie "file.orig" 703 * or "file~"). 704 */ 705if(def) { 706int deflen =strlen(def); 707if(deflen < len && !strncmp(start, def, deflen)) 708returnsquash_slash(xstrdup(def)); 709} 710 711if(state->root.len) { 712char*ret =xstrfmt("%s%.*s", state->root.buf, len, start); 713returnsquash_slash(ret); 714} 715 716returnsquash_slash(xmemdupz(start, len)); 717} 718 719static char*find_name(struct apply_state *state, 720const char*line, 721char*def, 722int p_value, 723int terminate) 724{ 725if(*line =='"') { 726char*name =find_name_gnu(state, line, def, p_value); 727if(name) 728return name; 729} 730 731returnfind_name_common(state, line, def, p_value, NULL, terminate); 732} 733 734static char*find_name_traditional(struct apply_state *state, 735const char*line, 736char*def, 737int p_value) 738{ 739size_t len; 740size_t date_len; 741 742if(*line =='"') { 743char*name =find_name_gnu(state, line, def, p_value); 744if(name) 745return name; 746} 747 748 len =strchrnul(line,'\n') - line; 749 date_len =diff_timestamp_len(line, len); 750if(!date_len) 751returnfind_name_common(state, line, def, p_value, NULL, TERM_TAB); 752 len -= date_len; 753 754returnfind_name_common(state, line, def, p_value, line + len,0); 755} 756 757static intcount_slashes(const char*cp) 758{ 759int cnt =0; 760char ch; 761 762while((ch = *cp++)) 763if(ch =='/') 764 cnt++; 765return cnt; 766} 767 768/* 769 * Given the string after "--- " or "+++ ", guess the appropriate 770 * p_value for the given patch. 771 */ 772static intguess_p_value(struct apply_state *state,const char*nameline) 773{ 774char*name, *cp; 775int val = -1; 776 777if(is_dev_null(nameline)) 778return-1; 779 name =find_name_traditional(state, nameline, NULL,0); 780if(!name) 781return-1; 782 cp =strchr(name,'/'); 783if(!cp) 784 val =0; 785else if(state->prefix) { 786/* 787 * Does it begin with "a/$our-prefix" and such? Then this is 788 * very likely to apply to our directory. 789 */ 790if(!strncmp(name, state->prefix, state->prefix_length)) 791 val =count_slashes(state->prefix); 792else{ 793 cp++; 794if(!strncmp(cp, state->prefix, state->prefix_length)) 795 val =count_slashes(state->prefix) +1; 796} 797} 798free(name); 799return val; 800} 801 802/* 803 * Does the ---/+++ line have the POSIX timestamp after the last HT? 804 * GNU diff puts epoch there to signal a creation/deletion event. Is 805 * this such a timestamp? 806 */ 807static inthas_epoch_timestamp(const char*nameline) 808{ 809/* 810 * We are only interested in epoch timestamp; any non-zero 811 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 812 * For the same reason, the date must be either 1969-12-31 or 813 * 1970-01-01, and the seconds part must be "00". 814 */ 815const char stamp_regexp[] = 816"^(1969-12-31|1970-01-01)" 817" " 818"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 819" " 820"([-+][0-2][0-9]:?[0-5][0-9])\n"; 821const char*timestamp = NULL, *cp, *colon; 822static regex_t *stamp; 823 regmatch_t m[10]; 824int zoneoffset; 825int hourminute; 826int status; 827 828for(cp = nameline; *cp !='\n'; cp++) { 829if(*cp =='\t') 830 timestamp = cp +1; 831} 832if(!timestamp) 833return0; 834if(!stamp) { 835 stamp =xmalloc(sizeof(*stamp)); 836if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 837warning(_("Cannot prepare timestamp regexp%s"), 838 stamp_regexp); 839return0; 840} 841} 842 843 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 844if(status) { 845if(status != REG_NOMATCH) 846warning(_("regexec returned%dfor input:%s"), 847 status, timestamp); 848return0; 849} 850 851 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 852if(*colon ==':') 853 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 854else 855 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 856if(timestamp[m[3].rm_so] =='-') 857 zoneoffset = -zoneoffset; 858 859/* 860 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 861 * (west of GMT) or 1970-01-01 (east of GMT) 862 */ 863if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 864(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 865return0; 866 867 hourminute = (strtol(timestamp +11, NULL,10) *60+ 868strtol(timestamp +14, NULL,10) - 869 zoneoffset); 870 871return((zoneoffset <0&& hourminute ==1440) || 872(0<= zoneoffset && !hourminute)); 873} 874 875/* 876 * Get the name etc info from the ---/+++ lines of a traditional patch header 877 * 878 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 879 * files, we can happily check the index for a match, but for creating a 880 * new file we should try to match whatever "patch" does. I have no idea. 881 */ 882static voidparse_traditional_patch(struct apply_state *state, 883const char*first, 884const char*second, 885struct patch *patch) 886{ 887char*name; 888 889 first +=4;/* skip "--- " */ 890 second +=4;/* skip "+++ " */ 891if(!state->p_value_known) { 892int p, q; 893 p =guess_p_value(state, first); 894 q =guess_p_value(state, second); 895if(p <0) p = q; 896if(0<= p && p == q) { 897 state->p_value = p; 898 state->p_value_known =1; 899} 900} 901if(is_dev_null(first)) { 902 patch->is_new =1; 903 patch->is_delete =0; 904 name =find_name_traditional(state, second, NULL, state->p_value); 905 patch->new_name = name; 906}else if(is_dev_null(second)) { 907 patch->is_new =0; 908 patch->is_delete =1; 909 name =find_name_traditional(state, first, NULL, state->p_value); 910 patch->old_name = name; 911}else{ 912char*first_name; 913 first_name =find_name_traditional(state, first, NULL, state->p_value); 914 name =find_name_traditional(state, second, first_name, state->p_value); 915free(first_name); 916if(has_epoch_timestamp(first)) { 917 patch->is_new =1; 918 patch->is_delete =0; 919 patch->new_name = name; 920}else if(has_epoch_timestamp(second)) { 921 patch->is_new =0; 922 patch->is_delete =1; 923 patch->old_name = name; 924}else{ 925 patch->old_name = name; 926 patch->new_name =xstrdup_or_null(name); 927} 928} 929if(!name) 930die(_("unable to find filename in patch at line%d"), state->linenr); 931} 932 933static intgitdiff_hdrend(struct apply_state *state, 934const char*line, 935struct patch *patch) 936{ 937return-1; 938} 939 940/* 941 * We're anal about diff header consistency, to make 942 * sure that we don't end up having strange ambiguous 943 * patches floating around. 944 * 945 * As a result, gitdiff_{old|new}name() will check 946 * their names against any previous information, just 947 * to make sure.. 948 */ 949#define DIFF_OLD_NAME 0 950#define DIFF_NEW_NAME 1 951 952static voidgitdiff_verify_name(struct apply_state *state, 953const char*line, 954int isnull, 955char**name, 956int side) 957{ 958if(!*name && !isnull) { 959*name =find_name(state, line, NULL, state->p_value, TERM_TAB); 960return; 961} 962 963if(*name) { 964int len =strlen(*name); 965char*another; 966if(isnull) 967die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 968*name, state->linenr); 969 another =find_name(state, line, NULL, state->p_value, TERM_TAB); 970if(!another ||memcmp(another, *name, len +1)) 971die((side == DIFF_NEW_NAME) ? 972_("git apply: bad git-diff - inconsistent new filename on line%d") : 973_("git apply: bad git-diff - inconsistent old filename on line%d"), state->linenr); 974free(another); 975}else{ 976/* expect "/dev/null" */ 977if(memcmp("/dev/null", line,9) || line[9] !='\n') 978die(_("git apply: bad git-diff - expected /dev/null on line%d"), state->linenr); 979} 980} 981 982static intgitdiff_oldname(struct apply_state *state, 983const char*line, 984struct patch *patch) 985{ 986gitdiff_verify_name(state, line, 987 patch->is_new, &patch->old_name, 988 DIFF_OLD_NAME); 989return0; 990} 991 992static intgitdiff_newname(struct apply_state *state, 993const char*line, 994struct patch *patch) 995{ 996gitdiff_verify_name(state, line, 997 patch->is_delete, &patch->new_name, 998 DIFF_NEW_NAME); 999return0;1000}10011002static intgitdiff_oldmode(struct apply_state *state,1003const char*line,1004struct patch *patch)1005{1006 patch->old_mode =strtoul(line, NULL,8);1007return0;1008}10091010static intgitdiff_newmode(struct apply_state *state,1011const char*line,1012struct patch *patch)1013{1014 patch->new_mode =strtoul(line, NULL,8);1015return0;1016}10171018static intgitdiff_delete(struct apply_state *state,1019const char*line,1020struct patch *patch)1021{1022 patch->is_delete =1;1023free(patch->old_name);1024 patch->old_name =xstrdup_or_null(patch->def_name);1025returngitdiff_oldmode(state, line, patch);1026}10271028static intgitdiff_newfile(struct apply_state *state,1029const char*line,1030struct patch *patch)1031{1032 patch->is_new =1;1033free(patch->new_name);1034 patch->new_name =xstrdup_or_null(patch->def_name);1035returngitdiff_newmode(state, line, patch);1036}10371038static intgitdiff_copysrc(struct apply_state *state,1039const char*line,1040struct patch *patch)1041{1042 patch->is_copy =1;1043free(patch->old_name);1044 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1045return0;1046}10471048static intgitdiff_copydst(struct apply_state *state,1049const char*line,1050struct patch *patch)1051{1052 patch->is_copy =1;1053free(patch->new_name);1054 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1055return0;1056}10571058static intgitdiff_renamesrc(struct apply_state *state,1059const char*line,1060struct patch *patch)1061{1062 patch->is_rename =1;1063free(patch->old_name);1064 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1065return0;1066}10671068static intgitdiff_renamedst(struct apply_state *state,1069const char*line,1070struct patch *patch)1071{1072 patch->is_rename =1;1073free(patch->new_name);1074 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1075return0;1076}10771078static intgitdiff_similarity(struct apply_state *state,1079const char*line,1080struct patch *patch)1081{1082unsigned long val =strtoul(line, NULL,10);1083if(val <=100)1084 patch->score = val;1085return0;1086}10871088static intgitdiff_dissimilarity(struct apply_state *state,1089const char*line,1090struct patch *patch)1091{1092unsigned long val =strtoul(line, NULL,10);1093if(val <=100)1094 patch->score = val;1095return0;1096}10971098static intgitdiff_index(struct apply_state *state,1099const char*line,1100struct patch *patch)1101{1102/*1103 * index line is N hexadecimal, "..", N hexadecimal,1104 * and optional space with octal mode.1105 */1106const char*ptr, *eol;1107int len;11081109 ptr =strchr(line,'.');1110if(!ptr || ptr[1] !='.'||40< ptr - line)1111return0;1112 len = ptr - line;1113memcpy(patch->old_sha1_prefix, line, len);1114 patch->old_sha1_prefix[len] =0;11151116 line = ptr +2;1117 ptr =strchr(line,' ');1118 eol =strchrnul(line,'\n');11191120if(!ptr || eol < ptr)1121 ptr = eol;1122 len = ptr - line;11231124if(40< len)1125return0;1126memcpy(patch->new_sha1_prefix, line, len);1127 patch->new_sha1_prefix[len] =0;1128if(*ptr ==' ')1129 patch->old_mode =strtoul(ptr+1, NULL,8);1130return0;1131}11321133/*1134 * This is normal for a diff that doesn't change anything: we'll fall through1135 * into the next diff. Tell the parser to break out.1136 */1137static intgitdiff_unrecognized(struct apply_state *state,1138const char*line,1139struct patch *patch)1140{1141return-1;1142}11431144/*1145 * Skip p_value leading components from "line"; as we do not accept1146 * absolute paths, return NULL in that case.1147 */1148static const char*skip_tree_prefix(struct apply_state *state,1149const char*line,1150int llen)1151{1152int nslash;1153int i;11541155if(!state->p_value)1156return(llen && line[0] =='/') ? NULL : line;11571158 nslash = state->p_value;1159for(i =0; i < llen; i++) {1160int ch = line[i];1161if(ch =='/'&& --nslash <=0)1162return(i ==0) ? NULL : &line[i +1];1163}1164return NULL;1165}11661167/*1168 * This is to extract the same name that appears on "diff --git"1169 * line. We do not find and return anything if it is a rename1170 * patch, and it is OK because we will find the name elsewhere.1171 * We need to reliably find name only when it is mode-change only,1172 * creation or deletion of an empty file. In any of these cases,1173 * both sides are the same name under a/ and b/ respectively.1174 */1175static char*git_header_name(struct apply_state *state,1176const char*line,1177int llen)1178{1179const char*name;1180const char*second = NULL;1181size_t len, line_len;11821183 line +=strlen("diff --git ");1184 llen -=strlen("diff --git ");11851186if(*line =='"') {1187const char*cp;1188struct strbuf first = STRBUF_INIT;1189struct strbuf sp = STRBUF_INIT;11901191if(unquote_c_style(&first, line, &second))1192goto free_and_fail1;11931194/* strip the a/b prefix including trailing slash */1195 cp =skip_tree_prefix(state, first.buf, first.len);1196if(!cp)1197goto free_and_fail1;1198strbuf_remove(&first,0, cp - first.buf);11991200/*1201 * second points at one past closing dq of name.1202 * find the second name.1203 */1204while((second < line + llen) &&isspace(*second))1205 second++;12061207if(line + llen <= second)1208goto free_and_fail1;1209if(*second =='"') {1210if(unquote_c_style(&sp, second, NULL))1211goto free_and_fail1;1212 cp =skip_tree_prefix(state, sp.buf, sp.len);1213if(!cp)1214goto free_and_fail1;1215/* They must match, otherwise ignore */1216if(strcmp(cp, first.buf))1217goto free_and_fail1;1218strbuf_release(&sp);1219returnstrbuf_detach(&first, NULL);1220}12211222/* unquoted second */1223 cp =skip_tree_prefix(state, second, line + llen - second);1224if(!cp)1225goto free_and_fail1;1226if(line + llen - cp != first.len ||1227memcmp(first.buf, cp, first.len))1228goto free_and_fail1;1229returnstrbuf_detach(&first, NULL);12301231 free_and_fail1:1232strbuf_release(&first);1233strbuf_release(&sp);1234return NULL;1235}12361237/* unquoted first name */1238 name =skip_tree_prefix(state, line, llen);1239if(!name)1240return NULL;12411242/*1243 * since the first name is unquoted, a dq if exists must be1244 * the beginning of the second name.1245 */1246for(second = name; second < line + llen; second++) {1247if(*second =='"') {1248struct strbuf sp = STRBUF_INIT;1249const char*np;12501251if(unquote_c_style(&sp, second, NULL))1252goto free_and_fail2;12531254 np =skip_tree_prefix(state, sp.buf, sp.len);1255if(!np)1256goto free_and_fail2;12571258 len = sp.buf + sp.len - np;1259if(len < second - name &&1260!strncmp(np, name, len) &&1261isspace(name[len])) {1262/* Good */1263strbuf_remove(&sp,0, np - sp.buf);1264returnstrbuf_detach(&sp, NULL);1265}12661267 free_and_fail2:1268strbuf_release(&sp);1269return NULL;1270}1271}12721273/*1274 * Accept a name only if it shows up twice, exactly the same1275 * form.1276 */1277 second =strchr(name,'\n');1278if(!second)1279return NULL;1280 line_len = second - name;1281for(len =0; ; len++) {1282switch(name[len]) {1283default:1284continue;1285case'\n':1286return NULL;1287case'\t':case' ':1288/*1289 * Is this the separator between the preimage1290 * and the postimage pathname? Again, we are1291 * only interested in the case where there is1292 * no rename, as this is only to set def_name1293 * and a rename patch has the names elsewhere1294 * in an unambiguous form.1295 */1296if(!name[len +1])1297return NULL;/* no postimage name */1298 second =skip_tree_prefix(state, name + len +1,1299 line_len - (len +1));1300if(!second)1301return NULL;1302/*1303 * Does len bytes starting at "name" and "second"1304 * (that are separated by one HT or SP we just1305 * found) exactly match?1306 */1307if(second[len] =='\n'&& !strncmp(name, second, len))1308returnxmemdupz(name, len);1309}1310}1311}13121313/* Verify that we recognize the lines following a git header */1314static intparse_git_header(struct apply_state *state,1315const char*line,1316int len,1317unsigned int size,1318struct patch *patch)1319{1320unsigned long offset;13211322/* A git diff has explicit new/delete information, so we don't guess */1323 patch->is_new =0;1324 patch->is_delete =0;13251326/*1327 * Some things may not have the old name in the1328 * rest of the headers anywhere (pure mode changes,1329 * or removing or adding empty files), so we get1330 * the default name from the header.1331 */1332 patch->def_name =git_header_name(state, line, len);1333if(patch->def_name && state->root.len) {1334char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1335free(patch->def_name);1336 patch->def_name = s;1337}13381339 line += len;1340 size -= len;1341 state->linenr++;1342for(offset = len ; size >0; offset += len, size -= len, line += len, state->linenr++) {1343static const struct opentry {1344const char*str;1345int(*fn)(struct apply_state *,const char*,struct patch *);1346} optable[] = {1347{"@@ -", gitdiff_hdrend },1348{"--- ", gitdiff_oldname },1349{"+++ ", gitdiff_newname },1350{"old mode ", gitdiff_oldmode },1351{"new mode ", gitdiff_newmode },1352{"deleted file mode ", gitdiff_delete },1353{"new file mode ", gitdiff_newfile },1354{"copy from ", gitdiff_copysrc },1355{"copy to ", gitdiff_copydst },1356{"rename old ", gitdiff_renamesrc },1357{"rename new ", gitdiff_renamedst },1358{"rename from ", gitdiff_renamesrc },1359{"rename to ", gitdiff_renamedst },1360{"similarity index ", gitdiff_similarity },1361{"dissimilarity index ", gitdiff_dissimilarity },1362{"index ", gitdiff_index },1363{"", gitdiff_unrecognized },1364};1365int i;13661367 len =linelen(line, size);1368if(!len || line[len-1] !='\n')1369break;1370for(i =0; i <ARRAY_SIZE(optable); i++) {1371const struct opentry *p = optable + i;1372int oplen =strlen(p->str);1373if(len < oplen ||memcmp(p->str, line, oplen))1374continue;1375if(p->fn(state, line + oplen, patch) <0)1376return offset;1377break;1378}1379}13801381return offset;1382}13831384static intparse_num(const char*line,unsigned long*p)1385{1386char*ptr;13871388if(!isdigit(*line))1389return0;1390*p =strtoul(line, &ptr,10);1391return ptr - line;1392}13931394static intparse_range(const char*line,int len,int offset,const char*expect,1395unsigned long*p1,unsigned long*p2)1396{1397int digits, ex;13981399if(offset <0|| offset >= len)1400return-1;1401 line += offset;1402 len -= offset;14031404 digits =parse_num(line, p1);1405if(!digits)1406return-1;14071408 offset += digits;1409 line += digits;1410 len -= digits;14111412*p2 =1;1413if(*line ==',') {1414 digits =parse_num(line+1, p2);1415if(!digits)1416return-1;14171418 offset += digits+1;1419 line += digits+1;1420 len -= digits+1;1421}14221423 ex =strlen(expect);1424if(ex > len)1425return-1;1426if(memcmp(line, expect, ex))1427return-1;14281429return offset + ex;1430}14311432static voidrecount_diff(const char*line,int size,struct fragment *fragment)1433{1434int oldlines =0, newlines =0, ret =0;14351436if(size <1) {1437warning("recount: ignore empty hunk");1438return;1439}14401441for(;;) {1442int len =linelen(line, size);1443 size -= len;1444 line += len;14451446if(size <1)1447break;14481449switch(*line) {1450case' ':case'\n':1451 newlines++;1452/* fall through */1453case'-':1454 oldlines++;1455continue;1456case'+':1457 newlines++;1458continue;1459case'\\':1460continue;1461case'@':1462 ret = size <3|| !starts_with(line,"@@ ");1463break;1464case'd':1465 ret = size <5|| !starts_with(line,"diff ");1466break;1467default:1468 ret = -1;1469break;1470}1471if(ret) {1472warning(_("recount: unexpected line: %.*s"),1473(int)linelen(line, size), line);1474return;1475}1476break;1477}1478 fragment->oldlines = oldlines;1479 fragment->newlines = newlines;1480}14811482/*1483 * Parse a unified diff fragment header of the1484 * form "@@ -a,b +c,d @@"1485 */1486static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1487{1488int offset;14891490if(!len || line[len-1] !='\n')1491return-1;14921493/* Figure out the number of lines in a fragment */1494 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1495 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14961497return offset;1498}14991500static intfind_header(struct apply_state *state,1501const char*line,1502unsigned long size,1503int*hdrsize,1504struct patch *patch)1505{1506unsigned long offset, len;15071508 patch->is_toplevel_relative =0;1509 patch->is_rename = patch->is_copy =0;1510 patch->is_new = patch->is_delete = -1;1511 patch->old_mode = patch->new_mode =0;1512 patch->old_name = patch->new_name = NULL;1513for(offset =0; size >0; offset += len, size -= len, line += len, state->linenr++) {1514unsigned long nextlen;15151516 len =linelen(line, size);1517if(!len)1518break;15191520/* Testing this early allows us to take a few shortcuts.. */1521if(len <6)1522continue;15231524/*1525 * Make sure we don't find any unconnected patch fragments.1526 * That's a sign that we didn't find a header, and that a1527 * patch has become corrupted/broken up.1528 */1529if(!memcmp("@@ -", line,4)) {1530struct fragment dummy;1531if(parse_fragment_header(line, len, &dummy) <0)1532continue;1533die(_("patch fragment without header at line%d: %.*s"),1534 state->linenr, (int)len-1, line);1535}15361537if(size < len +6)1538break;15391540/*1541 * Git patch? It might not have a real patch, just a rename1542 * or mode change, so we handle that specially1543 */1544if(!memcmp("diff --git ", line,11)) {1545int git_hdr_len =parse_git_header(state, line, len, size, patch);1546if(git_hdr_len <= len)1547continue;1548if(!patch->old_name && !patch->new_name) {1549if(!patch->def_name)1550die(Q_("git diff header lacks filename information when removing "1551"%dleading pathname component (line%d)",1552"git diff header lacks filename information when removing "1553"%dleading pathname components (line%d)",1554 state->p_value),1555 state->p_value, state->linenr);1556 patch->old_name =xstrdup(patch->def_name);1557 patch->new_name =xstrdup(patch->def_name);1558}1559if(!patch->is_delete && !patch->new_name)1560die("git diff header lacks filename information "1561"(line%d)", state->linenr);1562 patch->is_toplevel_relative =1;1563*hdrsize = git_hdr_len;1564return offset;1565}15661567/* --- followed by +++ ? */1568if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1569continue;15701571/*1572 * We only accept unified patches, so we want it to1573 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1574 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1575 */1576 nextlen =linelen(line + len, size - len);1577if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1578continue;15791580/* Ok, we'll consider it a patch */1581parse_traditional_patch(state, line, line+len, patch);1582*hdrsize = len + nextlen;1583 state->linenr +=2;1584return offset;1585}1586return-1;1587}15881589static voidrecord_ws_error(struct apply_state *state,1590unsigned result,1591const char*line,1592int len,1593int linenr)1594{1595char*err;15961597if(!result)1598return;15991600 state->whitespace_error++;1601if(state->squelch_whitespace_errors &&1602 state->squelch_whitespace_errors < state->whitespace_error)1603return;16041605 err =whitespace_error_string(result);1606fprintf(stderr,"%s:%d:%s.\n%.*s\n",1607 state->patch_input_file, linenr, err, len, line);1608free(err);1609}16101611static voidcheck_whitespace(struct apply_state *state,1612const char*line,1613int len,1614unsigned ws_rule)1615{1616unsigned result =ws_check(line +1, len -1, ws_rule);16171618record_ws_error(state, result, line +1, len -2, state->linenr);1619}16201621/*1622 * Parse a unified diff. Note that this really needs to parse each1623 * fragment separately, since the only way to know the difference1624 * between a "---" that is part of a patch, and a "---" that starts1625 * the next patch is to look at the line counts..1626 */1627static intparse_fragment(struct apply_state *state,1628const char*line,1629unsigned long size,1630struct patch *patch,1631struct fragment *fragment)1632{1633int added, deleted;1634int len =linelen(line, size), offset;1635unsigned long oldlines, newlines;1636unsigned long leading, trailing;16371638 offset =parse_fragment_header(line, len, fragment);1639if(offset <0)1640return-1;1641if(offset >0&& patch->recount)1642recount_diff(line + offset, size - offset, fragment);1643 oldlines = fragment->oldlines;1644 newlines = fragment->newlines;1645 leading =0;1646 trailing =0;16471648/* Parse the thing.. */1649 line += len;1650 size -= len;1651 state->linenr++;1652 added = deleted =0;1653for(offset = len;16540< size;1655 offset += len, size -= len, line += len, state->linenr++) {1656if(!oldlines && !newlines)1657break;1658 len =linelen(line, size);1659if(!len || line[len-1] !='\n')1660return-1;1661switch(*line) {1662default:1663return-1;1664case'\n':/* newer GNU diff, an empty context line */1665case' ':1666 oldlines--;1667 newlines--;1668if(!deleted && !added)1669 leading++;1670 trailing++;1671if(!state->apply_in_reverse &&1672 state->ws_error_action == correct_ws_error)1673check_whitespace(state, line, len, patch->ws_rule);1674break;1675case'-':1676if(state->apply_in_reverse &&1677 state->ws_error_action != nowarn_ws_error)1678check_whitespace(state, line, len, patch->ws_rule);1679 deleted++;1680 oldlines--;1681 trailing =0;1682break;1683case'+':1684if(!state->apply_in_reverse &&1685 state->ws_error_action != nowarn_ws_error)1686check_whitespace(state, line, len, patch->ws_rule);1687 added++;1688 newlines--;1689 trailing =0;1690break;16911692/*1693 * We allow "\ No newline at end of file". Depending1694 * on locale settings when the patch was produced we1695 * don't know what this line looks like. The only1696 * thing we do know is that it begins with "\ ".1697 * Checking for 12 is just for sanity check -- any1698 * l10n of "\ No newline..." is at least that long.1699 */1700case'\\':1701if(len <12||memcmp(line,"\\",2))1702return-1;1703break;1704}1705}1706if(oldlines || newlines)1707return-1;1708if(!deleted && !added)1709return-1;17101711 fragment->leading = leading;1712 fragment->trailing = trailing;17131714/*1715 * If a fragment ends with an incomplete line, we failed to include1716 * it in the above loop because we hit oldlines == newlines == 01717 * before seeing it.1718 */1719if(12< size && !memcmp(line,"\\",2))1720 offset +=linelen(line, size);17211722 patch->lines_added += added;1723 patch->lines_deleted += deleted;17241725if(0< patch->is_new && oldlines)1726returnerror(_("new file depends on old contents"));1727if(0< patch->is_delete && newlines)1728returnerror(_("deleted file still has contents"));1729return offset;1730}17311732/*1733 * We have seen "diff --git a/... b/..." header (or a traditional patch1734 * header). Read hunks that belong to this patch into fragments and hang1735 * them to the given patch structure.1736 *1737 * The (fragment->patch, fragment->size) pair points into the memory given1738 * by the caller, not a copy, when we return.1739 */1740static intparse_single_patch(struct apply_state *state,1741const char*line,1742unsigned long size,1743struct patch *patch)1744{1745unsigned long offset =0;1746unsigned long oldlines =0, newlines =0, context =0;1747struct fragment **fragp = &patch->fragments;17481749while(size >4&& !memcmp(line,"@@ -",4)) {1750struct fragment *fragment;1751int len;17521753 fragment =xcalloc(1,sizeof(*fragment));1754 fragment->linenr = state->linenr;1755 len =parse_fragment(state, line, size, patch, fragment);1756if(len <=0)1757die(_("corrupt patch at line%d"), state->linenr);1758 fragment->patch = line;1759 fragment->size = len;1760 oldlines += fragment->oldlines;1761 newlines += fragment->newlines;1762 context += fragment->leading + fragment->trailing;17631764*fragp = fragment;1765 fragp = &fragment->next;17661767 offset += len;1768 line += len;1769 size -= len;1770}17711772/*1773 * If something was removed (i.e. we have old-lines) it cannot1774 * be creation, and if something was added it cannot be1775 * deletion. However, the reverse is not true; --unified=01776 * patches that only add are not necessarily creation even1777 * though they do not have any old lines, and ones that only1778 * delete are not necessarily deletion.1779 *1780 * Unfortunately, a real creation/deletion patch do _not_ have1781 * any context line by definition, so we cannot safely tell it1782 * apart with --unified=0 insanity. At least if the patch has1783 * more than one hunk it is not creation or deletion.1784 */1785if(patch->is_new <0&&1786(oldlines || (patch->fragments && patch->fragments->next)))1787 patch->is_new =0;1788if(patch->is_delete <0&&1789(newlines || (patch->fragments && patch->fragments->next)))1790 patch->is_delete =0;17911792if(0< patch->is_new && oldlines)1793die(_("new file%sdepends on old contents"), patch->new_name);1794if(0< patch->is_delete && newlines)1795die(_("deleted file%sstill has contents"), patch->old_name);1796if(!patch->is_delete && !newlines && context)1797fprintf_ln(stderr,1798_("** warning: "1799"file%sbecomes empty but is not deleted"),1800 patch->new_name);18011802return offset;1803}18041805staticinlineintmetadata_changes(struct patch *patch)1806{1807return patch->is_rename >0||1808 patch->is_copy >0||1809 patch->is_new >0||1810 patch->is_delete ||1811(patch->old_mode && patch->new_mode &&1812 patch->old_mode != patch->new_mode);1813}18141815static char*inflate_it(const void*data,unsigned long size,1816unsigned long inflated_size)1817{1818 git_zstream stream;1819void*out;1820int st;18211822memset(&stream,0,sizeof(stream));18231824 stream.next_in = (unsigned char*)data;1825 stream.avail_in = size;1826 stream.next_out = out =xmalloc(inflated_size);1827 stream.avail_out = inflated_size;1828git_inflate_init(&stream);1829 st =git_inflate(&stream, Z_FINISH);1830git_inflate_end(&stream);1831if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1832free(out);1833return NULL;1834}1835return out;1836}18371838/*1839 * Read a binary hunk and return a new fragment; fragment->patch1840 * points at an allocated memory that the caller must free, so1841 * it is marked as "->free_patch = 1".1842 */1843static struct fragment *parse_binary_hunk(struct apply_state *state,1844char**buf_p,1845unsigned long*sz_p,1846int*status_p,1847int*used_p)1848{1849/*1850 * Expect a line that begins with binary patch method ("literal"1851 * or "delta"), followed by the length of data before deflating.1852 * a sequence of 'length-byte' followed by base-85 encoded data1853 * should follow, terminated by a newline.1854 *1855 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1856 * and we would limit the patch line to 66 characters,1857 * so one line can fit up to 13 groups that would decode1858 * to 52 bytes max. The length byte 'A'-'Z' corresponds1859 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1860 */1861int llen, used;1862unsigned long size = *sz_p;1863char*buffer = *buf_p;1864int patch_method;1865unsigned long origlen;1866char*data = NULL;1867int hunk_size =0;1868struct fragment *frag;18691870 llen =linelen(buffer, size);1871 used = llen;18721873*status_p =0;18741875if(starts_with(buffer,"delta ")) {1876 patch_method = BINARY_DELTA_DEFLATED;1877 origlen =strtoul(buffer +6, NULL,10);1878}1879else if(starts_with(buffer,"literal ")) {1880 patch_method = BINARY_LITERAL_DEFLATED;1881 origlen =strtoul(buffer +8, NULL,10);1882}1883else1884return NULL;18851886 state->linenr++;1887 buffer += llen;1888while(1) {1889int byte_length, max_byte_length, newsize;1890 llen =linelen(buffer, size);1891 used += llen;1892 state->linenr++;1893if(llen ==1) {1894/* consume the blank line */1895 buffer++;1896 size--;1897break;1898}1899/*1900 * Minimum line is "A00000\n" which is 7-byte long,1901 * and the line length must be multiple of 5 plus 2.1902 */1903if((llen <7) || (llen-2) %5)1904goto corrupt;1905 max_byte_length = (llen -2) /5*4;1906 byte_length = *buffer;1907if('A'<= byte_length && byte_length <='Z')1908 byte_length = byte_length -'A'+1;1909else if('a'<= byte_length && byte_length <='z')1910 byte_length = byte_length -'a'+27;1911else1912goto corrupt;1913/* if the input length was not multiple of 4, we would1914 * have filler at the end but the filler should never1915 * exceed 3 bytes1916 */1917if(max_byte_length < byte_length ||1918 byte_length <= max_byte_length -4)1919goto corrupt;1920 newsize = hunk_size + byte_length;1921 data =xrealloc(data, newsize);1922if(decode_85(data + hunk_size, buffer +1, byte_length))1923goto corrupt;1924 hunk_size = newsize;1925 buffer += llen;1926 size -= llen;1927}19281929 frag =xcalloc(1,sizeof(*frag));1930 frag->patch =inflate_it(data, hunk_size, origlen);1931 frag->free_patch =1;1932if(!frag->patch)1933goto corrupt;1934free(data);1935 frag->size = origlen;1936*buf_p = buffer;1937*sz_p = size;1938*used_p = used;1939 frag->binary_patch_method = patch_method;1940return frag;19411942 corrupt:1943free(data);1944*status_p = -1;1945error(_("corrupt binary patch at line%d: %.*s"),1946 state->linenr-1, llen-1, buffer);1947return NULL;1948}19491950/*1951 * Returns:1952 * -1 in case of error,1953 * the length of the parsed binary patch otherwise1954 */1955static intparse_binary(struct apply_state *state,1956char*buffer,1957unsigned long size,1958struct patch *patch)1959{1960/*1961 * We have read "GIT binary patch\n"; what follows is a line1962 * that says the patch method (currently, either "literal" or1963 * "delta") and the length of data before deflating; a1964 * sequence of 'length-byte' followed by base-85 encoded data1965 * follows.1966 *1967 * When a binary patch is reversible, there is another binary1968 * hunk in the same format, starting with patch method (either1969 * "literal" or "delta") with the length of data, and a sequence1970 * of length-byte + base-85 encoded data, terminated with another1971 * empty line. This data, when applied to the postimage, produces1972 * the preimage.1973 */1974struct fragment *forward;1975struct fragment *reverse;1976int status;1977int used, used_1;19781979 forward =parse_binary_hunk(state, &buffer, &size, &status, &used);1980if(!forward && !status)1981/* there has to be one hunk (forward hunk) */1982returnerror(_("unrecognized binary patch at line%d"), state->linenr-1);1983if(status)1984/* otherwise we already gave an error message */1985return status;19861987 reverse =parse_binary_hunk(state, &buffer, &size, &status, &used_1);1988if(reverse)1989 used += used_1;1990else if(status) {1991/*1992 * Not having reverse hunk is not an error, but having1993 * a corrupt reverse hunk is.1994 */1995free((void*) forward->patch);1996free(forward);1997return status;1998}1999 forward->next = reverse;2000 patch->fragments = forward;2001 patch->is_binary =1;2002return used;2003}20042005static voidprefix_one(struct apply_state *state,char**name)2006{2007char*old_name = *name;2008if(!old_name)2009return;2010*name =xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));2011free(old_name);2012}20132014static voidprefix_patch(struct apply_state *state,struct patch *p)2015{2016if(!state->prefix || p->is_toplevel_relative)2017return;2018prefix_one(state, &p->new_name);2019prefix_one(state, &p->old_name);2020}20212022/*2023 * include/exclude2024 */20252026static voidadd_name_limit(struct apply_state *state,2027const char*name,2028int exclude)2029{2030struct string_list_item *it;20312032 it =string_list_append(&state->limit_by_name, name);2033 it->util = exclude ? NULL : (void*)1;2034}20352036static intuse_patch(struct apply_state *state,struct patch *p)2037{2038const char*pathname = p->new_name ? p->new_name : p->old_name;2039int i;20402041/* Paths outside are not touched regardless of "--include" */2042if(0< state->prefix_length) {2043int pathlen =strlen(pathname);2044if(pathlen <= state->prefix_length ||2045memcmp(state->prefix, pathname, state->prefix_length))2046return0;2047}20482049/* See if it matches any of exclude/include rule */2050for(i =0; i < state->limit_by_name.nr; i++) {2051struct string_list_item *it = &state->limit_by_name.items[i];2052if(!wildmatch(it->string, pathname,0, NULL))2053return(it->util != NULL);2054}20552056/*2057 * If we had any include, a path that does not match any rule is2058 * not used. Otherwise, we saw bunch of exclude rules (or none)2059 * and such a path is used.2060 */2061return!state->has_include;2062}206320642065/*2066 * Read the patch text in "buffer" that extends for "size" bytes; stop2067 * reading after seeing a single patch (i.e. changes to a single file).2068 * Create fragments (i.e. patch hunks) and hang them to the given patch.2069 * Return the number of bytes consumed, so that the caller can call us2070 * again for the next patch.2071 */2072static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2073{2074int hdrsize, patchsize;2075int offset =find_header(state, buffer, size, &hdrsize, patch);20762077if(offset <0)2078return offset;20792080prefix_patch(state, patch);20812082if(!use_patch(state, patch))2083 patch->ws_rule =0;2084else2085 patch->ws_rule =whitespace_rule(patch->new_name2086? patch->new_name2087: patch->old_name);20882089 patchsize =parse_single_patch(state,2090 buffer + offset + hdrsize,2091 size - offset - hdrsize,2092 patch);20932094if(!patchsize) {2095static const char git_binary[] ="GIT binary patch\n";2096int hd = hdrsize + offset;2097unsigned long llen =linelen(buffer + hd, size - hd);20982099if(llen ==sizeof(git_binary) -1&&2100!memcmp(git_binary, buffer + hd, llen)) {2101int used;2102 state->linenr++;2103 used =parse_binary(state, buffer + hd + llen,2104 size - hd - llen, patch);2105if(used <0)2106return-1;2107if(used)2108 patchsize = used + llen;2109else2110 patchsize =0;2111}2112else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2113static const char*binhdr[] = {2114"Binary files ",2115"Files ",2116 NULL,2117};2118int i;2119for(i =0; binhdr[i]; i++) {2120int len =strlen(binhdr[i]);2121if(len < size - hd &&2122!memcmp(binhdr[i], buffer + hd, len)) {2123 state->linenr++;2124 patch->is_binary =1;2125 patchsize = llen;2126break;2127}2128}2129}21302131/* Empty patch cannot be applied if it is a text patch2132 * without metadata change. A binary patch appears2133 * empty to us here.2134 */2135if((state->apply || state->check) &&2136(!patch->is_binary && !metadata_changes(patch)))2137die(_("patch with only garbage at line%d"), state->linenr);2138}21392140return offset + hdrsize + patchsize;2141}21422143#define swap(a,b) myswap((a),(b),sizeof(a))21442145#define myswap(a, b, size) do { \2146 unsigned char mytmp[size]; \2147 memcpy(mytmp, &a, size); \2148 memcpy(&a, &b, size); \2149 memcpy(&b, mytmp, size); \2150} while (0)21512152static voidreverse_patches(struct patch *p)2153{2154for(; p; p = p->next) {2155struct fragment *frag = p->fragments;21562157swap(p->new_name, p->old_name);2158swap(p->new_mode, p->old_mode);2159swap(p->is_new, p->is_delete);2160swap(p->lines_added, p->lines_deleted);2161swap(p->old_sha1_prefix, p->new_sha1_prefix);21622163for(; frag; frag = frag->next) {2164swap(frag->newpos, frag->oldpos);2165swap(frag->newlines, frag->oldlines);2166}2167}2168}21692170static const char pluses[] =2171"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2172static const char minuses[]=2173"----------------------------------------------------------------------";21742175static voidshow_stats(struct apply_state *state,struct patch *patch)2176{2177struct strbuf qname = STRBUF_INIT;2178char*cp = patch->new_name ? patch->new_name : patch->old_name;2179int max, add, del;21802181quote_c_style(cp, &qname, NULL,0);21822183/*2184 * "scale" the filename2185 */2186 max = state->max_len;2187if(max >50)2188 max =50;21892190if(qname.len > max) {2191 cp =strchr(qname.buf + qname.len +3- max,'/');2192if(!cp)2193 cp = qname.buf + qname.len +3- max;2194strbuf_splice(&qname,0, cp - qname.buf,"...",3);2195}21962197if(patch->is_binary) {2198printf(" %-*s | Bin\n", max, qname.buf);2199strbuf_release(&qname);2200return;2201}22022203printf(" %-*s |", max, qname.buf);2204strbuf_release(&qname);22052206/*2207 * scale the add/delete2208 */2209 max = max + state->max_change >70?70- max : state->max_change;2210 add = patch->lines_added;2211 del = patch->lines_deleted;22122213if(state->max_change >0) {2214int total = ((add + del) * max + state->max_change /2) / state->max_change;2215 add = (add * max + state->max_change /2) / state->max_change;2216 del = total - add;2217}2218printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2219 add, pluses, del, minuses);2220}22212222static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2223{2224switch(st->st_mode & S_IFMT) {2225case S_IFLNK:2226if(strbuf_readlink(buf, path, st->st_size) <0)2227returnerror(_("unable to read symlink%s"), path);2228return0;2229case S_IFREG:2230if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2231returnerror(_("unable to open or read%s"), path);2232convert_to_git(path, buf->buf, buf->len, buf,0);2233return0;2234default:2235return-1;2236}2237}22382239/*2240 * Update the preimage, and the common lines in postimage,2241 * from buffer buf of length len. If postlen is 0 the postimage2242 * is updated in place, otherwise it's updated on a new buffer2243 * of length postlen2244 */22452246static voidupdate_pre_post_images(struct image *preimage,2247struct image *postimage,2248char*buf,2249size_t len,size_t postlen)2250{2251int i, ctx, reduced;2252char*new, *old, *fixed;2253struct image fixed_preimage;22542255/*2256 * Update the preimage with whitespace fixes. Note that we2257 * are not losing preimage->buf -- apply_one_fragment() will2258 * free "oldlines".2259 */2260prepare_image(&fixed_preimage, buf, len,1);2261assert(postlen2262? fixed_preimage.nr == preimage->nr2263: fixed_preimage.nr <= preimage->nr);2264for(i =0; i < fixed_preimage.nr; i++)2265 fixed_preimage.line[i].flag = preimage->line[i].flag;2266free(preimage->line_allocated);2267*preimage = fixed_preimage;22682269/*2270 * Adjust the common context lines in postimage. This can be2271 * done in-place when we are shrinking it with whitespace2272 * fixing, but needs a new buffer when ignoring whitespace or2273 * expanding leading tabs to spaces.2274 *2275 * We trust the caller to tell us if the update can be done2276 * in place (postlen==0) or not.2277 */2278 old = postimage->buf;2279if(postlen)2280new= postimage->buf =xmalloc(postlen);2281else2282new= old;2283 fixed = preimage->buf;22842285for(i = reduced = ctx =0; i < postimage->nr; i++) {2286size_t l_len = postimage->line[i].len;2287if(!(postimage->line[i].flag & LINE_COMMON)) {2288/* an added line -- no counterparts in preimage */2289memmove(new, old, l_len);2290 old += l_len;2291new+= l_len;2292continue;2293}22942295/* a common context -- skip it in the original postimage */2296 old += l_len;22972298/* and find the corresponding one in the fixed preimage */2299while(ctx < preimage->nr &&2300!(preimage->line[ctx].flag & LINE_COMMON)) {2301 fixed += preimage->line[ctx].len;2302 ctx++;2303}23042305/*2306 * preimage is expected to run out, if the caller2307 * fixed addition of trailing blank lines.2308 */2309if(preimage->nr <= ctx) {2310 reduced++;2311continue;2312}23132314/* and copy it in, while fixing the line length */2315 l_len = preimage->line[ctx].len;2316memcpy(new, fixed, l_len);2317new+= l_len;2318 fixed += l_len;2319 postimage->line[i].len = l_len;2320 ctx++;2321}23222323if(postlen2324? postlen <new- postimage->buf2325: postimage->len <new- postimage->buf)2326die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2327(int)postlen, (int) postimage->len, (int)(new- postimage->buf));23282329/* Fix the length of the whole thing */2330 postimage->len =new- postimage->buf;2331 postimage->nr -= reduced;2332}23332334static intline_by_line_fuzzy_match(struct image *img,2335struct image *preimage,2336struct image *postimage,2337unsigned longtry,2338int try_lno,2339int preimage_limit)2340{2341int i;2342size_t imgoff =0;2343size_t preoff =0;2344size_t postlen = postimage->len;2345size_t extra_chars;2346char*buf;2347char*preimage_eof;2348char*preimage_end;2349struct strbuf fixed;2350char*fixed_buf;2351size_t fixed_len;23522353for(i =0; i < preimage_limit; i++) {2354size_t prelen = preimage->line[i].len;2355size_t imglen = img->line[try_lno+i].len;23562357if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2358 preimage->buf + preoff, prelen))2359return0;2360if(preimage->line[i].flag & LINE_COMMON)2361 postlen += imglen - prelen;2362 imgoff += imglen;2363 preoff += prelen;2364}23652366/*2367 * Ok, the preimage matches with whitespace fuzz.2368 *2369 * imgoff now holds the true length of the target that2370 * matches the preimage before the end of the file.2371 *2372 * Count the number of characters in the preimage that fall2373 * beyond the end of the file and make sure that all of them2374 * are whitespace characters. (This can only happen if2375 * we are removing blank lines at the end of the file.)2376 */2377 buf = preimage_eof = preimage->buf + preoff;2378for( ; i < preimage->nr; i++)2379 preoff += preimage->line[i].len;2380 preimage_end = preimage->buf + preoff;2381for( ; buf < preimage_end; buf++)2382if(!isspace(*buf))2383return0;23842385/*2386 * Update the preimage and the common postimage context2387 * lines to use the same whitespace as the target.2388 * If whitespace is missing in the target (i.e.2389 * if the preimage extends beyond the end of the file),2390 * use the whitespace from the preimage.2391 */2392 extra_chars = preimage_end - preimage_eof;2393strbuf_init(&fixed, imgoff + extra_chars);2394strbuf_add(&fixed, img->buf +try, imgoff);2395strbuf_add(&fixed, preimage_eof, extra_chars);2396 fixed_buf =strbuf_detach(&fixed, &fixed_len);2397update_pre_post_images(preimage, postimage,2398 fixed_buf, fixed_len, postlen);2399return1;2400}24012402static intmatch_fragment(struct apply_state *state,2403struct image *img,2404struct image *preimage,2405struct image *postimage,2406unsigned longtry,2407int try_lno,2408unsigned ws_rule,2409int match_beginning,int match_end)2410{2411int i;2412char*fixed_buf, *buf, *orig, *target;2413struct strbuf fixed;2414size_t fixed_len, postlen;2415int preimage_limit;24162417if(preimage->nr + try_lno <= img->nr) {2418/*2419 * The hunk falls within the boundaries of img.2420 */2421 preimage_limit = preimage->nr;2422if(match_end && (preimage->nr + try_lno != img->nr))2423return0;2424}else if(state->ws_error_action == correct_ws_error &&2425(ws_rule & WS_BLANK_AT_EOF)) {2426/*2427 * This hunk extends beyond the end of img, and we are2428 * removing blank lines at the end of the file. This2429 * many lines from the beginning of the preimage must2430 * match with img, and the remainder of the preimage2431 * must be blank.2432 */2433 preimage_limit = img->nr - try_lno;2434}else{2435/*2436 * The hunk extends beyond the end of the img and2437 * we are not removing blanks at the end, so we2438 * should reject the hunk at this position.2439 */2440return0;2441}24422443if(match_beginning && try_lno)2444return0;24452446/* Quick hash check */2447for(i =0; i < preimage_limit; i++)2448if((img->line[try_lno + i].flag & LINE_PATCHED) ||2449(preimage->line[i].hash != img->line[try_lno + i].hash))2450return0;24512452if(preimage_limit == preimage->nr) {2453/*2454 * Do we have an exact match? If we were told to match2455 * at the end, size must be exactly at try+fragsize,2456 * otherwise try+fragsize must be still within the preimage,2457 * and either case, the old piece should match the preimage2458 * exactly.2459 */2460if((match_end2461? (try+ preimage->len == img->len)2462: (try+ preimage->len <= img->len)) &&2463!memcmp(img->buf +try, preimage->buf, preimage->len))2464return1;2465}else{2466/*2467 * The preimage extends beyond the end of img, so2468 * there cannot be an exact match.2469 *2470 * There must be one non-blank context line that match2471 * a line before the end of img.2472 */2473char*buf_end;24742475 buf = preimage->buf;2476 buf_end = buf;2477for(i =0; i < preimage_limit; i++)2478 buf_end += preimage->line[i].len;24792480for( ; buf < buf_end; buf++)2481if(!isspace(*buf))2482break;2483if(buf == buf_end)2484return0;2485}24862487/*2488 * No exact match. If we are ignoring whitespace, run a line-by-line2489 * fuzzy matching. We collect all the line length information because2490 * we need it to adjust whitespace if we match.2491 */2492if(state->ws_ignore_action == ignore_ws_change)2493returnline_by_line_fuzzy_match(img, preimage, postimage,2494try, try_lno, preimage_limit);24952496if(state->ws_error_action != correct_ws_error)2497return0;24982499/*2500 * The hunk does not apply byte-by-byte, but the hash says2501 * it might with whitespace fuzz. We weren't asked to2502 * ignore whitespace, we were asked to correct whitespace2503 * errors, so let's try matching after whitespace correction.2504 *2505 * While checking the preimage against the target, whitespace2506 * errors in both fixed, we count how large the corresponding2507 * postimage needs to be. The postimage prepared by2508 * apply_one_fragment() has whitespace errors fixed on added2509 * lines already, but the common lines were propagated as-is,2510 * which may become longer when their whitespace errors are2511 * fixed.2512 */25132514/* First count added lines in postimage */2515 postlen =0;2516for(i =0; i < postimage->nr; i++) {2517if(!(postimage->line[i].flag & LINE_COMMON))2518 postlen += postimage->line[i].len;2519}25202521/*2522 * The preimage may extend beyond the end of the file,2523 * but in this loop we will only handle the part of the2524 * preimage that falls within the file.2525 */2526strbuf_init(&fixed, preimage->len +1);2527 orig = preimage->buf;2528 target = img->buf +try;2529for(i =0; i < preimage_limit; i++) {2530size_t oldlen = preimage->line[i].len;2531size_t tgtlen = img->line[try_lno + i].len;2532size_t fixstart = fixed.len;2533struct strbuf tgtfix;2534int match;25352536/* Try fixing the line in the preimage */2537ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25382539/* Try fixing the line in the target */2540strbuf_init(&tgtfix, tgtlen);2541ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);25422543/*2544 * If they match, either the preimage was based on2545 * a version before our tree fixed whitespace breakage,2546 * or we are lacking a whitespace-fix patch the tree2547 * the preimage was based on already had (i.e. target2548 * has whitespace breakage, the preimage doesn't).2549 * In either case, we are fixing the whitespace breakages2550 * so we might as well take the fix together with their2551 * real change.2552 */2553 match = (tgtfix.len == fixed.len - fixstart &&2554!memcmp(tgtfix.buf, fixed.buf + fixstart,2555 fixed.len - fixstart));25562557/* Add the length if this is common with the postimage */2558if(preimage->line[i].flag & LINE_COMMON)2559 postlen += tgtfix.len;25602561strbuf_release(&tgtfix);2562if(!match)2563goto unmatch_exit;25642565 orig += oldlen;2566 target += tgtlen;2567}256825692570/*2571 * Now handle the lines in the preimage that falls beyond the2572 * end of the file (if any). They will only match if they are2573 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2574 * false).2575 */2576for( ; i < preimage->nr; i++) {2577size_t fixstart = fixed.len;/* start of the fixed preimage */2578size_t oldlen = preimage->line[i].len;2579int j;25802581/* Try fixing the line in the preimage */2582ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25832584for(j = fixstart; j < fixed.len; j++)2585if(!isspace(fixed.buf[j]))2586goto unmatch_exit;25872588 orig += oldlen;2589}25902591/*2592 * Yes, the preimage is based on an older version that still2593 * has whitespace breakages unfixed, and fixing them makes the2594 * hunk match. Update the context lines in the postimage.2595 */2596 fixed_buf =strbuf_detach(&fixed, &fixed_len);2597if(postlen < postimage->len)2598 postlen =0;2599update_pre_post_images(preimage, postimage,2600 fixed_buf, fixed_len, postlen);2601return1;26022603 unmatch_exit:2604strbuf_release(&fixed);2605return0;2606}26072608static intfind_pos(struct apply_state *state,2609struct image *img,2610struct image *preimage,2611struct image *postimage,2612int line,2613unsigned ws_rule,2614int match_beginning,int match_end)2615{2616int i;2617unsigned long backwards, forwards,try;2618int backwards_lno, forwards_lno, try_lno;26192620/*2621 * If match_beginning or match_end is specified, there is no2622 * point starting from a wrong line that will never match and2623 * wander around and wait for a match at the specified end.2624 */2625if(match_beginning)2626 line =0;2627else if(match_end)2628 line = img->nr - preimage->nr;26292630/*2631 * Because the comparison is unsigned, the following test2632 * will also take care of a negative line number that can2633 * result when match_end and preimage is larger than the target.2634 */2635if((size_t) line > img->nr)2636 line = img->nr;26372638try=0;2639for(i =0; i < line; i++)2640try+= img->line[i].len;26412642/*2643 * There's probably some smart way to do this, but I'll leave2644 * that to the smart and beautiful people. I'm simple and stupid.2645 */2646 backwards =try;2647 backwards_lno = line;2648 forwards =try;2649 forwards_lno = line;2650 try_lno = line;26512652for(i =0; ; i++) {2653if(match_fragment(state, img, preimage, postimage,2654try, try_lno, ws_rule,2655 match_beginning, match_end))2656return try_lno;26572658 again:2659if(backwards_lno ==0&& forwards_lno == img->nr)2660break;26612662if(i &1) {2663if(backwards_lno ==0) {2664 i++;2665goto again;2666}2667 backwards_lno--;2668 backwards -= img->line[backwards_lno].len;2669try= backwards;2670 try_lno = backwards_lno;2671}else{2672if(forwards_lno == img->nr) {2673 i++;2674goto again;2675}2676 forwards += img->line[forwards_lno].len;2677 forwards_lno++;2678try= forwards;2679 try_lno = forwards_lno;2680}26812682}2683return-1;2684}26852686static voidremove_first_line(struct image *img)2687{2688 img->buf += img->line[0].len;2689 img->len -= img->line[0].len;2690 img->line++;2691 img->nr--;2692}26932694static voidremove_last_line(struct image *img)2695{2696 img->len -= img->line[--img->nr].len;2697}26982699/*2700 * The change from "preimage" and "postimage" has been found to2701 * apply at applied_pos (counts in line numbers) in "img".2702 * Update "img" to remove "preimage" and replace it with "postimage".2703 */2704static voidupdate_image(struct apply_state *state,2705struct image *img,2706int applied_pos,2707struct image *preimage,2708struct image *postimage)2709{2710/*2711 * remove the copy of preimage at offset in img2712 * and replace it with postimage2713 */2714int i, nr;2715size_t remove_count, insert_count, applied_at =0;2716char*result;2717int preimage_limit;27182719/*2720 * If we are removing blank lines at the end of img,2721 * the preimage may extend beyond the end.2722 * If that is the case, we must be careful only to2723 * remove the part of the preimage that falls within2724 * the boundaries of img. Initialize preimage_limit2725 * to the number of lines in the preimage that falls2726 * within the boundaries.2727 */2728 preimage_limit = preimage->nr;2729if(preimage_limit > img->nr - applied_pos)2730 preimage_limit = img->nr - applied_pos;27312732for(i =0; i < applied_pos; i++)2733 applied_at += img->line[i].len;27342735 remove_count =0;2736for(i =0; i < preimage_limit; i++)2737 remove_count += img->line[applied_pos + i].len;2738 insert_count = postimage->len;27392740/* Adjust the contents */2741 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2742memcpy(result, img->buf, applied_at);2743memcpy(result + applied_at, postimage->buf, postimage->len);2744memcpy(result + applied_at + postimage->len,2745 img->buf + (applied_at + remove_count),2746 img->len - (applied_at + remove_count));2747free(img->buf);2748 img->buf = result;2749 img->len += insert_count - remove_count;2750 result[img->len] ='\0';27512752/* Adjust the line table */2753 nr = img->nr + postimage->nr - preimage_limit;2754if(preimage_limit < postimage->nr) {2755/*2756 * NOTE: this knows that we never call remove_first_line()2757 * on anything other than pre/post image.2758 */2759REALLOC_ARRAY(img->line, nr);2760 img->line_allocated = img->line;2761}2762if(preimage_limit != postimage->nr)2763memmove(img->line + applied_pos + postimage->nr,2764 img->line + applied_pos + preimage_limit,2765(img->nr - (applied_pos + preimage_limit)) *2766sizeof(*img->line));2767memcpy(img->line + applied_pos,2768 postimage->line,2769 postimage->nr *sizeof(*img->line));2770if(!state->allow_overlap)2771for(i =0; i < postimage->nr; i++)2772 img->line[applied_pos + i].flag |= LINE_PATCHED;2773 img->nr = nr;2774}27752776/*2777 * Use the patch-hunk text in "frag" to prepare two images (preimage and2778 * postimage) for the hunk. Find lines that match "preimage" in "img" and2779 * replace the part of "img" with "postimage" text.2780 */2781static intapply_one_fragment(struct apply_state *state,2782struct image *img,struct fragment *frag,2783int inaccurate_eof,unsigned ws_rule,2784int nth_fragment)2785{2786int match_beginning, match_end;2787const char*patch = frag->patch;2788int size = frag->size;2789char*old, *oldlines;2790struct strbuf newlines;2791int new_blank_lines_at_end =0;2792int found_new_blank_lines_at_end =0;2793int hunk_linenr = frag->linenr;2794unsigned long leading, trailing;2795int pos, applied_pos;2796struct image preimage;2797struct image postimage;27982799memset(&preimage,0,sizeof(preimage));2800memset(&postimage,0,sizeof(postimage));2801 oldlines =xmalloc(size);2802strbuf_init(&newlines, size);28032804 old = oldlines;2805while(size >0) {2806char first;2807int len =linelen(patch, size);2808int plen;2809int added_blank_line =0;2810int is_blank_context =0;2811size_t start;28122813if(!len)2814break;28152816/*2817 * "plen" is how much of the line we should use for2818 * the actual patch data. Normally we just remove the2819 * first character on the line, but if the line is2820 * followed by "\ No newline", then we also remove the2821 * last one (which is the newline, of course).2822 */2823 plen = len -1;2824if(len < size && patch[len] =='\\')2825 plen--;2826 first = *patch;2827if(state->apply_in_reverse) {2828if(first =='-')2829 first ='+';2830else if(first =='+')2831 first ='-';2832}28332834switch(first) {2835case'\n':2836/* Newer GNU diff, empty context line */2837if(plen <0)2838/* ... followed by '\No newline'; nothing */2839break;2840*old++ ='\n';2841strbuf_addch(&newlines,'\n');2842add_line_info(&preimage,"\n",1, LINE_COMMON);2843add_line_info(&postimage,"\n",1, LINE_COMMON);2844 is_blank_context =1;2845break;2846case' ':2847if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2848ws_blank_line(patch +1, plen, ws_rule))2849 is_blank_context =1;2850case'-':2851memcpy(old, patch +1, plen);2852add_line_info(&preimage, old, plen,2853(first ==' '? LINE_COMMON :0));2854 old += plen;2855if(first =='-')2856break;2857/* Fall-through for ' ' */2858case'+':2859/* --no-add does not add new lines */2860if(first =='+'&& state->no_add)2861break;28622863 start = newlines.len;2864if(first !='+'||2865!state->whitespace_error ||2866 state->ws_error_action != correct_ws_error) {2867strbuf_add(&newlines, patch +1, plen);2868}2869else{2870ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2871}2872add_line_info(&postimage, newlines.buf + start, newlines.len - start,2873(first =='+'?0: LINE_COMMON));2874if(first =='+'&&2875(ws_rule & WS_BLANK_AT_EOF) &&2876ws_blank_line(patch +1, plen, ws_rule))2877 added_blank_line =1;2878break;2879case'@':case'\\':2880/* Ignore it, we already handled it */2881break;2882default:2883if(state->apply_verbosely)2884error(_("invalid start of line: '%c'"), first);2885 applied_pos = -1;2886goto out;2887}2888if(added_blank_line) {2889if(!new_blank_lines_at_end)2890 found_new_blank_lines_at_end = hunk_linenr;2891 new_blank_lines_at_end++;2892}2893else if(is_blank_context)2894;2895else2896 new_blank_lines_at_end =0;2897 patch += len;2898 size -= len;2899 hunk_linenr++;2900}2901if(inaccurate_eof &&2902 old > oldlines && old[-1] =='\n'&&2903 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2904 old--;2905strbuf_setlen(&newlines, newlines.len -1);2906}29072908 leading = frag->leading;2909 trailing = frag->trailing;29102911/*2912 * A hunk to change lines at the beginning would begin with2913 * @@ -1,L +N,M @@2914 * but we need to be careful. -U0 that inserts before the second2915 * line also has this pattern.2916 *2917 * And a hunk to add to an empty file would begin with2918 * @@ -0,0 +N,M @@2919 *2920 * In other words, a hunk that is (frag->oldpos <= 1) with or2921 * without leading context must match at the beginning.2922 */2923 match_beginning = (!frag->oldpos ||2924(frag->oldpos ==1&& !state->unidiff_zero));29252926/*2927 * A hunk without trailing lines must match at the end.2928 * However, we simply cannot tell if a hunk must match end2929 * from the lack of trailing lines if the patch was generated2930 * with unidiff without any context.2931 */2932 match_end = !state->unidiff_zero && !trailing;29332934 pos = frag->newpos ? (frag->newpos -1) :0;2935 preimage.buf = oldlines;2936 preimage.len = old - oldlines;2937 postimage.buf = newlines.buf;2938 postimage.len = newlines.len;2939 preimage.line = preimage.line_allocated;2940 postimage.line = postimage.line_allocated;29412942for(;;) {29432944 applied_pos =find_pos(state, img, &preimage, &postimage, pos,2945 ws_rule, match_beginning, match_end);29462947if(applied_pos >=0)2948break;29492950/* Am I at my context limits? */2951if((leading <= state->p_context) && (trailing <= state->p_context))2952break;2953if(match_beginning || match_end) {2954 match_beginning = match_end =0;2955continue;2956}29572958/*2959 * Reduce the number of context lines; reduce both2960 * leading and trailing if they are equal otherwise2961 * just reduce the larger context.2962 */2963if(leading >= trailing) {2964remove_first_line(&preimage);2965remove_first_line(&postimage);2966 pos--;2967 leading--;2968}2969if(trailing > leading) {2970remove_last_line(&preimage);2971remove_last_line(&postimage);2972 trailing--;2973}2974}29752976if(applied_pos >=0) {2977if(new_blank_lines_at_end &&2978 preimage.nr + applied_pos >= img->nr &&2979(ws_rule & WS_BLANK_AT_EOF) &&2980 state->ws_error_action != nowarn_ws_error) {2981record_ws_error(state, WS_BLANK_AT_EOF,"+",1,2982 found_new_blank_lines_at_end);2983if(state->ws_error_action == correct_ws_error) {2984while(new_blank_lines_at_end--)2985remove_last_line(&postimage);2986}2987/*2988 * We would want to prevent write_out_results()2989 * from taking place in apply_patch() that follows2990 * the callchain led us here, which is:2991 * apply_patch->check_patch_list->check_patch->2992 * apply_data->apply_fragments->apply_one_fragment2993 */2994if(state->ws_error_action == die_on_ws_error)2995 state->apply =0;2996}29972998if(state->apply_verbosely && applied_pos != pos) {2999int offset = applied_pos - pos;3000if(state->apply_in_reverse)3001 offset =0- offset;3002fprintf_ln(stderr,3003Q_("Hunk #%dsucceeded at%d(offset%dline).",3004"Hunk #%dsucceeded at%d(offset%dlines).",3005 offset),3006 nth_fragment, applied_pos +1, offset);3007}30083009/*3010 * Warn if it was necessary to reduce the number3011 * of context lines.3012 */3013if((leading != frag->leading) ||3014(trailing != frag->trailing))3015fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"3016" to apply fragment at%d"),3017 leading, trailing, applied_pos+1);3018update_image(state, img, applied_pos, &preimage, &postimage);3019}else{3020if(state->apply_verbosely)3021error(_("while searching for:\n%.*s"),3022(int)(old - oldlines), oldlines);3023}30243025out:3026free(oldlines);3027strbuf_release(&newlines);3028free(preimage.line_allocated);3029free(postimage.line_allocated);30303031return(applied_pos <0);3032}30333034static intapply_binary_fragment(struct apply_state *state,3035struct image *img,3036struct patch *patch)3037{3038struct fragment *fragment = patch->fragments;3039unsigned long len;3040void*dst;30413042if(!fragment)3043returnerror(_("missing binary patch data for '%s'"),3044 patch->new_name ?3045 patch->new_name :3046 patch->old_name);30473048/* Binary patch is irreversible without the optional second hunk */3049if(state->apply_in_reverse) {3050if(!fragment->next)3051returnerror("cannot reverse-apply a binary patch "3052"without the reverse hunk to '%s'",3053 patch->new_name3054? patch->new_name : patch->old_name);3055 fragment = fragment->next;3056}3057switch(fragment->binary_patch_method) {3058case BINARY_DELTA_DEFLATED:3059 dst =patch_delta(img->buf, img->len, fragment->patch,3060 fragment->size, &len);3061if(!dst)3062return-1;3063clear_image(img);3064 img->buf = dst;3065 img->len = len;3066return0;3067case BINARY_LITERAL_DEFLATED:3068clear_image(img);3069 img->len = fragment->size;3070 img->buf =xmemdupz(fragment->patch, img->len);3071return0;3072}3073return-1;3074}30753076/*3077 * Replace "img" with the result of applying the binary patch.3078 * The binary patch data itself in patch->fragment is still kept3079 * but the preimage prepared by the caller in "img" is freed here3080 * or in the helper function apply_binary_fragment() this calls.3081 */3082static intapply_binary(struct apply_state *state,3083struct image *img,3084struct patch *patch)3085{3086const char*name = patch->old_name ? patch->old_name : patch->new_name;3087unsigned char sha1[20];30883089/*3090 * For safety, we require patch index line to contain3091 * full 40-byte textual SHA1 for old and new, at least for now.3092 */3093if(strlen(patch->old_sha1_prefix) !=40||3094strlen(patch->new_sha1_prefix) !=40||3095get_sha1_hex(patch->old_sha1_prefix, sha1) ||3096get_sha1_hex(patch->new_sha1_prefix, sha1))3097returnerror("cannot apply binary patch to '%s' "3098"without full index line", name);30993100if(patch->old_name) {3101/*3102 * See if the old one matches what the patch3103 * applies to.3104 */3105hash_sha1_file(img->buf, img->len, blob_type, sha1);3106if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3107returnerror("the patch applies to '%s' (%s), "3108"which does not match the "3109"current contents.",3110 name,sha1_to_hex(sha1));3111}3112else{3113/* Otherwise, the old one must be empty. */3114if(img->len)3115returnerror("the patch applies to an empty "3116"'%s' but it is not empty", name);3117}31183119get_sha1_hex(patch->new_sha1_prefix, sha1);3120if(is_null_sha1(sha1)) {3121clear_image(img);3122return0;/* deletion patch */3123}31243125if(has_sha1_file(sha1)) {3126/* We already have the postimage */3127enum object_type type;3128unsigned long size;3129char*result;31303131 result =read_sha1_file(sha1, &type, &size);3132if(!result)3133returnerror("the necessary postimage%sfor "3134"'%s' cannot be read",3135 patch->new_sha1_prefix, name);3136clear_image(img);3137 img->buf = result;3138 img->len = size;3139}else{3140/*3141 * We have verified buf matches the preimage;3142 * apply the patch data to it, which is stored3143 * in the patch->fragments->{patch,size}.3144 */3145if(apply_binary_fragment(state, img, patch))3146returnerror(_("binary patch does not apply to '%s'"),3147 name);31483149/* verify that the result matches */3150hash_sha1_file(img->buf, img->len, blob_type, sha1);3151if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3152returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3153 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3154}31553156return0;3157}31583159static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3160{3161struct fragment *frag = patch->fragments;3162const char*name = patch->old_name ? patch->old_name : patch->new_name;3163unsigned ws_rule = patch->ws_rule;3164unsigned inaccurate_eof = patch->inaccurate_eof;3165int nth =0;31663167if(patch->is_binary)3168returnapply_binary(state, img, patch);31693170while(frag) {3171 nth++;3172if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3173error(_("patch failed:%s:%ld"), name, frag->oldpos);3174if(!state->apply_with_reject)3175return-1;3176 frag->rejected =1;3177}3178 frag = frag->next;3179}3180return0;3181}31823183static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3184{3185if(S_ISGITLINK(mode)) {3186strbuf_grow(buf,100);3187strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3188}else{3189enum object_type type;3190unsigned long sz;3191char*result;31923193 result =read_sha1_file(sha1, &type, &sz);3194if(!result)3195return-1;3196/* XXX read_sha1_file NUL-terminates */3197strbuf_attach(buf, result, sz, sz +1);3198}3199return0;3200}32013202static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3203{3204if(!ce)3205return0;3206returnread_blob_object(buf, ce->sha1, ce->ce_mode);3207}32083209static struct patch *in_fn_table(struct apply_state *state,const char*name)3210{3211struct string_list_item *item;32123213if(name == NULL)3214return NULL;32153216 item =string_list_lookup(&state->fn_table, name);3217if(item != NULL)3218return(struct patch *)item->util;32193220return NULL;3221}32223223/*3224 * item->util in the filename table records the status of the path.3225 * Usually it points at a patch (whose result records the contents3226 * of it after applying it), but it could be PATH_WAS_DELETED for a3227 * path that a previously applied patch has already removed, or3228 * PATH_TO_BE_DELETED for a path that a later patch would remove.3229 *3230 * The latter is needed to deal with a case where two paths A and B3231 * are swapped by first renaming A to B and then renaming B to A;3232 * moving A to B should not be prevented due to presence of B as we3233 * will remove it in a later patch.3234 */3235#define PATH_TO_BE_DELETED ((struct patch *) -2)3236#define PATH_WAS_DELETED ((struct patch *) -1)32373238static intto_be_deleted(struct patch *patch)3239{3240return patch == PATH_TO_BE_DELETED;3241}32423243static intwas_deleted(struct patch *patch)3244{3245return patch == PATH_WAS_DELETED;3246}32473248static voidadd_to_fn_table(struct apply_state *state,struct patch *patch)3249{3250struct string_list_item *item;32513252/*3253 * Always add new_name unless patch is a deletion3254 * This should cover the cases for normal diffs,3255 * file creations and copies3256 */3257if(patch->new_name != NULL) {3258 item =string_list_insert(&state->fn_table, patch->new_name);3259 item->util = patch;3260}32613262/*3263 * store a failure on rename/deletion cases because3264 * later chunks shouldn't patch old names3265 */3266if((patch->new_name == NULL) || (patch->is_rename)) {3267 item =string_list_insert(&state->fn_table, patch->old_name);3268 item->util = PATH_WAS_DELETED;3269}3270}32713272static voidprepare_fn_table(struct apply_state *state,struct patch *patch)3273{3274/*3275 * store information about incoming file deletion3276 */3277while(patch) {3278if((patch->new_name == NULL) || (patch->is_rename)) {3279struct string_list_item *item;3280 item =string_list_insert(&state->fn_table, patch->old_name);3281 item->util = PATH_TO_BE_DELETED;3282}3283 patch = patch->next;3284}3285}32863287static intcheckout_target(struct index_state *istate,3288struct cache_entry *ce,struct stat *st)3289{3290struct checkout costate;32913292memset(&costate,0,sizeof(costate));3293 costate.base_dir ="";3294 costate.refresh_cache =1;3295 costate.istate = istate;3296if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3297returnerror(_("cannot checkout%s"), ce->name);3298return0;3299}33003301static struct patch *previous_patch(struct apply_state *state,3302struct patch *patch,3303int*gone)3304{3305struct patch *previous;33063307*gone =0;3308if(patch->is_copy || patch->is_rename)3309return NULL;/* "git" patches do not depend on the order */33103311 previous =in_fn_table(state, patch->old_name);3312if(!previous)3313return NULL;33143315if(to_be_deleted(previous))3316return NULL;/* the deletion hasn't happened yet */33173318if(was_deleted(previous))3319*gone =1;33203321return previous;3322}33233324static intverify_index_match(const struct cache_entry *ce,struct stat *st)3325{3326if(S_ISGITLINK(ce->ce_mode)) {3327if(!S_ISDIR(st->st_mode))3328return-1;3329return0;3330}3331returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3332}33333334#define SUBMODULE_PATCH_WITHOUT_INDEX 133353336static intload_patch_target(struct apply_state *state,3337struct strbuf *buf,3338const struct cache_entry *ce,3339struct stat *st,3340const char*name,3341unsigned expected_mode)3342{3343if(state->cached || state->check_index) {3344if(read_file_or_gitlink(ce, buf))3345returnerror(_("read of%sfailed"), name);3346}else if(name) {3347if(S_ISGITLINK(expected_mode)) {3348if(ce)3349returnread_file_or_gitlink(ce, buf);3350else3351return SUBMODULE_PATCH_WITHOUT_INDEX;3352}else if(has_symlink_leading_path(name,strlen(name))) {3353returnerror(_("reading from '%s' beyond a symbolic link"), name);3354}else{3355if(read_old_data(st, name, buf))3356returnerror(_("read of%sfailed"), name);3357}3358}3359return0;3360}33613362/*3363 * We are about to apply "patch"; populate the "image" with the3364 * current version we have, from the working tree or from the index,3365 * depending on the situation e.g. --cached/--index. If we are3366 * applying a non-git patch that incrementally updates the tree,3367 * we read from the result of a previous diff.3368 */3369static intload_preimage(struct apply_state *state,3370struct image *image,3371struct patch *patch,struct stat *st,3372const struct cache_entry *ce)3373{3374struct strbuf buf = STRBUF_INIT;3375size_t len;3376char*img;3377struct patch *previous;3378int status;33793380 previous =previous_patch(state, patch, &status);3381if(status)3382returnerror(_("path%shas been renamed/deleted"),3383 patch->old_name);3384if(previous) {3385/* We have a patched copy in memory; use that. */3386strbuf_add(&buf, previous->result, previous->resultsize);3387}else{3388 status =load_patch_target(state, &buf, ce, st,3389 patch->old_name, patch->old_mode);3390if(status <0)3391return status;3392else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3393/*3394 * There is no way to apply subproject3395 * patch without looking at the index.3396 * NEEDSWORK: shouldn't this be flagged3397 * as an error???3398 */3399free_fragment_list(patch->fragments);3400 patch->fragments = NULL;3401}else if(status) {3402returnerror(_("read of%sfailed"), patch->old_name);3403}3404}34053406 img =strbuf_detach(&buf, &len);3407prepare_image(image, img, len, !patch->is_binary);3408return0;3409}34103411static intthree_way_merge(struct image *image,3412char*path,3413const unsigned char*base,3414const unsigned char*ours,3415const unsigned char*theirs)3416{3417 mmfile_t base_file, our_file, their_file;3418 mmbuffer_t result = { NULL };3419int status;34203421read_mmblob(&base_file, base);3422read_mmblob(&our_file, ours);3423read_mmblob(&their_file, theirs);3424 status =ll_merge(&result, path,3425&base_file,"base",3426&our_file,"ours",3427&their_file,"theirs", NULL);3428free(base_file.ptr);3429free(our_file.ptr);3430free(their_file.ptr);3431if(status <0|| !result.ptr) {3432free(result.ptr);3433return-1;3434}3435clear_image(image);3436 image->buf = result.ptr;3437 image->len = result.size;34383439return status;3440}34413442/*3443 * When directly falling back to add/add three-way merge, we read from3444 * the current contents of the new_name. In no cases other than that3445 * this function will be called.3446 */3447static intload_current(struct apply_state *state,3448struct image *image,3449struct patch *patch)3450{3451struct strbuf buf = STRBUF_INIT;3452int status, pos;3453size_t len;3454char*img;3455struct stat st;3456struct cache_entry *ce;3457char*name = patch->new_name;3458unsigned mode = patch->new_mode;34593460if(!patch->is_new)3461die("BUG: patch to%sis not a creation", patch->old_name);34623463 pos =cache_name_pos(name,strlen(name));3464if(pos <0)3465returnerror(_("%s: does not exist in index"), name);3466 ce = active_cache[pos];3467if(lstat(name, &st)) {3468if(errno != ENOENT)3469returnerror(_("%s:%s"), name,strerror(errno));3470if(checkout_target(&the_index, ce, &st))3471return-1;3472}3473if(verify_index_match(ce, &st))3474returnerror(_("%s: does not match index"), name);34753476 status =load_patch_target(state, &buf, ce, &st, name, mode);3477if(status <0)3478return status;3479else if(status)3480return-1;3481 img =strbuf_detach(&buf, &len);3482prepare_image(image, img, len, !patch->is_binary);3483return0;3484}34853486static inttry_threeway(struct apply_state *state,3487struct image *image,3488struct patch *patch,3489struct stat *st,3490const struct cache_entry *ce)3491{3492unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3493struct strbuf buf = STRBUF_INIT;3494size_t len;3495int status;3496char*img;3497struct image tmp_image;34983499/* No point falling back to 3-way merge in these cases */3500if(patch->is_delete ||3501S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3502return-1;35033504/* Preimage the patch was prepared for */3505if(patch->is_new)3506write_sha1_file("",0, blob_type, pre_sha1);3507else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3508read_blob_object(&buf, pre_sha1, patch->old_mode))3509returnerror("repository lacks the necessary blob to fall back on 3-way merge.");35103511fprintf(stderr,"Falling back to three-way merge...\n");35123513 img =strbuf_detach(&buf, &len);3514prepare_image(&tmp_image, img, len,1);3515/* Apply the patch to get the post image */3516if(apply_fragments(state, &tmp_image, patch) <0) {3517clear_image(&tmp_image);3518return-1;3519}3520/* post_sha1[] is theirs */3521write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3522clear_image(&tmp_image);35233524/* our_sha1[] is ours */3525if(patch->is_new) {3526if(load_current(state, &tmp_image, patch))3527returnerror("cannot read the current contents of '%s'",3528 patch->new_name);3529}else{3530if(load_preimage(state, &tmp_image, patch, st, ce))3531returnerror("cannot read the current contents of '%s'",3532 patch->old_name);3533}3534write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3535clear_image(&tmp_image);35363537/* in-core three-way merge between post and our using pre as base */3538 status =three_way_merge(image, patch->new_name,3539 pre_sha1, our_sha1, post_sha1);3540if(status <0) {3541fprintf(stderr,"Failed to fall back on three-way merge...\n");3542return status;3543}35443545if(status) {3546 patch->conflicted_threeway =1;3547if(patch->is_new)3548oidclr(&patch->threeway_stage[0]);3549else3550hashcpy(patch->threeway_stage[0].hash, pre_sha1);3551hashcpy(patch->threeway_stage[1].hash, our_sha1);3552hashcpy(patch->threeway_stage[2].hash, post_sha1);3553fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3554}else{3555fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3556}3557return0;3558}35593560static intapply_data(struct apply_state *state,struct patch *patch,3561struct stat *st,const struct cache_entry *ce)3562{3563struct image image;35643565if(load_preimage(state, &image, patch, st, ce) <0)3566return-1;35673568if(patch->direct_to_threeway ||3569apply_fragments(state, &image, patch) <0) {3570/* Note: with --reject, apply_fragments() returns 0 */3571if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3572return-1;3573}3574 patch->result = image.buf;3575 patch->resultsize = image.len;3576add_to_fn_table(state, patch);3577free(image.line_allocated);35783579if(0< patch->is_delete && patch->resultsize)3580returnerror(_("removal patch leaves file contents"));35813582return0;3583}35843585/*3586 * If "patch" that we are looking at modifies or deletes what we have,3587 * we would want it not to lose any local modification we have, either3588 * in the working tree or in the index.3589 *3590 * This also decides if a non-git patch is a creation patch or a3591 * modification to an existing empty file. We do not check the state3592 * of the current tree for a creation patch in this function; the caller3593 * check_patch() separately makes sure (and errors out otherwise) that3594 * the path the patch creates does not exist in the current tree.3595 */3596static intcheck_preimage(struct apply_state *state,3597struct patch *patch,3598struct cache_entry **ce,3599struct stat *st)3600{3601const char*old_name = patch->old_name;3602struct patch *previous = NULL;3603int stat_ret =0, status;3604unsigned st_mode =0;36053606if(!old_name)3607return0;36083609assert(patch->is_new <=0);3610 previous =previous_patch(state, patch, &status);36113612if(status)3613returnerror(_("path%shas been renamed/deleted"), old_name);3614if(previous) {3615 st_mode = previous->new_mode;3616}else if(!state->cached) {3617 stat_ret =lstat(old_name, st);3618if(stat_ret && errno != ENOENT)3619returnerror(_("%s:%s"), old_name,strerror(errno));3620}36213622if(state->check_index && !previous) {3623int pos =cache_name_pos(old_name,strlen(old_name));3624if(pos <0) {3625if(patch->is_new <0)3626goto is_new;3627returnerror(_("%s: does not exist in index"), old_name);3628}3629*ce = active_cache[pos];3630if(stat_ret <0) {3631if(checkout_target(&the_index, *ce, st))3632return-1;3633}3634if(!state->cached &&verify_index_match(*ce, st))3635returnerror(_("%s: does not match index"), old_name);3636if(state->cached)3637 st_mode = (*ce)->ce_mode;3638}else if(stat_ret <0) {3639if(patch->is_new <0)3640goto is_new;3641returnerror(_("%s:%s"), old_name,strerror(errno));3642}36433644if(!state->cached && !previous)3645 st_mode =ce_mode_from_stat(*ce, st->st_mode);36463647if(patch->is_new <0)3648 patch->is_new =0;3649if(!patch->old_mode)3650 patch->old_mode = st_mode;3651if((st_mode ^ patch->old_mode) & S_IFMT)3652returnerror(_("%s: wrong type"), old_name);3653if(st_mode != patch->old_mode)3654warning(_("%shas type%o, expected%o"),3655 old_name, st_mode, patch->old_mode);3656if(!patch->new_mode && !patch->is_delete)3657 patch->new_mode = st_mode;3658return0;36593660 is_new:3661 patch->is_new =1;3662 patch->is_delete =0;3663free(patch->old_name);3664 patch->old_name = NULL;3665return0;3666}366736683669#define EXISTS_IN_INDEX 13670#define EXISTS_IN_WORKTREE 236713672static intcheck_to_create(struct apply_state *state,3673const char*new_name,3674int ok_if_exists)3675{3676struct stat nst;36773678if(state->check_index &&3679cache_name_pos(new_name,strlen(new_name)) >=0&&3680!ok_if_exists)3681return EXISTS_IN_INDEX;3682if(state->cached)3683return0;36843685if(!lstat(new_name, &nst)) {3686if(S_ISDIR(nst.st_mode) || ok_if_exists)3687return0;3688/*3689 * A leading component of new_name might be a symlink3690 * that is going to be removed with this patch, but3691 * still pointing at somewhere that has the path.3692 * In such a case, path "new_name" does not exist as3693 * far as git is concerned.3694 */3695if(has_symlink_leading_path(new_name,strlen(new_name)))3696return0;36973698return EXISTS_IN_WORKTREE;3699}else if((errno != ENOENT) && (errno != ENOTDIR)) {3700returnerror("%s:%s", new_name,strerror(errno));3701}3702return0;3703}37043705/*3706 * We need to keep track of how symlinks in the preimage are3707 * manipulated by the patches. A patch to add a/b/c where a/b3708 * is a symlink should not be allowed to affect the directory3709 * the symlink points at, but if the same patch removes a/b,3710 * it is perfectly fine, as the patch removes a/b to make room3711 * to create a directory a/b so that a/b/c can be created.3712 */3713static struct string_list symlink_changes;3714#define SYMLINK_GOES_AWAY 013715#define SYMLINK_IN_RESULT 0237163717static uintptr_tregister_symlink_changes(const char*path,uintptr_t what)3718{3719struct string_list_item *ent;37203721 ent =string_list_lookup(&symlink_changes, path);3722if(!ent) {3723 ent =string_list_insert(&symlink_changes, path);3724 ent->util = (void*)0;3725}3726 ent->util = (void*)(what | ((uintptr_t)ent->util));3727return(uintptr_t)ent->util;3728}37293730static uintptr_tcheck_symlink_changes(const char*path)3731{3732struct string_list_item *ent;37333734 ent =string_list_lookup(&symlink_changes, path);3735if(!ent)3736return0;3737return(uintptr_t)ent->util;3738}37393740static voidprepare_symlink_changes(struct patch *patch)3741{3742for( ; patch; patch = patch->next) {3743if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3744(patch->is_rename || patch->is_delete))3745/* the symlink at patch->old_name is removed */3746register_symlink_changes(patch->old_name, SYMLINK_GOES_AWAY);37473748if(patch->new_name &&S_ISLNK(patch->new_mode))3749/* the symlink at patch->new_name is created or remains */3750register_symlink_changes(patch->new_name, SYMLINK_IN_RESULT);3751}3752}37533754static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3755{3756do{3757unsigned int change;37583759while(--name->len && name->buf[name->len] !='/')3760;/* scan backwards */3761if(!name->len)3762break;3763 name->buf[name->len] ='\0';3764 change =check_symlink_changes(name->buf);3765if(change & SYMLINK_IN_RESULT)3766return1;3767if(change & SYMLINK_GOES_AWAY)3768/*3769 * This cannot be "return 0", because we may3770 * see a new one created at a higher level.3771 */3772continue;37733774/* otherwise, check the preimage */3775if(state->check_index) {3776struct cache_entry *ce;37773778 ce =cache_file_exists(name->buf, name->len, ignore_case);3779if(ce &&S_ISLNK(ce->ce_mode))3780return1;3781}else{3782struct stat st;3783if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3784return1;3785}3786}while(1);3787return0;3788}37893790static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3791{3792int ret;3793struct strbuf name = STRBUF_INIT;37943795assert(*name_ !='\0');3796strbuf_addstr(&name, name_);3797 ret =path_is_beyond_symlink_1(state, &name);3798strbuf_release(&name);37993800return ret;3801}38023803static voiddie_on_unsafe_path(struct patch *patch)3804{3805const char*old_name = NULL;3806const char*new_name = NULL;3807if(patch->is_delete)3808 old_name = patch->old_name;3809else if(!patch->is_new && !patch->is_copy)3810 old_name = patch->old_name;3811if(!patch->is_delete)3812 new_name = patch->new_name;38133814if(old_name && !verify_path(old_name))3815die(_("invalid path '%s'"), old_name);3816if(new_name && !verify_path(new_name))3817die(_("invalid path '%s'"), new_name);3818}38193820/*3821 * Check and apply the patch in-core; leave the result in patch->result3822 * for the caller to write it out to the final destination.3823 */3824static intcheck_patch(struct apply_state *state,struct patch *patch)3825{3826struct stat st;3827const char*old_name = patch->old_name;3828const char*new_name = patch->new_name;3829const char*name = old_name ? old_name : new_name;3830struct cache_entry *ce = NULL;3831struct patch *tpatch;3832int ok_if_exists;3833int status;38343835 patch->rejected =1;/* we will drop this after we succeed */38363837 status =check_preimage(state, patch, &ce, &st);3838if(status)3839return status;3840 old_name = patch->old_name;38413842/*3843 * A type-change diff is always split into a patch to delete3844 * old, immediately followed by a patch to create new (see3845 * diff.c::run_diff()); in such a case it is Ok that the entry3846 * to be deleted by the previous patch is still in the working3847 * tree and in the index.3848 *3849 * A patch to swap-rename between A and B would first rename A3850 * to B and then rename B to A. While applying the first one,3851 * the presence of B should not stop A from getting renamed to3852 * B; ask to_be_deleted() about the later rename. Removal of3853 * B and rename from A to B is handled the same way by asking3854 * was_deleted().3855 */3856if((tpatch =in_fn_table(state, new_name)) &&3857(was_deleted(tpatch) ||to_be_deleted(tpatch)))3858 ok_if_exists =1;3859else3860 ok_if_exists =0;38613862if(new_name &&3863((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3864int err =check_to_create(state, new_name, ok_if_exists);38653866if(err && state->threeway) {3867 patch->direct_to_threeway =1;3868}else switch(err) {3869case0:3870break;/* happy */3871case EXISTS_IN_INDEX:3872returnerror(_("%s: already exists in index"), new_name);3873break;3874case EXISTS_IN_WORKTREE:3875returnerror(_("%s: already exists in working directory"),3876 new_name);3877default:3878return err;3879}38803881if(!patch->new_mode) {3882if(0< patch->is_new)3883 patch->new_mode = S_IFREG |0644;3884else3885 patch->new_mode = patch->old_mode;3886}3887}38883889if(new_name && old_name) {3890int same = !strcmp(old_name, new_name);3891if(!patch->new_mode)3892 patch->new_mode = patch->old_mode;3893if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3894if(same)3895returnerror(_("new mode (%o) of%sdoes not "3896"match old mode (%o)"),3897 patch->new_mode, new_name,3898 patch->old_mode);3899else3900returnerror(_("new mode (%o) of%sdoes not "3901"match old mode (%o) of%s"),3902 patch->new_mode, new_name,3903 patch->old_mode, old_name);3904}3905}39063907if(!state->unsafe_paths)3908die_on_unsafe_path(patch);39093910/*3911 * An attempt to read from or delete a path that is beyond a3912 * symbolic link will be prevented by load_patch_target() that3913 * is called at the beginning of apply_data() so we do not3914 * have to worry about a patch marked with "is_delete" bit3915 * here. We however need to make sure that the patch result3916 * is not deposited to a path that is beyond a symbolic link3917 * here.3918 */3919if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3920returnerror(_("affected file '%s' is beyond a symbolic link"),3921 patch->new_name);39223923if(apply_data(state, patch, &st, ce) <0)3924returnerror(_("%s: patch does not apply"), name);3925 patch->rejected =0;3926return0;3927}39283929static intcheck_patch_list(struct apply_state *state,struct patch *patch)3930{3931int err =0;39323933prepare_symlink_changes(patch);3934prepare_fn_table(state, patch);3935while(patch) {3936if(state->apply_verbosely)3937say_patch_name(stderr,3938_("Checking patch%s..."), patch);3939 err |=check_patch(state, patch);3940 patch = patch->next;3941}3942return err;3943}39443945/* This function tries to read the sha1 from the current index */3946static intget_current_sha1(const char*path,unsigned char*sha1)3947{3948int pos;39493950if(read_cache() <0)3951return-1;3952 pos =cache_name_pos(path,strlen(path));3953if(pos <0)3954return-1;3955hashcpy(sha1, active_cache[pos]->sha1);3956return0;3957}39583959static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3960{3961/*3962 * A usable gitlink patch has only one fragment (hunk) that looks like:3963 * @@ -1 +1 @@3964 * -Subproject commit <old sha1>3965 * +Subproject commit <new sha1>3966 * or3967 * @@ -1 +0,0 @@3968 * -Subproject commit <old sha1>3969 * for a removal patch.3970 */3971struct fragment *hunk = p->fragments;3972static const char heading[] ="-Subproject commit ";3973char*preimage;39743975if(/* does the patch have only one hunk? */3976 hunk && !hunk->next &&3977/* is its preimage one line? */3978 hunk->oldpos ==1&& hunk->oldlines ==1&&3979/* does preimage begin with the heading? */3980(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3981starts_with(++preimage, heading) &&3982/* does it record full SHA-1? */3983!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3984 preimage[sizeof(heading) +40-1] =='\n'&&3985/* does the abbreviated name on the index line agree with it? */3986starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3987return0;/* it all looks fine */39883989/* we may have full object name on the index line */3990returnget_sha1_hex(p->old_sha1_prefix, sha1);3991}39923993/* Build an index that contains the just the files needed for a 3way merge */3994static voidbuild_fake_ancestor(struct patch *list,const char*filename)3995{3996struct patch *patch;3997struct index_state result = { NULL };3998static struct lock_file lock;39994000/* Once we start supporting the reverse patch, it may be4001 * worth showing the new sha1 prefix, but until then...4002 */4003for(patch = list; patch; patch = patch->next) {4004unsigned char sha1[20];4005struct cache_entry *ce;4006const char*name;40074008 name = patch->old_name ? patch->old_name : patch->new_name;4009if(0< patch->is_new)4010continue;40114012if(S_ISGITLINK(patch->old_mode)) {4013if(!preimage_sha1_in_gitlink_patch(patch, sha1))4014;/* ok, the textual part looks sane */4015else4016die("sha1 information is lacking or useless for submodule%s",4017 name);4018}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {4019;/* ok */4020}else if(!patch->lines_added && !patch->lines_deleted) {4021/* mode-only change: update the current */4022if(get_current_sha1(patch->old_name, sha1))4023die("mode change for%s, which is not "4024"in current HEAD", name);4025}else4026die("sha1 information is lacking or useless "4027"(%s).", name);40284029 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);4030if(!ce)4031die(_("make_cache_entry failed for path '%s'"), name);4032if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))4033die("Could not add%sto temporary index", name);4034}40354036hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);4037if(write_locked_index(&result, &lock, COMMIT_LOCK))4038die("Could not write temporary index to%s", filename);40394040discard_index(&result);4041}40424043static voidstat_patch_list(struct apply_state *state,struct patch *patch)4044{4045int files, adds, dels;40464047for(files = adds = dels =0; patch ; patch = patch->next) {4048 files++;4049 adds += patch->lines_added;4050 dels += patch->lines_deleted;4051show_stats(state, patch);4052}40534054print_stat_summary(stdout, files, adds, dels);4055}40564057static voidnumstat_patch_list(struct apply_state *state,4058struct patch *patch)4059{4060for( ; patch; patch = patch->next) {4061const char*name;4062 name = patch->new_name ? patch->new_name : patch->old_name;4063if(patch->is_binary)4064printf("-\t-\t");4065else4066printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4067write_name_quoted(name, stdout, state->line_termination);4068}4069}40704071static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4072{4073if(mode)4074printf("%smode%06o%s\n", newdelete, mode, name);4075else4076printf("%s %s\n", newdelete, name);4077}40784079static voidshow_mode_change(struct patch *p,int show_name)4080{4081if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4082if(show_name)4083printf(" mode change%06o =>%06o%s\n",4084 p->old_mode, p->new_mode, p->new_name);4085else4086printf(" mode change%06o =>%06o\n",4087 p->old_mode, p->new_mode);4088}4089}40904091static voidshow_rename_copy(struct patch *p)4092{4093const char*renamecopy = p->is_rename ?"rename":"copy";4094const char*old, *new;40954096/* Find common prefix */4097 old = p->old_name;4098new= p->new_name;4099while(1) {4100const char*slash_old, *slash_new;4101 slash_old =strchr(old,'/');4102 slash_new =strchr(new,'/');4103if(!slash_old ||4104!slash_new ||4105 slash_old - old != slash_new -new||4106memcmp(old,new, slash_new -new))4107break;4108 old = slash_old +1;4109new= slash_new +1;4110}4111/* p->old_name thru old is the common prefix, and old and new4112 * through the end of names are renames4113 */4114if(old != p->old_name)4115printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4116(int)(old - p->old_name), p->old_name,4117 old,new, p->score);4118else4119printf("%s %s=>%s(%d%%)\n", renamecopy,4120 p->old_name, p->new_name, p->score);4121show_mode_change(p,0);4122}41234124static voidsummary_patch_list(struct patch *patch)4125{4126struct patch *p;41274128for(p = patch; p; p = p->next) {4129if(p->is_new)4130show_file_mode_name("create", p->new_mode, p->new_name);4131else if(p->is_delete)4132show_file_mode_name("delete", p->old_mode, p->old_name);4133else{4134if(p->is_rename || p->is_copy)4135show_rename_copy(p);4136else{4137if(p->score) {4138printf(" rewrite%s(%d%%)\n",4139 p->new_name, p->score);4140show_mode_change(p,0);4141}4142else4143show_mode_change(p,1);4144}4145}4146}4147}41484149static voidpatch_stats(struct apply_state *state,struct patch *patch)4150{4151int lines = patch->lines_added + patch->lines_deleted;41524153if(lines > state->max_change)4154 state->max_change = lines;4155if(patch->old_name) {4156int len =quote_c_style(patch->old_name, NULL, NULL,0);4157if(!len)4158 len =strlen(patch->old_name);4159if(len > state->max_len)4160 state->max_len = len;4161}4162if(patch->new_name) {4163int len =quote_c_style(patch->new_name, NULL, NULL,0);4164if(!len)4165 len =strlen(patch->new_name);4166if(len > state->max_len)4167 state->max_len = len;4168}4169}41704171static voidremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4172{4173if(state->update_index) {4174if(remove_file_from_cache(patch->old_name) <0)4175die(_("unable to remove%sfrom index"), patch->old_name);4176}4177if(!state->cached) {4178if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4179remove_path(patch->old_name);4180}4181}4182}41834184static voidadd_index_file(struct apply_state *state,4185const char*path,4186unsigned mode,4187void*buf,4188unsigned long size)4189{4190struct stat st;4191struct cache_entry *ce;4192int namelen =strlen(path);4193unsigned ce_size =cache_entry_size(namelen);41944195if(!state->update_index)4196return;41974198 ce =xcalloc(1, ce_size);4199memcpy(ce->name, path, namelen);4200 ce->ce_mode =create_ce_mode(mode);4201 ce->ce_flags =create_ce_flags(0);4202 ce->ce_namelen = namelen;4203if(S_ISGITLINK(mode)) {4204const char*s;42054206if(!skip_prefix(buf,"Subproject commit ", &s) ||4207get_sha1_hex(s, ce->sha1))4208die(_("corrupt patch for submodule%s"), path);4209}else{4210if(!state->cached) {4211if(lstat(path, &st) <0)4212die_errno(_("unable to stat newly created file '%s'"),4213 path);4214fill_stat_cache_info(ce, &st);4215}4216if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4217die(_("unable to create backing store for newly created file%s"), path);4218}4219if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4220die(_("unable to add cache entry for%s"), path);4221}42224223static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4224{4225int fd;4226struct strbuf nbuf = STRBUF_INIT;42274228if(S_ISGITLINK(mode)) {4229struct stat st;4230if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4231return0;4232returnmkdir(path,0777);4233}42344235if(has_symlinks &&S_ISLNK(mode))4236/* Although buf:size is counted string, it also is NUL4237 * terminated.4238 */4239returnsymlink(buf, path);42404241 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4242if(fd <0)4243return-1;42444245if(convert_to_working_tree(path, buf, size, &nbuf)) {4246 size = nbuf.len;4247 buf = nbuf.buf;4248}4249write_or_die(fd, buf, size);4250strbuf_release(&nbuf);42514252if(close(fd) <0)4253die_errno(_("closing file '%s'"), path);4254return0;4255}42564257/*4258 * We optimistically assume that the directories exist,4259 * which is true 99% of the time anyway. If they don't,4260 * we create them and try again.4261 */4262static voidcreate_one_file(struct apply_state *state,4263char*path,4264unsigned mode,4265const char*buf,4266unsigned long size)4267{4268if(state->cached)4269return;4270if(!try_create_file(path, mode, buf, size))4271return;42724273if(errno == ENOENT) {4274if(safe_create_leading_directories(path))4275return;4276if(!try_create_file(path, mode, buf, size))4277return;4278}42794280if(errno == EEXIST || errno == EACCES) {4281/* We may be trying to create a file where a directory4282 * used to be.4283 */4284struct stat st;4285if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4286 errno = EEXIST;4287}42884289if(errno == EEXIST) {4290unsigned int nr =getpid();42914292for(;;) {4293char newpath[PATH_MAX];4294mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4295if(!try_create_file(newpath, mode, buf, size)) {4296if(!rename(newpath, path))4297return;4298unlink_or_warn(newpath);4299break;4300}4301if(errno != EEXIST)4302break;4303++nr;4304}4305}4306die_errno(_("unable to write file '%s' mode%o"), path, mode);4307}43084309static voidadd_conflicted_stages_file(struct apply_state *state,4310struct patch *patch)4311{4312int stage, namelen;4313unsigned ce_size, mode;4314struct cache_entry *ce;43154316if(!state->update_index)4317return;4318 namelen =strlen(patch->new_name);4319 ce_size =cache_entry_size(namelen);4320 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);43214322remove_file_from_cache(patch->new_name);4323for(stage =1; stage <4; stage++) {4324if(is_null_oid(&patch->threeway_stage[stage -1]))4325continue;4326 ce =xcalloc(1, ce_size);4327memcpy(ce->name, patch->new_name, namelen);4328 ce->ce_mode =create_ce_mode(mode);4329 ce->ce_flags =create_ce_flags(stage);4330 ce->ce_namelen = namelen;4331hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4332if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4333die(_("unable to add cache entry for%s"), patch->new_name);4334}4335}43364337static voidcreate_file(struct apply_state *state,struct patch *patch)4338{4339char*path = patch->new_name;4340unsigned mode = patch->new_mode;4341unsigned long size = patch->resultsize;4342char*buf = patch->result;43434344if(!mode)4345 mode = S_IFREG |0644;4346create_one_file(state, path, mode, buf, size);43474348if(patch->conflicted_threeway)4349add_conflicted_stages_file(state, patch);4350else4351add_index_file(state, path, mode, buf, size);4352}43534354/* phase zero is to remove, phase one is to create */4355static voidwrite_out_one_result(struct apply_state *state,4356struct patch *patch,4357int phase)4358{4359if(patch->is_delete >0) {4360if(phase ==0)4361remove_file(state, patch,1);4362return;4363}4364if(patch->is_new >0|| patch->is_copy) {4365if(phase ==1)4366create_file(state, patch);4367return;4368}4369/*4370 * Rename or modification boils down to the same4371 * thing: remove the old, write the new4372 */4373if(phase ==0)4374remove_file(state, patch, patch->is_rename);4375if(phase ==1)4376create_file(state, patch);4377}43784379static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4380{4381FILE*rej;4382char namebuf[PATH_MAX];4383struct fragment *frag;4384int cnt =0;4385struct strbuf sb = STRBUF_INIT;43864387for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4388if(!frag->rejected)4389continue;4390 cnt++;4391}43924393if(!cnt) {4394if(state->apply_verbosely)4395say_patch_name(stderr,4396_("Applied patch%scleanly."), patch);4397return0;4398}43994400/* This should not happen, because a removal patch that leaves4401 * contents are marked "rejected" at the patch level.4402 */4403if(!patch->new_name)4404die(_("internal error"));44054406/* Say this even without --verbose */4407strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4408"Applying patch %%swith%drejects...",4409 cnt),4410 cnt);4411say_patch_name(stderr, sb.buf, patch);4412strbuf_release(&sb);44134414 cnt =strlen(patch->new_name);4415if(ARRAY_SIZE(namebuf) <= cnt +5) {4416 cnt =ARRAY_SIZE(namebuf) -5;4417warning(_("truncating .rej filename to %.*s.rej"),4418 cnt -1, patch->new_name);4419}4420memcpy(namebuf, patch->new_name, cnt);4421memcpy(namebuf + cnt,".rej",5);44224423 rej =fopen(namebuf,"w");4424if(!rej)4425returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));44264427/* Normal git tools never deal with .rej, so do not pretend4428 * this is a git patch by saying --git or giving extended4429 * headers. While at it, maybe please "kompare" that wants4430 * the trailing TAB and some garbage at the end of line ;-).4431 */4432fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4433 patch->new_name, patch->new_name);4434for(cnt =1, frag = patch->fragments;4435 frag;4436 cnt++, frag = frag->next) {4437if(!frag->rejected) {4438fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4439continue;4440}4441fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4442fprintf(rej,"%.*s", frag->size, frag->patch);4443if(frag->patch[frag->size-1] !='\n')4444fputc('\n', rej);4445}4446fclose(rej);4447return-1;4448}44494450static intwrite_out_results(struct apply_state *state,struct patch *list)4451{4452int phase;4453int errs =0;4454struct patch *l;4455struct string_list cpath = STRING_LIST_INIT_DUP;44564457for(phase =0; phase <2; phase++) {4458 l = list;4459while(l) {4460if(l->rejected)4461 errs =1;4462else{4463write_out_one_result(state, l, phase);4464if(phase ==1) {4465if(write_out_one_reject(state, l))4466 errs =1;4467if(l->conflicted_threeway) {4468string_list_append(&cpath, l->new_name);4469 errs =1;4470}4471}4472}4473 l = l->next;4474}4475}44764477if(cpath.nr) {4478struct string_list_item *item;44794480string_list_sort(&cpath);4481for_each_string_list_item(item, &cpath)4482fprintf(stderr,"U%s\n", item->string);4483string_list_clear(&cpath,0);44844485rerere(0);4486}44874488return errs;4489}44904491static struct lock_file lock_file;44924493#define INACCURATE_EOF (1<<0)4494#define RECOUNT (1<<1)44954496static intapply_patch(struct apply_state *state,4497int fd,4498const char*filename,4499int options)4500{4501size_t offset;4502struct strbuf buf = STRBUF_INIT;/* owns the patch text */4503struct patch *list = NULL, **listp = &list;4504int skipped_patch =0;45054506 state->patch_input_file = filename;4507read_patch_file(&buf, fd);4508 offset =0;4509while(offset < buf.len) {4510struct patch *patch;4511int nr;45124513 patch =xcalloc(1,sizeof(*patch));4514 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4515 patch->recount = !!(options & RECOUNT);4516 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4517if(nr <0) {4518free_patch(patch);4519break;4520}4521if(state->apply_in_reverse)4522reverse_patches(patch);4523if(use_patch(state, patch)) {4524patch_stats(state, patch);4525*listp = patch;4526 listp = &patch->next;4527}4528else{4529if(state->apply_verbosely)4530say_patch_name(stderr,_("Skipped patch '%s'."), patch);4531free_patch(patch);4532 skipped_patch++;4533}4534 offset += nr;4535}45364537if(!list && !skipped_patch)4538die(_("unrecognized input"));45394540if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4541 state->apply =0;45424543 state->update_index = state->check_index && state->apply;4544if(state->update_index && newfd <0)4545 newfd =hold_locked_index(&lock_file,1);45464547if(state->check_index) {4548if(read_cache() <0)4549die(_("unable to read index file"));4550}45514552if((state->check || state->apply) &&4553check_patch_list(state, list) <0&&4554!state->apply_with_reject)4555exit(1);45564557if(state->apply &&write_out_results(state, list)) {4558if(state->apply_with_reject)4559exit(1);4560/* with --3way, we still need to write the index out */4561return1;4562}45634564if(state->fake_ancestor)4565build_fake_ancestor(list, state->fake_ancestor);45664567if(state->diffstat)4568stat_patch_list(state, list);45694570if(state->numstat)4571numstat_patch_list(state, list);45724573if(state->summary)4574summary_patch_list(list);45754576free_patch_list(list);4577strbuf_release(&buf);4578string_list_clear(&state->fn_table,0);4579return0;4580}45814582static voidgit_apply_config(void)4583{4584git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4585git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4586git_config(git_default_config, NULL);4587}45884589static intoption_parse_exclude(const struct option *opt,4590const char*arg,int unset)4591{4592struct apply_state *state = opt->value;4593add_name_limit(state, arg,1);4594return0;4595}45964597static intoption_parse_include(const struct option *opt,4598const char*arg,int unset)4599{4600struct apply_state *state = opt->value;4601add_name_limit(state, arg,0);4602 state->has_include =1;4603return0;4604}46054606static intoption_parse_p(const struct option *opt,4607const char*arg,4608int unset)4609{4610struct apply_state *state = opt->value;4611 state->p_value =atoi(arg);4612 state->p_value_known =1;4613return0;4614}46154616static intoption_parse_space_change(const struct option *opt,4617const char*arg,int unset)4618{4619struct apply_state *state = opt->value;4620if(unset)4621 state->ws_ignore_action = ignore_ws_none;4622else4623 state->ws_ignore_action = ignore_ws_change;4624return0;4625}46264627static intoption_parse_whitespace(const struct option *opt,4628const char*arg,int unset)4629{4630struct apply_state *state = opt->value;4631 state->whitespace_option = arg;4632parse_whitespace_option(state, arg);4633return0;4634}46354636static intoption_parse_directory(const struct option *opt,4637const char*arg,int unset)4638{4639struct apply_state *state = opt->value;4640strbuf_reset(&state->root);4641strbuf_addstr(&state->root, arg);4642strbuf_complete(&state->root,'/');4643return0;4644}46454646static voidinit_apply_state(struct apply_state *state,const char*prefix)4647{4648memset(state,0,sizeof(*state));4649 state->prefix = prefix;4650 state->prefix_length = state->prefix ?strlen(state->prefix) :0;4651 state->apply =1;4652 state->line_termination ='\n';4653 state->p_value =1;4654 state->p_context = UINT_MAX;4655 state->squelch_whitespace_errors =5;4656 state->ws_error_action = warn_on_ws_error;4657 state->ws_ignore_action = ignore_ws_none;4658 state->linenr =1;4659strbuf_init(&state->root,0);46604661git_apply_config();4662if(apply_default_whitespace)4663parse_whitespace_option(state, apply_default_whitespace);4664if(apply_default_ignorewhitespace)4665parse_ignorewhitespace_option(state, apply_default_ignorewhitespace);4666}46674668static voidclear_apply_state(struct apply_state *state)4669{4670string_list_clear(&state->limit_by_name,0);4671strbuf_release(&state->root);46724673/* &state->fn_table is cleared at the end of apply_patch() */4674}46754676intcmd_apply(int argc,const char**argv,const char*prefix)4677{4678int i;4679int errs =0;4680int is_not_gitdir = !startup_info->have_repository;4681int force_apply =0;4682int options =0;4683int read_stdin =1;4684struct apply_state state;46854686struct option builtin_apply_options[] = {4687{ OPTION_CALLBACK,0,"exclude", &state,N_("path"),4688N_("don't apply changes matching the given path"),46890, option_parse_exclude },4690{ OPTION_CALLBACK,0,"include", &state,N_("path"),4691N_("apply changes matching the given path"),46920, option_parse_include },4693{ OPTION_CALLBACK,'p', NULL, &state,N_("num"),4694N_("remove <num> leading slashes from traditional diff paths"),46950, option_parse_p },4696OPT_BOOL(0,"no-add", &state.no_add,4697N_("ignore additions made by the patch")),4698OPT_BOOL(0,"stat", &state.diffstat,4699N_("instead of applying the patch, output diffstat for the input")),4700OPT_NOOP_NOARG(0,"allow-binary-replacement"),4701OPT_NOOP_NOARG(0,"binary"),4702OPT_BOOL(0,"numstat", &state.numstat,4703N_("show number of added and deleted lines in decimal notation")),4704OPT_BOOL(0,"summary", &state.summary,4705N_("instead of applying the patch, output a summary for the input")),4706OPT_BOOL(0,"check", &state.check,4707N_("instead of applying the patch, see if the patch is applicable")),4708OPT_BOOL(0,"index", &state.check_index,4709N_("make sure the patch is applicable to the current index")),4710OPT_BOOL(0,"cached", &state.cached,4711N_("apply a patch without touching the working tree")),4712OPT_BOOL(0,"unsafe-paths", &state.unsafe_paths,4713N_("accept a patch that touches outside the working area")),4714OPT_BOOL(0,"apply", &force_apply,4715N_("also apply the patch (use with --stat/--summary/--check)")),4716OPT_BOOL('3',"3way", &state.threeway,4717N_("attempt three-way merge if a patch does not apply")),4718OPT_FILENAME(0,"build-fake-ancestor", &state.fake_ancestor,4719N_("build a temporary index based on embedded index information")),4720/* Think twice before adding "--nul" synonym to this */4721OPT_SET_INT('z', NULL, &state.line_termination,4722N_("paths are separated with NUL character"),'\0'),4723OPT_INTEGER('C', NULL, &state.p_context,4724N_("ensure at least <n> lines of context match")),4725{ OPTION_CALLBACK,0,"whitespace", &state,N_("action"),4726N_("detect new or modified lines that have whitespace errors"),47270, option_parse_whitespace },4728{ OPTION_CALLBACK,0,"ignore-space-change", &state, NULL,4729N_("ignore changes in whitespace when finding context"),4730 PARSE_OPT_NOARG, option_parse_space_change },4731{ OPTION_CALLBACK,0,"ignore-whitespace", &state, NULL,4732N_("ignore changes in whitespace when finding context"),4733 PARSE_OPT_NOARG, option_parse_space_change },4734OPT_BOOL('R',"reverse", &state.apply_in_reverse,4735N_("apply the patch in reverse")),4736OPT_BOOL(0,"unidiff-zero", &state.unidiff_zero,4737N_("don't expect at least one line of context")),4738OPT_BOOL(0,"reject", &state.apply_with_reject,4739N_("leave the rejected hunks in corresponding *.rej files")),4740OPT_BOOL(0,"allow-overlap", &state.allow_overlap,4741N_("allow overlapping hunks")),4742OPT__VERBOSE(&state.apply_verbosely,N_("be verbose")),4743OPT_BIT(0,"inaccurate-eof", &options,4744N_("tolerate incorrectly detected missing new-line at the end of file"),4745 INACCURATE_EOF),4746OPT_BIT(0,"recount", &options,4747N_("do not trust the line counts in the hunk headers"),4748 RECOUNT),4749{ OPTION_CALLBACK,0,"directory", &state,N_("root"),4750N_("prepend <root> to all filenames"),47510, option_parse_directory },4752OPT_END()4753};47544755init_apply_state(&state, prefix);47564757 argc =parse_options(argc, argv, state.prefix, builtin_apply_options,4758 apply_usage,0);47594760if(state.apply_with_reject && state.threeway)4761die("--reject and --3way cannot be used together.");4762if(state.cached && state.threeway)4763die("--cached and --3way cannot be used together.");4764if(state.threeway) {4765if(is_not_gitdir)4766die(_("--3way outside a repository"));4767 state.check_index =1;4768}4769if(state.apply_with_reject)4770 state.apply = state.apply_verbosely =1;4771if(!force_apply && (state.diffstat || state.numstat || state.summary || state.check || state.fake_ancestor))4772 state.apply =0;4773if(state.check_index && is_not_gitdir)4774die(_("--index outside a repository"));4775if(state.cached) {4776if(is_not_gitdir)4777die(_("--cached outside a repository"));4778 state.check_index =1;4779}4780if(state.check_index)4781 state.unsafe_paths =0;47824783for(i =0; i < argc; i++) {4784const char*arg = argv[i];4785int fd;47864787if(!strcmp(arg,"-")) {4788 errs |=apply_patch(&state,0,"<stdin>", options);4789 read_stdin =0;4790continue;4791}else if(0< state.prefix_length)4792 arg =prefix_filename(state.prefix,4793 state.prefix_length,4794 arg);47954796 fd =open(arg, O_RDONLY);4797if(fd <0)4798die_errno(_("can't open patch '%s'"), arg);4799 read_stdin =0;4800set_default_whitespace_mode(&state);4801 errs |=apply_patch(&state, fd, arg, options);4802close(fd);4803}4804set_default_whitespace_mode(&state);4805if(read_stdin)4806 errs |=apply_patch(&state,0,"<stdin>", options);4807if(state.whitespace_error) {4808if(state.squelch_whitespace_errors &&4809 state.squelch_whitespace_errors < state.whitespace_error) {4810int squelched =4811 state.whitespace_error - state.squelch_whitespace_errors;4812warning(Q_("squelched%dwhitespace error",4813"squelched%dwhitespace errors",4814 squelched),4815 squelched);4816}4817if(state.ws_error_action == die_on_ws_error)4818die(Q_("%dline adds whitespace errors.",4819"%dlines add whitespace errors.",4820 state.whitespace_error),4821 state.whitespace_error);4822if(state.applied_after_fixing_ws && state.apply)4823warning("%dline%sapplied after"4824" fixing whitespace errors.",4825 state.applied_after_fixing_ws,4826 state.applied_after_fixing_ws ==1?"":"s");4827else if(state.whitespace_error)4828warning(Q_("%dline adds whitespace errors.",4829"%dlines add whitespace errors.",4830 state.whitespace_error),4831 state.whitespace_error);4832}48334834if(state.update_index) {4835if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK))4836die(_("Unable to write new index file"));4837}48384839clear_apply_state(&state);48404841return!!errs;4842}