1/* 2 * apply.c 3 * 4 * Copyright (C) Linus Torvalds, 2005 5 * 6 * This applies patches on top of some (arbitrary) version of the SCM. 7 * 8 */ 9#include"cache.h" 10#include"lockfile.h" 11#include"cache-tree.h" 12#include"quote.h" 13#include"blob.h" 14#include"delta.h" 15#include"builtin.h" 16#include"string-list.h" 17#include"dir.h" 18#include"diff.h" 19#include"parse-options.h" 20#include"xdiff-interface.h" 21#include"ll-merge.h" 22#include"rerere.h" 23 24struct apply_state { 25const char*prefix; 26int prefix_length; 27 28/* These control what gets looked at and modified */ 29int apply;/* this is not a dry-run */ 30int cached;/* apply to the index only */ 31int check;/* preimage must match working tree, don't actually apply */ 32int check_index;/* preimage must match the indexed version */ 33int update_index;/* check_index && apply */ 34 35/* These control cosmetic aspect of the output */ 36int diffstat;/* just show a diffstat, and don't actually apply */ 37int numstat;/* just show a numeric diffstat, and don't actually apply */ 38int summary;/* just report creation, deletion, etc, and don't actually apply */ 39 40/* These boolean parameters control how the apply is done */ 41int allow_overlap; 42int apply_in_reverse; 43int apply_with_reject; 44int apply_verbosely; 45int no_add; 46int threeway; 47int unidiff_zero; 48int unsafe_paths; 49 50/* Other non boolean parameters */ 51const char*fake_ancestor; 52const char*patch_input_file; 53int line_termination; 54struct strbuf root; 55int p_value; 56int p_value_known; 57unsigned int p_context; 58 59/* Exclude and include path parameters */ 60struct string_list limit_by_name; 61int has_include; 62}; 63 64static int newfd = -1; 65 66static const char*const apply_usage[] = { 67N_("git apply [<options>] [<patch>...]"), 68 NULL 69}; 70 71static enum ws_error_action { 72 nowarn_ws_error, 73 warn_on_ws_error, 74 die_on_ws_error, 75 correct_ws_error 76} ws_error_action = warn_on_ws_error; 77static int whitespace_error; 78static int squelch_whitespace_errors =5; 79static int applied_after_fixing_ws; 80 81static enum ws_ignore { 82 ignore_ws_none, 83 ignore_ws_change 84} ws_ignore_action = ignore_ws_none; 85 86 87static voidparse_whitespace_option(const char*option) 88{ 89if(!option) { 90 ws_error_action = warn_on_ws_error; 91return; 92} 93if(!strcmp(option,"warn")) { 94 ws_error_action = warn_on_ws_error; 95return; 96} 97if(!strcmp(option,"nowarn")) { 98 ws_error_action = nowarn_ws_error; 99return; 100} 101if(!strcmp(option,"error")) { 102 ws_error_action = die_on_ws_error; 103return; 104} 105if(!strcmp(option,"error-all")) { 106 ws_error_action = die_on_ws_error; 107 squelch_whitespace_errors =0; 108return; 109} 110if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 111 ws_error_action = correct_ws_error; 112return; 113} 114die(_("unrecognized whitespace option '%s'"), option); 115} 116 117static voidparse_ignorewhitespace_option(const char*option) 118{ 119if(!option || !strcmp(option,"no") || 120!strcmp(option,"false") || !strcmp(option,"never") || 121!strcmp(option,"none")) { 122 ws_ignore_action = ignore_ws_none; 123return; 124} 125if(!strcmp(option,"change")) { 126 ws_ignore_action = ignore_ws_change; 127return; 128} 129die(_("unrecognized whitespace ignore option '%s'"), option); 130} 131 132static voidset_default_whitespace_mode(struct apply_state *state, 133const char*whitespace_option) 134{ 135if(!whitespace_option && !apply_default_whitespace) 136 ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 137} 138 139/* 140 * For "diff-stat" like behaviour, we keep track of the biggest change 141 * we've seen, and the longest filename. That allows us to do simple 142 * scaling. 143 */ 144static int max_change, max_len; 145 146/* 147 * Various "current state", notably line numbers and what 148 * file (and how) we're patching right now.. The "is_xxxx" 149 * things are flags, where -1 means "don't know yet". 150 */ 151static int state_linenr =1; 152 153/* 154 * This represents one "hunk" from a patch, starting with 155 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 156 * patch text is pointed at by patch, and its byte length 157 * is stored in size. leading and trailing are the number 158 * of context lines. 159 */ 160struct fragment { 161unsigned long leading, trailing; 162unsigned long oldpos, oldlines; 163unsigned long newpos, newlines; 164/* 165 * 'patch' is usually borrowed from buf in apply_patch(), 166 * but some codepaths store an allocated buffer. 167 */ 168const char*patch; 169unsigned free_patch:1, 170 rejected:1; 171int size; 172int linenr; 173struct fragment *next; 174}; 175 176/* 177 * When dealing with a binary patch, we reuse "leading" field 178 * to store the type of the binary hunk, either deflated "delta" 179 * or deflated "literal". 180 */ 181#define binary_patch_method leading 182#define BINARY_DELTA_DEFLATED 1 183#define BINARY_LITERAL_DEFLATED 2 184 185/* 186 * This represents a "patch" to a file, both metainfo changes 187 * such as creation/deletion, filemode and content changes represented 188 * as a series of fragments. 189 */ 190struct patch { 191char*new_name, *old_name, *def_name; 192unsigned int old_mode, new_mode; 193int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 194int rejected; 195unsigned ws_rule; 196int lines_added, lines_deleted; 197int score; 198unsigned int is_toplevel_relative:1; 199unsigned int inaccurate_eof:1; 200unsigned int is_binary:1; 201unsigned int is_copy:1; 202unsigned int is_rename:1; 203unsigned int recount:1; 204unsigned int conflicted_threeway:1; 205unsigned int direct_to_threeway:1; 206struct fragment *fragments; 207char*result; 208size_t resultsize; 209char old_sha1_prefix[41]; 210char new_sha1_prefix[41]; 211struct patch *next; 212 213/* three-way fallback result */ 214struct object_id threeway_stage[3]; 215}; 216 217static voidfree_fragment_list(struct fragment *list) 218{ 219while(list) { 220struct fragment *next = list->next; 221if(list->free_patch) 222free((char*)list->patch); 223free(list); 224 list = next; 225} 226} 227 228static voidfree_patch(struct patch *patch) 229{ 230free_fragment_list(patch->fragments); 231free(patch->def_name); 232free(patch->old_name); 233free(patch->new_name); 234free(patch->result); 235free(patch); 236} 237 238static voidfree_patch_list(struct patch *list) 239{ 240while(list) { 241struct patch *next = list->next; 242free_patch(list); 243 list = next; 244} 245} 246 247/* 248 * A line in a file, len-bytes long (includes the terminating LF, 249 * except for an incomplete line at the end if the file ends with 250 * one), and its contents hashes to 'hash'. 251 */ 252struct line { 253size_t len; 254unsigned hash :24; 255unsigned flag :8; 256#define LINE_COMMON 1 257#define LINE_PATCHED 2 258}; 259 260/* 261 * This represents a "file", which is an array of "lines". 262 */ 263struct image { 264char*buf; 265size_t len; 266size_t nr; 267size_t alloc; 268struct line *line_allocated; 269struct line *line; 270}; 271 272/* 273 * Records filenames that have been touched, in order to handle 274 * the case where more than one patches touch the same file. 275 */ 276 277static struct string_list fn_table; 278 279static uint32_thash_line(const char*cp,size_t len) 280{ 281size_t i; 282uint32_t h; 283for(i =0, h =0; i < len; i++) { 284if(!isspace(cp[i])) { 285 h = h *3+ (cp[i] &0xff); 286} 287} 288return h; 289} 290 291/* 292 * Compare lines s1 of length n1 and s2 of length n2, ignoring 293 * whitespace difference. Returns 1 if they match, 0 otherwise 294 */ 295static intfuzzy_matchlines(const char*s1,size_t n1, 296const char*s2,size_t n2) 297{ 298const char*last1 = s1 + n1 -1; 299const char*last2 = s2 + n2 -1; 300int result =0; 301 302/* ignore line endings */ 303while((*last1 =='\r') || (*last1 =='\n')) 304 last1--; 305while((*last2 =='\r') || (*last2 =='\n')) 306 last2--; 307 308/* skip leading whitespaces, if both begin with whitespace */ 309if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 310while(isspace(*s1) && (s1 <= last1)) 311 s1++; 312while(isspace(*s2) && (s2 <= last2)) 313 s2++; 314} 315/* early return if both lines are empty */ 316if((s1 > last1) && (s2 > last2)) 317return1; 318while(!result) { 319 result = *s1++ - *s2++; 320/* 321 * Skip whitespace inside. We check for whitespace on 322 * both buffers because we don't want "a b" to match 323 * "ab" 324 */ 325if(isspace(*s1) &&isspace(*s2)) { 326while(isspace(*s1) && s1 <= last1) 327 s1++; 328while(isspace(*s2) && s2 <= last2) 329 s2++; 330} 331/* 332 * If we reached the end on one side only, 333 * lines don't match 334 */ 335if( 336((s2 > last2) && (s1 <= last1)) || 337((s1 > last1) && (s2 <= last2))) 338return0; 339if((s1 > last1) && (s2 > last2)) 340break; 341} 342 343return!result; 344} 345 346static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 347{ 348ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 349 img->line_allocated[img->nr].len = len; 350 img->line_allocated[img->nr].hash =hash_line(bol, len); 351 img->line_allocated[img->nr].flag = flag; 352 img->nr++; 353} 354 355/* 356 * "buf" has the file contents to be patched (read from various sources). 357 * attach it to "image" and add line-based index to it. 358 * "image" now owns the "buf". 359 */ 360static voidprepare_image(struct image *image,char*buf,size_t len, 361int prepare_linetable) 362{ 363const char*cp, *ep; 364 365memset(image,0,sizeof(*image)); 366 image->buf = buf; 367 image->len = len; 368 369if(!prepare_linetable) 370return; 371 372 ep = image->buf + image->len; 373 cp = image->buf; 374while(cp < ep) { 375const char*next; 376for(next = cp; next < ep && *next !='\n'; next++) 377; 378if(next < ep) 379 next++; 380add_line_info(image, cp, next - cp,0); 381 cp = next; 382} 383 image->line = image->line_allocated; 384} 385 386static voidclear_image(struct image *image) 387{ 388free(image->buf); 389free(image->line_allocated); 390memset(image,0,sizeof(*image)); 391} 392 393/* fmt must contain _one_ %s and no other substitution */ 394static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 395{ 396struct strbuf sb = STRBUF_INIT; 397 398if(patch->old_name && patch->new_name && 399strcmp(patch->old_name, patch->new_name)) { 400quote_c_style(patch->old_name, &sb, NULL,0); 401strbuf_addstr(&sb," => "); 402quote_c_style(patch->new_name, &sb, NULL,0); 403}else{ 404const char*n = patch->new_name; 405if(!n) 406 n = patch->old_name; 407quote_c_style(n, &sb, NULL,0); 408} 409fprintf(output, fmt, sb.buf); 410fputc('\n', output); 411strbuf_release(&sb); 412} 413 414#define SLOP (16) 415 416static voidread_patch_file(struct strbuf *sb,int fd) 417{ 418if(strbuf_read(sb, fd,0) <0) 419die_errno("git apply: failed to read"); 420 421/* 422 * Make sure that we have some slop in the buffer 423 * so that we can do speculative "memcmp" etc, and 424 * see to it that it is NUL-filled. 425 */ 426strbuf_grow(sb, SLOP); 427memset(sb->buf + sb->len,0, SLOP); 428} 429 430static unsigned longlinelen(const char*buffer,unsigned long size) 431{ 432unsigned long len =0; 433while(size--) { 434 len++; 435if(*buffer++ =='\n') 436break; 437} 438return len; 439} 440 441static intis_dev_null(const char*str) 442{ 443returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 444} 445 446#define TERM_SPACE 1 447#define TERM_TAB 2 448 449static intname_terminate(const char*name,int namelen,int c,int terminate) 450{ 451if(c ==' '&& !(terminate & TERM_SPACE)) 452return0; 453if(c =='\t'&& !(terminate & TERM_TAB)) 454return0; 455 456return1; 457} 458 459/* remove double slashes to make --index work with such filenames */ 460static char*squash_slash(char*name) 461{ 462int i =0, j =0; 463 464if(!name) 465return NULL; 466 467while(name[i]) { 468if((name[j++] = name[i++]) =='/') 469while(name[i] =='/') 470 i++; 471} 472 name[j] ='\0'; 473return name; 474} 475 476static char*find_name_gnu(struct apply_state *state, 477const char*line, 478const char*def, 479int p_value) 480{ 481struct strbuf name = STRBUF_INIT; 482char*cp; 483 484/* 485 * Proposed "new-style" GNU patch/diff format; see 486 * http://marc.info/?l=git&m=112927316408690&w=2 487 */ 488if(unquote_c_style(&name, line, NULL)) { 489strbuf_release(&name); 490return NULL; 491} 492 493for(cp = name.buf; p_value; p_value--) { 494 cp =strchr(cp,'/'); 495if(!cp) { 496strbuf_release(&name); 497return NULL; 498} 499 cp++; 500} 501 502strbuf_remove(&name,0, cp - name.buf); 503if(state->root.len) 504strbuf_insert(&name,0, state->root.buf, state->root.len); 505returnsquash_slash(strbuf_detach(&name, NULL)); 506} 507 508static size_tsane_tz_len(const char*line,size_t len) 509{ 510const char*tz, *p; 511 512if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 513return0; 514 tz = line + len -strlen(" +0500"); 515 516if(tz[1] !='+'&& tz[1] !='-') 517return0; 518 519for(p = tz +2; p != line + len; p++) 520if(!isdigit(*p)) 521return0; 522 523return line + len - tz; 524} 525 526static size_ttz_with_colon_len(const char*line,size_t len) 527{ 528const char*tz, *p; 529 530if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 531return0; 532 tz = line + len -strlen(" +08:00"); 533 534if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 535return0; 536 p = tz +2; 537if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 538!isdigit(*p++) || !isdigit(*p++)) 539return0; 540 541return line + len - tz; 542} 543 544static size_tdate_len(const char*line,size_t len) 545{ 546const char*date, *p; 547 548if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 549return0; 550 p = date = line + len -strlen("72-02-05"); 551 552if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 553!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 554!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 555return0; 556 557if(date - line >=strlen("19") && 558isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 559 date -=strlen("19"); 560 561return line + len - date; 562} 563 564static size_tshort_time_len(const char*line,size_t len) 565{ 566const char*time, *p; 567 568if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 569return0; 570 p = time = line + len -strlen(" 07:01:32"); 571 572/* Permit 1-digit hours? */ 573if(*p++ !=' '|| 574!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 575!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 576!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 577return0; 578 579return line + len - time; 580} 581 582static size_tfractional_time_len(const char*line,size_t len) 583{ 584const char*p; 585size_t n; 586 587/* Expected format: 19:41:17.620000023 */ 588if(!len || !isdigit(line[len -1])) 589return0; 590 p = line + len -1; 591 592/* Fractional seconds. */ 593while(p > line &&isdigit(*p)) 594 p--; 595if(*p !='.') 596return0; 597 598/* Hours, minutes, and whole seconds. */ 599 n =short_time_len(line, p - line); 600if(!n) 601return0; 602 603return line + len - p + n; 604} 605 606static size_ttrailing_spaces_len(const char*line,size_t len) 607{ 608const char*p; 609 610/* Expected format: ' ' x (1 or more) */ 611if(!len || line[len -1] !=' ') 612return0; 613 614 p = line + len; 615while(p != line) { 616 p--; 617if(*p !=' ') 618return line + len - (p +1); 619} 620 621/* All spaces! */ 622return len; 623} 624 625static size_tdiff_timestamp_len(const char*line,size_t len) 626{ 627const char*end = line + len; 628size_t n; 629 630/* 631 * Posix: 2010-07-05 19:41:17 632 * GNU: 2010-07-05 19:41:17.620000023 -0500 633 */ 634 635if(!isdigit(end[-1])) 636return0; 637 638 n =sane_tz_len(line, end - line); 639if(!n) 640 n =tz_with_colon_len(line, end - line); 641 end -= n; 642 643 n =short_time_len(line, end - line); 644if(!n) 645 n =fractional_time_len(line, end - line); 646 end -= n; 647 648 n =date_len(line, end - line); 649if(!n)/* No date. Too bad. */ 650return0; 651 end -= n; 652 653if(end == line)/* No space before date. */ 654return0; 655if(end[-1] =='\t') {/* Success! */ 656 end--; 657return line + len - end; 658} 659if(end[-1] !=' ')/* No space before date. */ 660return0; 661 662/* Whitespace damage. */ 663 end -=trailing_spaces_len(line, end - line); 664return line + len - end; 665} 666 667static char*find_name_common(struct apply_state *state, 668const char*line, 669const char*def, 670int p_value, 671const char*end, 672int terminate) 673{ 674int len; 675const char*start = NULL; 676 677if(p_value ==0) 678 start = line; 679while(line != end) { 680char c = *line; 681 682if(!end &&isspace(c)) { 683if(c =='\n') 684break; 685if(name_terminate(start, line-start, c, terminate)) 686break; 687} 688 line++; 689if(c =='/'&& !--p_value) 690 start = line; 691} 692if(!start) 693returnsquash_slash(xstrdup_or_null(def)); 694 len = line - start; 695if(!len) 696returnsquash_slash(xstrdup_or_null(def)); 697 698/* 699 * Generally we prefer the shorter name, especially 700 * if the other one is just a variation of that with 701 * something else tacked on to the end (ie "file.orig" 702 * or "file~"). 703 */ 704if(def) { 705int deflen =strlen(def); 706if(deflen < len && !strncmp(start, def, deflen)) 707returnsquash_slash(xstrdup(def)); 708} 709 710if(state->root.len) { 711char*ret =xstrfmt("%s%.*s", state->root.buf, len, start); 712returnsquash_slash(ret); 713} 714 715returnsquash_slash(xmemdupz(start, len)); 716} 717 718static char*find_name(struct apply_state *state, 719const char*line, 720char*def, 721int p_value, 722int terminate) 723{ 724if(*line =='"') { 725char*name =find_name_gnu(state, line, def, p_value); 726if(name) 727return name; 728} 729 730returnfind_name_common(state, line, def, p_value, NULL, terminate); 731} 732 733static char*find_name_traditional(struct apply_state *state, 734const char*line, 735char*def, 736int p_value) 737{ 738size_t len; 739size_t date_len; 740 741if(*line =='"') { 742char*name =find_name_gnu(state, line, def, p_value); 743if(name) 744return name; 745} 746 747 len =strchrnul(line,'\n') - line; 748 date_len =diff_timestamp_len(line, len); 749if(!date_len) 750returnfind_name_common(state, line, def, p_value, NULL, TERM_TAB); 751 len -= date_len; 752 753returnfind_name_common(state, line, def, p_value, line + len,0); 754} 755 756static intcount_slashes(const char*cp) 757{ 758int cnt =0; 759char ch; 760 761while((ch = *cp++)) 762if(ch =='/') 763 cnt++; 764return cnt; 765} 766 767/* 768 * Given the string after "--- " or "+++ ", guess the appropriate 769 * p_value for the given patch. 770 */ 771static intguess_p_value(struct apply_state *state,const char*nameline) 772{ 773char*name, *cp; 774int val = -1; 775 776if(is_dev_null(nameline)) 777return-1; 778 name =find_name_traditional(state, nameline, NULL,0); 779if(!name) 780return-1; 781 cp =strchr(name,'/'); 782if(!cp) 783 val =0; 784else if(state->prefix) { 785/* 786 * Does it begin with "a/$our-prefix" and such? Then this is 787 * very likely to apply to our directory. 788 */ 789if(!strncmp(name, state->prefix, state->prefix_length)) 790 val =count_slashes(state->prefix); 791else{ 792 cp++; 793if(!strncmp(cp, state->prefix, state->prefix_length)) 794 val =count_slashes(state->prefix) +1; 795} 796} 797free(name); 798return val; 799} 800 801/* 802 * Does the ---/+++ line have the POSIX timestamp after the last HT? 803 * GNU diff puts epoch there to signal a creation/deletion event. Is 804 * this such a timestamp? 805 */ 806static inthas_epoch_timestamp(const char*nameline) 807{ 808/* 809 * We are only interested in epoch timestamp; any non-zero 810 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 811 * For the same reason, the date must be either 1969-12-31 or 812 * 1970-01-01, and the seconds part must be "00". 813 */ 814const char stamp_regexp[] = 815"^(1969-12-31|1970-01-01)" 816" " 817"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 818" " 819"([-+][0-2][0-9]:?[0-5][0-9])\n"; 820const char*timestamp = NULL, *cp, *colon; 821static regex_t *stamp; 822 regmatch_t m[10]; 823int zoneoffset; 824int hourminute; 825int status; 826 827for(cp = nameline; *cp !='\n'; cp++) { 828if(*cp =='\t') 829 timestamp = cp +1; 830} 831if(!timestamp) 832return0; 833if(!stamp) { 834 stamp =xmalloc(sizeof(*stamp)); 835if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 836warning(_("Cannot prepare timestamp regexp%s"), 837 stamp_regexp); 838return0; 839} 840} 841 842 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 843if(status) { 844if(status != REG_NOMATCH) 845warning(_("regexec returned%dfor input:%s"), 846 status, timestamp); 847return0; 848} 849 850 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 851if(*colon ==':') 852 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 853else 854 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 855if(timestamp[m[3].rm_so] =='-') 856 zoneoffset = -zoneoffset; 857 858/* 859 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 860 * (west of GMT) or 1970-01-01 (east of GMT) 861 */ 862if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 863(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 864return0; 865 866 hourminute = (strtol(timestamp +11, NULL,10) *60+ 867strtol(timestamp +14, NULL,10) - 868 zoneoffset); 869 870return((zoneoffset <0&& hourminute ==1440) || 871(0<= zoneoffset && !hourminute)); 872} 873 874/* 875 * Get the name etc info from the ---/+++ lines of a traditional patch header 876 * 877 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 878 * files, we can happily check the index for a match, but for creating a 879 * new file we should try to match whatever "patch" does. I have no idea. 880 */ 881static voidparse_traditional_patch(struct apply_state *state, 882const char*first, 883const char*second, 884struct patch *patch) 885{ 886char*name; 887 888 first +=4;/* skip "--- " */ 889 second +=4;/* skip "+++ " */ 890if(!state->p_value_known) { 891int p, q; 892 p =guess_p_value(state, first); 893 q =guess_p_value(state, second); 894if(p <0) p = q; 895if(0<= p && p == q) { 896 state->p_value = p; 897 state->p_value_known =1; 898} 899} 900if(is_dev_null(first)) { 901 patch->is_new =1; 902 patch->is_delete =0; 903 name =find_name_traditional(state, second, NULL, state->p_value); 904 patch->new_name = name; 905}else if(is_dev_null(second)) { 906 patch->is_new =0; 907 patch->is_delete =1; 908 name =find_name_traditional(state, first, NULL, state->p_value); 909 patch->old_name = name; 910}else{ 911char*first_name; 912 first_name =find_name_traditional(state, first, NULL, state->p_value); 913 name =find_name_traditional(state, second, first_name, state->p_value); 914free(first_name); 915if(has_epoch_timestamp(first)) { 916 patch->is_new =1; 917 patch->is_delete =0; 918 patch->new_name = name; 919}else if(has_epoch_timestamp(second)) { 920 patch->is_new =0; 921 patch->is_delete =1; 922 patch->old_name = name; 923}else{ 924 patch->old_name = name; 925 patch->new_name =xstrdup_or_null(name); 926} 927} 928if(!name) 929die(_("unable to find filename in patch at line%d"), state_linenr); 930} 931 932static intgitdiff_hdrend(struct apply_state *state, 933const char*line, 934struct patch *patch) 935{ 936return-1; 937} 938 939/* 940 * We're anal about diff header consistency, to make 941 * sure that we don't end up having strange ambiguous 942 * patches floating around. 943 * 944 * As a result, gitdiff_{old|new}name() will check 945 * their names against any previous information, just 946 * to make sure.. 947 */ 948#define DIFF_OLD_NAME 0 949#define DIFF_NEW_NAME 1 950 951static voidgitdiff_verify_name(struct apply_state *state, 952const char*line, 953int isnull, 954char**name, 955int side) 956{ 957if(!*name && !isnull) { 958*name =find_name(state, line, NULL, state->p_value, TERM_TAB); 959return; 960} 961 962if(*name) { 963int len =strlen(*name); 964char*another; 965if(isnull) 966die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 967*name, state_linenr); 968 another =find_name(state, line, NULL, state->p_value, TERM_TAB); 969if(!another ||memcmp(another, *name, len +1)) 970die((side == DIFF_NEW_NAME) ? 971_("git apply: bad git-diff - inconsistent new filename on line%d") : 972_("git apply: bad git-diff - inconsistent old filename on line%d"), state_linenr); 973free(another); 974}else{ 975/* expect "/dev/null" */ 976if(memcmp("/dev/null", line,9) || line[9] !='\n') 977die(_("git apply: bad git-diff - expected /dev/null on line%d"), state_linenr); 978} 979} 980 981static intgitdiff_oldname(struct apply_state *state, 982const char*line, 983struct patch *patch) 984{ 985gitdiff_verify_name(state, line, 986 patch->is_new, &patch->old_name, 987 DIFF_OLD_NAME); 988return0; 989} 990 991static intgitdiff_newname(struct apply_state *state, 992const char*line, 993struct patch *patch) 994{ 995gitdiff_verify_name(state, line, 996 patch->is_delete, &patch->new_name, 997 DIFF_NEW_NAME); 998return0; 999}10001001static intgitdiff_oldmode(struct apply_state *state,1002const char*line,1003struct patch *patch)1004{1005 patch->old_mode =strtoul(line, NULL,8);1006return0;1007}10081009static intgitdiff_newmode(struct apply_state *state,1010const char*line,1011struct patch *patch)1012{1013 patch->new_mode =strtoul(line, NULL,8);1014return0;1015}10161017static intgitdiff_delete(struct apply_state *state,1018const char*line,1019struct patch *patch)1020{1021 patch->is_delete =1;1022free(patch->old_name);1023 patch->old_name =xstrdup_or_null(patch->def_name);1024returngitdiff_oldmode(state, line, patch);1025}10261027static intgitdiff_newfile(struct apply_state *state,1028const char*line,1029struct patch *patch)1030{1031 patch->is_new =1;1032free(patch->new_name);1033 patch->new_name =xstrdup_or_null(patch->def_name);1034returngitdiff_newmode(state, line, patch);1035}10361037static intgitdiff_copysrc(struct apply_state *state,1038const char*line,1039struct patch *patch)1040{1041 patch->is_copy =1;1042free(patch->old_name);1043 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1044return0;1045}10461047static intgitdiff_copydst(struct apply_state *state,1048const char*line,1049struct patch *patch)1050{1051 patch->is_copy =1;1052free(patch->new_name);1053 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1054return0;1055}10561057static intgitdiff_renamesrc(struct apply_state *state,1058const char*line,1059struct patch *patch)1060{1061 patch->is_rename =1;1062free(patch->old_name);1063 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1064return0;1065}10661067static intgitdiff_renamedst(struct apply_state *state,1068const char*line,1069struct patch *patch)1070{1071 patch->is_rename =1;1072free(patch->new_name);1073 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1074return0;1075}10761077static intgitdiff_similarity(struct apply_state *state,1078const char*line,1079struct patch *patch)1080{1081unsigned long val =strtoul(line, NULL,10);1082if(val <=100)1083 patch->score = val;1084return0;1085}10861087static intgitdiff_dissimilarity(struct apply_state *state,1088const char*line,1089struct patch *patch)1090{1091unsigned long val =strtoul(line, NULL,10);1092if(val <=100)1093 patch->score = val;1094return0;1095}10961097static intgitdiff_index(struct apply_state *state,1098const char*line,1099struct patch *patch)1100{1101/*1102 * index line is N hexadecimal, "..", N hexadecimal,1103 * and optional space with octal mode.1104 */1105const char*ptr, *eol;1106int len;11071108 ptr =strchr(line,'.');1109if(!ptr || ptr[1] !='.'||40< ptr - line)1110return0;1111 len = ptr - line;1112memcpy(patch->old_sha1_prefix, line, len);1113 patch->old_sha1_prefix[len] =0;11141115 line = ptr +2;1116 ptr =strchr(line,' ');1117 eol =strchrnul(line,'\n');11181119if(!ptr || eol < ptr)1120 ptr = eol;1121 len = ptr - line;11221123if(40< len)1124return0;1125memcpy(patch->new_sha1_prefix, line, len);1126 patch->new_sha1_prefix[len] =0;1127if(*ptr ==' ')1128 patch->old_mode =strtoul(ptr+1, NULL,8);1129return0;1130}11311132/*1133 * This is normal for a diff that doesn't change anything: we'll fall through1134 * into the next diff. Tell the parser to break out.1135 */1136static intgitdiff_unrecognized(struct apply_state *state,1137const char*line,1138struct patch *patch)1139{1140return-1;1141}11421143/*1144 * Skip p_value leading components from "line"; as we do not accept1145 * absolute paths, return NULL in that case.1146 */1147static const char*skip_tree_prefix(struct apply_state *state,1148const char*line,1149int llen)1150{1151int nslash;1152int i;11531154if(!state->p_value)1155return(llen && line[0] =='/') ? NULL : line;11561157 nslash = state->p_value;1158for(i =0; i < llen; i++) {1159int ch = line[i];1160if(ch =='/'&& --nslash <=0)1161return(i ==0) ? NULL : &line[i +1];1162}1163return NULL;1164}11651166/*1167 * This is to extract the same name that appears on "diff --git"1168 * line. We do not find and return anything if it is a rename1169 * patch, and it is OK because we will find the name elsewhere.1170 * We need to reliably find name only when it is mode-change only,1171 * creation or deletion of an empty file. In any of these cases,1172 * both sides are the same name under a/ and b/ respectively.1173 */1174static char*git_header_name(struct apply_state *state,1175const char*line,1176int llen)1177{1178const char*name;1179const char*second = NULL;1180size_t len, line_len;11811182 line +=strlen("diff --git ");1183 llen -=strlen("diff --git ");11841185if(*line =='"') {1186const char*cp;1187struct strbuf first = STRBUF_INIT;1188struct strbuf sp = STRBUF_INIT;11891190if(unquote_c_style(&first, line, &second))1191goto free_and_fail1;11921193/* strip the a/b prefix including trailing slash */1194 cp =skip_tree_prefix(state, first.buf, first.len);1195if(!cp)1196goto free_and_fail1;1197strbuf_remove(&first,0, cp - first.buf);11981199/*1200 * second points at one past closing dq of name.1201 * find the second name.1202 */1203while((second < line + llen) &&isspace(*second))1204 second++;12051206if(line + llen <= second)1207goto free_and_fail1;1208if(*second =='"') {1209if(unquote_c_style(&sp, second, NULL))1210goto free_and_fail1;1211 cp =skip_tree_prefix(state, sp.buf, sp.len);1212if(!cp)1213goto free_and_fail1;1214/* They must match, otherwise ignore */1215if(strcmp(cp, first.buf))1216goto free_and_fail1;1217strbuf_release(&sp);1218returnstrbuf_detach(&first, NULL);1219}12201221/* unquoted second */1222 cp =skip_tree_prefix(state, second, line + llen - second);1223if(!cp)1224goto free_and_fail1;1225if(line + llen - cp != first.len ||1226memcmp(first.buf, cp, first.len))1227goto free_and_fail1;1228returnstrbuf_detach(&first, NULL);12291230 free_and_fail1:1231strbuf_release(&first);1232strbuf_release(&sp);1233return NULL;1234}12351236/* unquoted first name */1237 name =skip_tree_prefix(state, line, llen);1238if(!name)1239return NULL;12401241/*1242 * since the first name is unquoted, a dq if exists must be1243 * the beginning of the second name.1244 */1245for(second = name; second < line + llen; second++) {1246if(*second =='"') {1247struct strbuf sp = STRBUF_INIT;1248const char*np;12491250if(unquote_c_style(&sp, second, NULL))1251goto free_and_fail2;12521253 np =skip_tree_prefix(state, sp.buf, sp.len);1254if(!np)1255goto free_and_fail2;12561257 len = sp.buf + sp.len - np;1258if(len < second - name &&1259!strncmp(np, name, len) &&1260isspace(name[len])) {1261/* Good */1262strbuf_remove(&sp,0, np - sp.buf);1263returnstrbuf_detach(&sp, NULL);1264}12651266 free_and_fail2:1267strbuf_release(&sp);1268return NULL;1269}1270}12711272/*1273 * Accept a name only if it shows up twice, exactly the same1274 * form.1275 */1276 second =strchr(name,'\n');1277if(!second)1278return NULL;1279 line_len = second - name;1280for(len =0; ; len++) {1281switch(name[len]) {1282default:1283continue;1284case'\n':1285return NULL;1286case'\t':case' ':1287/*1288 * Is this the separator between the preimage1289 * and the postimage pathname? Again, we are1290 * only interested in the case where there is1291 * no rename, as this is only to set def_name1292 * and a rename patch has the names elsewhere1293 * in an unambiguous form.1294 */1295if(!name[len +1])1296return NULL;/* no postimage name */1297 second =skip_tree_prefix(state, name + len +1,1298 line_len - (len +1));1299if(!second)1300return NULL;1301/*1302 * Does len bytes starting at "name" and "second"1303 * (that are separated by one HT or SP we just1304 * found) exactly match?1305 */1306if(second[len] =='\n'&& !strncmp(name, second, len))1307returnxmemdupz(name, len);1308}1309}1310}13111312/* Verify that we recognize the lines following a git header */1313static intparse_git_header(struct apply_state *state,1314const char*line,1315int len,1316unsigned int size,1317struct patch *patch)1318{1319unsigned long offset;13201321/* A git diff has explicit new/delete information, so we don't guess */1322 patch->is_new =0;1323 patch->is_delete =0;13241325/*1326 * Some things may not have the old name in the1327 * rest of the headers anywhere (pure mode changes,1328 * or removing or adding empty files), so we get1329 * the default name from the header.1330 */1331 patch->def_name =git_header_name(state, line, len);1332if(patch->def_name && state->root.len) {1333char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1334free(patch->def_name);1335 patch->def_name = s;1336}13371338 line += len;1339 size -= len;1340 state_linenr++;1341for(offset = len ; size >0; offset += len, size -= len, line += len, state_linenr++) {1342static const struct opentry {1343const char*str;1344int(*fn)(struct apply_state *,const char*,struct patch *);1345} optable[] = {1346{"@@ -", gitdiff_hdrend },1347{"--- ", gitdiff_oldname },1348{"+++ ", gitdiff_newname },1349{"old mode ", gitdiff_oldmode },1350{"new mode ", gitdiff_newmode },1351{"deleted file mode ", gitdiff_delete },1352{"new file mode ", gitdiff_newfile },1353{"copy from ", gitdiff_copysrc },1354{"copy to ", gitdiff_copydst },1355{"rename old ", gitdiff_renamesrc },1356{"rename new ", gitdiff_renamedst },1357{"rename from ", gitdiff_renamesrc },1358{"rename to ", gitdiff_renamedst },1359{"similarity index ", gitdiff_similarity },1360{"dissimilarity index ", gitdiff_dissimilarity },1361{"index ", gitdiff_index },1362{"", gitdiff_unrecognized },1363};1364int i;13651366 len =linelen(line, size);1367if(!len || line[len-1] !='\n')1368break;1369for(i =0; i <ARRAY_SIZE(optable); i++) {1370const struct opentry *p = optable + i;1371int oplen =strlen(p->str);1372if(len < oplen ||memcmp(p->str, line, oplen))1373continue;1374if(p->fn(state, line + oplen, patch) <0)1375return offset;1376break;1377}1378}13791380return offset;1381}13821383static intparse_num(const char*line,unsigned long*p)1384{1385char*ptr;13861387if(!isdigit(*line))1388return0;1389*p =strtoul(line, &ptr,10);1390return ptr - line;1391}13921393static intparse_range(const char*line,int len,int offset,const char*expect,1394unsigned long*p1,unsigned long*p2)1395{1396int digits, ex;13971398if(offset <0|| offset >= len)1399return-1;1400 line += offset;1401 len -= offset;14021403 digits =parse_num(line, p1);1404if(!digits)1405return-1;14061407 offset += digits;1408 line += digits;1409 len -= digits;14101411*p2 =1;1412if(*line ==',') {1413 digits =parse_num(line+1, p2);1414if(!digits)1415return-1;14161417 offset += digits+1;1418 line += digits+1;1419 len -= digits+1;1420}14211422 ex =strlen(expect);1423if(ex > len)1424return-1;1425if(memcmp(line, expect, ex))1426return-1;14271428return offset + ex;1429}14301431static voidrecount_diff(const char*line,int size,struct fragment *fragment)1432{1433int oldlines =0, newlines =0, ret =0;14341435if(size <1) {1436warning("recount: ignore empty hunk");1437return;1438}14391440for(;;) {1441int len =linelen(line, size);1442 size -= len;1443 line += len;14441445if(size <1)1446break;14471448switch(*line) {1449case' ':case'\n':1450 newlines++;1451/* fall through */1452case'-':1453 oldlines++;1454continue;1455case'+':1456 newlines++;1457continue;1458case'\\':1459continue;1460case'@':1461 ret = size <3|| !starts_with(line,"@@ ");1462break;1463case'd':1464 ret = size <5|| !starts_with(line,"diff ");1465break;1466default:1467 ret = -1;1468break;1469}1470if(ret) {1471warning(_("recount: unexpected line: %.*s"),1472(int)linelen(line, size), line);1473return;1474}1475break;1476}1477 fragment->oldlines = oldlines;1478 fragment->newlines = newlines;1479}14801481/*1482 * Parse a unified diff fragment header of the1483 * form "@@ -a,b +c,d @@"1484 */1485static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1486{1487int offset;14881489if(!len || line[len-1] !='\n')1490return-1;14911492/* Figure out the number of lines in a fragment */1493 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1494 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14951496return offset;1497}14981499static intfind_header(struct apply_state *state,1500const char*line,1501unsigned long size,1502int*hdrsize,1503struct patch *patch)1504{1505unsigned long offset, len;15061507 patch->is_toplevel_relative =0;1508 patch->is_rename = patch->is_copy =0;1509 patch->is_new = patch->is_delete = -1;1510 patch->old_mode = patch->new_mode =0;1511 patch->old_name = patch->new_name = NULL;1512for(offset =0; size >0; offset += len, size -= len, line += len, state_linenr++) {1513unsigned long nextlen;15141515 len =linelen(line, size);1516if(!len)1517break;15181519/* Testing this early allows us to take a few shortcuts.. */1520if(len <6)1521continue;15221523/*1524 * Make sure we don't find any unconnected patch fragments.1525 * That's a sign that we didn't find a header, and that a1526 * patch has become corrupted/broken up.1527 */1528if(!memcmp("@@ -", line,4)) {1529struct fragment dummy;1530if(parse_fragment_header(line, len, &dummy) <0)1531continue;1532die(_("patch fragment without header at line%d: %.*s"),1533 state_linenr, (int)len-1, line);1534}15351536if(size < len +6)1537break;15381539/*1540 * Git patch? It might not have a real patch, just a rename1541 * or mode change, so we handle that specially1542 */1543if(!memcmp("diff --git ", line,11)) {1544int git_hdr_len =parse_git_header(state, line, len, size, patch);1545if(git_hdr_len <= len)1546continue;1547if(!patch->old_name && !patch->new_name) {1548if(!patch->def_name)1549die(Q_("git diff header lacks filename information when removing "1550"%dleading pathname component (line%d)",1551"git diff header lacks filename information when removing "1552"%dleading pathname components (line%d)",1553 state->p_value),1554 state->p_value, state_linenr);1555 patch->old_name =xstrdup(patch->def_name);1556 patch->new_name =xstrdup(patch->def_name);1557}1558if(!patch->is_delete && !patch->new_name)1559die("git diff header lacks filename information "1560"(line%d)", state_linenr);1561 patch->is_toplevel_relative =1;1562*hdrsize = git_hdr_len;1563return offset;1564}15651566/* --- followed by +++ ? */1567if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1568continue;15691570/*1571 * We only accept unified patches, so we want it to1572 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1573 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1574 */1575 nextlen =linelen(line + len, size - len);1576if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1577continue;15781579/* Ok, we'll consider it a patch */1580parse_traditional_patch(state, line, line+len, patch);1581*hdrsize = len + nextlen;1582 state_linenr +=2;1583return offset;1584}1585return-1;1586}15871588static voidrecord_ws_error(struct apply_state *state,1589unsigned result,1590const char*line,1591int len,1592int linenr)1593{1594char*err;15951596if(!result)1597return;15981599 whitespace_error++;1600if(squelch_whitespace_errors &&1601 squelch_whitespace_errors < whitespace_error)1602return;16031604 err =whitespace_error_string(result);1605fprintf(stderr,"%s:%d:%s.\n%.*s\n",1606 state->patch_input_file, linenr, err, len, line);1607free(err);1608}16091610static voidcheck_whitespace(struct apply_state *state,1611const char*line,1612int len,1613unsigned ws_rule)1614{1615unsigned result =ws_check(line +1, len -1, ws_rule);16161617record_ws_error(state, result, line +1, len -2, state_linenr);1618}16191620/*1621 * Parse a unified diff. Note that this really needs to parse each1622 * fragment separately, since the only way to know the difference1623 * between a "---" that is part of a patch, and a "---" that starts1624 * the next patch is to look at the line counts..1625 */1626static intparse_fragment(struct apply_state *state,1627const char*line,1628unsigned long size,1629struct patch *patch,1630struct fragment *fragment)1631{1632int added, deleted;1633int len =linelen(line, size), offset;1634unsigned long oldlines, newlines;1635unsigned long leading, trailing;16361637 offset =parse_fragment_header(line, len, fragment);1638if(offset <0)1639return-1;1640if(offset >0&& patch->recount)1641recount_diff(line + offset, size - offset, fragment);1642 oldlines = fragment->oldlines;1643 newlines = fragment->newlines;1644 leading =0;1645 trailing =0;16461647/* Parse the thing.. */1648 line += len;1649 size -= len;1650 state_linenr++;1651 added = deleted =0;1652for(offset = len;16530< size;1654 offset += len, size -= len, line += len, state_linenr++) {1655if(!oldlines && !newlines)1656break;1657 len =linelen(line, size);1658if(!len || line[len-1] !='\n')1659return-1;1660switch(*line) {1661default:1662return-1;1663case'\n':/* newer GNU diff, an empty context line */1664case' ':1665 oldlines--;1666 newlines--;1667if(!deleted && !added)1668 leading++;1669 trailing++;1670if(!state->apply_in_reverse &&1671 ws_error_action == correct_ws_error)1672check_whitespace(state, line, len, patch->ws_rule);1673break;1674case'-':1675if(state->apply_in_reverse &&1676 ws_error_action != nowarn_ws_error)1677check_whitespace(state, line, len, patch->ws_rule);1678 deleted++;1679 oldlines--;1680 trailing =0;1681break;1682case'+':1683if(!state->apply_in_reverse &&1684 ws_error_action != nowarn_ws_error)1685check_whitespace(state, line, len, patch->ws_rule);1686 added++;1687 newlines--;1688 trailing =0;1689break;16901691/*1692 * We allow "\ No newline at end of file". Depending1693 * on locale settings when the patch was produced we1694 * don't know what this line looks like. The only1695 * thing we do know is that it begins with "\ ".1696 * Checking for 12 is just for sanity check -- any1697 * l10n of "\ No newline..." is at least that long.1698 */1699case'\\':1700if(len <12||memcmp(line,"\\",2))1701return-1;1702break;1703}1704}1705if(oldlines || newlines)1706return-1;1707if(!deleted && !added)1708return-1;17091710 fragment->leading = leading;1711 fragment->trailing = trailing;17121713/*1714 * If a fragment ends with an incomplete line, we failed to include1715 * it in the above loop because we hit oldlines == newlines == 01716 * before seeing it.1717 */1718if(12< size && !memcmp(line,"\\",2))1719 offset +=linelen(line, size);17201721 patch->lines_added += added;1722 patch->lines_deleted += deleted;17231724if(0< patch->is_new && oldlines)1725returnerror(_("new file depends on old contents"));1726if(0< patch->is_delete && newlines)1727returnerror(_("deleted file still has contents"));1728return offset;1729}17301731/*1732 * We have seen "diff --git a/... b/..." header (or a traditional patch1733 * header). Read hunks that belong to this patch into fragments and hang1734 * them to the given patch structure.1735 *1736 * The (fragment->patch, fragment->size) pair points into the memory given1737 * by the caller, not a copy, when we return.1738 */1739static intparse_single_patch(struct apply_state *state,1740const char*line,1741unsigned long size,1742struct patch *patch)1743{1744unsigned long offset =0;1745unsigned long oldlines =0, newlines =0, context =0;1746struct fragment **fragp = &patch->fragments;17471748while(size >4&& !memcmp(line,"@@ -",4)) {1749struct fragment *fragment;1750int len;17511752 fragment =xcalloc(1,sizeof(*fragment));1753 fragment->linenr = state_linenr;1754 len =parse_fragment(state, line, size, patch, fragment);1755if(len <=0)1756die(_("corrupt patch at line%d"), state_linenr);1757 fragment->patch = line;1758 fragment->size = len;1759 oldlines += fragment->oldlines;1760 newlines += fragment->newlines;1761 context += fragment->leading + fragment->trailing;17621763*fragp = fragment;1764 fragp = &fragment->next;17651766 offset += len;1767 line += len;1768 size -= len;1769}17701771/*1772 * If something was removed (i.e. we have old-lines) it cannot1773 * be creation, and if something was added it cannot be1774 * deletion. However, the reverse is not true; --unified=01775 * patches that only add are not necessarily creation even1776 * though they do not have any old lines, and ones that only1777 * delete are not necessarily deletion.1778 *1779 * Unfortunately, a real creation/deletion patch do _not_ have1780 * any context line by definition, so we cannot safely tell it1781 * apart with --unified=0 insanity. At least if the patch has1782 * more than one hunk it is not creation or deletion.1783 */1784if(patch->is_new <0&&1785(oldlines || (patch->fragments && patch->fragments->next)))1786 patch->is_new =0;1787if(patch->is_delete <0&&1788(newlines || (patch->fragments && patch->fragments->next)))1789 patch->is_delete =0;17901791if(0< patch->is_new && oldlines)1792die(_("new file%sdepends on old contents"), patch->new_name);1793if(0< patch->is_delete && newlines)1794die(_("deleted file%sstill has contents"), patch->old_name);1795if(!patch->is_delete && !newlines && context)1796fprintf_ln(stderr,1797_("** warning: "1798"file%sbecomes empty but is not deleted"),1799 patch->new_name);18001801return offset;1802}18031804staticinlineintmetadata_changes(struct patch *patch)1805{1806return patch->is_rename >0||1807 patch->is_copy >0||1808 patch->is_new >0||1809 patch->is_delete ||1810(patch->old_mode && patch->new_mode &&1811 patch->old_mode != patch->new_mode);1812}18131814static char*inflate_it(const void*data,unsigned long size,1815unsigned long inflated_size)1816{1817 git_zstream stream;1818void*out;1819int st;18201821memset(&stream,0,sizeof(stream));18221823 stream.next_in = (unsigned char*)data;1824 stream.avail_in = size;1825 stream.next_out = out =xmalloc(inflated_size);1826 stream.avail_out = inflated_size;1827git_inflate_init(&stream);1828 st =git_inflate(&stream, Z_FINISH);1829git_inflate_end(&stream);1830if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1831free(out);1832return NULL;1833}1834return out;1835}18361837/*1838 * Read a binary hunk and return a new fragment; fragment->patch1839 * points at an allocated memory that the caller must free, so1840 * it is marked as "->free_patch = 1".1841 */1842static struct fragment *parse_binary_hunk(char**buf_p,1843unsigned long*sz_p,1844int*status_p,1845int*used_p)1846{1847/*1848 * Expect a line that begins with binary patch method ("literal"1849 * or "delta"), followed by the length of data before deflating.1850 * a sequence of 'length-byte' followed by base-85 encoded data1851 * should follow, terminated by a newline.1852 *1853 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1854 * and we would limit the patch line to 66 characters,1855 * so one line can fit up to 13 groups that would decode1856 * to 52 bytes max. The length byte 'A'-'Z' corresponds1857 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1858 */1859int llen, used;1860unsigned long size = *sz_p;1861char*buffer = *buf_p;1862int patch_method;1863unsigned long origlen;1864char*data = NULL;1865int hunk_size =0;1866struct fragment *frag;18671868 llen =linelen(buffer, size);1869 used = llen;18701871*status_p =0;18721873if(starts_with(buffer,"delta ")) {1874 patch_method = BINARY_DELTA_DEFLATED;1875 origlen =strtoul(buffer +6, NULL,10);1876}1877else if(starts_with(buffer,"literal ")) {1878 patch_method = BINARY_LITERAL_DEFLATED;1879 origlen =strtoul(buffer +8, NULL,10);1880}1881else1882return NULL;18831884 state_linenr++;1885 buffer += llen;1886while(1) {1887int byte_length, max_byte_length, newsize;1888 llen =linelen(buffer, size);1889 used += llen;1890 state_linenr++;1891if(llen ==1) {1892/* consume the blank line */1893 buffer++;1894 size--;1895break;1896}1897/*1898 * Minimum line is "A00000\n" which is 7-byte long,1899 * and the line length must be multiple of 5 plus 2.1900 */1901if((llen <7) || (llen-2) %5)1902goto corrupt;1903 max_byte_length = (llen -2) /5*4;1904 byte_length = *buffer;1905if('A'<= byte_length && byte_length <='Z')1906 byte_length = byte_length -'A'+1;1907else if('a'<= byte_length && byte_length <='z')1908 byte_length = byte_length -'a'+27;1909else1910goto corrupt;1911/* if the input length was not multiple of 4, we would1912 * have filler at the end but the filler should never1913 * exceed 3 bytes1914 */1915if(max_byte_length < byte_length ||1916 byte_length <= max_byte_length -4)1917goto corrupt;1918 newsize = hunk_size + byte_length;1919 data =xrealloc(data, newsize);1920if(decode_85(data + hunk_size, buffer +1, byte_length))1921goto corrupt;1922 hunk_size = newsize;1923 buffer += llen;1924 size -= llen;1925}19261927 frag =xcalloc(1,sizeof(*frag));1928 frag->patch =inflate_it(data, hunk_size, origlen);1929 frag->free_patch =1;1930if(!frag->patch)1931goto corrupt;1932free(data);1933 frag->size = origlen;1934*buf_p = buffer;1935*sz_p = size;1936*used_p = used;1937 frag->binary_patch_method = patch_method;1938return frag;19391940 corrupt:1941free(data);1942*status_p = -1;1943error(_("corrupt binary patch at line%d: %.*s"),1944 state_linenr-1, llen-1, buffer);1945return NULL;1946}19471948/*1949 * Returns:1950 * -1 in case of error,1951 * the length of the parsed binary patch otherwise1952 */1953static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1954{1955/*1956 * We have read "GIT binary patch\n"; what follows is a line1957 * that says the patch method (currently, either "literal" or1958 * "delta") and the length of data before deflating; a1959 * sequence of 'length-byte' followed by base-85 encoded data1960 * follows.1961 *1962 * When a binary patch is reversible, there is another binary1963 * hunk in the same format, starting with patch method (either1964 * "literal" or "delta") with the length of data, and a sequence1965 * of length-byte + base-85 encoded data, terminated with another1966 * empty line. This data, when applied to the postimage, produces1967 * the preimage.1968 */1969struct fragment *forward;1970struct fragment *reverse;1971int status;1972int used, used_1;19731974 forward =parse_binary_hunk(&buffer, &size, &status, &used);1975if(!forward && !status)1976/* there has to be one hunk (forward hunk) */1977returnerror(_("unrecognized binary patch at line%d"), state_linenr-1);1978if(status)1979/* otherwise we already gave an error message */1980return status;19811982 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1983if(reverse)1984 used += used_1;1985else if(status) {1986/*1987 * Not having reverse hunk is not an error, but having1988 * a corrupt reverse hunk is.1989 */1990free((void*) forward->patch);1991free(forward);1992return status;1993}1994 forward->next = reverse;1995 patch->fragments = forward;1996 patch->is_binary =1;1997return used;1998}19992000static voidprefix_one(struct apply_state *state,char**name)2001{2002char*old_name = *name;2003if(!old_name)2004return;2005*name =xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));2006free(old_name);2007}20082009static voidprefix_patch(struct apply_state *state,struct patch *p)2010{2011if(!state->prefix || p->is_toplevel_relative)2012return;2013prefix_one(state, &p->new_name);2014prefix_one(state, &p->old_name);2015}20162017/*2018 * include/exclude2019 */20202021static voidadd_name_limit(struct apply_state *state,2022const char*name,2023int exclude)2024{2025struct string_list_item *it;20262027 it =string_list_append(&state->limit_by_name, name);2028 it->util = exclude ? NULL : (void*)1;2029}20302031static intuse_patch(struct apply_state *state,struct patch *p)2032{2033const char*pathname = p->new_name ? p->new_name : p->old_name;2034int i;20352036/* Paths outside are not touched regardless of "--include" */2037if(0< state->prefix_length) {2038int pathlen =strlen(pathname);2039if(pathlen <= state->prefix_length ||2040memcmp(state->prefix, pathname, state->prefix_length))2041return0;2042}20432044/* See if it matches any of exclude/include rule */2045for(i =0; i < state->limit_by_name.nr; i++) {2046struct string_list_item *it = &state->limit_by_name.items[i];2047if(!wildmatch(it->string, pathname,0, NULL))2048return(it->util != NULL);2049}20502051/*2052 * If we had any include, a path that does not match any rule is2053 * not used. Otherwise, we saw bunch of exclude rules (or none)2054 * and such a path is used.2055 */2056return!state->has_include;2057}205820592060/*2061 * Read the patch text in "buffer" that extends for "size" bytes; stop2062 * reading after seeing a single patch (i.e. changes to a single file).2063 * Create fragments (i.e. patch hunks) and hang them to the given patch.2064 * Return the number of bytes consumed, so that the caller can call us2065 * again for the next patch.2066 */2067static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2068{2069int hdrsize, patchsize;2070int offset =find_header(state, buffer, size, &hdrsize, patch);20712072if(offset <0)2073return offset;20742075prefix_patch(state, patch);20762077if(!use_patch(state, patch))2078 patch->ws_rule =0;2079else2080 patch->ws_rule =whitespace_rule(patch->new_name2081? patch->new_name2082: patch->old_name);20832084 patchsize =parse_single_patch(state,2085 buffer + offset + hdrsize,2086 size - offset - hdrsize,2087 patch);20882089if(!patchsize) {2090static const char git_binary[] ="GIT binary patch\n";2091int hd = hdrsize + offset;2092unsigned long llen =linelen(buffer + hd, size - hd);20932094if(llen ==sizeof(git_binary) -1&&2095!memcmp(git_binary, buffer + hd, llen)) {2096int used;2097 state_linenr++;2098 used =parse_binary(buffer + hd + llen,2099 size - hd - llen, patch);2100if(used <0)2101return-1;2102if(used)2103 patchsize = used + llen;2104else2105 patchsize =0;2106}2107else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2108static const char*binhdr[] = {2109"Binary files ",2110"Files ",2111 NULL,2112};2113int i;2114for(i =0; binhdr[i]; i++) {2115int len =strlen(binhdr[i]);2116if(len < size - hd &&2117!memcmp(binhdr[i], buffer + hd, len)) {2118 state_linenr++;2119 patch->is_binary =1;2120 patchsize = llen;2121break;2122}2123}2124}21252126/* Empty patch cannot be applied if it is a text patch2127 * without metadata change. A binary patch appears2128 * empty to us here.2129 */2130if((state->apply || state->check) &&2131(!patch->is_binary && !metadata_changes(patch)))2132die(_("patch with only garbage at line%d"), state_linenr);2133}21342135return offset + hdrsize + patchsize;2136}21372138#define swap(a,b) myswap((a),(b),sizeof(a))21392140#define myswap(a, b, size) do { \2141 unsigned char mytmp[size]; \2142 memcpy(mytmp, &a, size); \2143 memcpy(&a, &b, size); \2144 memcpy(&b, mytmp, size); \2145} while (0)21462147static voidreverse_patches(struct patch *p)2148{2149for(; p; p = p->next) {2150struct fragment *frag = p->fragments;21512152swap(p->new_name, p->old_name);2153swap(p->new_mode, p->old_mode);2154swap(p->is_new, p->is_delete);2155swap(p->lines_added, p->lines_deleted);2156swap(p->old_sha1_prefix, p->new_sha1_prefix);21572158for(; frag; frag = frag->next) {2159swap(frag->newpos, frag->oldpos);2160swap(frag->newlines, frag->oldlines);2161}2162}2163}21642165static const char pluses[] =2166"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2167static const char minuses[]=2168"----------------------------------------------------------------------";21692170static voidshow_stats(struct patch *patch)2171{2172struct strbuf qname = STRBUF_INIT;2173char*cp = patch->new_name ? patch->new_name : patch->old_name;2174int max, add, del;21752176quote_c_style(cp, &qname, NULL,0);21772178/*2179 * "scale" the filename2180 */2181 max = max_len;2182if(max >50)2183 max =50;21842185if(qname.len > max) {2186 cp =strchr(qname.buf + qname.len +3- max,'/');2187if(!cp)2188 cp = qname.buf + qname.len +3- max;2189strbuf_splice(&qname,0, cp - qname.buf,"...",3);2190}21912192if(patch->is_binary) {2193printf(" %-*s | Bin\n", max, qname.buf);2194strbuf_release(&qname);2195return;2196}21972198printf(" %-*s |", max, qname.buf);2199strbuf_release(&qname);22002201/*2202 * scale the add/delete2203 */2204 max = max + max_change >70?70- max : max_change;2205 add = patch->lines_added;2206 del = patch->lines_deleted;22072208if(max_change >0) {2209int total = ((add + del) * max + max_change /2) / max_change;2210 add = (add * max + max_change /2) / max_change;2211 del = total - add;2212}2213printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2214 add, pluses, del, minuses);2215}22162217static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2218{2219switch(st->st_mode & S_IFMT) {2220case S_IFLNK:2221if(strbuf_readlink(buf, path, st->st_size) <0)2222returnerror(_("unable to read symlink%s"), path);2223return0;2224case S_IFREG:2225if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2226returnerror(_("unable to open or read%s"), path);2227convert_to_git(path, buf->buf, buf->len, buf,0);2228return0;2229default:2230return-1;2231}2232}22332234/*2235 * Update the preimage, and the common lines in postimage,2236 * from buffer buf of length len. If postlen is 0 the postimage2237 * is updated in place, otherwise it's updated on a new buffer2238 * of length postlen2239 */22402241static voidupdate_pre_post_images(struct image *preimage,2242struct image *postimage,2243char*buf,2244size_t len,size_t postlen)2245{2246int i, ctx, reduced;2247char*new, *old, *fixed;2248struct image fixed_preimage;22492250/*2251 * Update the preimage with whitespace fixes. Note that we2252 * are not losing preimage->buf -- apply_one_fragment() will2253 * free "oldlines".2254 */2255prepare_image(&fixed_preimage, buf, len,1);2256assert(postlen2257? fixed_preimage.nr == preimage->nr2258: fixed_preimage.nr <= preimage->nr);2259for(i =0; i < fixed_preimage.nr; i++)2260 fixed_preimage.line[i].flag = preimage->line[i].flag;2261free(preimage->line_allocated);2262*preimage = fixed_preimage;22632264/*2265 * Adjust the common context lines in postimage. This can be2266 * done in-place when we are shrinking it with whitespace2267 * fixing, but needs a new buffer when ignoring whitespace or2268 * expanding leading tabs to spaces.2269 *2270 * We trust the caller to tell us if the update can be done2271 * in place (postlen==0) or not.2272 */2273 old = postimage->buf;2274if(postlen)2275new= postimage->buf =xmalloc(postlen);2276else2277new= old;2278 fixed = preimage->buf;22792280for(i = reduced = ctx =0; i < postimage->nr; i++) {2281size_t l_len = postimage->line[i].len;2282if(!(postimage->line[i].flag & LINE_COMMON)) {2283/* an added line -- no counterparts in preimage */2284memmove(new, old, l_len);2285 old += l_len;2286new+= l_len;2287continue;2288}22892290/* a common context -- skip it in the original postimage */2291 old += l_len;22922293/* and find the corresponding one in the fixed preimage */2294while(ctx < preimage->nr &&2295!(preimage->line[ctx].flag & LINE_COMMON)) {2296 fixed += preimage->line[ctx].len;2297 ctx++;2298}22992300/*2301 * preimage is expected to run out, if the caller2302 * fixed addition of trailing blank lines.2303 */2304if(preimage->nr <= ctx) {2305 reduced++;2306continue;2307}23082309/* and copy it in, while fixing the line length */2310 l_len = preimage->line[ctx].len;2311memcpy(new, fixed, l_len);2312new+= l_len;2313 fixed += l_len;2314 postimage->line[i].len = l_len;2315 ctx++;2316}23172318if(postlen2319? postlen <new- postimage->buf2320: postimage->len <new- postimage->buf)2321die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2322(int)postlen, (int) postimage->len, (int)(new- postimage->buf));23232324/* Fix the length of the whole thing */2325 postimage->len =new- postimage->buf;2326 postimage->nr -= reduced;2327}23282329static intline_by_line_fuzzy_match(struct image *img,2330struct image *preimage,2331struct image *postimage,2332unsigned longtry,2333int try_lno,2334int preimage_limit)2335{2336int i;2337size_t imgoff =0;2338size_t preoff =0;2339size_t postlen = postimage->len;2340size_t extra_chars;2341char*buf;2342char*preimage_eof;2343char*preimage_end;2344struct strbuf fixed;2345char*fixed_buf;2346size_t fixed_len;23472348for(i =0; i < preimage_limit; i++) {2349size_t prelen = preimage->line[i].len;2350size_t imglen = img->line[try_lno+i].len;23512352if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2353 preimage->buf + preoff, prelen))2354return0;2355if(preimage->line[i].flag & LINE_COMMON)2356 postlen += imglen - prelen;2357 imgoff += imglen;2358 preoff += prelen;2359}23602361/*2362 * Ok, the preimage matches with whitespace fuzz.2363 *2364 * imgoff now holds the true length of the target that2365 * matches the preimage before the end of the file.2366 *2367 * Count the number of characters in the preimage that fall2368 * beyond the end of the file and make sure that all of them2369 * are whitespace characters. (This can only happen if2370 * we are removing blank lines at the end of the file.)2371 */2372 buf = preimage_eof = preimage->buf + preoff;2373for( ; i < preimage->nr; i++)2374 preoff += preimage->line[i].len;2375 preimage_end = preimage->buf + preoff;2376for( ; buf < preimage_end; buf++)2377if(!isspace(*buf))2378return0;23792380/*2381 * Update the preimage and the common postimage context2382 * lines to use the same whitespace as the target.2383 * If whitespace is missing in the target (i.e.2384 * if the preimage extends beyond the end of the file),2385 * use the whitespace from the preimage.2386 */2387 extra_chars = preimage_end - preimage_eof;2388strbuf_init(&fixed, imgoff + extra_chars);2389strbuf_add(&fixed, img->buf +try, imgoff);2390strbuf_add(&fixed, preimage_eof, extra_chars);2391 fixed_buf =strbuf_detach(&fixed, &fixed_len);2392update_pre_post_images(preimage, postimage,2393 fixed_buf, fixed_len, postlen);2394return1;2395}23962397static intmatch_fragment(struct image *img,2398struct image *preimage,2399struct image *postimage,2400unsigned longtry,2401int try_lno,2402unsigned ws_rule,2403int match_beginning,int match_end)2404{2405int i;2406char*fixed_buf, *buf, *orig, *target;2407struct strbuf fixed;2408size_t fixed_len, postlen;2409int preimage_limit;24102411if(preimage->nr + try_lno <= img->nr) {2412/*2413 * The hunk falls within the boundaries of img.2414 */2415 preimage_limit = preimage->nr;2416if(match_end && (preimage->nr + try_lno != img->nr))2417return0;2418}else if(ws_error_action == correct_ws_error &&2419(ws_rule & WS_BLANK_AT_EOF)) {2420/*2421 * This hunk extends beyond the end of img, and we are2422 * removing blank lines at the end of the file. This2423 * many lines from the beginning of the preimage must2424 * match with img, and the remainder of the preimage2425 * must be blank.2426 */2427 preimage_limit = img->nr - try_lno;2428}else{2429/*2430 * The hunk extends beyond the end of the img and2431 * we are not removing blanks at the end, so we2432 * should reject the hunk at this position.2433 */2434return0;2435}24362437if(match_beginning && try_lno)2438return0;24392440/* Quick hash check */2441for(i =0; i < preimage_limit; i++)2442if((img->line[try_lno + i].flag & LINE_PATCHED) ||2443(preimage->line[i].hash != img->line[try_lno + i].hash))2444return0;24452446if(preimage_limit == preimage->nr) {2447/*2448 * Do we have an exact match? If we were told to match2449 * at the end, size must be exactly at try+fragsize,2450 * otherwise try+fragsize must be still within the preimage,2451 * and either case, the old piece should match the preimage2452 * exactly.2453 */2454if((match_end2455? (try+ preimage->len == img->len)2456: (try+ preimage->len <= img->len)) &&2457!memcmp(img->buf +try, preimage->buf, preimage->len))2458return1;2459}else{2460/*2461 * The preimage extends beyond the end of img, so2462 * there cannot be an exact match.2463 *2464 * There must be one non-blank context line that match2465 * a line before the end of img.2466 */2467char*buf_end;24682469 buf = preimage->buf;2470 buf_end = buf;2471for(i =0; i < preimage_limit; i++)2472 buf_end += preimage->line[i].len;24732474for( ; buf < buf_end; buf++)2475if(!isspace(*buf))2476break;2477if(buf == buf_end)2478return0;2479}24802481/*2482 * No exact match. If we are ignoring whitespace, run a line-by-line2483 * fuzzy matching. We collect all the line length information because2484 * we need it to adjust whitespace if we match.2485 */2486if(ws_ignore_action == ignore_ws_change)2487returnline_by_line_fuzzy_match(img, preimage, postimage,2488try, try_lno, preimage_limit);24892490if(ws_error_action != correct_ws_error)2491return0;24922493/*2494 * The hunk does not apply byte-by-byte, but the hash says2495 * it might with whitespace fuzz. We weren't asked to2496 * ignore whitespace, we were asked to correct whitespace2497 * errors, so let's try matching after whitespace correction.2498 *2499 * While checking the preimage against the target, whitespace2500 * errors in both fixed, we count how large the corresponding2501 * postimage needs to be. The postimage prepared by2502 * apply_one_fragment() has whitespace errors fixed on added2503 * lines already, but the common lines were propagated as-is,2504 * which may become longer when their whitespace errors are2505 * fixed.2506 */25072508/* First count added lines in postimage */2509 postlen =0;2510for(i =0; i < postimage->nr; i++) {2511if(!(postimage->line[i].flag & LINE_COMMON))2512 postlen += postimage->line[i].len;2513}25142515/*2516 * The preimage may extend beyond the end of the file,2517 * but in this loop we will only handle the part of the2518 * preimage that falls within the file.2519 */2520strbuf_init(&fixed, preimage->len +1);2521 orig = preimage->buf;2522 target = img->buf +try;2523for(i =0; i < preimage_limit; i++) {2524size_t oldlen = preimage->line[i].len;2525size_t tgtlen = img->line[try_lno + i].len;2526size_t fixstart = fixed.len;2527struct strbuf tgtfix;2528int match;25292530/* Try fixing the line in the preimage */2531ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25322533/* Try fixing the line in the target */2534strbuf_init(&tgtfix, tgtlen);2535ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);25362537/*2538 * If they match, either the preimage was based on2539 * a version before our tree fixed whitespace breakage,2540 * or we are lacking a whitespace-fix patch the tree2541 * the preimage was based on already had (i.e. target2542 * has whitespace breakage, the preimage doesn't).2543 * In either case, we are fixing the whitespace breakages2544 * so we might as well take the fix together with their2545 * real change.2546 */2547 match = (tgtfix.len == fixed.len - fixstart &&2548!memcmp(tgtfix.buf, fixed.buf + fixstart,2549 fixed.len - fixstart));25502551/* Add the length if this is common with the postimage */2552if(preimage->line[i].flag & LINE_COMMON)2553 postlen += tgtfix.len;25542555strbuf_release(&tgtfix);2556if(!match)2557goto unmatch_exit;25582559 orig += oldlen;2560 target += tgtlen;2561}256225632564/*2565 * Now handle the lines in the preimage that falls beyond the2566 * end of the file (if any). They will only match if they are2567 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2568 * false).2569 */2570for( ; i < preimage->nr; i++) {2571size_t fixstart = fixed.len;/* start of the fixed preimage */2572size_t oldlen = preimage->line[i].len;2573int j;25742575/* Try fixing the line in the preimage */2576ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25772578for(j = fixstart; j < fixed.len; j++)2579if(!isspace(fixed.buf[j]))2580goto unmatch_exit;25812582 orig += oldlen;2583}25842585/*2586 * Yes, the preimage is based on an older version that still2587 * has whitespace breakages unfixed, and fixing them makes the2588 * hunk match. Update the context lines in the postimage.2589 */2590 fixed_buf =strbuf_detach(&fixed, &fixed_len);2591if(postlen < postimage->len)2592 postlen =0;2593update_pre_post_images(preimage, postimage,2594 fixed_buf, fixed_len, postlen);2595return1;25962597 unmatch_exit:2598strbuf_release(&fixed);2599return0;2600}26012602static intfind_pos(struct image *img,2603struct image *preimage,2604struct image *postimage,2605int line,2606unsigned ws_rule,2607int match_beginning,int match_end)2608{2609int i;2610unsigned long backwards, forwards,try;2611int backwards_lno, forwards_lno, try_lno;26122613/*2614 * If match_beginning or match_end is specified, there is no2615 * point starting from a wrong line that will never match and2616 * wander around and wait for a match at the specified end.2617 */2618if(match_beginning)2619 line =0;2620else if(match_end)2621 line = img->nr - preimage->nr;26222623/*2624 * Because the comparison is unsigned, the following test2625 * will also take care of a negative line number that can2626 * result when match_end and preimage is larger than the target.2627 */2628if((size_t) line > img->nr)2629 line = img->nr;26302631try=0;2632for(i =0; i < line; i++)2633try+= img->line[i].len;26342635/*2636 * There's probably some smart way to do this, but I'll leave2637 * that to the smart and beautiful people. I'm simple and stupid.2638 */2639 backwards =try;2640 backwards_lno = line;2641 forwards =try;2642 forwards_lno = line;2643 try_lno = line;26442645for(i =0; ; i++) {2646if(match_fragment(img, preimage, postimage,2647try, try_lno, ws_rule,2648 match_beginning, match_end))2649return try_lno;26502651 again:2652if(backwards_lno ==0&& forwards_lno == img->nr)2653break;26542655if(i &1) {2656if(backwards_lno ==0) {2657 i++;2658goto again;2659}2660 backwards_lno--;2661 backwards -= img->line[backwards_lno].len;2662try= backwards;2663 try_lno = backwards_lno;2664}else{2665if(forwards_lno == img->nr) {2666 i++;2667goto again;2668}2669 forwards += img->line[forwards_lno].len;2670 forwards_lno++;2671try= forwards;2672 try_lno = forwards_lno;2673}26742675}2676return-1;2677}26782679static voidremove_first_line(struct image *img)2680{2681 img->buf += img->line[0].len;2682 img->len -= img->line[0].len;2683 img->line++;2684 img->nr--;2685}26862687static voidremove_last_line(struct image *img)2688{2689 img->len -= img->line[--img->nr].len;2690}26912692/*2693 * The change from "preimage" and "postimage" has been found to2694 * apply at applied_pos (counts in line numbers) in "img".2695 * Update "img" to remove "preimage" and replace it with "postimage".2696 */2697static voidupdate_image(struct apply_state *state,2698struct image *img,2699int applied_pos,2700struct image *preimage,2701struct image *postimage)2702{2703/*2704 * remove the copy of preimage at offset in img2705 * and replace it with postimage2706 */2707int i, nr;2708size_t remove_count, insert_count, applied_at =0;2709char*result;2710int preimage_limit;27112712/*2713 * If we are removing blank lines at the end of img,2714 * the preimage may extend beyond the end.2715 * If that is the case, we must be careful only to2716 * remove the part of the preimage that falls within2717 * the boundaries of img. Initialize preimage_limit2718 * to the number of lines in the preimage that falls2719 * within the boundaries.2720 */2721 preimage_limit = preimage->nr;2722if(preimage_limit > img->nr - applied_pos)2723 preimage_limit = img->nr - applied_pos;27242725for(i =0; i < applied_pos; i++)2726 applied_at += img->line[i].len;27272728 remove_count =0;2729for(i =0; i < preimage_limit; i++)2730 remove_count += img->line[applied_pos + i].len;2731 insert_count = postimage->len;27322733/* Adjust the contents */2734 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2735memcpy(result, img->buf, applied_at);2736memcpy(result + applied_at, postimage->buf, postimage->len);2737memcpy(result + applied_at + postimage->len,2738 img->buf + (applied_at + remove_count),2739 img->len - (applied_at + remove_count));2740free(img->buf);2741 img->buf = result;2742 img->len += insert_count - remove_count;2743 result[img->len] ='\0';27442745/* Adjust the line table */2746 nr = img->nr + postimage->nr - preimage_limit;2747if(preimage_limit < postimage->nr) {2748/*2749 * NOTE: this knows that we never call remove_first_line()2750 * on anything other than pre/post image.2751 */2752REALLOC_ARRAY(img->line, nr);2753 img->line_allocated = img->line;2754}2755if(preimage_limit != postimage->nr)2756memmove(img->line + applied_pos + postimage->nr,2757 img->line + applied_pos + preimage_limit,2758(img->nr - (applied_pos + preimage_limit)) *2759sizeof(*img->line));2760memcpy(img->line + applied_pos,2761 postimage->line,2762 postimage->nr *sizeof(*img->line));2763if(!state->allow_overlap)2764for(i =0; i < postimage->nr; i++)2765 img->line[applied_pos + i].flag |= LINE_PATCHED;2766 img->nr = nr;2767}27682769/*2770 * Use the patch-hunk text in "frag" to prepare two images (preimage and2771 * postimage) for the hunk. Find lines that match "preimage" in "img" and2772 * replace the part of "img" with "postimage" text.2773 */2774static intapply_one_fragment(struct apply_state *state,2775struct image *img,struct fragment *frag,2776int inaccurate_eof,unsigned ws_rule,2777int nth_fragment)2778{2779int match_beginning, match_end;2780const char*patch = frag->patch;2781int size = frag->size;2782char*old, *oldlines;2783struct strbuf newlines;2784int new_blank_lines_at_end =0;2785int found_new_blank_lines_at_end =0;2786int hunk_linenr = frag->linenr;2787unsigned long leading, trailing;2788int pos, applied_pos;2789struct image preimage;2790struct image postimage;27912792memset(&preimage,0,sizeof(preimage));2793memset(&postimage,0,sizeof(postimage));2794 oldlines =xmalloc(size);2795strbuf_init(&newlines, size);27962797 old = oldlines;2798while(size >0) {2799char first;2800int len =linelen(patch, size);2801int plen;2802int added_blank_line =0;2803int is_blank_context =0;2804size_t start;28052806if(!len)2807break;28082809/*2810 * "plen" is how much of the line we should use for2811 * the actual patch data. Normally we just remove the2812 * first character on the line, but if the line is2813 * followed by "\ No newline", then we also remove the2814 * last one (which is the newline, of course).2815 */2816 plen = len -1;2817if(len < size && patch[len] =='\\')2818 plen--;2819 first = *patch;2820if(state->apply_in_reverse) {2821if(first =='-')2822 first ='+';2823else if(first =='+')2824 first ='-';2825}28262827switch(first) {2828case'\n':2829/* Newer GNU diff, empty context line */2830if(plen <0)2831/* ... followed by '\No newline'; nothing */2832break;2833*old++ ='\n';2834strbuf_addch(&newlines,'\n');2835add_line_info(&preimage,"\n",1, LINE_COMMON);2836add_line_info(&postimage,"\n",1, LINE_COMMON);2837 is_blank_context =1;2838break;2839case' ':2840if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2841ws_blank_line(patch +1, plen, ws_rule))2842 is_blank_context =1;2843case'-':2844memcpy(old, patch +1, plen);2845add_line_info(&preimage, old, plen,2846(first ==' '? LINE_COMMON :0));2847 old += plen;2848if(first =='-')2849break;2850/* Fall-through for ' ' */2851case'+':2852/* --no-add does not add new lines */2853if(first =='+'&& state->no_add)2854break;28552856 start = newlines.len;2857if(first !='+'||2858!whitespace_error ||2859 ws_error_action != correct_ws_error) {2860strbuf_add(&newlines, patch +1, plen);2861}2862else{2863ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2864}2865add_line_info(&postimage, newlines.buf + start, newlines.len - start,2866(first =='+'?0: LINE_COMMON));2867if(first =='+'&&2868(ws_rule & WS_BLANK_AT_EOF) &&2869ws_blank_line(patch +1, plen, ws_rule))2870 added_blank_line =1;2871break;2872case'@':case'\\':2873/* Ignore it, we already handled it */2874break;2875default:2876if(state->apply_verbosely)2877error(_("invalid start of line: '%c'"), first);2878 applied_pos = -1;2879goto out;2880}2881if(added_blank_line) {2882if(!new_blank_lines_at_end)2883 found_new_blank_lines_at_end = hunk_linenr;2884 new_blank_lines_at_end++;2885}2886else if(is_blank_context)2887;2888else2889 new_blank_lines_at_end =0;2890 patch += len;2891 size -= len;2892 hunk_linenr++;2893}2894if(inaccurate_eof &&2895 old > oldlines && old[-1] =='\n'&&2896 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2897 old--;2898strbuf_setlen(&newlines, newlines.len -1);2899}29002901 leading = frag->leading;2902 trailing = frag->trailing;29032904/*2905 * A hunk to change lines at the beginning would begin with2906 * @@ -1,L +N,M @@2907 * but we need to be careful. -U0 that inserts before the second2908 * line also has this pattern.2909 *2910 * And a hunk to add to an empty file would begin with2911 * @@ -0,0 +N,M @@2912 *2913 * In other words, a hunk that is (frag->oldpos <= 1) with or2914 * without leading context must match at the beginning.2915 */2916 match_beginning = (!frag->oldpos ||2917(frag->oldpos ==1&& !state->unidiff_zero));29182919/*2920 * A hunk without trailing lines must match at the end.2921 * However, we simply cannot tell if a hunk must match end2922 * from the lack of trailing lines if the patch was generated2923 * with unidiff without any context.2924 */2925 match_end = !state->unidiff_zero && !trailing;29262927 pos = frag->newpos ? (frag->newpos -1) :0;2928 preimage.buf = oldlines;2929 preimage.len = old - oldlines;2930 postimage.buf = newlines.buf;2931 postimage.len = newlines.len;2932 preimage.line = preimage.line_allocated;2933 postimage.line = postimage.line_allocated;29342935for(;;) {29362937 applied_pos =find_pos(img, &preimage, &postimage, pos,2938 ws_rule, match_beginning, match_end);29392940if(applied_pos >=0)2941break;29422943/* Am I at my context limits? */2944if((leading <= state->p_context) && (trailing <= state->p_context))2945break;2946if(match_beginning || match_end) {2947 match_beginning = match_end =0;2948continue;2949}29502951/*2952 * Reduce the number of context lines; reduce both2953 * leading and trailing if they are equal otherwise2954 * just reduce the larger context.2955 */2956if(leading >= trailing) {2957remove_first_line(&preimage);2958remove_first_line(&postimage);2959 pos--;2960 leading--;2961}2962if(trailing > leading) {2963remove_last_line(&preimage);2964remove_last_line(&postimage);2965 trailing--;2966}2967}29682969if(applied_pos >=0) {2970if(new_blank_lines_at_end &&2971 preimage.nr + applied_pos >= img->nr &&2972(ws_rule & WS_BLANK_AT_EOF) &&2973 ws_error_action != nowarn_ws_error) {2974record_ws_error(state, WS_BLANK_AT_EOF,"+",1,2975 found_new_blank_lines_at_end);2976if(ws_error_action == correct_ws_error) {2977while(new_blank_lines_at_end--)2978remove_last_line(&postimage);2979}2980/*2981 * We would want to prevent write_out_results()2982 * from taking place in apply_patch() that follows2983 * the callchain led us here, which is:2984 * apply_patch->check_patch_list->check_patch->2985 * apply_data->apply_fragments->apply_one_fragment2986 */2987if(ws_error_action == die_on_ws_error)2988 state->apply =0;2989}29902991if(state->apply_verbosely && applied_pos != pos) {2992int offset = applied_pos - pos;2993if(state->apply_in_reverse)2994 offset =0- offset;2995fprintf_ln(stderr,2996Q_("Hunk #%dsucceeded at%d(offset%dline).",2997"Hunk #%dsucceeded at%d(offset%dlines).",2998 offset),2999 nth_fragment, applied_pos +1, offset);3000}30013002/*3003 * Warn if it was necessary to reduce the number3004 * of context lines.3005 */3006if((leading != frag->leading) ||3007(trailing != frag->trailing))3008fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"3009" to apply fragment at%d"),3010 leading, trailing, applied_pos+1);3011update_image(state, img, applied_pos, &preimage, &postimage);3012}else{3013if(state->apply_verbosely)3014error(_("while searching for:\n%.*s"),3015(int)(old - oldlines), oldlines);3016}30173018out:3019free(oldlines);3020strbuf_release(&newlines);3021free(preimage.line_allocated);3022free(postimage.line_allocated);30233024return(applied_pos <0);3025}30263027static intapply_binary_fragment(struct apply_state *state,3028struct image *img,3029struct patch *patch)3030{3031struct fragment *fragment = patch->fragments;3032unsigned long len;3033void*dst;30343035if(!fragment)3036returnerror(_("missing binary patch data for '%s'"),3037 patch->new_name ?3038 patch->new_name :3039 patch->old_name);30403041/* Binary patch is irreversible without the optional second hunk */3042if(state->apply_in_reverse) {3043if(!fragment->next)3044returnerror("cannot reverse-apply a binary patch "3045"without the reverse hunk to '%s'",3046 patch->new_name3047? patch->new_name : patch->old_name);3048 fragment = fragment->next;3049}3050switch(fragment->binary_patch_method) {3051case BINARY_DELTA_DEFLATED:3052 dst =patch_delta(img->buf, img->len, fragment->patch,3053 fragment->size, &len);3054if(!dst)3055return-1;3056clear_image(img);3057 img->buf = dst;3058 img->len = len;3059return0;3060case BINARY_LITERAL_DEFLATED:3061clear_image(img);3062 img->len = fragment->size;3063 img->buf =xmemdupz(fragment->patch, img->len);3064return0;3065}3066return-1;3067}30683069/*3070 * Replace "img" with the result of applying the binary patch.3071 * The binary patch data itself in patch->fragment is still kept3072 * but the preimage prepared by the caller in "img" is freed here3073 * or in the helper function apply_binary_fragment() this calls.3074 */3075static intapply_binary(struct apply_state *state,3076struct image *img,3077struct patch *patch)3078{3079const char*name = patch->old_name ? patch->old_name : patch->new_name;3080unsigned char sha1[20];30813082/*3083 * For safety, we require patch index line to contain3084 * full 40-byte textual SHA1 for old and new, at least for now.3085 */3086if(strlen(patch->old_sha1_prefix) !=40||3087strlen(patch->new_sha1_prefix) !=40||3088get_sha1_hex(patch->old_sha1_prefix, sha1) ||3089get_sha1_hex(patch->new_sha1_prefix, sha1))3090returnerror("cannot apply binary patch to '%s' "3091"without full index line", name);30923093if(patch->old_name) {3094/*3095 * See if the old one matches what the patch3096 * applies to.3097 */3098hash_sha1_file(img->buf, img->len, blob_type, sha1);3099if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3100returnerror("the patch applies to '%s' (%s), "3101"which does not match the "3102"current contents.",3103 name,sha1_to_hex(sha1));3104}3105else{3106/* Otherwise, the old one must be empty. */3107if(img->len)3108returnerror("the patch applies to an empty "3109"'%s' but it is not empty", name);3110}31113112get_sha1_hex(patch->new_sha1_prefix, sha1);3113if(is_null_sha1(sha1)) {3114clear_image(img);3115return0;/* deletion patch */3116}31173118if(has_sha1_file(sha1)) {3119/* We already have the postimage */3120enum object_type type;3121unsigned long size;3122char*result;31233124 result =read_sha1_file(sha1, &type, &size);3125if(!result)3126returnerror("the necessary postimage%sfor "3127"'%s' cannot be read",3128 patch->new_sha1_prefix, name);3129clear_image(img);3130 img->buf = result;3131 img->len = size;3132}else{3133/*3134 * We have verified buf matches the preimage;3135 * apply the patch data to it, which is stored3136 * in the patch->fragments->{patch,size}.3137 */3138if(apply_binary_fragment(state, img, patch))3139returnerror(_("binary patch does not apply to '%s'"),3140 name);31413142/* verify that the result matches */3143hash_sha1_file(img->buf, img->len, blob_type, sha1);3144if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3145returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3146 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3147}31483149return0;3150}31513152static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3153{3154struct fragment *frag = patch->fragments;3155const char*name = patch->old_name ? patch->old_name : patch->new_name;3156unsigned ws_rule = patch->ws_rule;3157unsigned inaccurate_eof = patch->inaccurate_eof;3158int nth =0;31593160if(patch->is_binary)3161returnapply_binary(state, img, patch);31623163while(frag) {3164 nth++;3165if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3166error(_("patch failed:%s:%ld"), name, frag->oldpos);3167if(!state->apply_with_reject)3168return-1;3169 frag->rejected =1;3170}3171 frag = frag->next;3172}3173return0;3174}31753176static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3177{3178if(S_ISGITLINK(mode)) {3179strbuf_grow(buf,100);3180strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3181}else{3182enum object_type type;3183unsigned long sz;3184char*result;31853186 result =read_sha1_file(sha1, &type, &sz);3187if(!result)3188return-1;3189/* XXX read_sha1_file NUL-terminates */3190strbuf_attach(buf, result, sz, sz +1);3191}3192return0;3193}31943195static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3196{3197if(!ce)3198return0;3199returnread_blob_object(buf, ce->sha1, ce->ce_mode);3200}32013202static struct patch *in_fn_table(const char*name)3203{3204struct string_list_item *item;32053206if(name == NULL)3207return NULL;32083209 item =string_list_lookup(&fn_table, name);3210if(item != NULL)3211return(struct patch *)item->util;32123213return NULL;3214}32153216/*3217 * item->util in the filename table records the status of the path.3218 * Usually it points at a patch (whose result records the contents3219 * of it after applying it), but it could be PATH_WAS_DELETED for a3220 * path that a previously applied patch has already removed, or3221 * PATH_TO_BE_DELETED for a path that a later patch would remove.3222 *3223 * The latter is needed to deal with a case where two paths A and B3224 * are swapped by first renaming A to B and then renaming B to A;3225 * moving A to B should not be prevented due to presence of B as we3226 * will remove it in a later patch.3227 */3228#define PATH_TO_BE_DELETED ((struct patch *) -2)3229#define PATH_WAS_DELETED ((struct patch *) -1)32303231static intto_be_deleted(struct patch *patch)3232{3233return patch == PATH_TO_BE_DELETED;3234}32353236static intwas_deleted(struct patch *patch)3237{3238return patch == PATH_WAS_DELETED;3239}32403241static voidadd_to_fn_table(struct patch *patch)3242{3243struct string_list_item *item;32443245/*3246 * Always add new_name unless patch is a deletion3247 * This should cover the cases for normal diffs,3248 * file creations and copies3249 */3250if(patch->new_name != NULL) {3251 item =string_list_insert(&fn_table, patch->new_name);3252 item->util = patch;3253}32543255/*3256 * store a failure on rename/deletion cases because3257 * later chunks shouldn't patch old names3258 */3259if((patch->new_name == NULL) || (patch->is_rename)) {3260 item =string_list_insert(&fn_table, patch->old_name);3261 item->util = PATH_WAS_DELETED;3262}3263}32643265static voidprepare_fn_table(struct patch *patch)3266{3267/*3268 * store information about incoming file deletion3269 */3270while(patch) {3271if((patch->new_name == NULL) || (patch->is_rename)) {3272struct string_list_item *item;3273 item =string_list_insert(&fn_table, patch->old_name);3274 item->util = PATH_TO_BE_DELETED;3275}3276 patch = patch->next;3277}3278}32793280static intcheckout_target(struct index_state *istate,3281struct cache_entry *ce,struct stat *st)3282{3283struct checkout costate;32843285memset(&costate,0,sizeof(costate));3286 costate.base_dir ="";3287 costate.refresh_cache =1;3288 costate.istate = istate;3289if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3290returnerror(_("cannot checkout%s"), ce->name);3291return0;3292}32933294static struct patch *previous_patch(struct patch *patch,int*gone)3295{3296struct patch *previous;32973298*gone =0;3299if(patch->is_copy || patch->is_rename)3300return NULL;/* "git" patches do not depend on the order */33013302 previous =in_fn_table(patch->old_name);3303if(!previous)3304return NULL;33053306if(to_be_deleted(previous))3307return NULL;/* the deletion hasn't happened yet */33083309if(was_deleted(previous))3310*gone =1;33113312return previous;3313}33143315static intverify_index_match(const struct cache_entry *ce,struct stat *st)3316{3317if(S_ISGITLINK(ce->ce_mode)) {3318if(!S_ISDIR(st->st_mode))3319return-1;3320return0;3321}3322returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3323}33243325#define SUBMODULE_PATCH_WITHOUT_INDEX 133263327static intload_patch_target(struct apply_state *state,3328struct strbuf *buf,3329const struct cache_entry *ce,3330struct stat *st,3331const char*name,3332unsigned expected_mode)3333{3334if(state->cached || state->check_index) {3335if(read_file_or_gitlink(ce, buf))3336returnerror(_("read of%sfailed"), name);3337}else if(name) {3338if(S_ISGITLINK(expected_mode)) {3339if(ce)3340returnread_file_or_gitlink(ce, buf);3341else3342return SUBMODULE_PATCH_WITHOUT_INDEX;3343}else if(has_symlink_leading_path(name,strlen(name))) {3344returnerror(_("reading from '%s' beyond a symbolic link"), name);3345}else{3346if(read_old_data(st, name, buf))3347returnerror(_("read of%sfailed"), name);3348}3349}3350return0;3351}33523353/*3354 * We are about to apply "patch"; populate the "image" with the3355 * current version we have, from the working tree or from the index,3356 * depending on the situation e.g. --cached/--index. If we are3357 * applying a non-git patch that incrementally updates the tree,3358 * we read from the result of a previous diff.3359 */3360static intload_preimage(struct apply_state *state,3361struct image *image,3362struct patch *patch,struct stat *st,3363const struct cache_entry *ce)3364{3365struct strbuf buf = STRBUF_INIT;3366size_t len;3367char*img;3368struct patch *previous;3369int status;33703371 previous =previous_patch(patch, &status);3372if(status)3373returnerror(_("path%shas been renamed/deleted"),3374 patch->old_name);3375if(previous) {3376/* We have a patched copy in memory; use that. */3377strbuf_add(&buf, previous->result, previous->resultsize);3378}else{3379 status =load_patch_target(state, &buf, ce, st,3380 patch->old_name, patch->old_mode);3381if(status <0)3382return status;3383else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3384/*3385 * There is no way to apply subproject3386 * patch without looking at the index.3387 * NEEDSWORK: shouldn't this be flagged3388 * as an error???3389 */3390free_fragment_list(patch->fragments);3391 patch->fragments = NULL;3392}else if(status) {3393returnerror(_("read of%sfailed"), patch->old_name);3394}3395}33963397 img =strbuf_detach(&buf, &len);3398prepare_image(image, img, len, !patch->is_binary);3399return0;3400}34013402static intthree_way_merge(struct image *image,3403char*path,3404const unsigned char*base,3405const unsigned char*ours,3406const unsigned char*theirs)3407{3408 mmfile_t base_file, our_file, their_file;3409 mmbuffer_t result = { NULL };3410int status;34113412read_mmblob(&base_file, base);3413read_mmblob(&our_file, ours);3414read_mmblob(&their_file, theirs);3415 status =ll_merge(&result, path,3416&base_file,"base",3417&our_file,"ours",3418&their_file,"theirs", NULL);3419free(base_file.ptr);3420free(our_file.ptr);3421free(their_file.ptr);3422if(status <0|| !result.ptr) {3423free(result.ptr);3424return-1;3425}3426clear_image(image);3427 image->buf = result.ptr;3428 image->len = result.size;34293430return status;3431}34323433/*3434 * When directly falling back to add/add three-way merge, we read from3435 * the current contents of the new_name. In no cases other than that3436 * this function will be called.3437 */3438static intload_current(struct apply_state *state,3439struct image *image,3440struct patch *patch)3441{3442struct strbuf buf = STRBUF_INIT;3443int status, pos;3444size_t len;3445char*img;3446struct stat st;3447struct cache_entry *ce;3448char*name = patch->new_name;3449unsigned mode = patch->new_mode;34503451if(!patch->is_new)3452die("BUG: patch to%sis not a creation", patch->old_name);34533454 pos =cache_name_pos(name,strlen(name));3455if(pos <0)3456returnerror(_("%s: does not exist in index"), name);3457 ce = active_cache[pos];3458if(lstat(name, &st)) {3459if(errno != ENOENT)3460returnerror(_("%s:%s"), name,strerror(errno));3461if(checkout_target(&the_index, ce, &st))3462return-1;3463}3464if(verify_index_match(ce, &st))3465returnerror(_("%s: does not match index"), name);34663467 status =load_patch_target(state, &buf, ce, &st, name, mode);3468if(status <0)3469return status;3470else if(status)3471return-1;3472 img =strbuf_detach(&buf, &len);3473prepare_image(image, img, len, !patch->is_binary);3474return0;3475}34763477static inttry_threeway(struct apply_state *state,3478struct image *image,3479struct patch *patch,3480struct stat *st,3481const struct cache_entry *ce)3482{3483unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3484struct strbuf buf = STRBUF_INIT;3485size_t len;3486int status;3487char*img;3488struct image tmp_image;34893490/* No point falling back to 3-way merge in these cases */3491if(patch->is_delete ||3492S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3493return-1;34943495/* Preimage the patch was prepared for */3496if(patch->is_new)3497write_sha1_file("",0, blob_type, pre_sha1);3498else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3499read_blob_object(&buf, pre_sha1, patch->old_mode))3500returnerror("repository lacks the necessary blob to fall back on 3-way merge.");35013502fprintf(stderr,"Falling back to three-way merge...\n");35033504 img =strbuf_detach(&buf, &len);3505prepare_image(&tmp_image, img, len,1);3506/* Apply the patch to get the post image */3507if(apply_fragments(state, &tmp_image, patch) <0) {3508clear_image(&tmp_image);3509return-1;3510}3511/* post_sha1[] is theirs */3512write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3513clear_image(&tmp_image);35143515/* our_sha1[] is ours */3516if(patch->is_new) {3517if(load_current(state, &tmp_image, patch))3518returnerror("cannot read the current contents of '%s'",3519 patch->new_name);3520}else{3521if(load_preimage(state, &tmp_image, patch, st, ce))3522returnerror("cannot read the current contents of '%s'",3523 patch->old_name);3524}3525write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3526clear_image(&tmp_image);35273528/* in-core three-way merge between post and our using pre as base */3529 status =three_way_merge(image, patch->new_name,3530 pre_sha1, our_sha1, post_sha1);3531if(status <0) {3532fprintf(stderr,"Failed to fall back on three-way merge...\n");3533return status;3534}35353536if(status) {3537 patch->conflicted_threeway =1;3538if(patch->is_new)3539oidclr(&patch->threeway_stage[0]);3540else3541hashcpy(patch->threeway_stage[0].hash, pre_sha1);3542hashcpy(patch->threeway_stage[1].hash, our_sha1);3543hashcpy(patch->threeway_stage[2].hash, post_sha1);3544fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3545}else{3546fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3547}3548return0;3549}35503551static intapply_data(struct apply_state *state,struct patch *patch,3552struct stat *st,const struct cache_entry *ce)3553{3554struct image image;35553556if(load_preimage(state, &image, patch, st, ce) <0)3557return-1;35583559if(patch->direct_to_threeway ||3560apply_fragments(state, &image, patch) <0) {3561/* Note: with --reject, apply_fragments() returns 0 */3562if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3563return-1;3564}3565 patch->result = image.buf;3566 patch->resultsize = image.len;3567add_to_fn_table(patch);3568free(image.line_allocated);35693570if(0< patch->is_delete && patch->resultsize)3571returnerror(_("removal patch leaves file contents"));35723573return0;3574}35753576/*3577 * If "patch" that we are looking at modifies or deletes what we have,3578 * we would want it not to lose any local modification we have, either3579 * in the working tree or in the index.3580 *3581 * This also decides if a non-git patch is a creation patch or a3582 * modification to an existing empty file. We do not check the state3583 * of the current tree for a creation patch in this function; the caller3584 * check_patch() separately makes sure (and errors out otherwise) that3585 * the path the patch creates does not exist in the current tree.3586 */3587static intcheck_preimage(struct apply_state *state,3588struct patch *patch,3589struct cache_entry **ce,3590struct stat *st)3591{3592const char*old_name = patch->old_name;3593struct patch *previous = NULL;3594int stat_ret =0, status;3595unsigned st_mode =0;35963597if(!old_name)3598return0;35993600assert(patch->is_new <=0);3601 previous =previous_patch(patch, &status);36023603if(status)3604returnerror(_("path%shas been renamed/deleted"), old_name);3605if(previous) {3606 st_mode = previous->new_mode;3607}else if(!state->cached) {3608 stat_ret =lstat(old_name, st);3609if(stat_ret && errno != ENOENT)3610returnerror(_("%s:%s"), old_name,strerror(errno));3611}36123613if(state->check_index && !previous) {3614int pos =cache_name_pos(old_name,strlen(old_name));3615if(pos <0) {3616if(patch->is_new <0)3617goto is_new;3618returnerror(_("%s: does not exist in index"), old_name);3619}3620*ce = active_cache[pos];3621if(stat_ret <0) {3622if(checkout_target(&the_index, *ce, st))3623return-1;3624}3625if(!state->cached &&verify_index_match(*ce, st))3626returnerror(_("%s: does not match index"), old_name);3627if(state->cached)3628 st_mode = (*ce)->ce_mode;3629}else if(stat_ret <0) {3630if(patch->is_new <0)3631goto is_new;3632returnerror(_("%s:%s"), old_name,strerror(errno));3633}36343635if(!state->cached && !previous)3636 st_mode =ce_mode_from_stat(*ce, st->st_mode);36373638if(patch->is_new <0)3639 patch->is_new =0;3640if(!patch->old_mode)3641 patch->old_mode = st_mode;3642if((st_mode ^ patch->old_mode) & S_IFMT)3643returnerror(_("%s: wrong type"), old_name);3644if(st_mode != patch->old_mode)3645warning(_("%shas type%o, expected%o"),3646 old_name, st_mode, patch->old_mode);3647if(!patch->new_mode && !patch->is_delete)3648 patch->new_mode = st_mode;3649return0;36503651 is_new:3652 patch->is_new =1;3653 patch->is_delete =0;3654free(patch->old_name);3655 patch->old_name = NULL;3656return0;3657}365836593660#define EXISTS_IN_INDEX 13661#define EXISTS_IN_WORKTREE 236623663static intcheck_to_create(struct apply_state *state,3664const char*new_name,3665int ok_if_exists)3666{3667struct stat nst;36683669if(state->check_index &&3670cache_name_pos(new_name,strlen(new_name)) >=0&&3671!ok_if_exists)3672return EXISTS_IN_INDEX;3673if(state->cached)3674return0;36753676if(!lstat(new_name, &nst)) {3677if(S_ISDIR(nst.st_mode) || ok_if_exists)3678return0;3679/*3680 * A leading component of new_name might be a symlink3681 * that is going to be removed with this patch, but3682 * still pointing at somewhere that has the path.3683 * In such a case, path "new_name" does not exist as3684 * far as git is concerned.3685 */3686if(has_symlink_leading_path(new_name,strlen(new_name)))3687return0;36883689return EXISTS_IN_WORKTREE;3690}else if((errno != ENOENT) && (errno != ENOTDIR)) {3691returnerror("%s:%s", new_name,strerror(errno));3692}3693return0;3694}36953696/*3697 * We need to keep track of how symlinks in the preimage are3698 * manipulated by the patches. A patch to add a/b/c where a/b3699 * is a symlink should not be allowed to affect the directory3700 * the symlink points at, but if the same patch removes a/b,3701 * it is perfectly fine, as the patch removes a/b to make room3702 * to create a directory a/b so that a/b/c can be created.3703 */3704static struct string_list symlink_changes;3705#define SYMLINK_GOES_AWAY 013706#define SYMLINK_IN_RESULT 0237073708static uintptr_tregister_symlink_changes(const char*path,uintptr_t what)3709{3710struct string_list_item *ent;37113712 ent =string_list_lookup(&symlink_changes, path);3713if(!ent) {3714 ent =string_list_insert(&symlink_changes, path);3715 ent->util = (void*)0;3716}3717 ent->util = (void*)(what | ((uintptr_t)ent->util));3718return(uintptr_t)ent->util;3719}37203721static uintptr_tcheck_symlink_changes(const char*path)3722{3723struct string_list_item *ent;37243725 ent =string_list_lookup(&symlink_changes, path);3726if(!ent)3727return0;3728return(uintptr_t)ent->util;3729}37303731static voidprepare_symlink_changes(struct patch *patch)3732{3733for( ; patch; patch = patch->next) {3734if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3735(patch->is_rename || patch->is_delete))3736/* the symlink at patch->old_name is removed */3737register_symlink_changes(patch->old_name, SYMLINK_GOES_AWAY);37383739if(patch->new_name &&S_ISLNK(patch->new_mode))3740/* the symlink at patch->new_name is created or remains */3741register_symlink_changes(patch->new_name, SYMLINK_IN_RESULT);3742}3743}37443745static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3746{3747do{3748unsigned int change;37493750while(--name->len && name->buf[name->len] !='/')3751;/* scan backwards */3752if(!name->len)3753break;3754 name->buf[name->len] ='\0';3755 change =check_symlink_changes(name->buf);3756if(change & SYMLINK_IN_RESULT)3757return1;3758if(change & SYMLINK_GOES_AWAY)3759/*3760 * This cannot be "return 0", because we may3761 * see a new one created at a higher level.3762 */3763continue;37643765/* otherwise, check the preimage */3766if(state->check_index) {3767struct cache_entry *ce;37683769 ce =cache_file_exists(name->buf, name->len, ignore_case);3770if(ce &&S_ISLNK(ce->ce_mode))3771return1;3772}else{3773struct stat st;3774if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3775return1;3776}3777}while(1);3778return0;3779}37803781static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3782{3783int ret;3784struct strbuf name = STRBUF_INIT;37853786assert(*name_ !='\0');3787strbuf_addstr(&name, name_);3788 ret =path_is_beyond_symlink_1(state, &name);3789strbuf_release(&name);37903791return ret;3792}37933794static voiddie_on_unsafe_path(struct patch *patch)3795{3796const char*old_name = NULL;3797const char*new_name = NULL;3798if(patch->is_delete)3799 old_name = patch->old_name;3800else if(!patch->is_new && !patch->is_copy)3801 old_name = patch->old_name;3802if(!patch->is_delete)3803 new_name = patch->new_name;38043805if(old_name && !verify_path(old_name))3806die(_("invalid path '%s'"), old_name);3807if(new_name && !verify_path(new_name))3808die(_("invalid path '%s'"), new_name);3809}38103811/*3812 * Check and apply the patch in-core; leave the result in patch->result3813 * for the caller to write it out to the final destination.3814 */3815static intcheck_patch(struct apply_state *state,struct patch *patch)3816{3817struct stat st;3818const char*old_name = patch->old_name;3819const char*new_name = patch->new_name;3820const char*name = old_name ? old_name : new_name;3821struct cache_entry *ce = NULL;3822struct patch *tpatch;3823int ok_if_exists;3824int status;38253826 patch->rejected =1;/* we will drop this after we succeed */38273828 status =check_preimage(state, patch, &ce, &st);3829if(status)3830return status;3831 old_name = patch->old_name;38323833/*3834 * A type-change diff is always split into a patch to delete3835 * old, immediately followed by a patch to create new (see3836 * diff.c::run_diff()); in such a case it is Ok that the entry3837 * to be deleted by the previous patch is still in the working3838 * tree and in the index.3839 *3840 * A patch to swap-rename between A and B would first rename A3841 * to B and then rename B to A. While applying the first one,3842 * the presence of B should not stop A from getting renamed to3843 * B; ask to_be_deleted() about the later rename. Removal of3844 * B and rename from A to B is handled the same way by asking3845 * was_deleted().3846 */3847if((tpatch =in_fn_table(new_name)) &&3848(was_deleted(tpatch) ||to_be_deleted(tpatch)))3849 ok_if_exists =1;3850else3851 ok_if_exists =0;38523853if(new_name &&3854((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3855int err =check_to_create(state, new_name, ok_if_exists);38563857if(err && state->threeway) {3858 patch->direct_to_threeway =1;3859}else switch(err) {3860case0:3861break;/* happy */3862case EXISTS_IN_INDEX:3863returnerror(_("%s: already exists in index"), new_name);3864break;3865case EXISTS_IN_WORKTREE:3866returnerror(_("%s: already exists in working directory"),3867 new_name);3868default:3869return err;3870}38713872if(!patch->new_mode) {3873if(0< patch->is_new)3874 patch->new_mode = S_IFREG |0644;3875else3876 patch->new_mode = patch->old_mode;3877}3878}38793880if(new_name && old_name) {3881int same = !strcmp(old_name, new_name);3882if(!patch->new_mode)3883 patch->new_mode = patch->old_mode;3884if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3885if(same)3886returnerror(_("new mode (%o) of%sdoes not "3887"match old mode (%o)"),3888 patch->new_mode, new_name,3889 patch->old_mode);3890else3891returnerror(_("new mode (%o) of%sdoes not "3892"match old mode (%o) of%s"),3893 patch->new_mode, new_name,3894 patch->old_mode, old_name);3895}3896}38973898if(!state->unsafe_paths)3899die_on_unsafe_path(patch);39003901/*3902 * An attempt to read from or delete a path that is beyond a3903 * symbolic link will be prevented by load_patch_target() that3904 * is called at the beginning of apply_data() so we do not3905 * have to worry about a patch marked with "is_delete" bit3906 * here. We however need to make sure that the patch result3907 * is not deposited to a path that is beyond a symbolic link3908 * here.3909 */3910if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3911returnerror(_("affected file '%s' is beyond a symbolic link"),3912 patch->new_name);39133914if(apply_data(state, patch, &st, ce) <0)3915returnerror(_("%s: patch does not apply"), name);3916 patch->rejected =0;3917return0;3918}39193920static intcheck_patch_list(struct apply_state *state,struct patch *patch)3921{3922int err =0;39233924prepare_symlink_changes(patch);3925prepare_fn_table(patch);3926while(patch) {3927if(state->apply_verbosely)3928say_patch_name(stderr,3929_("Checking patch%s..."), patch);3930 err |=check_patch(state, patch);3931 patch = patch->next;3932}3933return err;3934}39353936/* This function tries to read the sha1 from the current index */3937static intget_current_sha1(const char*path,unsigned char*sha1)3938{3939int pos;39403941if(read_cache() <0)3942return-1;3943 pos =cache_name_pos(path,strlen(path));3944if(pos <0)3945return-1;3946hashcpy(sha1, active_cache[pos]->sha1);3947return0;3948}39493950static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3951{3952/*3953 * A usable gitlink patch has only one fragment (hunk) that looks like:3954 * @@ -1 +1 @@3955 * -Subproject commit <old sha1>3956 * +Subproject commit <new sha1>3957 * or3958 * @@ -1 +0,0 @@3959 * -Subproject commit <old sha1>3960 * for a removal patch.3961 */3962struct fragment *hunk = p->fragments;3963static const char heading[] ="-Subproject commit ";3964char*preimage;39653966if(/* does the patch have only one hunk? */3967 hunk && !hunk->next &&3968/* is its preimage one line? */3969 hunk->oldpos ==1&& hunk->oldlines ==1&&3970/* does preimage begin with the heading? */3971(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3972starts_with(++preimage, heading) &&3973/* does it record full SHA-1? */3974!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3975 preimage[sizeof(heading) +40-1] =='\n'&&3976/* does the abbreviated name on the index line agree with it? */3977starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3978return0;/* it all looks fine */39793980/* we may have full object name on the index line */3981returnget_sha1_hex(p->old_sha1_prefix, sha1);3982}39833984/* Build an index that contains the just the files needed for a 3way merge */3985static voidbuild_fake_ancestor(struct patch *list,const char*filename)3986{3987struct patch *patch;3988struct index_state result = { NULL };3989static struct lock_file lock;39903991/* Once we start supporting the reverse patch, it may be3992 * worth showing the new sha1 prefix, but until then...3993 */3994for(patch = list; patch; patch = patch->next) {3995unsigned char sha1[20];3996struct cache_entry *ce;3997const char*name;39983999 name = patch->old_name ? patch->old_name : patch->new_name;4000if(0< patch->is_new)4001continue;40024003if(S_ISGITLINK(patch->old_mode)) {4004if(!preimage_sha1_in_gitlink_patch(patch, sha1))4005;/* ok, the textual part looks sane */4006else4007die("sha1 information is lacking or useless for submodule%s",4008 name);4009}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {4010;/* ok */4011}else if(!patch->lines_added && !patch->lines_deleted) {4012/* mode-only change: update the current */4013if(get_current_sha1(patch->old_name, sha1))4014die("mode change for%s, which is not "4015"in current HEAD", name);4016}else4017die("sha1 information is lacking or useless "4018"(%s).", name);40194020 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);4021if(!ce)4022die(_("make_cache_entry failed for path '%s'"), name);4023if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))4024die("Could not add%sto temporary index", name);4025}40264027hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);4028if(write_locked_index(&result, &lock, COMMIT_LOCK))4029die("Could not write temporary index to%s", filename);40304031discard_index(&result);4032}40334034static voidstat_patch_list(struct patch *patch)4035{4036int files, adds, dels;40374038for(files = adds = dels =0; patch ; patch = patch->next) {4039 files++;4040 adds += patch->lines_added;4041 dels += patch->lines_deleted;4042show_stats(patch);4043}40444045print_stat_summary(stdout, files, adds, dels);4046}40474048static voidnumstat_patch_list(struct apply_state *state,4049struct patch *patch)4050{4051for( ; patch; patch = patch->next) {4052const char*name;4053 name = patch->new_name ? patch->new_name : patch->old_name;4054if(patch->is_binary)4055printf("-\t-\t");4056else4057printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4058write_name_quoted(name, stdout, state->line_termination);4059}4060}40614062static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4063{4064if(mode)4065printf("%smode%06o%s\n", newdelete, mode, name);4066else4067printf("%s %s\n", newdelete, name);4068}40694070static voidshow_mode_change(struct patch *p,int show_name)4071{4072if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4073if(show_name)4074printf(" mode change%06o =>%06o%s\n",4075 p->old_mode, p->new_mode, p->new_name);4076else4077printf(" mode change%06o =>%06o\n",4078 p->old_mode, p->new_mode);4079}4080}40814082static voidshow_rename_copy(struct patch *p)4083{4084const char*renamecopy = p->is_rename ?"rename":"copy";4085const char*old, *new;40864087/* Find common prefix */4088 old = p->old_name;4089new= p->new_name;4090while(1) {4091const char*slash_old, *slash_new;4092 slash_old =strchr(old,'/');4093 slash_new =strchr(new,'/');4094if(!slash_old ||4095!slash_new ||4096 slash_old - old != slash_new -new||4097memcmp(old,new, slash_new -new))4098break;4099 old = slash_old +1;4100new= slash_new +1;4101}4102/* p->old_name thru old is the common prefix, and old and new4103 * through the end of names are renames4104 */4105if(old != p->old_name)4106printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4107(int)(old - p->old_name), p->old_name,4108 old,new, p->score);4109else4110printf("%s %s=>%s(%d%%)\n", renamecopy,4111 p->old_name, p->new_name, p->score);4112show_mode_change(p,0);4113}41144115static voidsummary_patch_list(struct patch *patch)4116{4117struct patch *p;41184119for(p = patch; p; p = p->next) {4120if(p->is_new)4121show_file_mode_name("create", p->new_mode, p->new_name);4122else if(p->is_delete)4123show_file_mode_name("delete", p->old_mode, p->old_name);4124else{4125if(p->is_rename || p->is_copy)4126show_rename_copy(p);4127else{4128if(p->score) {4129printf(" rewrite%s(%d%%)\n",4130 p->new_name, p->score);4131show_mode_change(p,0);4132}4133else4134show_mode_change(p,1);4135}4136}4137}4138}41394140static voidpatch_stats(struct patch *patch)4141{4142int lines = patch->lines_added + patch->lines_deleted;41434144if(lines > max_change)4145 max_change = lines;4146if(patch->old_name) {4147int len =quote_c_style(patch->old_name, NULL, NULL,0);4148if(!len)4149 len =strlen(patch->old_name);4150if(len > max_len)4151 max_len = len;4152}4153if(patch->new_name) {4154int len =quote_c_style(patch->new_name, NULL, NULL,0);4155if(!len)4156 len =strlen(patch->new_name);4157if(len > max_len)4158 max_len = len;4159}4160}41614162static voidremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4163{4164if(state->update_index) {4165if(remove_file_from_cache(patch->old_name) <0)4166die(_("unable to remove%sfrom index"), patch->old_name);4167}4168if(!state->cached) {4169if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4170remove_path(patch->old_name);4171}4172}4173}41744175static voidadd_index_file(struct apply_state *state,4176const char*path,4177unsigned mode,4178void*buf,4179unsigned long size)4180{4181struct stat st;4182struct cache_entry *ce;4183int namelen =strlen(path);4184unsigned ce_size =cache_entry_size(namelen);41854186if(!state->update_index)4187return;41884189 ce =xcalloc(1, ce_size);4190memcpy(ce->name, path, namelen);4191 ce->ce_mode =create_ce_mode(mode);4192 ce->ce_flags =create_ce_flags(0);4193 ce->ce_namelen = namelen;4194if(S_ISGITLINK(mode)) {4195const char*s;41964197if(!skip_prefix(buf,"Subproject commit ", &s) ||4198get_sha1_hex(s, ce->sha1))4199die(_("corrupt patch for submodule%s"), path);4200}else{4201if(!state->cached) {4202if(lstat(path, &st) <0)4203die_errno(_("unable to stat newly created file '%s'"),4204 path);4205fill_stat_cache_info(ce, &st);4206}4207if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4208die(_("unable to create backing store for newly created file%s"), path);4209}4210if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4211die(_("unable to add cache entry for%s"), path);4212}42134214static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4215{4216int fd;4217struct strbuf nbuf = STRBUF_INIT;42184219if(S_ISGITLINK(mode)) {4220struct stat st;4221if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4222return0;4223returnmkdir(path,0777);4224}42254226if(has_symlinks &&S_ISLNK(mode))4227/* Although buf:size is counted string, it also is NUL4228 * terminated.4229 */4230returnsymlink(buf, path);42314232 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4233if(fd <0)4234return-1;42354236if(convert_to_working_tree(path, buf, size, &nbuf)) {4237 size = nbuf.len;4238 buf = nbuf.buf;4239}4240write_or_die(fd, buf, size);4241strbuf_release(&nbuf);42424243if(close(fd) <0)4244die_errno(_("closing file '%s'"), path);4245return0;4246}42474248/*4249 * We optimistically assume that the directories exist,4250 * which is true 99% of the time anyway. If they don't,4251 * we create them and try again.4252 */4253static voidcreate_one_file(struct apply_state *state,4254char*path,4255unsigned mode,4256const char*buf,4257unsigned long size)4258{4259if(state->cached)4260return;4261if(!try_create_file(path, mode, buf, size))4262return;42634264if(errno == ENOENT) {4265if(safe_create_leading_directories(path))4266return;4267if(!try_create_file(path, mode, buf, size))4268return;4269}42704271if(errno == EEXIST || errno == EACCES) {4272/* We may be trying to create a file where a directory4273 * used to be.4274 */4275struct stat st;4276if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4277 errno = EEXIST;4278}42794280if(errno == EEXIST) {4281unsigned int nr =getpid();42824283for(;;) {4284char newpath[PATH_MAX];4285mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4286if(!try_create_file(newpath, mode, buf, size)) {4287if(!rename(newpath, path))4288return;4289unlink_or_warn(newpath);4290break;4291}4292if(errno != EEXIST)4293break;4294++nr;4295}4296}4297die_errno(_("unable to write file '%s' mode%o"), path, mode);4298}42994300static voidadd_conflicted_stages_file(struct apply_state *state,4301struct patch *patch)4302{4303int stage, namelen;4304unsigned ce_size, mode;4305struct cache_entry *ce;43064307if(!state->update_index)4308return;4309 namelen =strlen(patch->new_name);4310 ce_size =cache_entry_size(namelen);4311 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);43124313remove_file_from_cache(patch->new_name);4314for(stage =1; stage <4; stage++) {4315if(is_null_oid(&patch->threeway_stage[stage -1]))4316continue;4317 ce =xcalloc(1, ce_size);4318memcpy(ce->name, patch->new_name, namelen);4319 ce->ce_mode =create_ce_mode(mode);4320 ce->ce_flags =create_ce_flags(stage);4321 ce->ce_namelen = namelen;4322hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4323if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4324die(_("unable to add cache entry for%s"), patch->new_name);4325}4326}43274328static voidcreate_file(struct apply_state *state,struct patch *patch)4329{4330char*path = patch->new_name;4331unsigned mode = patch->new_mode;4332unsigned long size = patch->resultsize;4333char*buf = patch->result;43344335if(!mode)4336 mode = S_IFREG |0644;4337create_one_file(state, path, mode, buf, size);43384339if(patch->conflicted_threeway)4340add_conflicted_stages_file(state, patch);4341else4342add_index_file(state, path, mode, buf, size);4343}43444345/* phase zero is to remove, phase one is to create */4346static voidwrite_out_one_result(struct apply_state *state,4347struct patch *patch,4348int phase)4349{4350if(patch->is_delete >0) {4351if(phase ==0)4352remove_file(state, patch,1);4353return;4354}4355if(patch->is_new >0|| patch->is_copy) {4356if(phase ==1)4357create_file(state, patch);4358return;4359}4360/*4361 * Rename or modification boils down to the same4362 * thing: remove the old, write the new4363 */4364if(phase ==0)4365remove_file(state, patch, patch->is_rename);4366if(phase ==1)4367create_file(state, patch);4368}43694370static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4371{4372FILE*rej;4373char namebuf[PATH_MAX];4374struct fragment *frag;4375int cnt =0;4376struct strbuf sb = STRBUF_INIT;43774378for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4379if(!frag->rejected)4380continue;4381 cnt++;4382}43834384if(!cnt) {4385if(state->apply_verbosely)4386say_patch_name(stderr,4387_("Applied patch%scleanly."), patch);4388return0;4389}43904391/* This should not happen, because a removal patch that leaves4392 * contents are marked "rejected" at the patch level.4393 */4394if(!patch->new_name)4395die(_("internal error"));43964397/* Say this even without --verbose */4398strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4399"Applying patch %%swith%drejects...",4400 cnt),4401 cnt);4402say_patch_name(stderr, sb.buf, patch);4403strbuf_release(&sb);44044405 cnt =strlen(patch->new_name);4406if(ARRAY_SIZE(namebuf) <= cnt +5) {4407 cnt =ARRAY_SIZE(namebuf) -5;4408warning(_("truncating .rej filename to %.*s.rej"),4409 cnt -1, patch->new_name);4410}4411memcpy(namebuf, patch->new_name, cnt);4412memcpy(namebuf + cnt,".rej",5);44134414 rej =fopen(namebuf,"w");4415if(!rej)4416returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));44174418/* Normal git tools never deal with .rej, so do not pretend4419 * this is a git patch by saying --git or giving extended4420 * headers. While at it, maybe please "kompare" that wants4421 * the trailing TAB and some garbage at the end of line ;-).4422 */4423fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4424 patch->new_name, patch->new_name);4425for(cnt =1, frag = patch->fragments;4426 frag;4427 cnt++, frag = frag->next) {4428if(!frag->rejected) {4429fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4430continue;4431}4432fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4433fprintf(rej,"%.*s", frag->size, frag->patch);4434if(frag->patch[frag->size-1] !='\n')4435fputc('\n', rej);4436}4437fclose(rej);4438return-1;4439}44404441static intwrite_out_results(struct apply_state *state,struct patch *list)4442{4443int phase;4444int errs =0;4445struct patch *l;4446struct string_list cpath = STRING_LIST_INIT_DUP;44474448for(phase =0; phase <2; phase++) {4449 l = list;4450while(l) {4451if(l->rejected)4452 errs =1;4453else{4454write_out_one_result(state, l, phase);4455if(phase ==1) {4456if(write_out_one_reject(state, l))4457 errs =1;4458if(l->conflicted_threeway) {4459string_list_append(&cpath, l->new_name);4460 errs =1;4461}4462}4463}4464 l = l->next;4465}4466}44674468if(cpath.nr) {4469struct string_list_item *item;44704471string_list_sort(&cpath);4472for_each_string_list_item(item, &cpath)4473fprintf(stderr,"U%s\n", item->string);4474string_list_clear(&cpath,0);44754476rerere(0);4477}44784479return errs;4480}44814482static struct lock_file lock_file;44834484#define INACCURATE_EOF (1<<0)4485#define RECOUNT (1<<1)44864487static intapply_patch(struct apply_state *state,4488int fd,4489const char*filename,4490int options)4491{4492size_t offset;4493struct strbuf buf = STRBUF_INIT;/* owns the patch text */4494struct patch *list = NULL, **listp = &list;4495int skipped_patch =0;44964497 state->patch_input_file = filename;4498read_patch_file(&buf, fd);4499 offset =0;4500while(offset < buf.len) {4501struct patch *patch;4502int nr;45034504 patch =xcalloc(1,sizeof(*patch));4505 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4506 patch->recount = !!(options & RECOUNT);4507 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4508if(nr <0) {4509free_patch(patch);4510break;4511}4512if(state->apply_in_reverse)4513reverse_patches(patch);4514if(use_patch(state, patch)) {4515patch_stats(patch);4516*listp = patch;4517 listp = &patch->next;4518}4519else{4520if(state->apply_verbosely)4521say_patch_name(stderr,_("Skipped patch '%s'."), patch);4522free_patch(patch);4523 skipped_patch++;4524}4525 offset += nr;4526}45274528if(!list && !skipped_patch)4529die(_("unrecognized input"));45304531if(whitespace_error && (ws_error_action == die_on_ws_error))4532 state->apply =0;45334534 state->update_index = state->check_index && state->apply;4535if(state->update_index && newfd <0)4536 newfd =hold_locked_index(&lock_file,1);45374538if(state->check_index) {4539if(read_cache() <0)4540die(_("unable to read index file"));4541}45424543if((state->check || state->apply) &&4544check_patch_list(state, list) <0&&4545!state->apply_with_reject)4546exit(1);45474548if(state->apply &&write_out_results(state, list)) {4549if(state->apply_with_reject)4550exit(1);4551/* with --3way, we still need to write the index out */4552return1;4553}45544555if(state->fake_ancestor)4556build_fake_ancestor(list, state->fake_ancestor);45574558if(state->diffstat)4559stat_patch_list(list);45604561if(state->numstat)4562numstat_patch_list(state, list);45634564if(state->summary)4565summary_patch_list(list);45664567free_patch_list(list);4568strbuf_release(&buf);4569string_list_clear(&fn_table,0);4570return0;4571}45724573static voidgit_apply_config(void)4574{4575git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4576git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4577git_config(git_default_config, NULL);4578}45794580static intoption_parse_exclude(const struct option *opt,4581const char*arg,int unset)4582{4583struct apply_state *state = opt->value;4584add_name_limit(state, arg,1);4585return0;4586}45874588static intoption_parse_include(const struct option *opt,4589const char*arg,int unset)4590{4591struct apply_state *state = opt->value;4592add_name_limit(state, arg,0);4593 state->has_include =1;4594return0;4595}45964597static intoption_parse_p(const struct option *opt,4598const char*arg,4599int unset)4600{4601struct apply_state *state = opt->value;4602 state->p_value =atoi(arg);4603 state->p_value_known =1;4604return0;4605}46064607static intoption_parse_space_change(const struct option *opt,4608const char*arg,int unset)4609{4610if(unset)4611 ws_ignore_action = ignore_ws_none;4612else4613 ws_ignore_action = ignore_ws_change;4614return0;4615}46164617static intoption_parse_whitespace(const struct option *opt,4618const char*arg,int unset)4619{4620const char**whitespace_option = opt->value;46214622*whitespace_option = arg;4623parse_whitespace_option(arg);4624return0;4625}46264627static intoption_parse_directory(const struct option *opt,4628const char*arg,int unset)4629{4630struct apply_state *state = opt->value;4631strbuf_reset(&state->root);4632strbuf_addstr(&state->root, arg);4633strbuf_complete(&state->root,'/');4634return0;4635}46364637static voidinit_apply_state(struct apply_state *state,const char*prefix)4638{4639memset(state,0,sizeof(*state));4640 state->prefix = prefix;4641 state->prefix_length = state->prefix ?strlen(state->prefix) :0;4642 state->apply =1;4643 state->line_termination ='\n';4644 state->p_value =1;4645 state->p_context = UINT_MAX;4646strbuf_init(&state->root,0);46474648git_apply_config();4649if(apply_default_whitespace)4650parse_whitespace_option(apply_default_whitespace);4651if(apply_default_ignorewhitespace)4652parse_ignorewhitespace_option(apply_default_ignorewhitespace);4653}46544655static voidclear_apply_state(struct apply_state *state)4656{4657string_list_clear(&state->limit_by_name,0);4658strbuf_release(&state->root);4659}46604661intcmd_apply(int argc,const char**argv,const char*prefix)4662{4663int i;4664int errs =0;4665int is_not_gitdir = !startup_info->have_repository;4666int force_apply =0;4667int options =0;4668int read_stdin =1;4669struct apply_state state;46704671const char*whitespace_option = NULL;46724673struct option builtin_apply_options[] = {4674{ OPTION_CALLBACK,0,"exclude", &state,N_("path"),4675N_("don't apply changes matching the given path"),46760, option_parse_exclude },4677{ OPTION_CALLBACK,0,"include", &state,N_("path"),4678N_("apply changes matching the given path"),46790, option_parse_include },4680{ OPTION_CALLBACK,'p', NULL, &state,N_("num"),4681N_("remove <num> leading slashes from traditional diff paths"),46820, option_parse_p },4683OPT_BOOL(0,"no-add", &state.no_add,4684N_("ignore additions made by the patch")),4685OPT_BOOL(0,"stat", &state.diffstat,4686N_("instead of applying the patch, output diffstat for the input")),4687OPT_NOOP_NOARG(0,"allow-binary-replacement"),4688OPT_NOOP_NOARG(0,"binary"),4689OPT_BOOL(0,"numstat", &state.numstat,4690N_("show number of added and deleted lines in decimal notation")),4691OPT_BOOL(0,"summary", &state.summary,4692N_("instead of applying the patch, output a summary for the input")),4693OPT_BOOL(0,"check", &state.check,4694N_("instead of applying the patch, see if the patch is applicable")),4695OPT_BOOL(0,"index", &state.check_index,4696N_("make sure the patch is applicable to the current index")),4697OPT_BOOL(0,"cached", &state.cached,4698N_("apply a patch without touching the working tree")),4699OPT_BOOL(0,"unsafe-paths", &state.unsafe_paths,4700N_("accept a patch that touches outside the working area")),4701OPT_BOOL(0,"apply", &force_apply,4702N_("also apply the patch (use with --stat/--summary/--check)")),4703OPT_BOOL('3',"3way", &state.threeway,4704N_("attempt three-way merge if a patch does not apply")),4705OPT_FILENAME(0,"build-fake-ancestor", &state.fake_ancestor,4706N_("build a temporary index based on embedded index information")),4707/* Think twice before adding "--nul" synonym to this */4708OPT_SET_INT('z', NULL, &state.line_termination,4709N_("paths are separated with NUL character"),'\0'),4710OPT_INTEGER('C', NULL, &state.p_context,4711N_("ensure at least <n> lines of context match")),4712{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,N_("action"),4713N_("detect new or modified lines that have whitespace errors"),47140, option_parse_whitespace },4715{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,4716N_("ignore changes in whitespace when finding context"),4717 PARSE_OPT_NOARG, option_parse_space_change },4718{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,4719N_("ignore changes in whitespace when finding context"),4720 PARSE_OPT_NOARG, option_parse_space_change },4721OPT_BOOL('R',"reverse", &state.apply_in_reverse,4722N_("apply the patch in reverse")),4723OPT_BOOL(0,"unidiff-zero", &state.unidiff_zero,4724N_("don't expect at least one line of context")),4725OPT_BOOL(0,"reject", &state.apply_with_reject,4726N_("leave the rejected hunks in corresponding *.rej files")),4727OPT_BOOL(0,"allow-overlap", &state.allow_overlap,4728N_("allow overlapping hunks")),4729OPT__VERBOSE(&state.apply_verbosely,N_("be verbose")),4730OPT_BIT(0,"inaccurate-eof", &options,4731N_("tolerate incorrectly detected missing new-line at the end of file"),4732 INACCURATE_EOF),4733OPT_BIT(0,"recount", &options,4734N_("do not trust the line counts in the hunk headers"),4735 RECOUNT),4736{ OPTION_CALLBACK,0,"directory", &state,N_("root"),4737N_("prepend <root> to all filenames"),47380, option_parse_directory },4739OPT_END()4740};47414742init_apply_state(&state, prefix);47434744 argc =parse_options(argc, argv, state.prefix, builtin_apply_options,4745 apply_usage,0);47464747if(state.apply_with_reject && state.threeway)4748die("--reject and --3way cannot be used together.");4749if(state.cached && state.threeway)4750die("--cached and --3way cannot be used together.");4751if(state.threeway) {4752if(is_not_gitdir)4753die(_("--3way outside a repository"));4754 state.check_index =1;4755}4756if(state.apply_with_reject)4757 state.apply = state.apply_verbosely =1;4758if(!force_apply && (state.diffstat || state.numstat || state.summary || state.check || state.fake_ancestor))4759 state.apply =0;4760if(state.check_index && is_not_gitdir)4761die(_("--index outside a repository"));4762if(state.cached) {4763if(is_not_gitdir)4764die(_("--cached outside a repository"));4765 state.check_index =1;4766}4767if(state.check_index)4768 state.unsafe_paths =0;47694770for(i =0; i < argc; i++) {4771const char*arg = argv[i];4772int fd;47734774if(!strcmp(arg,"-")) {4775 errs |=apply_patch(&state,0,"<stdin>", options);4776 read_stdin =0;4777continue;4778}else if(0< state.prefix_length)4779 arg =prefix_filename(state.prefix,4780 state.prefix_length,4781 arg);47824783 fd =open(arg, O_RDONLY);4784if(fd <0)4785die_errno(_("can't open patch '%s'"), arg);4786 read_stdin =0;4787set_default_whitespace_mode(&state, whitespace_option);4788 errs |=apply_patch(&state, fd, arg, options);4789close(fd);4790}4791set_default_whitespace_mode(&state, whitespace_option);4792if(read_stdin)4793 errs |=apply_patch(&state,0,"<stdin>", options);4794if(whitespace_error) {4795if(squelch_whitespace_errors &&4796 squelch_whitespace_errors < whitespace_error) {4797int squelched =4798 whitespace_error - squelch_whitespace_errors;4799warning(Q_("squelched%dwhitespace error",4800"squelched%dwhitespace errors",4801 squelched),4802 squelched);4803}4804if(ws_error_action == die_on_ws_error)4805die(Q_("%dline adds whitespace errors.",4806"%dlines add whitespace errors.",4807 whitespace_error),4808 whitespace_error);4809if(applied_after_fixing_ws && state.apply)4810warning("%dline%sapplied after"4811" fixing whitespace errors.",4812 applied_after_fixing_ws,4813 applied_after_fixing_ws ==1?"":"s");4814else if(whitespace_error)4815warning(Q_("%dline adds whitespace errors.",4816"%dlines add whitespace errors.",4817 whitespace_error),4818 whitespace_error);4819}48204821if(state.update_index) {4822if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK))4823die(_("Unable to write new index file"));4824}48254826clear_apply_state(&state);48274828return!!errs;4829}