1/* 2 * apply.c 3 * 4 * Copyright (C) Linus Torvalds, 2005 5 * 6 * This applies patches on top of some (arbitrary) version of the SCM. 7 * 8 */ 9#include"cache.h" 10#include"lockfile.h" 11#include"cache-tree.h" 12#include"quote.h" 13#include"blob.h" 14#include"delta.h" 15#include"builtin.h" 16#include"string-list.h" 17#include"dir.h" 18#include"diff.h" 19#include"parse-options.h" 20#include"xdiff-interface.h" 21#include"ll-merge.h" 22#include"rerere.h" 23 24enum ws_error_action { 25 nowarn_ws_error, 26 warn_on_ws_error, 27 die_on_ws_error, 28 correct_ws_error 29}; 30 31 32enum ws_ignore { 33 ignore_ws_none, 34 ignore_ws_change 35}; 36 37struct apply_state { 38const char*prefix; 39int prefix_length; 40 41/* These control what gets looked at and modified */ 42int apply;/* this is not a dry-run */ 43int cached;/* apply to the index only */ 44int check;/* preimage must match working tree, don't actually apply */ 45int check_index;/* preimage must match the indexed version */ 46int update_index;/* check_index && apply */ 47 48/* These control cosmetic aspect of the output */ 49int diffstat;/* just show a diffstat, and don't actually apply */ 50int numstat;/* just show a numeric diffstat, and don't actually apply */ 51int summary;/* just report creation, deletion, etc, and don't actually apply */ 52 53/* These boolean parameters control how the apply is done */ 54int allow_overlap; 55int apply_in_reverse; 56int apply_with_reject; 57int apply_verbosely; 58int no_add; 59int threeway; 60int unidiff_zero; 61int unsafe_paths; 62 63/* Other non boolean parameters */ 64const char*fake_ancestor; 65const char*patch_input_file; 66int line_termination; 67struct strbuf root; 68int p_value; 69int p_value_known; 70unsigned int p_context; 71 72/* Exclude and include path parameters */ 73struct string_list limit_by_name; 74int has_include; 75 76/* 77 * For "diff-stat" like behaviour, we keep track of the biggest change 78 * we've seen, and the longest filename. That allows us to do simple 79 * scaling. 80 */ 81int max_change; 82int max_len; 83 84/* These control whitespace errors */ 85enum ws_error_action ws_error_action; 86enum ws_ignore ws_ignore_action; 87const char*whitespace_option; 88int whitespace_error; 89int squelch_whitespace_errors; 90int applied_after_fixing_ws; 91}; 92 93static int newfd = -1; 94 95static const char*const apply_usage[] = { 96N_("git apply [<options>] [<patch>...]"), 97 NULL 98}; 99 100static voidparse_whitespace_option(struct apply_state *state,const char*option) 101{ 102if(!option) { 103 state->ws_error_action = warn_on_ws_error; 104return; 105} 106if(!strcmp(option,"warn")) { 107 state->ws_error_action = warn_on_ws_error; 108return; 109} 110if(!strcmp(option,"nowarn")) { 111 state->ws_error_action = nowarn_ws_error; 112return; 113} 114if(!strcmp(option,"error")) { 115 state->ws_error_action = die_on_ws_error; 116return; 117} 118if(!strcmp(option,"error-all")) { 119 state->ws_error_action = die_on_ws_error; 120 state->squelch_whitespace_errors =0; 121return; 122} 123if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 124 state->ws_error_action = correct_ws_error; 125return; 126} 127die(_("unrecognized whitespace option '%s'"), option); 128} 129 130static voidparse_ignorewhitespace_option(struct apply_state *state, 131const char*option) 132{ 133if(!option || !strcmp(option,"no") || 134!strcmp(option,"false") || !strcmp(option,"never") || 135!strcmp(option,"none")) { 136 state->ws_ignore_action = ignore_ws_none; 137return; 138} 139if(!strcmp(option,"change")) { 140 state->ws_ignore_action = ignore_ws_change; 141return; 142} 143die(_("unrecognized whitespace ignore option '%s'"), option); 144} 145 146static voidset_default_whitespace_mode(struct apply_state *state) 147{ 148if(!state->whitespace_option && !apply_default_whitespace) 149 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 150} 151 152/* 153 * Various "current state", notably line numbers and what 154 * file (and how) we're patching right now.. The "is_xxxx" 155 * things are flags, where -1 means "don't know yet". 156 */ 157static int state_linenr =1; 158 159/* 160 * This represents one "hunk" from a patch, starting with 161 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 162 * patch text is pointed at by patch, and its byte length 163 * is stored in size. leading and trailing are the number 164 * of context lines. 165 */ 166struct fragment { 167unsigned long leading, trailing; 168unsigned long oldpos, oldlines; 169unsigned long newpos, newlines; 170/* 171 * 'patch' is usually borrowed from buf in apply_patch(), 172 * but some codepaths store an allocated buffer. 173 */ 174const char*patch; 175unsigned free_patch:1, 176 rejected:1; 177int size; 178int linenr; 179struct fragment *next; 180}; 181 182/* 183 * When dealing with a binary patch, we reuse "leading" field 184 * to store the type of the binary hunk, either deflated "delta" 185 * or deflated "literal". 186 */ 187#define binary_patch_method leading 188#define BINARY_DELTA_DEFLATED 1 189#define BINARY_LITERAL_DEFLATED 2 190 191/* 192 * This represents a "patch" to a file, both metainfo changes 193 * such as creation/deletion, filemode and content changes represented 194 * as a series of fragments. 195 */ 196struct patch { 197char*new_name, *old_name, *def_name; 198unsigned int old_mode, new_mode; 199int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 200int rejected; 201unsigned ws_rule; 202int lines_added, lines_deleted; 203int score; 204unsigned int is_toplevel_relative:1; 205unsigned int inaccurate_eof:1; 206unsigned int is_binary:1; 207unsigned int is_copy:1; 208unsigned int is_rename:1; 209unsigned int recount:1; 210unsigned int conflicted_threeway:1; 211unsigned int direct_to_threeway:1; 212struct fragment *fragments; 213char*result; 214size_t resultsize; 215char old_sha1_prefix[41]; 216char new_sha1_prefix[41]; 217struct patch *next; 218 219/* three-way fallback result */ 220struct object_id threeway_stage[3]; 221}; 222 223static voidfree_fragment_list(struct fragment *list) 224{ 225while(list) { 226struct fragment *next = list->next; 227if(list->free_patch) 228free((char*)list->patch); 229free(list); 230 list = next; 231} 232} 233 234static voidfree_patch(struct patch *patch) 235{ 236free_fragment_list(patch->fragments); 237free(patch->def_name); 238free(patch->old_name); 239free(patch->new_name); 240free(patch->result); 241free(patch); 242} 243 244static voidfree_patch_list(struct patch *list) 245{ 246while(list) { 247struct patch *next = list->next; 248free_patch(list); 249 list = next; 250} 251} 252 253/* 254 * A line in a file, len-bytes long (includes the terminating LF, 255 * except for an incomplete line at the end if the file ends with 256 * one), and its contents hashes to 'hash'. 257 */ 258struct line { 259size_t len; 260unsigned hash :24; 261unsigned flag :8; 262#define LINE_COMMON 1 263#define LINE_PATCHED 2 264}; 265 266/* 267 * This represents a "file", which is an array of "lines". 268 */ 269struct image { 270char*buf; 271size_t len; 272size_t nr; 273size_t alloc; 274struct line *line_allocated; 275struct line *line; 276}; 277 278/* 279 * Records filenames that have been touched, in order to handle 280 * the case where more than one patches touch the same file. 281 */ 282 283static struct string_list fn_table; 284 285static uint32_thash_line(const char*cp,size_t len) 286{ 287size_t i; 288uint32_t h; 289for(i =0, h =0; i < len; i++) { 290if(!isspace(cp[i])) { 291 h = h *3+ (cp[i] &0xff); 292} 293} 294return h; 295} 296 297/* 298 * Compare lines s1 of length n1 and s2 of length n2, ignoring 299 * whitespace difference. Returns 1 if they match, 0 otherwise 300 */ 301static intfuzzy_matchlines(const char*s1,size_t n1, 302const char*s2,size_t n2) 303{ 304const char*last1 = s1 + n1 -1; 305const char*last2 = s2 + n2 -1; 306int result =0; 307 308/* ignore line endings */ 309while((*last1 =='\r') || (*last1 =='\n')) 310 last1--; 311while((*last2 =='\r') || (*last2 =='\n')) 312 last2--; 313 314/* skip leading whitespaces, if both begin with whitespace */ 315if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 316while(isspace(*s1) && (s1 <= last1)) 317 s1++; 318while(isspace(*s2) && (s2 <= last2)) 319 s2++; 320} 321/* early return if both lines are empty */ 322if((s1 > last1) && (s2 > last2)) 323return1; 324while(!result) { 325 result = *s1++ - *s2++; 326/* 327 * Skip whitespace inside. We check for whitespace on 328 * both buffers because we don't want "a b" to match 329 * "ab" 330 */ 331if(isspace(*s1) &&isspace(*s2)) { 332while(isspace(*s1) && s1 <= last1) 333 s1++; 334while(isspace(*s2) && s2 <= last2) 335 s2++; 336} 337/* 338 * If we reached the end on one side only, 339 * lines don't match 340 */ 341if( 342((s2 > last2) && (s1 <= last1)) || 343((s1 > last1) && (s2 <= last2))) 344return0; 345if((s1 > last1) && (s2 > last2)) 346break; 347} 348 349return!result; 350} 351 352static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 353{ 354ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 355 img->line_allocated[img->nr].len = len; 356 img->line_allocated[img->nr].hash =hash_line(bol, len); 357 img->line_allocated[img->nr].flag = flag; 358 img->nr++; 359} 360 361/* 362 * "buf" has the file contents to be patched (read from various sources). 363 * attach it to "image" and add line-based index to it. 364 * "image" now owns the "buf". 365 */ 366static voidprepare_image(struct image *image,char*buf,size_t len, 367int prepare_linetable) 368{ 369const char*cp, *ep; 370 371memset(image,0,sizeof(*image)); 372 image->buf = buf; 373 image->len = len; 374 375if(!prepare_linetable) 376return; 377 378 ep = image->buf + image->len; 379 cp = image->buf; 380while(cp < ep) { 381const char*next; 382for(next = cp; next < ep && *next !='\n'; next++) 383; 384if(next < ep) 385 next++; 386add_line_info(image, cp, next - cp,0); 387 cp = next; 388} 389 image->line = image->line_allocated; 390} 391 392static voidclear_image(struct image *image) 393{ 394free(image->buf); 395free(image->line_allocated); 396memset(image,0,sizeof(*image)); 397} 398 399/* fmt must contain _one_ %s and no other substitution */ 400static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 401{ 402struct strbuf sb = STRBUF_INIT; 403 404if(patch->old_name && patch->new_name && 405strcmp(patch->old_name, patch->new_name)) { 406quote_c_style(patch->old_name, &sb, NULL,0); 407strbuf_addstr(&sb," => "); 408quote_c_style(patch->new_name, &sb, NULL,0); 409}else{ 410const char*n = patch->new_name; 411if(!n) 412 n = patch->old_name; 413quote_c_style(n, &sb, NULL,0); 414} 415fprintf(output, fmt, sb.buf); 416fputc('\n', output); 417strbuf_release(&sb); 418} 419 420#define SLOP (16) 421 422static voidread_patch_file(struct strbuf *sb,int fd) 423{ 424if(strbuf_read(sb, fd,0) <0) 425die_errno("git apply: failed to read"); 426 427/* 428 * Make sure that we have some slop in the buffer 429 * so that we can do speculative "memcmp" etc, and 430 * see to it that it is NUL-filled. 431 */ 432strbuf_grow(sb, SLOP); 433memset(sb->buf + sb->len,0, SLOP); 434} 435 436static unsigned longlinelen(const char*buffer,unsigned long size) 437{ 438unsigned long len =0; 439while(size--) { 440 len++; 441if(*buffer++ =='\n') 442break; 443} 444return len; 445} 446 447static intis_dev_null(const char*str) 448{ 449returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 450} 451 452#define TERM_SPACE 1 453#define TERM_TAB 2 454 455static intname_terminate(const char*name,int namelen,int c,int terminate) 456{ 457if(c ==' '&& !(terminate & TERM_SPACE)) 458return0; 459if(c =='\t'&& !(terminate & TERM_TAB)) 460return0; 461 462return1; 463} 464 465/* remove double slashes to make --index work with such filenames */ 466static char*squash_slash(char*name) 467{ 468int i =0, j =0; 469 470if(!name) 471return NULL; 472 473while(name[i]) { 474if((name[j++] = name[i++]) =='/') 475while(name[i] =='/') 476 i++; 477} 478 name[j] ='\0'; 479return name; 480} 481 482static char*find_name_gnu(struct apply_state *state, 483const char*line, 484const char*def, 485int p_value) 486{ 487struct strbuf name = STRBUF_INIT; 488char*cp; 489 490/* 491 * Proposed "new-style" GNU patch/diff format; see 492 * http://marc.info/?l=git&m=112927316408690&w=2 493 */ 494if(unquote_c_style(&name, line, NULL)) { 495strbuf_release(&name); 496return NULL; 497} 498 499for(cp = name.buf; p_value; p_value--) { 500 cp =strchr(cp,'/'); 501if(!cp) { 502strbuf_release(&name); 503return NULL; 504} 505 cp++; 506} 507 508strbuf_remove(&name,0, cp - name.buf); 509if(state->root.len) 510strbuf_insert(&name,0, state->root.buf, state->root.len); 511returnsquash_slash(strbuf_detach(&name, NULL)); 512} 513 514static size_tsane_tz_len(const char*line,size_t len) 515{ 516const char*tz, *p; 517 518if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 519return0; 520 tz = line + len -strlen(" +0500"); 521 522if(tz[1] !='+'&& tz[1] !='-') 523return0; 524 525for(p = tz +2; p != line + len; p++) 526if(!isdigit(*p)) 527return0; 528 529return line + len - tz; 530} 531 532static size_ttz_with_colon_len(const char*line,size_t len) 533{ 534const char*tz, *p; 535 536if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 537return0; 538 tz = line + len -strlen(" +08:00"); 539 540if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 541return0; 542 p = tz +2; 543if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 544!isdigit(*p++) || !isdigit(*p++)) 545return0; 546 547return line + len - tz; 548} 549 550static size_tdate_len(const char*line,size_t len) 551{ 552const char*date, *p; 553 554if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 555return0; 556 p = date = line + len -strlen("72-02-05"); 557 558if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 559!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 560!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 561return0; 562 563if(date - line >=strlen("19") && 564isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 565 date -=strlen("19"); 566 567return line + len - date; 568} 569 570static size_tshort_time_len(const char*line,size_t len) 571{ 572const char*time, *p; 573 574if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 575return0; 576 p = time = line + len -strlen(" 07:01:32"); 577 578/* Permit 1-digit hours? */ 579if(*p++ !=' '|| 580!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 581!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 582!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 583return0; 584 585return line + len - time; 586} 587 588static size_tfractional_time_len(const char*line,size_t len) 589{ 590const char*p; 591size_t n; 592 593/* Expected format: 19:41:17.620000023 */ 594if(!len || !isdigit(line[len -1])) 595return0; 596 p = line + len -1; 597 598/* Fractional seconds. */ 599while(p > line &&isdigit(*p)) 600 p--; 601if(*p !='.') 602return0; 603 604/* Hours, minutes, and whole seconds. */ 605 n =short_time_len(line, p - line); 606if(!n) 607return0; 608 609return line + len - p + n; 610} 611 612static size_ttrailing_spaces_len(const char*line,size_t len) 613{ 614const char*p; 615 616/* Expected format: ' ' x (1 or more) */ 617if(!len || line[len -1] !=' ') 618return0; 619 620 p = line + len; 621while(p != line) { 622 p--; 623if(*p !=' ') 624return line + len - (p +1); 625} 626 627/* All spaces! */ 628return len; 629} 630 631static size_tdiff_timestamp_len(const char*line,size_t len) 632{ 633const char*end = line + len; 634size_t n; 635 636/* 637 * Posix: 2010-07-05 19:41:17 638 * GNU: 2010-07-05 19:41:17.620000023 -0500 639 */ 640 641if(!isdigit(end[-1])) 642return0; 643 644 n =sane_tz_len(line, end - line); 645if(!n) 646 n =tz_with_colon_len(line, end - line); 647 end -= n; 648 649 n =short_time_len(line, end - line); 650if(!n) 651 n =fractional_time_len(line, end - line); 652 end -= n; 653 654 n =date_len(line, end - line); 655if(!n)/* No date. Too bad. */ 656return0; 657 end -= n; 658 659if(end == line)/* No space before date. */ 660return0; 661if(end[-1] =='\t') {/* Success! */ 662 end--; 663return line + len - end; 664} 665if(end[-1] !=' ')/* No space before date. */ 666return0; 667 668/* Whitespace damage. */ 669 end -=trailing_spaces_len(line, end - line); 670return line + len - end; 671} 672 673static char*find_name_common(struct apply_state *state, 674const char*line, 675const char*def, 676int p_value, 677const char*end, 678int terminate) 679{ 680int len; 681const char*start = NULL; 682 683if(p_value ==0) 684 start = line; 685while(line != end) { 686char c = *line; 687 688if(!end &&isspace(c)) { 689if(c =='\n') 690break; 691if(name_terminate(start, line-start, c, terminate)) 692break; 693} 694 line++; 695if(c =='/'&& !--p_value) 696 start = line; 697} 698if(!start) 699returnsquash_slash(xstrdup_or_null(def)); 700 len = line - start; 701if(!len) 702returnsquash_slash(xstrdup_or_null(def)); 703 704/* 705 * Generally we prefer the shorter name, especially 706 * if the other one is just a variation of that with 707 * something else tacked on to the end (ie "file.orig" 708 * or "file~"). 709 */ 710if(def) { 711int deflen =strlen(def); 712if(deflen < len && !strncmp(start, def, deflen)) 713returnsquash_slash(xstrdup(def)); 714} 715 716if(state->root.len) { 717char*ret =xstrfmt("%s%.*s", state->root.buf, len, start); 718returnsquash_slash(ret); 719} 720 721returnsquash_slash(xmemdupz(start, len)); 722} 723 724static char*find_name(struct apply_state *state, 725const char*line, 726char*def, 727int p_value, 728int terminate) 729{ 730if(*line =='"') { 731char*name =find_name_gnu(state, line, def, p_value); 732if(name) 733return name; 734} 735 736returnfind_name_common(state, line, def, p_value, NULL, terminate); 737} 738 739static char*find_name_traditional(struct apply_state *state, 740const char*line, 741char*def, 742int p_value) 743{ 744size_t len; 745size_t date_len; 746 747if(*line =='"') { 748char*name =find_name_gnu(state, line, def, p_value); 749if(name) 750return name; 751} 752 753 len =strchrnul(line,'\n') - line; 754 date_len =diff_timestamp_len(line, len); 755if(!date_len) 756returnfind_name_common(state, line, def, p_value, NULL, TERM_TAB); 757 len -= date_len; 758 759returnfind_name_common(state, line, def, p_value, line + len,0); 760} 761 762static intcount_slashes(const char*cp) 763{ 764int cnt =0; 765char ch; 766 767while((ch = *cp++)) 768if(ch =='/') 769 cnt++; 770return cnt; 771} 772 773/* 774 * Given the string after "--- " or "+++ ", guess the appropriate 775 * p_value for the given patch. 776 */ 777static intguess_p_value(struct apply_state *state,const char*nameline) 778{ 779char*name, *cp; 780int val = -1; 781 782if(is_dev_null(nameline)) 783return-1; 784 name =find_name_traditional(state, nameline, NULL,0); 785if(!name) 786return-1; 787 cp =strchr(name,'/'); 788if(!cp) 789 val =0; 790else if(state->prefix) { 791/* 792 * Does it begin with "a/$our-prefix" and such? Then this is 793 * very likely to apply to our directory. 794 */ 795if(!strncmp(name, state->prefix, state->prefix_length)) 796 val =count_slashes(state->prefix); 797else{ 798 cp++; 799if(!strncmp(cp, state->prefix, state->prefix_length)) 800 val =count_slashes(state->prefix) +1; 801} 802} 803free(name); 804return val; 805} 806 807/* 808 * Does the ---/+++ line have the POSIX timestamp after the last HT? 809 * GNU diff puts epoch there to signal a creation/deletion event. Is 810 * this such a timestamp? 811 */ 812static inthas_epoch_timestamp(const char*nameline) 813{ 814/* 815 * We are only interested in epoch timestamp; any non-zero 816 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 817 * For the same reason, the date must be either 1969-12-31 or 818 * 1970-01-01, and the seconds part must be "00". 819 */ 820const char stamp_regexp[] = 821"^(1969-12-31|1970-01-01)" 822" " 823"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 824" " 825"([-+][0-2][0-9]:?[0-5][0-9])\n"; 826const char*timestamp = NULL, *cp, *colon; 827static regex_t *stamp; 828 regmatch_t m[10]; 829int zoneoffset; 830int hourminute; 831int status; 832 833for(cp = nameline; *cp !='\n'; cp++) { 834if(*cp =='\t') 835 timestamp = cp +1; 836} 837if(!timestamp) 838return0; 839if(!stamp) { 840 stamp =xmalloc(sizeof(*stamp)); 841if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 842warning(_("Cannot prepare timestamp regexp%s"), 843 stamp_regexp); 844return0; 845} 846} 847 848 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 849if(status) { 850if(status != REG_NOMATCH) 851warning(_("regexec returned%dfor input:%s"), 852 status, timestamp); 853return0; 854} 855 856 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 857if(*colon ==':') 858 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 859else 860 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 861if(timestamp[m[3].rm_so] =='-') 862 zoneoffset = -zoneoffset; 863 864/* 865 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 866 * (west of GMT) or 1970-01-01 (east of GMT) 867 */ 868if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 869(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 870return0; 871 872 hourminute = (strtol(timestamp +11, NULL,10) *60+ 873strtol(timestamp +14, NULL,10) - 874 zoneoffset); 875 876return((zoneoffset <0&& hourminute ==1440) || 877(0<= zoneoffset && !hourminute)); 878} 879 880/* 881 * Get the name etc info from the ---/+++ lines of a traditional patch header 882 * 883 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 884 * files, we can happily check the index for a match, but for creating a 885 * new file we should try to match whatever "patch" does. I have no idea. 886 */ 887static voidparse_traditional_patch(struct apply_state *state, 888const char*first, 889const char*second, 890struct patch *patch) 891{ 892char*name; 893 894 first +=4;/* skip "--- " */ 895 second +=4;/* skip "+++ " */ 896if(!state->p_value_known) { 897int p, q; 898 p =guess_p_value(state, first); 899 q =guess_p_value(state, second); 900if(p <0) p = q; 901if(0<= p && p == q) { 902 state->p_value = p; 903 state->p_value_known =1; 904} 905} 906if(is_dev_null(first)) { 907 patch->is_new =1; 908 patch->is_delete =0; 909 name =find_name_traditional(state, second, NULL, state->p_value); 910 patch->new_name = name; 911}else if(is_dev_null(second)) { 912 patch->is_new =0; 913 patch->is_delete =1; 914 name =find_name_traditional(state, first, NULL, state->p_value); 915 patch->old_name = name; 916}else{ 917char*first_name; 918 first_name =find_name_traditional(state, first, NULL, state->p_value); 919 name =find_name_traditional(state, second, first_name, state->p_value); 920free(first_name); 921if(has_epoch_timestamp(first)) { 922 patch->is_new =1; 923 patch->is_delete =0; 924 patch->new_name = name; 925}else if(has_epoch_timestamp(second)) { 926 patch->is_new =0; 927 patch->is_delete =1; 928 patch->old_name = name; 929}else{ 930 patch->old_name = name; 931 patch->new_name =xstrdup_or_null(name); 932} 933} 934if(!name) 935die(_("unable to find filename in patch at line%d"), state_linenr); 936} 937 938static intgitdiff_hdrend(struct apply_state *state, 939const char*line, 940struct patch *patch) 941{ 942return-1; 943} 944 945/* 946 * We're anal about diff header consistency, to make 947 * sure that we don't end up having strange ambiguous 948 * patches floating around. 949 * 950 * As a result, gitdiff_{old|new}name() will check 951 * their names against any previous information, just 952 * to make sure.. 953 */ 954#define DIFF_OLD_NAME 0 955#define DIFF_NEW_NAME 1 956 957static voidgitdiff_verify_name(struct apply_state *state, 958const char*line, 959int isnull, 960char**name, 961int side) 962{ 963if(!*name && !isnull) { 964*name =find_name(state, line, NULL, state->p_value, TERM_TAB); 965return; 966} 967 968if(*name) { 969int len =strlen(*name); 970char*another; 971if(isnull) 972die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 973*name, state_linenr); 974 another =find_name(state, line, NULL, state->p_value, TERM_TAB); 975if(!another ||memcmp(another, *name, len +1)) 976die((side == DIFF_NEW_NAME) ? 977_("git apply: bad git-diff - inconsistent new filename on line%d") : 978_("git apply: bad git-diff - inconsistent old filename on line%d"), state_linenr); 979free(another); 980}else{ 981/* expect "/dev/null" */ 982if(memcmp("/dev/null", line,9) || line[9] !='\n') 983die(_("git apply: bad git-diff - expected /dev/null on line%d"), state_linenr); 984} 985} 986 987static intgitdiff_oldname(struct apply_state *state, 988const char*line, 989struct patch *patch) 990{ 991gitdiff_verify_name(state, line, 992 patch->is_new, &patch->old_name, 993 DIFF_OLD_NAME); 994return0; 995} 996 997static intgitdiff_newname(struct apply_state *state, 998const char*line, 999struct patch *patch)1000{1001gitdiff_verify_name(state, line,1002 patch->is_delete, &patch->new_name,1003 DIFF_NEW_NAME);1004return0;1005}10061007static intgitdiff_oldmode(struct apply_state *state,1008const char*line,1009struct patch *patch)1010{1011 patch->old_mode =strtoul(line, NULL,8);1012return0;1013}10141015static intgitdiff_newmode(struct apply_state *state,1016const char*line,1017struct patch *patch)1018{1019 patch->new_mode =strtoul(line, NULL,8);1020return0;1021}10221023static intgitdiff_delete(struct apply_state *state,1024const char*line,1025struct patch *patch)1026{1027 patch->is_delete =1;1028free(patch->old_name);1029 patch->old_name =xstrdup_or_null(patch->def_name);1030returngitdiff_oldmode(state, line, patch);1031}10321033static intgitdiff_newfile(struct apply_state *state,1034const char*line,1035struct patch *patch)1036{1037 patch->is_new =1;1038free(patch->new_name);1039 patch->new_name =xstrdup_or_null(patch->def_name);1040returngitdiff_newmode(state, line, patch);1041}10421043static intgitdiff_copysrc(struct apply_state *state,1044const char*line,1045struct patch *patch)1046{1047 patch->is_copy =1;1048free(patch->old_name);1049 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1050return0;1051}10521053static intgitdiff_copydst(struct apply_state *state,1054const char*line,1055struct patch *patch)1056{1057 patch->is_copy =1;1058free(patch->new_name);1059 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1060return0;1061}10621063static intgitdiff_renamesrc(struct apply_state *state,1064const char*line,1065struct patch *patch)1066{1067 patch->is_rename =1;1068free(patch->old_name);1069 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1070return0;1071}10721073static intgitdiff_renamedst(struct apply_state *state,1074const char*line,1075struct patch *patch)1076{1077 patch->is_rename =1;1078free(patch->new_name);1079 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1080return0;1081}10821083static intgitdiff_similarity(struct apply_state *state,1084const char*line,1085struct patch *patch)1086{1087unsigned long val =strtoul(line, NULL,10);1088if(val <=100)1089 patch->score = val;1090return0;1091}10921093static intgitdiff_dissimilarity(struct apply_state *state,1094const char*line,1095struct patch *patch)1096{1097unsigned long val =strtoul(line, NULL,10);1098if(val <=100)1099 patch->score = val;1100return0;1101}11021103static intgitdiff_index(struct apply_state *state,1104const char*line,1105struct patch *patch)1106{1107/*1108 * index line is N hexadecimal, "..", N hexadecimal,1109 * and optional space with octal mode.1110 */1111const char*ptr, *eol;1112int len;11131114 ptr =strchr(line,'.');1115if(!ptr || ptr[1] !='.'||40< ptr - line)1116return0;1117 len = ptr - line;1118memcpy(patch->old_sha1_prefix, line, len);1119 patch->old_sha1_prefix[len] =0;11201121 line = ptr +2;1122 ptr =strchr(line,' ');1123 eol =strchrnul(line,'\n');11241125if(!ptr || eol < ptr)1126 ptr = eol;1127 len = ptr - line;11281129if(40< len)1130return0;1131memcpy(patch->new_sha1_prefix, line, len);1132 patch->new_sha1_prefix[len] =0;1133if(*ptr ==' ')1134 patch->old_mode =strtoul(ptr+1, NULL,8);1135return0;1136}11371138/*1139 * This is normal for a diff that doesn't change anything: we'll fall through1140 * into the next diff. Tell the parser to break out.1141 */1142static intgitdiff_unrecognized(struct apply_state *state,1143const char*line,1144struct patch *patch)1145{1146return-1;1147}11481149/*1150 * Skip p_value leading components from "line"; as we do not accept1151 * absolute paths, return NULL in that case.1152 */1153static const char*skip_tree_prefix(struct apply_state *state,1154const char*line,1155int llen)1156{1157int nslash;1158int i;11591160if(!state->p_value)1161return(llen && line[0] =='/') ? NULL : line;11621163 nslash = state->p_value;1164for(i =0; i < llen; i++) {1165int ch = line[i];1166if(ch =='/'&& --nslash <=0)1167return(i ==0) ? NULL : &line[i +1];1168}1169return NULL;1170}11711172/*1173 * This is to extract the same name that appears on "diff --git"1174 * line. We do not find and return anything if it is a rename1175 * patch, and it is OK because we will find the name elsewhere.1176 * We need to reliably find name only when it is mode-change only,1177 * creation or deletion of an empty file. In any of these cases,1178 * both sides are the same name under a/ and b/ respectively.1179 */1180static char*git_header_name(struct apply_state *state,1181const char*line,1182int llen)1183{1184const char*name;1185const char*second = NULL;1186size_t len, line_len;11871188 line +=strlen("diff --git ");1189 llen -=strlen("diff --git ");11901191if(*line =='"') {1192const char*cp;1193struct strbuf first = STRBUF_INIT;1194struct strbuf sp = STRBUF_INIT;11951196if(unquote_c_style(&first, line, &second))1197goto free_and_fail1;11981199/* strip the a/b prefix including trailing slash */1200 cp =skip_tree_prefix(state, first.buf, first.len);1201if(!cp)1202goto free_and_fail1;1203strbuf_remove(&first,0, cp - first.buf);12041205/*1206 * second points at one past closing dq of name.1207 * find the second name.1208 */1209while((second < line + llen) &&isspace(*second))1210 second++;12111212if(line + llen <= second)1213goto free_and_fail1;1214if(*second =='"') {1215if(unquote_c_style(&sp, second, NULL))1216goto free_and_fail1;1217 cp =skip_tree_prefix(state, sp.buf, sp.len);1218if(!cp)1219goto free_and_fail1;1220/* They must match, otherwise ignore */1221if(strcmp(cp, first.buf))1222goto free_and_fail1;1223strbuf_release(&sp);1224returnstrbuf_detach(&first, NULL);1225}12261227/* unquoted second */1228 cp =skip_tree_prefix(state, second, line + llen - second);1229if(!cp)1230goto free_and_fail1;1231if(line + llen - cp != first.len ||1232memcmp(first.buf, cp, first.len))1233goto free_and_fail1;1234returnstrbuf_detach(&first, NULL);12351236 free_and_fail1:1237strbuf_release(&first);1238strbuf_release(&sp);1239return NULL;1240}12411242/* unquoted first name */1243 name =skip_tree_prefix(state, line, llen);1244if(!name)1245return NULL;12461247/*1248 * since the first name is unquoted, a dq if exists must be1249 * the beginning of the second name.1250 */1251for(second = name; second < line + llen; second++) {1252if(*second =='"') {1253struct strbuf sp = STRBUF_INIT;1254const char*np;12551256if(unquote_c_style(&sp, second, NULL))1257goto free_and_fail2;12581259 np =skip_tree_prefix(state, sp.buf, sp.len);1260if(!np)1261goto free_and_fail2;12621263 len = sp.buf + sp.len - np;1264if(len < second - name &&1265!strncmp(np, name, len) &&1266isspace(name[len])) {1267/* Good */1268strbuf_remove(&sp,0, np - sp.buf);1269returnstrbuf_detach(&sp, NULL);1270}12711272 free_and_fail2:1273strbuf_release(&sp);1274return NULL;1275}1276}12771278/*1279 * Accept a name only if it shows up twice, exactly the same1280 * form.1281 */1282 second =strchr(name,'\n');1283if(!second)1284return NULL;1285 line_len = second - name;1286for(len =0; ; len++) {1287switch(name[len]) {1288default:1289continue;1290case'\n':1291return NULL;1292case'\t':case' ':1293/*1294 * Is this the separator between the preimage1295 * and the postimage pathname? Again, we are1296 * only interested in the case where there is1297 * no rename, as this is only to set def_name1298 * and a rename patch has the names elsewhere1299 * in an unambiguous form.1300 */1301if(!name[len +1])1302return NULL;/* no postimage name */1303 second =skip_tree_prefix(state, name + len +1,1304 line_len - (len +1));1305if(!second)1306return NULL;1307/*1308 * Does len bytes starting at "name" and "second"1309 * (that are separated by one HT or SP we just1310 * found) exactly match?1311 */1312if(second[len] =='\n'&& !strncmp(name, second, len))1313returnxmemdupz(name, len);1314}1315}1316}13171318/* Verify that we recognize the lines following a git header */1319static intparse_git_header(struct apply_state *state,1320const char*line,1321int len,1322unsigned int size,1323struct patch *patch)1324{1325unsigned long offset;13261327/* A git diff has explicit new/delete information, so we don't guess */1328 patch->is_new =0;1329 patch->is_delete =0;13301331/*1332 * Some things may not have the old name in the1333 * rest of the headers anywhere (pure mode changes,1334 * or removing or adding empty files), so we get1335 * the default name from the header.1336 */1337 patch->def_name =git_header_name(state, line, len);1338if(patch->def_name && state->root.len) {1339char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1340free(patch->def_name);1341 patch->def_name = s;1342}13431344 line += len;1345 size -= len;1346 state_linenr++;1347for(offset = len ; size >0; offset += len, size -= len, line += len, state_linenr++) {1348static const struct opentry {1349const char*str;1350int(*fn)(struct apply_state *,const char*,struct patch *);1351} optable[] = {1352{"@@ -", gitdiff_hdrend },1353{"--- ", gitdiff_oldname },1354{"+++ ", gitdiff_newname },1355{"old mode ", gitdiff_oldmode },1356{"new mode ", gitdiff_newmode },1357{"deleted file mode ", gitdiff_delete },1358{"new file mode ", gitdiff_newfile },1359{"copy from ", gitdiff_copysrc },1360{"copy to ", gitdiff_copydst },1361{"rename old ", gitdiff_renamesrc },1362{"rename new ", gitdiff_renamedst },1363{"rename from ", gitdiff_renamesrc },1364{"rename to ", gitdiff_renamedst },1365{"similarity index ", gitdiff_similarity },1366{"dissimilarity index ", gitdiff_dissimilarity },1367{"index ", gitdiff_index },1368{"", gitdiff_unrecognized },1369};1370int i;13711372 len =linelen(line, size);1373if(!len || line[len-1] !='\n')1374break;1375for(i =0; i <ARRAY_SIZE(optable); i++) {1376const struct opentry *p = optable + i;1377int oplen =strlen(p->str);1378if(len < oplen ||memcmp(p->str, line, oplen))1379continue;1380if(p->fn(state, line + oplen, patch) <0)1381return offset;1382break;1383}1384}13851386return offset;1387}13881389static intparse_num(const char*line,unsigned long*p)1390{1391char*ptr;13921393if(!isdigit(*line))1394return0;1395*p =strtoul(line, &ptr,10);1396return ptr - line;1397}13981399static intparse_range(const char*line,int len,int offset,const char*expect,1400unsigned long*p1,unsigned long*p2)1401{1402int digits, ex;14031404if(offset <0|| offset >= len)1405return-1;1406 line += offset;1407 len -= offset;14081409 digits =parse_num(line, p1);1410if(!digits)1411return-1;14121413 offset += digits;1414 line += digits;1415 len -= digits;14161417*p2 =1;1418if(*line ==',') {1419 digits =parse_num(line+1, p2);1420if(!digits)1421return-1;14221423 offset += digits+1;1424 line += digits+1;1425 len -= digits+1;1426}14271428 ex =strlen(expect);1429if(ex > len)1430return-1;1431if(memcmp(line, expect, ex))1432return-1;14331434return offset + ex;1435}14361437static voidrecount_diff(const char*line,int size,struct fragment *fragment)1438{1439int oldlines =0, newlines =0, ret =0;14401441if(size <1) {1442warning("recount: ignore empty hunk");1443return;1444}14451446for(;;) {1447int len =linelen(line, size);1448 size -= len;1449 line += len;14501451if(size <1)1452break;14531454switch(*line) {1455case' ':case'\n':1456 newlines++;1457/* fall through */1458case'-':1459 oldlines++;1460continue;1461case'+':1462 newlines++;1463continue;1464case'\\':1465continue;1466case'@':1467 ret = size <3|| !starts_with(line,"@@ ");1468break;1469case'd':1470 ret = size <5|| !starts_with(line,"diff ");1471break;1472default:1473 ret = -1;1474break;1475}1476if(ret) {1477warning(_("recount: unexpected line: %.*s"),1478(int)linelen(line, size), line);1479return;1480}1481break;1482}1483 fragment->oldlines = oldlines;1484 fragment->newlines = newlines;1485}14861487/*1488 * Parse a unified diff fragment header of the1489 * form "@@ -a,b +c,d @@"1490 */1491static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1492{1493int offset;14941495if(!len || line[len-1] !='\n')1496return-1;14971498/* Figure out the number of lines in a fragment */1499 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1500 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);15011502return offset;1503}15041505static intfind_header(struct apply_state *state,1506const char*line,1507unsigned long size,1508int*hdrsize,1509struct patch *patch)1510{1511unsigned long offset, len;15121513 patch->is_toplevel_relative =0;1514 patch->is_rename = patch->is_copy =0;1515 patch->is_new = patch->is_delete = -1;1516 patch->old_mode = patch->new_mode =0;1517 patch->old_name = patch->new_name = NULL;1518for(offset =0; size >0; offset += len, size -= len, line += len, state_linenr++) {1519unsigned long nextlen;15201521 len =linelen(line, size);1522if(!len)1523break;15241525/* Testing this early allows us to take a few shortcuts.. */1526if(len <6)1527continue;15281529/*1530 * Make sure we don't find any unconnected patch fragments.1531 * That's a sign that we didn't find a header, and that a1532 * patch has become corrupted/broken up.1533 */1534if(!memcmp("@@ -", line,4)) {1535struct fragment dummy;1536if(parse_fragment_header(line, len, &dummy) <0)1537continue;1538die(_("patch fragment without header at line%d: %.*s"),1539 state_linenr, (int)len-1, line);1540}15411542if(size < len +6)1543break;15441545/*1546 * Git patch? It might not have a real patch, just a rename1547 * or mode change, so we handle that specially1548 */1549if(!memcmp("diff --git ", line,11)) {1550int git_hdr_len =parse_git_header(state, line, len, size, patch);1551if(git_hdr_len <= len)1552continue;1553if(!patch->old_name && !patch->new_name) {1554if(!patch->def_name)1555die(Q_("git diff header lacks filename information when removing "1556"%dleading pathname component (line%d)",1557"git diff header lacks filename information when removing "1558"%dleading pathname components (line%d)",1559 state->p_value),1560 state->p_value, state_linenr);1561 patch->old_name =xstrdup(patch->def_name);1562 patch->new_name =xstrdup(patch->def_name);1563}1564if(!patch->is_delete && !patch->new_name)1565die("git diff header lacks filename information "1566"(line%d)", state_linenr);1567 patch->is_toplevel_relative =1;1568*hdrsize = git_hdr_len;1569return offset;1570}15711572/* --- followed by +++ ? */1573if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1574continue;15751576/*1577 * We only accept unified patches, so we want it to1578 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1579 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1580 */1581 nextlen =linelen(line + len, size - len);1582if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1583continue;15841585/* Ok, we'll consider it a patch */1586parse_traditional_patch(state, line, line+len, patch);1587*hdrsize = len + nextlen;1588 state_linenr +=2;1589return offset;1590}1591return-1;1592}15931594static voidrecord_ws_error(struct apply_state *state,1595unsigned result,1596const char*line,1597int len,1598int linenr)1599{1600char*err;16011602if(!result)1603return;16041605 state->whitespace_error++;1606if(state->squelch_whitespace_errors &&1607 state->squelch_whitespace_errors < state->whitespace_error)1608return;16091610 err =whitespace_error_string(result);1611fprintf(stderr,"%s:%d:%s.\n%.*s\n",1612 state->patch_input_file, linenr, err, len, line);1613free(err);1614}16151616static voidcheck_whitespace(struct apply_state *state,1617const char*line,1618int len,1619unsigned ws_rule)1620{1621unsigned result =ws_check(line +1, len -1, ws_rule);16221623record_ws_error(state, result, line +1, len -2, state_linenr);1624}16251626/*1627 * Parse a unified diff. Note that this really needs to parse each1628 * fragment separately, since the only way to know the difference1629 * between a "---" that is part of a patch, and a "---" that starts1630 * the next patch is to look at the line counts..1631 */1632static intparse_fragment(struct apply_state *state,1633const char*line,1634unsigned long size,1635struct patch *patch,1636struct fragment *fragment)1637{1638int added, deleted;1639int len =linelen(line, size), offset;1640unsigned long oldlines, newlines;1641unsigned long leading, trailing;16421643 offset =parse_fragment_header(line, len, fragment);1644if(offset <0)1645return-1;1646if(offset >0&& patch->recount)1647recount_diff(line + offset, size - offset, fragment);1648 oldlines = fragment->oldlines;1649 newlines = fragment->newlines;1650 leading =0;1651 trailing =0;16521653/* Parse the thing.. */1654 line += len;1655 size -= len;1656 state_linenr++;1657 added = deleted =0;1658for(offset = len;16590< size;1660 offset += len, size -= len, line += len, state_linenr++) {1661if(!oldlines && !newlines)1662break;1663 len =linelen(line, size);1664if(!len || line[len-1] !='\n')1665return-1;1666switch(*line) {1667default:1668return-1;1669case'\n':/* newer GNU diff, an empty context line */1670case' ':1671 oldlines--;1672 newlines--;1673if(!deleted && !added)1674 leading++;1675 trailing++;1676if(!state->apply_in_reverse &&1677 state->ws_error_action == correct_ws_error)1678check_whitespace(state, line, len, patch->ws_rule);1679break;1680case'-':1681if(state->apply_in_reverse &&1682 state->ws_error_action != nowarn_ws_error)1683check_whitespace(state, line, len, patch->ws_rule);1684 deleted++;1685 oldlines--;1686 trailing =0;1687break;1688case'+':1689if(!state->apply_in_reverse &&1690 state->ws_error_action != nowarn_ws_error)1691check_whitespace(state, line, len, patch->ws_rule);1692 added++;1693 newlines--;1694 trailing =0;1695break;16961697/*1698 * We allow "\ No newline at end of file". Depending1699 * on locale settings when the patch was produced we1700 * don't know what this line looks like. The only1701 * thing we do know is that it begins with "\ ".1702 * Checking for 12 is just for sanity check -- any1703 * l10n of "\ No newline..." is at least that long.1704 */1705case'\\':1706if(len <12||memcmp(line,"\\",2))1707return-1;1708break;1709}1710}1711if(oldlines || newlines)1712return-1;1713if(!deleted && !added)1714return-1;17151716 fragment->leading = leading;1717 fragment->trailing = trailing;17181719/*1720 * If a fragment ends with an incomplete line, we failed to include1721 * it in the above loop because we hit oldlines == newlines == 01722 * before seeing it.1723 */1724if(12< size && !memcmp(line,"\\",2))1725 offset +=linelen(line, size);17261727 patch->lines_added += added;1728 patch->lines_deleted += deleted;17291730if(0< patch->is_new && oldlines)1731returnerror(_("new file depends on old contents"));1732if(0< patch->is_delete && newlines)1733returnerror(_("deleted file still has contents"));1734return offset;1735}17361737/*1738 * We have seen "diff --git a/... b/..." header (or a traditional patch1739 * header). Read hunks that belong to this patch into fragments and hang1740 * them to the given patch structure.1741 *1742 * The (fragment->patch, fragment->size) pair points into the memory given1743 * by the caller, not a copy, when we return.1744 */1745static intparse_single_patch(struct apply_state *state,1746const char*line,1747unsigned long size,1748struct patch *patch)1749{1750unsigned long offset =0;1751unsigned long oldlines =0, newlines =0, context =0;1752struct fragment **fragp = &patch->fragments;17531754while(size >4&& !memcmp(line,"@@ -",4)) {1755struct fragment *fragment;1756int len;17571758 fragment =xcalloc(1,sizeof(*fragment));1759 fragment->linenr = state_linenr;1760 len =parse_fragment(state, line, size, patch, fragment);1761if(len <=0)1762die(_("corrupt patch at line%d"), state_linenr);1763 fragment->patch = line;1764 fragment->size = len;1765 oldlines += fragment->oldlines;1766 newlines += fragment->newlines;1767 context += fragment->leading + fragment->trailing;17681769*fragp = fragment;1770 fragp = &fragment->next;17711772 offset += len;1773 line += len;1774 size -= len;1775}17761777/*1778 * If something was removed (i.e. we have old-lines) it cannot1779 * be creation, and if something was added it cannot be1780 * deletion. However, the reverse is not true; --unified=01781 * patches that only add are not necessarily creation even1782 * though they do not have any old lines, and ones that only1783 * delete are not necessarily deletion.1784 *1785 * Unfortunately, a real creation/deletion patch do _not_ have1786 * any context line by definition, so we cannot safely tell it1787 * apart with --unified=0 insanity. At least if the patch has1788 * more than one hunk it is not creation or deletion.1789 */1790if(patch->is_new <0&&1791(oldlines || (patch->fragments && patch->fragments->next)))1792 patch->is_new =0;1793if(patch->is_delete <0&&1794(newlines || (patch->fragments && patch->fragments->next)))1795 patch->is_delete =0;17961797if(0< patch->is_new && oldlines)1798die(_("new file%sdepends on old contents"), patch->new_name);1799if(0< patch->is_delete && newlines)1800die(_("deleted file%sstill has contents"), patch->old_name);1801if(!patch->is_delete && !newlines && context)1802fprintf_ln(stderr,1803_("** warning: "1804"file%sbecomes empty but is not deleted"),1805 patch->new_name);18061807return offset;1808}18091810staticinlineintmetadata_changes(struct patch *patch)1811{1812return patch->is_rename >0||1813 patch->is_copy >0||1814 patch->is_new >0||1815 patch->is_delete ||1816(patch->old_mode && patch->new_mode &&1817 patch->old_mode != patch->new_mode);1818}18191820static char*inflate_it(const void*data,unsigned long size,1821unsigned long inflated_size)1822{1823 git_zstream stream;1824void*out;1825int st;18261827memset(&stream,0,sizeof(stream));18281829 stream.next_in = (unsigned char*)data;1830 stream.avail_in = size;1831 stream.next_out = out =xmalloc(inflated_size);1832 stream.avail_out = inflated_size;1833git_inflate_init(&stream);1834 st =git_inflate(&stream, Z_FINISH);1835git_inflate_end(&stream);1836if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1837free(out);1838return NULL;1839}1840return out;1841}18421843/*1844 * Read a binary hunk and return a new fragment; fragment->patch1845 * points at an allocated memory that the caller must free, so1846 * it is marked as "->free_patch = 1".1847 */1848static struct fragment *parse_binary_hunk(char**buf_p,1849unsigned long*sz_p,1850int*status_p,1851int*used_p)1852{1853/*1854 * Expect a line that begins with binary patch method ("literal"1855 * or "delta"), followed by the length of data before deflating.1856 * a sequence of 'length-byte' followed by base-85 encoded data1857 * should follow, terminated by a newline.1858 *1859 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1860 * and we would limit the patch line to 66 characters,1861 * so one line can fit up to 13 groups that would decode1862 * to 52 bytes max. The length byte 'A'-'Z' corresponds1863 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1864 */1865int llen, used;1866unsigned long size = *sz_p;1867char*buffer = *buf_p;1868int patch_method;1869unsigned long origlen;1870char*data = NULL;1871int hunk_size =0;1872struct fragment *frag;18731874 llen =linelen(buffer, size);1875 used = llen;18761877*status_p =0;18781879if(starts_with(buffer,"delta ")) {1880 patch_method = BINARY_DELTA_DEFLATED;1881 origlen =strtoul(buffer +6, NULL,10);1882}1883else if(starts_with(buffer,"literal ")) {1884 patch_method = BINARY_LITERAL_DEFLATED;1885 origlen =strtoul(buffer +8, NULL,10);1886}1887else1888return NULL;18891890 state_linenr++;1891 buffer += llen;1892while(1) {1893int byte_length, max_byte_length, newsize;1894 llen =linelen(buffer, size);1895 used += llen;1896 state_linenr++;1897if(llen ==1) {1898/* consume the blank line */1899 buffer++;1900 size--;1901break;1902}1903/*1904 * Minimum line is "A00000\n" which is 7-byte long,1905 * and the line length must be multiple of 5 plus 2.1906 */1907if((llen <7) || (llen-2) %5)1908goto corrupt;1909 max_byte_length = (llen -2) /5*4;1910 byte_length = *buffer;1911if('A'<= byte_length && byte_length <='Z')1912 byte_length = byte_length -'A'+1;1913else if('a'<= byte_length && byte_length <='z')1914 byte_length = byte_length -'a'+27;1915else1916goto corrupt;1917/* if the input length was not multiple of 4, we would1918 * have filler at the end but the filler should never1919 * exceed 3 bytes1920 */1921if(max_byte_length < byte_length ||1922 byte_length <= max_byte_length -4)1923goto corrupt;1924 newsize = hunk_size + byte_length;1925 data =xrealloc(data, newsize);1926if(decode_85(data + hunk_size, buffer +1, byte_length))1927goto corrupt;1928 hunk_size = newsize;1929 buffer += llen;1930 size -= llen;1931}19321933 frag =xcalloc(1,sizeof(*frag));1934 frag->patch =inflate_it(data, hunk_size, origlen);1935 frag->free_patch =1;1936if(!frag->patch)1937goto corrupt;1938free(data);1939 frag->size = origlen;1940*buf_p = buffer;1941*sz_p = size;1942*used_p = used;1943 frag->binary_patch_method = patch_method;1944return frag;19451946 corrupt:1947free(data);1948*status_p = -1;1949error(_("corrupt binary patch at line%d: %.*s"),1950 state_linenr-1, llen-1, buffer);1951return NULL;1952}19531954/*1955 * Returns:1956 * -1 in case of error,1957 * the length of the parsed binary patch otherwise1958 */1959static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1960{1961/*1962 * We have read "GIT binary patch\n"; what follows is a line1963 * that says the patch method (currently, either "literal" or1964 * "delta") and the length of data before deflating; a1965 * sequence of 'length-byte' followed by base-85 encoded data1966 * follows.1967 *1968 * When a binary patch is reversible, there is another binary1969 * hunk in the same format, starting with patch method (either1970 * "literal" or "delta") with the length of data, and a sequence1971 * of length-byte + base-85 encoded data, terminated with another1972 * empty line. This data, when applied to the postimage, produces1973 * the preimage.1974 */1975struct fragment *forward;1976struct fragment *reverse;1977int status;1978int used, used_1;19791980 forward =parse_binary_hunk(&buffer, &size, &status, &used);1981if(!forward && !status)1982/* there has to be one hunk (forward hunk) */1983returnerror(_("unrecognized binary patch at line%d"), state_linenr-1);1984if(status)1985/* otherwise we already gave an error message */1986return status;19871988 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1989if(reverse)1990 used += used_1;1991else if(status) {1992/*1993 * Not having reverse hunk is not an error, but having1994 * a corrupt reverse hunk is.1995 */1996free((void*) forward->patch);1997free(forward);1998return status;1999}2000 forward->next = reverse;2001 patch->fragments = forward;2002 patch->is_binary =1;2003return used;2004}20052006static voidprefix_one(struct apply_state *state,char**name)2007{2008char*old_name = *name;2009if(!old_name)2010return;2011*name =xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));2012free(old_name);2013}20142015static voidprefix_patch(struct apply_state *state,struct patch *p)2016{2017if(!state->prefix || p->is_toplevel_relative)2018return;2019prefix_one(state, &p->new_name);2020prefix_one(state, &p->old_name);2021}20222023/*2024 * include/exclude2025 */20262027static voidadd_name_limit(struct apply_state *state,2028const char*name,2029int exclude)2030{2031struct string_list_item *it;20322033 it =string_list_append(&state->limit_by_name, name);2034 it->util = exclude ? NULL : (void*)1;2035}20362037static intuse_patch(struct apply_state *state,struct patch *p)2038{2039const char*pathname = p->new_name ? p->new_name : p->old_name;2040int i;20412042/* Paths outside are not touched regardless of "--include" */2043if(0< state->prefix_length) {2044int pathlen =strlen(pathname);2045if(pathlen <= state->prefix_length ||2046memcmp(state->prefix, pathname, state->prefix_length))2047return0;2048}20492050/* See if it matches any of exclude/include rule */2051for(i =0; i < state->limit_by_name.nr; i++) {2052struct string_list_item *it = &state->limit_by_name.items[i];2053if(!wildmatch(it->string, pathname,0, NULL))2054return(it->util != NULL);2055}20562057/*2058 * If we had any include, a path that does not match any rule is2059 * not used. Otherwise, we saw bunch of exclude rules (or none)2060 * and such a path is used.2061 */2062return!state->has_include;2063}206420652066/*2067 * Read the patch text in "buffer" that extends for "size" bytes; stop2068 * reading after seeing a single patch (i.e. changes to a single file).2069 * Create fragments (i.e. patch hunks) and hang them to the given patch.2070 * Return the number of bytes consumed, so that the caller can call us2071 * again for the next patch.2072 */2073static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2074{2075int hdrsize, patchsize;2076int offset =find_header(state, buffer, size, &hdrsize, patch);20772078if(offset <0)2079return offset;20802081prefix_patch(state, patch);20822083if(!use_patch(state, patch))2084 patch->ws_rule =0;2085else2086 patch->ws_rule =whitespace_rule(patch->new_name2087? patch->new_name2088: patch->old_name);20892090 patchsize =parse_single_patch(state,2091 buffer + offset + hdrsize,2092 size - offset - hdrsize,2093 patch);20942095if(!patchsize) {2096static const char git_binary[] ="GIT binary patch\n";2097int hd = hdrsize + offset;2098unsigned long llen =linelen(buffer + hd, size - hd);20992100if(llen ==sizeof(git_binary) -1&&2101!memcmp(git_binary, buffer + hd, llen)) {2102int used;2103 state_linenr++;2104 used =parse_binary(buffer + hd + llen,2105 size - hd - llen, patch);2106if(used <0)2107return-1;2108if(used)2109 patchsize = used + llen;2110else2111 patchsize =0;2112}2113else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2114static const char*binhdr[] = {2115"Binary files ",2116"Files ",2117 NULL,2118};2119int i;2120for(i =0; binhdr[i]; i++) {2121int len =strlen(binhdr[i]);2122if(len < size - hd &&2123!memcmp(binhdr[i], buffer + hd, len)) {2124 state_linenr++;2125 patch->is_binary =1;2126 patchsize = llen;2127break;2128}2129}2130}21312132/* Empty patch cannot be applied if it is a text patch2133 * without metadata change. A binary patch appears2134 * empty to us here.2135 */2136if((state->apply || state->check) &&2137(!patch->is_binary && !metadata_changes(patch)))2138die(_("patch with only garbage at line%d"), state_linenr);2139}21402141return offset + hdrsize + patchsize;2142}21432144#define swap(a,b) myswap((a),(b),sizeof(a))21452146#define myswap(a, b, size) do { \2147 unsigned char mytmp[size]; \2148 memcpy(mytmp, &a, size); \2149 memcpy(&a, &b, size); \2150 memcpy(&b, mytmp, size); \2151} while (0)21522153static voidreverse_patches(struct patch *p)2154{2155for(; p; p = p->next) {2156struct fragment *frag = p->fragments;21572158swap(p->new_name, p->old_name);2159swap(p->new_mode, p->old_mode);2160swap(p->is_new, p->is_delete);2161swap(p->lines_added, p->lines_deleted);2162swap(p->old_sha1_prefix, p->new_sha1_prefix);21632164for(; frag; frag = frag->next) {2165swap(frag->newpos, frag->oldpos);2166swap(frag->newlines, frag->oldlines);2167}2168}2169}21702171static const char pluses[] =2172"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2173static const char minuses[]=2174"----------------------------------------------------------------------";21752176static voidshow_stats(struct apply_state *state,struct patch *patch)2177{2178struct strbuf qname = STRBUF_INIT;2179char*cp = patch->new_name ? patch->new_name : patch->old_name;2180int max, add, del;21812182quote_c_style(cp, &qname, NULL,0);21832184/*2185 * "scale" the filename2186 */2187 max = state->max_len;2188if(max >50)2189 max =50;21902191if(qname.len > max) {2192 cp =strchr(qname.buf + qname.len +3- max,'/');2193if(!cp)2194 cp = qname.buf + qname.len +3- max;2195strbuf_splice(&qname,0, cp - qname.buf,"...",3);2196}21972198if(patch->is_binary) {2199printf(" %-*s | Bin\n", max, qname.buf);2200strbuf_release(&qname);2201return;2202}22032204printf(" %-*s |", max, qname.buf);2205strbuf_release(&qname);22062207/*2208 * scale the add/delete2209 */2210 max = max + state->max_change >70?70- max : state->max_change;2211 add = patch->lines_added;2212 del = patch->lines_deleted;22132214if(state->max_change >0) {2215int total = ((add + del) * max + state->max_change /2) / state->max_change;2216 add = (add * max + state->max_change /2) / state->max_change;2217 del = total - add;2218}2219printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2220 add, pluses, del, minuses);2221}22222223static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2224{2225switch(st->st_mode & S_IFMT) {2226case S_IFLNK:2227if(strbuf_readlink(buf, path, st->st_size) <0)2228returnerror(_("unable to read symlink%s"), path);2229return0;2230case S_IFREG:2231if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2232returnerror(_("unable to open or read%s"), path);2233convert_to_git(path, buf->buf, buf->len, buf,0);2234return0;2235default:2236return-1;2237}2238}22392240/*2241 * Update the preimage, and the common lines in postimage,2242 * from buffer buf of length len. If postlen is 0 the postimage2243 * is updated in place, otherwise it's updated on a new buffer2244 * of length postlen2245 */22462247static voidupdate_pre_post_images(struct image *preimage,2248struct image *postimage,2249char*buf,2250size_t len,size_t postlen)2251{2252int i, ctx, reduced;2253char*new, *old, *fixed;2254struct image fixed_preimage;22552256/*2257 * Update the preimage with whitespace fixes. Note that we2258 * are not losing preimage->buf -- apply_one_fragment() will2259 * free "oldlines".2260 */2261prepare_image(&fixed_preimage, buf, len,1);2262assert(postlen2263? fixed_preimage.nr == preimage->nr2264: fixed_preimage.nr <= preimage->nr);2265for(i =0; i < fixed_preimage.nr; i++)2266 fixed_preimage.line[i].flag = preimage->line[i].flag;2267free(preimage->line_allocated);2268*preimage = fixed_preimage;22692270/*2271 * Adjust the common context lines in postimage. This can be2272 * done in-place when we are shrinking it with whitespace2273 * fixing, but needs a new buffer when ignoring whitespace or2274 * expanding leading tabs to spaces.2275 *2276 * We trust the caller to tell us if the update can be done2277 * in place (postlen==0) or not.2278 */2279 old = postimage->buf;2280if(postlen)2281new= postimage->buf =xmalloc(postlen);2282else2283new= old;2284 fixed = preimage->buf;22852286for(i = reduced = ctx =0; i < postimage->nr; i++) {2287size_t l_len = postimage->line[i].len;2288if(!(postimage->line[i].flag & LINE_COMMON)) {2289/* an added line -- no counterparts in preimage */2290memmove(new, old, l_len);2291 old += l_len;2292new+= l_len;2293continue;2294}22952296/* a common context -- skip it in the original postimage */2297 old += l_len;22982299/* and find the corresponding one in the fixed preimage */2300while(ctx < preimage->nr &&2301!(preimage->line[ctx].flag & LINE_COMMON)) {2302 fixed += preimage->line[ctx].len;2303 ctx++;2304}23052306/*2307 * preimage is expected to run out, if the caller2308 * fixed addition of trailing blank lines.2309 */2310if(preimage->nr <= ctx) {2311 reduced++;2312continue;2313}23142315/* and copy it in, while fixing the line length */2316 l_len = preimage->line[ctx].len;2317memcpy(new, fixed, l_len);2318new+= l_len;2319 fixed += l_len;2320 postimage->line[i].len = l_len;2321 ctx++;2322}23232324if(postlen2325? postlen <new- postimage->buf2326: postimage->len <new- postimage->buf)2327die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2328(int)postlen, (int) postimage->len, (int)(new- postimage->buf));23292330/* Fix the length of the whole thing */2331 postimage->len =new- postimage->buf;2332 postimage->nr -= reduced;2333}23342335static intline_by_line_fuzzy_match(struct image *img,2336struct image *preimage,2337struct image *postimage,2338unsigned longtry,2339int try_lno,2340int preimage_limit)2341{2342int i;2343size_t imgoff =0;2344size_t preoff =0;2345size_t postlen = postimage->len;2346size_t extra_chars;2347char*buf;2348char*preimage_eof;2349char*preimage_end;2350struct strbuf fixed;2351char*fixed_buf;2352size_t fixed_len;23532354for(i =0; i < preimage_limit; i++) {2355size_t prelen = preimage->line[i].len;2356size_t imglen = img->line[try_lno+i].len;23572358if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2359 preimage->buf + preoff, prelen))2360return0;2361if(preimage->line[i].flag & LINE_COMMON)2362 postlen += imglen - prelen;2363 imgoff += imglen;2364 preoff += prelen;2365}23662367/*2368 * Ok, the preimage matches with whitespace fuzz.2369 *2370 * imgoff now holds the true length of the target that2371 * matches the preimage before the end of the file.2372 *2373 * Count the number of characters in the preimage that fall2374 * beyond the end of the file and make sure that all of them2375 * are whitespace characters. (This can only happen if2376 * we are removing blank lines at the end of the file.)2377 */2378 buf = preimage_eof = preimage->buf + preoff;2379for( ; i < preimage->nr; i++)2380 preoff += preimage->line[i].len;2381 preimage_end = preimage->buf + preoff;2382for( ; buf < preimage_end; buf++)2383if(!isspace(*buf))2384return0;23852386/*2387 * Update the preimage and the common postimage context2388 * lines to use the same whitespace as the target.2389 * If whitespace is missing in the target (i.e.2390 * if the preimage extends beyond the end of the file),2391 * use the whitespace from the preimage.2392 */2393 extra_chars = preimage_end - preimage_eof;2394strbuf_init(&fixed, imgoff + extra_chars);2395strbuf_add(&fixed, img->buf +try, imgoff);2396strbuf_add(&fixed, preimage_eof, extra_chars);2397 fixed_buf =strbuf_detach(&fixed, &fixed_len);2398update_pre_post_images(preimage, postimage,2399 fixed_buf, fixed_len, postlen);2400return1;2401}24022403static intmatch_fragment(struct apply_state *state,2404struct image *img,2405struct image *preimage,2406struct image *postimage,2407unsigned longtry,2408int try_lno,2409unsigned ws_rule,2410int match_beginning,int match_end)2411{2412int i;2413char*fixed_buf, *buf, *orig, *target;2414struct strbuf fixed;2415size_t fixed_len, postlen;2416int preimage_limit;24172418if(preimage->nr + try_lno <= img->nr) {2419/*2420 * The hunk falls within the boundaries of img.2421 */2422 preimage_limit = preimage->nr;2423if(match_end && (preimage->nr + try_lno != img->nr))2424return0;2425}else if(state->ws_error_action == correct_ws_error &&2426(ws_rule & WS_BLANK_AT_EOF)) {2427/*2428 * This hunk extends beyond the end of img, and we are2429 * removing blank lines at the end of the file. This2430 * many lines from the beginning of the preimage must2431 * match with img, and the remainder of the preimage2432 * must be blank.2433 */2434 preimage_limit = img->nr - try_lno;2435}else{2436/*2437 * The hunk extends beyond the end of the img and2438 * we are not removing blanks at the end, so we2439 * should reject the hunk at this position.2440 */2441return0;2442}24432444if(match_beginning && try_lno)2445return0;24462447/* Quick hash check */2448for(i =0; i < preimage_limit; i++)2449if((img->line[try_lno + i].flag & LINE_PATCHED) ||2450(preimage->line[i].hash != img->line[try_lno + i].hash))2451return0;24522453if(preimage_limit == preimage->nr) {2454/*2455 * Do we have an exact match? If we were told to match2456 * at the end, size must be exactly at try+fragsize,2457 * otherwise try+fragsize must be still within the preimage,2458 * and either case, the old piece should match the preimage2459 * exactly.2460 */2461if((match_end2462? (try+ preimage->len == img->len)2463: (try+ preimage->len <= img->len)) &&2464!memcmp(img->buf +try, preimage->buf, preimage->len))2465return1;2466}else{2467/*2468 * The preimage extends beyond the end of img, so2469 * there cannot be an exact match.2470 *2471 * There must be one non-blank context line that match2472 * a line before the end of img.2473 */2474char*buf_end;24752476 buf = preimage->buf;2477 buf_end = buf;2478for(i =0; i < preimage_limit; i++)2479 buf_end += preimage->line[i].len;24802481for( ; buf < buf_end; buf++)2482if(!isspace(*buf))2483break;2484if(buf == buf_end)2485return0;2486}24872488/*2489 * No exact match. If we are ignoring whitespace, run a line-by-line2490 * fuzzy matching. We collect all the line length information because2491 * we need it to adjust whitespace if we match.2492 */2493if(state->ws_ignore_action == ignore_ws_change)2494returnline_by_line_fuzzy_match(img, preimage, postimage,2495try, try_lno, preimage_limit);24962497if(state->ws_error_action != correct_ws_error)2498return0;24992500/*2501 * The hunk does not apply byte-by-byte, but the hash says2502 * it might with whitespace fuzz. We weren't asked to2503 * ignore whitespace, we were asked to correct whitespace2504 * errors, so let's try matching after whitespace correction.2505 *2506 * While checking the preimage against the target, whitespace2507 * errors in both fixed, we count how large the corresponding2508 * postimage needs to be. The postimage prepared by2509 * apply_one_fragment() has whitespace errors fixed on added2510 * lines already, but the common lines were propagated as-is,2511 * which may become longer when their whitespace errors are2512 * fixed.2513 */25142515/* First count added lines in postimage */2516 postlen =0;2517for(i =0; i < postimage->nr; i++) {2518if(!(postimage->line[i].flag & LINE_COMMON))2519 postlen += postimage->line[i].len;2520}25212522/*2523 * The preimage may extend beyond the end of the file,2524 * but in this loop we will only handle the part of the2525 * preimage that falls within the file.2526 */2527strbuf_init(&fixed, preimage->len +1);2528 orig = preimage->buf;2529 target = img->buf +try;2530for(i =0; i < preimage_limit; i++) {2531size_t oldlen = preimage->line[i].len;2532size_t tgtlen = img->line[try_lno + i].len;2533size_t fixstart = fixed.len;2534struct strbuf tgtfix;2535int match;25362537/* Try fixing the line in the preimage */2538ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25392540/* Try fixing the line in the target */2541strbuf_init(&tgtfix, tgtlen);2542ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);25432544/*2545 * If they match, either the preimage was based on2546 * a version before our tree fixed whitespace breakage,2547 * or we are lacking a whitespace-fix patch the tree2548 * the preimage was based on already had (i.e. target2549 * has whitespace breakage, the preimage doesn't).2550 * In either case, we are fixing the whitespace breakages2551 * so we might as well take the fix together with their2552 * real change.2553 */2554 match = (tgtfix.len == fixed.len - fixstart &&2555!memcmp(tgtfix.buf, fixed.buf + fixstart,2556 fixed.len - fixstart));25572558/* Add the length if this is common with the postimage */2559if(preimage->line[i].flag & LINE_COMMON)2560 postlen += tgtfix.len;25612562strbuf_release(&tgtfix);2563if(!match)2564goto unmatch_exit;25652566 orig += oldlen;2567 target += tgtlen;2568}256925702571/*2572 * Now handle the lines in the preimage that falls beyond the2573 * end of the file (if any). They will only match if they are2574 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2575 * false).2576 */2577for( ; i < preimage->nr; i++) {2578size_t fixstart = fixed.len;/* start of the fixed preimage */2579size_t oldlen = preimage->line[i].len;2580int j;25812582/* Try fixing the line in the preimage */2583ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25842585for(j = fixstart; j < fixed.len; j++)2586if(!isspace(fixed.buf[j]))2587goto unmatch_exit;25882589 orig += oldlen;2590}25912592/*2593 * Yes, the preimage is based on an older version that still2594 * has whitespace breakages unfixed, and fixing them makes the2595 * hunk match. Update the context lines in the postimage.2596 */2597 fixed_buf =strbuf_detach(&fixed, &fixed_len);2598if(postlen < postimage->len)2599 postlen =0;2600update_pre_post_images(preimage, postimage,2601 fixed_buf, fixed_len, postlen);2602return1;26032604 unmatch_exit:2605strbuf_release(&fixed);2606return0;2607}26082609static intfind_pos(struct apply_state *state,2610struct image *img,2611struct image *preimage,2612struct image *postimage,2613int line,2614unsigned ws_rule,2615int match_beginning,int match_end)2616{2617int i;2618unsigned long backwards, forwards,try;2619int backwards_lno, forwards_lno, try_lno;26202621/*2622 * If match_beginning or match_end is specified, there is no2623 * point starting from a wrong line that will never match and2624 * wander around and wait for a match at the specified end.2625 */2626if(match_beginning)2627 line =0;2628else if(match_end)2629 line = img->nr - preimage->nr;26302631/*2632 * Because the comparison is unsigned, the following test2633 * will also take care of a negative line number that can2634 * result when match_end and preimage is larger than the target.2635 */2636if((size_t) line > img->nr)2637 line = img->nr;26382639try=0;2640for(i =0; i < line; i++)2641try+= img->line[i].len;26422643/*2644 * There's probably some smart way to do this, but I'll leave2645 * that to the smart and beautiful people. I'm simple and stupid.2646 */2647 backwards =try;2648 backwards_lno = line;2649 forwards =try;2650 forwards_lno = line;2651 try_lno = line;26522653for(i =0; ; i++) {2654if(match_fragment(state, img, preimage, postimage,2655try, try_lno, ws_rule,2656 match_beginning, match_end))2657return try_lno;26582659 again:2660if(backwards_lno ==0&& forwards_lno == img->nr)2661break;26622663if(i &1) {2664if(backwards_lno ==0) {2665 i++;2666goto again;2667}2668 backwards_lno--;2669 backwards -= img->line[backwards_lno].len;2670try= backwards;2671 try_lno = backwards_lno;2672}else{2673if(forwards_lno == img->nr) {2674 i++;2675goto again;2676}2677 forwards += img->line[forwards_lno].len;2678 forwards_lno++;2679try= forwards;2680 try_lno = forwards_lno;2681}26822683}2684return-1;2685}26862687static voidremove_first_line(struct image *img)2688{2689 img->buf += img->line[0].len;2690 img->len -= img->line[0].len;2691 img->line++;2692 img->nr--;2693}26942695static voidremove_last_line(struct image *img)2696{2697 img->len -= img->line[--img->nr].len;2698}26992700/*2701 * The change from "preimage" and "postimage" has been found to2702 * apply at applied_pos (counts in line numbers) in "img".2703 * Update "img" to remove "preimage" and replace it with "postimage".2704 */2705static voidupdate_image(struct apply_state *state,2706struct image *img,2707int applied_pos,2708struct image *preimage,2709struct image *postimage)2710{2711/*2712 * remove the copy of preimage at offset in img2713 * and replace it with postimage2714 */2715int i, nr;2716size_t remove_count, insert_count, applied_at =0;2717char*result;2718int preimage_limit;27192720/*2721 * If we are removing blank lines at the end of img,2722 * the preimage may extend beyond the end.2723 * If that is the case, we must be careful only to2724 * remove the part of the preimage that falls within2725 * the boundaries of img. Initialize preimage_limit2726 * to the number of lines in the preimage that falls2727 * within the boundaries.2728 */2729 preimage_limit = preimage->nr;2730if(preimage_limit > img->nr - applied_pos)2731 preimage_limit = img->nr - applied_pos;27322733for(i =0; i < applied_pos; i++)2734 applied_at += img->line[i].len;27352736 remove_count =0;2737for(i =0; i < preimage_limit; i++)2738 remove_count += img->line[applied_pos + i].len;2739 insert_count = postimage->len;27402741/* Adjust the contents */2742 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2743memcpy(result, img->buf, applied_at);2744memcpy(result + applied_at, postimage->buf, postimage->len);2745memcpy(result + applied_at + postimage->len,2746 img->buf + (applied_at + remove_count),2747 img->len - (applied_at + remove_count));2748free(img->buf);2749 img->buf = result;2750 img->len += insert_count - remove_count;2751 result[img->len] ='\0';27522753/* Adjust the line table */2754 nr = img->nr + postimage->nr - preimage_limit;2755if(preimage_limit < postimage->nr) {2756/*2757 * NOTE: this knows that we never call remove_first_line()2758 * on anything other than pre/post image.2759 */2760REALLOC_ARRAY(img->line, nr);2761 img->line_allocated = img->line;2762}2763if(preimage_limit != postimage->nr)2764memmove(img->line + applied_pos + postimage->nr,2765 img->line + applied_pos + preimage_limit,2766(img->nr - (applied_pos + preimage_limit)) *2767sizeof(*img->line));2768memcpy(img->line + applied_pos,2769 postimage->line,2770 postimage->nr *sizeof(*img->line));2771if(!state->allow_overlap)2772for(i =0; i < postimage->nr; i++)2773 img->line[applied_pos + i].flag |= LINE_PATCHED;2774 img->nr = nr;2775}27762777/*2778 * Use the patch-hunk text in "frag" to prepare two images (preimage and2779 * postimage) for the hunk. Find lines that match "preimage" in "img" and2780 * replace the part of "img" with "postimage" text.2781 */2782static intapply_one_fragment(struct apply_state *state,2783struct image *img,struct fragment *frag,2784int inaccurate_eof,unsigned ws_rule,2785int nth_fragment)2786{2787int match_beginning, match_end;2788const char*patch = frag->patch;2789int size = frag->size;2790char*old, *oldlines;2791struct strbuf newlines;2792int new_blank_lines_at_end =0;2793int found_new_blank_lines_at_end =0;2794int hunk_linenr = frag->linenr;2795unsigned long leading, trailing;2796int pos, applied_pos;2797struct image preimage;2798struct image postimage;27992800memset(&preimage,0,sizeof(preimage));2801memset(&postimage,0,sizeof(postimage));2802 oldlines =xmalloc(size);2803strbuf_init(&newlines, size);28042805 old = oldlines;2806while(size >0) {2807char first;2808int len =linelen(patch, size);2809int plen;2810int added_blank_line =0;2811int is_blank_context =0;2812size_t start;28132814if(!len)2815break;28162817/*2818 * "plen" is how much of the line we should use for2819 * the actual patch data. Normally we just remove the2820 * first character on the line, but if the line is2821 * followed by "\ No newline", then we also remove the2822 * last one (which is the newline, of course).2823 */2824 plen = len -1;2825if(len < size && patch[len] =='\\')2826 plen--;2827 first = *patch;2828if(state->apply_in_reverse) {2829if(first =='-')2830 first ='+';2831else if(first =='+')2832 first ='-';2833}28342835switch(first) {2836case'\n':2837/* Newer GNU diff, empty context line */2838if(plen <0)2839/* ... followed by '\No newline'; nothing */2840break;2841*old++ ='\n';2842strbuf_addch(&newlines,'\n');2843add_line_info(&preimage,"\n",1, LINE_COMMON);2844add_line_info(&postimage,"\n",1, LINE_COMMON);2845 is_blank_context =1;2846break;2847case' ':2848if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2849ws_blank_line(patch +1, plen, ws_rule))2850 is_blank_context =1;2851case'-':2852memcpy(old, patch +1, plen);2853add_line_info(&preimage, old, plen,2854(first ==' '? LINE_COMMON :0));2855 old += plen;2856if(first =='-')2857break;2858/* Fall-through for ' ' */2859case'+':2860/* --no-add does not add new lines */2861if(first =='+'&& state->no_add)2862break;28632864 start = newlines.len;2865if(first !='+'||2866!state->whitespace_error ||2867 state->ws_error_action != correct_ws_error) {2868strbuf_add(&newlines, patch +1, plen);2869}2870else{2871ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2872}2873add_line_info(&postimage, newlines.buf + start, newlines.len - start,2874(first =='+'?0: LINE_COMMON));2875if(first =='+'&&2876(ws_rule & WS_BLANK_AT_EOF) &&2877ws_blank_line(patch +1, plen, ws_rule))2878 added_blank_line =1;2879break;2880case'@':case'\\':2881/* Ignore it, we already handled it */2882break;2883default:2884if(state->apply_verbosely)2885error(_("invalid start of line: '%c'"), first);2886 applied_pos = -1;2887goto out;2888}2889if(added_blank_line) {2890if(!new_blank_lines_at_end)2891 found_new_blank_lines_at_end = hunk_linenr;2892 new_blank_lines_at_end++;2893}2894else if(is_blank_context)2895;2896else2897 new_blank_lines_at_end =0;2898 patch += len;2899 size -= len;2900 hunk_linenr++;2901}2902if(inaccurate_eof &&2903 old > oldlines && old[-1] =='\n'&&2904 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2905 old--;2906strbuf_setlen(&newlines, newlines.len -1);2907}29082909 leading = frag->leading;2910 trailing = frag->trailing;29112912/*2913 * A hunk to change lines at the beginning would begin with2914 * @@ -1,L +N,M @@2915 * but we need to be careful. -U0 that inserts before the second2916 * line also has this pattern.2917 *2918 * And a hunk to add to an empty file would begin with2919 * @@ -0,0 +N,M @@2920 *2921 * In other words, a hunk that is (frag->oldpos <= 1) with or2922 * without leading context must match at the beginning.2923 */2924 match_beginning = (!frag->oldpos ||2925(frag->oldpos ==1&& !state->unidiff_zero));29262927/*2928 * A hunk without trailing lines must match at the end.2929 * However, we simply cannot tell if a hunk must match end2930 * from the lack of trailing lines if the patch was generated2931 * with unidiff without any context.2932 */2933 match_end = !state->unidiff_zero && !trailing;29342935 pos = frag->newpos ? (frag->newpos -1) :0;2936 preimage.buf = oldlines;2937 preimage.len = old - oldlines;2938 postimage.buf = newlines.buf;2939 postimage.len = newlines.len;2940 preimage.line = preimage.line_allocated;2941 postimage.line = postimage.line_allocated;29422943for(;;) {29442945 applied_pos =find_pos(state, img, &preimage, &postimage, pos,2946 ws_rule, match_beginning, match_end);29472948if(applied_pos >=0)2949break;29502951/* Am I at my context limits? */2952if((leading <= state->p_context) && (trailing <= state->p_context))2953break;2954if(match_beginning || match_end) {2955 match_beginning = match_end =0;2956continue;2957}29582959/*2960 * Reduce the number of context lines; reduce both2961 * leading and trailing if they are equal otherwise2962 * just reduce the larger context.2963 */2964if(leading >= trailing) {2965remove_first_line(&preimage);2966remove_first_line(&postimage);2967 pos--;2968 leading--;2969}2970if(trailing > leading) {2971remove_last_line(&preimage);2972remove_last_line(&postimage);2973 trailing--;2974}2975}29762977if(applied_pos >=0) {2978if(new_blank_lines_at_end &&2979 preimage.nr + applied_pos >= img->nr &&2980(ws_rule & WS_BLANK_AT_EOF) &&2981 state->ws_error_action != nowarn_ws_error) {2982record_ws_error(state, WS_BLANK_AT_EOF,"+",1,2983 found_new_blank_lines_at_end);2984if(state->ws_error_action == correct_ws_error) {2985while(new_blank_lines_at_end--)2986remove_last_line(&postimage);2987}2988/*2989 * We would want to prevent write_out_results()2990 * from taking place in apply_patch() that follows2991 * the callchain led us here, which is:2992 * apply_patch->check_patch_list->check_patch->2993 * apply_data->apply_fragments->apply_one_fragment2994 */2995if(state->ws_error_action == die_on_ws_error)2996 state->apply =0;2997}29982999if(state->apply_verbosely && applied_pos != pos) {3000int offset = applied_pos - pos;3001if(state->apply_in_reverse)3002 offset =0- offset;3003fprintf_ln(stderr,3004Q_("Hunk #%dsucceeded at%d(offset%dline).",3005"Hunk #%dsucceeded at%d(offset%dlines).",3006 offset),3007 nth_fragment, applied_pos +1, offset);3008}30093010/*3011 * Warn if it was necessary to reduce the number3012 * of context lines.3013 */3014if((leading != frag->leading) ||3015(trailing != frag->trailing))3016fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"3017" to apply fragment at%d"),3018 leading, trailing, applied_pos+1);3019update_image(state, img, applied_pos, &preimage, &postimage);3020}else{3021if(state->apply_verbosely)3022error(_("while searching for:\n%.*s"),3023(int)(old - oldlines), oldlines);3024}30253026out:3027free(oldlines);3028strbuf_release(&newlines);3029free(preimage.line_allocated);3030free(postimage.line_allocated);30313032return(applied_pos <0);3033}30343035static intapply_binary_fragment(struct apply_state *state,3036struct image *img,3037struct patch *patch)3038{3039struct fragment *fragment = patch->fragments;3040unsigned long len;3041void*dst;30423043if(!fragment)3044returnerror(_("missing binary patch data for '%s'"),3045 patch->new_name ?3046 patch->new_name :3047 patch->old_name);30483049/* Binary patch is irreversible without the optional second hunk */3050if(state->apply_in_reverse) {3051if(!fragment->next)3052returnerror("cannot reverse-apply a binary patch "3053"without the reverse hunk to '%s'",3054 patch->new_name3055? patch->new_name : patch->old_name);3056 fragment = fragment->next;3057}3058switch(fragment->binary_patch_method) {3059case BINARY_DELTA_DEFLATED:3060 dst =patch_delta(img->buf, img->len, fragment->patch,3061 fragment->size, &len);3062if(!dst)3063return-1;3064clear_image(img);3065 img->buf = dst;3066 img->len = len;3067return0;3068case BINARY_LITERAL_DEFLATED:3069clear_image(img);3070 img->len = fragment->size;3071 img->buf =xmemdupz(fragment->patch, img->len);3072return0;3073}3074return-1;3075}30763077/*3078 * Replace "img" with the result of applying the binary patch.3079 * The binary patch data itself in patch->fragment is still kept3080 * but the preimage prepared by the caller in "img" is freed here3081 * or in the helper function apply_binary_fragment() this calls.3082 */3083static intapply_binary(struct apply_state *state,3084struct image *img,3085struct patch *patch)3086{3087const char*name = patch->old_name ? patch->old_name : patch->new_name;3088unsigned char sha1[20];30893090/*3091 * For safety, we require patch index line to contain3092 * full 40-byte textual SHA1 for old and new, at least for now.3093 */3094if(strlen(patch->old_sha1_prefix) !=40||3095strlen(patch->new_sha1_prefix) !=40||3096get_sha1_hex(patch->old_sha1_prefix, sha1) ||3097get_sha1_hex(patch->new_sha1_prefix, sha1))3098returnerror("cannot apply binary patch to '%s' "3099"without full index line", name);31003101if(patch->old_name) {3102/*3103 * See if the old one matches what the patch3104 * applies to.3105 */3106hash_sha1_file(img->buf, img->len, blob_type, sha1);3107if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3108returnerror("the patch applies to '%s' (%s), "3109"which does not match the "3110"current contents.",3111 name,sha1_to_hex(sha1));3112}3113else{3114/* Otherwise, the old one must be empty. */3115if(img->len)3116returnerror("the patch applies to an empty "3117"'%s' but it is not empty", name);3118}31193120get_sha1_hex(patch->new_sha1_prefix, sha1);3121if(is_null_sha1(sha1)) {3122clear_image(img);3123return0;/* deletion patch */3124}31253126if(has_sha1_file(sha1)) {3127/* We already have the postimage */3128enum object_type type;3129unsigned long size;3130char*result;31313132 result =read_sha1_file(sha1, &type, &size);3133if(!result)3134returnerror("the necessary postimage%sfor "3135"'%s' cannot be read",3136 patch->new_sha1_prefix, name);3137clear_image(img);3138 img->buf = result;3139 img->len = size;3140}else{3141/*3142 * We have verified buf matches the preimage;3143 * apply the patch data to it, which is stored3144 * in the patch->fragments->{patch,size}.3145 */3146if(apply_binary_fragment(state, img, patch))3147returnerror(_("binary patch does not apply to '%s'"),3148 name);31493150/* verify that the result matches */3151hash_sha1_file(img->buf, img->len, blob_type, sha1);3152if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3153returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3154 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3155}31563157return0;3158}31593160static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3161{3162struct fragment *frag = patch->fragments;3163const char*name = patch->old_name ? patch->old_name : patch->new_name;3164unsigned ws_rule = patch->ws_rule;3165unsigned inaccurate_eof = patch->inaccurate_eof;3166int nth =0;31673168if(patch->is_binary)3169returnapply_binary(state, img, patch);31703171while(frag) {3172 nth++;3173if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3174error(_("patch failed:%s:%ld"), name, frag->oldpos);3175if(!state->apply_with_reject)3176return-1;3177 frag->rejected =1;3178}3179 frag = frag->next;3180}3181return0;3182}31833184static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3185{3186if(S_ISGITLINK(mode)) {3187strbuf_grow(buf,100);3188strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3189}else{3190enum object_type type;3191unsigned long sz;3192char*result;31933194 result =read_sha1_file(sha1, &type, &sz);3195if(!result)3196return-1;3197/* XXX read_sha1_file NUL-terminates */3198strbuf_attach(buf, result, sz, sz +1);3199}3200return0;3201}32023203static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3204{3205if(!ce)3206return0;3207returnread_blob_object(buf, ce->sha1, ce->ce_mode);3208}32093210static struct patch *in_fn_table(const char*name)3211{3212struct string_list_item *item;32133214if(name == NULL)3215return NULL;32163217 item =string_list_lookup(&fn_table, name);3218if(item != NULL)3219return(struct patch *)item->util;32203221return NULL;3222}32233224/*3225 * item->util in the filename table records the status of the path.3226 * Usually it points at a patch (whose result records the contents3227 * of it after applying it), but it could be PATH_WAS_DELETED for a3228 * path that a previously applied patch has already removed, or3229 * PATH_TO_BE_DELETED for a path that a later patch would remove.3230 *3231 * The latter is needed to deal with a case where two paths A and B3232 * are swapped by first renaming A to B and then renaming B to A;3233 * moving A to B should not be prevented due to presence of B as we3234 * will remove it in a later patch.3235 */3236#define PATH_TO_BE_DELETED ((struct patch *) -2)3237#define PATH_WAS_DELETED ((struct patch *) -1)32383239static intto_be_deleted(struct patch *patch)3240{3241return patch == PATH_TO_BE_DELETED;3242}32433244static intwas_deleted(struct patch *patch)3245{3246return patch == PATH_WAS_DELETED;3247}32483249static voidadd_to_fn_table(struct patch *patch)3250{3251struct string_list_item *item;32523253/*3254 * Always add new_name unless patch is a deletion3255 * This should cover the cases for normal diffs,3256 * file creations and copies3257 */3258if(patch->new_name != NULL) {3259 item =string_list_insert(&fn_table, patch->new_name);3260 item->util = patch;3261}32623263/*3264 * store a failure on rename/deletion cases because3265 * later chunks shouldn't patch old names3266 */3267if((patch->new_name == NULL) || (patch->is_rename)) {3268 item =string_list_insert(&fn_table, patch->old_name);3269 item->util = PATH_WAS_DELETED;3270}3271}32723273static voidprepare_fn_table(struct patch *patch)3274{3275/*3276 * store information about incoming file deletion3277 */3278while(patch) {3279if((patch->new_name == NULL) || (patch->is_rename)) {3280struct string_list_item *item;3281 item =string_list_insert(&fn_table, patch->old_name);3282 item->util = PATH_TO_BE_DELETED;3283}3284 patch = patch->next;3285}3286}32873288static intcheckout_target(struct index_state *istate,3289struct cache_entry *ce,struct stat *st)3290{3291struct checkout costate;32923293memset(&costate,0,sizeof(costate));3294 costate.base_dir ="";3295 costate.refresh_cache =1;3296 costate.istate = istate;3297if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3298returnerror(_("cannot checkout%s"), ce->name);3299return0;3300}33013302static struct patch *previous_patch(struct patch *patch,int*gone)3303{3304struct patch *previous;33053306*gone =0;3307if(patch->is_copy || patch->is_rename)3308return NULL;/* "git" patches do not depend on the order */33093310 previous =in_fn_table(patch->old_name);3311if(!previous)3312return NULL;33133314if(to_be_deleted(previous))3315return NULL;/* the deletion hasn't happened yet */33163317if(was_deleted(previous))3318*gone =1;33193320return previous;3321}33223323static intverify_index_match(const struct cache_entry *ce,struct stat *st)3324{3325if(S_ISGITLINK(ce->ce_mode)) {3326if(!S_ISDIR(st->st_mode))3327return-1;3328return0;3329}3330returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3331}33323333#define SUBMODULE_PATCH_WITHOUT_INDEX 133343335static intload_patch_target(struct apply_state *state,3336struct strbuf *buf,3337const struct cache_entry *ce,3338struct stat *st,3339const char*name,3340unsigned expected_mode)3341{3342if(state->cached || state->check_index) {3343if(read_file_or_gitlink(ce, buf))3344returnerror(_("read of%sfailed"), name);3345}else if(name) {3346if(S_ISGITLINK(expected_mode)) {3347if(ce)3348returnread_file_or_gitlink(ce, buf);3349else3350return SUBMODULE_PATCH_WITHOUT_INDEX;3351}else if(has_symlink_leading_path(name,strlen(name))) {3352returnerror(_("reading from '%s' beyond a symbolic link"), name);3353}else{3354if(read_old_data(st, name, buf))3355returnerror(_("read of%sfailed"), name);3356}3357}3358return0;3359}33603361/*3362 * We are about to apply "patch"; populate the "image" with the3363 * current version we have, from the working tree or from the index,3364 * depending on the situation e.g. --cached/--index. If we are3365 * applying a non-git patch that incrementally updates the tree,3366 * we read from the result of a previous diff.3367 */3368static intload_preimage(struct apply_state *state,3369struct image *image,3370struct patch *patch,struct stat *st,3371const struct cache_entry *ce)3372{3373struct strbuf buf = STRBUF_INIT;3374size_t len;3375char*img;3376struct patch *previous;3377int status;33783379 previous =previous_patch(patch, &status);3380if(status)3381returnerror(_("path%shas been renamed/deleted"),3382 patch->old_name);3383if(previous) {3384/* We have a patched copy in memory; use that. */3385strbuf_add(&buf, previous->result, previous->resultsize);3386}else{3387 status =load_patch_target(state, &buf, ce, st,3388 patch->old_name, patch->old_mode);3389if(status <0)3390return status;3391else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3392/*3393 * There is no way to apply subproject3394 * patch without looking at the index.3395 * NEEDSWORK: shouldn't this be flagged3396 * as an error???3397 */3398free_fragment_list(patch->fragments);3399 patch->fragments = NULL;3400}else if(status) {3401returnerror(_("read of%sfailed"), patch->old_name);3402}3403}34043405 img =strbuf_detach(&buf, &len);3406prepare_image(image, img, len, !patch->is_binary);3407return0;3408}34093410static intthree_way_merge(struct image *image,3411char*path,3412const unsigned char*base,3413const unsigned char*ours,3414const unsigned char*theirs)3415{3416 mmfile_t base_file, our_file, their_file;3417 mmbuffer_t result = { NULL };3418int status;34193420read_mmblob(&base_file, base);3421read_mmblob(&our_file, ours);3422read_mmblob(&their_file, theirs);3423 status =ll_merge(&result, path,3424&base_file,"base",3425&our_file,"ours",3426&their_file,"theirs", NULL);3427free(base_file.ptr);3428free(our_file.ptr);3429free(their_file.ptr);3430if(status <0|| !result.ptr) {3431free(result.ptr);3432return-1;3433}3434clear_image(image);3435 image->buf = result.ptr;3436 image->len = result.size;34373438return status;3439}34403441/*3442 * When directly falling back to add/add three-way merge, we read from3443 * the current contents of the new_name. In no cases other than that3444 * this function will be called.3445 */3446static intload_current(struct apply_state *state,3447struct image *image,3448struct patch *patch)3449{3450struct strbuf buf = STRBUF_INIT;3451int status, pos;3452size_t len;3453char*img;3454struct stat st;3455struct cache_entry *ce;3456char*name = patch->new_name;3457unsigned mode = patch->new_mode;34583459if(!patch->is_new)3460die("BUG: patch to%sis not a creation", patch->old_name);34613462 pos =cache_name_pos(name,strlen(name));3463if(pos <0)3464returnerror(_("%s: does not exist in index"), name);3465 ce = active_cache[pos];3466if(lstat(name, &st)) {3467if(errno != ENOENT)3468returnerror(_("%s:%s"), name,strerror(errno));3469if(checkout_target(&the_index, ce, &st))3470return-1;3471}3472if(verify_index_match(ce, &st))3473returnerror(_("%s: does not match index"), name);34743475 status =load_patch_target(state, &buf, ce, &st, name, mode);3476if(status <0)3477return status;3478else if(status)3479return-1;3480 img =strbuf_detach(&buf, &len);3481prepare_image(image, img, len, !patch->is_binary);3482return0;3483}34843485static inttry_threeway(struct apply_state *state,3486struct image *image,3487struct patch *patch,3488struct stat *st,3489const struct cache_entry *ce)3490{3491unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3492struct strbuf buf = STRBUF_INIT;3493size_t len;3494int status;3495char*img;3496struct image tmp_image;34973498/* No point falling back to 3-way merge in these cases */3499if(patch->is_delete ||3500S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3501return-1;35023503/* Preimage the patch was prepared for */3504if(patch->is_new)3505write_sha1_file("",0, blob_type, pre_sha1);3506else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3507read_blob_object(&buf, pre_sha1, patch->old_mode))3508returnerror("repository lacks the necessary blob to fall back on 3-way merge.");35093510fprintf(stderr,"Falling back to three-way merge...\n");35113512 img =strbuf_detach(&buf, &len);3513prepare_image(&tmp_image, img, len,1);3514/* Apply the patch to get the post image */3515if(apply_fragments(state, &tmp_image, patch) <0) {3516clear_image(&tmp_image);3517return-1;3518}3519/* post_sha1[] is theirs */3520write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3521clear_image(&tmp_image);35223523/* our_sha1[] is ours */3524if(patch->is_new) {3525if(load_current(state, &tmp_image, patch))3526returnerror("cannot read the current contents of '%s'",3527 patch->new_name);3528}else{3529if(load_preimage(state, &tmp_image, patch, st, ce))3530returnerror("cannot read the current contents of '%s'",3531 patch->old_name);3532}3533write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3534clear_image(&tmp_image);35353536/* in-core three-way merge between post and our using pre as base */3537 status =three_way_merge(image, patch->new_name,3538 pre_sha1, our_sha1, post_sha1);3539if(status <0) {3540fprintf(stderr,"Failed to fall back on three-way merge...\n");3541return status;3542}35433544if(status) {3545 patch->conflicted_threeway =1;3546if(patch->is_new)3547oidclr(&patch->threeway_stage[0]);3548else3549hashcpy(patch->threeway_stage[0].hash, pre_sha1);3550hashcpy(patch->threeway_stage[1].hash, our_sha1);3551hashcpy(patch->threeway_stage[2].hash, post_sha1);3552fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3553}else{3554fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3555}3556return0;3557}35583559static intapply_data(struct apply_state *state,struct patch *patch,3560struct stat *st,const struct cache_entry *ce)3561{3562struct image image;35633564if(load_preimage(state, &image, patch, st, ce) <0)3565return-1;35663567if(patch->direct_to_threeway ||3568apply_fragments(state, &image, patch) <0) {3569/* Note: with --reject, apply_fragments() returns 0 */3570if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3571return-1;3572}3573 patch->result = image.buf;3574 patch->resultsize = image.len;3575add_to_fn_table(patch);3576free(image.line_allocated);35773578if(0< patch->is_delete && patch->resultsize)3579returnerror(_("removal patch leaves file contents"));35803581return0;3582}35833584/*3585 * If "patch" that we are looking at modifies or deletes what we have,3586 * we would want it not to lose any local modification we have, either3587 * in the working tree or in the index.3588 *3589 * This also decides if a non-git patch is a creation patch or a3590 * modification to an existing empty file. We do not check the state3591 * of the current tree for a creation patch in this function; the caller3592 * check_patch() separately makes sure (and errors out otherwise) that3593 * the path the patch creates does not exist in the current tree.3594 */3595static intcheck_preimage(struct apply_state *state,3596struct patch *patch,3597struct cache_entry **ce,3598struct stat *st)3599{3600const char*old_name = patch->old_name;3601struct patch *previous = NULL;3602int stat_ret =0, status;3603unsigned st_mode =0;36043605if(!old_name)3606return0;36073608assert(patch->is_new <=0);3609 previous =previous_patch(patch, &status);36103611if(status)3612returnerror(_("path%shas been renamed/deleted"), old_name);3613if(previous) {3614 st_mode = previous->new_mode;3615}else if(!state->cached) {3616 stat_ret =lstat(old_name, st);3617if(stat_ret && errno != ENOENT)3618returnerror(_("%s:%s"), old_name,strerror(errno));3619}36203621if(state->check_index && !previous) {3622int pos =cache_name_pos(old_name,strlen(old_name));3623if(pos <0) {3624if(patch->is_new <0)3625goto is_new;3626returnerror(_("%s: does not exist in index"), old_name);3627}3628*ce = active_cache[pos];3629if(stat_ret <0) {3630if(checkout_target(&the_index, *ce, st))3631return-1;3632}3633if(!state->cached &&verify_index_match(*ce, st))3634returnerror(_("%s: does not match index"), old_name);3635if(state->cached)3636 st_mode = (*ce)->ce_mode;3637}else if(stat_ret <0) {3638if(patch->is_new <0)3639goto is_new;3640returnerror(_("%s:%s"), old_name,strerror(errno));3641}36423643if(!state->cached && !previous)3644 st_mode =ce_mode_from_stat(*ce, st->st_mode);36453646if(patch->is_new <0)3647 patch->is_new =0;3648if(!patch->old_mode)3649 patch->old_mode = st_mode;3650if((st_mode ^ patch->old_mode) & S_IFMT)3651returnerror(_("%s: wrong type"), old_name);3652if(st_mode != patch->old_mode)3653warning(_("%shas type%o, expected%o"),3654 old_name, st_mode, patch->old_mode);3655if(!patch->new_mode && !patch->is_delete)3656 patch->new_mode = st_mode;3657return0;36583659 is_new:3660 patch->is_new =1;3661 patch->is_delete =0;3662free(patch->old_name);3663 patch->old_name = NULL;3664return0;3665}366636673668#define EXISTS_IN_INDEX 13669#define EXISTS_IN_WORKTREE 236703671static intcheck_to_create(struct apply_state *state,3672const char*new_name,3673int ok_if_exists)3674{3675struct stat nst;36763677if(state->check_index &&3678cache_name_pos(new_name,strlen(new_name)) >=0&&3679!ok_if_exists)3680return EXISTS_IN_INDEX;3681if(state->cached)3682return0;36833684if(!lstat(new_name, &nst)) {3685if(S_ISDIR(nst.st_mode) || ok_if_exists)3686return0;3687/*3688 * A leading component of new_name might be a symlink3689 * that is going to be removed with this patch, but3690 * still pointing at somewhere that has the path.3691 * In such a case, path "new_name" does not exist as3692 * far as git is concerned.3693 */3694if(has_symlink_leading_path(new_name,strlen(new_name)))3695return0;36963697return EXISTS_IN_WORKTREE;3698}else if((errno != ENOENT) && (errno != ENOTDIR)) {3699returnerror("%s:%s", new_name,strerror(errno));3700}3701return0;3702}37033704/*3705 * We need to keep track of how symlinks in the preimage are3706 * manipulated by the patches. A patch to add a/b/c where a/b3707 * is a symlink should not be allowed to affect the directory3708 * the symlink points at, but if the same patch removes a/b,3709 * it is perfectly fine, as the patch removes a/b to make room3710 * to create a directory a/b so that a/b/c can be created.3711 */3712static struct string_list symlink_changes;3713#define SYMLINK_GOES_AWAY 013714#define SYMLINK_IN_RESULT 0237153716static uintptr_tregister_symlink_changes(const char*path,uintptr_t what)3717{3718struct string_list_item *ent;37193720 ent =string_list_lookup(&symlink_changes, path);3721if(!ent) {3722 ent =string_list_insert(&symlink_changes, path);3723 ent->util = (void*)0;3724}3725 ent->util = (void*)(what | ((uintptr_t)ent->util));3726return(uintptr_t)ent->util;3727}37283729static uintptr_tcheck_symlink_changes(const char*path)3730{3731struct string_list_item *ent;37323733 ent =string_list_lookup(&symlink_changes, path);3734if(!ent)3735return0;3736return(uintptr_t)ent->util;3737}37383739static voidprepare_symlink_changes(struct patch *patch)3740{3741for( ; patch; patch = patch->next) {3742if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3743(patch->is_rename || patch->is_delete))3744/* the symlink at patch->old_name is removed */3745register_symlink_changes(patch->old_name, SYMLINK_GOES_AWAY);37463747if(patch->new_name &&S_ISLNK(patch->new_mode))3748/* the symlink at patch->new_name is created or remains */3749register_symlink_changes(patch->new_name, SYMLINK_IN_RESULT);3750}3751}37523753static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3754{3755do{3756unsigned int change;37573758while(--name->len && name->buf[name->len] !='/')3759;/* scan backwards */3760if(!name->len)3761break;3762 name->buf[name->len] ='\0';3763 change =check_symlink_changes(name->buf);3764if(change & SYMLINK_IN_RESULT)3765return1;3766if(change & SYMLINK_GOES_AWAY)3767/*3768 * This cannot be "return 0", because we may3769 * see a new one created at a higher level.3770 */3771continue;37723773/* otherwise, check the preimage */3774if(state->check_index) {3775struct cache_entry *ce;37763777 ce =cache_file_exists(name->buf, name->len, ignore_case);3778if(ce &&S_ISLNK(ce->ce_mode))3779return1;3780}else{3781struct stat st;3782if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3783return1;3784}3785}while(1);3786return0;3787}37883789static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3790{3791int ret;3792struct strbuf name = STRBUF_INIT;37933794assert(*name_ !='\0');3795strbuf_addstr(&name, name_);3796 ret =path_is_beyond_symlink_1(state, &name);3797strbuf_release(&name);37983799return ret;3800}38013802static voiddie_on_unsafe_path(struct patch *patch)3803{3804const char*old_name = NULL;3805const char*new_name = NULL;3806if(patch->is_delete)3807 old_name = patch->old_name;3808else if(!patch->is_new && !patch->is_copy)3809 old_name = patch->old_name;3810if(!patch->is_delete)3811 new_name = patch->new_name;38123813if(old_name && !verify_path(old_name))3814die(_("invalid path '%s'"), old_name);3815if(new_name && !verify_path(new_name))3816die(_("invalid path '%s'"), new_name);3817}38183819/*3820 * Check and apply the patch in-core; leave the result in patch->result3821 * for the caller to write it out to the final destination.3822 */3823static intcheck_patch(struct apply_state *state,struct patch *patch)3824{3825struct stat st;3826const char*old_name = patch->old_name;3827const char*new_name = patch->new_name;3828const char*name = old_name ? old_name : new_name;3829struct cache_entry *ce = NULL;3830struct patch *tpatch;3831int ok_if_exists;3832int status;38333834 patch->rejected =1;/* we will drop this after we succeed */38353836 status =check_preimage(state, patch, &ce, &st);3837if(status)3838return status;3839 old_name = patch->old_name;38403841/*3842 * A type-change diff is always split into a patch to delete3843 * old, immediately followed by a patch to create new (see3844 * diff.c::run_diff()); in such a case it is Ok that the entry3845 * to be deleted by the previous patch is still in the working3846 * tree and in the index.3847 *3848 * A patch to swap-rename between A and B would first rename A3849 * to B and then rename B to A. While applying the first one,3850 * the presence of B should not stop A from getting renamed to3851 * B; ask to_be_deleted() about the later rename. Removal of3852 * B and rename from A to B is handled the same way by asking3853 * was_deleted().3854 */3855if((tpatch =in_fn_table(new_name)) &&3856(was_deleted(tpatch) ||to_be_deleted(tpatch)))3857 ok_if_exists =1;3858else3859 ok_if_exists =0;38603861if(new_name &&3862((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3863int err =check_to_create(state, new_name, ok_if_exists);38643865if(err && state->threeway) {3866 patch->direct_to_threeway =1;3867}else switch(err) {3868case0:3869break;/* happy */3870case EXISTS_IN_INDEX:3871returnerror(_("%s: already exists in index"), new_name);3872break;3873case EXISTS_IN_WORKTREE:3874returnerror(_("%s: already exists in working directory"),3875 new_name);3876default:3877return err;3878}38793880if(!patch->new_mode) {3881if(0< patch->is_new)3882 patch->new_mode = S_IFREG |0644;3883else3884 patch->new_mode = patch->old_mode;3885}3886}38873888if(new_name && old_name) {3889int same = !strcmp(old_name, new_name);3890if(!patch->new_mode)3891 patch->new_mode = patch->old_mode;3892if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3893if(same)3894returnerror(_("new mode (%o) of%sdoes not "3895"match old mode (%o)"),3896 patch->new_mode, new_name,3897 patch->old_mode);3898else3899returnerror(_("new mode (%o) of%sdoes not "3900"match old mode (%o) of%s"),3901 patch->new_mode, new_name,3902 patch->old_mode, old_name);3903}3904}39053906if(!state->unsafe_paths)3907die_on_unsafe_path(patch);39083909/*3910 * An attempt to read from or delete a path that is beyond a3911 * symbolic link will be prevented by load_patch_target() that3912 * is called at the beginning of apply_data() so we do not3913 * have to worry about a patch marked with "is_delete" bit3914 * here. We however need to make sure that the patch result3915 * is not deposited to a path that is beyond a symbolic link3916 * here.3917 */3918if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3919returnerror(_("affected file '%s' is beyond a symbolic link"),3920 patch->new_name);39213922if(apply_data(state, patch, &st, ce) <0)3923returnerror(_("%s: patch does not apply"), name);3924 patch->rejected =0;3925return0;3926}39273928static intcheck_patch_list(struct apply_state *state,struct patch *patch)3929{3930int err =0;39313932prepare_symlink_changes(patch);3933prepare_fn_table(patch);3934while(patch) {3935if(state->apply_verbosely)3936say_patch_name(stderr,3937_("Checking patch%s..."), patch);3938 err |=check_patch(state, patch);3939 patch = patch->next;3940}3941return err;3942}39433944/* This function tries to read the sha1 from the current index */3945static intget_current_sha1(const char*path,unsigned char*sha1)3946{3947int pos;39483949if(read_cache() <0)3950return-1;3951 pos =cache_name_pos(path,strlen(path));3952if(pos <0)3953return-1;3954hashcpy(sha1, active_cache[pos]->sha1);3955return0;3956}39573958static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3959{3960/*3961 * A usable gitlink patch has only one fragment (hunk) that looks like:3962 * @@ -1 +1 @@3963 * -Subproject commit <old sha1>3964 * +Subproject commit <new sha1>3965 * or3966 * @@ -1 +0,0 @@3967 * -Subproject commit <old sha1>3968 * for a removal patch.3969 */3970struct fragment *hunk = p->fragments;3971static const char heading[] ="-Subproject commit ";3972char*preimage;39733974if(/* does the patch have only one hunk? */3975 hunk && !hunk->next &&3976/* is its preimage one line? */3977 hunk->oldpos ==1&& hunk->oldlines ==1&&3978/* does preimage begin with the heading? */3979(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3980starts_with(++preimage, heading) &&3981/* does it record full SHA-1? */3982!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3983 preimage[sizeof(heading) +40-1] =='\n'&&3984/* does the abbreviated name on the index line agree with it? */3985starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3986return0;/* it all looks fine */39873988/* we may have full object name on the index line */3989returnget_sha1_hex(p->old_sha1_prefix, sha1);3990}39913992/* Build an index that contains the just the files needed for a 3way merge */3993static voidbuild_fake_ancestor(struct patch *list,const char*filename)3994{3995struct patch *patch;3996struct index_state result = { NULL };3997static struct lock_file lock;39983999/* Once we start supporting the reverse patch, it may be4000 * worth showing the new sha1 prefix, but until then...4001 */4002for(patch = list; patch; patch = patch->next) {4003unsigned char sha1[20];4004struct cache_entry *ce;4005const char*name;40064007 name = patch->old_name ? patch->old_name : patch->new_name;4008if(0< patch->is_new)4009continue;40104011if(S_ISGITLINK(patch->old_mode)) {4012if(!preimage_sha1_in_gitlink_patch(patch, sha1))4013;/* ok, the textual part looks sane */4014else4015die("sha1 information is lacking or useless for submodule%s",4016 name);4017}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {4018;/* ok */4019}else if(!patch->lines_added && !patch->lines_deleted) {4020/* mode-only change: update the current */4021if(get_current_sha1(patch->old_name, sha1))4022die("mode change for%s, which is not "4023"in current HEAD", name);4024}else4025die("sha1 information is lacking or useless "4026"(%s).", name);40274028 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);4029if(!ce)4030die(_("make_cache_entry failed for path '%s'"), name);4031if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))4032die("Could not add%sto temporary index", name);4033}40344035hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);4036if(write_locked_index(&result, &lock, COMMIT_LOCK))4037die("Could not write temporary index to%s", filename);40384039discard_index(&result);4040}40414042static voidstat_patch_list(struct apply_state *state,struct patch *patch)4043{4044int files, adds, dels;40454046for(files = adds = dels =0; patch ; patch = patch->next) {4047 files++;4048 adds += patch->lines_added;4049 dels += patch->lines_deleted;4050show_stats(state, patch);4051}40524053print_stat_summary(stdout, files, adds, dels);4054}40554056static voidnumstat_patch_list(struct apply_state *state,4057struct patch *patch)4058{4059for( ; patch; patch = patch->next) {4060const char*name;4061 name = patch->new_name ? patch->new_name : patch->old_name;4062if(patch->is_binary)4063printf("-\t-\t");4064else4065printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4066write_name_quoted(name, stdout, state->line_termination);4067}4068}40694070static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4071{4072if(mode)4073printf("%smode%06o%s\n", newdelete, mode, name);4074else4075printf("%s %s\n", newdelete, name);4076}40774078static voidshow_mode_change(struct patch *p,int show_name)4079{4080if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4081if(show_name)4082printf(" mode change%06o =>%06o%s\n",4083 p->old_mode, p->new_mode, p->new_name);4084else4085printf(" mode change%06o =>%06o\n",4086 p->old_mode, p->new_mode);4087}4088}40894090static voidshow_rename_copy(struct patch *p)4091{4092const char*renamecopy = p->is_rename ?"rename":"copy";4093const char*old, *new;40944095/* Find common prefix */4096 old = p->old_name;4097new= p->new_name;4098while(1) {4099const char*slash_old, *slash_new;4100 slash_old =strchr(old,'/');4101 slash_new =strchr(new,'/');4102if(!slash_old ||4103!slash_new ||4104 slash_old - old != slash_new -new||4105memcmp(old,new, slash_new -new))4106break;4107 old = slash_old +1;4108new= slash_new +1;4109}4110/* p->old_name thru old is the common prefix, and old and new4111 * through the end of names are renames4112 */4113if(old != p->old_name)4114printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4115(int)(old - p->old_name), p->old_name,4116 old,new, p->score);4117else4118printf("%s %s=>%s(%d%%)\n", renamecopy,4119 p->old_name, p->new_name, p->score);4120show_mode_change(p,0);4121}41224123static voidsummary_patch_list(struct patch *patch)4124{4125struct patch *p;41264127for(p = patch; p; p = p->next) {4128if(p->is_new)4129show_file_mode_name("create", p->new_mode, p->new_name);4130else if(p->is_delete)4131show_file_mode_name("delete", p->old_mode, p->old_name);4132else{4133if(p->is_rename || p->is_copy)4134show_rename_copy(p);4135else{4136if(p->score) {4137printf(" rewrite%s(%d%%)\n",4138 p->new_name, p->score);4139show_mode_change(p,0);4140}4141else4142show_mode_change(p,1);4143}4144}4145}4146}41474148static voidpatch_stats(struct apply_state *state,struct patch *patch)4149{4150int lines = patch->lines_added + patch->lines_deleted;41514152if(lines > state->max_change)4153 state->max_change = lines;4154if(patch->old_name) {4155int len =quote_c_style(patch->old_name, NULL, NULL,0);4156if(!len)4157 len =strlen(patch->old_name);4158if(len > state->max_len)4159 state->max_len = len;4160}4161if(patch->new_name) {4162int len =quote_c_style(patch->new_name, NULL, NULL,0);4163if(!len)4164 len =strlen(patch->new_name);4165if(len > state->max_len)4166 state->max_len = len;4167}4168}41694170static voidremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4171{4172if(state->update_index) {4173if(remove_file_from_cache(patch->old_name) <0)4174die(_("unable to remove%sfrom index"), patch->old_name);4175}4176if(!state->cached) {4177if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4178remove_path(patch->old_name);4179}4180}4181}41824183static voidadd_index_file(struct apply_state *state,4184const char*path,4185unsigned mode,4186void*buf,4187unsigned long size)4188{4189struct stat st;4190struct cache_entry *ce;4191int namelen =strlen(path);4192unsigned ce_size =cache_entry_size(namelen);41934194if(!state->update_index)4195return;41964197 ce =xcalloc(1, ce_size);4198memcpy(ce->name, path, namelen);4199 ce->ce_mode =create_ce_mode(mode);4200 ce->ce_flags =create_ce_flags(0);4201 ce->ce_namelen = namelen;4202if(S_ISGITLINK(mode)) {4203const char*s;42044205if(!skip_prefix(buf,"Subproject commit ", &s) ||4206get_sha1_hex(s, ce->sha1))4207die(_("corrupt patch for submodule%s"), path);4208}else{4209if(!state->cached) {4210if(lstat(path, &st) <0)4211die_errno(_("unable to stat newly created file '%s'"),4212 path);4213fill_stat_cache_info(ce, &st);4214}4215if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4216die(_("unable to create backing store for newly created file%s"), path);4217}4218if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4219die(_("unable to add cache entry for%s"), path);4220}42214222static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4223{4224int fd;4225struct strbuf nbuf = STRBUF_INIT;42264227if(S_ISGITLINK(mode)) {4228struct stat st;4229if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4230return0;4231returnmkdir(path,0777);4232}42334234if(has_symlinks &&S_ISLNK(mode))4235/* Although buf:size is counted string, it also is NUL4236 * terminated.4237 */4238returnsymlink(buf, path);42394240 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4241if(fd <0)4242return-1;42434244if(convert_to_working_tree(path, buf, size, &nbuf)) {4245 size = nbuf.len;4246 buf = nbuf.buf;4247}4248write_or_die(fd, buf, size);4249strbuf_release(&nbuf);42504251if(close(fd) <0)4252die_errno(_("closing file '%s'"), path);4253return0;4254}42554256/*4257 * We optimistically assume that the directories exist,4258 * which is true 99% of the time anyway. If they don't,4259 * we create them and try again.4260 */4261static voidcreate_one_file(struct apply_state *state,4262char*path,4263unsigned mode,4264const char*buf,4265unsigned long size)4266{4267if(state->cached)4268return;4269if(!try_create_file(path, mode, buf, size))4270return;42714272if(errno == ENOENT) {4273if(safe_create_leading_directories(path))4274return;4275if(!try_create_file(path, mode, buf, size))4276return;4277}42784279if(errno == EEXIST || errno == EACCES) {4280/* We may be trying to create a file where a directory4281 * used to be.4282 */4283struct stat st;4284if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4285 errno = EEXIST;4286}42874288if(errno == EEXIST) {4289unsigned int nr =getpid();42904291for(;;) {4292char newpath[PATH_MAX];4293mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4294if(!try_create_file(newpath, mode, buf, size)) {4295if(!rename(newpath, path))4296return;4297unlink_or_warn(newpath);4298break;4299}4300if(errno != EEXIST)4301break;4302++nr;4303}4304}4305die_errno(_("unable to write file '%s' mode%o"), path, mode);4306}43074308static voidadd_conflicted_stages_file(struct apply_state *state,4309struct patch *patch)4310{4311int stage, namelen;4312unsigned ce_size, mode;4313struct cache_entry *ce;43144315if(!state->update_index)4316return;4317 namelen =strlen(patch->new_name);4318 ce_size =cache_entry_size(namelen);4319 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);43204321remove_file_from_cache(patch->new_name);4322for(stage =1; stage <4; stage++) {4323if(is_null_oid(&patch->threeway_stage[stage -1]))4324continue;4325 ce =xcalloc(1, ce_size);4326memcpy(ce->name, patch->new_name, namelen);4327 ce->ce_mode =create_ce_mode(mode);4328 ce->ce_flags =create_ce_flags(stage);4329 ce->ce_namelen = namelen;4330hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4331if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4332die(_("unable to add cache entry for%s"), patch->new_name);4333}4334}43354336static voidcreate_file(struct apply_state *state,struct patch *patch)4337{4338char*path = patch->new_name;4339unsigned mode = patch->new_mode;4340unsigned long size = patch->resultsize;4341char*buf = patch->result;43424343if(!mode)4344 mode = S_IFREG |0644;4345create_one_file(state, path, mode, buf, size);43464347if(patch->conflicted_threeway)4348add_conflicted_stages_file(state, patch);4349else4350add_index_file(state, path, mode, buf, size);4351}43524353/* phase zero is to remove, phase one is to create */4354static voidwrite_out_one_result(struct apply_state *state,4355struct patch *patch,4356int phase)4357{4358if(patch->is_delete >0) {4359if(phase ==0)4360remove_file(state, patch,1);4361return;4362}4363if(patch->is_new >0|| patch->is_copy) {4364if(phase ==1)4365create_file(state, patch);4366return;4367}4368/*4369 * Rename or modification boils down to the same4370 * thing: remove the old, write the new4371 */4372if(phase ==0)4373remove_file(state, patch, patch->is_rename);4374if(phase ==1)4375create_file(state, patch);4376}43774378static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4379{4380FILE*rej;4381char namebuf[PATH_MAX];4382struct fragment *frag;4383int cnt =0;4384struct strbuf sb = STRBUF_INIT;43854386for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4387if(!frag->rejected)4388continue;4389 cnt++;4390}43914392if(!cnt) {4393if(state->apply_verbosely)4394say_patch_name(stderr,4395_("Applied patch%scleanly."), patch);4396return0;4397}43984399/* This should not happen, because a removal patch that leaves4400 * contents are marked "rejected" at the patch level.4401 */4402if(!patch->new_name)4403die(_("internal error"));44044405/* Say this even without --verbose */4406strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4407"Applying patch %%swith%drejects...",4408 cnt),4409 cnt);4410say_patch_name(stderr, sb.buf, patch);4411strbuf_release(&sb);44124413 cnt =strlen(patch->new_name);4414if(ARRAY_SIZE(namebuf) <= cnt +5) {4415 cnt =ARRAY_SIZE(namebuf) -5;4416warning(_("truncating .rej filename to %.*s.rej"),4417 cnt -1, patch->new_name);4418}4419memcpy(namebuf, patch->new_name, cnt);4420memcpy(namebuf + cnt,".rej",5);44214422 rej =fopen(namebuf,"w");4423if(!rej)4424returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));44254426/* Normal git tools never deal with .rej, so do not pretend4427 * this is a git patch by saying --git or giving extended4428 * headers. While at it, maybe please "kompare" that wants4429 * the trailing TAB and some garbage at the end of line ;-).4430 */4431fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4432 patch->new_name, patch->new_name);4433for(cnt =1, frag = patch->fragments;4434 frag;4435 cnt++, frag = frag->next) {4436if(!frag->rejected) {4437fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4438continue;4439}4440fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4441fprintf(rej,"%.*s", frag->size, frag->patch);4442if(frag->patch[frag->size-1] !='\n')4443fputc('\n', rej);4444}4445fclose(rej);4446return-1;4447}44484449static intwrite_out_results(struct apply_state *state,struct patch *list)4450{4451int phase;4452int errs =0;4453struct patch *l;4454struct string_list cpath = STRING_LIST_INIT_DUP;44554456for(phase =0; phase <2; phase++) {4457 l = list;4458while(l) {4459if(l->rejected)4460 errs =1;4461else{4462write_out_one_result(state, l, phase);4463if(phase ==1) {4464if(write_out_one_reject(state, l))4465 errs =1;4466if(l->conflicted_threeway) {4467string_list_append(&cpath, l->new_name);4468 errs =1;4469}4470}4471}4472 l = l->next;4473}4474}44754476if(cpath.nr) {4477struct string_list_item *item;44784479string_list_sort(&cpath);4480for_each_string_list_item(item, &cpath)4481fprintf(stderr,"U%s\n", item->string);4482string_list_clear(&cpath,0);44834484rerere(0);4485}44864487return errs;4488}44894490static struct lock_file lock_file;44914492#define INACCURATE_EOF (1<<0)4493#define RECOUNT (1<<1)44944495static intapply_patch(struct apply_state *state,4496int fd,4497const char*filename,4498int options)4499{4500size_t offset;4501struct strbuf buf = STRBUF_INIT;/* owns the patch text */4502struct patch *list = NULL, **listp = &list;4503int skipped_patch =0;45044505 state->patch_input_file = filename;4506read_patch_file(&buf, fd);4507 offset =0;4508while(offset < buf.len) {4509struct patch *patch;4510int nr;45114512 patch =xcalloc(1,sizeof(*patch));4513 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4514 patch->recount = !!(options & RECOUNT);4515 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4516if(nr <0) {4517free_patch(patch);4518break;4519}4520if(state->apply_in_reverse)4521reverse_patches(patch);4522if(use_patch(state, patch)) {4523patch_stats(state, patch);4524*listp = patch;4525 listp = &patch->next;4526}4527else{4528if(state->apply_verbosely)4529say_patch_name(stderr,_("Skipped patch '%s'."), patch);4530free_patch(patch);4531 skipped_patch++;4532}4533 offset += nr;4534}45354536if(!list && !skipped_patch)4537die(_("unrecognized input"));45384539if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4540 state->apply =0;45414542 state->update_index = state->check_index && state->apply;4543if(state->update_index && newfd <0)4544 newfd =hold_locked_index(&lock_file,1);45454546if(state->check_index) {4547if(read_cache() <0)4548die(_("unable to read index file"));4549}45504551if((state->check || state->apply) &&4552check_patch_list(state, list) <0&&4553!state->apply_with_reject)4554exit(1);45554556if(state->apply &&write_out_results(state, list)) {4557if(state->apply_with_reject)4558exit(1);4559/* with --3way, we still need to write the index out */4560return1;4561}45624563if(state->fake_ancestor)4564build_fake_ancestor(list, state->fake_ancestor);45654566if(state->diffstat)4567stat_patch_list(state, list);45684569if(state->numstat)4570numstat_patch_list(state, list);45714572if(state->summary)4573summary_patch_list(list);45744575free_patch_list(list);4576strbuf_release(&buf);4577string_list_clear(&fn_table,0);4578return0;4579}45804581static voidgit_apply_config(void)4582{4583git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4584git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4585git_config(git_default_config, NULL);4586}45874588static intoption_parse_exclude(const struct option *opt,4589const char*arg,int unset)4590{4591struct apply_state *state = opt->value;4592add_name_limit(state, arg,1);4593return0;4594}45954596static intoption_parse_include(const struct option *opt,4597const char*arg,int unset)4598{4599struct apply_state *state = opt->value;4600add_name_limit(state, arg,0);4601 state->has_include =1;4602return0;4603}46044605static intoption_parse_p(const struct option *opt,4606const char*arg,4607int unset)4608{4609struct apply_state *state = opt->value;4610 state->p_value =atoi(arg);4611 state->p_value_known =1;4612return0;4613}46144615static intoption_parse_space_change(const struct option *opt,4616const char*arg,int unset)4617{4618struct apply_state *state = opt->value;4619if(unset)4620 state->ws_ignore_action = ignore_ws_none;4621else4622 state->ws_ignore_action = ignore_ws_change;4623return0;4624}46254626static intoption_parse_whitespace(const struct option *opt,4627const char*arg,int unset)4628{4629struct apply_state *state = opt->value;4630 state->whitespace_option = arg;4631parse_whitespace_option(state, arg);4632return0;4633}46344635static intoption_parse_directory(const struct option *opt,4636const char*arg,int unset)4637{4638struct apply_state *state = opt->value;4639strbuf_reset(&state->root);4640strbuf_addstr(&state->root, arg);4641strbuf_complete(&state->root,'/');4642return0;4643}46444645static voidinit_apply_state(struct apply_state *state,const char*prefix)4646{4647memset(state,0,sizeof(*state));4648 state->prefix = prefix;4649 state->prefix_length = state->prefix ?strlen(state->prefix) :0;4650 state->apply =1;4651 state->line_termination ='\n';4652 state->p_value =1;4653 state->p_context = UINT_MAX;4654 state->squelch_whitespace_errors =5;4655 state->ws_error_action = warn_on_ws_error;4656 state->ws_ignore_action = ignore_ws_none;4657strbuf_init(&state->root,0);46584659git_apply_config();4660if(apply_default_whitespace)4661parse_whitespace_option(state, apply_default_whitespace);4662if(apply_default_ignorewhitespace)4663parse_ignorewhitespace_option(state, apply_default_ignorewhitespace);4664}46654666static voidclear_apply_state(struct apply_state *state)4667{4668string_list_clear(&state->limit_by_name,0);4669strbuf_release(&state->root);4670}46714672intcmd_apply(int argc,const char**argv,const char*prefix)4673{4674int i;4675int errs =0;4676int is_not_gitdir = !startup_info->have_repository;4677int force_apply =0;4678int options =0;4679int read_stdin =1;4680struct apply_state state;46814682struct option builtin_apply_options[] = {4683{ OPTION_CALLBACK,0,"exclude", &state,N_("path"),4684N_("don't apply changes matching the given path"),46850, option_parse_exclude },4686{ OPTION_CALLBACK,0,"include", &state,N_("path"),4687N_("apply changes matching the given path"),46880, option_parse_include },4689{ OPTION_CALLBACK,'p', NULL, &state,N_("num"),4690N_("remove <num> leading slashes from traditional diff paths"),46910, option_parse_p },4692OPT_BOOL(0,"no-add", &state.no_add,4693N_("ignore additions made by the patch")),4694OPT_BOOL(0,"stat", &state.diffstat,4695N_("instead of applying the patch, output diffstat for the input")),4696OPT_NOOP_NOARG(0,"allow-binary-replacement"),4697OPT_NOOP_NOARG(0,"binary"),4698OPT_BOOL(0,"numstat", &state.numstat,4699N_("show number of added and deleted lines in decimal notation")),4700OPT_BOOL(0,"summary", &state.summary,4701N_("instead of applying the patch, output a summary for the input")),4702OPT_BOOL(0,"check", &state.check,4703N_("instead of applying the patch, see if the patch is applicable")),4704OPT_BOOL(0,"index", &state.check_index,4705N_("make sure the patch is applicable to the current index")),4706OPT_BOOL(0,"cached", &state.cached,4707N_("apply a patch without touching the working tree")),4708OPT_BOOL(0,"unsafe-paths", &state.unsafe_paths,4709N_("accept a patch that touches outside the working area")),4710OPT_BOOL(0,"apply", &force_apply,4711N_("also apply the patch (use with --stat/--summary/--check)")),4712OPT_BOOL('3',"3way", &state.threeway,4713N_("attempt three-way merge if a patch does not apply")),4714OPT_FILENAME(0,"build-fake-ancestor", &state.fake_ancestor,4715N_("build a temporary index based on embedded index information")),4716/* Think twice before adding "--nul" synonym to this */4717OPT_SET_INT('z', NULL, &state.line_termination,4718N_("paths are separated with NUL character"),'\0'),4719OPT_INTEGER('C', NULL, &state.p_context,4720N_("ensure at least <n> lines of context match")),4721{ OPTION_CALLBACK,0,"whitespace", &state,N_("action"),4722N_("detect new or modified lines that have whitespace errors"),47230, option_parse_whitespace },4724{ OPTION_CALLBACK,0,"ignore-space-change", &state, NULL,4725N_("ignore changes in whitespace when finding context"),4726 PARSE_OPT_NOARG, option_parse_space_change },4727{ OPTION_CALLBACK,0,"ignore-whitespace", &state, NULL,4728N_("ignore changes in whitespace when finding context"),4729 PARSE_OPT_NOARG, option_parse_space_change },4730OPT_BOOL('R',"reverse", &state.apply_in_reverse,4731N_("apply the patch in reverse")),4732OPT_BOOL(0,"unidiff-zero", &state.unidiff_zero,4733N_("don't expect at least one line of context")),4734OPT_BOOL(0,"reject", &state.apply_with_reject,4735N_("leave the rejected hunks in corresponding *.rej files")),4736OPT_BOOL(0,"allow-overlap", &state.allow_overlap,4737N_("allow overlapping hunks")),4738OPT__VERBOSE(&state.apply_verbosely,N_("be verbose")),4739OPT_BIT(0,"inaccurate-eof", &options,4740N_("tolerate incorrectly detected missing new-line at the end of file"),4741 INACCURATE_EOF),4742OPT_BIT(0,"recount", &options,4743N_("do not trust the line counts in the hunk headers"),4744 RECOUNT),4745{ OPTION_CALLBACK,0,"directory", &state,N_("root"),4746N_("prepend <root> to all filenames"),47470, option_parse_directory },4748OPT_END()4749};47504751init_apply_state(&state, prefix);47524753 argc =parse_options(argc, argv, state.prefix, builtin_apply_options,4754 apply_usage,0);47554756if(state.apply_with_reject && state.threeway)4757die("--reject and --3way cannot be used together.");4758if(state.cached && state.threeway)4759die("--cached and --3way cannot be used together.");4760if(state.threeway) {4761if(is_not_gitdir)4762die(_("--3way outside a repository"));4763 state.check_index =1;4764}4765if(state.apply_with_reject)4766 state.apply = state.apply_verbosely =1;4767if(!force_apply && (state.diffstat || state.numstat || state.summary || state.check || state.fake_ancestor))4768 state.apply =0;4769if(state.check_index && is_not_gitdir)4770die(_("--index outside a repository"));4771if(state.cached) {4772if(is_not_gitdir)4773die(_("--cached outside a repository"));4774 state.check_index =1;4775}4776if(state.check_index)4777 state.unsafe_paths =0;47784779for(i =0; i < argc; i++) {4780const char*arg = argv[i];4781int fd;47824783if(!strcmp(arg,"-")) {4784 errs |=apply_patch(&state,0,"<stdin>", options);4785 read_stdin =0;4786continue;4787}else if(0< state.prefix_length)4788 arg =prefix_filename(state.prefix,4789 state.prefix_length,4790 arg);47914792 fd =open(arg, O_RDONLY);4793if(fd <0)4794die_errno(_("can't open patch '%s'"), arg);4795 read_stdin =0;4796set_default_whitespace_mode(&state);4797 errs |=apply_patch(&state, fd, arg, options);4798close(fd);4799}4800set_default_whitespace_mode(&state);4801if(read_stdin)4802 errs |=apply_patch(&state,0,"<stdin>", options);4803if(state.whitespace_error) {4804if(state.squelch_whitespace_errors &&4805 state.squelch_whitespace_errors < state.whitespace_error) {4806int squelched =4807 state.whitespace_error - state.squelch_whitespace_errors;4808warning(Q_("squelched%dwhitespace error",4809"squelched%dwhitespace errors",4810 squelched),4811 squelched);4812}4813if(state.ws_error_action == die_on_ws_error)4814die(Q_("%dline adds whitespace errors.",4815"%dlines add whitespace errors.",4816 state.whitespace_error),4817 state.whitespace_error);4818if(state.applied_after_fixing_ws && state.apply)4819warning("%dline%sapplied after"4820" fixing whitespace errors.",4821 state.applied_after_fixing_ws,4822 state.applied_after_fixing_ws ==1?"":"s");4823else if(state.whitespace_error)4824warning(Q_("%dline adds whitespace errors.",4825"%dlines add whitespace errors.",4826 state.whitespace_error),4827 state.whitespace_error);4828}48294830if(state.update_index) {4831if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK))4832die(_("Unable to write new index file"));4833}48344835clear_apply_state(&state);48364837return!!errs;4838}