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 37/* 38 * We need to keep track of how symlinks in the preimage are 39 * manipulated by the patches. A patch to add a/b/c where a/b 40 * is a symlink should not be allowed to affect the directory 41 * the symlink points at, but if the same patch removes a/b, 42 * it is perfectly fine, as the patch removes a/b to make room 43 * to create a directory a/b so that a/b/c can be created. 44 * 45 * See also "struct string_list symlink_changes" in "struct 46 * apply_state". 47 */ 48#define SYMLINK_GOES_AWAY 01 49#define SYMLINK_IN_RESULT 02 50 51struct apply_state { 52const char*prefix; 53int prefix_length; 54 55/* 56 * Since lockfile.c keeps a linked list of all created 57 * lock_file structures, it isn't safe to free(lock_file). 58 */ 59struct lock_file *lock_file; 60 61/* These control what gets looked at and modified */ 62int apply;/* this is not a dry-run */ 63int cached;/* apply to the index only */ 64int check;/* preimage must match working tree, don't actually apply */ 65int check_index;/* preimage must match the indexed version */ 66int update_index;/* check_index && apply */ 67 68/* These control cosmetic aspect of the output */ 69int diffstat;/* just show a diffstat, and don't actually apply */ 70int numstat;/* just show a numeric diffstat, and don't actually apply */ 71int summary;/* just report creation, deletion, etc, and don't actually apply */ 72 73/* These boolean parameters control how the apply is done */ 74int allow_overlap; 75int apply_in_reverse; 76int apply_with_reject; 77int apply_verbosely; 78int no_add; 79int threeway; 80int unidiff_zero; 81int unsafe_paths; 82 83/* Other non boolean parameters */ 84const char*fake_ancestor; 85const char*patch_input_file; 86int line_termination; 87struct strbuf root; 88int p_value; 89int p_value_known; 90unsigned int p_context; 91 92/* Exclude and include path parameters */ 93struct string_list limit_by_name; 94int has_include; 95 96/* Various "current state" */ 97int linenr;/* current line number */ 98struct string_list symlink_changes;/* we have to track symlinks */ 99 100/* 101 * For "diff-stat" like behaviour, we keep track of the biggest change 102 * we've seen, and the longest filename. That allows us to do simple 103 * scaling. 104 */ 105int max_change; 106int max_len; 107 108/* 109 * Records filenames that have been touched, in order to handle 110 * the case where more than one patches touch the same file. 111 */ 112struct string_list fn_table; 113 114/* These control whitespace errors */ 115enum ws_error_action ws_error_action; 116enum ws_ignore ws_ignore_action; 117const char*whitespace_option; 118int whitespace_error; 119int squelch_whitespace_errors; 120int applied_after_fixing_ws; 121}; 122 123static int newfd = -1; 124 125static const char*const apply_usage[] = { 126N_("git apply [<options>] [<patch>...]"), 127 NULL 128}; 129 130static voidparse_whitespace_option(struct apply_state *state,const char*option) 131{ 132if(!option) { 133 state->ws_error_action = warn_on_ws_error; 134return; 135} 136if(!strcmp(option,"warn")) { 137 state->ws_error_action = warn_on_ws_error; 138return; 139} 140if(!strcmp(option,"nowarn")) { 141 state->ws_error_action = nowarn_ws_error; 142return; 143} 144if(!strcmp(option,"error")) { 145 state->ws_error_action = die_on_ws_error; 146return; 147} 148if(!strcmp(option,"error-all")) { 149 state->ws_error_action = die_on_ws_error; 150 state->squelch_whitespace_errors =0; 151return; 152} 153if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 154 state->ws_error_action = correct_ws_error; 155return; 156} 157die(_("unrecognized whitespace option '%s'"), option); 158} 159 160static voidparse_ignorewhitespace_option(struct apply_state *state, 161const char*option) 162{ 163if(!option || !strcmp(option,"no") || 164!strcmp(option,"false") || !strcmp(option,"never") || 165!strcmp(option,"none")) { 166 state->ws_ignore_action = ignore_ws_none; 167return; 168} 169if(!strcmp(option,"change")) { 170 state->ws_ignore_action = ignore_ws_change; 171return; 172} 173die(_("unrecognized whitespace ignore option '%s'"), option); 174} 175 176static voidset_default_whitespace_mode(struct apply_state *state) 177{ 178if(!state->whitespace_option && !apply_default_whitespace) 179 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 180} 181 182/* 183 * This represents one "hunk" from a patch, starting with 184 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 185 * patch text is pointed at by patch, and its byte length 186 * is stored in size. leading and trailing are the number 187 * of context lines. 188 */ 189struct fragment { 190unsigned long leading, trailing; 191unsigned long oldpos, oldlines; 192unsigned long newpos, newlines; 193/* 194 * 'patch' is usually borrowed from buf in apply_patch(), 195 * but some codepaths store an allocated buffer. 196 */ 197const char*patch; 198unsigned free_patch:1, 199 rejected:1; 200int size; 201int linenr; 202struct fragment *next; 203}; 204 205/* 206 * When dealing with a binary patch, we reuse "leading" field 207 * to store the type of the binary hunk, either deflated "delta" 208 * or deflated "literal". 209 */ 210#define binary_patch_method leading 211#define BINARY_DELTA_DEFLATED 1 212#define BINARY_LITERAL_DEFLATED 2 213 214/* 215 * This represents a "patch" to a file, both metainfo changes 216 * such as creation/deletion, filemode and content changes represented 217 * as a series of fragments. 218 */ 219struct patch { 220char*new_name, *old_name, *def_name; 221unsigned int old_mode, new_mode; 222int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 223int rejected; 224unsigned ws_rule; 225int lines_added, lines_deleted; 226int score; 227unsigned int is_toplevel_relative:1; 228unsigned int inaccurate_eof:1; 229unsigned int is_binary:1; 230unsigned int is_copy:1; 231unsigned int is_rename:1; 232unsigned int recount:1; 233unsigned int conflicted_threeway:1; 234unsigned int direct_to_threeway:1; 235struct fragment *fragments; 236char*result; 237size_t resultsize; 238char old_sha1_prefix[41]; 239char new_sha1_prefix[41]; 240struct patch *next; 241 242/* three-way fallback result */ 243struct object_id threeway_stage[3]; 244}; 245 246static voidfree_fragment_list(struct fragment *list) 247{ 248while(list) { 249struct fragment *next = list->next; 250if(list->free_patch) 251free((char*)list->patch); 252free(list); 253 list = next; 254} 255} 256 257static voidfree_patch(struct patch *patch) 258{ 259free_fragment_list(patch->fragments); 260free(patch->def_name); 261free(patch->old_name); 262free(patch->new_name); 263free(patch->result); 264free(patch); 265} 266 267static voidfree_patch_list(struct patch *list) 268{ 269while(list) { 270struct patch *next = list->next; 271free_patch(list); 272 list = next; 273} 274} 275 276/* 277 * A line in a file, len-bytes long (includes the terminating LF, 278 * except for an incomplete line at the end if the file ends with 279 * one), and its contents hashes to 'hash'. 280 */ 281struct line { 282size_t len; 283unsigned hash :24; 284unsigned flag :8; 285#define LINE_COMMON 1 286#define LINE_PATCHED 2 287}; 288 289/* 290 * This represents a "file", which is an array of "lines". 291 */ 292struct image { 293char*buf; 294size_t len; 295size_t nr; 296size_t alloc; 297struct line *line_allocated; 298struct line *line; 299}; 300 301static uint32_thash_line(const char*cp,size_t len) 302{ 303size_t i; 304uint32_t h; 305for(i =0, h =0; i < len; i++) { 306if(!isspace(cp[i])) { 307 h = h *3+ (cp[i] &0xff); 308} 309} 310return h; 311} 312 313/* 314 * Compare lines s1 of length n1 and s2 of length n2, ignoring 315 * whitespace difference. Returns 1 if they match, 0 otherwise 316 */ 317static intfuzzy_matchlines(const char*s1,size_t n1, 318const char*s2,size_t n2) 319{ 320const char*last1 = s1 + n1 -1; 321const char*last2 = s2 + n2 -1; 322int result =0; 323 324/* ignore line endings */ 325while((*last1 =='\r') || (*last1 =='\n')) 326 last1--; 327while((*last2 =='\r') || (*last2 =='\n')) 328 last2--; 329 330/* skip leading whitespaces, if both begin with whitespace */ 331if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 332while(isspace(*s1) && (s1 <= last1)) 333 s1++; 334while(isspace(*s2) && (s2 <= last2)) 335 s2++; 336} 337/* early return if both lines are empty */ 338if((s1 > last1) && (s2 > last2)) 339return1; 340while(!result) { 341 result = *s1++ - *s2++; 342/* 343 * Skip whitespace inside. We check for whitespace on 344 * both buffers because we don't want "a b" to match 345 * "ab" 346 */ 347if(isspace(*s1) &&isspace(*s2)) { 348while(isspace(*s1) && s1 <= last1) 349 s1++; 350while(isspace(*s2) && s2 <= last2) 351 s2++; 352} 353/* 354 * If we reached the end on one side only, 355 * lines don't match 356 */ 357if( 358((s2 > last2) && (s1 <= last1)) || 359((s1 > last1) && (s2 <= last2))) 360return0; 361if((s1 > last1) && (s2 > last2)) 362break; 363} 364 365return!result; 366} 367 368static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 369{ 370ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 371 img->line_allocated[img->nr].len = len; 372 img->line_allocated[img->nr].hash =hash_line(bol, len); 373 img->line_allocated[img->nr].flag = flag; 374 img->nr++; 375} 376 377/* 378 * "buf" has the file contents to be patched (read from various sources). 379 * attach it to "image" and add line-based index to it. 380 * "image" now owns the "buf". 381 */ 382static voidprepare_image(struct image *image,char*buf,size_t len, 383int prepare_linetable) 384{ 385const char*cp, *ep; 386 387memset(image,0,sizeof(*image)); 388 image->buf = buf; 389 image->len = len; 390 391if(!prepare_linetable) 392return; 393 394 ep = image->buf + image->len; 395 cp = image->buf; 396while(cp < ep) { 397const char*next; 398for(next = cp; next < ep && *next !='\n'; next++) 399; 400if(next < ep) 401 next++; 402add_line_info(image, cp, next - cp,0); 403 cp = next; 404} 405 image->line = image->line_allocated; 406} 407 408static voidclear_image(struct image *image) 409{ 410free(image->buf); 411free(image->line_allocated); 412memset(image,0,sizeof(*image)); 413} 414 415/* fmt must contain _one_ %s and no other substitution */ 416static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 417{ 418struct strbuf sb = STRBUF_INIT; 419 420if(patch->old_name && patch->new_name && 421strcmp(patch->old_name, patch->new_name)) { 422quote_c_style(patch->old_name, &sb, NULL,0); 423strbuf_addstr(&sb," => "); 424quote_c_style(patch->new_name, &sb, NULL,0); 425}else{ 426const char*n = patch->new_name; 427if(!n) 428 n = patch->old_name; 429quote_c_style(n, &sb, NULL,0); 430} 431fprintf(output, fmt, sb.buf); 432fputc('\n', output); 433strbuf_release(&sb); 434} 435 436#define SLOP (16) 437 438static voidread_patch_file(struct strbuf *sb,int fd) 439{ 440if(strbuf_read(sb, fd,0) <0) 441die_errno("git apply: failed to read"); 442 443/* 444 * Make sure that we have some slop in the buffer 445 * so that we can do speculative "memcmp" etc, and 446 * see to it that it is NUL-filled. 447 */ 448strbuf_grow(sb, SLOP); 449memset(sb->buf + sb->len,0, SLOP); 450} 451 452static unsigned longlinelen(const char*buffer,unsigned long size) 453{ 454unsigned long len =0; 455while(size--) { 456 len++; 457if(*buffer++ =='\n') 458break; 459} 460return len; 461} 462 463static intis_dev_null(const char*str) 464{ 465returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 466} 467 468#define TERM_SPACE 1 469#define TERM_TAB 2 470 471static intname_terminate(const char*name,int namelen,int c,int terminate) 472{ 473if(c ==' '&& !(terminate & TERM_SPACE)) 474return0; 475if(c =='\t'&& !(terminate & TERM_TAB)) 476return0; 477 478return1; 479} 480 481/* remove double slashes to make --index work with such filenames */ 482static char*squash_slash(char*name) 483{ 484int i =0, j =0; 485 486if(!name) 487return NULL; 488 489while(name[i]) { 490if((name[j++] = name[i++]) =='/') 491while(name[i] =='/') 492 i++; 493} 494 name[j] ='\0'; 495return name; 496} 497 498static char*find_name_gnu(struct apply_state *state, 499const char*line, 500const char*def, 501int p_value) 502{ 503struct strbuf name = STRBUF_INIT; 504char*cp; 505 506/* 507 * Proposed "new-style" GNU patch/diff format; see 508 * http://marc.info/?l=git&m=112927316408690&w=2 509 */ 510if(unquote_c_style(&name, line, NULL)) { 511strbuf_release(&name); 512return NULL; 513} 514 515for(cp = name.buf; p_value; p_value--) { 516 cp =strchr(cp,'/'); 517if(!cp) { 518strbuf_release(&name); 519return NULL; 520} 521 cp++; 522} 523 524strbuf_remove(&name,0, cp - name.buf); 525if(state->root.len) 526strbuf_insert(&name,0, state->root.buf, state->root.len); 527returnsquash_slash(strbuf_detach(&name, NULL)); 528} 529 530static size_tsane_tz_len(const char*line,size_t len) 531{ 532const char*tz, *p; 533 534if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 535return0; 536 tz = line + len -strlen(" +0500"); 537 538if(tz[1] !='+'&& tz[1] !='-') 539return0; 540 541for(p = tz +2; p != line + len; p++) 542if(!isdigit(*p)) 543return0; 544 545return line + len - tz; 546} 547 548static size_ttz_with_colon_len(const char*line,size_t len) 549{ 550const char*tz, *p; 551 552if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 553return0; 554 tz = line + len -strlen(" +08:00"); 555 556if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 557return0; 558 p = tz +2; 559if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 560!isdigit(*p++) || !isdigit(*p++)) 561return0; 562 563return line + len - tz; 564} 565 566static size_tdate_len(const char*line,size_t len) 567{ 568const char*date, *p; 569 570if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 571return0; 572 p = date = line + len -strlen("72-02-05"); 573 574if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 575!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 576!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 577return0; 578 579if(date - line >=strlen("19") && 580isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 581 date -=strlen("19"); 582 583return line + len - date; 584} 585 586static size_tshort_time_len(const char*line,size_t len) 587{ 588const char*time, *p; 589 590if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 591return0; 592 p = time = line + len -strlen(" 07:01:32"); 593 594/* Permit 1-digit hours? */ 595if(*p++ !=' '|| 596!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 597!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 598!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 599return0; 600 601return line + len - time; 602} 603 604static size_tfractional_time_len(const char*line,size_t len) 605{ 606const char*p; 607size_t n; 608 609/* Expected format: 19:41:17.620000023 */ 610if(!len || !isdigit(line[len -1])) 611return0; 612 p = line + len -1; 613 614/* Fractional seconds. */ 615while(p > line &&isdigit(*p)) 616 p--; 617if(*p !='.') 618return0; 619 620/* Hours, minutes, and whole seconds. */ 621 n =short_time_len(line, p - line); 622if(!n) 623return0; 624 625return line + len - p + n; 626} 627 628static size_ttrailing_spaces_len(const char*line,size_t len) 629{ 630const char*p; 631 632/* Expected format: ' ' x (1 or more) */ 633if(!len || line[len -1] !=' ') 634return0; 635 636 p = line + len; 637while(p != line) { 638 p--; 639if(*p !=' ') 640return line + len - (p +1); 641} 642 643/* All spaces! */ 644return len; 645} 646 647static size_tdiff_timestamp_len(const char*line,size_t len) 648{ 649const char*end = line + len; 650size_t n; 651 652/* 653 * Posix: 2010-07-05 19:41:17 654 * GNU: 2010-07-05 19:41:17.620000023 -0500 655 */ 656 657if(!isdigit(end[-1])) 658return0; 659 660 n =sane_tz_len(line, end - line); 661if(!n) 662 n =tz_with_colon_len(line, end - line); 663 end -= n; 664 665 n =short_time_len(line, end - line); 666if(!n) 667 n =fractional_time_len(line, end - line); 668 end -= n; 669 670 n =date_len(line, end - line); 671if(!n)/* No date. Too bad. */ 672return0; 673 end -= n; 674 675if(end == line)/* No space before date. */ 676return0; 677if(end[-1] =='\t') {/* Success! */ 678 end--; 679return line + len - end; 680} 681if(end[-1] !=' ')/* No space before date. */ 682return0; 683 684/* Whitespace damage. */ 685 end -=trailing_spaces_len(line, end - line); 686return line + len - end; 687} 688 689static char*find_name_common(struct apply_state *state, 690const char*line, 691const char*def, 692int p_value, 693const char*end, 694int terminate) 695{ 696int len; 697const char*start = NULL; 698 699if(p_value ==0) 700 start = line; 701while(line != end) { 702char c = *line; 703 704if(!end &&isspace(c)) { 705if(c =='\n') 706break; 707if(name_terminate(start, line-start, c, terminate)) 708break; 709} 710 line++; 711if(c =='/'&& !--p_value) 712 start = line; 713} 714if(!start) 715returnsquash_slash(xstrdup_or_null(def)); 716 len = line - start; 717if(!len) 718returnsquash_slash(xstrdup_or_null(def)); 719 720/* 721 * Generally we prefer the shorter name, especially 722 * if the other one is just a variation of that with 723 * something else tacked on to the end (ie "file.orig" 724 * or "file~"). 725 */ 726if(def) { 727int deflen =strlen(def); 728if(deflen < len && !strncmp(start, def, deflen)) 729returnsquash_slash(xstrdup(def)); 730} 731 732if(state->root.len) { 733char*ret =xstrfmt("%s%.*s", state->root.buf, len, start); 734returnsquash_slash(ret); 735} 736 737returnsquash_slash(xmemdupz(start, len)); 738} 739 740static char*find_name(struct apply_state *state, 741const char*line, 742char*def, 743int p_value, 744int terminate) 745{ 746if(*line =='"') { 747char*name =find_name_gnu(state, line, def, p_value); 748if(name) 749return name; 750} 751 752returnfind_name_common(state, line, def, p_value, NULL, terminate); 753} 754 755static char*find_name_traditional(struct apply_state *state, 756const char*line, 757char*def, 758int p_value) 759{ 760size_t len; 761size_t date_len; 762 763if(*line =='"') { 764char*name =find_name_gnu(state, line, def, p_value); 765if(name) 766return name; 767} 768 769 len =strchrnul(line,'\n') - line; 770 date_len =diff_timestamp_len(line, len); 771if(!date_len) 772returnfind_name_common(state, line, def, p_value, NULL, TERM_TAB); 773 len -= date_len; 774 775returnfind_name_common(state, line, def, p_value, line + len,0); 776} 777 778static intcount_slashes(const char*cp) 779{ 780int cnt =0; 781char ch; 782 783while((ch = *cp++)) 784if(ch =='/') 785 cnt++; 786return cnt; 787} 788 789/* 790 * Given the string after "--- " or "+++ ", guess the appropriate 791 * p_value for the given patch. 792 */ 793static intguess_p_value(struct apply_state *state,const char*nameline) 794{ 795char*name, *cp; 796int val = -1; 797 798if(is_dev_null(nameline)) 799return-1; 800 name =find_name_traditional(state, nameline, NULL,0); 801if(!name) 802return-1; 803 cp =strchr(name,'/'); 804if(!cp) 805 val =0; 806else if(state->prefix) { 807/* 808 * Does it begin with "a/$our-prefix" and such? Then this is 809 * very likely to apply to our directory. 810 */ 811if(!strncmp(name, state->prefix, state->prefix_length)) 812 val =count_slashes(state->prefix); 813else{ 814 cp++; 815if(!strncmp(cp, state->prefix, state->prefix_length)) 816 val =count_slashes(state->prefix) +1; 817} 818} 819free(name); 820return val; 821} 822 823/* 824 * Does the ---/+++ line have the POSIX timestamp after the last HT? 825 * GNU diff puts epoch there to signal a creation/deletion event. Is 826 * this such a timestamp? 827 */ 828static inthas_epoch_timestamp(const char*nameline) 829{ 830/* 831 * We are only interested in epoch timestamp; any non-zero 832 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 833 * For the same reason, the date must be either 1969-12-31 or 834 * 1970-01-01, and the seconds part must be "00". 835 */ 836const char stamp_regexp[] = 837"^(1969-12-31|1970-01-01)" 838" " 839"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 840" " 841"([-+][0-2][0-9]:?[0-5][0-9])\n"; 842const char*timestamp = NULL, *cp, *colon; 843static regex_t *stamp; 844 regmatch_t m[10]; 845int zoneoffset; 846int hourminute; 847int status; 848 849for(cp = nameline; *cp !='\n'; cp++) { 850if(*cp =='\t') 851 timestamp = cp +1; 852} 853if(!timestamp) 854return0; 855if(!stamp) { 856 stamp =xmalloc(sizeof(*stamp)); 857if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 858warning(_("Cannot prepare timestamp regexp%s"), 859 stamp_regexp); 860return0; 861} 862} 863 864 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 865if(status) { 866if(status != REG_NOMATCH) 867warning(_("regexec returned%dfor input:%s"), 868 status, timestamp); 869return0; 870} 871 872 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 873if(*colon ==':') 874 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 875else 876 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 877if(timestamp[m[3].rm_so] =='-') 878 zoneoffset = -zoneoffset; 879 880/* 881 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 882 * (west of GMT) or 1970-01-01 (east of GMT) 883 */ 884if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 885(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 886return0; 887 888 hourminute = (strtol(timestamp +11, NULL,10) *60+ 889strtol(timestamp +14, NULL,10) - 890 zoneoffset); 891 892return((zoneoffset <0&& hourminute ==1440) || 893(0<= zoneoffset && !hourminute)); 894} 895 896/* 897 * Get the name etc info from the ---/+++ lines of a traditional patch header 898 * 899 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 900 * files, we can happily check the index for a match, but for creating a 901 * new file we should try to match whatever "patch" does. I have no idea. 902 */ 903static voidparse_traditional_patch(struct apply_state *state, 904const char*first, 905const char*second, 906struct patch *patch) 907{ 908char*name; 909 910 first +=4;/* skip "--- " */ 911 second +=4;/* skip "+++ " */ 912if(!state->p_value_known) { 913int p, q; 914 p =guess_p_value(state, first); 915 q =guess_p_value(state, second); 916if(p <0) p = q; 917if(0<= p && p == q) { 918 state->p_value = p; 919 state->p_value_known =1; 920} 921} 922if(is_dev_null(first)) { 923 patch->is_new =1; 924 patch->is_delete =0; 925 name =find_name_traditional(state, second, NULL, state->p_value); 926 patch->new_name = name; 927}else if(is_dev_null(second)) { 928 patch->is_new =0; 929 patch->is_delete =1; 930 name =find_name_traditional(state, first, NULL, state->p_value); 931 patch->old_name = name; 932}else{ 933char*first_name; 934 first_name =find_name_traditional(state, first, NULL, state->p_value); 935 name =find_name_traditional(state, second, first_name, state->p_value); 936free(first_name); 937if(has_epoch_timestamp(first)) { 938 patch->is_new =1; 939 patch->is_delete =0; 940 patch->new_name = name; 941}else if(has_epoch_timestamp(second)) { 942 patch->is_new =0; 943 patch->is_delete =1; 944 patch->old_name = name; 945}else{ 946 patch->old_name = name; 947 patch->new_name =xstrdup_or_null(name); 948} 949} 950if(!name) 951die(_("unable to find filename in patch at line%d"), state->linenr); 952} 953 954static intgitdiff_hdrend(struct apply_state *state, 955const char*line, 956struct patch *patch) 957{ 958return-1; 959} 960 961/* 962 * We're anal about diff header consistency, to make 963 * sure that we don't end up having strange ambiguous 964 * patches floating around. 965 * 966 * As a result, gitdiff_{old|new}name() will check 967 * their names against any previous information, just 968 * to make sure.. 969 */ 970#define DIFF_OLD_NAME 0 971#define DIFF_NEW_NAME 1 972 973static voidgitdiff_verify_name(struct apply_state *state, 974const char*line, 975int isnull, 976char**name, 977int side) 978{ 979if(!*name && !isnull) { 980*name =find_name(state, line, NULL, state->p_value, TERM_TAB); 981return; 982} 983 984if(*name) { 985int len =strlen(*name); 986char*another; 987if(isnull) 988die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 989*name, state->linenr); 990 another =find_name(state, line, NULL, state->p_value, TERM_TAB); 991if(!another ||memcmp(another, *name, len +1)) 992die((side == DIFF_NEW_NAME) ? 993_("git apply: bad git-diff - inconsistent new filename on line%d") : 994_("git apply: bad git-diff - inconsistent old filename on line%d"), state->linenr); 995free(another); 996}else{ 997/* expect "/dev/null" */ 998if(memcmp("/dev/null", line,9) || line[9] !='\n') 999die(_("git apply: bad git-diff - expected /dev/null on line%d"), state->linenr);1000}1001}10021003static intgitdiff_oldname(struct apply_state *state,1004const char*line,1005struct patch *patch)1006{1007gitdiff_verify_name(state, line,1008 patch->is_new, &patch->old_name,1009 DIFF_OLD_NAME);1010return0;1011}10121013static intgitdiff_newname(struct apply_state *state,1014const char*line,1015struct patch *patch)1016{1017gitdiff_verify_name(state, line,1018 patch->is_delete, &patch->new_name,1019 DIFF_NEW_NAME);1020return0;1021}10221023static intgitdiff_oldmode(struct apply_state *state,1024const char*line,1025struct patch *patch)1026{1027 patch->old_mode =strtoul(line, NULL,8);1028return0;1029}10301031static intgitdiff_newmode(struct apply_state *state,1032const char*line,1033struct patch *patch)1034{1035 patch->new_mode =strtoul(line, NULL,8);1036return0;1037}10381039static intgitdiff_delete(struct apply_state *state,1040const char*line,1041struct patch *patch)1042{1043 patch->is_delete =1;1044free(patch->old_name);1045 patch->old_name =xstrdup_or_null(patch->def_name);1046returngitdiff_oldmode(state, line, patch);1047}10481049static intgitdiff_newfile(struct apply_state *state,1050const char*line,1051struct patch *patch)1052{1053 patch->is_new =1;1054free(patch->new_name);1055 patch->new_name =xstrdup_or_null(patch->def_name);1056returngitdiff_newmode(state, line, patch);1057}10581059static intgitdiff_copysrc(struct apply_state *state,1060const char*line,1061struct patch *patch)1062{1063 patch->is_copy =1;1064free(patch->old_name);1065 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1066return0;1067}10681069static intgitdiff_copydst(struct apply_state *state,1070const char*line,1071struct patch *patch)1072{1073 patch->is_copy =1;1074free(patch->new_name);1075 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1076return0;1077}10781079static intgitdiff_renamesrc(struct apply_state *state,1080const char*line,1081struct patch *patch)1082{1083 patch->is_rename =1;1084free(patch->old_name);1085 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1086return0;1087}10881089static intgitdiff_renamedst(struct apply_state *state,1090const char*line,1091struct patch *patch)1092{1093 patch->is_rename =1;1094free(patch->new_name);1095 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1096return0;1097}10981099static intgitdiff_similarity(struct apply_state *state,1100const char*line,1101struct patch *patch)1102{1103unsigned long val =strtoul(line, NULL,10);1104if(val <=100)1105 patch->score = val;1106return0;1107}11081109static intgitdiff_dissimilarity(struct apply_state *state,1110const char*line,1111struct patch *patch)1112{1113unsigned long val =strtoul(line, NULL,10);1114if(val <=100)1115 patch->score = val;1116return0;1117}11181119static intgitdiff_index(struct apply_state *state,1120const char*line,1121struct patch *patch)1122{1123/*1124 * index line is N hexadecimal, "..", N hexadecimal,1125 * and optional space with octal mode.1126 */1127const char*ptr, *eol;1128int len;11291130 ptr =strchr(line,'.');1131if(!ptr || ptr[1] !='.'||40< ptr - line)1132return0;1133 len = ptr - line;1134memcpy(patch->old_sha1_prefix, line, len);1135 patch->old_sha1_prefix[len] =0;11361137 line = ptr +2;1138 ptr =strchr(line,' ');1139 eol =strchrnul(line,'\n');11401141if(!ptr || eol < ptr)1142 ptr = eol;1143 len = ptr - line;11441145if(40< len)1146return0;1147memcpy(patch->new_sha1_prefix, line, len);1148 patch->new_sha1_prefix[len] =0;1149if(*ptr ==' ')1150 patch->old_mode =strtoul(ptr+1, NULL,8);1151return0;1152}11531154/*1155 * This is normal for a diff that doesn't change anything: we'll fall through1156 * into the next diff. Tell the parser to break out.1157 */1158static intgitdiff_unrecognized(struct apply_state *state,1159const char*line,1160struct patch *patch)1161{1162return-1;1163}11641165/*1166 * Skip p_value leading components from "line"; as we do not accept1167 * absolute paths, return NULL in that case.1168 */1169static const char*skip_tree_prefix(struct apply_state *state,1170const char*line,1171int llen)1172{1173int nslash;1174int i;11751176if(!state->p_value)1177return(llen && line[0] =='/') ? NULL : line;11781179 nslash = state->p_value;1180for(i =0; i < llen; i++) {1181int ch = line[i];1182if(ch =='/'&& --nslash <=0)1183return(i ==0) ? NULL : &line[i +1];1184}1185return NULL;1186}11871188/*1189 * This is to extract the same name that appears on "diff --git"1190 * line. We do not find and return anything if it is a rename1191 * patch, and it is OK because we will find the name elsewhere.1192 * We need to reliably find name only when it is mode-change only,1193 * creation or deletion of an empty file. In any of these cases,1194 * both sides are the same name under a/ and b/ respectively.1195 */1196static char*git_header_name(struct apply_state *state,1197const char*line,1198int llen)1199{1200const char*name;1201const char*second = NULL;1202size_t len, line_len;12031204 line +=strlen("diff --git ");1205 llen -=strlen("diff --git ");12061207if(*line =='"') {1208const char*cp;1209struct strbuf first = STRBUF_INIT;1210struct strbuf sp = STRBUF_INIT;12111212if(unquote_c_style(&first, line, &second))1213goto free_and_fail1;12141215/* strip the a/b prefix including trailing slash */1216 cp =skip_tree_prefix(state, first.buf, first.len);1217if(!cp)1218goto free_and_fail1;1219strbuf_remove(&first,0, cp - first.buf);12201221/*1222 * second points at one past closing dq of name.1223 * find the second name.1224 */1225while((second < line + llen) &&isspace(*second))1226 second++;12271228if(line + llen <= second)1229goto free_and_fail1;1230if(*second =='"') {1231if(unquote_c_style(&sp, second, NULL))1232goto free_and_fail1;1233 cp =skip_tree_prefix(state, sp.buf, sp.len);1234if(!cp)1235goto free_and_fail1;1236/* They must match, otherwise ignore */1237if(strcmp(cp, first.buf))1238goto free_and_fail1;1239strbuf_release(&sp);1240returnstrbuf_detach(&first, NULL);1241}12421243/* unquoted second */1244 cp =skip_tree_prefix(state, second, line + llen - second);1245if(!cp)1246goto free_and_fail1;1247if(line + llen - cp != first.len ||1248memcmp(first.buf, cp, first.len))1249goto free_and_fail1;1250returnstrbuf_detach(&first, NULL);12511252 free_and_fail1:1253strbuf_release(&first);1254strbuf_release(&sp);1255return NULL;1256}12571258/* unquoted first name */1259 name =skip_tree_prefix(state, line, llen);1260if(!name)1261return NULL;12621263/*1264 * since the first name is unquoted, a dq if exists must be1265 * the beginning of the second name.1266 */1267for(second = name; second < line + llen; second++) {1268if(*second =='"') {1269struct strbuf sp = STRBUF_INIT;1270const char*np;12711272if(unquote_c_style(&sp, second, NULL))1273goto free_and_fail2;12741275 np =skip_tree_prefix(state, sp.buf, sp.len);1276if(!np)1277goto free_and_fail2;12781279 len = sp.buf + sp.len - np;1280if(len < second - name &&1281!strncmp(np, name, len) &&1282isspace(name[len])) {1283/* Good */1284strbuf_remove(&sp,0, np - sp.buf);1285returnstrbuf_detach(&sp, NULL);1286}12871288 free_and_fail2:1289strbuf_release(&sp);1290return NULL;1291}1292}12931294/*1295 * Accept a name only if it shows up twice, exactly the same1296 * form.1297 */1298 second =strchr(name,'\n');1299if(!second)1300return NULL;1301 line_len = second - name;1302for(len =0; ; len++) {1303switch(name[len]) {1304default:1305continue;1306case'\n':1307return NULL;1308case'\t':case' ':1309/*1310 * Is this the separator between the preimage1311 * and the postimage pathname? Again, we are1312 * only interested in the case where there is1313 * no rename, as this is only to set def_name1314 * and a rename patch has the names elsewhere1315 * in an unambiguous form.1316 */1317if(!name[len +1])1318return NULL;/* no postimage name */1319 second =skip_tree_prefix(state, name + len +1,1320 line_len - (len +1));1321if(!second)1322return NULL;1323/*1324 * Does len bytes starting at "name" and "second"1325 * (that are separated by one HT or SP we just1326 * found) exactly match?1327 */1328if(second[len] =='\n'&& !strncmp(name, second, len))1329returnxmemdupz(name, len);1330}1331}1332}13331334/* Verify that we recognize the lines following a git header */1335static intparse_git_header(struct apply_state *state,1336const char*line,1337int len,1338unsigned int size,1339struct patch *patch)1340{1341unsigned long offset;13421343/* A git diff has explicit new/delete information, so we don't guess */1344 patch->is_new =0;1345 patch->is_delete =0;13461347/*1348 * Some things may not have the old name in the1349 * rest of the headers anywhere (pure mode changes,1350 * or removing or adding empty files), so we get1351 * the default name from the header.1352 */1353 patch->def_name =git_header_name(state, line, len);1354if(patch->def_name && state->root.len) {1355char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1356free(patch->def_name);1357 patch->def_name = s;1358}13591360 line += len;1361 size -= len;1362 state->linenr++;1363for(offset = len ; size >0; offset += len, size -= len, line += len, state->linenr++) {1364static const struct opentry {1365const char*str;1366int(*fn)(struct apply_state *,const char*,struct patch *);1367} optable[] = {1368{"@@ -", gitdiff_hdrend },1369{"--- ", gitdiff_oldname },1370{"+++ ", gitdiff_newname },1371{"old mode ", gitdiff_oldmode },1372{"new mode ", gitdiff_newmode },1373{"deleted file mode ", gitdiff_delete },1374{"new file mode ", gitdiff_newfile },1375{"copy from ", gitdiff_copysrc },1376{"copy to ", gitdiff_copydst },1377{"rename old ", gitdiff_renamesrc },1378{"rename new ", gitdiff_renamedst },1379{"rename from ", gitdiff_renamesrc },1380{"rename to ", gitdiff_renamedst },1381{"similarity index ", gitdiff_similarity },1382{"dissimilarity index ", gitdiff_dissimilarity },1383{"index ", gitdiff_index },1384{"", gitdiff_unrecognized },1385};1386int i;13871388 len =linelen(line, size);1389if(!len || line[len-1] !='\n')1390break;1391for(i =0; i <ARRAY_SIZE(optable); i++) {1392const struct opentry *p = optable + i;1393int oplen =strlen(p->str);1394if(len < oplen ||memcmp(p->str, line, oplen))1395continue;1396if(p->fn(state, line + oplen, patch) <0)1397return offset;1398break;1399}1400}14011402return offset;1403}14041405static intparse_num(const char*line,unsigned long*p)1406{1407char*ptr;14081409if(!isdigit(*line))1410return0;1411*p =strtoul(line, &ptr,10);1412return ptr - line;1413}14141415static intparse_range(const char*line,int len,int offset,const char*expect,1416unsigned long*p1,unsigned long*p2)1417{1418int digits, ex;14191420if(offset <0|| offset >= len)1421return-1;1422 line += offset;1423 len -= offset;14241425 digits =parse_num(line, p1);1426if(!digits)1427return-1;14281429 offset += digits;1430 line += digits;1431 len -= digits;14321433*p2 =1;1434if(*line ==',') {1435 digits =parse_num(line+1, p2);1436if(!digits)1437return-1;14381439 offset += digits+1;1440 line += digits+1;1441 len -= digits+1;1442}14431444 ex =strlen(expect);1445if(ex > len)1446return-1;1447if(memcmp(line, expect, ex))1448return-1;14491450return offset + ex;1451}14521453static voidrecount_diff(const char*line,int size,struct fragment *fragment)1454{1455int oldlines =0, newlines =0, ret =0;14561457if(size <1) {1458warning("recount: ignore empty hunk");1459return;1460}14611462for(;;) {1463int len =linelen(line, size);1464 size -= len;1465 line += len;14661467if(size <1)1468break;14691470switch(*line) {1471case' ':case'\n':1472 newlines++;1473/* fall through */1474case'-':1475 oldlines++;1476continue;1477case'+':1478 newlines++;1479continue;1480case'\\':1481continue;1482case'@':1483 ret = size <3|| !starts_with(line,"@@ ");1484break;1485case'd':1486 ret = size <5|| !starts_with(line,"diff ");1487break;1488default:1489 ret = -1;1490break;1491}1492if(ret) {1493warning(_("recount: unexpected line: %.*s"),1494(int)linelen(line, size), line);1495return;1496}1497break;1498}1499 fragment->oldlines = oldlines;1500 fragment->newlines = newlines;1501}15021503/*1504 * Parse a unified diff fragment header of the1505 * form "@@ -a,b +c,d @@"1506 */1507static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1508{1509int offset;15101511if(!len || line[len-1] !='\n')1512return-1;15131514/* Figure out the number of lines in a fragment */1515 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1516 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);15171518return offset;1519}15201521static intfind_header(struct apply_state *state,1522const char*line,1523unsigned long size,1524int*hdrsize,1525struct patch *patch)1526{1527unsigned long offset, len;15281529 patch->is_toplevel_relative =0;1530 patch->is_rename = patch->is_copy =0;1531 patch->is_new = patch->is_delete = -1;1532 patch->old_mode = patch->new_mode =0;1533 patch->old_name = patch->new_name = NULL;1534for(offset =0; size >0; offset += len, size -= len, line += len, state->linenr++) {1535unsigned long nextlen;15361537 len =linelen(line, size);1538if(!len)1539break;15401541/* Testing this early allows us to take a few shortcuts.. */1542if(len <6)1543continue;15441545/*1546 * Make sure we don't find any unconnected patch fragments.1547 * That's a sign that we didn't find a header, and that a1548 * patch has become corrupted/broken up.1549 */1550if(!memcmp("@@ -", line,4)) {1551struct fragment dummy;1552if(parse_fragment_header(line, len, &dummy) <0)1553continue;1554die(_("patch fragment without header at line%d: %.*s"),1555 state->linenr, (int)len-1, line);1556}15571558if(size < len +6)1559break;15601561/*1562 * Git patch? It might not have a real patch, just a rename1563 * or mode change, so we handle that specially1564 */1565if(!memcmp("diff --git ", line,11)) {1566int git_hdr_len =parse_git_header(state, line, len, size, patch);1567if(git_hdr_len <= len)1568continue;1569if(!patch->old_name && !patch->new_name) {1570if(!patch->def_name)1571die(Q_("git diff header lacks filename information when removing "1572"%dleading pathname component (line%d)",1573"git diff header lacks filename information when removing "1574"%dleading pathname components (line%d)",1575 state->p_value),1576 state->p_value, state->linenr);1577 patch->old_name =xstrdup(patch->def_name);1578 patch->new_name =xstrdup(patch->def_name);1579}1580if(!patch->is_delete && !patch->new_name)1581die("git diff header lacks filename information "1582"(line%d)", state->linenr);1583 patch->is_toplevel_relative =1;1584*hdrsize = git_hdr_len;1585return offset;1586}15871588/* --- followed by +++ ? */1589if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1590continue;15911592/*1593 * We only accept unified patches, so we want it to1594 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1595 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1596 */1597 nextlen =linelen(line + len, size - len);1598if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1599continue;16001601/* Ok, we'll consider it a patch */1602parse_traditional_patch(state, line, line+len, patch);1603*hdrsize = len + nextlen;1604 state->linenr +=2;1605return offset;1606}1607return-1;1608}16091610static voidrecord_ws_error(struct apply_state *state,1611unsigned result,1612const char*line,1613int len,1614int linenr)1615{1616char*err;16171618if(!result)1619return;16201621 state->whitespace_error++;1622if(state->squelch_whitespace_errors &&1623 state->squelch_whitespace_errors < state->whitespace_error)1624return;16251626 err =whitespace_error_string(result);1627fprintf(stderr,"%s:%d:%s.\n%.*s\n",1628 state->patch_input_file, linenr, err, len, line);1629free(err);1630}16311632static voidcheck_whitespace(struct apply_state *state,1633const char*line,1634int len,1635unsigned ws_rule)1636{1637unsigned result =ws_check(line +1, len -1, ws_rule);16381639record_ws_error(state, result, line +1, len -2, state->linenr);1640}16411642/*1643 * Parse a unified diff. Note that this really needs to parse each1644 * fragment separately, since the only way to know the difference1645 * between a "---" that is part of a patch, and a "---" that starts1646 * the next patch is to look at the line counts..1647 */1648static intparse_fragment(struct apply_state *state,1649const char*line,1650unsigned long size,1651struct patch *patch,1652struct fragment *fragment)1653{1654int added, deleted;1655int len =linelen(line, size), offset;1656unsigned long oldlines, newlines;1657unsigned long leading, trailing;16581659 offset =parse_fragment_header(line, len, fragment);1660if(offset <0)1661return-1;1662if(offset >0&& patch->recount)1663recount_diff(line + offset, size - offset, fragment);1664 oldlines = fragment->oldlines;1665 newlines = fragment->newlines;1666 leading =0;1667 trailing =0;16681669/* Parse the thing.. */1670 line += len;1671 size -= len;1672 state->linenr++;1673 added = deleted =0;1674for(offset = len;16750< size;1676 offset += len, size -= len, line += len, state->linenr++) {1677if(!oldlines && !newlines)1678break;1679 len =linelen(line, size);1680if(!len || line[len-1] !='\n')1681return-1;1682switch(*line) {1683default:1684return-1;1685case'\n':/* newer GNU diff, an empty context line */1686case' ':1687 oldlines--;1688 newlines--;1689if(!deleted && !added)1690 leading++;1691 trailing++;1692if(!state->apply_in_reverse &&1693 state->ws_error_action == correct_ws_error)1694check_whitespace(state, line, len, patch->ws_rule);1695break;1696case'-':1697if(state->apply_in_reverse &&1698 state->ws_error_action != nowarn_ws_error)1699check_whitespace(state, line, len, patch->ws_rule);1700 deleted++;1701 oldlines--;1702 trailing =0;1703break;1704case'+':1705if(!state->apply_in_reverse &&1706 state->ws_error_action != nowarn_ws_error)1707check_whitespace(state, line, len, patch->ws_rule);1708 added++;1709 newlines--;1710 trailing =0;1711break;17121713/*1714 * We allow "\ No newline at end of file". Depending1715 * on locale settings when the patch was produced we1716 * don't know what this line looks like. The only1717 * thing we do know is that it begins with "\ ".1718 * Checking for 12 is just for sanity check -- any1719 * l10n of "\ No newline..." is at least that long.1720 */1721case'\\':1722if(len <12||memcmp(line,"\\",2))1723return-1;1724break;1725}1726}1727if(oldlines || newlines)1728return-1;1729if(!deleted && !added)1730return-1;17311732 fragment->leading = leading;1733 fragment->trailing = trailing;17341735/*1736 * If a fragment ends with an incomplete line, we failed to include1737 * it in the above loop because we hit oldlines == newlines == 01738 * before seeing it.1739 */1740if(12< size && !memcmp(line,"\\",2))1741 offset +=linelen(line, size);17421743 patch->lines_added += added;1744 patch->lines_deleted += deleted;17451746if(0< patch->is_new && oldlines)1747returnerror(_("new file depends on old contents"));1748if(0< patch->is_delete && newlines)1749returnerror(_("deleted file still has contents"));1750return offset;1751}17521753/*1754 * We have seen "diff --git a/... b/..." header (or a traditional patch1755 * header). Read hunks that belong to this patch into fragments and hang1756 * them to the given patch structure.1757 *1758 * The (fragment->patch, fragment->size) pair points into the memory given1759 * by the caller, not a copy, when we return.1760 */1761static intparse_single_patch(struct apply_state *state,1762const char*line,1763unsigned long size,1764struct patch *patch)1765{1766unsigned long offset =0;1767unsigned long oldlines =0, newlines =0, context =0;1768struct fragment **fragp = &patch->fragments;17691770while(size >4&& !memcmp(line,"@@ -",4)) {1771struct fragment *fragment;1772int len;17731774 fragment =xcalloc(1,sizeof(*fragment));1775 fragment->linenr = state->linenr;1776 len =parse_fragment(state, line, size, patch, fragment);1777if(len <=0)1778die(_("corrupt patch at line%d"), state->linenr);1779 fragment->patch = line;1780 fragment->size = len;1781 oldlines += fragment->oldlines;1782 newlines += fragment->newlines;1783 context += fragment->leading + fragment->trailing;17841785*fragp = fragment;1786 fragp = &fragment->next;17871788 offset += len;1789 line += len;1790 size -= len;1791}17921793/*1794 * If something was removed (i.e. we have old-lines) it cannot1795 * be creation, and if something was added it cannot be1796 * deletion. However, the reverse is not true; --unified=01797 * patches that only add are not necessarily creation even1798 * though they do not have any old lines, and ones that only1799 * delete are not necessarily deletion.1800 *1801 * Unfortunately, a real creation/deletion patch do _not_ have1802 * any context line by definition, so we cannot safely tell it1803 * apart with --unified=0 insanity. At least if the patch has1804 * more than one hunk it is not creation or deletion.1805 */1806if(patch->is_new <0&&1807(oldlines || (patch->fragments && patch->fragments->next)))1808 patch->is_new =0;1809if(patch->is_delete <0&&1810(newlines || (patch->fragments && patch->fragments->next)))1811 patch->is_delete =0;18121813if(0< patch->is_new && oldlines)1814die(_("new file%sdepends on old contents"), patch->new_name);1815if(0< patch->is_delete && newlines)1816die(_("deleted file%sstill has contents"), patch->old_name);1817if(!patch->is_delete && !newlines && context)1818fprintf_ln(stderr,1819_("** warning: "1820"file%sbecomes empty but is not deleted"),1821 patch->new_name);18221823return offset;1824}18251826staticinlineintmetadata_changes(struct patch *patch)1827{1828return patch->is_rename >0||1829 patch->is_copy >0||1830 patch->is_new >0||1831 patch->is_delete ||1832(patch->old_mode && patch->new_mode &&1833 patch->old_mode != patch->new_mode);1834}18351836static char*inflate_it(const void*data,unsigned long size,1837unsigned long inflated_size)1838{1839 git_zstream stream;1840void*out;1841int st;18421843memset(&stream,0,sizeof(stream));18441845 stream.next_in = (unsigned char*)data;1846 stream.avail_in = size;1847 stream.next_out = out =xmalloc(inflated_size);1848 stream.avail_out = inflated_size;1849git_inflate_init(&stream);1850 st =git_inflate(&stream, Z_FINISH);1851git_inflate_end(&stream);1852if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1853free(out);1854return NULL;1855}1856return out;1857}18581859/*1860 * Read a binary hunk and return a new fragment; fragment->patch1861 * points at an allocated memory that the caller must free, so1862 * it is marked as "->free_patch = 1".1863 */1864static struct fragment *parse_binary_hunk(struct apply_state *state,1865char**buf_p,1866unsigned long*sz_p,1867int*status_p,1868int*used_p)1869{1870/*1871 * Expect a line that begins with binary patch method ("literal"1872 * or "delta"), followed by the length of data before deflating.1873 * a sequence of 'length-byte' followed by base-85 encoded data1874 * should follow, terminated by a newline.1875 *1876 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1877 * and we would limit the patch line to 66 characters,1878 * so one line can fit up to 13 groups that would decode1879 * to 52 bytes max. The length byte 'A'-'Z' corresponds1880 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1881 */1882int llen, used;1883unsigned long size = *sz_p;1884char*buffer = *buf_p;1885int patch_method;1886unsigned long origlen;1887char*data = NULL;1888int hunk_size =0;1889struct fragment *frag;18901891 llen =linelen(buffer, size);1892 used = llen;18931894*status_p =0;18951896if(starts_with(buffer,"delta ")) {1897 patch_method = BINARY_DELTA_DEFLATED;1898 origlen =strtoul(buffer +6, NULL,10);1899}1900else if(starts_with(buffer,"literal ")) {1901 patch_method = BINARY_LITERAL_DEFLATED;1902 origlen =strtoul(buffer +8, NULL,10);1903}1904else1905return NULL;19061907 state->linenr++;1908 buffer += llen;1909while(1) {1910int byte_length, max_byte_length, newsize;1911 llen =linelen(buffer, size);1912 used += llen;1913 state->linenr++;1914if(llen ==1) {1915/* consume the blank line */1916 buffer++;1917 size--;1918break;1919}1920/*1921 * Minimum line is "A00000\n" which is 7-byte long,1922 * and the line length must be multiple of 5 plus 2.1923 */1924if((llen <7) || (llen-2) %5)1925goto corrupt;1926 max_byte_length = (llen -2) /5*4;1927 byte_length = *buffer;1928if('A'<= byte_length && byte_length <='Z')1929 byte_length = byte_length -'A'+1;1930else if('a'<= byte_length && byte_length <='z')1931 byte_length = byte_length -'a'+27;1932else1933goto corrupt;1934/* if the input length was not multiple of 4, we would1935 * have filler at the end but the filler should never1936 * exceed 3 bytes1937 */1938if(max_byte_length < byte_length ||1939 byte_length <= max_byte_length -4)1940goto corrupt;1941 newsize = hunk_size + byte_length;1942 data =xrealloc(data, newsize);1943if(decode_85(data + hunk_size, buffer +1, byte_length))1944goto corrupt;1945 hunk_size = newsize;1946 buffer += llen;1947 size -= llen;1948}19491950 frag =xcalloc(1,sizeof(*frag));1951 frag->patch =inflate_it(data, hunk_size, origlen);1952 frag->free_patch =1;1953if(!frag->patch)1954goto corrupt;1955free(data);1956 frag->size = origlen;1957*buf_p = buffer;1958*sz_p = size;1959*used_p = used;1960 frag->binary_patch_method = patch_method;1961return frag;19621963 corrupt:1964free(data);1965*status_p = -1;1966error(_("corrupt binary patch at line%d: %.*s"),1967 state->linenr-1, llen-1, buffer);1968return NULL;1969}19701971/*1972 * Returns:1973 * -1 in case of error,1974 * the length of the parsed binary patch otherwise1975 */1976static intparse_binary(struct apply_state *state,1977char*buffer,1978unsigned long size,1979struct patch *patch)1980{1981/*1982 * We have read "GIT binary patch\n"; what follows is a line1983 * that says the patch method (currently, either "literal" or1984 * "delta") and the length of data before deflating; a1985 * sequence of 'length-byte' followed by base-85 encoded data1986 * follows.1987 *1988 * When a binary patch is reversible, there is another binary1989 * hunk in the same format, starting with patch method (either1990 * "literal" or "delta") with the length of data, and a sequence1991 * of length-byte + base-85 encoded data, terminated with another1992 * empty line. This data, when applied to the postimage, produces1993 * the preimage.1994 */1995struct fragment *forward;1996struct fragment *reverse;1997int status;1998int used, used_1;19992000 forward =parse_binary_hunk(state, &buffer, &size, &status, &used);2001if(!forward && !status)2002/* there has to be one hunk (forward hunk) */2003returnerror(_("unrecognized binary patch at line%d"), state->linenr-1);2004if(status)2005/* otherwise we already gave an error message */2006return status;20072008 reverse =parse_binary_hunk(state, &buffer, &size, &status, &used_1);2009if(reverse)2010 used += used_1;2011else if(status) {2012/*2013 * Not having reverse hunk is not an error, but having2014 * a corrupt reverse hunk is.2015 */2016free((void*) forward->patch);2017free(forward);2018return status;2019}2020 forward->next = reverse;2021 patch->fragments = forward;2022 patch->is_binary =1;2023return used;2024}20252026static voidprefix_one(struct apply_state *state,char**name)2027{2028char*old_name = *name;2029if(!old_name)2030return;2031*name =xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));2032free(old_name);2033}20342035static voidprefix_patch(struct apply_state *state,struct patch *p)2036{2037if(!state->prefix || p->is_toplevel_relative)2038return;2039prefix_one(state, &p->new_name);2040prefix_one(state, &p->old_name);2041}20422043/*2044 * include/exclude2045 */20462047static voidadd_name_limit(struct apply_state *state,2048const char*name,2049int exclude)2050{2051struct string_list_item *it;20522053 it =string_list_append(&state->limit_by_name, name);2054 it->util = exclude ? NULL : (void*)1;2055}20562057static intuse_patch(struct apply_state *state,struct patch *p)2058{2059const char*pathname = p->new_name ? p->new_name : p->old_name;2060int i;20612062/* Paths outside are not touched regardless of "--include" */2063if(0< state->prefix_length) {2064int pathlen =strlen(pathname);2065if(pathlen <= state->prefix_length ||2066memcmp(state->prefix, pathname, state->prefix_length))2067return0;2068}20692070/* See if it matches any of exclude/include rule */2071for(i =0; i < state->limit_by_name.nr; i++) {2072struct string_list_item *it = &state->limit_by_name.items[i];2073if(!wildmatch(it->string, pathname,0, NULL))2074return(it->util != NULL);2075}20762077/*2078 * If we had any include, a path that does not match any rule is2079 * not used. Otherwise, we saw bunch of exclude rules (or none)2080 * and such a path is used.2081 */2082return!state->has_include;2083}208420852086/*2087 * Read the patch text in "buffer" that extends for "size" bytes; stop2088 * reading after seeing a single patch (i.e. changes to a single file).2089 * Create fragments (i.e. patch hunks) and hang them to the given patch.2090 * Return the number of bytes consumed, so that the caller can call us2091 * again for the next patch.2092 */2093static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2094{2095int hdrsize, patchsize;2096int offset =find_header(state, buffer, size, &hdrsize, patch);20972098if(offset <0)2099return offset;21002101prefix_patch(state, patch);21022103if(!use_patch(state, patch))2104 patch->ws_rule =0;2105else2106 patch->ws_rule =whitespace_rule(patch->new_name2107? patch->new_name2108: patch->old_name);21092110 patchsize =parse_single_patch(state,2111 buffer + offset + hdrsize,2112 size - offset - hdrsize,2113 patch);21142115if(!patchsize) {2116static const char git_binary[] ="GIT binary patch\n";2117int hd = hdrsize + offset;2118unsigned long llen =linelen(buffer + hd, size - hd);21192120if(llen ==sizeof(git_binary) -1&&2121!memcmp(git_binary, buffer + hd, llen)) {2122int used;2123 state->linenr++;2124 used =parse_binary(state, buffer + hd + llen,2125 size - hd - llen, patch);2126if(used <0)2127return-1;2128if(used)2129 patchsize = used + llen;2130else2131 patchsize =0;2132}2133else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2134static const char*binhdr[] = {2135"Binary files ",2136"Files ",2137 NULL,2138};2139int i;2140for(i =0; binhdr[i]; i++) {2141int len =strlen(binhdr[i]);2142if(len < size - hd &&2143!memcmp(binhdr[i], buffer + hd, len)) {2144 state->linenr++;2145 patch->is_binary =1;2146 patchsize = llen;2147break;2148}2149}2150}21512152/* Empty patch cannot be applied if it is a text patch2153 * without metadata change. A binary patch appears2154 * empty to us here.2155 */2156if((state->apply || state->check) &&2157(!patch->is_binary && !metadata_changes(patch)))2158die(_("patch with only garbage at line%d"), state->linenr);2159}21602161return offset + hdrsize + patchsize;2162}21632164#define swap(a,b) myswap((a),(b),sizeof(a))21652166#define myswap(a, b, size) do { \2167 unsigned char mytmp[size]; \2168 memcpy(mytmp, &a, size); \2169 memcpy(&a, &b, size); \2170 memcpy(&b, mytmp, size); \2171} while (0)21722173static voidreverse_patches(struct patch *p)2174{2175for(; p; p = p->next) {2176struct fragment *frag = p->fragments;21772178swap(p->new_name, p->old_name);2179swap(p->new_mode, p->old_mode);2180swap(p->is_new, p->is_delete);2181swap(p->lines_added, p->lines_deleted);2182swap(p->old_sha1_prefix, p->new_sha1_prefix);21832184for(; frag; frag = frag->next) {2185swap(frag->newpos, frag->oldpos);2186swap(frag->newlines, frag->oldlines);2187}2188}2189}21902191static const char pluses[] =2192"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2193static const char minuses[]=2194"----------------------------------------------------------------------";21952196static voidshow_stats(struct apply_state *state,struct patch *patch)2197{2198struct strbuf qname = STRBUF_INIT;2199char*cp = patch->new_name ? patch->new_name : patch->old_name;2200int max, add, del;22012202quote_c_style(cp, &qname, NULL,0);22032204/*2205 * "scale" the filename2206 */2207 max = state->max_len;2208if(max >50)2209 max =50;22102211if(qname.len > max) {2212 cp =strchr(qname.buf + qname.len +3- max,'/');2213if(!cp)2214 cp = qname.buf + qname.len +3- max;2215strbuf_splice(&qname,0, cp - qname.buf,"...",3);2216}22172218if(patch->is_binary) {2219printf(" %-*s | Bin\n", max, qname.buf);2220strbuf_release(&qname);2221return;2222}22232224printf(" %-*s |", max, qname.buf);2225strbuf_release(&qname);22262227/*2228 * scale the add/delete2229 */2230 max = max + state->max_change >70?70- max : state->max_change;2231 add = patch->lines_added;2232 del = patch->lines_deleted;22332234if(state->max_change >0) {2235int total = ((add + del) * max + state->max_change /2) / state->max_change;2236 add = (add * max + state->max_change /2) / state->max_change;2237 del = total - add;2238}2239printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2240 add, pluses, del, minuses);2241}22422243static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2244{2245switch(st->st_mode & S_IFMT) {2246case S_IFLNK:2247if(strbuf_readlink(buf, path, st->st_size) <0)2248returnerror(_("unable to read symlink%s"), path);2249return0;2250case S_IFREG:2251if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2252returnerror(_("unable to open or read%s"), path);2253convert_to_git(path, buf->buf, buf->len, buf,0);2254return0;2255default:2256return-1;2257}2258}22592260/*2261 * Update the preimage, and the common lines in postimage,2262 * from buffer buf of length len. If postlen is 0 the postimage2263 * is updated in place, otherwise it's updated on a new buffer2264 * of length postlen2265 */22662267static voidupdate_pre_post_images(struct image *preimage,2268struct image *postimage,2269char*buf,2270size_t len,size_t postlen)2271{2272int i, ctx, reduced;2273char*new, *old, *fixed;2274struct image fixed_preimage;22752276/*2277 * Update the preimage with whitespace fixes. Note that we2278 * are not losing preimage->buf -- apply_one_fragment() will2279 * free "oldlines".2280 */2281prepare_image(&fixed_preimage, buf, len,1);2282assert(postlen2283? fixed_preimage.nr == preimage->nr2284: fixed_preimage.nr <= preimage->nr);2285for(i =0; i < fixed_preimage.nr; i++)2286 fixed_preimage.line[i].flag = preimage->line[i].flag;2287free(preimage->line_allocated);2288*preimage = fixed_preimage;22892290/*2291 * Adjust the common context lines in postimage. This can be2292 * done in-place when we are shrinking it with whitespace2293 * fixing, but needs a new buffer when ignoring whitespace or2294 * expanding leading tabs to spaces.2295 *2296 * We trust the caller to tell us if the update can be done2297 * in place (postlen==0) or not.2298 */2299 old = postimage->buf;2300if(postlen)2301new= postimage->buf =xmalloc(postlen);2302else2303new= old;2304 fixed = preimage->buf;23052306for(i = reduced = ctx =0; i < postimage->nr; i++) {2307size_t l_len = postimage->line[i].len;2308if(!(postimage->line[i].flag & LINE_COMMON)) {2309/* an added line -- no counterparts in preimage */2310memmove(new, old, l_len);2311 old += l_len;2312new+= l_len;2313continue;2314}23152316/* a common context -- skip it in the original postimage */2317 old += l_len;23182319/* and find the corresponding one in the fixed preimage */2320while(ctx < preimage->nr &&2321!(preimage->line[ctx].flag & LINE_COMMON)) {2322 fixed += preimage->line[ctx].len;2323 ctx++;2324}23252326/*2327 * preimage is expected to run out, if the caller2328 * fixed addition of trailing blank lines.2329 */2330if(preimage->nr <= ctx) {2331 reduced++;2332continue;2333}23342335/* and copy it in, while fixing the line length */2336 l_len = preimage->line[ctx].len;2337memcpy(new, fixed, l_len);2338new+= l_len;2339 fixed += l_len;2340 postimage->line[i].len = l_len;2341 ctx++;2342}23432344if(postlen2345? postlen <new- postimage->buf2346: postimage->len <new- postimage->buf)2347die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2348(int)postlen, (int) postimage->len, (int)(new- postimage->buf));23492350/* Fix the length of the whole thing */2351 postimage->len =new- postimage->buf;2352 postimage->nr -= reduced;2353}23542355static intline_by_line_fuzzy_match(struct image *img,2356struct image *preimage,2357struct image *postimage,2358unsigned longtry,2359int try_lno,2360int preimage_limit)2361{2362int i;2363size_t imgoff =0;2364size_t preoff =0;2365size_t postlen = postimage->len;2366size_t extra_chars;2367char*buf;2368char*preimage_eof;2369char*preimage_end;2370struct strbuf fixed;2371char*fixed_buf;2372size_t fixed_len;23732374for(i =0; i < preimage_limit; i++) {2375size_t prelen = preimage->line[i].len;2376size_t imglen = img->line[try_lno+i].len;23772378if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2379 preimage->buf + preoff, prelen))2380return0;2381if(preimage->line[i].flag & LINE_COMMON)2382 postlen += imglen - prelen;2383 imgoff += imglen;2384 preoff += prelen;2385}23862387/*2388 * Ok, the preimage matches with whitespace fuzz.2389 *2390 * imgoff now holds the true length of the target that2391 * matches the preimage before the end of the file.2392 *2393 * Count the number of characters in the preimage that fall2394 * beyond the end of the file and make sure that all of them2395 * are whitespace characters. (This can only happen if2396 * we are removing blank lines at the end of the file.)2397 */2398 buf = preimage_eof = preimage->buf + preoff;2399for( ; i < preimage->nr; i++)2400 preoff += preimage->line[i].len;2401 preimage_end = preimage->buf + preoff;2402for( ; buf < preimage_end; buf++)2403if(!isspace(*buf))2404return0;24052406/*2407 * Update the preimage and the common postimage context2408 * lines to use the same whitespace as the target.2409 * If whitespace is missing in the target (i.e.2410 * if the preimage extends beyond the end of the file),2411 * use the whitespace from the preimage.2412 */2413 extra_chars = preimage_end - preimage_eof;2414strbuf_init(&fixed, imgoff + extra_chars);2415strbuf_add(&fixed, img->buf +try, imgoff);2416strbuf_add(&fixed, preimage_eof, extra_chars);2417 fixed_buf =strbuf_detach(&fixed, &fixed_len);2418update_pre_post_images(preimage, postimage,2419 fixed_buf, fixed_len, postlen);2420return1;2421}24222423static intmatch_fragment(struct apply_state *state,2424struct image *img,2425struct image *preimage,2426struct image *postimage,2427unsigned longtry,2428int try_lno,2429unsigned ws_rule,2430int match_beginning,int match_end)2431{2432int i;2433char*fixed_buf, *buf, *orig, *target;2434struct strbuf fixed;2435size_t fixed_len, postlen;2436int preimage_limit;24372438if(preimage->nr + try_lno <= img->nr) {2439/*2440 * The hunk falls within the boundaries of img.2441 */2442 preimage_limit = preimage->nr;2443if(match_end && (preimage->nr + try_lno != img->nr))2444return0;2445}else if(state->ws_error_action == correct_ws_error &&2446(ws_rule & WS_BLANK_AT_EOF)) {2447/*2448 * This hunk extends beyond the end of img, and we are2449 * removing blank lines at the end of the file. This2450 * many lines from the beginning of the preimage must2451 * match with img, and the remainder of the preimage2452 * must be blank.2453 */2454 preimage_limit = img->nr - try_lno;2455}else{2456/*2457 * The hunk extends beyond the end of the img and2458 * we are not removing blanks at the end, so we2459 * should reject the hunk at this position.2460 */2461return0;2462}24632464if(match_beginning && try_lno)2465return0;24662467/* Quick hash check */2468for(i =0; i < preimage_limit; i++)2469if((img->line[try_lno + i].flag & LINE_PATCHED) ||2470(preimage->line[i].hash != img->line[try_lno + i].hash))2471return0;24722473if(preimage_limit == preimage->nr) {2474/*2475 * Do we have an exact match? If we were told to match2476 * at the end, size must be exactly at try+fragsize,2477 * otherwise try+fragsize must be still within the preimage,2478 * and either case, the old piece should match the preimage2479 * exactly.2480 */2481if((match_end2482? (try+ preimage->len == img->len)2483: (try+ preimage->len <= img->len)) &&2484!memcmp(img->buf +try, preimage->buf, preimage->len))2485return1;2486}else{2487/*2488 * The preimage extends beyond the end of img, so2489 * there cannot be an exact match.2490 *2491 * There must be one non-blank context line that match2492 * a line before the end of img.2493 */2494char*buf_end;24952496 buf = preimage->buf;2497 buf_end = buf;2498for(i =0; i < preimage_limit; i++)2499 buf_end += preimage->line[i].len;25002501for( ; buf < buf_end; buf++)2502if(!isspace(*buf))2503break;2504if(buf == buf_end)2505return0;2506}25072508/*2509 * No exact match. If we are ignoring whitespace, run a line-by-line2510 * fuzzy matching. We collect all the line length information because2511 * we need it to adjust whitespace if we match.2512 */2513if(state->ws_ignore_action == ignore_ws_change)2514returnline_by_line_fuzzy_match(img, preimage, postimage,2515try, try_lno, preimage_limit);25162517if(state->ws_error_action != correct_ws_error)2518return0;25192520/*2521 * The hunk does not apply byte-by-byte, but the hash says2522 * it might with whitespace fuzz. We weren't asked to2523 * ignore whitespace, we were asked to correct whitespace2524 * errors, so let's try matching after whitespace correction.2525 *2526 * While checking the preimage against the target, whitespace2527 * errors in both fixed, we count how large the corresponding2528 * postimage needs to be. The postimage prepared by2529 * apply_one_fragment() has whitespace errors fixed on added2530 * lines already, but the common lines were propagated as-is,2531 * which may become longer when their whitespace errors are2532 * fixed.2533 */25342535/* First count added lines in postimage */2536 postlen =0;2537for(i =0; i < postimage->nr; i++) {2538if(!(postimage->line[i].flag & LINE_COMMON))2539 postlen += postimage->line[i].len;2540}25412542/*2543 * The preimage may extend beyond the end of the file,2544 * but in this loop we will only handle the part of the2545 * preimage that falls within the file.2546 */2547strbuf_init(&fixed, preimage->len +1);2548 orig = preimage->buf;2549 target = img->buf +try;2550for(i =0; i < preimage_limit; i++) {2551size_t oldlen = preimage->line[i].len;2552size_t tgtlen = img->line[try_lno + i].len;2553size_t fixstart = fixed.len;2554struct strbuf tgtfix;2555int match;25562557/* Try fixing the line in the preimage */2558ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25592560/* Try fixing the line in the target */2561strbuf_init(&tgtfix, tgtlen);2562ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);25632564/*2565 * If they match, either the preimage was based on2566 * a version before our tree fixed whitespace breakage,2567 * or we are lacking a whitespace-fix patch the tree2568 * the preimage was based on already had (i.e. target2569 * has whitespace breakage, the preimage doesn't).2570 * In either case, we are fixing the whitespace breakages2571 * so we might as well take the fix together with their2572 * real change.2573 */2574 match = (tgtfix.len == fixed.len - fixstart &&2575!memcmp(tgtfix.buf, fixed.buf + fixstart,2576 fixed.len - fixstart));25772578/* Add the length if this is common with the postimage */2579if(preimage->line[i].flag & LINE_COMMON)2580 postlen += tgtfix.len;25812582strbuf_release(&tgtfix);2583if(!match)2584goto unmatch_exit;25852586 orig += oldlen;2587 target += tgtlen;2588}258925902591/*2592 * Now handle the lines in the preimage that falls beyond the2593 * end of the file (if any). They will only match if they are2594 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2595 * false).2596 */2597for( ; i < preimage->nr; i++) {2598size_t fixstart = fixed.len;/* start of the fixed preimage */2599size_t oldlen = preimage->line[i].len;2600int j;26012602/* Try fixing the line in the preimage */2603ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);26042605for(j = fixstart; j < fixed.len; j++)2606if(!isspace(fixed.buf[j]))2607goto unmatch_exit;26082609 orig += oldlen;2610}26112612/*2613 * Yes, the preimage is based on an older version that still2614 * has whitespace breakages unfixed, and fixing them makes the2615 * hunk match. Update the context lines in the postimage.2616 */2617 fixed_buf =strbuf_detach(&fixed, &fixed_len);2618if(postlen < postimage->len)2619 postlen =0;2620update_pre_post_images(preimage, postimage,2621 fixed_buf, fixed_len, postlen);2622return1;26232624 unmatch_exit:2625strbuf_release(&fixed);2626return0;2627}26282629static intfind_pos(struct apply_state *state,2630struct image *img,2631struct image *preimage,2632struct image *postimage,2633int line,2634unsigned ws_rule,2635int match_beginning,int match_end)2636{2637int i;2638unsigned long backwards, forwards,try;2639int backwards_lno, forwards_lno, try_lno;26402641/*2642 * If match_beginning or match_end is specified, there is no2643 * point starting from a wrong line that will never match and2644 * wander around and wait for a match at the specified end.2645 */2646if(match_beginning)2647 line =0;2648else if(match_end)2649 line = img->nr - preimage->nr;26502651/*2652 * Because the comparison is unsigned, the following test2653 * will also take care of a negative line number that can2654 * result when match_end and preimage is larger than the target.2655 */2656if((size_t) line > img->nr)2657 line = img->nr;26582659try=0;2660for(i =0; i < line; i++)2661try+= img->line[i].len;26622663/*2664 * There's probably some smart way to do this, but I'll leave2665 * that to the smart and beautiful people. I'm simple and stupid.2666 */2667 backwards =try;2668 backwards_lno = line;2669 forwards =try;2670 forwards_lno = line;2671 try_lno = line;26722673for(i =0; ; i++) {2674if(match_fragment(state, img, preimage, postimage,2675try, try_lno, ws_rule,2676 match_beginning, match_end))2677return try_lno;26782679 again:2680if(backwards_lno ==0&& forwards_lno == img->nr)2681break;26822683if(i &1) {2684if(backwards_lno ==0) {2685 i++;2686goto again;2687}2688 backwards_lno--;2689 backwards -= img->line[backwards_lno].len;2690try= backwards;2691 try_lno = backwards_lno;2692}else{2693if(forwards_lno == img->nr) {2694 i++;2695goto again;2696}2697 forwards += img->line[forwards_lno].len;2698 forwards_lno++;2699try= forwards;2700 try_lno = forwards_lno;2701}27022703}2704return-1;2705}27062707static voidremove_first_line(struct image *img)2708{2709 img->buf += img->line[0].len;2710 img->len -= img->line[0].len;2711 img->line++;2712 img->nr--;2713}27142715static voidremove_last_line(struct image *img)2716{2717 img->len -= img->line[--img->nr].len;2718}27192720/*2721 * The change from "preimage" and "postimage" has been found to2722 * apply at applied_pos (counts in line numbers) in "img".2723 * Update "img" to remove "preimage" and replace it with "postimage".2724 */2725static voidupdate_image(struct apply_state *state,2726struct image *img,2727int applied_pos,2728struct image *preimage,2729struct image *postimage)2730{2731/*2732 * remove the copy of preimage at offset in img2733 * and replace it with postimage2734 */2735int i, nr;2736size_t remove_count, insert_count, applied_at =0;2737char*result;2738int preimage_limit;27392740/*2741 * If we are removing blank lines at the end of img,2742 * the preimage may extend beyond the end.2743 * If that is the case, we must be careful only to2744 * remove the part of the preimage that falls within2745 * the boundaries of img. Initialize preimage_limit2746 * to the number of lines in the preimage that falls2747 * within the boundaries.2748 */2749 preimage_limit = preimage->nr;2750if(preimage_limit > img->nr - applied_pos)2751 preimage_limit = img->nr - applied_pos;27522753for(i =0; i < applied_pos; i++)2754 applied_at += img->line[i].len;27552756 remove_count =0;2757for(i =0; i < preimage_limit; i++)2758 remove_count += img->line[applied_pos + i].len;2759 insert_count = postimage->len;27602761/* Adjust the contents */2762 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2763memcpy(result, img->buf, applied_at);2764memcpy(result + applied_at, postimage->buf, postimage->len);2765memcpy(result + applied_at + postimage->len,2766 img->buf + (applied_at + remove_count),2767 img->len - (applied_at + remove_count));2768free(img->buf);2769 img->buf = result;2770 img->len += insert_count - remove_count;2771 result[img->len] ='\0';27722773/* Adjust the line table */2774 nr = img->nr + postimage->nr - preimage_limit;2775if(preimage_limit < postimage->nr) {2776/*2777 * NOTE: this knows that we never call remove_first_line()2778 * on anything other than pre/post image.2779 */2780REALLOC_ARRAY(img->line, nr);2781 img->line_allocated = img->line;2782}2783if(preimage_limit != postimage->nr)2784memmove(img->line + applied_pos + postimage->nr,2785 img->line + applied_pos + preimage_limit,2786(img->nr - (applied_pos + preimage_limit)) *2787sizeof(*img->line));2788memcpy(img->line + applied_pos,2789 postimage->line,2790 postimage->nr *sizeof(*img->line));2791if(!state->allow_overlap)2792for(i =0; i < postimage->nr; i++)2793 img->line[applied_pos + i].flag |= LINE_PATCHED;2794 img->nr = nr;2795}27962797/*2798 * Use the patch-hunk text in "frag" to prepare two images (preimage and2799 * postimage) for the hunk. Find lines that match "preimage" in "img" and2800 * replace the part of "img" with "postimage" text.2801 */2802static intapply_one_fragment(struct apply_state *state,2803struct image *img,struct fragment *frag,2804int inaccurate_eof,unsigned ws_rule,2805int nth_fragment)2806{2807int match_beginning, match_end;2808const char*patch = frag->patch;2809int size = frag->size;2810char*old, *oldlines;2811struct strbuf newlines;2812int new_blank_lines_at_end =0;2813int found_new_blank_lines_at_end =0;2814int hunk_linenr = frag->linenr;2815unsigned long leading, trailing;2816int pos, applied_pos;2817struct image preimage;2818struct image postimage;28192820memset(&preimage,0,sizeof(preimage));2821memset(&postimage,0,sizeof(postimage));2822 oldlines =xmalloc(size);2823strbuf_init(&newlines, size);28242825 old = oldlines;2826while(size >0) {2827char first;2828int len =linelen(patch, size);2829int plen;2830int added_blank_line =0;2831int is_blank_context =0;2832size_t start;28332834if(!len)2835break;28362837/*2838 * "plen" is how much of the line we should use for2839 * the actual patch data. Normally we just remove the2840 * first character on the line, but if the line is2841 * followed by "\ No newline", then we also remove the2842 * last one (which is the newline, of course).2843 */2844 plen = len -1;2845if(len < size && patch[len] =='\\')2846 plen--;2847 first = *patch;2848if(state->apply_in_reverse) {2849if(first =='-')2850 first ='+';2851else if(first =='+')2852 first ='-';2853}28542855switch(first) {2856case'\n':2857/* Newer GNU diff, empty context line */2858if(plen <0)2859/* ... followed by '\No newline'; nothing */2860break;2861*old++ ='\n';2862strbuf_addch(&newlines,'\n');2863add_line_info(&preimage,"\n",1, LINE_COMMON);2864add_line_info(&postimage,"\n",1, LINE_COMMON);2865 is_blank_context =1;2866break;2867case' ':2868if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2869ws_blank_line(patch +1, plen, ws_rule))2870 is_blank_context =1;2871case'-':2872memcpy(old, patch +1, plen);2873add_line_info(&preimage, old, plen,2874(first ==' '? LINE_COMMON :0));2875 old += plen;2876if(first =='-')2877break;2878/* Fall-through for ' ' */2879case'+':2880/* --no-add does not add new lines */2881if(first =='+'&& state->no_add)2882break;28832884 start = newlines.len;2885if(first !='+'||2886!state->whitespace_error ||2887 state->ws_error_action != correct_ws_error) {2888strbuf_add(&newlines, patch +1, plen);2889}2890else{2891ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2892}2893add_line_info(&postimage, newlines.buf + start, newlines.len - start,2894(first =='+'?0: LINE_COMMON));2895if(first =='+'&&2896(ws_rule & WS_BLANK_AT_EOF) &&2897ws_blank_line(patch +1, plen, ws_rule))2898 added_blank_line =1;2899break;2900case'@':case'\\':2901/* Ignore it, we already handled it */2902break;2903default:2904if(state->apply_verbosely)2905error(_("invalid start of line: '%c'"), first);2906 applied_pos = -1;2907goto out;2908}2909if(added_blank_line) {2910if(!new_blank_lines_at_end)2911 found_new_blank_lines_at_end = hunk_linenr;2912 new_blank_lines_at_end++;2913}2914else if(is_blank_context)2915;2916else2917 new_blank_lines_at_end =0;2918 patch += len;2919 size -= len;2920 hunk_linenr++;2921}2922if(inaccurate_eof &&2923 old > oldlines && old[-1] =='\n'&&2924 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2925 old--;2926strbuf_setlen(&newlines, newlines.len -1);2927}29282929 leading = frag->leading;2930 trailing = frag->trailing;29312932/*2933 * A hunk to change lines at the beginning would begin with2934 * @@ -1,L +N,M @@2935 * but we need to be careful. -U0 that inserts before the second2936 * line also has this pattern.2937 *2938 * And a hunk to add to an empty file would begin with2939 * @@ -0,0 +N,M @@2940 *2941 * In other words, a hunk that is (frag->oldpos <= 1) with or2942 * without leading context must match at the beginning.2943 */2944 match_beginning = (!frag->oldpos ||2945(frag->oldpos ==1&& !state->unidiff_zero));29462947/*2948 * A hunk without trailing lines must match at the end.2949 * However, we simply cannot tell if a hunk must match end2950 * from the lack of trailing lines if the patch was generated2951 * with unidiff without any context.2952 */2953 match_end = !state->unidiff_zero && !trailing;29542955 pos = frag->newpos ? (frag->newpos -1) :0;2956 preimage.buf = oldlines;2957 preimage.len = old - oldlines;2958 postimage.buf = newlines.buf;2959 postimage.len = newlines.len;2960 preimage.line = preimage.line_allocated;2961 postimage.line = postimage.line_allocated;29622963for(;;) {29642965 applied_pos =find_pos(state, img, &preimage, &postimage, pos,2966 ws_rule, match_beginning, match_end);29672968if(applied_pos >=0)2969break;29702971/* Am I at my context limits? */2972if((leading <= state->p_context) && (trailing <= state->p_context))2973break;2974if(match_beginning || match_end) {2975 match_beginning = match_end =0;2976continue;2977}29782979/*2980 * Reduce the number of context lines; reduce both2981 * leading and trailing if they are equal otherwise2982 * just reduce the larger context.2983 */2984if(leading >= trailing) {2985remove_first_line(&preimage);2986remove_first_line(&postimage);2987 pos--;2988 leading--;2989}2990if(trailing > leading) {2991remove_last_line(&preimage);2992remove_last_line(&postimage);2993 trailing--;2994}2995}29962997if(applied_pos >=0) {2998if(new_blank_lines_at_end &&2999 preimage.nr + applied_pos >= img->nr &&3000(ws_rule & WS_BLANK_AT_EOF) &&3001 state->ws_error_action != nowarn_ws_error) {3002record_ws_error(state, WS_BLANK_AT_EOF,"+",1,3003 found_new_blank_lines_at_end);3004if(state->ws_error_action == correct_ws_error) {3005while(new_blank_lines_at_end--)3006remove_last_line(&postimage);3007}3008/*3009 * We would want to prevent write_out_results()3010 * from taking place in apply_patch() that follows3011 * the callchain led us here, which is:3012 * apply_patch->check_patch_list->check_patch->3013 * apply_data->apply_fragments->apply_one_fragment3014 */3015if(state->ws_error_action == die_on_ws_error)3016 state->apply =0;3017}30183019if(state->apply_verbosely && applied_pos != pos) {3020int offset = applied_pos - pos;3021if(state->apply_in_reverse)3022 offset =0- offset;3023fprintf_ln(stderr,3024Q_("Hunk #%dsucceeded at%d(offset%dline).",3025"Hunk #%dsucceeded at%d(offset%dlines).",3026 offset),3027 nth_fragment, applied_pos +1, offset);3028}30293030/*3031 * Warn if it was necessary to reduce the number3032 * of context lines.3033 */3034if((leading != frag->leading) ||3035(trailing != frag->trailing))3036fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"3037" to apply fragment at%d"),3038 leading, trailing, applied_pos+1);3039update_image(state, img, applied_pos, &preimage, &postimage);3040}else{3041if(state->apply_verbosely)3042error(_("while searching for:\n%.*s"),3043(int)(old - oldlines), oldlines);3044}30453046out:3047free(oldlines);3048strbuf_release(&newlines);3049free(preimage.line_allocated);3050free(postimage.line_allocated);30513052return(applied_pos <0);3053}30543055static intapply_binary_fragment(struct apply_state *state,3056struct image *img,3057struct patch *patch)3058{3059struct fragment *fragment = patch->fragments;3060unsigned long len;3061void*dst;30623063if(!fragment)3064returnerror(_("missing binary patch data for '%s'"),3065 patch->new_name ?3066 patch->new_name :3067 patch->old_name);30683069/* Binary patch is irreversible without the optional second hunk */3070if(state->apply_in_reverse) {3071if(!fragment->next)3072returnerror("cannot reverse-apply a binary patch "3073"without the reverse hunk to '%s'",3074 patch->new_name3075? patch->new_name : patch->old_name);3076 fragment = fragment->next;3077}3078switch(fragment->binary_patch_method) {3079case BINARY_DELTA_DEFLATED:3080 dst =patch_delta(img->buf, img->len, fragment->patch,3081 fragment->size, &len);3082if(!dst)3083return-1;3084clear_image(img);3085 img->buf = dst;3086 img->len = len;3087return0;3088case BINARY_LITERAL_DEFLATED:3089clear_image(img);3090 img->len = fragment->size;3091 img->buf =xmemdupz(fragment->patch, img->len);3092return0;3093}3094return-1;3095}30963097/*3098 * Replace "img" with the result of applying the binary patch.3099 * The binary patch data itself in patch->fragment is still kept3100 * but the preimage prepared by the caller in "img" is freed here3101 * or in the helper function apply_binary_fragment() this calls.3102 */3103static intapply_binary(struct apply_state *state,3104struct image *img,3105struct patch *patch)3106{3107const char*name = patch->old_name ? patch->old_name : patch->new_name;3108unsigned char sha1[20];31093110/*3111 * For safety, we require patch index line to contain3112 * full 40-byte textual SHA1 for old and new, at least for now.3113 */3114if(strlen(patch->old_sha1_prefix) !=40||3115strlen(patch->new_sha1_prefix) !=40||3116get_sha1_hex(patch->old_sha1_prefix, sha1) ||3117get_sha1_hex(patch->new_sha1_prefix, sha1))3118returnerror("cannot apply binary patch to '%s' "3119"without full index line", name);31203121if(patch->old_name) {3122/*3123 * See if the old one matches what the patch3124 * applies to.3125 */3126hash_sha1_file(img->buf, img->len, blob_type, sha1);3127if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3128returnerror("the patch applies to '%s' (%s), "3129"which does not match the "3130"current contents.",3131 name,sha1_to_hex(sha1));3132}3133else{3134/* Otherwise, the old one must be empty. */3135if(img->len)3136returnerror("the patch applies to an empty "3137"'%s' but it is not empty", name);3138}31393140get_sha1_hex(patch->new_sha1_prefix, sha1);3141if(is_null_sha1(sha1)) {3142clear_image(img);3143return0;/* deletion patch */3144}31453146if(has_sha1_file(sha1)) {3147/* We already have the postimage */3148enum object_type type;3149unsigned long size;3150char*result;31513152 result =read_sha1_file(sha1, &type, &size);3153if(!result)3154returnerror("the necessary postimage%sfor "3155"'%s' cannot be read",3156 patch->new_sha1_prefix, name);3157clear_image(img);3158 img->buf = result;3159 img->len = size;3160}else{3161/*3162 * We have verified buf matches the preimage;3163 * apply the patch data to it, which is stored3164 * in the patch->fragments->{patch,size}.3165 */3166if(apply_binary_fragment(state, img, patch))3167returnerror(_("binary patch does not apply to '%s'"),3168 name);31693170/* verify that the result matches */3171hash_sha1_file(img->buf, img->len, blob_type, sha1);3172if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3173returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3174 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3175}31763177return0;3178}31793180static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3181{3182struct fragment *frag = patch->fragments;3183const char*name = patch->old_name ? patch->old_name : patch->new_name;3184unsigned ws_rule = patch->ws_rule;3185unsigned inaccurate_eof = patch->inaccurate_eof;3186int nth =0;31873188if(patch->is_binary)3189returnapply_binary(state, img, patch);31903191while(frag) {3192 nth++;3193if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3194error(_("patch failed:%s:%ld"), name, frag->oldpos);3195if(!state->apply_with_reject)3196return-1;3197 frag->rejected =1;3198}3199 frag = frag->next;3200}3201return0;3202}32033204static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3205{3206if(S_ISGITLINK(mode)) {3207strbuf_grow(buf,100);3208strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3209}else{3210enum object_type type;3211unsigned long sz;3212char*result;32133214 result =read_sha1_file(sha1, &type, &sz);3215if(!result)3216return-1;3217/* XXX read_sha1_file NUL-terminates */3218strbuf_attach(buf, result, sz, sz +1);3219}3220return0;3221}32223223static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3224{3225if(!ce)3226return0;3227returnread_blob_object(buf, ce->sha1, ce->ce_mode);3228}32293230static struct patch *in_fn_table(struct apply_state *state,const char*name)3231{3232struct string_list_item *item;32333234if(name == NULL)3235return NULL;32363237 item =string_list_lookup(&state->fn_table, name);3238if(item != NULL)3239return(struct patch *)item->util;32403241return NULL;3242}32433244/*3245 * item->util in the filename table records the status of the path.3246 * Usually it points at a patch (whose result records the contents3247 * of it after applying it), but it could be PATH_WAS_DELETED for a3248 * path that a previously applied patch has already removed, or3249 * PATH_TO_BE_DELETED for a path that a later patch would remove.3250 *3251 * The latter is needed to deal with a case where two paths A and B3252 * are swapped by first renaming A to B and then renaming B to A;3253 * moving A to B should not be prevented due to presence of B as we3254 * will remove it in a later patch.3255 */3256#define PATH_TO_BE_DELETED ((struct patch *) -2)3257#define PATH_WAS_DELETED ((struct patch *) -1)32583259static intto_be_deleted(struct patch *patch)3260{3261return patch == PATH_TO_BE_DELETED;3262}32633264static intwas_deleted(struct patch *patch)3265{3266return patch == PATH_WAS_DELETED;3267}32683269static voidadd_to_fn_table(struct apply_state *state,struct patch *patch)3270{3271struct string_list_item *item;32723273/*3274 * Always add new_name unless patch is a deletion3275 * This should cover the cases for normal diffs,3276 * file creations and copies3277 */3278if(patch->new_name != NULL) {3279 item =string_list_insert(&state->fn_table, patch->new_name);3280 item->util = patch;3281}32823283/*3284 * store a failure on rename/deletion cases because3285 * later chunks shouldn't patch old names3286 */3287if((patch->new_name == NULL) || (patch->is_rename)) {3288 item =string_list_insert(&state->fn_table, patch->old_name);3289 item->util = PATH_WAS_DELETED;3290}3291}32923293static voidprepare_fn_table(struct apply_state *state,struct patch *patch)3294{3295/*3296 * store information about incoming file deletion3297 */3298while(patch) {3299if((patch->new_name == NULL) || (patch->is_rename)) {3300struct string_list_item *item;3301 item =string_list_insert(&state->fn_table, patch->old_name);3302 item->util = PATH_TO_BE_DELETED;3303}3304 patch = patch->next;3305}3306}33073308static intcheckout_target(struct index_state *istate,3309struct cache_entry *ce,struct stat *st)3310{3311struct checkout costate;33123313memset(&costate,0,sizeof(costate));3314 costate.base_dir ="";3315 costate.refresh_cache =1;3316 costate.istate = istate;3317if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3318returnerror(_("cannot checkout%s"), ce->name);3319return0;3320}33213322static struct patch *previous_patch(struct apply_state *state,3323struct patch *patch,3324int*gone)3325{3326struct patch *previous;33273328*gone =0;3329if(patch->is_copy || patch->is_rename)3330return NULL;/* "git" patches do not depend on the order */33313332 previous =in_fn_table(state, patch->old_name);3333if(!previous)3334return NULL;33353336if(to_be_deleted(previous))3337return NULL;/* the deletion hasn't happened yet */33383339if(was_deleted(previous))3340*gone =1;33413342return previous;3343}33443345static intverify_index_match(const struct cache_entry *ce,struct stat *st)3346{3347if(S_ISGITLINK(ce->ce_mode)) {3348if(!S_ISDIR(st->st_mode))3349return-1;3350return0;3351}3352returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3353}33543355#define SUBMODULE_PATCH_WITHOUT_INDEX 133563357static intload_patch_target(struct apply_state *state,3358struct strbuf *buf,3359const struct cache_entry *ce,3360struct stat *st,3361const char*name,3362unsigned expected_mode)3363{3364if(state->cached || state->check_index) {3365if(read_file_or_gitlink(ce, buf))3366returnerror(_("read of%sfailed"), name);3367}else if(name) {3368if(S_ISGITLINK(expected_mode)) {3369if(ce)3370returnread_file_or_gitlink(ce, buf);3371else3372return SUBMODULE_PATCH_WITHOUT_INDEX;3373}else if(has_symlink_leading_path(name,strlen(name))) {3374returnerror(_("reading from '%s' beyond a symbolic link"), name);3375}else{3376if(read_old_data(st, name, buf))3377returnerror(_("read of%sfailed"), name);3378}3379}3380return0;3381}33823383/*3384 * We are about to apply "patch"; populate the "image" with the3385 * current version we have, from the working tree or from the index,3386 * depending on the situation e.g. --cached/--index. If we are3387 * applying a non-git patch that incrementally updates the tree,3388 * we read from the result of a previous diff.3389 */3390static intload_preimage(struct apply_state *state,3391struct image *image,3392struct patch *patch,struct stat *st,3393const struct cache_entry *ce)3394{3395struct strbuf buf = STRBUF_INIT;3396size_t len;3397char*img;3398struct patch *previous;3399int status;34003401 previous =previous_patch(state, patch, &status);3402if(status)3403returnerror(_("path%shas been renamed/deleted"),3404 patch->old_name);3405if(previous) {3406/* We have a patched copy in memory; use that. */3407strbuf_add(&buf, previous->result, previous->resultsize);3408}else{3409 status =load_patch_target(state, &buf, ce, st,3410 patch->old_name, patch->old_mode);3411if(status <0)3412return status;3413else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3414/*3415 * There is no way to apply subproject3416 * patch without looking at the index.3417 * NEEDSWORK: shouldn't this be flagged3418 * as an error???3419 */3420free_fragment_list(patch->fragments);3421 patch->fragments = NULL;3422}else if(status) {3423returnerror(_("read of%sfailed"), patch->old_name);3424}3425}34263427 img =strbuf_detach(&buf, &len);3428prepare_image(image, img, len, !patch->is_binary);3429return0;3430}34313432static intthree_way_merge(struct image *image,3433char*path,3434const unsigned char*base,3435const unsigned char*ours,3436const unsigned char*theirs)3437{3438 mmfile_t base_file, our_file, their_file;3439 mmbuffer_t result = { NULL };3440int status;34413442read_mmblob(&base_file, base);3443read_mmblob(&our_file, ours);3444read_mmblob(&their_file, theirs);3445 status =ll_merge(&result, path,3446&base_file,"base",3447&our_file,"ours",3448&their_file,"theirs", NULL);3449free(base_file.ptr);3450free(our_file.ptr);3451free(their_file.ptr);3452if(status <0|| !result.ptr) {3453free(result.ptr);3454return-1;3455}3456clear_image(image);3457 image->buf = result.ptr;3458 image->len = result.size;34593460return status;3461}34623463/*3464 * When directly falling back to add/add three-way merge, we read from3465 * the current contents of the new_name. In no cases other than that3466 * this function will be called.3467 */3468static intload_current(struct apply_state *state,3469struct image *image,3470struct patch *patch)3471{3472struct strbuf buf = STRBUF_INIT;3473int status, pos;3474size_t len;3475char*img;3476struct stat st;3477struct cache_entry *ce;3478char*name = patch->new_name;3479unsigned mode = patch->new_mode;34803481if(!patch->is_new)3482die("BUG: patch to%sis not a creation", patch->old_name);34833484 pos =cache_name_pos(name,strlen(name));3485if(pos <0)3486returnerror(_("%s: does not exist in index"), name);3487 ce = active_cache[pos];3488if(lstat(name, &st)) {3489if(errno != ENOENT)3490returnerror(_("%s:%s"), name,strerror(errno));3491if(checkout_target(&the_index, ce, &st))3492return-1;3493}3494if(verify_index_match(ce, &st))3495returnerror(_("%s: does not match index"), name);34963497 status =load_patch_target(state, &buf, ce, &st, name, mode);3498if(status <0)3499return status;3500else if(status)3501return-1;3502 img =strbuf_detach(&buf, &len);3503prepare_image(image, img, len, !patch->is_binary);3504return0;3505}35063507static inttry_threeway(struct apply_state *state,3508struct image *image,3509struct patch *patch,3510struct stat *st,3511const struct cache_entry *ce)3512{3513unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3514struct strbuf buf = STRBUF_INIT;3515size_t len;3516int status;3517char*img;3518struct image tmp_image;35193520/* No point falling back to 3-way merge in these cases */3521if(patch->is_delete ||3522S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3523return-1;35243525/* Preimage the patch was prepared for */3526if(patch->is_new)3527write_sha1_file("",0, blob_type, pre_sha1);3528else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3529read_blob_object(&buf, pre_sha1, patch->old_mode))3530returnerror("repository lacks the necessary blob to fall back on 3-way merge.");35313532fprintf(stderr,"Falling back to three-way merge...\n");35333534 img =strbuf_detach(&buf, &len);3535prepare_image(&tmp_image, img, len,1);3536/* Apply the patch to get the post image */3537if(apply_fragments(state, &tmp_image, patch) <0) {3538clear_image(&tmp_image);3539return-1;3540}3541/* post_sha1[] is theirs */3542write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3543clear_image(&tmp_image);35443545/* our_sha1[] is ours */3546if(patch->is_new) {3547if(load_current(state, &tmp_image, patch))3548returnerror("cannot read the current contents of '%s'",3549 patch->new_name);3550}else{3551if(load_preimage(state, &tmp_image, patch, st, ce))3552returnerror("cannot read the current contents of '%s'",3553 patch->old_name);3554}3555write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3556clear_image(&tmp_image);35573558/* in-core three-way merge between post and our using pre as base */3559 status =three_way_merge(image, patch->new_name,3560 pre_sha1, our_sha1, post_sha1);3561if(status <0) {3562fprintf(stderr,"Failed to fall back on three-way merge...\n");3563return status;3564}35653566if(status) {3567 patch->conflicted_threeway =1;3568if(patch->is_new)3569oidclr(&patch->threeway_stage[0]);3570else3571hashcpy(patch->threeway_stage[0].hash, pre_sha1);3572hashcpy(patch->threeway_stage[1].hash, our_sha1);3573hashcpy(patch->threeway_stage[2].hash, post_sha1);3574fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3575}else{3576fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3577}3578return0;3579}35803581static intapply_data(struct apply_state *state,struct patch *patch,3582struct stat *st,const struct cache_entry *ce)3583{3584struct image image;35853586if(load_preimage(state, &image, patch, st, ce) <0)3587return-1;35883589if(patch->direct_to_threeway ||3590apply_fragments(state, &image, patch) <0) {3591/* Note: with --reject, apply_fragments() returns 0 */3592if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3593return-1;3594}3595 patch->result = image.buf;3596 patch->resultsize = image.len;3597add_to_fn_table(state, patch);3598free(image.line_allocated);35993600if(0< patch->is_delete && patch->resultsize)3601returnerror(_("removal patch leaves file contents"));36023603return0;3604}36053606/*3607 * If "patch" that we are looking at modifies or deletes what we have,3608 * we would want it not to lose any local modification we have, either3609 * in the working tree or in the index.3610 *3611 * This also decides if a non-git patch is a creation patch or a3612 * modification to an existing empty file. We do not check the state3613 * of the current tree for a creation patch in this function; the caller3614 * check_patch() separately makes sure (and errors out otherwise) that3615 * the path the patch creates does not exist in the current tree.3616 */3617static intcheck_preimage(struct apply_state *state,3618struct patch *patch,3619struct cache_entry **ce,3620struct stat *st)3621{3622const char*old_name = patch->old_name;3623struct patch *previous = NULL;3624int stat_ret =0, status;3625unsigned st_mode =0;36263627if(!old_name)3628return0;36293630assert(patch->is_new <=0);3631 previous =previous_patch(state, patch, &status);36323633if(status)3634returnerror(_("path%shas been renamed/deleted"), old_name);3635if(previous) {3636 st_mode = previous->new_mode;3637}else if(!state->cached) {3638 stat_ret =lstat(old_name, st);3639if(stat_ret && errno != ENOENT)3640returnerror(_("%s:%s"), old_name,strerror(errno));3641}36423643if(state->check_index && !previous) {3644int pos =cache_name_pos(old_name,strlen(old_name));3645if(pos <0) {3646if(patch->is_new <0)3647goto is_new;3648returnerror(_("%s: does not exist in index"), old_name);3649}3650*ce = active_cache[pos];3651if(stat_ret <0) {3652if(checkout_target(&the_index, *ce, st))3653return-1;3654}3655if(!state->cached &&verify_index_match(*ce, st))3656returnerror(_("%s: does not match index"), old_name);3657if(state->cached)3658 st_mode = (*ce)->ce_mode;3659}else if(stat_ret <0) {3660if(patch->is_new <0)3661goto is_new;3662returnerror(_("%s:%s"), old_name,strerror(errno));3663}36643665if(!state->cached && !previous)3666 st_mode =ce_mode_from_stat(*ce, st->st_mode);36673668if(patch->is_new <0)3669 patch->is_new =0;3670if(!patch->old_mode)3671 patch->old_mode = st_mode;3672if((st_mode ^ patch->old_mode) & S_IFMT)3673returnerror(_("%s: wrong type"), old_name);3674if(st_mode != patch->old_mode)3675warning(_("%shas type%o, expected%o"),3676 old_name, st_mode, patch->old_mode);3677if(!patch->new_mode && !patch->is_delete)3678 patch->new_mode = st_mode;3679return0;36803681 is_new:3682 patch->is_new =1;3683 patch->is_delete =0;3684free(patch->old_name);3685 patch->old_name = NULL;3686return0;3687}368836893690#define EXISTS_IN_INDEX 13691#define EXISTS_IN_WORKTREE 236923693static intcheck_to_create(struct apply_state *state,3694const char*new_name,3695int ok_if_exists)3696{3697struct stat nst;36983699if(state->check_index &&3700cache_name_pos(new_name,strlen(new_name)) >=0&&3701!ok_if_exists)3702return EXISTS_IN_INDEX;3703if(state->cached)3704return0;37053706if(!lstat(new_name, &nst)) {3707if(S_ISDIR(nst.st_mode) || ok_if_exists)3708return0;3709/*3710 * A leading component of new_name might be a symlink3711 * that is going to be removed with this patch, but3712 * still pointing at somewhere that has the path.3713 * In such a case, path "new_name" does not exist as3714 * far as git is concerned.3715 */3716if(has_symlink_leading_path(new_name,strlen(new_name)))3717return0;37183719return EXISTS_IN_WORKTREE;3720}else if((errno != ENOENT) && (errno != ENOTDIR)) {3721returnerror("%s:%s", new_name,strerror(errno));3722}3723return0;3724}37253726static uintptr_tregister_symlink_changes(struct apply_state *state,3727const char*path,3728uintptr_t what)3729{3730struct string_list_item *ent;37313732 ent =string_list_lookup(&state->symlink_changes, path);3733if(!ent) {3734 ent =string_list_insert(&state->symlink_changes, path);3735 ent->util = (void*)0;3736}3737 ent->util = (void*)(what | ((uintptr_t)ent->util));3738return(uintptr_t)ent->util;3739}37403741static uintptr_tcheck_symlink_changes(struct apply_state *state,const char*path)3742{3743struct string_list_item *ent;37443745 ent =string_list_lookup(&state->symlink_changes, path);3746if(!ent)3747return0;3748return(uintptr_t)ent->util;3749}37503751static voidprepare_symlink_changes(struct apply_state *state,struct patch *patch)3752{3753for( ; patch; patch = patch->next) {3754if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3755(patch->is_rename || patch->is_delete))3756/* the symlink at patch->old_name is removed */3757register_symlink_changes(state, patch->old_name, SYMLINK_GOES_AWAY);37583759if(patch->new_name &&S_ISLNK(patch->new_mode))3760/* the symlink at patch->new_name is created or remains */3761register_symlink_changes(state, patch->new_name, SYMLINK_IN_RESULT);3762}3763}37643765static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3766{3767do{3768unsigned int change;37693770while(--name->len && name->buf[name->len] !='/')3771;/* scan backwards */3772if(!name->len)3773break;3774 name->buf[name->len] ='\0';3775 change =check_symlink_changes(state, name->buf);3776if(change & SYMLINK_IN_RESULT)3777return1;3778if(change & SYMLINK_GOES_AWAY)3779/*3780 * This cannot be "return 0", because we may3781 * see a new one created at a higher level.3782 */3783continue;37843785/* otherwise, check the preimage */3786if(state->check_index) {3787struct cache_entry *ce;37883789 ce =cache_file_exists(name->buf, name->len, ignore_case);3790if(ce &&S_ISLNK(ce->ce_mode))3791return1;3792}else{3793struct stat st;3794if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3795return1;3796}3797}while(1);3798return0;3799}38003801static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3802{3803int ret;3804struct strbuf name = STRBUF_INIT;38053806assert(*name_ !='\0');3807strbuf_addstr(&name, name_);3808 ret =path_is_beyond_symlink_1(state, &name);3809strbuf_release(&name);38103811return ret;3812}38133814static voiddie_on_unsafe_path(struct patch *patch)3815{3816const char*old_name = NULL;3817const char*new_name = NULL;3818if(patch->is_delete)3819 old_name = patch->old_name;3820else if(!patch->is_new && !patch->is_copy)3821 old_name = patch->old_name;3822if(!patch->is_delete)3823 new_name = patch->new_name;38243825if(old_name && !verify_path(old_name))3826die(_("invalid path '%s'"), old_name);3827if(new_name && !verify_path(new_name))3828die(_("invalid path '%s'"), new_name);3829}38303831/*3832 * Check and apply the patch in-core; leave the result in patch->result3833 * for the caller to write it out to the final destination.3834 */3835static intcheck_patch(struct apply_state *state,struct patch *patch)3836{3837struct stat st;3838const char*old_name = patch->old_name;3839const char*new_name = patch->new_name;3840const char*name = old_name ? old_name : new_name;3841struct cache_entry *ce = NULL;3842struct patch *tpatch;3843int ok_if_exists;3844int status;38453846 patch->rejected =1;/* we will drop this after we succeed */38473848 status =check_preimage(state, patch, &ce, &st);3849if(status)3850return status;3851 old_name = patch->old_name;38523853/*3854 * A type-change diff is always split into a patch to delete3855 * old, immediately followed by a patch to create new (see3856 * diff.c::run_diff()); in such a case it is Ok that the entry3857 * to be deleted by the previous patch is still in the working3858 * tree and in the index.3859 *3860 * A patch to swap-rename between A and B would first rename A3861 * to B and then rename B to A. While applying the first one,3862 * the presence of B should not stop A from getting renamed to3863 * B; ask to_be_deleted() about the later rename. Removal of3864 * B and rename from A to B is handled the same way by asking3865 * was_deleted().3866 */3867if((tpatch =in_fn_table(state, new_name)) &&3868(was_deleted(tpatch) ||to_be_deleted(tpatch)))3869 ok_if_exists =1;3870else3871 ok_if_exists =0;38723873if(new_name &&3874((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3875int err =check_to_create(state, new_name, ok_if_exists);38763877if(err && state->threeway) {3878 patch->direct_to_threeway =1;3879}else switch(err) {3880case0:3881break;/* happy */3882case EXISTS_IN_INDEX:3883returnerror(_("%s: already exists in index"), new_name);3884break;3885case EXISTS_IN_WORKTREE:3886returnerror(_("%s: already exists in working directory"),3887 new_name);3888default:3889return err;3890}38913892if(!patch->new_mode) {3893if(0< patch->is_new)3894 patch->new_mode = S_IFREG |0644;3895else3896 patch->new_mode = patch->old_mode;3897}3898}38993900if(new_name && old_name) {3901int same = !strcmp(old_name, new_name);3902if(!patch->new_mode)3903 patch->new_mode = patch->old_mode;3904if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3905if(same)3906returnerror(_("new mode (%o) of%sdoes not "3907"match old mode (%o)"),3908 patch->new_mode, new_name,3909 patch->old_mode);3910else3911returnerror(_("new mode (%o) of%sdoes not "3912"match old mode (%o) of%s"),3913 patch->new_mode, new_name,3914 patch->old_mode, old_name);3915}3916}39173918if(!state->unsafe_paths)3919die_on_unsafe_path(patch);39203921/*3922 * An attempt to read from or delete a path that is beyond a3923 * symbolic link will be prevented by load_patch_target() that3924 * is called at the beginning of apply_data() so we do not3925 * have to worry about a patch marked with "is_delete" bit3926 * here. We however need to make sure that the patch result3927 * is not deposited to a path that is beyond a symbolic link3928 * here.3929 */3930if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3931returnerror(_("affected file '%s' is beyond a symbolic link"),3932 patch->new_name);39333934if(apply_data(state, patch, &st, ce) <0)3935returnerror(_("%s: patch does not apply"), name);3936 patch->rejected =0;3937return0;3938}39393940static intcheck_patch_list(struct apply_state *state,struct patch *patch)3941{3942int err =0;39433944prepare_symlink_changes(state, patch);3945prepare_fn_table(state, patch);3946while(patch) {3947if(state->apply_verbosely)3948say_patch_name(stderr,3949_("Checking patch%s..."), patch);3950 err |=check_patch(state, patch);3951 patch = patch->next;3952}3953return err;3954}39553956/* This function tries to read the sha1 from the current index */3957static intget_current_sha1(const char*path,unsigned char*sha1)3958{3959int pos;39603961if(read_cache() <0)3962return-1;3963 pos =cache_name_pos(path,strlen(path));3964if(pos <0)3965return-1;3966hashcpy(sha1, active_cache[pos]->sha1);3967return0;3968}39693970static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3971{3972/*3973 * A usable gitlink patch has only one fragment (hunk) that looks like:3974 * @@ -1 +1 @@3975 * -Subproject commit <old sha1>3976 * +Subproject commit <new sha1>3977 * or3978 * @@ -1 +0,0 @@3979 * -Subproject commit <old sha1>3980 * for a removal patch.3981 */3982struct fragment *hunk = p->fragments;3983static const char heading[] ="-Subproject commit ";3984char*preimage;39853986if(/* does the patch have only one hunk? */3987 hunk && !hunk->next &&3988/* is its preimage one line? */3989 hunk->oldpos ==1&& hunk->oldlines ==1&&3990/* does preimage begin with the heading? */3991(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3992starts_with(++preimage, heading) &&3993/* does it record full SHA-1? */3994!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3995 preimage[sizeof(heading) +40-1] =='\n'&&3996/* does the abbreviated name on the index line agree with it? */3997starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3998return0;/* it all looks fine */39994000/* we may have full object name on the index line */4001returnget_sha1_hex(p->old_sha1_prefix, sha1);4002}40034004/* Build an index that contains the just the files needed for a 3way merge */4005static voidbuild_fake_ancestor(struct patch *list,const char*filename)4006{4007struct patch *patch;4008struct index_state result = { NULL };4009static struct lock_file lock;40104011/* Once we start supporting the reverse patch, it may be4012 * worth showing the new sha1 prefix, but until then...4013 */4014for(patch = list; patch; patch = patch->next) {4015unsigned char sha1[20];4016struct cache_entry *ce;4017const char*name;40184019 name = patch->old_name ? patch->old_name : patch->new_name;4020if(0< patch->is_new)4021continue;40224023if(S_ISGITLINK(patch->old_mode)) {4024if(!preimage_sha1_in_gitlink_patch(patch, sha1))4025;/* ok, the textual part looks sane */4026else4027die("sha1 information is lacking or useless for submodule%s",4028 name);4029}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {4030;/* ok */4031}else if(!patch->lines_added && !patch->lines_deleted) {4032/* mode-only change: update the current */4033if(get_current_sha1(patch->old_name, sha1))4034die("mode change for%s, which is not "4035"in current HEAD", name);4036}else4037die("sha1 information is lacking or useless "4038"(%s).", name);40394040 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);4041if(!ce)4042die(_("make_cache_entry failed for path '%s'"), name);4043if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))4044die("Could not add%sto temporary index", name);4045}40464047hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);4048if(write_locked_index(&result, &lock, COMMIT_LOCK))4049die("Could not write temporary index to%s", filename);40504051discard_index(&result);4052}40534054static voidstat_patch_list(struct apply_state *state,struct patch *patch)4055{4056int files, adds, dels;40574058for(files = adds = dels =0; patch ; patch = patch->next) {4059 files++;4060 adds += patch->lines_added;4061 dels += patch->lines_deleted;4062show_stats(state, patch);4063}40644065print_stat_summary(stdout, files, adds, dels);4066}40674068static voidnumstat_patch_list(struct apply_state *state,4069struct patch *patch)4070{4071for( ; patch; patch = patch->next) {4072const char*name;4073 name = patch->new_name ? patch->new_name : patch->old_name;4074if(patch->is_binary)4075printf("-\t-\t");4076else4077printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4078write_name_quoted(name, stdout, state->line_termination);4079}4080}40814082static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4083{4084if(mode)4085printf("%smode%06o%s\n", newdelete, mode, name);4086else4087printf("%s %s\n", newdelete, name);4088}40894090static voidshow_mode_change(struct patch *p,int show_name)4091{4092if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4093if(show_name)4094printf(" mode change%06o =>%06o%s\n",4095 p->old_mode, p->new_mode, p->new_name);4096else4097printf(" mode change%06o =>%06o\n",4098 p->old_mode, p->new_mode);4099}4100}41014102static voidshow_rename_copy(struct patch *p)4103{4104const char*renamecopy = p->is_rename ?"rename":"copy";4105const char*old, *new;41064107/* Find common prefix */4108 old = p->old_name;4109new= p->new_name;4110while(1) {4111const char*slash_old, *slash_new;4112 slash_old =strchr(old,'/');4113 slash_new =strchr(new,'/');4114if(!slash_old ||4115!slash_new ||4116 slash_old - old != slash_new -new||4117memcmp(old,new, slash_new -new))4118break;4119 old = slash_old +1;4120new= slash_new +1;4121}4122/* p->old_name thru old is the common prefix, and old and new4123 * through the end of names are renames4124 */4125if(old != p->old_name)4126printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4127(int)(old - p->old_name), p->old_name,4128 old,new, p->score);4129else4130printf("%s %s=>%s(%d%%)\n", renamecopy,4131 p->old_name, p->new_name, p->score);4132show_mode_change(p,0);4133}41344135static voidsummary_patch_list(struct patch *patch)4136{4137struct patch *p;41384139for(p = patch; p; p = p->next) {4140if(p->is_new)4141show_file_mode_name("create", p->new_mode, p->new_name);4142else if(p->is_delete)4143show_file_mode_name("delete", p->old_mode, p->old_name);4144else{4145if(p->is_rename || p->is_copy)4146show_rename_copy(p);4147else{4148if(p->score) {4149printf(" rewrite%s(%d%%)\n",4150 p->new_name, p->score);4151show_mode_change(p,0);4152}4153else4154show_mode_change(p,1);4155}4156}4157}4158}41594160static voidpatch_stats(struct apply_state *state,struct patch *patch)4161{4162int lines = patch->lines_added + patch->lines_deleted;41634164if(lines > state->max_change)4165 state->max_change = lines;4166if(patch->old_name) {4167int len =quote_c_style(patch->old_name, NULL, NULL,0);4168if(!len)4169 len =strlen(patch->old_name);4170if(len > state->max_len)4171 state->max_len = len;4172}4173if(patch->new_name) {4174int len =quote_c_style(patch->new_name, NULL, NULL,0);4175if(!len)4176 len =strlen(patch->new_name);4177if(len > state->max_len)4178 state->max_len = len;4179}4180}41814182static voidremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4183{4184if(state->update_index) {4185if(remove_file_from_cache(patch->old_name) <0)4186die(_("unable to remove%sfrom index"), patch->old_name);4187}4188if(!state->cached) {4189if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4190remove_path(patch->old_name);4191}4192}4193}41944195static voidadd_index_file(struct apply_state *state,4196const char*path,4197unsigned mode,4198void*buf,4199unsigned long size)4200{4201struct stat st;4202struct cache_entry *ce;4203int namelen =strlen(path);4204unsigned ce_size =cache_entry_size(namelen);42054206if(!state->update_index)4207return;42084209 ce =xcalloc(1, ce_size);4210memcpy(ce->name, path, namelen);4211 ce->ce_mode =create_ce_mode(mode);4212 ce->ce_flags =create_ce_flags(0);4213 ce->ce_namelen = namelen;4214if(S_ISGITLINK(mode)) {4215const char*s;42164217if(!skip_prefix(buf,"Subproject commit ", &s) ||4218get_sha1_hex(s, ce->sha1))4219die(_("corrupt patch for submodule%s"), path);4220}else{4221if(!state->cached) {4222if(lstat(path, &st) <0)4223die_errno(_("unable to stat newly created file '%s'"),4224 path);4225fill_stat_cache_info(ce, &st);4226}4227if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4228die(_("unable to create backing store for newly created file%s"), path);4229}4230if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4231die(_("unable to add cache entry for%s"), path);4232}42334234static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4235{4236int fd;4237struct strbuf nbuf = STRBUF_INIT;42384239if(S_ISGITLINK(mode)) {4240struct stat st;4241if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4242return0;4243returnmkdir(path,0777);4244}42454246if(has_symlinks &&S_ISLNK(mode))4247/* Although buf:size is counted string, it also is NUL4248 * terminated.4249 */4250returnsymlink(buf, path);42514252 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4253if(fd <0)4254return-1;42554256if(convert_to_working_tree(path, buf, size, &nbuf)) {4257 size = nbuf.len;4258 buf = nbuf.buf;4259}4260write_or_die(fd, buf, size);4261strbuf_release(&nbuf);42624263if(close(fd) <0)4264die_errno(_("closing file '%s'"), path);4265return0;4266}42674268/*4269 * We optimistically assume that the directories exist,4270 * which is true 99% of the time anyway. If they don't,4271 * we create them and try again.4272 */4273static voidcreate_one_file(struct apply_state *state,4274char*path,4275unsigned mode,4276const char*buf,4277unsigned long size)4278{4279if(state->cached)4280return;4281if(!try_create_file(path, mode, buf, size))4282return;42834284if(errno == ENOENT) {4285if(safe_create_leading_directories(path))4286return;4287if(!try_create_file(path, mode, buf, size))4288return;4289}42904291if(errno == EEXIST || errno == EACCES) {4292/* We may be trying to create a file where a directory4293 * used to be.4294 */4295struct stat st;4296if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4297 errno = EEXIST;4298}42994300if(errno == EEXIST) {4301unsigned int nr =getpid();43024303for(;;) {4304char newpath[PATH_MAX];4305mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4306if(!try_create_file(newpath, mode, buf, size)) {4307if(!rename(newpath, path))4308return;4309unlink_or_warn(newpath);4310break;4311}4312if(errno != EEXIST)4313break;4314++nr;4315}4316}4317die_errno(_("unable to write file '%s' mode%o"), path, mode);4318}43194320static voidadd_conflicted_stages_file(struct apply_state *state,4321struct patch *patch)4322{4323int stage, namelen;4324unsigned ce_size, mode;4325struct cache_entry *ce;43264327if(!state->update_index)4328return;4329 namelen =strlen(patch->new_name);4330 ce_size =cache_entry_size(namelen);4331 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);43324333remove_file_from_cache(patch->new_name);4334for(stage =1; stage <4; stage++) {4335if(is_null_oid(&patch->threeway_stage[stage -1]))4336continue;4337 ce =xcalloc(1, ce_size);4338memcpy(ce->name, patch->new_name, namelen);4339 ce->ce_mode =create_ce_mode(mode);4340 ce->ce_flags =create_ce_flags(stage);4341 ce->ce_namelen = namelen;4342hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4343if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4344die(_("unable to add cache entry for%s"), patch->new_name);4345}4346}43474348static voidcreate_file(struct apply_state *state,struct patch *patch)4349{4350char*path = patch->new_name;4351unsigned mode = patch->new_mode;4352unsigned long size = patch->resultsize;4353char*buf = patch->result;43544355if(!mode)4356 mode = S_IFREG |0644;4357create_one_file(state, path, mode, buf, size);43584359if(patch->conflicted_threeway)4360add_conflicted_stages_file(state, patch);4361else4362add_index_file(state, path, mode, buf, size);4363}43644365/* phase zero is to remove, phase one is to create */4366static voidwrite_out_one_result(struct apply_state *state,4367struct patch *patch,4368int phase)4369{4370if(patch->is_delete >0) {4371if(phase ==0)4372remove_file(state, patch,1);4373return;4374}4375if(patch->is_new >0|| patch->is_copy) {4376if(phase ==1)4377create_file(state, patch);4378return;4379}4380/*4381 * Rename or modification boils down to the same4382 * thing: remove the old, write the new4383 */4384if(phase ==0)4385remove_file(state, patch, patch->is_rename);4386if(phase ==1)4387create_file(state, patch);4388}43894390static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4391{4392FILE*rej;4393char namebuf[PATH_MAX];4394struct fragment *frag;4395int cnt =0;4396struct strbuf sb = STRBUF_INIT;43974398for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4399if(!frag->rejected)4400continue;4401 cnt++;4402}44034404if(!cnt) {4405if(state->apply_verbosely)4406say_patch_name(stderr,4407_("Applied patch%scleanly."), patch);4408return0;4409}44104411/* This should not happen, because a removal patch that leaves4412 * contents are marked "rejected" at the patch level.4413 */4414if(!patch->new_name)4415die(_("internal error"));44164417/* Say this even without --verbose */4418strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4419"Applying patch %%swith%drejects...",4420 cnt),4421 cnt);4422say_patch_name(stderr, sb.buf, patch);4423strbuf_release(&sb);44244425 cnt =strlen(patch->new_name);4426if(ARRAY_SIZE(namebuf) <= cnt +5) {4427 cnt =ARRAY_SIZE(namebuf) -5;4428warning(_("truncating .rej filename to %.*s.rej"),4429 cnt -1, patch->new_name);4430}4431memcpy(namebuf, patch->new_name, cnt);4432memcpy(namebuf + cnt,".rej",5);44334434 rej =fopen(namebuf,"w");4435if(!rej)4436returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));44374438/* Normal git tools never deal with .rej, so do not pretend4439 * this is a git patch by saying --git or giving extended4440 * headers. While at it, maybe please "kompare" that wants4441 * the trailing TAB and some garbage at the end of line ;-).4442 */4443fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4444 patch->new_name, patch->new_name);4445for(cnt =1, frag = patch->fragments;4446 frag;4447 cnt++, frag = frag->next) {4448if(!frag->rejected) {4449fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4450continue;4451}4452fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4453fprintf(rej,"%.*s", frag->size, frag->patch);4454if(frag->patch[frag->size-1] !='\n')4455fputc('\n', rej);4456}4457fclose(rej);4458return-1;4459}44604461static intwrite_out_results(struct apply_state *state,struct patch *list)4462{4463int phase;4464int errs =0;4465struct patch *l;4466struct string_list cpath = STRING_LIST_INIT_DUP;44674468for(phase =0; phase <2; phase++) {4469 l = list;4470while(l) {4471if(l->rejected)4472 errs =1;4473else{4474write_out_one_result(state, l, phase);4475if(phase ==1) {4476if(write_out_one_reject(state, l))4477 errs =1;4478if(l->conflicted_threeway) {4479string_list_append(&cpath, l->new_name);4480 errs =1;4481}4482}4483}4484 l = l->next;4485}4486}44874488if(cpath.nr) {4489struct string_list_item *item;44904491string_list_sort(&cpath);4492for_each_string_list_item(item, &cpath)4493fprintf(stderr,"U%s\n", item->string);4494string_list_clear(&cpath,0);44954496rerere(0);4497}44984499return errs;4500}45014502static struct lock_file lock_file;45034504#define INACCURATE_EOF (1<<0)4505#define RECOUNT (1<<1)45064507static intapply_patch(struct apply_state *state,4508int fd,4509const char*filename,4510int options)4511{4512size_t offset;4513struct strbuf buf = STRBUF_INIT;/* owns the patch text */4514struct patch *list = NULL, **listp = &list;4515int skipped_patch =0;45164517 state->patch_input_file = filename;4518read_patch_file(&buf, fd);4519 offset =0;4520while(offset < buf.len) {4521struct patch *patch;4522int nr;45234524 patch =xcalloc(1,sizeof(*patch));4525 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4526 patch->recount = !!(options & RECOUNT);4527 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4528if(nr <0) {4529free_patch(patch);4530break;4531}4532if(state->apply_in_reverse)4533reverse_patches(patch);4534if(use_patch(state, patch)) {4535patch_stats(state, patch);4536*listp = patch;4537 listp = &patch->next;4538}4539else{4540if(state->apply_verbosely)4541say_patch_name(stderr,_("Skipped patch '%s'."), patch);4542free_patch(patch);4543 skipped_patch++;4544}4545 offset += nr;4546}45474548if(!list && !skipped_patch)4549die(_("unrecognized input"));45504551if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4552 state->apply =0;45534554 state->update_index = state->check_index && state->apply;4555if(state->update_index && newfd <0)4556 newfd =hold_locked_index(state->lock_file,1);45574558if(state->check_index) {4559if(read_cache() <0)4560die(_("unable to read index file"));4561}45624563if((state->check || state->apply) &&4564check_patch_list(state, list) <0&&4565!state->apply_with_reject)4566exit(1);45674568if(state->apply &&write_out_results(state, list)) {4569if(state->apply_with_reject)4570exit(1);4571/* with --3way, we still need to write the index out */4572return1;4573}45744575if(state->fake_ancestor)4576build_fake_ancestor(list, state->fake_ancestor);45774578if(state->diffstat)4579stat_patch_list(state, list);45804581if(state->numstat)4582numstat_patch_list(state, list);45834584if(state->summary)4585summary_patch_list(list);45864587free_patch_list(list);4588strbuf_release(&buf);4589string_list_clear(&state->fn_table,0);4590return0;4591}45924593static voidgit_apply_config(void)4594{4595git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4596git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4597git_config(git_default_config, NULL);4598}45994600static intoption_parse_exclude(const struct option *opt,4601const char*arg,int unset)4602{4603struct apply_state *state = opt->value;4604add_name_limit(state, arg,1);4605return0;4606}46074608static intoption_parse_include(const struct option *opt,4609const char*arg,int unset)4610{4611struct apply_state *state = opt->value;4612add_name_limit(state, arg,0);4613 state->has_include =1;4614return0;4615}46164617static intoption_parse_p(const struct option *opt,4618const char*arg,4619int unset)4620{4621struct apply_state *state = opt->value;4622 state->p_value =atoi(arg);4623 state->p_value_known =1;4624return0;4625}46264627static intoption_parse_space_change(const struct option *opt,4628const char*arg,int unset)4629{4630struct apply_state *state = opt->value;4631if(unset)4632 state->ws_ignore_action = ignore_ws_none;4633else4634 state->ws_ignore_action = ignore_ws_change;4635return0;4636}46374638static intoption_parse_whitespace(const struct option *opt,4639const char*arg,int unset)4640{4641struct apply_state *state = opt->value;4642 state->whitespace_option = arg;4643parse_whitespace_option(state, arg);4644return0;4645}46464647static intoption_parse_directory(const struct option *opt,4648const char*arg,int unset)4649{4650struct apply_state *state = opt->value;4651strbuf_reset(&state->root);4652strbuf_addstr(&state->root, arg);4653strbuf_complete(&state->root,'/');4654return0;4655}46564657static voidinit_apply_state(struct apply_state *state,4658const char*prefix,4659struct lock_file *lock_file)4660{4661memset(state,0,sizeof(*state));4662 state->prefix = prefix;4663 state->prefix_length = state->prefix ?strlen(state->prefix) :0;4664 state->lock_file = lock_file;4665 state->apply =1;4666 state->line_termination ='\n';4667 state->p_value =1;4668 state->p_context = UINT_MAX;4669 state->squelch_whitespace_errors =5;4670 state->ws_error_action = warn_on_ws_error;4671 state->ws_ignore_action = ignore_ws_none;4672 state->linenr =1;4673strbuf_init(&state->root,0);46744675git_apply_config();4676if(apply_default_whitespace)4677parse_whitespace_option(state, apply_default_whitespace);4678if(apply_default_ignorewhitespace)4679parse_ignorewhitespace_option(state, apply_default_ignorewhitespace);4680}46814682static voidclear_apply_state(struct apply_state *state)4683{4684string_list_clear(&state->limit_by_name,0);4685string_list_clear(&state->symlink_changes,0);4686strbuf_release(&state->root);46874688/* &state->fn_table is cleared at the end of apply_patch() */4689}46904691static voidcheck_apply_state(struct apply_state *state,int force_apply)4692{4693int is_not_gitdir = !startup_info->have_repository;46944695if(state->apply_with_reject && state->threeway)4696die("--reject and --3way cannot be used together.");4697if(state->cached && state->threeway)4698die("--cached and --3way cannot be used together.");4699if(state->threeway) {4700if(is_not_gitdir)4701die(_("--3way outside a repository"));4702 state->check_index =1;4703}4704if(state->apply_with_reject)4705 state->apply = state->apply_verbosely =1;4706if(!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor))4707 state->apply =0;4708if(state->check_index && is_not_gitdir)4709die(_("--index outside a repository"));4710if(state->cached) {4711if(is_not_gitdir)4712die(_("--cached outside a repository"));4713 state->check_index =1;4714}4715if(state->check_index)4716 state->unsafe_paths =0;4717if(!state->lock_file)4718die("BUG: state->lock_file should not be NULL");4719}47204721static intapply_all_patches(struct apply_state *state,4722int argc,4723const char**argv,4724int options)4725{4726int i;4727int errs =0;4728int read_stdin =1;47294730for(i =0; i < argc; i++) {4731const char*arg = argv[i];4732int fd;47334734if(!strcmp(arg,"-")) {4735 errs |=apply_patch(state,0,"<stdin>", options);4736 read_stdin =0;4737continue;4738}else if(0< state->prefix_length)4739 arg =prefix_filename(state->prefix,4740 state->prefix_length,4741 arg);47424743 fd =open(arg, O_RDONLY);4744if(fd <0)4745die_errno(_("can't open patch '%s'"), arg);4746 read_stdin =0;4747set_default_whitespace_mode(state);4748 errs |=apply_patch(state, fd, arg, options);4749close(fd);4750}4751set_default_whitespace_mode(state);4752if(read_stdin)4753 errs |=apply_patch(state,0,"<stdin>", options);47544755if(state->whitespace_error) {4756if(state->squelch_whitespace_errors &&4757 state->squelch_whitespace_errors < state->whitespace_error) {4758int squelched =4759 state->whitespace_error - state->squelch_whitespace_errors;4760warning(Q_("squelched%dwhitespace error",4761"squelched%dwhitespace errors",4762 squelched),4763 squelched);4764}4765if(state->ws_error_action == die_on_ws_error)4766die(Q_("%dline adds whitespace errors.",4767"%dlines add whitespace errors.",4768 state->whitespace_error),4769 state->whitespace_error);4770if(state->applied_after_fixing_ws && state->apply)4771warning("%dline%sapplied after"4772" fixing whitespace errors.",4773 state->applied_after_fixing_ws,4774 state->applied_after_fixing_ws ==1?"":"s");4775else if(state->whitespace_error)4776warning(Q_("%dline adds whitespace errors.",4777"%dlines add whitespace errors.",4778 state->whitespace_error),4779 state->whitespace_error);4780}47814782if(state->update_index) {4783if(write_locked_index(&the_index, state->lock_file, COMMIT_LOCK))4784die(_("Unable to write new index file"));4785}47864787return!!errs;4788}47894790intcmd_apply(int argc,const char**argv,const char*prefix)4791{4792int force_apply =0;4793int options =0;4794int ret;4795struct apply_state state;47964797struct option builtin_apply_options[] = {4798{ OPTION_CALLBACK,0,"exclude", &state,N_("path"),4799N_("don't apply changes matching the given path"),48000, option_parse_exclude },4801{ OPTION_CALLBACK,0,"include", &state,N_("path"),4802N_("apply changes matching the given path"),48030, option_parse_include },4804{ OPTION_CALLBACK,'p', NULL, &state,N_("num"),4805N_("remove <num> leading slashes from traditional diff paths"),48060, option_parse_p },4807OPT_BOOL(0,"no-add", &state.no_add,4808N_("ignore additions made by the patch")),4809OPT_BOOL(0,"stat", &state.diffstat,4810N_("instead of applying the patch, output diffstat for the input")),4811OPT_NOOP_NOARG(0,"allow-binary-replacement"),4812OPT_NOOP_NOARG(0,"binary"),4813OPT_BOOL(0,"numstat", &state.numstat,4814N_("show number of added and deleted lines in decimal notation")),4815OPT_BOOL(0,"summary", &state.summary,4816N_("instead of applying the patch, output a summary for the input")),4817OPT_BOOL(0,"check", &state.check,4818N_("instead of applying the patch, see if the patch is applicable")),4819OPT_BOOL(0,"index", &state.check_index,4820N_("make sure the patch is applicable to the current index")),4821OPT_BOOL(0,"cached", &state.cached,4822N_("apply a patch without touching the working tree")),4823OPT_BOOL(0,"unsafe-paths", &state.unsafe_paths,4824N_("accept a patch that touches outside the working area")),4825OPT_BOOL(0,"apply", &force_apply,4826N_("also apply the patch (use with --stat/--summary/--check)")),4827OPT_BOOL('3',"3way", &state.threeway,4828N_("attempt three-way merge if a patch does not apply")),4829OPT_FILENAME(0,"build-fake-ancestor", &state.fake_ancestor,4830N_("build a temporary index based on embedded index information")),4831/* Think twice before adding "--nul" synonym to this */4832OPT_SET_INT('z', NULL, &state.line_termination,4833N_("paths are separated with NUL character"),'\0'),4834OPT_INTEGER('C', NULL, &state.p_context,4835N_("ensure at least <n> lines of context match")),4836{ OPTION_CALLBACK,0,"whitespace", &state,N_("action"),4837N_("detect new or modified lines that have whitespace errors"),48380, option_parse_whitespace },4839{ OPTION_CALLBACK,0,"ignore-space-change", &state, NULL,4840N_("ignore changes in whitespace when finding context"),4841 PARSE_OPT_NOARG, option_parse_space_change },4842{ OPTION_CALLBACK,0,"ignore-whitespace", &state, NULL,4843N_("ignore changes in whitespace when finding context"),4844 PARSE_OPT_NOARG, option_parse_space_change },4845OPT_BOOL('R',"reverse", &state.apply_in_reverse,4846N_("apply the patch in reverse")),4847OPT_BOOL(0,"unidiff-zero", &state.unidiff_zero,4848N_("don't expect at least one line of context")),4849OPT_BOOL(0,"reject", &state.apply_with_reject,4850N_("leave the rejected hunks in corresponding *.rej files")),4851OPT_BOOL(0,"allow-overlap", &state.allow_overlap,4852N_("allow overlapping hunks")),4853OPT__VERBOSE(&state.apply_verbosely,N_("be verbose")),4854OPT_BIT(0,"inaccurate-eof", &options,4855N_("tolerate incorrectly detected missing new-line at the end of file"),4856 INACCURATE_EOF),4857OPT_BIT(0,"recount", &options,4858N_("do not trust the line counts in the hunk headers"),4859 RECOUNT),4860{ OPTION_CALLBACK,0,"directory", &state,N_("root"),4861N_("prepend <root> to all filenames"),48620, option_parse_directory },4863OPT_END()4864};48654866init_apply_state(&state, prefix, &lock_file);48674868 argc =parse_options(argc, argv, state.prefix, builtin_apply_options,4869 apply_usage,0);48704871check_apply_state(&state, force_apply);48724873 ret =apply_all_patches(&state, argc, argv, options);48744875clear_apply_state(&state);48764877return ret;4878}