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/* These are lock_file related */ 56struct lock_file *lock_file; 57int newfd; 58 59/* These control what gets looked at and modified */ 60int apply;/* this is not a dry-run */ 61int cached;/* apply to the index only */ 62int check;/* preimage must match working tree, don't actually apply */ 63int check_index;/* preimage must match the indexed version */ 64int update_index;/* check_index && apply */ 65 66/* These control cosmetic aspect of the output */ 67int diffstat;/* just show a diffstat, and don't actually apply */ 68int numstat;/* just show a numeric diffstat, and don't actually apply */ 69int summary;/* just report creation, deletion, etc, and don't actually apply */ 70 71/* These boolean parameters control how the apply is done */ 72int allow_overlap; 73int apply_in_reverse; 74int apply_with_reject; 75int apply_verbosely; 76int no_add; 77int threeway; 78int unidiff_zero; 79int unsafe_paths; 80 81/* Other non boolean parameters */ 82const char*fake_ancestor; 83const char*patch_input_file; 84int line_termination; 85struct strbuf root; 86int p_value; 87int p_value_known; 88unsigned int p_context; 89 90/* Exclude and include path parameters */ 91struct string_list limit_by_name; 92int has_include; 93 94/* Various "current state" */ 95int linenr;/* current line number */ 96struct string_list symlink_changes;/* we have to track symlinks */ 97 98/* 99 * For "diff-stat" like behaviour, we keep track of the biggest change 100 * we've seen, and the longest filename. That allows us to do simple 101 * scaling. 102 */ 103int max_change; 104int max_len; 105 106/* 107 * Records filenames that have been touched, in order to handle 108 * the case where more than one patches touch the same file. 109 */ 110struct string_list fn_table; 111 112/* These control whitespace errors */ 113enum ws_error_action ws_error_action; 114enum ws_ignore ws_ignore_action; 115const char*whitespace_option; 116int whitespace_error; 117int squelch_whitespace_errors; 118int applied_after_fixing_ws; 119}; 120 121static const char*const apply_usage[] = { 122N_("git apply [<options>] [<patch>...]"), 123 NULL 124}; 125 126static voidparse_whitespace_option(struct apply_state *state,const char*option) 127{ 128if(!option) { 129 state->ws_error_action = warn_on_ws_error; 130return; 131} 132if(!strcmp(option,"warn")) { 133 state->ws_error_action = warn_on_ws_error; 134return; 135} 136if(!strcmp(option,"nowarn")) { 137 state->ws_error_action = nowarn_ws_error; 138return; 139} 140if(!strcmp(option,"error")) { 141 state->ws_error_action = die_on_ws_error; 142return; 143} 144if(!strcmp(option,"error-all")) { 145 state->ws_error_action = die_on_ws_error; 146 state->squelch_whitespace_errors =0; 147return; 148} 149if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 150 state->ws_error_action = correct_ws_error; 151return; 152} 153die(_("unrecognized whitespace option '%s'"), option); 154} 155 156static voidparse_ignorewhitespace_option(struct apply_state *state, 157const char*option) 158{ 159if(!option || !strcmp(option,"no") || 160!strcmp(option,"false") || !strcmp(option,"never") || 161!strcmp(option,"none")) { 162 state->ws_ignore_action = ignore_ws_none; 163return; 164} 165if(!strcmp(option,"change")) { 166 state->ws_ignore_action = ignore_ws_change; 167return; 168} 169die(_("unrecognized whitespace ignore option '%s'"), option); 170} 171 172static voidset_default_whitespace_mode(struct apply_state *state) 173{ 174if(!state->whitespace_option && !apply_default_whitespace) 175 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 176} 177 178/* 179 * This represents one "hunk" from a patch, starting with 180 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 181 * patch text is pointed at by patch, and its byte length 182 * is stored in size. leading and trailing are the number 183 * of context lines. 184 */ 185struct fragment { 186unsigned long leading, trailing; 187unsigned long oldpos, oldlines; 188unsigned long newpos, newlines; 189/* 190 * 'patch' is usually borrowed from buf in apply_patch(), 191 * but some codepaths store an allocated buffer. 192 */ 193const char*patch; 194unsigned free_patch:1, 195 rejected:1; 196int size; 197int linenr; 198struct fragment *next; 199}; 200 201/* 202 * When dealing with a binary patch, we reuse "leading" field 203 * to store the type of the binary hunk, either deflated "delta" 204 * or deflated "literal". 205 */ 206#define binary_patch_method leading 207#define BINARY_DELTA_DEFLATED 1 208#define BINARY_LITERAL_DEFLATED 2 209 210/* 211 * This represents a "patch" to a file, both metainfo changes 212 * such as creation/deletion, filemode and content changes represented 213 * as a series of fragments. 214 */ 215struct patch { 216char*new_name, *old_name, *def_name; 217unsigned int old_mode, new_mode; 218int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 219int rejected; 220unsigned ws_rule; 221int lines_added, lines_deleted; 222int score; 223unsigned int is_toplevel_relative:1; 224unsigned int inaccurate_eof:1; 225unsigned int is_binary:1; 226unsigned int is_copy:1; 227unsigned int is_rename:1; 228unsigned int recount:1; 229unsigned int conflicted_threeway:1; 230unsigned int direct_to_threeway:1; 231struct fragment *fragments; 232char*result; 233size_t resultsize; 234char old_sha1_prefix[41]; 235char new_sha1_prefix[41]; 236struct patch *next; 237 238/* three-way fallback result */ 239struct object_id threeway_stage[3]; 240}; 241 242static voidfree_fragment_list(struct fragment *list) 243{ 244while(list) { 245struct fragment *next = list->next; 246if(list->free_patch) 247free((char*)list->patch); 248free(list); 249 list = next; 250} 251} 252 253static voidfree_patch(struct patch *patch) 254{ 255free_fragment_list(patch->fragments); 256free(patch->def_name); 257free(patch->old_name); 258free(patch->new_name); 259free(patch->result); 260free(patch); 261} 262 263static voidfree_patch_list(struct patch *list) 264{ 265while(list) { 266struct patch *next = list->next; 267free_patch(list); 268 list = next; 269} 270} 271 272/* 273 * A line in a file, len-bytes long (includes the terminating LF, 274 * except for an incomplete line at the end if the file ends with 275 * one), and its contents hashes to 'hash'. 276 */ 277struct line { 278size_t len; 279unsigned hash :24; 280unsigned flag :8; 281#define LINE_COMMON 1 282#define LINE_PATCHED 2 283}; 284 285/* 286 * This represents a "file", which is an array of "lines". 287 */ 288struct image { 289char*buf; 290size_t len; 291size_t nr; 292size_t alloc; 293struct line *line_allocated; 294struct line *line; 295}; 296 297static uint32_thash_line(const char*cp,size_t len) 298{ 299size_t i; 300uint32_t h; 301for(i =0, h =0; i < len; i++) { 302if(!isspace(cp[i])) { 303 h = h *3+ (cp[i] &0xff); 304} 305} 306return h; 307} 308 309/* 310 * Compare lines s1 of length n1 and s2 of length n2, ignoring 311 * whitespace difference. Returns 1 if they match, 0 otherwise 312 */ 313static intfuzzy_matchlines(const char*s1,size_t n1, 314const char*s2,size_t n2) 315{ 316const char*last1 = s1 + n1 -1; 317const char*last2 = s2 + n2 -1; 318int result =0; 319 320/* ignore line endings */ 321while((*last1 =='\r') || (*last1 =='\n')) 322 last1--; 323while((*last2 =='\r') || (*last2 =='\n')) 324 last2--; 325 326/* skip leading whitespaces, if both begin with whitespace */ 327if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 328while(isspace(*s1) && (s1 <= last1)) 329 s1++; 330while(isspace(*s2) && (s2 <= last2)) 331 s2++; 332} 333/* early return if both lines are empty */ 334if((s1 > last1) && (s2 > last2)) 335return1; 336while(!result) { 337 result = *s1++ - *s2++; 338/* 339 * Skip whitespace inside. We check for whitespace on 340 * both buffers because we don't want "a b" to match 341 * "ab" 342 */ 343if(isspace(*s1) &&isspace(*s2)) { 344while(isspace(*s1) && s1 <= last1) 345 s1++; 346while(isspace(*s2) && s2 <= last2) 347 s2++; 348} 349/* 350 * If we reached the end on one side only, 351 * lines don't match 352 */ 353if( 354((s2 > last2) && (s1 <= last1)) || 355((s1 > last1) && (s2 <= last2))) 356return0; 357if((s1 > last1) && (s2 > last2)) 358break; 359} 360 361return!result; 362} 363 364static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 365{ 366ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 367 img->line_allocated[img->nr].len = len; 368 img->line_allocated[img->nr].hash =hash_line(bol, len); 369 img->line_allocated[img->nr].flag = flag; 370 img->nr++; 371} 372 373/* 374 * "buf" has the file contents to be patched (read from various sources). 375 * attach it to "image" and add line-based index to it. 376 * "image" now owns the "buf". 377 */ 378static voidprepare_image(struct image *image,char*buf,size_t len, 379int prepare_linetable) 380{ 381const char*cp, *ep; 382 383memset(image,0,sizeof(*image)); 384 image->buf = buf; 385 image->len = len; 386 387if(!prepare_linetable) 388return; 389 390 ep = image->buf + image->len; 391 cp = image->buf; 392while(cp < ep) { 393const char*next; 394for(next = cp; next < ep && *next !='\n'; next++) 395; 396if(next < ep) 397 next++; 398add_line_info(image, cp, next - cp,0); 399 cp = next; 400} 401 image->line = image->line_allocated; 402} 403 404static voidclear_image(struct image *image) 405{ 406free(image->buf); 407free(image->line_allocated); 408memset(image,0,sizeof(*image)); 409} 410 411/* fmt must contain _one_ %s and no other substitution */ 412static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 413{ 414struct strbuf sb = STRBUF_INIT; 415 416if(patch->old_name && patch->new_name && 417strcmp(patch->old_name, patch->new_name)) { 418quote_c_style(patch->old_name, &sb, NULL,0); 419strbuf_addstr(&sb," => "); 420quote_c_style(patch->new_name, &sb, NULL,0); 421}else{ 422const char*n = patch->new_name; 423if(!n) 424 n = patch->old_name; 425quote_c_style(n, &sb, NULL,0); 426} 427fprintf(output, fmt, sb.buf); 428fputc('\n', output); 429strbuf_release(&sb); 430} 431 432#define SLOP (16) 433 434static voidread_patch_file(struct strbuf *sb,int fd) 435{ 436if(strbuf_read(sb, fd,0) <0) 437die_errno("git apply: failed to read"); 438 439/* 440 * Make sure that we have some slop in the buffer 441 * so that we can do speculative "memcmp" etc, and 442 * see to it that it is NUL-filled. 443 */ 444strbuf_grow(sb, SLOP); 445memset(sb->buf + sb->len,0, SLOP); 446} 447 448static unsigned longlinelen(const char*buffer,unsigned long size) 449{ 450unsigned long len =0; 451while(size--) { 452 len++; 453if(*buffer++ =='\n') 454break; 455} 456return len; 457} 458 459static intis_dev_null(const char*str) 460{ 461returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 462} 463 464#define TERM_SPACE 1 465#define TERM_TAB 2 466 467static intname_terminate(int c,int terminate) 468{ 469if(c ==' '&& !(terminate & TERM_SPACE)) 470return0; 471if(c =='\t'&& !(terminate & TERM_TAB)) 472return0; 473 474return1; 475} 476 477/* remove double slashes to make --index work with such filenames */ 478static char*squash_slash(char*name) 479{ 480int i =0, j =0; 481 482if(!name) 483return NULL; 484 485while(name[i]) { 486if((name[j++] = name[i++]) =='/') 487while(name[i] =='/') 488 i++; 489} 490 name[j] ='\0'; 491return name; 492} 493 494static char*find_name_gnu(struct apply_state *state, 495const char*line, 496const char*def, 497int p_value) 498{ 499struct strbuf name = STRBUF_INIT; 500char*cp; 501 502/* 503 * Proposed "new-style" GNU patch/diff format; see 504 * http://marc.info/?l=git&m=112927316408690&w=2 505 */ 506if(unquote_c_style(&name, line, NULL)) { 507strbuf_release(&name); 508return NULL; 509} 510 511for(cp = name.buf; p_value; p_value--) { 512 cp =strchr(cp,'/'); 513if(!cp) { 514strbuf_release(&name); 515return NULL; 516} 517 cp++; 518} 519 520strbuf_remove(&name,0, cp - name.buf); 521if(state->root.len) 522strbuf_insert(&name,0, state->root.buf, state->root.len); 523returnsquash_slash(strbuf_detach(&name, NULL)); 524} 525 526static size_tsane_tz_len(const char*line,size_t len) 527{ 528const char*tz, *p; 529 530if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 531return0; 532 tz = line + len -strlen(" +0500"); 533 534if(tz[1] !='+'&& tz[1] !='-') 535return0; 536 537for(p = tz +2; p != line + len; p++) 538if(!isdigit(*p)) 539return0; 540 541return line + len - tz; 542} 543 544static size_ttz_with_colon_len(const char*line,size_t len) 545{ 546const char*tz, *p; 547 548if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 549return0; 550 tz = line + len -strlen(" +08:00"); 551 552if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 553return0; 554 p = tz +2; 555if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 556!isdigit(*p++) || !isdigit(*p++)) 557return0; 558 559return line + len - tz; 560} 561 562static size_tdate_len(const char*line,size_t len) 563{ 564const char*date, *p; 565 566if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 567return0; 568 p = date = line + len -strlen("72-02-05"); 569 570if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 571!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 572!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 573return0; 574 575if(date - line >=strlen("19") && 576isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 577 date -=strlen("19"); 578 579return line + len - date; 580} 581 582static size_tshort_time_len(const char*line,size_t len) 583{ 584const char*time, *p; 585 586if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 587return0; 588 p = time = line + len -strlen(" 07:01:32"); 589 590/* Permit 1-digit hours? */ 591if(*p++ !=' '|| 592!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 593!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 594!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 595return0; 596 597return line + len - time; 598} 599 600static size_tfractional_time_len(const char*line,size_t len) 601{ 602const char*p; 603size_t n; 604 605/* Expected format: 19:41:17.620000023 */ 606if(!len || !isdigit(line[len -1])) 607return0; 608 p = line + len -1; 609 610/* Fractional seconds. */ 611while(p > line &&isdigit(*p)) 612 p--; 613if(*p !='.') 614return0; 615 616/* Hours, minutes, and whole seconds. */ 617 n =short_time_len(line, p - line); 618if(!n) 619return0; 620 621return line + len - p + n; 622} 623 624static size_ttrailing_spaces_len(const char*line,size_t len) 625{ 626const char*p; 627 628/* Expected format: ' ' x (1 or more) */ 629if(!len || line[len -1] !=' ') 630return0; 631 632 p = line + len; 633while(p != line) { 634 p--; 635if(*p !=' ') 636return line + len - (p +1); 637} 638 639/* All spaces! */ 640return len; 641} 642 643static size_tdiff_timestamp_len(const char*line,size_t len) 644{ 645const char*end = line + len; 646size_t n; 647 648/* 649 * Posix: 2010-07-05 19:41:17 650 * GNU: 2010-07-05 19:41:17.620000023 -0500 651 */ 652 653if(!isdigit(end[-1])) 654return0; 655 656 n =sane_tz_len(line, end - line); 657if(!n) 658 n =tz_with_colon_len(line, end - line); 659 end -= n; 660 661 n =short_time_len(line, end - line); 662if(!n) 663 n =fractional_time_len(line, end - line); 664 end -= n; 665 666 n =date_len(line, end - line); 667if(!n)/* No date. Too bad. */ 668return0; 669 end -= n; 670 671if(end == line)/* No space before date. */ 672return0; 673if(end[-1] =='\t') {/* Success! */ 674 end--; 675return line + len - end; 676} 677if(end[-1] !=' ')/* No space before date. */ 678return0; 679 680/* Whitespace damage. */ 681 end -=trailing_spaces_len(line, end - line); 682return line + len - end; 683} 684 685static char*find_name_common(struct apply_state *state, 686const char*line, 687const char*def, 688int p_value, 689const char*end, 690int terminate) 691{ 692int len; 693const char*start = NULL; 694 695if(p_value ==0) 696 start = line; 697while(line != end) { 698char c = *line; 699 700if(!end &&isspace(c)) { 701if(c =='\n') 702break; 703if(name_terminate(c, terminate)) 704break; 705} 706 line++; 707if(c =='/'&& !--p_value) 708 start = line; 709} 710if(!start) 711returnsquash_slash(xstrdup_or_null(def)); 712 len = line - start; 713if(!len) 714returnsquash_slash(xstrdup_or_null(def)); 715 716/* 717 * Generally we prefer the shorter name, especially 718 * if the other one is just a variation of that with 719 * something else tacked on to the end (ie "file.orig" 720 * or "file~"). 721 */ 722if(def) { 723int deflen =strlen(def); 724if(deflen < len && !strncmp(start, def, deflen)) 725returnsquash_slash(xstrdup(def)); 726} 727 728if(state->root.len) { 729char*ret =xstrfmt("%s%.*s", state->root.buf, len, start); 730returnsquash_slash(ret); 731} 732 733returnsquash_slash(xmemdupz(start, len)); 734} 735 736static char*find_name(struct apply_state *state, 737const char*line, 738char*def, 739int p_value, 740int terminate) 741{ 742if(*line =='"') { 743char*name =find_name_gnu(state, line, def, p_value); 744if(name) 745return name; 746} 747 748returnfind_name_common(state, line, def, p_value, NULL, terminate); 749} 750 751static char*find_name_traditional(struct apply_state *state, 752const char*line, 753char*def, 754int p_value) 755{ 756size_t len; 757size_t date_len; 758 759if(*line =='"') { 760char*name =find_name_gnu(state, line, def, p_value); 761if(name) 762return name; 763} 764 765 len =strchrnul(line,'\n') - line; 766 date_len =diff_timestamp_len(line, len); 767if(!date_len) 768returnfind_name_common(state, line, def, p_value, NULL, TERM_TAB); 769 len -= date_len; 770 771returnfind_name_common(state, line, def, p_value, line + len,0); 772} 773 774static intcount_slashes(const char*cp) 775{ 776int cnt =0; 777char ch; 778 779while((ch = *cp++)) 780if(ch =='/') 781 cnt++; 782return cnt; 783} 784 785/* 786 * Given the string after "--- " or "+++ ", guess the appropriate 787 * p_value for the given patch. 788 */ 789static intguess_p_value(struct apply_state *state,const char*nameline) 790{ 791char*name, *cp; 792int val = -1; 793 794if(is_dev_null(nameline)) 795return-1; 796 name =find_name_traditional(state, nameline, NULL,0); 797if(!name) 798return-1; 799 cp =strchr(name,'/'); 800if(!cp) 801 val =0; 802else if(state->prefix) { 803/* 804 * Does it begin with "a/$our-prefix" and such? Then this is 805 * very likely to apply to our directory. 806 */ 807if(!strncmp(name, state->prefix, state->prefix_length)) 808 val =count_slashes(state->prefix); 809else{ 810 cp++; 811if(!strncmp(cp, state->prefix, state->prefix_length)) 812 val =count_slashes(state->prefix) +1; 813} 814} 815free(name); 816return val; 817} 818 819/* 820 * Does the ---/+++ line have the POSIX timestamp after the last HT? 821 * GNU diff puts epoch there to signal a creation/deletion event. Is 822 * this such a timestamp? 823 */ 824static inthas_epoch_timestamp(const char*nameline) 825{ 826/* 827 * We are only interested in epoch timestamp; any non-zero 828 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 829 * For the same reason, the date must be either 1969-12-31 or 830 * 1970-01-01, and the seconds part must be "00". 831 */ 832const char stamp_regexp[] = 833"^(1969-12-31|1970-01-01)" 834" " 835"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 836" " 837"([-+][0-2][0-9]:?[0-5][0-9])\n"; 838const char*timestamp = NULL, *cp, *colon; 839static regex_t *stamp; 840 regmatch_t m[10]; 841int zoneoffset; 842int hourminute; 843int status; 844 845for(cp = nameline; *cp !='\n'; cp++) { 846if(*cp =='\t') 847 timestamp = cp +1; 848} 849if(!timestamp) 850return0; 851if(!stamp) { 852 stamp =xmalloc(sizeof(*stamp)); 853if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 854warning(_("Cannot prepare timestamp regexp%s"), 855 stamp_regexp); 856return0; 857} 858} 859 860 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 861if(status) { 862if(status != REG_NOMATCH) 863warning(_("regexec returned%dfor input:%s"), 864 status, timestamp); 865return0; 866} 867 868 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 869if(*colon ==':') 870 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 871else 872 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 873if(timestamp[m[3].rm_so] =='-') 874 zoneoffset = -zoneoffset; 875 876/* 877 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 878 * (west of GMT) or 1970-01-01 (east of GMT) 879 */ 880if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 881(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 882return0; 883 884 hourminute = (strtol(timestamp +11, NULL,10) *60+ 885strtol(timestamp +14, NULL,10) - 886 zoneoffset); 887 888return((zoneoffset <0&& hourminute ==1440) || 889(0<= zoneoffset && !hourminute)); 890} 891 892/* 893 * Get the name etc info from the ---/+++ lines of a traditional patch header 894 * 895 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 896 * files, we can happily check the index for a match, but for creating a 897 * new file we should try to match whatever "patch" does. I have no idea. 898 */ 899static voidparse_traditional_patch(struct apply_state *state, 900const char*first, 901const char*second, 902struct patch *patch) 903{ 904char*name; 905 906 first +=4;/* skip "--- " */ 907 second +=4;/* skip "+++ " */ 908if(!state->p_value_known) { 909int p, q; 910 p =guess_p_value(state, first); 911 q =guess_p_value(state, second); 912if(p <0) p = q; 913if(0<= p && p == q) { 914 state->p_value = p; 915 state->p_value_known =1; 916} 917} 918if(is_dev_null(first)) { 919 patch->is_new =1; 920 patch->is_delete =0; 921 name =find_name_traditional(state, second, NULL, state->p_value); 922 patch->new_name = name; 923}else if(is_dev_null(second)) { 924 patch->is_new =0; 925 patch->is_delete =1; 926 name =find_name_traditional(state, first, NULL, state->p_value); 927 patch->old_name = name; 928}else{ 929char*first_name; 930 first_name =find_name_traditional(state, first, NULL, state->p_value); 931 name =find_name_traditional(state, second, first_name, state->p_value); 932free(first_name); 933if(has_epoch_timestamp(first)) { 934 patch->is_new =1; 935 patch->is_delete =0; 936 patch->new_name = name; 937}else if(has_epoch_timestamp(second)) { 938 patch->is_new =0; 939 patch->is_delete =1; 940 patch->old_name = name; 941}else{ 942 patch->old_name = name; 943 patch->new_name =xstrdup_or_null(name); 944} 945} 946if(!name) 947die(_("unable to find filename in patch at line%d"), state->linenr); 948} 949 950static intgitdiff_hdrend(struct apply_state *state, 951const char*line, 952struct patch *patch) 953{ 954return-1; 955} 956 957/* 958 * We're anal about diff header consistency, to make 959 * sure that we don't end up having strange ambiguous 960 * patches floating around. 961 * 962 * As a result, gitdiff_{old|new}name() will check 963 * their names against any previous information, just 964 * to make sure.. 965 */ 966#define DIFF_OLD_NAME 0 967#define DIFF_NEW_NAME 1 968 969static voidgitdiff_verify_name(struct apply_state *state, 970const char*line, 971int isnull, 972char**name, 973int side) 974{ 975if(!*name && !isnull) { 976*name =find_name(state, line, NULL, state->p_value, TERM_TAB); 977return; 978} 979 980if(*name) { 981int len =strlen(*name); 982char*another; 983if(isnull) 984die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 985*name, state->linenr); 986 another =find_name(state, line, NULL, state->p_value, TERM_TAB); 987if(!another ||memcmp(another, *name, len +1)) 988die((side == DIFF_NEW_NAME) ? 989_("git apply: bad git-diff - inconsistent new filename on line%d") : 990_("git apply: bad git-diff - inconsistent old filename on line%d"), state->linenr); 991free(another); 992}else{ 993/* expect "/dev/null" */ 994if(memcmp("/dev/null", line,9) || line[9] !='\n') 995die(_("git apply: bad git-diff - expected /dev/null on line%d"), state->linenr); 996} 997} 998 999static intgitdiff_oldname(struct apply_state *state,1000const char*line,1001struct patch *patch)1002{1003gitdiff_verify_name(state, line,1004 patch->is_new, &patch->old_name,1005 DIFF_OLD_NAME);1006return0;1007}10081009static intgitdiff_newname(struct apply_state *state,1010const char*line,1011struct patch *patch)1012{1013gitdiff_verify_name(state, line,1014 patch->is_delete, &patch->new_name,1015 DIFF_NEW_NAME);1016return0;1017}10181019static intgitdiff_oldmode(struct apply_state *state,1020const char*line,1021struct patch *patch)1022{1023 patch->old_mode =strtoul(line, NULL,8);1024return0;1025}10261027static intgitdiff_newmode(struct apply_state *state,1028const char*line,1029struct patch *patch)1030{1031 patch->new_mode =strtoul(line, NULL,8);1032return0;1033}10341035static intgitdiff_delete(struct apply_state *state,1036const char*line,1037struct patch *patch)1038{1039 patch->is_delete =1;1040free(patch->old_name);1041 patch->old_name =xstrdup_or_null(patch->def_name);1042returngitdiff_oldmode(state, line, patch);1043}10441045static intgitdiff_newfile(struct apply_state *state,1046const char*line,1047struct patch *patch)1048{1049 patch->is_new =1;1050free(patch->new_name);1051 patch->new_name =xstrdup_or_null(patch->def_name);1052returngitdiff_newmode(state, line, patch);1053}10541055static intgitdiff_copysrc(struct apply_state *state,1056const char*line,1057struct patch *patch)1058{1059 patch->is_copy =1;1060free(patch->old_name);1061 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1062return0;1063}10641065static intgitdiff_copydst(struct apply_state *state,1066const char*line,1067struct patch *patch)1068{1069 patch->is_copy =1;1070free(patch->new_name);1071 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1072return0;1073}10741075static intgitdiff_renamesrc(struct apply_state *state,1076const char*line,1077struct patch *patch)1078{1079 patch->is_rename =1;1080free(patch->old_name);1081 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1082return0;1083}10841085static intgitdiff_renamedst(struct apply_state *state,1086const char*line,1087struct patch *patch)1088{1089 patch->is_rename =1;1090free(patch->new_name);1091 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1092return0;1093}10941095static intgitdiff_similarity(struct apply_state *state,1096const char*line,1097struct patch *patch)1098{1099unsigned long val =strtoul(line, NULL,10);1100if(val <=100)1101 patch->score = val;1102return0;1103}11041105static intgitdiff_dissimilarity(struct apply_state *state,1106const char*line,1107struct patch *patch)1108{1109unsigned long val =strtoul(line, NULL,10);1110if(val <=100)1111 patch->score = val;1112return0;1113}11141115static intgitdiff_index(struct apply_state *state,1116const char*line,1117struct patch *patch)1118{1119/*1120 * index line is N hexadecimal, "..", N hexadecimal,1121 * and optional space with octal mode.1122 */1123const char*ptr, *eol;1124int len;11251126 ptr =strchr(line,'.');1127if(!ptr || ptr[1] !='.'||40< ptr - line)1128return0;1129 len = ptr - line;1130memcpy(patch->old_sha1_prefix, line, len);1131 patch->old_sha1_prefix[len] =0;11321133 line = ptr +2;1134 ptr =strchr(line,' ');1135 eol =strchrnul(line,'\n');11361137if(!ptr || eol < ptr)1138 ptr = eol;1139 len = ptr - line;11401141if(40< len)1142return0;1143memcpy(patch->new_sha1_prefix, line, len);1144 patch->new_sha1_prefix[len] =0;1145if(*ptr ==' ')1146 patch->old_mode =strtoul(ptr+1, NULL,8);1147return0;1148}11491150/*1151 * This is normal for a diff that doesn't change anything: we'll fall through1152 * into the next diff. Tell the parser to break out.1153 */1154static intgitdiff_unrecognized(struct apply_state *state,1155const char*line,1156struct patch *patch)1157{1158return-1;1159}11601161/*1162 * Skip p_value leading components from "line"; as we do not accept1163 * absolute paths, return NULL in that case.1164 */1165static const char*skip_tree_prefix(struct apply_state *state,1166const char*line,1167int llen)1168{1169int nslash;1170int i;11711172if(!state->p_value)1173return(llen && line[0] =='/') ? NULL : line;11741175 nslash = state->p_value;1176for(i =0; i < llen; i++) {1177int ch = line[i];1178if(ch =='/'&& --nslash <=0)1179return(i ==0) ? NULL : &line[i +1];1180}1181return NULL;1182}11831184/*1185 * This is to extract the same name that appears on "diff --git"1186 * line. We do not find and return anything if it is a rename1187 * patch, and it is OK because we will find the name elsewhere.1188 * We need to reliably find name only when it is mode-change only,1189 * creation or deletion of an empty file. In any of these cases,1190 * both sides are the same name under a/ and b/ respectively.1191 */1192static char*git_header_name(struct apply_state *state,1193const char*line,1194int llen)1195{1196const char*name;1197const char*second = NULL;1198size_t len, line_len;11991200 line +=strlen("diff --git ");1201 llen -=strlen("diff --git ");12021203if(*line =='"') {1204const char*cp;1205struct strbuf first = STRBUF_INIT;1206struct strbuf sp = STRBUF_INIT;12071208if(unquote_c_style(&first, line, &second))1209goto free_and_fail1;12101211/* strip the a/b prefix including trailing slash */1212 cp =skip_tree_prefix(state, first.buf, first.len);1213if(!cp)1214goto free_and_fail1;1215strbuf_remove(&first,0, cp - first.buf);12161217/*1218 * second points at one past closing dq of name.1219 * find the second name.1220 */1221while((second < line + llen) &&isspace(*second))1222 second++;12231224if(line + llen <= second)1225goto free_and_fail1;1226if(*second =='"') {1227if(unquote_c_style(&sp, second, NULL))1228goto free_and_fail1;1229 cp =skip_tree_prefix(state, sp.buf, sp.len);1230if(!cp)1231goto free_and_fail1;1232/* They must match, otherwise ignore */1233if(strcmp(cp, first.buf))1234goto free_and_fail1;1235strbuf_release(&sp);1236returnstrbuf_detach(&first, NULL);1237}12381239/* unquoted second */1240 cp =skip_tree_prefix(state, second, line + llen - second);1241if(!cp)1242goto free_and_fail1;1243if(line + llen - cp != first.len ||1244memcmp(first.buf, cp, first.len))1245goto free_and_fail1;1246returnstrbuf_detach(&first, NULL);12471248 free_and_fail1:1249strbuf_release(&first);1250strbuf_release(&sp);1251return NULL;1252}12531254/* unquoted first name */1255 name =skip_tree_prefix(state, line, llen);1256if(!name)1257return NULL;12581259/*1260 * since the first name is unquoted, a dq if exists must be1261 * the beginning of the second name.1262 */1263for(second = name; second < line + llen; second++) {1264if(*second =='"') {1265struct strbuf sp = STRBUF_INIT;1266const char*np;12671268if(unquote_c_style(&sp, second, NULL))1269goto free_and_fail2;12701271 np =skip_tree_prefix(state, sp.buf, sp.len);1272if(!np)1273goto free_and_fail2;12741275 len = sp.buf + sp.len - np;1276if(len < second - name &&1277!strncmp(np, name, len) &&1278isspace(name[len])) {1279/* Good */1280strbuf_remove(&sp,0, np - sp.buf);1281returnstrbuf_detach(&sp, NULL);1282}12831284 free_and_fail2:1285strbuf_release(&sp);1286return NULL;1287}1288}12891290/*1291 * Accept a name only if it shows up twice, exactly the same1292 * form.1293 */1294 second =strchr(name,'\n');1295if(!second)1296return NULL;1297 line_len = second - name;1298for(len =0; ; len++) {1299switch(name[len]) {1300default:1301continue;1302case'\n':1303return NULL;1304case'\t':case' ':1305/*1306 * Is this the separator between the preimage1307 * and the postimage pathname? Again, we are1308 * only interested in the case where there is1309 * no rename, as this is only to set def_name1310 * and a rename patch has the names elsewhere1311 * in an unambiguous form.1312 */1313if(!name[len +1])1314return NULL;/* no postimage name */1315 second =skip_tree_prefix(state, name + len +1,1316 line_len - (len +1));1317if(!second)1318return NULL;1319/*1320 * Does len bytes starting at "name" and "second"1321 * (that are separated by one HT or SP we just1322 * found) exactly match?1323 */1324if(second[len] =='\n'&& !strncmp(name, second, len))1325returnxmemdupz(name, len);1326}1327}1328}13291330/* Verify that we recognize the lines following a git header */1331static intparse_git_header(struct apply_state *state,1332const char*line,1333int len,1334unsigned int size,1335struct patch *patch)1336{1337unsigned long offset;13381339/* A git diff has explicit new/delete information, so we don't guess */1340 patch->is_new =0;1341 patch->is_delete =0;13421343/*1344 * Some things may not have the old name in the1345 * rest of the headers anywhere (pure mode changes,1346 * or removing or adding empty files), so we get1347 * the default name from the header.1348 */1349 patch->def_name =git_header_name(state, line, len);1350if(patch->def_name && state->root.len) {1351char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1352free(patch->def_name);1353 patch->def_name = s;1354}13551356 line += len;1357 size -= len;1358 state->linenr++;1359for(offset = len ; size >0; offset += len, size -= len, line += len, state->linenr++) {1360static const struct opentry {1361const char*str;1362int(*fn)(struct apply_state *,const char*,struct patch *);1363} optable[] = {1364{"@@ -", gitdiff_hdrend },1365{"--- ", gitdiff_oldname },1366{"+++ ", gitdiff_newname },1367{"old mode ", gitdiff_oldmode },1368{"new mode ", gitdiff_newmode },1369{"deleted file mode ", gitdiff_delete },1370{"new file mode ", gitdiff_newfile },1371{"copy from ", gitdiff_copysrc },1372{"copy to ", gitdiff_copydst },1373{"rename old ", gitdiff_renamesrc },1374{"rename new ", gitdiff_renamedst },1375{"rename from ", gitdiff_renamesrc },1376{"rename to ", gitdiff_renamedst },1377{"similarity index ", gitdiff_similarity },1378{"dissimilarity index ", gitdiff_dissimilarity },1379{"index ", gitdiff_index },1380{"", gitdiff_unrecognized },1381};1382int i;13831384 len =linelen(line, size);1385if(!len || line[len-1] !='\n')1386break;1387for(i =0; i <ARRAY_SIZE(optable); i++) {1388const struct opentry *p = optable + i;1389int oplen =strlen(p->str);1390if(len < oplen ||memcmp(p->str, line, oplen))1391continue;1392if(p->fn(state, line + oplen, patch) <0)1393return offset;1394break;1395}1396}13971398return offset;1399}14001401static intparse_num(const char*line,unsigned long*p)1402{1403char*ptr;14041405if(!isdigit(*line))1406return0;1407*p =strtoul(line, &ptr,10);1408return ptr - line;1409}14101411static intparse_range(const char*line,int len,int offset,const char*expect,1412unsigned long*p1,unsigned long*p2)1413{1414int digits, ex;14151416if(offset <0|| offset >= len)1417return-1;1418 line += offset;1419 len -= offset;14201421 digits =parse_num(line, p1);1422if(!digits)1423return-1;14241425 offset += digits;1426 line += digits;1427 len -= digits;14281429*p2 =1;1430if(*line ==',') {1431 digits =parse_num(line+1, p2);1432if(!digits)1433return-1;14341435 offset += digits+1;1436 line += digits+1;1437 len -= digits+1;1438}14391440 ex =strlen(expect);1441if(ex > len)1442return-1;1443if(memcmp(line, expect, ex))1444return-1;14451446return offset + ex;1447}14481449static voidrecount_diff(const char*line,int size,struct fragment *fragment)1450{1451int oldlines =0, newlines =0, ret =0;14521453if(size <1) {1454warning("recount: ignore empty hunk");1455return;1456}14571458for(;;) {1459int len =linelen(line, size);1460 size -= len;1461 line += len;14621463if(size <1)1464break;14651466switch(*line) {1467case' ':case'\n':1468 newlines++;1469/* fall through */1470case'-':1471 oldlines++;1472continue;1473case'+':1474 newlines++;1475continue;1476case'\\':1477continue;1478case'@':1479 ret = size <3|| !starts_with(line,"@@ ");1480break;1481case'd':1482 ret = size <5|| !starts_with(line,"diff ");1483break;1484default:1485 ret = -1;1486break;1487}1488if(ret) {1489warning(_("recount: unexpected line: %.*s"),1490(int)linelen(line, size), line);1491return;1492}1493break;1494}1495 fragment->oldlines = oldlines;1496 fragment->newlines = newlines;1497}14981499/*1500 * Parse a unified diff fragment header of the1501 * form "@@ -a,b +c,d @@"1502 */1503static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1504{1505int offset;15061507if(!len || line[len-1] !='\n')1508return-1;15091510/* Figure out the number of lines in a fragment */1511 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1512 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);15131514return offset;1515}15161517static intfind_header(struct apply_state *state,1518const char*line,1519unsigned long size,1520int*hdrsize,1521struct patch *patch)1522{1523unsigned long offset, len;15241525 patch->is_toplevel_relative =0;1526 patch->is_rename = patch->is_copy =0;1527 patch->is_new = patch->is_delete = -1;1528 patch->old_mode = patch->new_mode =0;1529 patch->old_name = patch->new_name = NULL;1530for(offset =0; size >0; offset += len, size -= len, line += len, state->linenr++) {1531unsigned long nextlen;15321533 len =linelen(line, size);1534if(!len)1535break;15361537/* Testing this early allows us to take a few shortcuts.. */1538if(len <6)1539continue;15401541/*1542 * Make sure we don't find any unconnected patch fragments.1543 * That's a sign that we didn't find a header, and that a1544 * patch has become corrupted/broken up.1545 */1546if(!memcmp("@@ -", line,4)) {1547struct fragment dummy;1548if(parse_fragment_header(line, len, &dummy) <0)1549continue;1550die(_("patch fragment without header at line%d: %.*s"),1551 state->linenr, (int)len-1, line);1552}15531554if(size < len +6)1555break;15561557/*1558 * Git patch? It might not have a real patch, just a rename1559 * or mode change, so we handle that specially1560 */1561if(!memcmp("diff --git ", line,11)) {1562int git_hdr_len =parse_git_header(state, line, len, size, patch);1563if(git_hdr_len <= len)1564continue;1565if(!patch->old_name && !patch->new_name) {1566if(!patch->def_name)1567die(Q_("git diff header lacks filename information when removing "1568"%dleading pathname component (line%d)",1569"git diff header lacks filename information when removing "1570"%dleading pathname components (line%d)",1571 state->p_value),1572 state->p_value, state->linenr);1573 patch->old_name =xstrdup(patch->def_name);1574 patch->new_name =xstrdup(patch->def_name);1575}1576if(!patch->is_delete && !patch->new_name)1577die("git diff header lacks filename information "1578"(line%d)", state->linenr);1579 patch->is_toplevel_relative =1;1580*hdrsize = git_hdr_len;1581return offset;1582}15831584/* --- followed by +++ ? */1585if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1586continue;15871588/*1589 * We only accept unified patches, so we want it to1590 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1591 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1592 */1593 nextlen =linelen(line + len, size - len);1594if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1595continue;15961597/* Ok, we'll consider it a patch */1598parse_traditional_patch(state, line, line+len, patch);1599*hdrsize = len + nextlen;1600 state->linenr +=2;1601return offset;1602}1603return-1;1604}16051606static voidrecord_ws_error(struct apply_state *state,1607unsigned result,1608const char*line,1609int len,1610int linenr)1611{1612char*err;16131614if(!result)1615return;16161617 state->whitespace_error++;1618if(state->squelch_whitespace_errors &&1619 state->squelch_whitespace_errors < state->whitespace_error)1620return;16211622 err =whitespace_error_string(result);1623fprintf(stderr,"%s:%d:%s.\n%.*s\n",1624 state->patch_input_file, linenr, err, len, line);1625free(err);1626}16271628static voidcheck_whitespace(struct apply_state *state,1629const char*line,1630int len,1631unsigned ws_rule)1632{1633unsigned result =ws_check(line +1, len -1, ws_rule);16341635record_ws_error(state, result, line +1, len -2, state->linenr);1636}16371638/*1639 * Parse a unified diff. Note that this really needs to parse each1640 * fragment separately, since the only way to know the difference1641 * between a "---" that is part of a patch, and a "---" that starts1642 * the next patch is to look at the line counts..1643 */1644static intparse_fragment(struct apply_state *state,1645const char*line,1646unsigned long size,1647struct patch *patch,1648struct fragment *fragment)1649{1650int added, deleted;1651int len =linelen(line, size), offset;1652unsigned long oldlines, newlines;1653unsigned long leading, trailing;16541655 offset =parse_fragment_header(line, len, fragment);1656if(offset <0)1657return-1;1658if(offset >0&& patch->recount)1659recount_diff(line + offset, size - offset, fragment);1660 oldlines = fragment->oldlines;1661 newlines = fragment->newlines;1662 leading =0;1663 trailing =0;16641665/* Parse the thing.. */1666 line += len;1667 size -= len;1668 state->linenr++;1669 added = deleted =0;1670for(offset = len;16710< size;1672 offset += len, size -= len, line += len, state->linenr++) {1673if(!oldlines && !newlines)1674break;1675 len =linelen(line, size);1676if(!len || line[len-1] !='\n')1677return-1;1678switch(*line) {1679default:1680return-1;1681case'\n':/* newer GNU diff, an empty context line */1682case' ':1683 oldlines--;1684 newlines--;1685if(!deleted && !added)1686 leading++;1687 trailing++;1688if(!state->apply_in_reverse &&1689 state->ws_error_action == correct_ws_error)1690check_whitespace(state, line, len, patch->ws_rule);1691break;1692case'-':1693if(state->apply_in_reverse &&1694 state->ws_error_action != nowarn_ws_error)1695check_whitespace(state, line, len, patch->ws_rule);1696 deleted++;1697 oldlines--;1698 trailing =0;1699break;1700case'+':1701if(!state->apply_in_reverse &&1702 state->ws_error_action != nowarn_ws_error)1703check_whitespace(state, line, len, patch->ws_rule);1704 added++;1705 newlines--;1706 trailing =0;1707break;17081709/*1710 * We allow "\ No newline at end of file". Depending1711 * on locale settings when the patch was produced we1712 * don't know what this line looks like. The only1713 * thing we do know is that it begins with "\ ".1714 * Checking for 12 is just for sanity check -- any1715 * l10n of "\ No newline..." is at least that long.1716 */1717case'\\':1718if(len <12||memcmp(line,"\\",2))1719return-1;1720break;1721}1722}1723if(oldlines || newlines)1724return-1;1725if(!deleted && !added)1726return-1;17271728 fragment->leading = leading;1729 fragment->trailing = trailing;17301731/*1732 * If a fragment ends with an incomplete line, we failed to include1733 * it in the above loop because we hit oldlines == newlines == 01734 * before seeing it.1735 */1736if(12< size && !memcmp(line,"\\",2))1737 offset +=linelen(line, size);17381739 patch->lines_added += added;1740 patch->lines_deleted += deleted;17411742if(0< patch->is_new && oldlines)1743returnerror(_("new file depends on old contents"));1744if(0< patch->is_delete && newlines)1745returnerror(_("deleted file still has contents"));1746return offset;1747}17481749/*1750 * We have seen "diff --git a/... b/..." header (or a traditional patch1751 * header). Read hunks that belong to this patch into fragments and hang1752 * them to the given patch structure.1753 *1754 * The (fragment->patch, fragment->size) pair points into the memory given1755 * by the caller, not a copy, when we return.1756 */1757static intparse_single_patch(struct apply_state *state,1758const char*line,1759unsigned long size,1760struct patch *patch)1761{1762unsigned long offset =0;1763unsigned long oldlines =0, newlines =0, context =0;1764struct fragment **fragp = &patch->fragments;17651766while(size >4&& !memcmp(line,"@@ -",4)) {1767struct fragment *fragment;1768int len;17691770 fragment =xcalloc(1,sizeof(*fragment));1771 fragment->linenr = state->linenr;1772 len =parse_fragment(state, line, size, patch, fragment);1773if(len <=0)1774die(_("corrupt patch at line%d"), state->linenr);1775 fragment->patch = line;1776 fragment->size = len;1777 oldlines += fragment->oldlines;1778 newlines += fragment->newlines;1779 context += fragment->leading + fragment->trailing;17801781*fragp = fragment;1782 fragp = &fragment->next;17831784 offset += len;1785 line += len;1786 size -= len;1787}17881789/*1790 * If something was removed (i.e. we have old-lines) it cannot1791 * be creation, and if something was added it cannot be1792 * deletion. However, the reverse is not true; --unified=01793 * patches that only add are not necessarily creation even1794 * though they do not have any old lines, and ones that only1795 * delete are not necessarily deletion.1796 *1797 * Unfortunately, a real creation/deletion patch do _not_ have1798 * any context line by definition, so we cannot safely tell it1799 * apart with --unified=0 insanity. At least if the patch has1800 * more than one hunk it is not creation or deletion.1801 */1802if(patch->is_new <0&&1803(oldlines || (patch->fragments && patch->fragments->next)))1804 patch->is_new =0;1805if(patch->is_delete <0&&1806(newlines || (patch->fragments && patch->fragments->next)))1807 patch->is_delete =0;18081809if(0< patch->is_new && oldlines)1810die(_("new file%sdepends on old contents"), patch->new_name);1811if(0< patch->is_delete && newlines)1812die(_("deleted file%sstill has contents"), patch->old_name);1813if(!patch->is_delete && !newlines && context)1814fprintf_ln(stderr,1815_("** warning: "1816"file%sbecomes empty but is not deleted"),1817 patch->new_name);18181819return offset;1820}18211822staticinlineintmetadata_changes(struct patch *patch)1823{1824return patch->is_rename >0||1825 patch->is_copy >0||1826 patch->is_new >0||1827 patch->is_delete ||1828(patch->old_mode && patch->new_mode &&1829 patch->old_mode != patch->new_mode);1830}18311832static char*inflate_it(const void*data,unsigned long size,1833unsigned long inflated_size)1834{1835 git_zstream stream;1836void*out;1837int st;18381839memset(&stream,0,sizeof(stream));18401841 stream.next_in = (unsigned char*)data;1842 stream.avail_in = size;1843 stream.next_out = out =xmalloc(inflated_size);1844 stream.avail_out = inflated_size;1845git_inflate_init(&stream);1846 st =git_inflate(&stream, Z_FINISH);1847git_inflate_end(&stream);1848if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1849free(out);1850return NULL;1851}1852return out;1853}18541855/*1856 * Read a binary hunk and return a new fragment; fragment->patch1857 * points at an allocated memory that the caller must free, so1858 * it is marked as "->free_patch = 1".1859 */1860static struct fragment *parse_binary_hunk(struct apply_state *state,1861char**buf_p,1862unsigned long*sz_p,1863int*status_p,1864int*used_p)1865{1866/*1867 * Expect a line that begins with binary patch method ("literal"1868 * or "delta"), followed by the length of data before deflating.1869 * a sequence of 'length-byte' followed by base-85 encoded data1870 * should follow, terminated by a newline.1871 *1872 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1873 * and we would limit the patch line to 66 characters,1874 * so one line can fit up to 13 groups that would decode1875 * to 52 bytes max. The length byte 'A'-'Z' corresponds1876 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1877 */1878int llen, used;1879unsigned long size = *sz_p;1880char*buffer = *buf_p;1881int patch_method;1882unsigned long origlen;1883char*data = NULL;1884int hunk_size =0;1885struct fragment *frag;18861887 llen =linelen(buffer, size);1888 used = llen;18891890*status_p =0;18911892if(starts_with(buffer,"delta ")) {1893 patch_method = BINARY_DELTA_DEFLATED;1894 origlen =strtoul(buffer +6, NULL,10);1895}1896else if(starts_with(buffer,"literal ")) {1897 patch_method = BINARY_LITERAL_DEFLATED;1898 origlen =strtoul(buffer +8, NULL,10);1899}1900else1901return NULL;19021903 state->linenr++;1904 buffer += llen;1905while(1) {1906int byte_length, max_byte_length, newsize;1907 llen =linelen(buffer, size);1908 used += llen;1909 state->linenr++;1910if(llen ==1) {1911/* consume the blank line */1912 buffer++;1913 size--;1914break;1915}1916/*1917 * Minimum line is "A00000\n" which is 7-byte long,1918 * and the line length must be multiple of 5 plus 2.1919 */1920if((llen <7) || (llen-2) %5)1921goto corrupt;1922 max_byte_length = (llen -2) /5*4;1923 byte_length = *buffer;1924if('A'<= byte_length && byte_length <='Z')1925 byte_length = byte_length -'A'+1;1926else if('a'<= byte_length && byte_length <='z')1927 byte_length = byte_length -'a'+27;1928else1929goto corrupt;1930/* if the input length was not multiple of 4, we would1931 * have filler at the end but the filler should never1932 * exceed 3 bytes1933 */1934if(max_byte_length < byte_length ||1935 byte_length <= max_byte_length -4)1936goto corrupt;1937 newsize = hunk_size + byte_length;1938 data =xrealloc(data, newsize);1939if(decode_85(data + hunk_size, buffer +1, byte_length))1940goto corrupt;1941 hunk_size = newsize;1942 buffer += llen;1943 size -= llen;1944}19451946 frag =xcalloc(1,sizeof(*frag));1947 frag->patch =inflate_it(data, hunk_size, origlen);1948 frag->free_patch =1;1949if(!frag->patch)1950goto corrupt;1951free(data);1952 frag->size = origlen;1953*buf_p = buffer;1954*sz_p = size;1955*used_p = used;1956 frag->binary_patch_method = patch_method;1957return frag;19581959 corrupt:1960free(data);1961*status_p = -1;1962error(_("corrupt binary patch at line%d: %.*s"),1963 state->linenr-1, llen-1, buffer);1964return NULL;1965}19661967/*1968 * Returns:1969 * -1 in case of error,1970 * the length of the parsed binary patch otherwise1971 */1972static intparse_binary(struct apply_state *state,1973char*buffer,1974unsigned long size,1975struct patch *patch)1976{1977/*1978 * We have read "GIT binary patch\n"; what follows is a line1979 * that says the patch method (currently, either "literal" or1980 * "delta") and the length of data before deflating; a1981 * sequence of 'length-byte' followed by base-85 encoded data1982 * follows.1983 *1984 * When a binary patch is reversible, there is another binary1985 * hunk in the same format, starting with patch method (either1986 * "literal" or "delta") with the length of data, and a sequence1987 * of length-byte + base-85 encoded data, terminated with another1988 * empty line. This data, when applied to the postimage, produces1989 * the preimage.1990 */1991struct fragment *forward;1992struct fragment *reverse;1993int status;1994int used, used_1;19951996 forward =parse_binary_hunk(state, &buffer, &size, &status, &used);1997if(!forward && !status)1998/* there has to be one hunk (forward hunk) */1999returnerror(_("unrecognized binary patch at line%d"), state->linenr-1);2000if(status)2001/* otherwise we already gave an error message */2002return status;20032004 reverse =parse_binary_hunk(state, &buffer, &size, &status, &used_1);2005if(reverse)2006 used += used_1;2007else if(status) {2008/*2009 * Not having reverse hunk is not an error, but having2010 * a corrupt reverse hunk is.2011 */2012free((void*) forward->patch);2013free(forward);2014return status;2015}2016 forward->next = reverse;2017 patch->fragments = forward;2018 patch->is_binary =1;2019return used;2020}20212022static voidprefix_one(struct apply_state *state,char**name)2023{2024char*old_name = *name;2025if(!old_name)2026return;2027*name =xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));2028free(old_name);2029}20302031static voidprefix_patch(struct apply_state *state,struct patch *p)2032{2033if(!state->prefix || p->is_toplevel_relative)2034return;2035prefix_one(state, &p->new_name);2036prefix_one(state, &p->old_name);2037}20382039/*2040 * include/exclude2041 */20422043static voidadd_name_limit(struct apply_state *state,2044const char*name,2045int exclude)2046{2047struct string_list_item *it;20482049 it =string_list_append(&state->limit_by_name, name);2050 it->util = exclude ? NULL : (void*)1;2051}20522053static intuse_patch(struct apply_state *state,struct patch *p)2054{2055const char*pathname = p->new_name ? p->new_name : p->old_name;2056int i;20572058/* Paths outside are not touched regardless of "--include" */2059if(0< state->prefix_length) {2060int pathlen =strlen(pathname);2061if(pathlen <= state->prefix_length ||2062memcmp(state->prefix, pathname, state->prefix_length))2063return0;2064}20652066/* See if it matches any of exclude/include rule */2067for(i =0; i < state->limit_by_name.nr; i++) {2068struct string_list_item *it = &state->limit_by_name.items[i];2069if(!wildmatch(it->string, pathname,0, NULL))2070return(it->util != NULL);2071}20722073/*2074 * If we had any include, a path that does not match any rule is2075 * not used. Otherwise, we saw bunch of exclude rules (or none)2076 * and such a path is used.2077 */2078return!state->has_include;2079}208020812082/*2083 * Read the patch text in "buffer" that extends for "size" bytes; stop2084 * reading after seeing a single patch (i.e. changes to a single file).2085 * Create fragments (i.e. patch hunks) and hang them to the given patch.2086 * Return the number of bytes consumed, so that the caller can call us2087 * again for the next patch.2088 */2089static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2090{2091int hdrsize, patchsize;2092int offset =find_header(state, buffer, size, &hdrsize, patch);20932094if(offset <0)2095return offset;20962097prefix_patch(state, patch);20982099if(!use_patch(state, patch))2100 patch->ws_rule =0;2101else2102 patch->ws_rule =whitespace_rule(patch->new_name2103? patch->new_name2104: patch->old_name);21052106 patchsize =parse_single_patch(state,2107 buffer + offset + hdrsize,2108 size - offset - hdrsize,2109 patch);21102111if(!patchsize) {2112static const char git_binary[] ="GIT binary patch\n";2113int hd = hdrsize + offset;2114unsigned long llen =linelen(buffer + hd, size - hd);21152116if(llen ==sizeof(git_binary) -1&&2117!memcmp(git_binary, buffer + hd, llen)) {2118int used;2119 state->linenr++;2120 used =parse_binary(state, buffer + hd + llen,2121 size - hd - llen, patch);2122if(used <0)2123return-1;2124if(used)2125 patchsize = used + llen;2126else2127 patchsize =0;2128}2129else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2130static const char*binhdr[] = {2131"Binary files ",2132"Files ",2133 NULL,2134};2135int i;2136for(i =0; binhdr[i]; i++) {2137int len =strlen(binhdr[i]);2138if(len < size - hd &&2139!memcmp(binhdr[i], buffer + hd, len)) {2140 state->linenr++;2141 patch->is_binary =1;2142 patchsize = llen;2143break;2144}2145}2146}21472148/* Empty patch cannot be applied if it is a text patch2149 * without metadata change. A binary patch appears2150 * empty to us here.2151 */2152if((state->apply || state->check) &&2153(!patch->is_binary && !metadata_changes(patch)))2154die(_("patch with only garbage at line%d"), state->linenr);2155}21562157return offset + hdrsize + patchsize;2158}21592160#define swap(a,b) myswap((a),(b),sizeof(a))21612162#define myswap(a, b, size) do { \2163 unsigned char mytmp[size]; \2164 memcpy(mytmp, &a, size); \2165 memcpy(&a, &b, size); \2166 memcpy(&b, mytmp, size); \2167} while (0)21682169static voidreverse_patches(struct patch *p)2170{2171for(; p; p = p->next) {2172struct fragment *frag = p->fragments;21732174swap(p->new_name, p->old_name);2175swap(p->new_mode, p->old_mode);2176swap(p->is_new, p->is_delete);2177swap(p->lines_added, p->lines_deleted);2178swap(p->old_sha1_prefix, p->new_sha1_prefix);21792180for(; frag; frag = frag->next) {2181swap(frag->newpos, frag->oldpos);2182swap(frag->newlines, frag->oldlines);2183}2184}2185}21862187static const char pluses[] =2188"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2189static const char minuses[]=2190"----------------------------------------------------------------------";21912192static voidshow_stats(struct apply_state *state,struct patch *patch)2193{2194struct strbuf qname = STRBUF_INIT;2195char*cp = patch->new_name ? patch->new_name : patch->old_name;2196int max, add, del;21972198quote_c_style(cp, &qname, NULL,0);21992200/*2201 * "scale" the filename2202 */2203 max = state->max_len;2204if(max >50)2205 max =50;22062207if(qname.len > max) {2208 cp =strchr(qname.buf + qname.len +3- max,'/');2209if(!cp)2210 cp = qname.buf + qname.len +3- max;2211strbuf_splice(&qname,0, cp - qname.buf,"...",3);2212}22132214if(patch->is_binary) {2215printf(" %-*s | Bin\n", max, qname.buf);2216strbuf_release(&qname);2217return;2218}22192220printf(" %-*s |", max, qname.buf);2221strbuf_release(&qname);22222223/*2224 * scale the add/delete2225 */2226 max = max + state->max_change >70?70- max : state->max_change;2227 add = patch->lines_added;2228 del = patch->lines_deleted;22292230if(state->max_change >0) {2231int total = ((add + del) * max + state->max_change /2) / state->max_change;2232 add = (add * max + state->max_change /2) / state->max_change;2233 del = total - add;2234}2235printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2236 add, pluses, del, minuses);2237}22382239static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2240{2241switch(st->st_mode & S_IFMT) {2242case S_IFLNK:2243if(strbuf_readlink(buf, path, st->st_size) <0)2244returnerror(_("unable to read symlink%s"), path);2245return0;2246case S_IFREG:2247if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2248returnerror(_("unable to open or read%s"), path);2249convert_to_git(path, buf->buf, buf->len, buf,0);2250return0;2251default:2252return-1;2253}2254}22552256/*2257 * Update the preimage, and the common lines in postimage,2258 * from buffer buf of length len. If postlen is 0 the postimage2259 * is updated in place, otherwise it's updated on a new buffer2260 * of length postlen2261 */22622263static voidupdate_pre_post_images(struct image *preimage,2264struct image *postimage,2265char*buf,2266size_t len,size_t postlen)2267{2268int i, ctx, reduced;2269char*new, *old, *fixed;2270struct image fixed_preimage;22712272/*2273 * Update the preimage with whitespace fixes. Note that we2274 * are not losing preimage->buf -- apply_one_fragment() will2275 * free "oldlines".2276 */2277prepare_image(&fixed_preimage, buf, len,1);2278assert(postlen2279? fixed_preimage.nr == preimage->nr2280: fixed_preimage.nr <= preimage->nr);2281for(i =0; i < fixed_preimage.nr; i++)2282 fixed_preimage.line[i].flag = preimage->line[i].flag;2283free(preimage->line_allocated);2284*preimage = fixed_preimage;22852286/*2287 * Adjust the common context lines in postimage. This can be2288 * done in-place when we are shrinking it with whitespace2289 * fixing, but needs a new buffer when ignoring whitespace or2290 * expanding leading tabs to spaces.2291 *2292 * We trust the caller to tell us if the update can be done2293 * in place (postlen==0) or not.2294 */2295 old = postimage->buf;2296if(postlen)2297new= postimage->buf =xmalloc(postlen);2298else2299new= old;2300 fixed = preimage->buf;23012302for(i = reduced = ctx =0; i < postimage->nr; i++) {2303size_t l_len = postimage->line[i].len;2304if(!(postimage->line[i].flag & LINE_COMMON)) {2305/* an added line -- no counterparts in preimage */2306memmove(new, old, l_len);2307 old += l_len;2308new+= l_len;2309continue;2310}23112312/* a common context -- skip it in the original postimage */2313 old += l_len;23142315/* and find the corresponding one in the fixed preimage */2316while(ctx < preimage->nr &&2317!(preimage->line[ctx].flag & LINE_COMMON)) {2318 fixed += preimage->line[ctx].len;2319 ctx++;2320}23212322/*2323 * preimage is expected to run out, if the caller2324 * fixed addition of trailing blank lines.2325 */2326if(preimage->nr <= ctx) {2327 reduced++;2328continue;2329}23302331/* and copy it in, while fixing the line length */2332 l_len = preimage->line[ctx].len;2333memcpy(new, fixed, l_len);2334new+= l_len;2335 fixed += l_len;2336 postimage->line[i].len = l_len;2337 ctx++;2338}23392340if(postlen2341? postlen <new- postimage->buf2342: postimage->len <new- postimage->buf)2343die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2344(int)postlen, (int) postimage->len, (int)(new- postimage->buf));23452346/* Fix the length of the whole thing */2347 postimage->len =new- postimage->buf;2348 postimage->nr -= reduced;2349}23502351static intline_by_line_fuzzy_match(struct image *img,2352struct image *preimage,2353struct image *postimage,2354unsigned longtry,2355int try_lno,2356int preimage_limit)2357{2358int i;2359size_t imgoff =0;2360size_t preoff =0;2361size_t postlen = postimage->len;2362size_t extra_chars;2363char*buf;2364char*preimage_eof;2365char*preimage_end;2366struct strbuf fixed;2367char*fixed_buf;2368size_t fixed_len;23692370for(i =0; i < preimage_limit; i++) {2371size_t prelen = preimage->line[i].len;2372size_t imglen = img->line[try_lno+i].len;23732374if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2375 preimage->buf + preoff, prelen))2376return0;2377if(preimage->line[i].flag & LINE_COMMON)2378 postlen += imglen - prelen;2379 imgoff += imglen;2380 preoff += prelen;2381}23822383/*2384 * Ok, the preimage matches with whitespace fuzz.2385 *2386 * imgoff now holds the true length of the target that2387 * matches the preimage before the end of the file.2388 *2389 * Count the number of characters in the preimage that fall2390 * beyond the end of the file and make sure that all of them2391 * are whitespace characters. (This can only happen if2392 * we are removing blank lines at the end of the file.)2393 */2394 buf = preimage_eof = preimage->buf + preoff;2395for( ; i < preimage->nr; i++)2396 preoff += preimage->line[i].len;2397 preimage_end = preimage->buf + preoff;2398for( ; buf < preimage_end; buf++)2399if(!isspace(*buf))2400return0;24012402/*2403 * Update the preimage and the common postimage context2404 * lines to use the same whitespace as the target.2405 * If whitespace is missing in the target (i.e.2406 * if the preimage extends beyond the end of the file),2407 * use the whitespace from the preimage.2408 */2409 extra_chars = preimage_end - preimage_eof;2410strbuf_init(&fixed, imgoff + extra_chars);2411strbuf_add(&fixed, img->buf +try, imgoff);2412strbuf_add(&fixed, preimage_eof, extra_chars);2413 fixed_buf =strbuf_detach(&fixed, &fixed_len);2414update_pre_post_images(preimage, postimage,2415 fixed_buf, fixed_len, postlen);2416return1;2417}24182419static intmatch_fragment(struct apply_state *state,2420struct image *img,2421struct image *preimage,2422struct image *postimage,2423unsigned longtry,2424int try_lno,2425unsigned ws_rule,2426int match_beginning,int match_end)2427{2428int i;2429char*fixed_buf, *buf, *orig, *target;2430struct strbuf fixed;2431size_t fixed_len, postlen;2432int preimage_limit;24332434if(preimage->nr + try_lno <= img->nr) {2435/*2436 * The hunk falls within the boundaries of img.2437 */2438 preimage_limit = preimage->nr;2439if(match_end && (preimage->nr + try_lno != img->nr))2440return0;2441}else if(state->ws_error_action == correct_ws_error &&2442(ws_rule & WS_BLANK_AT_EOF)) {2443/*2444 * This hunk extends beyond the end of img, and we are2445 * removing blank lines at the end of the file. This2446 * many lines from the beginning of the preimage must2447 * match with img, and the remainder of the preimage2448 * must be blank.2449 */2450 preimage_limit = img->nr - try_lno;2451}else{2452/*2453 * The hunk extends beyond the end of the img and2454 * we are not removing blanks at the end, so we2455 * should reject the hunk at this position.2456 */2457return0;2458}24592460if(match_beginning && try_lno)2461return0;24622463/* Quick hash check */2464for(i =0; i < preimage_limit; i++)2465if((img->line[try_lno + i].flag & LINE_PATCHED) ||2466(preimage->line[i].hash != img->line[try_lno + i].hash))2467return0;24682469if(preimage_limit == preimage->nr) {2470/*2471 * Do we have an exact match? If we were told to match2472 * at the end, size must be exactly at try+fragsize,2473 * otherwise try+fragsize must be still within the preimage,2474 * and either case, the old piece should match the preimage2475 * exactly.2476 */2477if((match_end2478? (try+ preimage->len == img->len)2479: (try+ preimage->len <= img->len)) &&2480!memcmp(img->buf +try, preimage->buf, preimage->len))2481return1;2482}else{2483/*2484 * The preimage extends beyond the end of img, so2485 * there cannot be an exact match.2486 *2487 * There must be one non-blank context line that match2488 * a line before the end of img.2489 */2490char*buf_end;24912492 buf = preimage->buf;2493 buf_end = buf;2494for(i =0; i < preimage_limit; i++)2495 buf_end += preimage->line[i].len;24962497for( ; buf < buf_end; buf++)2498if(!isspace(*buf))2499break;2500if(buf == buf_end)2501return0;2502}25032504/*2505 * No exact match. If we are ignoring whitespace, run a line-by-line2506 * fuzzy matching. We collect all the line length information because2507 * we need it to adjust whitespace if we match.2508 */2509if(state->ws_ignore_action == ignore_ws_change)2510returnline_by_line_fuzzy_match(img, preimage, postimage,2511try, try_lno, preimage_limit);25122513if(state->ws_error_action != correct_ws_error)2514return0;25152516/*2517 * The hunk does not apply byte-by-byte, but the hash says2518 * it might with whitespace fuzz. We weren't asked to2519 * ignore whitespace, we were asked to correct whitespace2520 * errors, so let's try matching after whitespace correction.2521 *2522 * While checking the preimage against the target, whitespace2523 * errors in both fixed, we count how large the corresponding2524 * postimage needs to be. The postimage prepared by2525 * apply_one_fragment() has whitespace errors fixed on added2526 * lines already, but the common lines were propagated as-is,2527 * which may become longer when their whitespace errors are2528 * fixed.2529 */25302531/* First count added lines in postimage */2532 postlen =0;2533for(i =0; i < postimage->nr; i++) {2534if(!(postimage->line[i].flag & LINE_COMMON))2535 postlen += postimage->line[i].len;2536}25372538/*2539 * The preimage may extend beyond the end of the file,2540 * but in this loop we will only handle the part of the2541 * preimage that falls within the file.2542 */2543strbuf_init(&fixed, preimage->len +1);2544 orig = preimage->buf;2545 target = img->buf +try;2546for(i =0; i < preimage_limit; i++) {2547size_t oldlen = preimage->line[i].len;2548size_t tgtlen = img->line[try_lno + i].len;2549size_t fixstart = fixed.len;2550struct strbuf tgtfix;2551int match;25522553/* Try fixing the line in the preimage */2554ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25552556/* Try fixing the line in the target */2557strbuf_init(&tgtfix, tgtlen);2558ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);25592560/*2561 * If they match, either the preimage was based on2562 * a version before our tree fixed whitespace breakage,2563 * or we are lacking a whitespace-fix patch the tree2564 * the preimage was based on already had (i.e. target2565 * has whitespace breakage, the preimage doesn't).2566 * In either case, we are fixing the whitespace breakages2567 * so we might as well take the fix together with their2568 * real change.2569 */2570 match = (tgtfix.len == fixed.len - fixstart &&2571!memcmp(tgtfix.buf, fixed.buf + fixstart,2572 fixed.len - fixstart));25732574/* Add the length if this is common with the postimage */2575if(preimage->line[i].flag & LINE_COMMON)2576 postlen += tgtfix.len;25772578strbuf_release(&tgtfix);2579if(!match)2580goto unmatch_exit;25812582 orig += oldlen;2583 target += tgtlen;2584}258525862587/*2588 * Now handle the lines in the preimage that falls beyond the2589 * end of the file (if any). They will only match if they are2590 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2591 * false).2592 */2593for( ; i < preimage->nr; i++) {2594size_t fixstart = fixed.len;/* start of the fixed preimage */2595size_t oldlen = preimage->line[i].len;2596int j;25972598/* Try fixing the line in the preimage */2599ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);26002601for(j = fixstart; j < fixed.len; j++)2602if(!isspace(fixed.buf[j]))2603goto unmatch_exit;26042605 orig += oldlen;2606}26072608/*2609 * Yes, the preimage is based on an older version that still2610 * has whitespace breakages unfixed, and fixing them makes the2611 * hunk match. Update the context lines in the postimage.2612 */2613 fixed_buf =strbuf_detach(&fixed, &fixed_len);2614if(postlen < postimage->len)2615 postlen =0;2616update_pre_post_images(preimage, postimage,2617 fixed_buf, fixed_len, postlen);2618return1;26192620 unmatch_exit:2621strbuf_release(&fixed);2622return0;2623}26242625static intfind_pos(struct apply_state *state,2626struct image *img,2627struct image *preimage,2628struct image *postimage,2629int line,2630unsigned ws_rule,2631int match_beginning,int match_end)2632{2633int i;2634unsigned long backwards, forwards,try;2635int backwards_lno, forwards_lno, try_lno;26362637/*2638 * If match_beginning or match_end is specified, there is no2639 * point starting from a wrong line that will never match and2640 * wander around and wait for a match at the specified end.2641 */2642if(match_beginning)2643 line =0;2644else if(match_end)2645 line = img->nr - preimage->nr;26462647/*2648 * Because the comparison is unsigned, the following test2649 * will also take care of a negative line number that can2650 * result when match_end and preimage is larger than the target.2651 */2652if((size_t) line > img->nr)2653 line = img->nr;26542655try=0;2656for(i =0; i < line; i++)2657try+= img->line[i].len;26582659/*2660 * There's probably some smart way to do this, but I'll leave2661 * that to the smart and beautiful people. I'm simple and stupid.2662 */2663 backwards =try;2664 backwards_lno = line;2665 forwards =try;2666 forwards_lno = line;2667 try_lno = line;26682669for(i =0; ; i++) {2670if(match_fragment(state, img, preimage, postimage,2671try, try_lno, ws_rule,2672 match_beginning, match_end))2673return try_lno;26742675 again:2676if(backwards_lno ==0&& forwards_lno == img->nr)2677break;26782679if(i &1) {2680if(backwards_lno ==0) {2681 i++;2682goto again;2683}2684 backwards_lno--;2685 backwards -= img->line[backwards_lno].len;2686try= backwards;2687 try_lno = backwards_lno;2688}else{2689if(forwards_lno == img->nr) {2690 i++;2691goto again;2692}2693 forwards += img->line[forwards_lno].len;2694 forwards_lno++;2695try= forwards;2696 try_lno = forwards_lno;2697}26982699}2700return-1;2701}27022703static voidremove_first_line(struct image *img)2704{2705 img->buf += img->line[0].len;2706 img->len -= img->line[0].len;2707 img->line++;2708 img->nr--;2709}27102711static voidremove_last_line(struct image *img)2712{2713 img->len -= img->line[--img->nr].len;2714}27152716/*2717 * The change from "preimage" and "postimage" has been found to2718 * apply at applied_pos (counts in line numbers) in "img".2719 * Update "img" to remove "preimage" and replace it with "postimage".2720 */2721static voidupdate_image(struct apply_state *state,2722struct image *img,2723int applied_pos,2724struct image *preimage,2725struct image *postimage)2726{2727/*2728 * remove the copy of preimage at offset in img2729 * and replace it with postimage2730 */2731int i, nr;2732size_t remove_count, insert_count, applied_at =0;2733char*result;2734int preimage_limit;27352736/*2737 * If we are removing blank lines at the end of img,2738 * the preimage may extend beyond the end.2739 * If that is the case, we must be careful only to2740 * remove the part of the preimage that falls within2741 * the boundaries of img. Initialize preimage_limit2742 * to the number of lines in the preimage that falls2743 * within the boundaries.2744 */2745 preimage_limit = preimage->nr;2746if(preimage_limit > img->nr - applied_pos)2747 preimage_limit = img->nr - applied_pos;27482749for(i =0; i < applied_pos; i++)2750 applied_at += img->line[i].len;27512752 remove_count =0;2753for(i =0; i < preimage_limit; i++)2754 remove_count += img->line[applied_pos + i].len;2755 insert_count = postimage->len;27562757/* Adjust the contents */2758 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2759memcpy(result, img->buf, applied_at);2760memcpy(result + applied_at, postimage->buf, postimage->len);2761memcpy(result + applied_at + postimage->len,2762 img->buf + (applied_at + remove_count),2763 img->len - (applied_at + remove_count));2764free(img->buf);2765 img->buf = result;2766 img->len += insert_count - remove_count;2767 result[img->len] ='\0';27682769/* Adjust the line table */2770 nr = img->nr + postimage->nr - preimage_limit;2771if(preimage_limit < postimage->nr) {2772/*2773 * NOTE: this knows that we never call remove_first_line()2774 * on anything other than pre/post image.2775 */2776REALLOC_ARRAY(img->line, nr);2777 img->line_allocated = img->line;2778}2779if(preimage_limit != postimage->nr)2780memmove(img->line + applied_pos + postimage->nr,2781 img->line + applied_pos + preimage_limit,2782(img->nr - (applied_pos + preimage_limit)) *2783sizeof(*img->line));2784memcpy(img->line + applied_pos,2785 postimage->line,2786 postimage->nr *sizeof(*img->line));2787if(!state->allow_overlap)2788for(i =0; i < postimage->nr; i++)2789 img->line[applied_pos + i].flag |= LINE_PATCHED;2790 img->nr = nr;2791}27922793/*2794 * Use the patch-hunk text in "frag" to prepare two images (preimage and2795 * postimage) for the hunk. Find lines that match "preimage" in "img" and2796 * replace the part of "img" with "postimage" text.2797 */2798static intapply_one_fragment(struct apply_state *state,2799struct image *img,struct fragment *frag,2800int inaccurate_eof,unsigned ws_rule,2801int nth_fragment)2802{2803int match_beginning, match_end;2804const char*patch = frag->patch;2805int size = frag->size;2806char*old, *oldlines;2807struct strbuf newlines;2808int new_blank_lines_at_end =0;2809int found_new_blank_lines_at_end =0;2810int hunk_linenr = frag->linenr;2811unsigned long leading, trailing;2812int pos, applied_pos;2813struct image preimage;2814struct image postimage;28152816memset(&preimage,0,sizeof(preimage));2817memset(&postimage,0,sizeof(postimage));2818 oldlines =xmalloc(size);2819strbuf_init(&newlines, size);28202821 old = oldlines;2822while(size >0) {2823char first;2824int len =linelen(patch, size);2825int plen;2826int added_blank_line =0;2827int is_blank_context =0;2828size_t start;28292830if(!len)2831break;28322833/*2834 * "plen" is how much of the line we should use for2835 * the actual patch data. Normally we just remove the2836 * first character on the line, but if the line is2837 * followed by "\ No newline", then we also remove the2838 * last one (which is the newline, of course).2839 */2840 plen = len -1;2841if(len < size && patch[len] =='\\')2842 plen--;2843 first = *patch;2844if(state->apply_in_reverse) {2845if(first =='-')2846 first ='+';2847else if(first =='+')2848 first ='-';2849}28502851switch(first) {2852case'\n':2853/* Newer GNU diff, empty context line */2854if(plen <0)2855/* ... followed by '\No newline'; nothing */2856break;2857*old++ ='\n';2858strbuf_addch(&newlines,'\n');2859add_line_info(&preimage,"\n",1, LINE_COMMON);2860add_line_info(&postimage,"\n",1, LINE_COMMON);2861 is_blank_context =1;2862break;2863case' ':2864if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2865ws_blank_line(patch +1, plen, ws_rule))2866 is_blank_context =1;2867case'-':2868memcpy(old, patch +1, plen);2869add_line_info(&preimage, old, plen,2870(first ==' '? LINE_COMMON :0));2871 old += plen;2872if(first =='-')2873break;2874/* Fall-through for ' ' */2875case'+':2876/* --no-add does not add new lines */2877if(first =='+'&& state->no_add)2878break;28792880 start = newlines.len;2881if(first !='+'||2882!state->whitespace_error ||2883 state->ws_error_action != correct_ws_error) {2884strbuf_add(&newlines, patch +1, plen);2885}2886else{2887ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2888}2889add_line_info(&postimage, newlines.buf + start, newlines.len - start,2890(first =='+'?0: LINE_COMMON));2891if(first =='+'&&2892(ws_rule & WS_BLANK_AT_EOF) &&2893ws_blank_line(patch +1, plen, ws_rule))2894 added_blank_line =1;2895break;2896case'@':case'\\':2897/* Ignore it, we already handled it */2898break;2899default:2900if(state->apply_verbosely)2901error(_("invalid start of line: '%c'"), first);2902 applied_pos = -1;2903goto out;2904}2905if(added_blank_line) {2906if(!new_blank_lines_at_end)2907 found_new_blank_lines_at_end = hunk_linenr;2908 new_blank_lines_at_end++;2909}2910else if(is_blank_context)2911;2912else2913 new_blank_lines_at_end =0;2914 patch += len;2915 size -= len;2916 hunk_linenr++;2917}2918if(inaccurate_eof &&2919 old > oldlines && old[-1] =='\n'&&2920 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2921 old--;2922strbuf_setlen(&newlines, newlines.len -1);2923}29242925 leading = frag->leading;2926 trailing = frag->trailing;29272928/*2929 * A hunk to change lines at the beginning would begin with2930 * @@ -1,L +N,M @@2931 * but we need to be careful. -U0 that inserts before the second2932 * line also has this pattern.2933 *2934 * And a hunk to add to an empty file would begin with2935 * @@ -0,0 +N,M @@2936 *2937 * In other words, a hunk that is (frag->oldpos <= 1) with or2938 * without leading context must match at the beginning.2939 */2940 match_beginning = (!frag->oldpos ||2941(frag->oldpos ==1&& !state->unidiff_zero));29422943/*2944 * A hunk without trailing lines must match at the end.2945 * However, we simply cannot tell if a hunk must match end2946 * from the lack of trailing lines if the patch was generated2947 * with unidiff without any context.2948 */2949 match_end = !state->unidiff_zero && !trailing;29502951 pos = frag->newpos ? (frag->newpos -1) :0;2952 preimage.buf = oldlines;2953 preimage.len = old - oldlines;2954 postimage.buf = newlines.buf;2955 postimage.len = newlines.len;2956 preimage.line = preimage.line_allocated;2957 postimage.line = postimage.line_allocated;29582959for(;;) {29602961 applied_pos =find_pos(state, img, &preimage, &postimage, pos,2962 ws_rule, match_beginning, match_end);29632964if(applied_pos >=0)2965break;29662967/* Am I at my context limits? */2968if((leading <= state->p_context) && (trailing <= state->p_context))2969break;2970if(match_beginning || match_end) {2971 match_beginning = match_end =0;2972continue;2973}29742975/*2976 * Reduce the number of context lines; reduce both2977 * leading and trailing if they are equal otherwise2978 * just reduce the larger context.2979 */2980if(leading >= trailing) {2981remove_first_line(&preimage);2982remove_first_line(&postimage);2983 pos--;2984 leading--;2985}2986if(trailing > leading) {2987remove_last_line(&preimage);2988remove_last_line(&postimage);2989 trailing--;2990}2991}29922993if(applied_pos >=0) {2994if(new_blank_lines_at_end &&2995 preimage.nr + applied_pos >= img->nr &&2996(ws_rule & WS_BLANK_AT_EOF) &&2997 state->ws_error_action != nowarn_ws_error) {2998record_ws_error(state, WS_BLANK_AT_EOF,"+",1,2999 found_new_blank_lines_at_end);3000if(state->ws_error_action == correct_ws_error) {3001while(new_blank_lines_at_end--)3002remove_last_line(&postimage);3003}3004/*3005 * We would want to prevent write_out_results()3006 * from taking place in apply_patch() that follows3007 * the callchain led us here, which is:3008 * apply_patch->check_patch_list->check_patch->3009 * apply_data->apply_fragments->apply_one_fragment3010 */3011if(state->ws_error_action == die_on_ws_error)3012 state->apply =0;3013}30143015if(state->apply_verbosely && applied_pos != pos) {3016int offset = applied_pos - pos;3017if(state->apply_in_reverse)3018 offset =0- offset;3019fprintf_ln(stderr,3020Q_("Hunk #%dsucceeded at%d(offset%dline).",3021"Hunk #%dsucceeded at%d(offset%dlines).",3022 offset),3023 nth_fragment, applied_pos +1, offset);3024}30253026/*3027 * Warn if it was necessary to reduce the number3028 * of context lines.3029 */3030if((leading != frag->leading) ||3031(trailing != frag->trailing))3032fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"3033" to apply fragment at%d"),3034 leading, trailing, applied_pos+1);3035update_image(state, img, applied_pos, &preimage, &postimage);3036}else{3037if(state->apply_verbosely)3038error(_("while searching for:\n%.*s"),3039(int)(old - oldlines), oldlines);3040}30413042out:3043free(oldlines);3044strbuf_release(&newlines);3045free(preimage.line_allocated);3046free(postimage.line_allocated);30473048return(applied_pos <0);3049}30503051static intapply_binary_fragment(struct apply_state *state,3052struct image *img,3053struct patch *patch)3054{3055struct fragment *fragment = patch->fragments;3056unsigned long len;3057void*dst;30583059if(!fragment)3060returnerror(_("missing binary patch data for '%s'"),3061 patch->new_name ?3062 patch->new_name :3063 patch->old_name);30643065/* Binary patch is irreversible without the optional second hunk */3066if(state->apply_in_reverse) {3067if(!fragment->next)3068returnerror("cannot reverse-apply a binary patch "3069"without the reverse hunk to '%s'",3070 patch->new_name3071? patch->new_name : patch->old_name);3072 fragment = fragment->next;3073}3074switch(fragment->binary_patch_method) {3075case BINARY_DELTA_DEFLATED:3076 dst =patch_delta(img->buf, img->len, fragment->patch,3077 fragment->size, &len);3078if(!dst)3079return-1;3080clear_image(img);3081 img->buf = dst;3082 img->len = len;3083return0;3084case BINARY_LITERAL_DEFLATED:3085clear_image(img);3086 img->len = fragment->size;3087 img->buf =xmemdupz(fragment->patch, img->len);3088return0;3089}3090return-1;3091}30923093/*3094 * Replace "img" with the result of applying the binary patch.3095 * The binary patch data itself in patch->fragment is still kept3096 * but the preimage prepared by the caller in "img" is freed here3097 * or in the helper function apply_binary_fragment() this calls.3098 */3099static intapply_binary(struct apply_state *state,3100struct image *img,3101struct patch *patch)3102{3103const char*name = patch->old_name ? patch->old_name : patch->new_name;3104unsigned char sha1[20];31053106/*3107 * For safety, we require patch index line to contain3108 * full 40-byte textual SHA1 for old and new, at least for now.3109 */3110if(strlen(patch->old_sha1_prefix) !=40||3111strlen(patch->new_sha1_prefix) !=40||3112get_sha1_hex(patch->old_sha1_prefix, sha1) ||3113get_sha1_hex(patch->new_sha1_prefix, sha1))3114returnerror("cannot apply binary patch to '%s' "3115"without full index line", name);31163117if(patch->old_name) {3118/*3119 * See if the old one matches what the patch3120 * applies to.3121 */3122hash_sha1_file(img->buf, img->len, blob_type, sha1);3123if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3124returnerror("the patch applies to '%s' (%s), "3125"which does not match the "3126"current contents.",3127 name,sha1_to_hex(sha1));3128}3129else{3130/* Otherwise, the old one must be empty. */3131if(img->len)3132returnerror("the patch applies to an empty "3133"'%s' but it is not empty", name);3134}31353136get_sha1_hex(patch->new_sha1_prefix, sha1);3137if(is_null_sha1(sha1)) {3138clear_image(img);3139return0;/* deletion patch */3140}31413142if(has_sha1_file(sha1)) {3143/* We already have the postimage */3144enum object_type type;3145unsigned long size;3146char*result;31473148 result =read_sha1_file(sha1, &type, &size);3149if(!result)3150returnerror("the necessary postimage%sfor "3151"'%s' cannot be read",3152 patch->new_sha1_prefix, name);3153clear_image(img);3154 img->buf = result;3155 img->len = size;3156}else{3157/*3158 * We have verified buf matches the preimage;3159 * apply the patch data to it, which is stored3160 * in the patch->fragments->{patch,size}.3161 */3162if(apply_binary_fragment(state, img, patch))3163returnerror(_("binary patch does not apply to '%s'"),3164 name);31653166/* verify that the result matches */3167hash_sha1_file(img->buf, img->len, blob_type, sha1);3168if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3169returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3170 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3171}31723173return0;3174}31753176static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3177{3178struct fragment *frag = patch->fragments;3179const char*name = patch->old_name ? patch->old_name : patch->new_name;3180unsigned ws_rule = patch->ws_rule;3181unsigned inaccurate_eof = patch->inaccurate_eof;3182int nth =0;31833184if(patch->is_binary)3185returnapply_binary(state, img, patch);31863187while(frag) {3188 nth++;3189if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3190error(_("patch failed:%s:%ld"), name, frag->oldpos);3191if(!state->apply_with_reject)3192return-1;3193 frag->rejected =1;3194}3195 frag = frag->next;3196}3197return0;3198}31993200static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3201{3202if(S_ISGITLINK(mode)) {3203strbuf_grow(buf,100);3204strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3205}else{3206enum object_type type;3207unsigned long sz;3208char*result;32093210 result =read_sha1_file(sha1, &type, &sz);3211if(!result)3212return-1;3213/* XXX read_sha1_file NUL-terminates */3214strbuf_attach(buf, result, sz, sz +1);3215}3216return0;3217}32183219static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3220{3221if(!ce)3222return0;3223returnread_blob_object(buf, ce->sha1, ce->ce_mode);3224}32253226static struct patch *in_fn_table(struct apply_state *state,const char*name)3227{3228struct string_list_item *item;32293230if(name == NULL)3231return NULL;32323233 item =string_list_lookup(&state->fn_table, name);3234if(item != NULL)3235return(struct patch *)item->util;32363237return NULL;3238}32393240/*3241 * item->util in the filename table records the status of the path.3242 * Usually it points at a patch (whose result records the contents3243 * of it after applying it), but it could be PATH_WAS_DELETED for a3244 * path that a previously applied patch has already removed, or3245 * PATH_TO_BE_DELETED for a path that a later patch would remove.3246 *3247 * The latter is needed to deal with a case where two paths A and B3248 * are swapped by first renaming A to B and then renaming B to A;3249 * moving A to B should not be prevented due to presence of B as we3250 * will remove it in a later patch.3251 */3252#define PATH_TO_BE_DELETED ((struct patch *) -2)3253#define PATH_WAS_DELETED ((struct patch *) -1)32543255static intto_be_deleted(struct patch *patch)3256{3257return patch == PATH_TO_BE_DELETED;3258}32593260static intwas_deleted(struct patch *patch)3261{3262return patch == PATH_WAS_DELETED;3263}32643265static voidadd_to_fn_table(struct apply_state *state,struct patch *patch)3266{3267struct string_list_item *item;32683269/*3270 * Always add new_name unless patch is a deletion3271 * This should cover the cases for normal diffs,3272 * file creations and copies3273 */3274if(patch->new_name != NULL) {3275 item =string_list_insert(&state->fn_table, patch->new_name);3276 item->util = patch;3277}32783279/*3280 * store a failure on rename/deletion cases because3281 * later chunks shouldn't patch old names3282 */3283if((patch->new_name == NULL) || (patch->is_rename)) {3284 item =string_list_insert(&state->fn_table, patch->old_name);3285 item->util = PATH_WAS_DELETED;3286}3287}32883289static voidprepare_fn_table(struct apply_state *state,struct patch *patch)3290{3291/*3292 * store information about incoming file deletion3293 */3294while(patch) {3295if((patch->new_name == NULL) || (patch->is_rename)) {3296struct string_list_item *item;3297 item =string_list_insert(&state->fn_table, patch->old_name);3298 item->util = PATH_TO_BE_DELETED;3299}3300 patch = patch->next;3301}3302}33033304static intcheckout_target(struct index_state *istate,3305struct cache_entry *ce,struct stat *st)3306{3307struct checkout costate;33083309memset(&costate,0,sizeof(costate));3310 costate.base_dir ="";3311 costate.refresh_cache =1;3312 costate.istate = istate;3313if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3314returnerror(_("cannot checkout%s"), ce->name);3315return0;3316}33173318static struct patch *previous_patch(struct apply_state *state,3319struct patch *patch,3320int*gone)3321{3322struct patch *previous;33233324*gone =0;3325if(patch->is_copy || patch->is_rename)3326return NULL;/* "git" patches do not depend on the order */33273328 previous =in_fn_table(state, patch->old_name);3329if(!previous)3330return NULL;33313332if(to_be_deleted(previous))3333return NULL;/* the deletion hasn't happened yet */33343335if(was_deleted(previous))3336*gone =1;33373338return previous;3339}33403341static intverify_index_match(const struct cache_entry *ce,struct stat *st)3342{3343if(S_ISGITLINK(ce->ce_mode)) {3344if(!S_ISDIR(st->st_mode))3345return-1;3346return0;3347}3348returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3349}33503351#define SUBMODULE_PATCH_WITHOUT_INDEX 133523353static intload_patch_target(struct apply_state *state,3354struct strbuf *buf,3355const struct cache_entry *ce,3356struct stat *st,3357const char*name,3358unsigned expected_mode)3359{3360if(state->cached || state->check_index) {3361if(read_file_or_gitlink(ce, buf))3362returnerror(_("read of%sfailed"), name);3363}else if(name) {3364if(S_ISGITLINK(expected_mode)) {3365if(ce)3366returnread_file_or_gitlink(ce, buf);3367else3368return SUBMODULE_PATCH_WITHOUT_INDEX;3369}else if(has_symlink_leading_path(name,strlen(name))) {3370returnerror(_("reading from '%s' beyond a symbolic link"), name);3371}else{3372if(read_old_data(st, name, buf))3373returnerror(_("read of%sfailed"), name);3374}3375}3376return0;3377}33783379/*3380 * We are about to apply "patch"; populate the "image" with the3381 * current version we have, from the working tree or from the index,3382 * depending on the situation e.g. --cached/--index. If we are3383 * applying a non-git patch that incrementally updates the tree,3384 * we read from the result of a previous diff.3385 */3386static intload_preimage(struct apply_state *state,3387struct image *image,3388struct patch *patch,struct stat *st,3389const struct cache_entry *ce)3390{3391struct strbuf buf = STRBUF_INIT;3392size_t len;3393char*img;3394struct patch *previous;3395int status;33963397 previous =previous_patch(state, patch, &status);3398if(status)3399returnerror(_("path%shas been renamed/deleted"),3400 patch->old_name);3401if(previous) {3402/* We have a patched copy in memory; use that. */3403strbuf_add(&buf, previous->result, previous->resultsize);3404}else{3405 status =load_patch_target(state, &buf, ce, st,3406 patch->old_name, patch->old_mode);3407if(status <0)3408return status;3409else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3410/*3411 * There is no way to apply subproject3412 * patch without looking at the index.3413 * NEEDSWORK: shouldn't this be flagged3414 * as an error???3415 */3416free_fragment_list(patch->fragments);3417 patch->fragments = NULL;3418}else if(status) {3419returnerror(_("read of%sfailed"), patch->old_name);3420}3421}34223423 img =strbuf_detach(&buf, &len);3424prepare_image(image, img, len, !patch->is_binary);3425return0;3426}34273428static intthree_way_merge(struct image *image,3429char*path,3430const unsigned char*base,3431const unsigned char*ours,3432const unsigned char*theirs)3433{3434 mmfile_t base_file, our_file, their_file;3435 mmbuffer_t result = { NULL };3436int status;34373438read_mmblob(&base_file, base);3439read_mmblob(&our_file, ours);3440read_mmblob(&their_file, theirs);3441 status =ll_merge(&result, path,3442&base_file,"base",3443&our_file,"ours",3444&their_file,"theirs", NULL);3445free(base_file.ptr);3446free(our_file.ptr);3447free(their_file.ptr);3448if(status <0|| !result.ptr) {3449free(result.ptr);3450return-1;3451}3452clear_image(image);3453 image->buf = result.ptr;3454 image->len = result.size;34553456return status;3457}34583459/*3460 * When directly falling back to add/add three-way merge, we read from3461 * the current contents of the new_name. In no cases other than that3462 * this function will be called.3463 */3464static intload_current(struct apply_state *state,3465struct image *image,3466struct patch *patch)3467{3468struct strbuf buf = STRBUF_INIT;3469int status, pos;3470size_t len;3471char*img;3472struct stat st;3473struct cache_entry *ce;3474char*name = patch->new_name;3475unsigned mode = patch->new_mode;34763477if(!patch->is_new)3478die("BUG: patch to%sis not a creation", patch->old_name);34793480 pos =cache_name_pos(name,strlen(name));3481if(pos <0)3482returnerror(_("%s: does not exist in index"), name);3483 ce = active_cache[pos];3484if(lstat(name, &st)) {3485if(errno != ENOENT)3486returnerror(_("%s:%s"), name,strerror(errno));3487if(checkout_target(&the_index, ce, &st))3488return-1;3489}3490if(verify_index_match(ce, &st))3491returnerror(_("%s: does not match index"), name);34923493 status =load_patch_target(state, &buf, ce, &st, name, mode);3494if(status <0)3495return status;3496else if(status)3497return-1;3498 img =strbuf_detach(&buf, &len);3499prepare_image(image, img, len, !patch->is_binary);3500return0;3501}35023503static inttry_threeway(struct apply_state *state,3504struct image *image,3505struct patch *patch,3506struct stat *st,3507const struct cache_entry *ce)3508{3509unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3510struct strbuf buf = STRBUF_INIT;3511size_t len;3512int status;3513char*img;3514struct image tmp_image;35153516/* No point falling back to 3-way merge in these cases */3517if(patch->is_delete ||3518S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3519return-1;35203521/* Preimage the patch was prepared for */3522if(patch->is_new)3523write_sha1_file("",0, blob_type, pre_sha1);3524else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3525read_blob_object(&buf, pre_sha1, patch->old_mode))3526returnerror("repository lacks the necessary blob to fall back on 3-way merge.");35273528fprintf(stderr,"Falling back to three-way merge...\n");35293530 img =strbuf_detach(&buf, &len);3531prepare_image(&tmp_image, img, len,1);3532/* Apply the patch to get the post image */3533if(apply_fragments(state, &tmp_image, patch) <0) {3534clear_image(&tmp_image);3535return-1;3536}3537/* post_sha1[] is theirs */3538write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3539clear_image(&tmp_image);35403541/* our_sha1[] is ours */3542if(patch->is_new) {3543if(load_current(state, &tmp_image, patch))3544returnerror("cannot read the current contents of '%s'",3545 patch->new_name);3546}else{3547if(load_preimage(state, &tmp_image, patch, st, ce))3548returnerror("cannot read the current contents of '%s'",3549 patch->old_name);3550}3551write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3552clear_image(&tmp_image);35533554/* in-core three-way merge between post and our using pre as base */3555 status =three_way_merge(image, patch->new_name,3556 pre_sha1, our_sha1, post_sha1);3557if(status <0) {3558fprintf(stderr,"Failed to fall back on three-way merge...\n");3559return status;3560}35613562if(status) {3563 patch->conflicted_threeway =1;3564if(patch->is_new)3565oidclr(&patch->threeway_stage[0]);3566else3567hashcpy(patch->threeway_stage[0].hash, pre_sha1);3568hashcpy(patch->threeway_stage[1].hash, our_sha1);3569hashcpy(patch->threeway_stage[2].hash, post_sha1);3570fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3571}else{3572fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3573}3574return0;3575}35763577static intapply_data(struct apply_state *state,struct patch *patch,3578struct stat *st,const struct cache_entry *ce)3579{3580struct image image;35813582if(load_preimage(state, &image, patch, st, ce) <0)3583return-1;35843585if(patch->direct_to_threeway ||3586apply_fragments(state, &image, patch) <0) {3587/* Note: with --reject, apply_fragments() returns 0 */3588if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3589return-1;3590}3591 patch->result = image.buf;3592 patch->resultsize = image.len;3593add_to_fn_table(state, patch);3594free(image.line_allocated);35953596if(0< patch->is_delete && patch->resultsize)3597returnerror(_("removal patch leaves file contents"));35983599return0;3600}36013602/*3603 * If "patch" that we are looking at modifies or deletes what we have,3604 * we would want it not to lose any local modification we have, either3605 * in the working tree or in the index.3606 *3607 * This also decides if a non-git patch is a creation patch or a3608 * modification to an existing empty file. We do not check the state3609 * of the current tree for a creation patch in this function; the caller3610 * check_patch() separately makes sure (and errors out otherwise) that3611 * the path the patch creates does not exist in the current tree.3612 */3613static intcheck_preimage(struct apply_state *state,3614struct patch *patch,3615struct cache_entry **ce,3616struct stat *st)3617{3618const char*old_name = patch->old_name;3619struct patch *previous = NULL;3620int stat_ret =0, status;3621unsigned st_mode =0;36223623if(!old_name)3624return0;36253626assert(patch->is_new <=0);3627 previous =previous_patch(state, patch, &status);36283629if(status)3630returnerror(_("path%shas been renamed/deleted"), old_name);3631if(previous) {3632 st_mode = previous->new_mode;3633}else if(!state->cached) {3634 stat_ret =lstat(old_name, st);3635if(stat_ret && errno != ENOENT)3636returnerror(_("%s:%s"), old_name,strerror(errno));3637}36383639if(state->check_index && !previous) {3640int pos =cache_name_pos(old_name,strlen(old_name));3641if(pos <0) {3642if(patch->is_new <0)3643goto is_new;3644returnerror(_("%s: does not exist in index"), old_name);3645}3646*ce = active_cache[pos];3647if(stat_ret <0) {3648if(checkout_target(&the_index, *ce, st))3649return-1;3650}3651if(!state->cached &&verify_index_match(*ce, st))3652returnerror(_("%s: does not match index"), old_name);3653if(state->cached)3654 st_mode = (*ce)->ce_mode;3655}else if(stat_ret <0) {3656if(patch->is_new <0)3657goto is_new;3658returnerror(_("%s:%s"), old_name,strerror(errno));3659}36603661if(!state->cached && !previous)3662 st_mode =ce_mode_from_stat(*ce, st->st_mode);36633664if(patch->is_new <0)3665 patch->is_new =0;3666if(!patch->old_mode)3667 patch->old_mode = st_mode;3668if((st_mode ^ patch->old_mode) & S_IFMT)3669returnerror(_("%s: wrong type"), old_name);3670if(st_mode != patch->old_mode)3671warning(_("%shas type%o, expected%o"),3672 old_name, st_mode, patch->old_mode);3673if(!patch->new_mode && !patch->is_delete)3674 patch->new_mode = st_mode;3675return0;36763677 is_new:3678 patch->is_new =1;3679 patch->is_delete =0;3680free(patch->old_name);3681 patch->old_name = NULL;3682return0;3683}368436853686#define EXISTS_IN_INDEX 13687#define EXISTS_IN_WORKTREE 236883689static intcheck_to_create(struct apply_state *state,3690const char*new_name,3691int ok_if_exists)3692{3693struct stat nst;36943695if(state->check_index &&3696cache_name_pos(new_name,strlen(new_name)) >=0&&3697!ok_if_exists)3698return EXISTS_IN_INDEX;3699if(state->cached)3700return0;37013702if(!lstat(new_name, &nst)) {3703if(S_ISDIR(nst.st_mode) || ok_if_exists)3704return0;3705/*3706 * A leading component of new_name might be a symlink3707 * that is going to be removed with this patch, but3708 * still pointing at somewhere that has the path.3709 * In such a case, path "new_name" does not exist as3710 * far as git is concerned.3711 */3712if(has_symlink_leading_path(new_name,strlen(new_name)))3713return0;37143715return EXISTS_IN_WORKTREE;3716}else if((errno != ENOENT) && (errno != ENOTDIR)) {3717returnerror("%s:%s", new_name,strerror(errno));3718}3719return0;3720}37213722static uintptr_tregister_symlink_changes(struct apply_state *state,3723const char*path,3724uintptr_t what)3725{3726struct string_list_item *ent;37273728 ent =string_list_lookup(&state->symlink_changes, path);3729if(!ent) {3730 ent =string_list_insert(&state->symlink_changes, path);3731 ent->util = (void*)0;3732}3733 ent->util = (void*)(what | ((uintptr_t)ent->util));3734return(uintptr_t)ent->util;3735}37363737static uintptr_tcheck_symlink_changes(struct apply_state *state,const char*path)3738{3739struct string_list_item *ent;37403741 ent =string_list_lookup(&state->symlink_changes, path);3742if(!ent)3743return0;3744return(uintptr_t)ent->util;3745}37463747static voidprepare_symlink_changes(struct apply_state *state,struct patch *patch)3748{3749for( ; patch; patch = patch->next) {3750if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3751(patch->is_rename || patch->is_delete))3752/* the symlink at patch->old_name is removed */3753register_symlink_changes(state, patch->old_name, SYMLINK_GOES_AWAY);37543755if(patch->new_name &&S_ISLNK(patch->new_mode))3756/* the symlink at patch->new_name is created or remains */3757register_symlink_changes(state, patch->new_name, SYMLINK_IN_RESULT);3758}3759}37603761static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3762{3763do{3764unsigned int change;37653766while(--name->len && name->buf[name->len] !='/')3767;/* scan backwards */3768if(!name->len)3769break;3770 name->buf[name->len] ='\0';3771 change =check_symlink_changes(state, name->buf);3772if(change & SYMLINK_IN_RESULT)3773return1;3774if(change & SYMLINK_GOES_AWAY)3775/*3776 * This cannot be "return 0", because we may3777 * see a new one created at a higher level.3778 */3779continue;37803781/* otherwise, check the preimage */3782if(state->check_index) {3783struct cache_entry *ce;37843785 ce =cache_file_exists(name->buf, name->len, ignore_case);3786if(ce &&S_ISLNK(ce->ce_mode))3787return1;3788}else{3789struct stat st;3790if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3791return1;3792}3793}while(1);3794return0;3795}37963797static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3798{3799int ret;3800struct strbuf name = STRBUF_INIT;38013802assert(*name_ !='\0');3803strbuf_addstr(&name, name_);3804 ret =path_is_beyond_symlink_1(state, &name);3805strbuf_release(&name);38063807return ret;3808}38093810static voiddie_on_unsafe_path(struct patch *patch)3811{3812const char*old_name = NULL;3813const char*new_name = NULL;3814if(patch->is_delete)3815 old_name = patch->old_name;3816else if(!patch->is_new && !patch->is_copy)3817 old_name = patch->old_name;3818if(!patch->is_delete)3819 new_name = patch->new_name;38203821if(old_name && !verify_path(old_name))3822die(_("invalid path '%s'"), old_name);3823if(new_name && !verify_path(new_name))3824die(_("invalid path '%s'"), new_name);3825}38263827/*3828 * Check and apply the patch in-core; leave the result in patch->result3829 * for the caller to write it out to the final destination.3830 */3831static intcheck_patch(struct apply_state *state,struct patch *patch)3832{3833struct stat st;3834const char*old_name = patch->old_name;3835const char*new_name = patch->new_name;3836const char*name = old_name ? old_name : new_name;3837struct cache_entry *ce = NULL;3838struct patch *tpatch;3839int ok_if_exists;3840int status;38413842 patch->rejected =1;/* we will drop this after we succeed */38433844 status =check_preimage(state, patch, &ce, &st);3845if(status)3846return status;3847 old_name = patch->old_name;38483849/*3850 * A type-change diff is always split into a patch to delete3851 * old, immediately followed by a patch to create new (see3852 * diff.c::run_diff()); in such a case it is Ok that the entry3853 * to be deleted by the previous patch is still in the working3854 * tree and in the index.3855 *3856 * A patch to swap-rename between A and B would first rename A3857 * to B and then rename B to A. While applying the first one,3858 * the presence of B should not stop A from getting renamed to3859 * B; ask to_be_deleted() about the later rename. Removal of3860 * B and rename from A to B is handled the same way by asking3861 * was_deleted().3862 */3863if((tpatch =in_fn_table(state, new_name)) &&3864(was_deleted(tpatch) ||to_be_deleted(tpatch)))3865 ok_if_exists =1;3866else3867 ok_if_exists =0;38683869if(new_name &&3870((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3871int err =check_to_create(state, new_name, ok_if_exists);38723873if(err && state->threeway) {3874 patch->direct_to_threeway =1;3875}else switch(err) {3876case0:3877break;/* happy */3878case EXISTS_IN_INDEX:3879returnerror(_("%s: already exists in index"), new_name);3880break;3881case EXISTS_IN_WORKTREE:3882returnerror(_("%s: already exists in working directory"),3883 new_name);3884default:3885return err;3886}38873888if(!patch->new_mode) {3889if(0< patch->is_new)3890 patch->new_mode = S_IFREG |0644;3891else3892 patch->new_mode = patch->old_mode;3893}3894}38953896if(new_name && old_name) {3897int same = !strcmp(old_name, new_name);3898if(!patch->new_mode)3899 patch->new_mode = patch->old_mode;3900if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3901if(same)3902returnerror(_("new mode (%o) of%sdoes not "3903"match old mode (%o)"),3904 patch->new_mode, new_name,3905 patch->old_mode);3906else3907returnerror(_("new mode (%o) of%sdoes not "3908"match old mode (%o) of%s"),3909 patch->new_mode, new_name,3910 patch->old_mode, old_name);3911}3912}39133914if(!state->unsafe_paths)3915die_on_unsafe_path(patch);39163917/*3918 * An attempt to read from or delete a path that is beyond a3919 * symbolic link will be prevented by load_patch_target() that3920 * is called at the beginning of apply_data() so we do not3921 * have to worry about a patch marked with "is_delete" bit3922 * here. We however need to make sure that the patch result3923 * is not deposited to a path that is beyond a symbolic link3924 * here.3925 */3926if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3927returnerror(_("affected file '%s' is beyond a symbolic link"),3928 patch->new_name);39293930if(apply_data(state, patch, &st, ce) <0)3931returnerror(_("%s: patch does not apply"), name);3932 patch->rejected =0;3933return0;3934}39353936static intcheck_patch_list(struct apply_state *state,struct patch *patch)3937{3938int err =0;39393940prepare_symlink_changes(state, patch);3941prepare_fn_table(state, patch);3942while(patch) {3943if(state->apply_verbosely)3944say_patch_name(stderr,3945_("Checking patch%s..."), patch);3946 err |=check_patch(state, patch);3947 patch = patch->next;3948}3949return err;3950}39513952/* This function tries to read the sha1 from the current index */3953static intget_current_sha1(const char*path,unsigned char*sha1)3954{3955int pos;39563957if(read_cache() <0)3958return-1;3959 pos =cache_name_pos(path,strlen(path));3960if(pos <0)3961return-1;3962hashcpy(sha1, active_cache[pos]->sha1);3963return0;3964}39653966static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3967{3968/*3969 * A usable gitlink patch has only one fragment (hunk) that looks like:3970 * @@ -1 +1 @@3971 * -Subproject commit <old sha1>3972 * +Subproject commit <new sha1>3973 * or3974 * @@ -1 +0,0 @@3975 * -Subproject commit <old sha1>3976 * for a removal patch.3977 */3978struct fragment *hunk = p->fragments;3979static const char heading[] ="-Subproject commit ";3980char*preimage;39813982if(/* does the patch have only one hunk? */3983 hunk && !hunk->next &&3984/* is its preimage one line? */3985 hunk->oldpos ==1&& hunk->oldlines ==1&&3986/* does preimage begin with the heading? */3987(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3988starts_with(++preimage, heading) &&3989/* does it record full SHA-1? */3990!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3991 preimage[sizeof(heading) +40-1] =='\n'&&3992/* does the abbreviated name on the index line agree with it? */3993starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3994return0;/* it all looks fine */39953996/* we may have full object name on the index line */3997returnget_sha1_hex(p->old_sha1_prefix, sha1);3998}39994000/* Build an index that contains the just the files needed for a 3way merge */4001static voidbuild_fake_ancestor(struct patch *list,const char*filename)4002{4003struct patch *patch;4004struct index_state result = { NULL };4005static struct lock_file lock;40064007/* Once we start supporting the reverse patch, it may be4008 * worth showing the new sha1 prefix, but until then...4009 */4010for(patch = list; patch; patch = patch->next) {4011unsigned char sha1[20];4012struct cache_entry *ce;4013const char*name;40144015 name = patch->old_name ? patch->old_name : patch->new_name;4016if(0< patch->is_new)4017continue;40184019if(S_ISGITLINK(patch->old_mode)) {4020if(!preimage_sha1_in_gitlink_patch(patch, sha1))4021;/* ok, the textual part looks sane */4022else4023die("sha1 information is lacking or useless for submodule%s",4024 name);4025}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {4026;/* ok */4027}else if(!patch->lines_added && !patch->lines_deleted) {4028/* mode-only change: update the current */4029if(get_current_sha1(patch->old_name, sha1))4030die("mode change for%s, which is not "4031"in current HEAD", name);4032}else4033die("sha1 information is lacking or useless "4034"(%s).", name);40354036 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);4037if(!ce)4038die(_("make_cache_entry failed for path '%s'"), name);4039if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))4040die("Could not add%sto temporary index", name);4041}40424043hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);4044if(write_locked_index(&result, &lock, COMMIT_LOCK))4045die("Could not write temporary index to%s", filename);40464047discard_index(&result);4048}40494050static voidstat_patch_list(struct apply_state *state,struct patch *patch)4051{4052int files, adds, dels;40534054for(files = adds = dels =0; patch ; patch = patch->next) {4055 files++;4056 adds += patch->lines_added;4057 dels += patch->lines_deleted;4058show_stats(state, patch);4059}40604061print_stat_summary(stdout, files, adds, dels);4062}40634064static voidnumstat_patch_list(struct apply_state *state,4065struct patch *patch)4066{4067for( ; patch; patch = patch->next) {4068const char*name;4069 name = patch->new_name ? patch->new_name : patch->old_name;4070if(patch->is_binary)4071printf("-\t-\t");4072else4073printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4074write_name_quoted(name, stdout, state->line_termination);4075}4076}40774078static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4079{4080if(mode)4081printf("%smode%06o%s\n", newdelete, mode, name);4082else4083printf("%s %s\n", newdelete, name);4084}40854086static voidshow_mode_change(struct patch *p,int show_name)4087{4088if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4089if(show_name)4090printf(" mode change%06o =>%06o%s\n",4091 p->old_mode, p->new_mode, p->new_name);4092else4093printf(" mode change%06o =>%06o\n",4094 p->old_mode, p->new_mode);4095}4096}40974098static voidshow_rename_copy(struct patch *p)4099{4100const char*renamecopy = p->is_rename ?"rename":"copy";4101const char*old, *new;41024103/* Find common prefix */4104 old = p->old_name;4105new= p->new_name;4106while(1) {4107const char*slash_old, *slash_new;4108 slash_old =strchr(old,'/');4109 slash_new =strchr(new,'/');4110if(!slash_old ||4111!slash_new ||4112 slash_old - old != slash_new -new||4113memcmp(old,new, slash_new -new))4114break;4115 old = slash_old +1;4116new= slash_new +1;4117}4118/* p->old_name thru old is the common prefix, and old and new4119 * through the end of names are renames4120 */4121if(old != p->old_name)4122printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4123(int)(old - p->old_name), p->old_name,4124 old,new, p->score);4125else4126printf("%s %s=>%s(%d%%)\n", renamecopy,4127 p->old_name, p->new_name, p->score);4128show_mode_change(p,0);4129}41304131static voidsummary_patch_list(struct patch *patch)4132{4133struct patch *p;41344135for(p = patch; p; p = p->next) {4136if(p->is_new)4137show_file_mode_name("create", p->new_mode, p->new_name);4138else if(p->is_delete)4139show_file_mode_name("delete", p->old_mode, p->old_name);4140else{4141if(p->is_rename || p->is_copy)4142show_rename_copy(p);4143else{4144if(p->score) {4145printf(" rewrite%s(%d%%)\n",4146 p->new_name, p->score);4147show_mode_change(p,0);4148}4149else4150show_mode_change(p,1);4151}4152}4153}4154}41554156static voidpatch_stats(struct apply_state *state,struct patch *patch)4157{4158int lines = patch->lines_added + patch->lines_deleted;41594160if(lines > state->max_change)4161 state->max_change = lines;4162if(patch->old_name) {4163int len =quote_c_style(patch->old_name, NULL, NULL,0);4164if(!len)4165 len =strlen(patch->old_name);4166if(len > state->max_len)4167 state->max_len = len;4168}4169if(patch->new_name) {4170int len =quote_c_style(patch->new_name, NULL, NULL,0);4171if(!len)4172 len =strlen(patch->new_name);4173if(len > state->max_len)4174 state->max_len = len;4175}4176}41774178static voidremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4179{4180if(state->update_index) {4181if(remove_file_from_cache(patch->old_name) <0)4182die(_("unable to remove%sfrom index"), patch->old_name);4183}4184if(!state->cached) {4185if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4186remove_path(patch->old_name);4187}4188}4189}41904191static voidadd_index_file(struct apply_state *state,4192const char*path,4193unsigned mode,4194void*buf,4195unsigned long size)4196{4197struct stat st;4198struct cache_entry *ce;4199int namelen =strlen(path);4200unsigned ce_size =cache_entry_size(namelen);42014202if(!state->update_index)4203return;42044205 ce =xcalloc(1, ce_size);4206memcpy(ce->name, path, namelen);4207 ce->ce_mode =create_ce_mode(mode);4208 ce->ce_flags =create_ce_flags(0);4209 ce->ce_namelen = namelen;4210if(S_ISGITLINK(mode)) {4211const char*s;42124213if(!skip_prefix(buf,"Subproject commit ", &s) ||4214get_sha1_hex(s, ce->sha1))4215die(_("corrupt patch for submodule%s"), path);4216}else{4217if(!state->cached) {4218if(lstat(path, &st) <0)4219die_errno(_("unable to stat newly created file '%s'"),4220 path);4221fill_stat_cache_info(ce, &st);4222}4223if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4224die(_("unable to create backing store for newly created file%s"), path);4225}4226if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4227die(_("unable to add cache entry for%s"), path);4228}42294230static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4231{4232int fd;4233struct strbuf nbuf = STRBUF_INIT;42344235if(S_ISGITLINK(mode)) {4236struct stat st;4237if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4238return0;4239returnmkdir(path,0777);4240}42414242if(has_symlinks &&S_ISLNK(mode))4243/* Although buf:size is counted string, it also is NUL4244 * terminated.4245 */4246returnsymlink(buf, path);42474248 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4249if(fd <0)4250return-1;42514252if(convert_to_working_tree(path, buf, size, &nbuf)) {4253 size = nbuf.len;4254 buf = nbuf.buf;4255}4256write_or_die(fd, buf, size);4257strbuf_release(&nbuf);42584259if(close(fd) <0)4260die_errno(_("closing file '%s'"), path);4261return0;4262}42634264/*4265 * We optimistically assume that the directories exist,4266 * which is true 99% of the time anyway. If they don't,4267 * we create them and try again.4268 */4269static voidcreate_one_file(struct apply_state *state,4270char*path,4271unsigned mode,4272const char*buf,4273unsigned long size)4274{4275if(state->cached)4276return;4277if(!try_create_file(path, mode, buf, size))4278return;42794280if(errno == ENOENT) {4281if(safe_create_leading_directories(path))4282return;4283if(!try_create_file(path, mode, buf, size))4284return;4285}42864287if(errno == EEXIST || errno == EACCES) {4288/* We may be trying to create a file where a directory4289 * used to be.4290 */4291struct stat st;4292if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4293 errno = EEXIST;4294}42954296if(errno == EEXIST) {4297unsigned int nr =getpid();42984299for(;;) {4300char newpath[PATH_MAX];4301mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4302if(!try_create_file(newpath, mode, buf, size)) {4303if(!rename(newpath, path))4304return;4305unlink_or_warn(newpath);4306break;4307}4308if(errno != EEXIST)4309break;4310++nr;4311}4312}4313die_errno(_("unable to write file '%s' mode%o"), path, mode);4314}43154316static voidadd_conflicted_stages_file(struct apply_state *state,4317struct patch *patch)4318{4319int stage, namelen;4320unsigned ce_size, mode;4321struct cache_entry *ce;43224323if(!state->update_index)4324return;4325 namelen =strlen(patch->new_name);4326 ce_size =cache_entry_size(namelen);4327 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);43284329remove_file_from_cache(patch->new_name);4330for(stage =1; stage <4; stage++) {4331if(is_null_oid(&patch->threeway_stage[stage -1]))4332continue;4333 ce =xcalloc(1, ce_size);4334memcpy(ce->name, patch->new_name, namelen);4335 ce->ce_mode =create_ce_mode(mode);4336 ce->ce_flags =create_ce_flags(stage);4337 ce->ce_namelen = namelen;4338hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4339if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4340die(_("unable to add cache entry for%s"), patch->new_name);4341}4342}43434344static voidcreate_file(struct apply_state *state,struct patch *patch)4345{4346char*path = patch->new_name;4347unsigned mode = patch->new_mode;4348unsigned long size = patch->resultsize;4349char*buf = patch->result;43504351if(!mode)4352 mode = S_IFREG |0644;4353create_one_file(state, path, mode, buf, size);43544355if(patch->conflicted_threeway)4356add_conflicted_stages_file(state, patch);4357else4358add_index_file(state, path, mode, buf, size);4359}43604361/* phase zero is to remove, phase one is to create */4362static voidwrite_out_one_result(struct apply_state *state,4363struct patch *patch,4364int phase)4365{4366if(patch->is_delete >0) {4367if(phase ==0)4368remove_file(state, patch,1);4369return;4370}4371if(patch->is_new >0|| patch->is_copy) {4372if(phase ==1)4373create_file(state, patch);4374return;4375}4376/*4377 * Rename or modification boils down to the same4378 * thing: remove the old, write the new4379 */4380if(phase ==0)4381remove_file(state, patch, patch->is_rename);4382if(phase ==1)4383create_file(state, patch);4384}43854386static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4387{4388FILE*rej;4389char namebuf[PATH_MAX];4390struct fragment *frag;4391int cnt =0;4392struct strbuf sb = STRBUF_INIT;43934394for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4395if(!frag->rejected)4396continue;4397 cnt++;4398}43994400if(!cnt) {4401if(state->apply_verbosely)4402say_patch_name(stderr,4403_("Applied patch%scleanly."), patch);4404return0;4405}44064407/* This should not happen, because a removal patch that leaves4408 * contents are marked "rejected" at the patch level.4409 */4410if(!patch->new_name)4411die(_("internal error"));44124413/* Say this even without --verbose */4414strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4415"Applying patch %%swith%drejects...",4416 cnt),4417 cnt);4418say_patch_name(stderr, sb.buf, patch);4419strbuf_release(&sb);44204421 cnt =strlen(patch->new_name);4422if(ARRAY_SIZE(namebuf) <= cnt +5) {4423 cnt =ARRAY_SIZE(namebuf) -5;4424warning(_("truncating .rej filename to %.*s.rej"),4425 cnt -1, patch->new_name);4426}4427memcpy(namebuf, patch->new_name, cnt);4428memcpy(namebuf + cnt,".rej",5);44294430 rej =fopen(namebuf,"w");4431if(!rej)4432returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));44334434/* Normal git tools never deal with .rej, so do not pretend4435 * this is a git patch by saying --git or giving extended4436 * headers. While at it, maybe please "kompare" that wants4437 * the trailing TAB and some garbage at the end of line ;-).4438 */4439fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4440 patch->new_name, patch->new_name);4441for(cnt =1, frag = patch->fragments;4442 frag;4443 cnt++, frag = frag->next) {4444if(!frag->rejected) {4445fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4446continue;4447}4448fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4449fprintf(rej,"%.*s", frag->size, frag->patch);4450if(frag->patch[frag->size-1] !='\n')4451fputc('\n', rej);4452}4453fclose(rej);4454return-1;4455}44564457static intwrite_out_results(struct apply_state *state,struct patch *list)4458{4459int phase;4460int errs =0;4461struct patch *l;4462struct string_list cpath = STRING_LIST_INIT_DUP;44634464for(phase =0; phase <2; phase++) {4465 l = list;4466while(l) {4467if(l->rejected)4468 errs =1;4469else{4470write_out_one_result(state, l, phase);4471if(phase ==1) {4472if(write_out_one_reject(state, l))4473 errs =1;4474if(l->conflicted_threeway) {4475string_list_append(&cpath, l->new_name);4476 errs =1;4477}4478}4479}4480 l = l->next;4481}4482}44834484if(cpath.nr) {4485struct string_list_item *item;44864487string_list_sort(&cpath);4488for_each_string_list_item(item, &cpath)4489fprintf(stderr,"U%s\n", item->string);4490string_list_clear(&cpath,0);44914492rerere(0);4493}44944495return errs;4496}44974498static struct lock_file lock_file;44994500#define INACCURATE_EOF (1<<0)4501#define RECOUNT (1<<1)45024503static intapply_patch(struct apply_state *state,4504int fd,4505const char*filename,4506int options)4507{4508size_t offset;4509struct strbuf buf = STRBUF_INIT;/* owns the patch text */4510struct patch *list = NULL, **listp = &list;4511int skipped_patch =0;45124513 state->patch_input_file = filename;4514read_patch_file(&buf, fd);4515 offset =0;4516while(offset < buf.len) {4517struct patch *patch;4518int nr;45194520 patch =xcalloc(1,sizeof(*patch));4521 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4522 patch->recount = !!(options & RECOUNT);4523 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4524if(nr <0) {4525free_patch(patch);4526break;4527}4528if(state->apply_in_reverse)4529reverse_patches(patch);4530if(use_patch(state, patch)) {4531patch_stats(state, patch);4532*listp = patch;4533 listp = &patch->next;4534}4535else{4536if(state->apply_verbosely)4537say_patch_name(stderr,_("Skipped patch '%s'."), patch);4538free_patch(patch);4539 skipped_patch++;4540}4541 offset += nr;4542}45434544if(!list && !skipped_patch)4545die(_("unrecognized input"));45464547if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4548 state->apply =0;45494550 state->update_index = state->check_index && state->apply;4551if(state->update_index && state->newfd <0)4552 state->newfd =hold_locked_index(state->lock_file,1);45534554if(state->check_index) {4555if(read_cache() <0)4556die(_("unable to read index file"));4557}45584559if((state->check || state->apply) &&4560check_patch_list(state, list) <0&&4561!state->apply_with_reject)4562exit(1);45634564if(state->apply &&write_out_results(state, list)) {4565if(state->apply_with_reject)4566exit(1);4567/* with --3way, we still need to write the index out */4568return1;4569}45704571if(state->fake_ancestor)4572build_fake_ancestor(list, state->fake_ancestor);45734574if(state->diffstat)4575stat_patch_list(state, list);45764577if(state->numstat)4578numstat_patch_list(state, list);45794580if(state->summary)4581summary_patch_list(list);45824583free_patch_list(list);4584strbuf_release(&buf);4585string_list_clear(&state->fn_table,0);4586return0;4587}45884589static voidgit_apply_config(void)4590{4591git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4592git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4593git_config(git_default_config, NULL);4594}45954596static intoption_parse_exclude(const struct option *opt,4597const char*arg,int unset)4598{4599struct apply_state *state = opt->value;4600add_name_limit(state, arg,1);4601return0;4602}46034604static intoption_parse_include(const struct option *opt,4605const char*arg,int unset)4606{4607struct apply_state *state = opt->value;4608add_name_limit(state, arg,0);4609 state->has_include =1;4610return0;4611}46124613static intoption_parse_p(const struct option *opt,4614const char*arg,4615int unset)4616{4617struct apply_state *state = opt->value;4618 state->p_value =atoi(arg);4619 state->p_value_known =1;4620return0;4621}46224623static intoption_parse_space_change(const struct option *opt,4624const char*arg,int unset)4625{4626struct apply_state *state = opt->value;4627if(unset)4628 state->ws_ignore_action = ignore_ws_none;4629else4630 state->ws_ignore_action = ignore_ws_change;4631return0;4632}46334634static intoption_parse_whitespace(const struct option *opt,4635const char*arg,int unset)4636{4637struct apply_state *state = opt->value;4638 state->whitespace_option = arg;4639parse_whitespace_option(state, arg);4640return0;4641}46424643static intoption_parse_directory(const struct option *opt,4644const char*arg,int unset)4645{4646struct apply_state *state = opt->value;4647strbuf_reset(&state->root);4648strbuf_addstr(&state->root, arg);4649strbuf_complete(&state->root,'/');4650return0;4651}46524653static voidinit_apply_state(struct apply_state *state,4654const char*prefix,4655struct lock_file *lock_file)4656{4657memset(state,0,sizeof(*state));4658 state->prefix = prefix;4659 state->prefix_length = state->prefix ?strlen(state->prefix) :0;4660 state->lock_file = lock_file;4661 state->newfd = -1;4662 state->apply =1;4663 state->line_termination ='\n';4664 state->p_value =1;4665 state->p_context = UINT_MAX;4666 state->squelch_whitespace_errors =5;4667 state->ws_error_action = warn_on_ws_error;4668 state->ws_ignore_action = ignore_ws_none;4669 state->linenr =1;4670string_list_init(&state->fn_table,0);4671string_list_init(&state->limit_by_name,0);4672string_list_init(&state->symlink_changes,0);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 state->newfd = -1;4786}47874788return!!errs;4789}47904791intcmd_apply(int argc,const char**argv,const char*prefix)4792{4793int force_apply =0;4794int options =0;4795int ret;4796struct apply_state state;47974798struct option builtin_apply_options[] = {4799{ OPTION_CALLBACK,0,"exclude", &state,N_("path"),4800N_("don't apply changes matching the given path"),48010, option_parse_exclude },4802{ OPTION_CALLBACK,0,"include", &state,N_("path"),4803N_("apply changes matching the given path"),48040, option_parse_include },4805{ OPTION_CALLBACK,'p', NULL, &state,N_("num"),4806N_("remove <num> leading slashes from traditional diff paths"),48070, option_parse_p },4808OPT_BOOL(0,"no-add", &state.no_add,4809N_("ignore additions made by the patch")),4810OPT_BOOL(0,"stat", &state.diffstat,4811N_("instead of applying the patch, output diffstat for the input")),4812OPT_NOOP_NOARG(0,"allow-binary-replacement"),4813OPT_NOOP_NOARG(0,"binary"),4814OPT_BOOL(0,"numstat", &state.numstat,4815N_("show number of added and deleted lines in decimal notation")),4816OPT_BOOL(0,"summary", &state.summary,4817N_("instead of applying the patch, output a summary for the input")),4818OPT_BOOL(0,"check", &state.check,4819N_("instead of applying the patch, see if the patch is applicable")),4820OPT_BOOL(0,"index", &state.check_index,4821N_("make sure the patch is applicable to the current index")),4822OPT_BOOL(0,"cached", &state.cached,4823N_("apply a patch without touching the working tree")),4824OPT_BOOL(0,"unsafe-paths", &state.unsafe_paths,4825N_("accept a patch that touches outside the working area")),4826OPT_BOOL(0,"apply", &force_apply,4827N_("also apply the patch (use with --stat/--summary/--check)")),4828OPT_BOOL('3',"3way", &state.threeway,4829N_("attempt three-way merge if a patch does not apply")),4830OPT_FILENAME(0,"build-fake-ancestor", &state.fake_ancestor,4831N_("build a temporary index based on embedded index information")),4832/* Think twice before adding "--nul" synonym to this */4833OPT_SET_INT('z', NULL, &state.line_termination,4834N_("paths are separated with NUL character"),'\0'),4835OPT_INTEGER('C', NULL, &state.p_context,4836N_("ensure at least <n> lines of context match")),4837{ OPTION_CALLBACK,0,"whitespace", &state,N_("action"),4838N_("detect new or modified lines that have whitespace errors"),48390, option_parse_whitespace },4840{ OPTION_CALLBACK,0,"ignore-space-change", &state, NULL,4841N_("ignore changes in whitespace when finding context"),4842 PARSE_OPT_NOARG, option_parse_space_change },4843{ OPTION_CALLBACK,0,"ignore-whitespace", &state, NULL,4844N_("ignore changes in whitespace when finding context"),4845 PARSE_OPT_NOARG, option_parse_space_change },4846OPT_BOOL('R',"reverse", &state.apply_in_reverse,4847N_("apply the patch in reverse")),4848OPT_BOOL(0,"unidiff-zero", &state.unidiff_zero,4849N_("don't expect at least one line of context")),4850OPT_BOOL(0,"reject", &state.apply_with_reject,4851N_("leave the rejected hunks in corresponding *.rej files")),4852OPT_BOOL(0,"allow-overlap", &state.allow_overlap,4853N_("allow overlapping hunks")),4854OPT__VERBOSE(&state.apply_verbosely,N_("be verbose")),4855OPT_BIT(0,"inaccurate-eof", &options,4856N_("tolerate incorrectly detected missing new-line at the end of file"),4857 INACCURATE_EOF),4858OPT_BIT(0,"recount", &options,4859N_("do not trust the line counts in the hunk headers"),4860 RECOUNT),4861{ OPTION_CALLBACK,0,"directory", &state,N_("root"),4862N_("prepend <root> to all filenames"),48630, option_parse_directory },4864OPT_END()4865};48664867init_apply_state(&state, prefix, &lock_file);48684869 argc =parse_options(argc, argv, state.prefix, builtin_apply_options,4870 apply_usage,0);48714872check_apply_state(&state, force_apply);48734874 ret =apply_all_patches(&state, argc, argv, options);48754876clear_apply_state(&state);48774878return ret;4879}