1/* 2 * apply.c 3 * 4 * Copyright (C) Linus Torvalds, 2005 5 * 6 * This applies patches on top of some (arbitrary) version of the SCM. 7 * 8 */ 9#include"cache.h" 10#include"lockfile.h" 11#include"cache-tree.h" 12#include"quote.h" 13#include"blob.h" 14#include"delta.h" 15#include"builtin.h" 16#include"string-list.h" 17#include"dir.h" 18#include"diff.h" 19#include"parse-options.h" 20#include"xdiff-interface.h" 21#include"ll-merge.h" 22#include"rerere.h" 23 24enum ws_error_action { 25 nowarn_ws_error, 26 warn_on_ws_error, 27 die_on_ws_error, 28 correct_ws_error 29}; 30 31 32enum ws_ignore { 33 ignore_ws_none, 34 ignore_ws_change 35}; 36 37/* 38 * We need to keep track of how symlinks in the preimage are 39 * manipulated by the patches. A patch to add a/b/c where a/b 40 * is a symlink should not be allowed to affect the directory 41 * the symlink points at, but if the same patch removes a/b, 42 * it is perfectly fine, as the patch removes a/b to make room 43 * to create a directory a/b so that a/b/c can be created. 44 * 45 * See also "struct string_list symlink_changes" in "struct 46 * apply_state". 47 */ 48#define SYMLINK_GOES_AWAY 01 49#define SYMLINK_IN_RESULT 02 50 51struct apply_state { 52const char*prefix; 53int prefix_length; 54 55/* 56 * Since lockfile.c keeps a linked list of all created 57 * lock_file structures, it isn't safe to free(lock_file). 58 */ 59struct lock_file *lock_file; 60int newfd; 61 62/* These control what gets looked at and modified */ 63int apply;/* this is not a dry-run */ 64int cached;/* apply to the index only */ 65int check;/* preimage must match working tree, don't actually apply */ 66int check_index;/* preimage must match the indexed version */ 67int update_index;/* check_index && apply */ 68 69/* These control cosmetic aspect of the output */ 70int diffstat;/* just show a diffstat, and don't actually apply */ 71int numstat;/* just show a numeric diffstat, and don't actually apply */ 72int summary;/* just report creation, deletion, etc, and don't actually apply */ 73 74/* These boolean parameters control how the apply is done */ 75int allow_overlap; 76int apply_in_reverse; 77int apply_with_reject; 78int apply_verbosely; 79int no_add; 80int threeway; 81int unidiff_zero; 82int unsafe_paths; 83 84/* Other non boolean parameters */ 85const char*fake_ancestor; 86const char*patch_input_file; 87int line_termination; 88struct strbuf root; 89int p_value; 90int p_value_known; 91unsigned int p_context; 92 93/* Exclude and include path parameters */ 94struct string_list limit_by_name; 95int has_include; 96 97/* Various "current state" */ 98int linenr;/* current line number */ 99struct string_list symlink_changes;/* we have to track symlinks */ 100 101/* 102 * For "diff-stat" like behaviour, we keep track of the biggest change 103 * we've seen, and the longest filename. That allows us to do simple 104 * scaling. 105 */ 106int max_change; 107int max_len; 108 109/* 110 * Records filenames that have been touched, in order to handle 111 * the case where more than one patches touch the same file. 112 */ 113struct string_list fn_table; 114 115/* These control whitespace errors */ 116enum ws_error_action ws_error_action; 117enum ws_ignore ws_ignore_action; 118const char*whitespace_option; 119int whitespace_error; 120int squelch_whitespace_errors; 121int applied_after_fixing_ws; 122}; 123 124static const char*const apply_usage[] = { 125N_("git apply [<options>] [<patch>...]"), 126 NULL 127}; 128 129static voidparse_whitespace_option(struct apply_state *state,const char*option) 130{ 131if(!option) { 132 state->ws_error_action = warn_on_ws_error; 133return; 134} 135if(!strcmp(option,"warn")) { 136 state->ws_error_action = warn_on_ws_error; 137return; 138} 139if(!strcmp(option,"nowarn")) { 140 state->ws_error_action = nowarn_ws_error; 141return; 142} 143if(!strcmp(option,"error")) { 144 state->ws_error_action = die_on_ws_error; 145return; 146} 147if(!strcmp(option,"error-all")) { 148 state->ws_error_action = die_on_ws_error; 149 state->squelch_whitespace_errors =0; 150return; 151} 152if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 153 state->ws_error_action = correct_ws_error; 154return; 155} 156die(_("unrecognized whitespace option '%s'"), option); 157} 158 159static voidparse_ignorewhitespace_option(struct apply_state *state, 160const char*option) 161{ 162if(!option || !strcmp(option,"no") || 163!strcmp(option,"false") || !strcmp(option,"never") || 164!strcmp(option,"none")) { 165 state->ws_ignore_action = ignore_ws_none; 166return; 167} 168if(!strcmp(option,"change")) { 169 state->ws_ignore_action = ignore_ws_change; 170return; 171} 172die(_("unrecognized whitespace ignore option '%s'"), option); 173} 174 175static voidset_default_whitespace_mode(struct apply_state *state) 176{ 177if(!state->whitespace_option && !apply_default_whitespace) 178 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 179} 180 181/* 182 * This represents one "hunk" from a patch, starting with 183 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 184 * patch text is pointed at by patch, and its byte length 185 * is stored in size. leading and trailing are the number 186 * of context lines. 187 */ 188struct fragment { 189unsigned long leading, trailing; 190unsigned long oldpos, oldlines; 191unsigned long newpos, newlines; 192/* 193 * 'patch' is usually borrowed from buf in apply_patch(), 194 * but some codepaths store an allocated buffer. 195 */ 196const char*patch; 197unsigned free_patch:1, 198 rejected:1; 199int size; 200int linenr; 201struct fragment *next; 202}; 203 204/* 205 * When dealing with a binary patch, we reuse "leading" field 206 * to store the type of the binary hunk, either deflated "delta" 207 * or deflated "literal". 208 */ 209#define binary_patch_method leading 210#define BINARY_DELTA_DEFLATED 1 211#define BINARY_LITERAL_DEFLATED 2 212 213/* 214 * This represents a "patch" to a file, both metainfo changes 215 * such as creation/deletion, filemode and content changes represented 216 * as a series of fragments. 217 */ 218struct patch { 219char*new_name, *old_name, *def_name; 220unsigned int old_mode, new_mode; 221int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 222int rejected; 223unsigned ws_rule; 224int lines_added, lines_deleted; 225int score; 226unsigned int is_toplevel_relative:1; 227unsigned int inaccurate_eof:1; 228unsigned int is_binary:1; 229unsigned int is_copy:1; 230unsigned int is_rename:1; 231unsigned int recount:1; 232unsigned int conflicted_threeway:1; 233unsigned int direct_to_threeway:1; 234struct fragment *fragments; 235char*result; 236size_t resultsize; 237char old_sha1_prefix[41]; 238char new_sha1_prefix[41]; 239struct patch *next; 240 241/* three-way fallback result */ 242struct object_id threeway_stage[3]; 243}; 244 245static voidfree_fragment_list(struct fragment *list) 246{ 247while(list) { 248struct fragment *next = list->next; 249if(list->free_patch) 250free((char*)list->patch); 251free(list); 252 list = next; 253} 254} 255 256static voidfree_patch(struct patch *patch) 257{ 258free_fragment_list(patch->fragments); 259free(patch->def_name); 260free(patch->old_name); 261free(patch->new_name); 262free(patch->result); 263free(patch); 264} 265 266static voidfree_patch_list(struct patch *list) 267{ 268while(list) { 269struct patch *next = list->next; 270free_patch(list); 271 list = next; 272} 273} 274 275/* 276 * A line in a file, len-bytes long (includes the terminating LF, 277 * except for an incomplete line at the end if the file ends with 278 * one), and its contents hashes to 'hash'. 279 */ 280struct line { 281size_t len; 282unsigned hash :24; 283unsigned flag :8; 284#define LINE_COMMON 1 285#define LINE_PATCHED 2 286}; 287 288/* 289 * This represents a "file", which is an array of "lines". 290 */ 291struct image { 292char*buf; 293size_t len; 294size_t nr; 295size_t alloc; 296struct line *line_allocated; 297struct line *line; 298}; 299 300static uint32_thash_line(const char*cp,size_t len) 301{ 302size_t i; 303uint32_t h; 304for(i =0, h =0; i < len; i++) { 305if(!isspace(cp[i])) { 306 h = h *3+ (cp[i] &0xff); 307} 308} 309return h; 310} 311 312/* 313 * Compare lines s1 of length n1 and s2 of length n2, ignoring 314 * whitespace difference. Returns 1 if they match, 0 otherwise 315 */ 316static intfuzzy_matchlines(const char*s1,size_t n1, 317const char*s2,size_t n2) 318{ 319const char*last1 = s1 + n1 -1; 320const char*last2 = s2 + n2 -1; 321int result =0; 322 323/* ignore line endings */ 324while((*last1 =='\r') || (*last1 =='\n')) 325 last1--; 326while((*last2 =='\r') || (*last2 =='\n')) 327 last2--; 328 329/* skip leading whitespaces, if both begin with whitespace */ 330if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 331while(isspace(*s1) && (s1 <= last1)) 332 s1++; 333while(isspace(*s2) && (s2 <= last2)) 334 s2++; 335} 336/* early return if both lines are empty */ 337if((s1 > last1) && (s2 > last2)) 338return1; 339while(!result) { 340 result = *s1++ - *s2++; 341/* 342 * Skip whitespace inside. We check for whitespace on 343 * both buffers because we don't want "a b" to match 344 * "ab" 345 */ 346if(isspace(*s1) &&isspace(*s2)) { 347while(isspace(*s1) && s1 <= last1) 348 s1++; 349while(isspace(*s2) && s2 <= last2) 350 s2++; 351} 352/* 353 * If we reached the end on one side only, 354 * lines don't match 355 */ 356if( 357((s2 > last2) && (s1 <= last1)) || 358((s1 > last1) && (s2 <= last2))) 359return0; 360if((s1 > last1) && (s2 > last2)) 361break; 362} 363 364return!result; 365} 366 367static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 368{ 369ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 370 img->line_allocated[img->nr].len = len; 371 img->line_allocated[img->nr].hash =hash_line(bol, len); 372 img->line_allocated[img->nr].flag = flag; 373 img->nr++; 374} 375 376/* 377 * "buf" has the file contents to be patched (read from various sources). 378 * attach it to "image" and add line-based index to it. 379 * "image" now owns the "buf". 380 */ 381static voidprepare_image(struct image *image,char*buf,size_t len, 382int prepare_linetable) 383{ 384const char*cp, *ep; 385 386memset(image,0,sizeof(*image)); 387 image->buf = buf; 388 image->len = len; 389 390if(!prepare_linetable) 391return; 392 393 ep = image->buf + image->len; 394 cp = image->buf; 395while(cp < ep) { 396const char*next; 397for(next = cp; next < ep && *next !='\n'; next++) 398; 399if(next < ep) 400 next++; 401add_line_info(image, cp, next - cp,0); 402 cp = next; 403} 404 image->line = image->line_allocated; 405} 406 407static voidclear_image(struct image *image) 408{ 409free(image->buf); 410free(image->line_allocated); 411memset(image,0,sizeof(*image)); 412} 413 414/* fmt must contain _one_ %s and no other substitution */ 415static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 416{ 417struct strbuf sb = STRBUF_INIT; 418 419if(patch->old_name && patch->new_name && 420strcmp(patch->old_name, patch->new_name)) { 421quote_c_style(patch->old_name, &sb, NULL,0); 422strbuf_addstr(&sb," => "); 423quote_c_style(patch->new_name, &sb, NULL,0); 424}else{ 425const char*n = patch->new_name; 426if(!n) 427 n = patch->old_name; 428quote_c_style(n, &sb, NULL,0); 429} 430fprintf(output, fmt, sb.buf); 431fputc('\n', output); 432strbuf_release(&sb); 433} 434 435#define SLOP (16) 436 437static voidread_patch_file(struct strbuf *sb,int fd) 438{ 439if(strbuf_read(sb, fd,0) <0) 440die_errno("git apply: failed to read"); 441 442/* 443 * Make sure that we have some slop in the buffer 444 * so that we can do speculative "memcmp" etc, and 445 * see to it that it is NUL-filled. 446 */ 447strbuf_grow(sb, SLOP); 448memset(sb->buf + sb->len,0, SLOP); 449} 450 451static unsigned longlinelen(const char*buffer,unsigned long size) 452{ 453unsigned long len =0; 454while(size--) { 455 len++; 456if(*buffer++ =='\n') 457break; 458} 459return len; 460} 461 462static intis_dev_null(const char*str) 463{ 464returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 465} 466 467#define TERM_SPACE 1 468#define TERM_TAB 2 469 470static intname_terminate(const char*name,int namelen,int c,int terminate) 471{ 472if(c ==' '&& !(terminate & TERM_SPACE)) 473return0; 474if(c =='\t'&& !(terminate & TERM_TAB)) 475return0; 476 477return1; 478} 479 480/* remove double slashes to make --index work with such filenames */ 481static char*squash_slash(char*name) 482{ 483int i =0, j =0; 484 485if(!name) 486return NULL; 487 488while(name[i]) { 489if((name[j++] = name[i++]) =='/') 490while(name[i] =='/') 491 i++; 492} 493 name[j] ='\0'; 494return name; 495} 496 497static char*find_name_gnu(struct apply_state *state, 498const char*line, 499const char*def, 500int p_value) 501{ 502struct strbuf name = STRBUF_INIT; 503char*cp; 504 505/* 506 * Proposed "new-style" GNU patch/diff format; see 507 * http://marc.info/?l=git&m=112927316408690&w=2 508 */ 509if(unquote_c_style(&name, line, NULL)) { 510strbuf_release(&name); 511return NULL; 512} 513 514for(cp = name.buf; p_value; p_value--) { 515 cp =strchr(cp,'/'); 516if(!cp) { 517strbuf_release(&name); 518return NULL; 519} 520 cp++; 521} 522 523strbuf_remove(&name,0, cp - name.buf); 524if(state->root.len) 525strbuf_insert(&name,0, state->root.buf, state->root.len); 526returnsquash_slash(strbuf_detach(&name, NULL)); 527} 528 529static size_tsane_tz_len(const char*line,size_t len) 530{ 531const char*tz, *p; 532 533if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 534return0; 535 tz = line + len -strlen(" +0500"); 536 537if(tz[1] !='+'&& tz[1] !='-') 538return0; 539 540for(p = tz +2; p != line + len; p++) 541if(!isdigit(*p)) 542return0; 543 544return line + len - tz; 545} 546 547static size_ttz_with_colon_len(const char*line,size_t len) 548{ 549const char*tz, *p; 550 551if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 552return0; 553 tz = line + len -strlen(" +08:00"); 554 555if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 556return0; 557 p = tz +2; 558if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 559!isdigit(*p++) || !isdigit(*p++)) 560return0; 561 562return line + len - tz; 563} 564 565static size_tdate_len(const char*line,size_t len) 566{ 567const char*date, *p; 568 569if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 570return0; 571 p = date = line + len -strlen("72-02-05"); 572 573if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 574!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 575!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 576return0; 577 578if(date - line >=strlen("19") && 579isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 580 date -=strlen("19"); 581 582return line + len - date; 583} 584 585static size_tshort_time_len(const char*line,size_t len) 586{ 587const char*time, *p; 588 589if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 590return0; 591 p = time = line + len -strlen(" 07:01:32"); 592 593/* Permit 1-digit hours? */ 594if(*p++ !=' '|| 595!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 596!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 597!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 598return0; 599 600return line + len - time; 601} 602 603static size_tfractional_time_len(const char*line,size_t len) 604{ 605const char*p; 606size_t n; 607 608/* Expected format: 19:41:17.620000023 */ 609if(!len || !isdigit(line[len -1])) 610return0; 611 p = line + len -1; 612 613/* Fractional seconds. */ 614while(p > line &&isdigit(*p)) 615 p--; 616if(*p !='.') 617return0; 618 619/* Hours, minutes, and whole seconds. */ 620 n =short_time_len(line, p - line); 621if(!n) 622return0; 623 624return line + len - p + n; 625} 626 627static size_ttrailing_spaces_len(const char*line,size_t len) 628{ 629const char*p; 630 631/* Expected format: ' ' x (1 or more) */ 632if(!len || line[len -1] !=' ') 633return0; 634 635 p = line + len; 636while(p != line) { 637 p--; 638if(*p !=' ') 639return line + len - (p +1); 640} 641 642/* All spaces! */ 643return len; 644} 645 646static size_tdiff_timestamp_len(const char*line,size_t len) 647{ 648const char*end = line + len; 649size_t n; 650 651/* 652 * Posix: 2010-07-05 19:41:17 653 * GNU: 2010-07-05 19:41:17.620000023 -0500 654 */ 655 656if(!isdigit(end[-1])) 657return0; 658 659 n =sane_tz_len(line, end - line); 660if(!n) 661 n =tz_with_colon_len(line, end - line); 662 end -= n; 663 664 n =short_time_len(line, end - line); 665if(!n) 666 n =fractional_time_len(line, end - line); 667 end -= n; 668 669 n =date_len(line, end - line); 670if(!n)/* No date. Too bad. */ 671return0; 672 end -= n; 673 674if(end == line)/* No space before date. */ 675return0; 676if(end[-1] =='\t') {/* Success! */ 677 end--; 678return line + len - end; 679} 680if(end[-1] !=' ')/* No space before date. */ 681return0; 682 683/* Whitespace damage. */ 684 end -=trailing_spaces_len(line, end - line); 685return line + len - end; 686} 687 688static char*find_name_common(struct apply_state *state, 689const char*line, 690const char*def, 691int p_value, 692const char*end, 693int terminate) 694{ 695int len; 696const char*start = NULL; 697 698if(p_value ==0) 699 start = line; 700while(line != end) { 701char c = *line; 702 703if(!end &&isspace(c)) { 704if(c =='\n') 705break; 706if(name_terminate(start, line-start, c, terminate)) 707break; 708} 709 line++; 710if(c =='/'&& !--p_value) 711 start = line; 712} 713if(!start) 714returnsquash_slash(xstrdup_or_null(def)); 715 len = line - start; 716if(!len) 717returnsquash_slash(xstrdup_or_null(def)); 718 719/* 720 * Generally we prefer the shorter name, especially 721 * if the other one is just a variation of that with 722 * something else tacked on to the end (ie "file.orig" 723 * or "file~"). 724 */ 725if(def) { 726int deflen =strlen(def); 727if(deflen < len && !strncmp(start, def, deflen)) 728returnsquash_slash(xstrdup(def)); 729} 730 731if(state->root.len) { 732char*ret =xstrfmt("%s%.*s", state->root.buf, len, start); 733returnsquash_slash(ret); 734} 735 736returnsquash_slash(xmemdupz(start, len)); 737} 738 739static char*find_name(struct apply_state *state, 740const char*line, 741char*def, 742int p_value, 743int terminate) 744{ 745if(*line =='"') { 746char*name =find_name_gnu(state, line, def, p_value); 747if(name) 748return name; 749} 750 751returnfind_name_common(state, line, def, p_value, NULL, terminate); 752} 753 754static char*find_name_traditional(struct apply_state *state, 755const char*line, 756char*def, 757int p_value) 758{ 759size_t len; 760size_t date_len; 761 762if(*line =='"') { 763char*name =find_name_gnu(state, line, def, p_value); 764if(name) 765return name; 766} 767 768 len =strchrnul(line,'\n') - line; 769 date_len =diff_timestamp_len(line, len); 770if(!date_len) 771returnfind_name_common(state, line, def, p_value, NULL, TERM_TAB); 772 len -= date_len; 773 774returnfind_name_common(state, line, def, p_value, line + len,0); 775} 776 777static intcount_slashes(const char*cp) 778{ 779int cnt =0; 780char ch; 781 782while((ch = *cp++)) 783if(ch =='/') 784 cnt++; 785return cnt; 786} 787 788/* 789 * Given the string after "--- " or "+++ ", guess the appropriate 790 * p_value for the given patch. 791 */ 792static intguess_p_value(struct apply_state *state,const char*nameline) 793{ 794char*name, *cp; 795int val = -1; 796 797if(is_dev_null(nameline)) 798return-1; 799 name =find_name_traditional(state, nameline, NULL,0); 800if(!name) 801return-1; 802 cp =strchr(name,'/'); 803if(!cp) 804 val =0; 805else if(state->prefix) { 806/* 807 * Does it begin with "a/$our-prefix" and such? Then this is 808 * very likely to apply to our directory. 809 */ 810if(!strncmp(name, state->prefix, state->prefix_length)) 811 val =count_slashes(state->prefix); 812else{ 813 cp++; 814if(!strncmp(cp, state->prefix, state->prefix_length)) 815 val =count_slashes(state->prefix) +1; 816} 817} 818free(name); 819return val; 820} 821 822/* 823 * Does the ---/+++ line have the POSIX timestamp after the last HT? 824 * GNU diff puts epoch there to signal a creation/deletion event. Is 825 * this such a timestamp? 826 */ 827static inthas_epoch_timestamp(const char*nameline) 828{ 829/* 830 * We are only interested in epoch timestamp; any non-zero 831 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 832 * For the same reason, the date must be either 1969-12-31 or 833 * 1970-01-01, and the seconds part must be "00". 834 */ 835const char stamp_regexp[] = 836"^(1969-12-31|1970-01-01)" 837" " 838"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 839" " 840"([-+][0-2][0-9]:?[0-5][0-9])\n"; 841const char*timestamp = NULL, *cp, *colon; 842static regex_t *stamp; 843 regmatch_t m[10]; 844int zoneoffset; 845int hourminute; 846int status; 847 848for(cp = nameline; *cp !='\n'; cp++) { 849if(*cp =='\t') 850 timestamp = cp +1; 851} 852if(!timestamp) 853return0; 854if(!stamp) { 855 stamp =xmalloc(sizeof(*stamp)); 856if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 857warning(_("Cannot prepare timestamp regexp%s"), 858 stamp_regexp); 859return0; 860} 861} 862 863 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 864if(status) { 865if(status != REG_NOMATCH) 866warning(_("regexec returned%dfor input:%s"), 867 status, timestamp); 868return0; 869} 870 871 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 872if(*colon ==':') 873 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 874else 875 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 876if(timestamp[m[3].rm_so] =='-') 877 zoneoffset = -zoneoffset; 878 879/* 880 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 881 * (west of GMT) or 1970-01-01 (east of GMT) 882 */ 883if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 884(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 885return0; 886 887 hourminute = (strtol(timestamp +11, NULL,10) *60+ 888strtol(timestamp +14, NULL,10) - 889 zoneoffset); 890 891return((zoneoffset <0&& hourminute ==1440) || 892(0<= zoneoffset && !hourminute)); 893} 894 895/* 896 * Get the name etc info from the ---/+++ lines of a traditional patch header 897 * 898 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 899 * files, we can happily check the index for a match, but for creating a 900 * new file we should try to match whatever "patch" does. I have no idea. 901 */ 902static voidparse_traditional_patch(struct apply_state *state, 903const char*first, 904const char*second, 905struct patch *patch) 906{ 907char*name; 908 909 first +=4;/* skip "--- " */ 910 second +=4;/* skip "+++ " */ 911if(!state->p_value_known) { 912int p, q; 913 p =guess_p_value(state, first); 914 q =guess_p_value(state, second); 915if(p <0) p = q; 916if(0<= p && p == q) { 917 state->p_value = p; 918 state->p_value_known =1; 919} 920} 921if(is_dev_null(first)) { 922 patch->is_new =1; 923 patch->is_delete =0; 924 name =find_name_traditional(state, second, NULL, state->p_value); 925 patch->new_name = name; 926}else if(is_dev_null(second)) { 927 patch->is_new =0; 928 patch->is_delete =1; 929 name =find_name_traditional(state, first, NULL, state->p_value); 930 patch->old_name = name; 931}else{ 932char*first_name; 933 first_name =find_name_traditional(state, first, NULL, state->p_value); 934 name =find_name_traditional(state, second, first_name, state->p_value); 935free(first_name); 936if(has_epoch_timestamp(first)) { 937 patch->is_new =1; 938 patch->is_delete =0; 939 patch->new_name = name; 940}else if(has_epoch_timestamp(second)) { 941 patch->is_new =0; 942 patch->is_delete =1; 943 patch->old_name = name; 944}else{ 945 patch->old_name = name; 946 patch->new_name =xstrdup_or_null(name); 947} 948} 949if(!name) 950die(_("unable to find filename in patch at line%d"), state->linenr); 951} 952 953static intgitdiff_hdrend(struct apply_state *state, 954const char*line, 955struct patch *patch) 956{ 957return-1; 958} 959 960/* 961 * We're anal about diff header consistency, to make 962 * sure that we don't end up having strange ambiguous 963 * patches floating around. 964 * 965 * As a result, gitdiff_{old|new}name() will check 966 * their names against any previous information, just 967 * to make sure.. 968 */ 969#define DIFF_OLD_NAME 0 970#define DIFF_NEW_NAME 1 971 972static voidgitdiff_verify_name(struct apply_state *state, 973const char*line, 974int isnull, 975char**name, 976int side) 977{ 978if(!*name && !isnull) { 979*name =find_name(state, line, NULL, state->p_value, TERM_TAB); 980return; 981} 982 983if(*name) { 984int len =strlen(*name); 985char*another; 986if(isnull) 987die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 988*name, state->linenr); 989 another =find_name(state, line, NULL, state->p_value, TERM_TAB); 990if(!another ||memcmp(another, *name, len +1)) 991die((side == DIFF_NEW_NAME) ? 992_("git apply: bad git-diff - inconsistent new filename on line%d") : 993_("git apply: bad git-diff - inconsistent old filename on line%d"), state->linenr); 994free(another); 995}else{ 996/* expect "/dev/null" */ 997if(memcmp("/dev/null", line,9) || line[9] !='\n') 998die(_("git apply: bad git-diff - expected /dev/null on line%d"), state->linenr); 999}1000}10011002static intgitdiff_oldname(struct apply_state *state,1003const char*line,1004struct patch *patch)1005{1006gitdiff_verify_name(state, line,1007 patch->is_new, &patch->old_name,1008 DIFF_OLD_NAME);1009return0;1010}10111012static intgitdiff_newname(struct apply_state *state,1013const char*line,1014struct patch *patch)1015{1016gitdiff_verify_name(state, line,1017 patch->is_delete, &patch->new_name,1018 DIFF_NEW_NAME);1019return0;1020}10211022static intgitdiff_oldmode(struct apply_state *state,1023const char*line,1024struct patch *patch)1025{1026 patch->old_mode =strtoul(line, NULL,8);1027return0;1028}10291030static intgitdiff_newmode(struct apply_state *state,1031const char*line,1032struct patch *patch)1033{1034 patch->new_mode =strtoul(line, NULL,8);1035return0;1036}10371038static intgitdiff_delete(struct apply_state *state,1039const char*line,1040struct patch *patch)1041{1042 patch->is_delete =1;1043free(patch->old_name);1044 patch->old_name =xstrdup_or_null(patch->def_name);1045returngitdiff_oldmode(state, line, patch);1046}10471048static intgitdiff_newfile(struct apply_state *state,1049const char*line,1050struct patch *patch)1051{1052 patch->is_new =1;1053free(patch->new_name);1054 patch->new_name =xstrdup_or_null(patch->def_name);1055returngitdiff_newmode(state, line, patch);1056}10571058static intgitdiff_copysrc(struct apply_state *state,1059const char*line,1060struct patch *patch)1061{1062 patch->is_copy =1;1063free(patch->old_name);1064 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1065return0;1066}10671068static intgitdiff_copydst(struct apply_state *state,1069const char*line,1070struct patch *patch)1071{1072 patch->is_copy =1;1073free(patch->new_name);1074 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1075return0;1076}10771078static intgitdiff_renamesrc(struct apply_state *state,1079const char*line,1080struct patch *patch)1081{1082 patch->is_rename =1;1083free(patch->old_name);1084 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1085return0;1086}10871088static intgitdiff_renamedst(struct apply_state *state,1089const char*line,1090struct patch *patch)1091{1092 patch->is_rename =1;1093free(patch->new_name);1094 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1095return0;1096}10971098static intgitdiff_similarity(struct apply_state *state,1099const char*line,1100struct patch *patch)1101{1102unsigned long val =strtoul(line, NULL,10);1103if(val <=100)1104 patch->score = val;1105return0;1106}11071108static intgitdiff_dissimilarity(struct apply_state *state,1109const char*line,1110struct patch *patch)1111{1112unsigned long val =strtoul(line, NULL,10);1113if(val <=100)1114 patch->score = val;1115return0;1116}11171118static intgitdiff_index(struct apply_state *state,1119const char*line,1120struct patch *patch)1121{1122/*1123 * index line is N hexadecimal, "..", N hexadecimal,1124 * and optional space with octal mode.1125 */1126const char*ptr, *eol;1127int len;11281129 ptr =strchr(line,'.');1130if(!ptr || ptr[1] !='.'||40< ptr - line)1131return0;1132 len = ptr - line;1133memcpy(patch->old_sha1_prefix, line, len);1134 patch->old_sha1_prefix[len] =0;11351136 line = ptr +2;1137 ptr =strchr(line,' ');1138 eol =strchrnul(line,'\n');11391140if(!ptr || eol < ptr)1141 ptr = eol;1142 len = ptr - line;11431144if(40< len)1145return0;1146memcpy(patch->new_sha1_prefix, line, len);1147 patch->new_sha1_prefix[len] =0;1148if(*ptr ==' ')1149 patch->old_mode =strtoul(ptr+1, NULL,8);1150return0;1151}11521153/*1154 * This is normal for a diff that doesn't change anything: we'll fall through1155 * into the next diff. Tell the parser to break out.1156 */1157static intgitdiff_unrecognized(struct apply_state *state,1158const char*line,1159struct patch *patch)1160{1161return-1;1162}11631164/*1165 * Skip p_value leading components from "line"; as we do not accept1166 * absolute paths, return NULL in that case.1167 */1168static const char*skip_tree_prefix(struct apply_state *state,1169const char*line,1170int llen)1171{1172int nslash;1173int i;11741175if(!state->p_value)1176return(llen && line[0] =='/') ? NULL : line;11771178 nslash = state->p_value;1179for(i =0; i < llen; i++) {1180int ch = line[i];1181if(ch =='/'&& --nslash <=0)1182return(i ==0) ? NULL : &line[i +1];1183}1184return NULL;1185}11861187/*1188 * This is to extract the same name that appears on "diff --git"1189 * line. We do not find and return anything if it is a rename1190 * patch, and it is OK because we will find the name elsewhere.1191 * We need to reliably find name only when it is mode-change only,1192 * creation or deletion of an empty file. In any of these cases,1193 * both sides are the same name under a/ and b/ respectively.1194 */1195static char*git_header_name(struct apply_state *state,1196const char*line,1197int llen)1198{1199const char*name;1200const char*second = NULL;1201size_t len, line_len;12021203 line +=strlen("diff --git ");1204 llen -=strlen("diff --git ");12051206if(*line =='"') {1207const char*cp;1208struct strbuf first = STRBUF_INIT;1209struct strbuf sp = STRBUF_INIT;12101211if(unquote_c_style(&first, line, &second))1212goto free_and_fail1;12131214/* strip the a/b prefix including trailing slash */1215 cp =skip_tree_prefix(state, first.buf, first.len);1216if(!cp)1217goto free_and_fail1;1218strbuf_remove(&first,0, cp - first.buf);12191220/*1221 * second points at one past closing dq of name.1222 * find the second name.1223 */1224while((second < line + llen) &&isspace(*second))1225 second++;12261227if(line + llen <= second)1228goto free_and_fail1;1229if(*second =='"') {1230if(unquote_c_style(&sp, second, NULL))1231goto free_and_fail1;1232 cp =skip_tree_prefix(state, sp.buf, sp.len);1233if(!cp)1234goto free_and_fail1;1235/* They must match, otherwise ignore */1236if(strcmp(cp, first.buf))1237goto free_and_fail1;1238strbuf_release(&sp);1239returnstrbuf_detach(&first, NULL);1240}12411242/* unquoted second */1243 cp =skip_tree_prefix(state, second, line + llen - second);1244if(!cp)1245goto free_and_fail1;1246if(line + llen - cp != first.len ||1247memcmp(first.buf, cp, first.len))1248goto free_and_fail1;1249returnstrbuf_detach(&first, NULL);12501251 free_and_fail1:1252strbuf_release(&first);1253strbuf_release(&sp);1254return NULL;1255}12561257/* unquoted first name */1258 name =skip_tree_prefix(state, line, llen);1259if(!name)1260return NULL;12611262/*1263 * since the first name is unquoted, a dq if exists must be1264 * the beginning of the second name.1265 */1266for(second = name; second < line + llen; second++) {1267if(*second =='"') {1268struct strbuf sp = STRBUF_INIT;1269const char*np;12701271if(unquote_c_style(&sp, second, NULL))1272goto free_and_fail2;12731274 np =skip_tree_prefix(state, sp.buf, sp.len);1275if(!np)1276goto free_and_fail2;12771278 len = sp.buf + sp.len - np;1279if(len < second - name &&1280!strncmp(np, name, len) &&1281isspace(name[len])) {1282/* Good */1283strbuf_remove(&sp,0, np - sp.buf);1284returnstrbuf_detach(&sp, NULL);1285}12861287 free_and_fail2:1288strbuf_release(&sp);1289return NULL;1290}1291}12921293/*1294 * Accept a name only if it shows up twice, exactly the same1295 * form.1296 */1297 second =strchr(name,'\n');1298if(!second)1299return NULL;1300 line_len = second - name;1301for(len =0; ; len++) {1302switch(name[len]) {1303default:1304continue;1305case'\n':1306return NULL;1307case'\t':case' ':1308/*1309 * Is this the separator between the preimage1310 * and the postimage pathname? Again, we are1311 * only interested in the case where there is1312 * no rename, as this is only to set def_name1313 * and a rename patch has the names elsewhere1314 * in an unambiguous form.1315 */1316if(!name[len +1])1317return NULL;/* no postimage name */1318 second =skip_tree_prefix(state, name + len +1,1319 line_len - (len +1));1320if(!second)1321return NULL;1322/*1323 * Does len bytes starting at "name" and "second"1324 * (that are separated by one HT or SP we just1325 * found) exactly match?1326 */1327if(second[len] =='\n'&& !strncmp(name, second, len))1328returnxmemdupz(name, len);1329}1330}1331}13321333/* Verify that we recognize the lines following a git header */1334static intparse_git_header(struct apply_state *state,1335const char*line,1336int len,1337unsigned int size,1338struct patch *patch)1339{1340unsigned long offset;13411342/* A git diff has explicit new/delete information, so we don't guess */1343 patch->is_new =0;1344 patch->is_delete =0;13451346/*1347 * Some things may not have the old name in the1348 * rest of the headers anywhere (pure mode changes,1349 * or removing or adding empty files), so we get1350 * the default name from the header.1351 */1352 patch->def_name =git_header_name(state, line, len);1353if(patch->def_name && state->root.len) {1354char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1355free(patch->def_name);1356 patch->def_name = s;1357}13581359 line += len;1360 size -= len;1361 state->linenr++;1362for(offset = len ; size >0; offset += len, size -= len, line += len, state->linenr++) {1363static const struct opentry {1364const char*str;1365int(*fn)(struct apply_state *,const char*,struct patch *);1366} optable[] = {1367{"@@ -", gitdiff_hdrend },1368{"--- ", gitdiff_oldname },1369{"+++ ", gitdiff_newname },1370{"old mode ", gitdiff_oldmode },1371{"new mode ", gitdiff_newmode },1372{"deleted file mode ", gitdiff_delete },1373{"new file mode ", gitdiff_newfile },1374{"copy from ", gitdiff_copysrc },1375{"copy to ", gitdiff_copydst },1376{"rename old ", gitdiff_renamesrc },1377{"rename new ", gitdiff_renamedst },1378{"rename from ", gitdiff_renamesrc },1379{"rename to ", gitdiff_renamedst },1380{"similarity index ", gitdiff_similarity },1381{"dissimilarity index ", gitdiff_dissimilarity },1382{"index ", gitdiff_index },1383{"", gitdiff_unrecognized },1384};1385int i;13861387 len =linelen(line, size);1388if(!len || line[len-1] !='\n')1389break;1390for(i =0; i <ARRAY_SIZE(optable); i++) {1391const struct opentry *p = optable + i;1392int oplen =strlen(p->str);1393if(len < oplen ||memcmp(p->str, line, oplen))1394continue;1395if(p->fn(state, line + oplen, patch) <0)1396return offset;1397break;1398}1399}14001401return offset;1402}14031404static intparse_num(const char*line,unsigned long*p)1405{1406char*ptr;14071408if(!isdigit(*line))1409return0;1410*p =strtoul(line, &ptr,10);1411return ptr - line;1412}14131414static intparse_range(const char*line,int len,int offset,const char*expect,1415unsigned long*p1,unsigned long*p2)1416{1417int digits, ex;14181419if(offset <0|| offset >= len)1420return-1;1421 line += offset;1422 len -= offset;14231424 digits =parse_num(line, p1);1425if(!digits)1426return-1;14271428 offset += digits;1429 line += digits;1430 len -= digits;14311432*p2 =1;1433if(*line ==',') {1434 digits =parse_num(line+1, p2);1435if(!digits)1436return-1;14371438 offset += digits+1;1439 line += digits+1;1440 len -= digits+1;1441}14421443 ex =strlen(expect);1444if(ex > len)1445return-1;1446if(memcmp(line, expect, ex))1447return-1;14481449return offset + ex;1450}14511452static voidrecount_diff(const char*line,int size,struct fragment *fragment)1453{1454int oldlines =0, newlines =0, ret =0;14551456if(size <1) {1457warning("recount: ignore empty hunk");1458return;1459}14601461for(;;) {1462int len =linelen(line, size);1463 size -= len;1464 line += len;14651466if(size <1)1467break;14681469switch(*line) {1470case' ':case'\n':1471 newlines++;1472/* fall through */1473case'-':1474 oldlines++;1475continue;1476case'+':1477 newlines++;1478continue;1479case'\\':1480continue;1481case'@':1482 ret = size <3|| !starts_with(line,"@@ ");1483break;1484case'd':1485 ret = size <5|| !starts_with(line,"diff ");1486break;1487default:1488 ret = -1;1489break;1490}1491if(ret) {1492warning(_("recount: unexpected line: %.*s"),1493(int)linelen(line, size), line);1494return;1495}1496break;1497}1498 fragment->oldlines = oldlines;1499 fragment->newlines = newlines;1500}15011502/*1503 * Parse a unified diff fragment header of the1504 * form "@@ -a,b +c,d @@"1505 */1506static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1507{1508int offset;15091510if(!len || line[len-1] !='\n')1511return-1;15121513/* Figure out the number of lines in a fragment */1514 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1515 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);15161517return offset;1518}15191520static intfind_header(struct apply_state *state,1521const char*line,1522unsigned long size,1523int*hdrsize,1524struct patch *patch)1525{1526unsigned long offset, len;15271528 patch->is_toplevel_relative =0;1529 patch->is_rename = patch->is_copy =0;1530 patch->is_new = patch->is_delete = -1;1531 patch->old_mode = patch->new_mode =0;1532 patch->old_name = patch->new_name = NULL;1533for(offset =0; size >0; offset += len, size -= len, line += len, state->linenr++) {1534unsigned long nextlen;15351536 len =linelen(line, size);1537if(!len)1538break;15391540/* Testing this early allows us to take a few shortcuts.. */1541if(len <6)1542continue;15431544/*1545 * Make sure we don't find any unconnected patch fragments.1546 * That's a sign that we didn't find a header, and that a1547 * patch has become corrupted/broken up.1548 */1549if(!memcmp("@@ -", line,4)) {1550struct fragment dummy;1551if(parse_fragment_header(line, len, &dummy) <0)1552continue;1553die(_("patch fragment without header at line%d: %.*s"),1554 state->linenr, (int)len-1, line);1555}15561557if(size < len +6)1558break;15591560/*1561 * Git patch? It might not have a real patch, just a rename1562 * or mode change, so we handle that specially1563 */1564if(!memcmp("diff --git ", line,11)) {1565int git_hdr_len =parse_git_header(state, line, len, size, patch);1566if(git_hdr_len <= len)1567continue;1568if(!patch->old_name && !patch->new_name) {1569if(!patch->def_name)1570die(Q_("git diff header lacks filename information when removing "1571"%dleading pathname component (line%d)",1572"git diff header lacks filename information when removing "1573"%dleading pathname components (line%d)",1574 state->p_value),1575 state->p_value, state->linenr);1576 patch->old_name =xstrdup(patch->def_name);1577 patch->new_name =xstrdup(patch->def_name);1578}1579if(!patch->is_delete && !patch->new_name)1580die("git diff header lacks filename information "1581"(line%d)", state->linenr);1582 patch->is_toplevel_relative =1;1583*hdrsize = git_hdr_len;1584return offset;1585}15861587/* --- followed by +++ ? */1588if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1589continue;15901591/*1592 * We only accept unified patches, so we want it to1593 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1594 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1595 */1596 nextlen =linelen(line + len, size - len);1597if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1598continue;15991600/* Ok, we'll consider it a patch */1601parse_traditional_patch(state, line, line+len, patch);1602*hdrsize = len + nextlen;1603 state->linenr +=2;1604return offset;1605}1606return-1;1607}16081609static voidrecord_ws_error(struct apply_state *state,1610unsigned result,1611const char*line,1612int len,1613int linenr)1614{1615char*err;16161617if(!result)1618return;16191620 state->whitespace_error++;1621if(state->squelch_whitespace_errors &&1622 state->squelch_whitespace_errors < state->whitespace_error)1623return;16241625 err =whitespace_error_string(result);1626fprintf(stderr,"%s:%d:%s.\n%.*s\n",1627 state->patch_input_file, linenr, err, len, line);1628free(err);1629}16301631static voidcheck_whitespace(struct apply_state *state,1632const char*line,1633int len,1634unsigned ws_rule)1635{1636unsigned result =ws_check(line +1, len -1, ws_rule);16371638record_ws_error(state, result, line +1, len -2, state->linenr);1639}16401641/*1642 * Parse a unified diff. Note that this really needs to parse each1643 * fragment separately, since the only way to know the difference1644 * between a "---" that is part of a patch, and a "---" that starts1645 * the next patch is to look at the line counts..1646 */1647static intparse_fragment(struct apply_state *state,1648const char*line,1649unsigned long size,1650struct patch *patch,1651struct fragment *fragment)1652{1653int added, deleted;1654int len =linelen(line, size), offset;1655unsigned long oldlines, newlines;1656unsigned long leading, trailing;16571658 offset =parse_fragment_header(line, len, fragment);1659if(offset <0)1660return-1;1661if(offset >0&& patch->recount)1662recount_diff(line + offset, size - offset, fragment);1663 oldlines = fragment->oldlines;1664 newlines = fragment->newlines;1665 leading =0;1666 trailing =0;16671668/* Parse the thing.. */1669 line += len;1670 size -= len;1671 state->linenr++;1672 added = deleted =0;1673for(offset = len;16740< size;1675 offset += len, size -= len, line += len, state->linenr++) {1676if(!oldlines && !newlines)1677break;1678 len =linelen(line, size);1679if(!len || line[len-1] !='\n')1680return-1;1681switch(*line) {1682default:1683return-1;1684case'\n':/* newer GNU diff, an empty context line */1685case' ':1686 oldlines--;1687 newlines--;1688if(!deleted && !added)1689 leading++;1690 trailing++;1691if(!state->apply_in_reverse &&1692 state->ws_error_action == correct_ws_error)1693check_whitespace(state, line, len, patch->ws_rule);1694break;1695case'-':1696if(state->apply_in_reverse &&1697 state->ws_error_action != nowarn_ws_error)1698check_whitespace(state, line, len, patch->ws_rule);1699 deleted++;1700 oldlines--;1701 trailing =0;1702break;1703case'+':1704if(!state->apply_in_reverse &&1705 state->ws_error_action != nowarn_ws_error)1706check_whitespace(state, line, len, patch->ws_rule);1707 added++;1708 newlines--;1709 trailing =0;1710break;17111712/*1713 * We allow "\ No newline at end of file". Depending1714 * on locale settings when the patch was produced we1715 * don't know what this line looks like. The only1716 * thing we do know is that it begins with "\ ".1717 * Checking for 12 is just for sanity check -- any1718 * l10n of "\ No newline..." is at least that long.1719 */1720case'\\':1721if(len <12||memcmp(line,"\\",2))1722return-1;1723break;1724}1725}1726if(oldlines || newlines)1727return-1;1728if(!deleted && !added)1729return-1;17301731 fragment->leading = leading;1732 fragment->trailing = trailing;17331734/*1735 * If a fragment ends with an incomplete line, we failed to include1736 * it in the above loop because we hit oldlines == newlines == 01737 * before seeing it.1738 */1739if(12< size && !memcmp(line,"\\",2))1740 offset +=linelen(line, size);17411742 patch->lines_added += added;1743 patch->lines_deleted += deleted;17441745if(0< patch->is_new && oldlines)1746returnerror(_("new file depends on old contents"));1747if(0< patch->is_delete && newlines)1748returnerror(_("deleted file still has contents"));1749return offset;1750}17511752/*1753 * We have seen "diff --git a/... b/..." header (or a traditional patch1754 * header). Read hunks that belong to this patch into fragments and hang1755 * them to the given patch structure.1756 *1757 * The (fragment->patch, fragment->size) pair points into the memory given1758 * by the caller, not a copy, when we return.1759 */1760static intparse_single_patch(struct apply_state *state,1761const char*line,1762unsigned long size,1763struct patch *patch)1764{1765unsigned long offset =0;1766unsigned long oldlines =0, newlines =0, context =0;1767struct fragment **fragp = &patch->fragments;17681769while(size >4&& !memcmp(line,"@@ -",4)) {1770struct fragment *fragment;1771int len;17721773 fragment =xcalloc(1,sizeof(*fragment));1774 fragment->linenr = state->linenr;1775 len =parse_fragment(state, line, size, patch, fragment);1776if(len <=0)1777die(_("corrupt patch at line%d"), state->linenr);1778 fragment->patch = line;1779 fragment->size = len;1780 oldlines += fragment->oldlines;1781 newlines += fragment->newlines;1782 context += fragment->leading + fragment->trailing;17831784*fragp = fragment;1785 fragp = &fragment->next;17861787 offset += len;1788 line += len;1789 size -= len;1790}17911792/*1793 * If something was removed (i.e. we have old-lines) it cannot1794 * be creation, and if something was added it cannot be1795 * deletion. However, the reverse is not true; --unified=01796 * patches that only add are not necessarily creation even1797 * though they do not have any old lines, and ones that only1798 * delete are not necessarily deletion.1799 *1800 * Unfortunately, a real creation/deletion patch do _not_ have1801 * any context line by definition, so we cannot safely tell it1802 * apart with --unified=0 insanity. At least if the patch has1803 * more than one hunk it is not creation or deletion.1804 */1805if(patch->is_new <0&&1806(oldlines || (patch->fragments && patch->fragments->next)))1807 patch->is_new =0;1808if(patch->is_delete <0&&1809(newlines || (patch->fragments && patch->fragments->next)))1810 patch->is_delete =0;18111812if(0< patch->is_new && oldlines)1813die(_("new file%sdepends on old contents"), patch->new_name);1814if(0< patch->is_delete && newlines)1815die(_("deleted file%sstill has contents"), patch->old_name);1816if(!patch->is_delete && !newlines && context)1817fprintf_ln(stderr,1818_("** warning: "1819"file%sbecomes empty but is not deleted"),1820 patch->new_name);18211822return offset;1823}18241825staticinlineintmetadata_changes(struct patch *patch)1826{1827return patch->is_rename >0||1828 patch->is_copy >0||1829 patch->is_new >0||1830 patch->is_delete ||1831(patch->old_mode && patch->new_mode &&1832 patch->old_mode != patch->new_mode);1833}18341835static char*inflate_it(const void*data,unsigned long size,1836unsigned long inflated_size)1837{1838 git_zstream stream;1839void*out;1840int st;18411842memset(&stream,0,sizeof(stream));18431844 stream.next_in = (unsigned char*)data;1845 stream.avail_in = size;1846 stream.next_out = out =xmalloc(inflated_size);1847 stream.avail_out = inflated_size;1848git_inflate_init(&stream);1849 st =git_inflate(&stream, Z_FINISH);1850git_inflate_end(&stream);1851if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1852free(out);1853return NULL;1854}1855return out;1856}18571858/*1859 * Read a binary hunk and return a new fragment; fragment->patch1860 * points at an allocated memory that the caller must free, so1861 * it is marked as "->free_patch = 1".1862 */1863static struct fragment *parse_binary_hunk(struct apply_state *state,1864char**buf_p,1865unsigned long*sz_p,1866int*status_p,1867int*used_p)1868{1869/*1870 * Expect a line that begins with binary patch method ("literal"1871 * or "delta"), followed by the length of data before deflating.1872 * a sequence of 'length-byte' followed by base-85 encoded data1873 * should follow, terminated by a newline.1874 *1875 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1876 * and we would limit the patch line to 66 characters,1877 * so one line can fit up to 13 groups that would decode1878 * to 52 bytes max. The length byte 'A'-'Z' corresponds1879 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1880 */1881int llen, used;1882unsigned long size = *sz_p;1883char*buffer = *buf_p;1884int patch_method;1885unsigned long origlen;1886char*data = NULL;1887int hunk_size =0;1888struct fragment *frag;18891890 llen =linelen(buffer, size);1891 used = llen;18921893*status_p =0;18941895if(starts_with(buffer,"delta ")) {1896 patch_method = BINARY_DELTA_DEFLATED;1897 origlen =strtoul(buffer +6, NULL,10);1898}1899else if(starts_with(buffer,"literal ")) {1900 patch_method = BINARY_LITERAL_DEFLATED;1901 origlen =strtoul(buffer +8, NULL,10);1902}1903else1904return NULL;19051906 state->linenr++;1907 buffer += llen;1908while(1) {1909int byte_length, max_byte_length, newsize;1910 llen =linelen(buffer, size);1911 used += llen;1912 state->linenr++;1913if(llen ==1) {1914/* consume the blank line */1915 buffer++;1916 size--;1917break;1918}1919/*1920 * Minimum line is "A00000\n" which is 7-byte long,1921 * and the line length must be multiple of 5 plus 2.1922 */1923if((llen <7) || (llen-2) %5)1924goto corrupt;1925 max_byte_length = (llen -2) /5*4;1926 byte_length = *buffer;1927if('A'<= byte_length && byte_length <='Z')1928 byte_length = byte_length -'A'+1;1929else if('a'<= byte_length && byte_length <='z')1930 byte_length = byte_length -'a'+27;1931else1932goto corrupt;1933/* if the input length was not multiple of 4, we would1934 * have filler at the end but the filler should never1935 * exceed 3 bytes1936 */1937if(max_byte_length < byte_length ||1938 byte_length <= max_byte_length -4)1939goto corrupt;1940 newsize = hunk_size + byte_length;1941 data =xrealloc(data, newsize);1942if(decode_85(data + hunk_size, buffer +1, byte_length))1943goto corrupt;1944 hunk_size = newsize;1945 buffer += llen;1946 size -= llen;1947}19481949 frag =xcalloc(1,sizeof(*frag));1950 frag->patch =inflate_it(data, hunk_size, origlen);1951 frag->free_patch =1;1952if(!frag->patch)1953goto corrupt;1954free(data);1955 frag->size = origlen;1956*buf_p = buffer;1957*sz_p = size;1958*used_p = used;1959 frag->binary_patch_method = patch_method;1960return frag;19611962 corrupt:1963free(data);1964*status_p = -1;1965error(_("corrupt binary patch at line%d: %.*s"),1966 state->linenr-1, llen-1, buffer);1967return NULL;1968}19691970/*1971 * Returns:1972 * -1 in case of error,1973 * the length of the parsed binary patch otherwise1974 */1975static intparse_binary(struct apply_state *state,1976char*buffer,1977unsigned long size,1978struct patch *patch)1979{1980/*1981 * We have read "GIT binary patch\n"; what follows is a line1982 * that says the patch method (currently, either "literal" or1983 * "delta") and the length of data before deflating; a1984 * sequence of 'length-byte' followed by base-85 encoded data1985 * follows.1986 *1987 * When a binary patch is reversible, there is another binary1988 * hunk in the same format, starting with patch method (either1989 * "literal" or "delta") with the length of data, and a sequence1990 * of length-byte + base-85 encoded data, terminated with another1991 * empty line. This data, when applied to the postimage, produces1992 * the preimage.1993 */1994struct fragment *forward;1995struct fragment *reverse;1996int status;1997int used, used_1;19981999 forward =parse_binary_hunk(state, &buffer, &size, &status, &used);2000if(!forward && !status)2001/* there has to be one hunk (forward hunk) */2002returnerror(_("unrecognized binary patch at line%d"), state->linenr-1);2003if(status)2004/* otherwise we already gave an error message */2005return status;20062007 reverse =parse_binary_hunk(state, &buffer, &size, &status, &used_1);2008if(reverse)2009 used += used_1;2010else if(status) {2011/*2012 * Not having reverse hunk is not an error, but having2013 * a corrupt reverse hunk is.2014 */2015free((void*) forward->patch);2016free(forward);2017return status;2018}2019 forward->next = reverse;2020 patch->fragments = forward;2021 patch->is_binary =1;2022return used;2023}20242025static voidprefix_one(struct apply_state *state,char**name)2026{2027char*old_name = *name;2028if(!old_name)2029return;2030*name =xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));2031free(old_name);2032}20332034static voidprefix_patch(struct apply_state *state,struct patch *p)2035{2036if(!state->prefix || p->is_toplevel_relative)2037return;2038prefix_one(state, &p->new_name);2039prefix_one(state, &p->old_name);2040}20412042/*2043 * include/exclude2044 */20452046static voidadd_name_limit(struct apply_state *state,2047const char*name,2048int exclude)2049{2050struct string_list_item *it;20512052 it =string_list_append(&state->limit_by_name, name);2053 it->util = exclude ? NULL : (void*)1;2054}20552056static intuse_patch(struct apply_state *state,struct patch *p)2057{2058const char*pathname = p->new_name ? p->new_name : p->old_name;2059int i;20602061/* Paths outside are not touched regardless of "--include" */2062if(0< state->prefix_length) {2063int pathlen =strlen(pathname);2064if(pathlen <= state->prefix_length ||2065memcmp(state->prefix, pathname, state->prefix_length))2066return0;2067}20682069/* See if it matches any of exclude/include rule */2070for(i =0; i < state->limit_by_name.nr; i++) {2071struct string_list_item *it = &state->limit_by_name.items[i];2072if(!wildmatch(it->string, pathname,0, NULL))2073return(it->util != NULL);2074}20752076/*2077 * If we had any include, a path that does not match any rule is2078 * not used. Otherwise, we saw bunch of exclude rules (or none)2079 * and such a path is used.2080 */2081return!state->has_include;2082}208320842085/*2086 * Read the patch text in "buffer" that extends for "size" bytes; stop2087 * reading after seeing a single patch (i.e. changes to a single file).2088 * Create fragments (i.e. patch hunks) and hang them to the given patch.2089 * Return the number of bytes consumed, so that the caller can call us2090 * again for the next patch.2091 */2092static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2093{2094int hdrsize, patchsize;2095int offset =find_header(state, buffer, size, &hdrsize, patch);20962097if(offset <0)2098return offset;20992100prefix_patch(state, patch);21012102if(!use_patch(state, patch))2103 patch->ws_rule =0;2104else2105 patch->ws_rule =whitespace_rule(patch->new_name2106? patch->new_name2107: patch->old_name);21082109 patchsize =parse_single_patch(state,2110 buffer + offset + hdrsize,2111 size - offset - hdrsize,2112 patch);21132114if(!patchsize) {2115static const char git_binary[] ="GIT binary patch\n";2116int hd = hdrsize + offset;2117unsigned long llen =linelen(buffer + hd, size - hd);21182119if(llen ==sizeof(git_binary) -1&&2120!memcmp(git_binary, buffer + hd, llen)) {2121int used;2122 state->linenr++;2123 used =parse_binary(state, buffer + hd + llen,2124 size - hd - llen, patch);2125if(used <0)2126return-1;2127if(used)2128 patchsize = used + llen;2129else2130 patchsize =0;2131}2132else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2133static const char*binhdr[] = {2134"Binary files ",2135"Files ",2136 NULL,2137};2138int i;2139for(i =0; binhdr[i]; i++) {2140int len =strlen(binhdr[i]);2141if(len < size - hd &&2142!memcmp(binhdr[i], buffer + hd, len)) {2143 state->linenr++;2144 patch->is_binary =1;2145 patchsize = llen;2146break;2147}2148}2149}21502151/* Empty patch cannot be applied if it is a text patch2152 * without metadata change. A binary patch appears2153 * empty to us here.2154 */2155if((state->apply || state->check) &&2156(!patch->is_binary && !metadata_changes(patch)))2157die(_("patch with only garbage at line%d"), state->linenr);2158}21592160return offset + hdrsize + patchsize;2161}21622163#define swap(a,b) myswap((a),(b),sizeof(a))21642165#define myswap(a, b, size) do { \2166 unsigned char mytmp[size]; \2167 memcpy(mytmp, &a, size); \2168 memcpy(&a, &b, size); \2169 memcpy(&b, mytmp, size); \2170} while (0)21712172static voidreverse_patches(struct patch *p)2173{2174for(; p; p = p->next) {2175struct fragment *frag = p->fragments;21762177swap(p->new_name, p->old_name);2178swap(p->new_mode, p->old_mode);2179swap(p->is_new, p->is_delete);2180swap(p->lines_added, p->lines_deleted);2181swap(p->old_sha1_prefix, p->new_sha1_prefix);21822183for(; frag; frag = frag->next) {2184swap(frag->newpos, frag->oldpos);2185swap(frag->newlines, frag->oldlines);2186}2187}2188}21892190static const char pluses[] =2191"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2192static const char minuses[]=2193"----------------------------------------------------------------------";21942195static voidshow_stats(struct apply_state *state,struct patch *patch)2196{2197struct strbuf qname = STRBUF_INIT;2198char*cp = patch->new_name ? patch->new_name : patch->old_name;2199int max, add, del;22002201quote_c_style(cp, &qname, NULL,0);22022203/*2204 * "scale" the filename2205 */2206 max = state->max_len;2207if(max >50)2208 max =50;22092210if(qname.len > max) {2211 cp =strchr(qname.buf + qname.len +3- max,'/');2212if(!cp)2213 cp = qname.buf + qname.len +3- max;2214strbuf_splice(&qname,0, cp - qname.buf,"...",3);2215}22162217if(patch->is_binary) {2218printf(" %-*s | Bin\n", max, qname.buf);2219strbuf_release(&qname);2220return;2221}22222223printf(" %-*s |", max, qname.buf);2224strbuf_release(&qname);22252226/*2227 * scale the add/delete2228 */2229 max = max + state->max_change >70?70- max : state->max_change;2230 add = patch->lines_added;2231 del = patch->lines_deleted;22322233if(state->max_change >0) {2234int total = ((add + del) * max + state->max_change /2) / state->max_change;2235 add = (add * max + state->max_change /2) / state->max_change;2236 del = total - add;2237}2238printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2239 add, pluses, del, minuses);2240}22412242static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2243{2244switch(st->st_mode & S_IFMT) {2245case S_IFLNK:2246if(strbuf_readlink(buf, path, st->st_size) <0)2247returnerror(_("unable to read symlink%s"), path);2248return0;2249case S_IFREG:2250if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2251returnerror(_("unable to open or read%s"), path);2252convert_to_git(path, buf->buf, buf->len, buf,0);2253return0;2254default:2255return-1;2256}2257}22582259/*2260 * Update the preimage, and the common lines in postimage,2261 * from buffer buf of length len. If postlen is 0 the postimage2262 * is updated in place, otherwise it's updated on a new buffer2263 * of length postlen2264 */22652266static voidupdate_pre_post_images(struct image *preimage,2267struct image *postimage,2268char*buf,2269size_t len,size_t postlen)2270{2271int i, ctx, reduced;2272char*new, *old, *fixed;2273struct image fixed_preimage;22742275/*2276 * Update the preimage with whitespace fixes. Note that we2277 * are not losing preimage->buf -- apply_one_fragment() will2278 * free "oldlines".2279 */2280prepare_image(&fixed_preimage, buf, len,1);2281assert(postlen2282? fixed_preimage.nr == preimage->nr2283: fixed_preimage.nr <= preimage->nr);2284for(i =0; i < fixed_preimage.nr; i++)2285 fixed_preimage.line[i].flag = preimage->line[i].flag;2286free(preimage->line_allocated);2287*preimage = fixed_preimage;22882289/*2290 * Adjust the common context lines in postimage. This can be2291 * done in-place when we are shrinking it with whitespace2292 * fixing, but needs a new buffer when ignoring whitespace or2293 * expanding leading tabs to spaces.2294 *2295 * We trust the caller to tell us if the update can be done2296 * in place (postlen==0) or not.2297 */2298 old = postimage->buf;2299if(postlen)2300new= postimage->buf =xmalloc(postlen);2301else2302new= old;2303 fixed = preimage->buf;23042305for(i = reduced = ctx =0; i < postimage->nr; i++) {2306size_t l_len = postimage->line[i].len;2307if(!(postimage->line[i].flag & LINE_COMMON)) {2308/* an added line -- no counterparts in preimage */2309memmove(new, old, l_len);2310 old += l_len;2311new+= l_len;2312continue;2313}23142315/* a common context -- skip it in the original postimage */2316 old += l_len;23172318/* and find the corresponding one in the fixed preimage */2319while(ctx < preimage->nr &&2320!(preimage->line[ctx].flag & LINE_COMMON)) {2321 fixed += preimage->line[ctx].len;2322 ctx++;2323}23242325/*2326 * preimage is expected to run out, if the caller2327 * fixed addition of trailing blank lines.2328 */2329if(preimage->nr <= ctx) {2330 reduced++;2331continue;2332}23332334/* and copy it in, while fixing the line length */2335 l_len = preimage->line[ctx].len;2336memcpy(new, fixed, l_len);2337new+= l_len;2338 fixed += l_len;2339 postimage->line[i].len = l_len;2340 ctx++;2341}23422343if(postlen2344? postlen <new- postimage->buf2345: postimage->len <new- postimage->buf)2346die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2347(int)postlen, (int) postimage->len, (int)(new- postimage->buf));23482349/* Fix the length of the whole thing */2350 postimage->len =new- postimage->buf;2351 postimage->nr -= reduced;2352}23532354static intline_by_line_fuzzy_match(struct image *img,2355struct image *preimage,2356struct image *postimage,2357unsigned longtry,2358int try_lno,2359int preimage_limit)2360{2361int i;2362size_t imgoff =0;2363size_t preoff =0;2364size_t postlen = postimage->len;2365size_t extra_chars;2366char*buf;2367char*preimage_eof;2368char*preimage_end;2369struct strbuf fixed;2370char*fixed_buf;2371size_t fixed_len;23722373for(i =0; i < preimage_limit; i++) {2374size_t prelen = preimage->line[i].len;2375size_t imglen = img->line[try_lno+i].len;23762377if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2378 preimage->buf + preoff, prelen))2379return0;2380if(preimage->line[i].flag & LINE_COMMON)2381 postlen += imglen - prelen;2382 imgoff += imglen;2383 preoff += prelen;2384}23852386/*2387 * Ok, the preimage matches with whitespace fuzz.2388 *2389 * imgoff now holds the true length of the target that2390 * matches the preimage before the end of the file.2391 *2392 * Count the number of characters in the preimage that fall2393 * beyond the end of the file and make sure that all of them2394 * are whitespace characters. (This can only happen if2395 * we are removing blank lines at the end of the file.)2396 */2397 buf = preimage_eof = preimage->buf + preoff;2398for( ; i < preimage->nr; i++)2399 preoff += preimage->line[i].len;2400 preimage_end = preimage->buf + preoff;2401for( ; buf < preimage_end; buf++)2402if(!isspace(*buf))2403return0;24042405/*2406 * Update the preimage and the common postimage context2407 * lines to use the same whitespace as the target.2408 * If whitespace is missing in the target (i.e.2409 * if the preimage extends beyond the end of the file),2410 * use the whitespace from the preimage.2411 */2412 extra_chars = preimage_end - preimage_eof;2413strbuf_init(&fixed, imgoff + extra_chars);2414strbuf_add(&fixed, img->buf +try, imgoff);2415strbuf_add(&fixed, preimage_eof, extra_chars);2416 fixed_buf =strbuf_detach(&fixed, &fixed_len);2417update_pre_post_images(preimage, postimage,2418 fixed_buf, fixed_len, postlen);2419return1;2420}24212422static intmatch_fragment(struct apply_state *state,2423struct image *img,2424struct image *preimage,2425struct image *postimage,2426unsigned longtry,2427int try_lno,2428unsigned ws_rule,2429int match_beginning,int match_end)2430{2431int i;2432char*fixed_buf, *buf, *orig, *target;2433struct strbuf fixed;2434size_t fixed_len, postlen;2435int preimage_limit;24362437if(preimage->nr + try_lno <= img->nr) {2438/*2439 * The hunk falls within the boundaries of img.2440 */2441 preimage_limit = preimage->nr;2442if(match_end && (preimage->nr + try_lno != img->nr))2443return0;2444}else if(state->ws_error_action == correct_ws_error &&2445(ws_rule & WS_BLANK_AT_EOF)) {2446/*2447 * This hunk extends beyond the end of img, and we are2448 * removing blank lines at the end of the file. This2449 * many lines from the beginning of the preimage must2450 * match with img, and the remainder of the preimage2451 * must be blank.2452 */2453 preimage_limit = img->nr - try_lno;2454}else{2455/*2456 * The hunk extends beyond the end of the img and2457 * we are not removing blanks at the end, so we2458 * should reject the hunk at this position.2459 */2460return0;2461}24622463if(match_beginning && try_lno)2464return0;24652466/* Quick hash check */2467for(i =0; i < preimage_limit; i++)2468if((img->line[try_lno + i].flag & LINE_PATCHED) ||2469(preimage->line[i].hash != img->line[try_lno + i].hash))2470return0;24712472if(preimage_limit == preimage->nr) {2473/*2474 * Do we have an exact match? If we were told to match2475 * at the end, size must be exactly at try+fragsize,2476 * otherwise try+fragsize must be still within the preimage,2477 * and either case, the old piece should match the preimage2478 * exactly.2479 */2480if((match_end2481? (try+ preimage->len == img->len)2482: (try+ preimage->len <= img->len)) &&2483!memcmp(img->buf +try, preimage->buf, preimage->len))2484return1;2485}else{2486/*2487 * The preimage extends beyond the end of img, so2488 * there cannot be an exact match.2489 *2490 * There must be one non-blank context line that match2491 * a line before the end of img.2492 */2493char*buf_end;24942495 buf = preimage->buf;2496 buf_end = buf;2497for(i =0; i < preimage_limit; i++)2498 buf_end += preimage->line[i].len;24992500for( ; buf < buf_end; buf++)2501if(!isspace(*buf))2502break;2503if(buf == buf_end)2504return0;2505}25062507/*2508 * No exact match. If we are ignoring whitespace, run a line-by-line2509 * fuzzy matching. We collect all the line length information because2510 * we need it to adjust whitespace if we match.2511 */2512if(state->ws_ignore_action == ignore_ws_change)2513returnline_by_line_fuzzy_match(img, preimage, postimage,2514try, try_lno, preimage_limit);25152516if(state->ws_error_action != correct_ws_error)2517return0;25182519/*2520 * The hunk does not apply byte-by-byte, but the hash says2521 * it might with whitespace fuzz. We weren't asked to2522 * ignore whitespace, we were asked to correct whitespace2523 * errors, so let's try matching after whitespace correction.2524 *2525 * While checking the preimage against the target, whitespace2526 * errors in both fixed, we count how large the corresponding2527 * postimage needs to be. The postimage prepared by2528 * apply_one_fragment() has whitespace errors fixed on added2529 * lines already, but the common lines were propagated as-is,2530 * which may become longer when their whitespace errors are2531 * fixed.2532 */25332534/* First count added lines in postimage */2535 postlen =0;2536for(i =0; i < postimage->nr; i++) {2537if(!(postimage->line[i].flag & LINE_COMMON))2538 postlen += postimage->line[i].len;2539}25402541/*2542 * The preimage may extend beyond the end of the file,2543 * but in this loop we will only handle the part of the2544 * preimage that falls within the file.2545 */2546strbuf_init(&fixed, preimage->len +1);2547 orig = preimage->buf;2548 target = img->buf +try;2549for(i =0; i < preimage_limit; i++) {2550size_t oldlen = preimage->line[i].len;2551size_t tgtlen = img->line[try_lno + i].len;2552size_t fixstart = fixed.len;2553struct strbuf tgtfix;2554int match;25552556/* Try fixing the line in the preimage */2557ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25582559/* Try fixing the line in the target */2560strbuf_init(&tgtfix, tgtlen);2561ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);25622563/*2564 * If they match, either the preimage was based on2565 * a version before our tree fixed whitespace breakage,2566 * or we are lacking a whitespace-fix patch the tree2567 * the preimage was based on already had (i.e. target2568 * has whitespace breakage, the preimage doesn't).2569 * In either case, we are fixing the whitespace breakages2570 * so we might as well take the fix together with their2571 * real change.2572 */2573 match = (tgtfix.len == fixed.len - fixstart &&2574!memcmp(tgtfix.buf, fixed.buf + fixstart,2575 fixed.len - fixstart));25762577/* Add the length if this is common with the postimage */2578if(preimage->line[i].flag & LINE_COMMON)2579 postlen += tgtfix.len;25802581strbuf_release(&tgtfix);2582if(!match)2583goto unmatch_exit;25842585 orig += oldlen;2586 target += tgtlen;2587}258825892590/*2591 * Now handle the lines in the preimage that falls beyond the2592 * end of the file (if any). They will only match if they are2593 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2594 * false).2595 */2596for( ; i < preimage->nr; i++) {2597size_t fixstart = fixed.len;/* start of the fixed preimage */2598size_t oldlen = preimage->line[i].len;2599int j;26002601/* Try fixing the line in the preimage */2602ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);26032604for(j = fixstart; j < fixed.len; j++)2605if(!isspace(fixed.buf[j]))2606goto unmatch_exit;26072608 orig += oldlen;2609}26102611/*2612 * Yes, the preimage is based on an older version that still2613 * has whitespace breakages unfixed, and fixing them makes the2614 * hunk match. Update the context lines in the postimage.2615 */2616 fixed_buf =strbuf_detach(&fixed, &fixed_len);2617if(postlen < postimage->len)2618 postlen =0;2619update_pre_post_images(preimage, postimage,2620 fixed_buf, fixed_len, postlen);2621return1;26222623 unmatch_exit:2624strbuf_release(&fixed);2625return0;2626}26272628static intfind_pos(struct apply_state *state,2629struct image *img,2630struct image *preimage,2631struct image *postimage,2632int line,2633unsigned ws_rule,2634int match_beginning,int match_end)2635{2636int i;2637unsigned long backwards, forwards,try;2638int backwards_lno, forwards_lno, try_lno;26392640/*2641 * If match_beginning or match_end is specified, there is no2642 * point starting from a wrong line that will never match and2643 * wander around and wait for a match at the specified end.2644 */2645if(match_beginning)2646 line =0;2647else if(match_end)2648 line = img->nr - preimage->nr;26492650/*2651 * Because the comparison is unsigned, the following test2652 * will also take care of a negative line number that can2653 * result when match_end and preimage is larger than the target.2654 */2655if((size_t) line > img->nr)2656 line = img->nr;26572658try=0;2659for(i =0; i < line; i++)2660try+= img->line[i].len;26612662/*2663 * There's probably some smart way to do this, but I'll leave2664 * that to the smart and beautiful people. I'm simple and stupid.2665 */2666 backwards =try;2667 backwards_lno = line;2668 forwards =try;2669 forwards_lno = line;2670 try_lno = line;26712672for(i =0; ; i++) {2673if(match_fragment(state, img, preimage, postimage,2674try, try_lno, ws_rule,2675 match_beginning, match_end))2676return try_lno;26772678 again:2679if(backwards_lno ==0&& forwards_lno == img->nr)2680break;26812682if(i &1) {2683if(backwards_lno ==0) {2684 i++;2685goto again;2686}2687 backwards_lno--;2688 backwards -= img->line[backwards_lno].len;2689try= backwards;2690 try_lno = backwards_lno;2691}else{2692if(forwards_lno == img->nr) {2693 i++;2694goto again;2695}2696 forwards += img->line[forwards_lno].len;2697 forwards_lno++;2698try= forwards;2699 try_lno = forwards_lno;2700}27012702}2703return-1;2704}27052706static voidremove_first_line(struct image *img)2707{2708 img->buf += img->line[0].len;2709 img->len -= img->line[0].len;2710 img->line++;2711 img->nr--;2712}27132714static voidremove_last_line(struct image *img)2715{2716 img->len -= img->line[--img->nr].len;2717}27182719/*2720 * The change from "preimage" and "postimage" has been found to2721 * apply at applied_pos (counts in line numbers) in "img".2722 * Update "img" to remove "preimage" and replace it with "postimage".2723 */2724static voidupdate_image(struct apply_state *state,2725struct image *img,2726int applied_pos,2727struct image *preimage,2728struct image *postimage)2729{2730/*2731 * remove the copy of preimage at offset in img2732 * and replace it with postimage2733 */2734int i, nr;2735size_t remove_count, insert_count, applied_at =0;2736char*result;2737int preimage_limit;27382739/*2740 * If we are removing blank lines at the end of img,2741 * the preimage may extend beyond the end.2742 * If that is the case, we must be careful only to2743 * remove the part of the preimage that falls within2744 * the boundaries of img. Initialize preimage_limit2745 * to the number of lines in the preimage that falls2746 * within the boundaries.2747 */2748 preimage_limit = preimage->nr;2749if(preimage_limit > img->nr - applied_pos)2750 preimage_limit = img->nr - applied_pos;27512752for(i =0; i < applied_pos; i++)2753 applied_at += img->line[i].len;27542755 remove_count =0;2756for(i =0; i < preimage_limit; i++)2757 remove_count += img->line[applied_pos + i].len;2758 insert_count = postimage->len;27592760/* Adjust the contents */2761 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2762memcpy(result, img->buf, applied_at);2763memcpy(result + applied_at, postimage->buf, postimage->len);2764memcpy(result + applied_at + postimage->len,2765 img->buf + (applied_at + remove_count),2766 img->len - (applied_at + remove_count));2767free(img->buf);2768 img->buf = result;2769 img->len += insert_count - remove_count;2770 result[img->len] ='\0';27712772/* Adjust the line table */2773 nr = img->nr + postimage->nr - preimage_limit;2774if(preimage_limit < postimage->nr) {2775/*2776 * NOTE: this knows that we never call remove_first_line()2777 * on anything other than pre/post image.2778 */2779REALLOC_ARRAY(img->line, nr);2780 img->line_allocated = img->line;2781}2782if(preimage_limit != postimage->nr)2783memmove(img->line + applied_pos + postimage->nr,2784 img->line + applied_pos + preimage_limit,2785(img->nr - (applied_pos + preimage_limit)) *2786sizeof(*img->line));2787memcpy(img->line + applied_pos,2788 postimage->line,2789 postimage->nr *sizeof(*img->line));2790if(!state->allow_overlap)2791for(i =0; i < postimage->nr; i++)2792 img->line[applied_pos + i].flag |= LINE_PATCHED;2793 img->nr = nr;2794}27952796/*2797 * Use the patch-hunk text in "frag" to prepare two images (preimage and2798 * postimage) for the hunk. Find lines that match "preimage" in "img" and2799 * replace the part of "img" with "postimage" text.2800 */2801static intapply_one_fragment(struct apply_state *state,2802struct image *img,struct fragment *frag,2803int inaccurate_eof,unsigned ws_rule,2804int nth_fragment)2805{2806int match_beginning, match_end;2807const char*patch = frag->patch;2808int size = frag->size;2809char*old, *oldlines;2810struct strbuf newlines;2811int new_blank_lines_at_end =0;2812int found_new_blank_lines_at_end =0;2813int hunk_linenr = frag->linenr;2814unsigned long leading, trailing;2815int pos, applied_pos;2816struct image preimage;2817struct image postimage;28182819memset(&preimage,0,sizeof(preimage));2820memset(&postimage,0,sizeof(postimage));2821 oldlines =xmalloc(size);2822strbuf_init(&newlines, size);28232824 old = oldlines;2825while(size >0) {2826char first;2827int len =linelen(patch, size);2828int plen;2829int added_blank_line =0;2830int is_blank_context =0;2831size_t start;28322833if(!len)2834break;28352836/*2837 * "plen" is how much of the line we should use for2838 * the actual patch data. Normally we just remove the2839 * first character on the line, but if the line is2840 * followed by "\ No newline", then we also remove the2841 * last one (which is the newline, of course).2842 */2843 plen = len -1;2844if(len < size && patch[len] =='\\')2845 plen--;2846 first = *patch;2847if(state->apply_in_reverse) {2848if(first =='-')2849 first ='+';2850else if(first =='+')2851 first ='-';2852}28532854switch(first) {2855case'\n':2856/* Newer GNU diff, empty context line */2857if(plen <0)2858/* ... followed by '\No newline'; nothing */2859break;2860*old++ ='\n';2861strbuf_addch(&newlines,'\n');2862add_line_info(&preimage,"\n",1, LINE_COMMON);2863add_line_info(&postimage,"\n",1, LINE_COMMON);2864 is_blank_context =1;2865break;2866case' ':2867if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2868ws_blank_line(patch +1, plen, ws_rule))2869 is_blank_context =1;2870case'-':2871memcpy(old, patch +1, plen);2872add_line_info(&preimage, old, plen,2873(first ==' '? LINE_COMMON :0));2874 old += plen;2875if(first =='-')2876break;2877/* Fall-through for ' ' */2878case'+':2879/* --no-add does not add new lines */2880if(first =='+'&& state->no_add)2881break;28822883 start = newlines.len;2884if(first !='+'||2885!state->whitespace_error ||2886 state->ws_error_action != correct_ws_error) {2887strbuf_add(&newlines, patch +1, plen);2888}2889else{2890ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2891}2892add_line_info(&postimage, newlines.buf + start, newlines.len - start,2893(first =='+'?0: LINE_COMMON));2894if(first =='+'&&2895(ws_rule & WS_BLANK_AT_EOF) &&2896ws_blank_line(patch +1, plen, ws_rule))2897 added_blank_line =1;2898break;2899case'@':case'\\':2900/* Ignore it, we already handled it */2901break;2902default:2903if(state->apply_verbosely)2904error(_("invalid start of line: '%c'"), first);2905 applied_pos = -1;2906goto out;2907}2908if(added_blank_line) {2909if(!new_blank_lines_at_end)2910 found_new_blank_lines_at_end = hunk_linenr;2911 new_blank_lines_at_end++;2912}2913else if(is_blank_context)2914;2915else2916 new_blank_lines_at_end =0;2917 patch += len;2918 size -= len;2919 hunk_linenr++;2920}2921if(inaccurate_eof &&2922 old > oldlines && old[-1] =='\n'&&2923 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2924 old--;2925strbuf_setlen(&newlines, newlines.len -1);2926}29272928 leading = frag->leading;2929 trailing = frag->trailing;29302931/*2932 * A hunk to change lines at the beginning would begin with2933 * @@ -1,L +N,M @@2934 * but we need to be careful. -U0 that inserts before the second2935 * line also has this pattern.2936 *2937 * And a hunk to add to an empty file would begin with2938 * @@ -0,0 +N,M @@2939 *2940 * In other words, a hunk that is (frag->oldpos <= 1) with or2941 * without leading context must match at the beginning.2942 */2943 match_beginning = (!frag->oldpos ||2944(frag->oldpos ==1&& !state->unidiff_zero));29452946/*2947 * A hunk without trailing lines must match at the end.2948 * However, we simply cannot tell if a hunk must match end2949 * from the lack of trailing lines if the patch was generated2950 * with unidiff without any context.2951 */2952 match_end = !state->unidiff_zero && !trailing;29532954 pos = frag->newpos ? (frag->newpos -1) :0;2955 preimage.buf = oldlines;2956 preimage.len = old - oldlines;2957 postimage.buf = newlines.buf;2958 postimage.len = newlines.len;2959 preimage.line = preimage.line_allocated;2960 postimage.line = postimage.line_allocated;29612962for(;;) {29632964 applied_pos =find_pos(state, img, &preimage, &postimage, pos,2965 ws_rule, match_beginning, match_end);29662967if(applied_pos >=0)2968break;29692970/* Am I at my context limits? */2971if((leading <= state->p_context) && (trailing <= state->p_context))2972break;2973if(match_beginning || match_end) {2974 match_beginning = match_end =0;2975continue;2976}29772978/*2979 * Reduce the number of context lines; reduce both2980 * leading and trailing if they are equal otherwise2981 * just reduce the larger context.2982 */2983if(leading >= trailing) {2984remove_first_line(&preimage);2985remove_first_line(&postimage);2986 pos--;2987 leading--;2988}2989if(trailing > leading) {2990remove_last_line(&preimage);2991remove_last_line(&postimage);2992 trailing--;2993}2994}29952996if(applied_pos >=0) {2997if(new_blank_lines_at_end &&2998 preimage.nr + applied_pos >= img->nr &&2999(ws_rule & WS_BLANK_AT_EOF) &&3000 state->ws_error_action != nowarn_ws_error) {3001record_ws_error(state, WS_BLANK_AT_EOF,"+",1,3002 found_new_blank_lines_at_end);3003if(state->ws_error_action == correct_ws_error) {3004while(new_blank_lines_at_end--)3005remove_last_line(&postimage);3006}3007/*3008 * We would want to prevent write_out_results()3009 * from taking place in apply_patch() that follows3010 * the callchain led us here, which is:3011 * apply_patch->check_patch_list->check_patch->3012 * apply_data->apply_fragments->apply_one_fragment3013 */3014if(state->ws_error_action == die_on_ws_error)3015 state->apply =0;3016}30173018if(state->apply_verbosely && applied_pos != pos) {3019int offset = applied_pos - pos;3020if(state->apply_in_reverse)3021 offset =0- offset;3022fprintf_ln(stderr,3023Q_("Hunk #%dsucceeded at%d(offset%dline).",3024"Hunk #%dsucceeded at%d(offset%dlines).",3025 offset),3026 nth_fragment, applied_pos +1, offset);3027}30283029/*3030 * Warn if it was necessary to reduce the number3031 * of context lines.3032 */3033if((leading != frag->leading) ||3034(trailing != frag->trailing))3035fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"3036" to apply fragment at%d"),3037 leading, trailing, applied_pos+1);3038update_image(state, img, applied_pos, &preimage, &postimage);3039}else{3040if(state->apply_verbosely)3041error(_("while searching for:\n%.*s"),3042(int)(old - oldlines), oldlines);3043}30443045out:3046free(oldlines);3047strbuf_release(&newlines);3048free(preimage.line_allocated);3049free(postimage.line_allocated);30503051return(applied_pos <0);3052}30533054static intapply_binary_fragment(struct apply_state *state,3055struct image *img,3056struct patch *patch)3057{3058struct fragment *fragment = patch->fragments;3059unsigned long len;3060void*dst;30613062if(!fragment)3063returnerror(_("missing binary patch data for '%s'"),3064 patch->new_name ?3065 patch->new_name :3066 patch->old_name);30673068/* Binary patch is irreversible without the optional second hunk */3069if(state->apply_in_reverse) {3070if(!fragment->next)3071returnerror("cannot reverse-apply a binary patch "3072"without the reverse hunk to '%s'",3073 patch->new_name3074? patch->new_name : patch->old_name);3075 fragment = fragment->next;3076}3077switch(fragment->binary_patch_method) {3078case BINARY_DELTA_DEFLATED:3079 dst =patch_delta(img->buf, img->len, fragment->patch,3080 fragment->size, &len);3081if(!dst)3082return-1;3083clear_image(img);3084 img->buf = dst;3085 img->len = len;3086return0;3087case BINARY_LITERAL_DEFLATED:3088clear_image(img);3089 img->len = fragment->size;3090 img->buf =xmemdupz(fragment->patch, img->len);3091return0;3092}3093return-1;3094}30953096/*3097 * Replace "img" with the result of applying the binary patch.3098 * The binary patch data itself in patch->fragment is still kept3099 * but the preimage prepared by the caller in "img" is freed here3100 * or in the helper function apply_binary_fragment() this calls.3101 */3102static intapply_binary(struct apply_state *state,3103struct image *img,3104struct patch *patch)3105{3106const char*name = patch->old_name ? patch->old_name : patch->new_name;3107unsigned char sha1[20];31083109/*3110 * For safety, we require patch index line to contain3111 * full 40-byte textual SHA1 for old and new, at least for now.3112 */3113if(strlen(patch->old_sha1_prefix) !=40||3114strlen(patch->new_sha1_prefix) !=40||3115get_sha1_hex(patch->old_sha1_prefix, sha1) ||3116get_sha1_hex(patch->new_sha1_prefix, sha1))3117returnerror("cannot apply binary patch to '%s' "3118"without full index line", name);31193120if(patch->old_name) {3121/*3122 * See if the old one matches what the patch3123 * applies to.3124 */3125hash_sha1_file(img->buf, img->len, blob_type, sha1);3126if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3127returnerror("the patch applies to '%s' (%s), "3128"which does not match the "3129"current contents.",3130 name,sha1_to_hex(sha1));3131}3132else{3133/* Otherwise, the old one must be empty. */3134if(img->len)3135returnerror("the patch applies to an empty "3136"'%s' but it is not empty", name);3137}31383139get_sha1_hex(patch->new_sha1_prefix, sha1);3140if(is_null_sha1(sha1)) {3141clear_image(img);3142return0;/* deletion patch */3143}31443145if(has_sha1_file(sha1)) {3146/* We already have the postimage */3147enum object_type type;3148unsigned long size;3149char*result;31503151 result =read_sha1_file(sha1, &type, &size);3152if(!result)3153returnerror("the necessary postimage%sfor "3154"'%s' cannot be read",3155 patch->new_sha1_prefix, name);3156clear_image(img);3157 img->buf = result;3158 img->len = size;3159}else{3160/*3161 * We have verified buf matches the preimage;3162 * apply the patch data to it, which is stored3163 * in the patch->fragments->{patch,size}.3164 */3165if(apply_binary_fragment(state, img, patch))3166returnerror(_("binary patch does not apply to '%s'"),3167 name);31683169/* verify that the result matches */3170hash_sha1_file(img->buf, img->len, blob_type, sha1);3171if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3172returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3173 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3174}31753176return0;3177}31783179static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3180{3181struct fragment *frag = patch->fragments;3182const char*name = patch->old_name ? patch->old_name : patch->new_name;3183unsigned ws_rule = patch->ws_rule;3184unsigned inaccurate_eof = patch->inaccurate_eof;3185int nth =0;31863187if(patch->is_binary)3188returnapply_binary(state, img, patch);31893190while(frag) {3191 nth++;3192if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3193error(_("patch failed:%s:%ld"), name, frag->oldpos);3194if(!state->apply_with_reject)3195return-1;3196 frag->rejected =1;3197}3198 frag = frag->next;3199}3200return0;3201}32023203static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3204{3205if(S_ISGITLINK(mode)) {3206strbuf_grow(buf,100);3207strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3208}else{3209enum object_type type;3210unsigned long sz;3211char*result;32123213 result =read_sha1_file(sha1, &type, &sz);3214if(!result)3215return-1;3216/* XXX read_sha1_file NUL-terminates */3217strbuf_attach(buf, result, sz, sz +1);3218}3219return0;3220}32213222static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3223{3224if(!ce)3225return0;3226returnread_blob_object(buf, ce->sha1, ce->ce_mode);3227}32283229static struct patch *in_fn_table(struct apply_state *state,const char*name)3230{3231struct string_list_item *item;32323233if(name == NULL)3234return NULL;32353236 item =string_list_lookup(&state->fn_table, name);3237if(item != NULL)3238return(struct patch *)item->util;32393240return NULL;3241}32423243/*3244 * item->util in the filename table records the status of the path.3245 * Usually it points at a patch (whose result records the contents3246 * of it after applying it), but it could be PATH_WAS_DELETED for a3247 * path that a previously applied patch has already removed, or3248 * PATH_TO_BE_DELETED for a path that a later patch would remove.3249 *3250 * The latter is needed to deal with a case where two paths A and B3251 * are swapped by first renaming A to B and then renaming B to A;3252 * moving A to B should not be prevented due to presence of B as we3253 * will remove it in a later patch.3254 */3255#define PATH_TO_BE_DELETED ((struct patch *) -2)3256#define PATH_WAS_DELETED ((struct patch *) -1)32573258static intto_be_deleted(struct patch *patch)3259{3260return patch == PATH_TO_BE_DELETED;3261}32623263static intwas_deleted(struct patch *patch)3264{3265return patch == PATH_WAS_DELETED;3266}32673268static voidadd_to_fn_table(struct apply_state *state,struct patch *patch)3269{3270struct string_list_item *item;32713272/*3273 * Always add new_name unless patch is a deletion3274 * This should cover the cases for normal diffs,3275 * file creations and copies3276 */3277if(patch->new_name != NULL) {3278 item =string_list_insert(&state->fn_table, patch->new_name);3279 item->util = patch;3280}32813282/*3283 * store a failure on rename/deletion cases because3284 * later chunks shouldn't patch old names3285 */3286if((patch->new_name == NULL) || (patch->is_rename)) {3287 item =string_list_insert(&state->fn_table, patch->old_name);3288 item->util = PATH_WAS_DELETED;3289}3290}32913292static voidprepare_fn_table(struct apply_state *state,struct patch *patch)3293{3294/*3295 * store information about incoming file deletion3296 */3297while(patch) {3298if((patch->new_name == NULL) || (patch->is_rename)) {3299struct string_list_item *item;3300 item =string_list_insert(&state->fn_table, patch->old_name);3301 item->util = PATH_TO_BE_DELETED;3302}3303 patch = patch->next;3304}3305}33063307static intcheckout_target(struct index_state *istate,3308struct cache_entry *ce,struct stat *st)3309{3310struct checkout costate;33113312memset(&costate,0,sizeof(costate));3313 costate.base_dir ="";3314 costate.refresh_cache =1;3315 costate.istate = istate;3316if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3317returnerror(_("cannot checkout%s"), ce->name);3318return0;3319}33203321static struct patch *previous_patch(struct apply_state *state,3322struct patch *patch,3323int*gone)3324{3325struct patch *previous;33263327*gone =0;3328if(patch->is_copy || patch->is_rename)3329return NULL;/* "git" patches do not depend on the order */33303331 previous =in_fn_table(state, patch->old_name);3332if(!previous)3333return NULL;33343335if(to_be_deleted(previous))3336return NULL;/* the deletion hasn't happened yet */33373338if(was_deleted(previous))3339*gone =1;33403341return previous;3342}33433344static intverify_index_match(const struct cache_entry *ce,struct stat *st)3345{3346if(S_ISGITLINK(ce->ce_mode)) {3347if(!S_ISDIR(st->st_mode))3348return-1;3349return0;3350}3351returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3352}33533354#define SUBMODULE_PATCH_WITHOUT_INDEX 133553356static intload_patch_target(struct apply_state *state,3357struct strbuf *buf,3358const struct cache_entry *ce,3359struct stat *st,3360const char*name,3361unsigned expected_mode)3362{3363if(state->cached || state->check_index) {3364if(read_file_or_gitlink(ce, buf))3365returnerror(_("read of%sfailed"), name);3366}else if(name) {3367if(S_ISGITLINK(expected_mode)) {3368if(ce)3369returnread_file_or_gitlink(ce, buf);3370else3371return SUBMODULE_PATCH_WITHOUT_INDEX;3372}else if(has_symlink_leading_path(name,strlen(name))) {3373returnerror(_("reading from '%s' beyond a symbolic link"), name);3374}else{3375if(read_old_data(st, name, buf))3376returnerror(_("read of%sfailed"), name);3377}3378}3379return0;3380}33813382/*3383 * We are about to apply "patch"; populate the "image" with the3384 * current version we have, from the working tree or from the index,3385 * depending on the situation e.g. --cached/--index. If we are3386 * applying a non-git patch that incrementally updates the tree,3387 * we read from the result of a previous diff.3388 */3389static intload_preimage(struct apply_state *state,3390struct image *image,3391struct patch *patch,struct stat *st,3392const struct cache_entry *ce)3393{3394struct strbuf buf = STRBUF_INIT;3395size_t len;3396char*img;3397struct patch *previous;3398int status;33993400 previous =previous_patch(state, patch, &status);3401if(status)3402returnerror(_("path%shas been renamed/deleted"),3403 patch->old_name);3404if(previous) {3405/* We have a patched copy in memory; use that. */3406strbuf_add(&buf, previous->result, previous->resultsize);3407}else{3408 status =load_patch_target(state, &buf, ce, st,3409 patch->old_name, patch->old_mode);3410if(status <0)3411return status;3412else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3413/*3414 * There is no way to apply subproject3415 * patch without looking at the index.3416 * NEEDSWORK: shouldn't this be flagged3417 * as an error???3418 */3419free_fragment_list(patch->fragments);3420 patch->fragments = NULL;3421}else if(status) {3422returnerror(_("read of%sfailed"), patch->old_name);3423}3424}34253426 img =strbuf_detach(&buf, &len);3427prepare_image(image, img, len, !patch->is_binary);3428return0;3429}34303431static intthree_way_merge(struct image *image,3432char*path,3433const unsigned char*base,3434const unsigned char*ours,3435const unsigned char*theirs)3436{3437 mmfile_t base_file, our_file, their_file;3438 mmbuffer_t result = { NULL };3439int status;34403441read_mmblob(&base_file, base);3442read_mmblob(&our_file, ours);3443read_mmblob(&their_file, theirs);3444 status =ll_merge(&result, path,3445&base_file,"base",3446&our_file,"ours",3447&their_file,"theirs", NULL);3448free(base_file.ptr);3449free(our_file.ptr);3450free(their_file.ptr);3451if(status <0|| !result.ptr) {3452free(result.ptr);3453return-1;3454}3455clear_image(image);3456 image->buf = result.ptr;3457 image->len = result.size;34583459return status;3460}34613462/*3463 * When directly falling back to add/add three-way merge, we read from3464 * the current contents of the new_name. In no cases other than that3465 * this function will be called.3466 */3467static intload_current(struct apply_state *state,3468struct image *image,3469struct patch *patch)3470{3471struct strbuf buf = STRBUF_INIT;3472int status, pos;3473size_t len;3474char*img;3475struct stat st;3476struct cache_entry *ce;3477char*name = patch->new_name;3478unsigned mode = patch->new_mode;34793480if(!patch->is_new)3481die("BUG: patch to%sis not a creation", patch->old_name);34823483 pos =cache_name_pos(name,strlen(name));3484if(pos <0)3485returnerror(_("%s: does not exist in index"), name);3486 ce = active_cache[pos];3487if(lstat(name, &st)) {3488if(errno != ENOENT)3489returnerror(_("%s:%s"), name,strerror(errno));3490if(checkout_target(&the_index, ce, &st))3491return-1;3492}3493if(verify_index_match(ce, &st))3494returnerror(_("%s: does not match index"), name);34953496 status =load_patch_target(state, &buf, ce, &st, name, mode);3497if(status <0)3498return status;3499else if(status)3500return-1;3501 img =strbuf_detach(&buf, &len);3502prepare_image(image, img, len, !patch->is_binary);3503return0;3504}35053506static inttry_threeway(struct apply_state *state,3507struct image *image,3508struct patch *patch,3509struct stat *st,3510const struct cache_entry *ce)3511{3512unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3513struct strbuf buf = STRBUF_INIT;3514size_t len;3515int status;3516char*img;3517struct image tmp_image;35183519/* No point falling back to 3-way merge in these cases */3520if(patch->is_delete ||3521S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3522return-1;35233524/* Preimage the patch was prepared for */3525if(patch->is_new)3526write_sha1_file("",0, blob_type, pre_sha1);3527else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3528read_blob_object(&buf, pre_sha1, patch->old_mode))3529returnerror("repository lacks the necessary blob to fall back on 3-way merge.");35303531fprintf(stderr,"Falling back to three-way merge...\n");35323533 img =strbuf_detach(&buf, &len);3534prepare_image(&tmp_image, img, len,1);3535/* Apply the patch to get the post image */3536if(apply_fragments(state, &tmp_image, patch) <0) {3537clear_image(&tmp_image);3538return-1;3539}3540/* post_sha1[] is theirs */3541write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3542clear_image(&tmp_image);35433544/* our_sha1[] is ours */3545if(patch->is_new) {3546if(load_current(state, &tmp_image, patch))3547returnerror("cannot read the current contents of '%s'",3548 patch->new_name);3549}else{3550if(load_preimage(state, &tmp_image, patch, st, ce))3551returnerror("cannot read the current contents of '%s'",3552 patch->old_name);3553}3554write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3555clear_image(&tmp_image);35563557/* in-core three-way merge between post and our using pre as base */3558 status =three_way_merge(image, patch->new_name,3559 pre_sha1, our_sha1, post_sha1);3560if(status <0) {3561fprintf(stderr,"Failed to fall back on three-way merge...\n");3562return status;3563}35643565if(status) {3566 patch->conflicted_threeway =1;3567if(patch->is_new)3568oidclr(&patch->threeway_stage[0]);3569else3570hashcpy(patch->threeway_stage[0].hash, pre_sha1);3571hashcpy(patch->threeway_stage[1].hash, our_sha1);3572hashcpy(patch->threeway_stage[2].hash, post_sha1);3573fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3574}else{3575fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3576}3577return0;3578}35793580static intapply_data(struct apply_state *state,struct patch *patch,3581struct stat *st,const struct cache_entry *ce)3582{3583struct image image;35843585if(load_preimage(state, &image, patch, st, ce) <0)3586return-1;35873588if(patch->direct_to_threeway ||3589apply_fragments(state, &image, patch) <0) {3590/* Note: with --reject, apply_fragments() returns 0 */3591if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3592return-1;3593}3594 patch->result = image.buf;3595 patch->resultsize = image.len;3596add_to_fn_table(state, patch);3597free(image.line_allocated);35983599if(0< patch->is_delete && patch->resultsize)3600returnerror(_("removal patch leaves file contents"));36013602return0;3603}36043605/*3606 * If "patch" that we are looking at modifies or deletes what we have,3607 * we would want it not to lose any local modification we have, either3608 * in the working tree or in the index.3609 *3610 * This also decides if a non-git patch is a creation patch or a3611 * modification to an existing empty file. We do not check the state3612 * of the current tree for a creation patch in this function; the caller3613 * check_patch() separately makes sure (and errors out otherwise) that3614 * the path the patch creates does not exist in the current tree.3615 */3616static intcheck_preimage(struct apply_state *state,3617struct patch *patch,3618struct cache_entry **ce,3619struct stat *st)3620{3621const char*old_name = patch->old_name;3622struct patch *previous = NULL;3623int stat_ret =0, status;3624unsigned st_mode =0;36253626if(!old_name)3627return0;36283629assert(patch->is_new <=0);3630 previous =previous_patch(state, patch, &status);36313632if(status)3633returnerror(_("path%shas been renamed/deleted"), old_name);3634if(previous) {3635 st_mode = previous->new_mode;3636}else if(!state->cached) {3637 stat_ret =lstat(old_name, st);3638if(stat_ret && errno != ENOENT)3639returnerror(_("%s:%s"), old_name,strerror(errno));3640}36413642if(state->check_index && !previous) {3643int pos =cache_name_pos(old_name,strlen(old_name));3644if(pos <0) {3645if(patch->is_new <0)3646goto is_new;3647returnerror(_("%s: does not exist in index"), old_name);3648}3649*ce = active_cache[pos];3650if(stat_ret <0) {3651if(checkout_target(&the_index, *ce, st))3652return-1;3653}3654if(!state->cached &&verify_index_match(*ce, st))3655returnerror(_("%s: does not match index"), old_name);3656if(state->cached)3657 st_mode = (*ce)->ce_mode;3658}else if(stat_ret <0) {3659if(patch->is_new <0)3660goto is_new;3661returnerror(_("%s:%s"), old_name,strerror(errno));3662}36633664if(!state->cached && !previous)3665 st_mode =ce_mode_from_stat(*ce, st->st_mode);36663667if(patch->is_new <0)3668 patch->is_new =0;3669if(!patch->old_mode)3670 patch->old_mode = st_mode;3671if((st_mode ^ patch->old_mode) & S_IFMT)3672returnerror(_("%s: wrong type"), old_name);3673if(st_mode != patch->old_mode)3674warning(_("%shas type%o, expected%o"),3675 old_name, st_mode, patch->old_mode);3676if(!patch->new_mode && !patch->is_delete)3677 patch->new_mode = st_mode;3678return0;36793680 is_new:3681 patch->is_new =1;3682 patch->is_delete =0;3683free(patch->old_name);3684 patch->old_name = NULL;3685return0;3686}368736883689#define EXISTS_IN_INDEX 13690#define EXISTS_IN_WORKTREE 236913692static intcheck_to_create(struct apply_state *state,3693const char*new_name,3694int ok_if_exists)3695{3696struct stat nst;36973698if(state->check_index &&3699cache_name_pos(new_name,strlen(new_name)) >=0&&3700!ok_if_exists)3701return EXISTS_IN_INDEX;3702if(state->cached)3703return0;37043705if(!lstat(new_name, &nst)) {3706if(S_ISDIR(nst.st_mode) || ok_if_exists)3707return0;3708/*3709 * A leading component of new_name might be a symlink3710 * that is going to be removed with this patch, but3711 * still pointing at somewhere that has the path.3712 * In such a case, path "new_name" does not exist as3713 * far as git is concerned.3714 */3715if(has_symlink_leading_path(new_name,strlen(new_name)))3716return0;37173718return EXISTS_IN_WORKTREE;3719}else if((errno != ENOENT) && (errno != ENOTDIR)) {3720returnerror("%s:%s", new_name,strerror(errno));3721}3722return0;3723}37243725static uintptr_tregister_symlink_changes(struct apply_state *state,3726const char*path,3727uintptr_t what)3728{3729struct string_list_item *ent;37303731 ent =string_list_lookup(&state->symlink_changes, path);3732if(!ent) {3733 ent =string_list_insert(&state->symlink_changes, path);3734 ent->util = (void*)0;3735}3736 ent->util = (void*)(what | ((uintptr_t)ent->util));3737return(uintptr_t)ent->util;3738}37393740static uintptr_tcheck_symlink_changes(struct apply_state *state,const char*path)3741{3742struct string_list_item *ent;37433744 ent =string_list_lookup(&state->symlink_changes, path);3745if(!ent)3746return0;3747return(uintptr_t)ent->util;3748}37493750static voidprepare_symlink_changes(struct apply_state *state,struct patch *patch)3751{3752for( ; patch; patch = patch->next) {3753if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3754(patch->is_rename || patch->is_delete))3755/* the symlink at patch->old_name is removed */3756register_symlink_changes(state, patch->old_name, SYMLINK_GOES_AWAY);37573758if(patch->new_name &&S_ISLNK(patch->new_mode))3759/* the symlink at patch->new_name is created or remains */3760register_symlink_changes(state, patch->new_name, SYMLINK_IN_RESULT);3761}3762}37633764static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3765{3766do{3767unsigned int change;37683769while(--name->len && name->buf[name->len] !='/')3770;/* scan backwards */3771if(!name->len)3772break;3773 name->buf[name->len] ='\0';3774 change =check_symlink_changes(state, name->buf);3775if(change & SYMLINK_IN_RESULT)3776return1;3777if(change & SYMLINK_GOES_AWAY)3778/*3779 * This cannot be "return 0", because we may3780 * see a new one created at a higher level.3781 */3782continue;37833784/* otherwise, check the preimage */3785if(state->check_index) {3786struct cache_entry *ce;37873788 ce =cache_file_exists(name->buf, name->len, ignore_case);3789if(ce &&S_ISLNK(ce->ce_mode))3790return1;3791}else{3792struct stat st;3793if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3794return1;3795}3796}while(1);3797return0;3798}37993800static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3801{3802int ret;3803struct strbuf name = STRBUF_INIT;38043805assert(*name_ !='\0');3806strbuf_addstr(&name, name_);3807 ret =path_is_beyond_symlink_1(state, &name);3808strbuf_release(&name);38093810return ret;3811}38123813static voiddie_on_unsafe_path(struct patch *patch)3814{3815const char*old_name = NULL;3816const char*new_name = NULL;3817if(patch->is_delete)3818 old_name = patch->old_name;3819else if(!patch->is_new && !patch->is_copy)3820 old_name = patch->old_name;3821if(!patch->is_delete)3822 new_name = patch->new_name;38233824if(old_name && !verify_path(old_name))3825die(_("invalid path '%s'"), old_name);3826if(new_name && !verify_path(new_name))3827die(_("invalid path '%s'"), new_name);3828}38293830/*3831 * Check and apply the patch in-core; leave the result in patch->result3832 * for the caller to write it out to the final destination.3833 */3834static intcheck_patch(struct apply_state *state,struct patch *patch)3835{3836struct stat st;3837const char*old_name = patch->old_name;3838const char*new_name = patch->new_name;3839const char*name = old_name ? old_name : new_name;3840struct cache_entry *ce = NULL;3841struct patch *tpatch;3842int ok_if_exists;3843int status;38443845 patch->rejected =1;/* we will drop this after we succeed */38463847 status =check_preimage(state, patch, &ce, &st);3848if(status)3849return status;3850 old_name = patch->old_name;38513852/*3853 * A type-change diff is always split into a patch to delete3854 * old, immediately followed by a patch to create new (see3855 * diff.c::run_diff()); in such a case it is Ok that the entry3856 * to be deleted by the previous patch is still in the working3857 * tree and in the index.3858 *3859 * A patch to swap-rename between A and B would first rename A3860 * to B and then rename B to A. While applying the first one,3861 * the presence of B should not stop A from getting renamed to3862 * B; ask to_be_deleted() about the later rename. Removal of3863 * B and rename from A to B is handled the same way by asking3864 * was_deleted().3865 */3866if((tpatch =in_fn_table(state, new_name)) &&3867(was_deleted(tpatch) ||to_be_deleted(tpatch)))3868 ok_if_exists =1;3869else3870 ok_if_exists =0;38713872if(new_name &&3873((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3874int err =check_to_create(state, new_name, ok_if_exists);38753876if(err && state->threeway) {3877 patch->direct_to_threeway =1;3878}else switch(err) {3879case0:3880break;/* happy */3881case EXISTS_IN_INDEX:3882returnerror(_("%s: already exists in index"), new_name);3883break;3884case EXISTS_IN_WORKTREE:3885returnerror(_("%s: already exists in working directory"),3886 new_name);3887default:3888return err;3889}38903891if(!patch->new_mode) {3892if(0< patch->is_new)3893 patch->new_mode = S_IFREG |0644;3894else3895 patch->new_mode = patch->old_mode;3896}3897}38983899if(new_name && old_name) {3900int same = !strcmp(old_name, new_name);3901if(!patch->new_mode)3902 patch->new_mode = patch->old_mode;3903if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3904if(same)3905returnerror(_("new mode (%o) of%sdoes not "3906"match old mode (%o)"),3907 patch->new_mode, new_name,3908 patch->old_mode);3909else3910returnerror(_("new mode (%o) of%sdoes not "3911"match old mode (%o) of%s"),3912 patch->new_mode, new_name,3913 patch->old_mode, old_name);3914}3915}39163917if(!state->unsafe_paths)3918die_on_unsafe_path(patch);39193920/*3921 * An attempt to read from or delete a path that is beyond a3922 * symbolic link will be prevented by load_patch_target() that3923 * is called at the beginning of apply_data() so we do not3924 * have to worry about a patch marked with "is_delete" bit3925 * here. We however need to make sure that the patch result3926 * is not deposited to a path that is beyond a symbolic link3927 * here.3928 */3929if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3930returnerror(_("affected file '%s' is beyond a symbolic link"),3931 patch->new_name);39323933if(apply_data(state, patch, &st, ce) <0)3934returnerror(_("%s: patch does not apply"), name);3935 patch->rejected =0;3936return0;3937}39383939static intcheck_patch_list(struct apply_state *state,struct patch *patch)3940{3941int err =0;39423943prepare_symlink_changes(state, patch);3944prepare_fn_table(state, patch);3945while(patch) {3946if(state->apply_verbosely)3947say_patch_name(stderr,3948_("Checking patch%s..."), patch);3949 err |=check_patch(state, patch);3950 patch = patch->next;3951}3952return err;3953}39543955/* This function tries to read the sha1 from the current index */3956static intget_current_sha1(const char*path,unsigned char*sha1)3957{3958int pos;39593960if(read_cache() <0)3961return-1;3962 pos =cache_name_pos(path,strlen(path));3963if(pos <0)3964return-1;3965hashcpy(sha1, active_cache[pos]->sha1);3966return0;3967}39683969static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3970{3971/*3972 * A usable gitlink patch has only one fragment (hunk) that looks like:3973 * @@ -1 +1 @@3974 * -Subproject commit <old sha1>3975 * +Subproject commit <new sha1>3976 * or3977 * @@ -1 +0,0 @@3978 * -Subproject commit <old sha1>3979 * for a removal patch.3980 */3981struct fragment *hunk = p->fragments;3982static const char heading[] ="-Subproject commit ";3983char*preimage;39843985if(/* does the patch have only one hunk? */3986 hunk && !hunk->next &&3987/* is its preimage one line? */3988 hunk->oldpos ==1&& hunk->oldlines ==1&&3989/* does preimage begin with the heading? */3990(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3991starts_with(++preimage, heading) &&3992/* does it record full SHA-1? */3993!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3994 preimage[sizeof(heading) +40-1] =='\n'&&3995/* does the abbreviated name on the index line agree with it? */3996starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3997return0;/* it all looks fine */39983999/* we may have full object name on the index line */4000returnget_sha1_hex(p->old_sha1_prefix, sha1);4001}40024003/* Build an index that contains the just the files needed for a 3way merge */4004static voidbuild_fake_ancestor(struct patch *list,const char*filename)4005{4006struct patch *patch;4007struct index_state result = { NULL };4008static struct lock_file lock;40094010/* Once we start supporting the reverse patch, it may be4011 * worth showing the new sha1 prefix, but until then...4012 */4013for(patch = list; patch; patch = patch->next) {4014unsigned char sha1[20];4015struct cache_entry *ce;4016const char*name;40174018 name = patch->old_name ? patch->old_name : patch->new_name;4019if(0< patch->is_new)4020continue;40214022if(S_ISGITLINK(patch->old_mode)) {4023if(!preimage_sha1_in_gitlink_patch(patch, sha1))4024;/* ok, the textual part looks sane */4025else4026die("sha1 information is lacking or useless for submodule%s",4027 name);4028}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {4029;/* ok */4030}else if(!patch->lines_added && !patch->lines_deleted) {4031/* mode-only change: update the current */4032if(get_current_sha1(patch->old_name, sha1))4033die("mode change for%s, which is not "4034"in current HEAD", name);4035}else4036die("sha1 information is lacking or useless "4037"(%s).", name);40384039 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);4040if(!ce)4041die(_("make_cache_entry failed for path '%s'"), name);4042if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))4043die("Could not add%sto temporary index", name);4044}40454046hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);4047if(write_locked_index(&result, &lock, COMMIT_LOCK))4048die("Could not write temporary index to%s", filename);40494050discard_index(&result);4051}40524053static voidstat_patch_list(struct apply_state *state,struct patch *patch)4054{4055int files, adds, dels;40564057for(files = adds = dels =0; patch ; patch = patch->next) {4058 files++;4059 adds += patch->lines_added;4060 dels += patch->lines_deleted;4061show_stats(state, patch);4062}40634064print_stat_summary(stdout, files, adds, dels);4065}40664067static voidnumstat_patch_list(struct apply_state *state,4068struct patch *patch)4069{4070for( ; patch; patch = patch->next) {4071const char*name;4072 name = patch->new_name ? patch->new_name : patch->old_name;4073if(patch->is_binary)4074printf("-\t-\t");4075else4076printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4077write_name_quoted(name, stdout, state->line_termination);4078}4079}40804081static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4082{4083if(mode)4084printf("%smode%06o%s\n", newdelete, mode, name);4085else4086printf("%s %s\n", newdelete, name);4087}40884089static voidshow_mode_change(struct patch *p,int show_name)4090{4091if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4092if(show_name)4093printf(" mode change%06o =>%06o%s\n",4094 p->old_mode, p->new_mode, p->new_name);4095else4096printf(" mode change%06o =>%06o\n",4097 p->old_mode, p->new_mode);4098}4099}41004101static voidshow_rename_copy(struct patch *p)4102{4103const char*renamecopy = p->is_rename ?"rename":"copy";4104const char*old, *new;41054106/* Find common prefix */4107 old = p->old_name;4108new= p->new_name;4109while(1) {4110const char*slash_old, *slash_new;4111 slash_old =strchr(old,'/');4112 slash_new =strchr(new,'/');4113if(!slash_old ||4114!slash_new ||4115 slash_old - old != slash_new -new||4116memcmp(old,new, slash_new -new))4117break;4118 old = slash_old +1;4119new= slash_new +1;4120}4121/* p->old_name thru old is the common prefix, and old and new4122 * through the end of names are renames4123 */4124if(old != p->old_name)4125printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4126(int)(old - p->old_name), p->old_name,4127 old,new, p->score);4128else4129printf("%s %s=>%s(%d%%)\n", renamecopy,4130 p->old_name, p->new_name, p->score);4131show_mode_change(p,0);4132}41334134static voidsummary_patch_list(struct patch *patch)4135{4136struct patch *p;41374138for(p = patch; p; p = p->next) {4139if(p->is_new)4140show_file_mode_name("create", p->new_mode, p->new_name);4141else if(p->is_delete)4142show_file_mode_name("delete", p->old_mode, p->old_name);4143else{4144if(p->is_rename || p->is_copy)4145show_rename_copy(p);4146else{4147if(p->score) {4148printf(" rewrite%s(%d%%)\n",4149 p->new_name, p->score);4150show_mode_change(p,0);4151}4152else4153show_mode_change(p,1);4154}4155}4156}4157}41584159static voidpatch_stats(struct apply_state *state,struct patch *patch)4160{4161int lines = patch->lines_added + patch->lines_deleted;41624163if(lines > state->max_change)4164 state->max_change = lines;4165if(patch->old_name) {4166int len =quote_c_style(patch->old_name, NULL, NULL,0);4167if(!len)4168 len =strlen(patch->old_name);4169if(len > state->max_len)4170 state->max_len = len;4171}4172if(patch->new_name) {4173int len =quote_c_style(patch->new_name, NULL, NULL,0);4174if(!len)4175 len =strlen(patch->new_name);4176if(len > state->max_len)4177 state->max_len = len;4178}4179}41804181static voidremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4182{4183if(state->update_index) {4184if(remove_file_from_cache(patch->old_name) <0)4185die(_("unable to remove%sfrom index"), patch->old_name);4186}4187if(!state->cached) {4188if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4189remove_path(patch->old_name);4190}4191}4192}41934194static voidadd_index_file(struct apply_state *state,4195const char*path,4196unsigned mode,4197void*buf,4198unsigned long size)4199{4200struct stat st;4201struct cache_entry *ce;4202int namelen =strlen(path);4203unsigned ce_size =cache_entry_size(namelen);42044205if(!state->update_index)4206return;42074208 ce =xcalloc(1, ce_size);4209memcpy(ce->name, path, namelen);4210 ce->ce_mode =create_ce_mode(mode);4211 ce->ce_flags =create_ce_flags(0);4212 ce->ce_namelen = namelen;4213if(S_ISGITLINK(mode)) {4214const char*s;42154216if(!skip_prefix(buf,"Subproject commit ", &s) ||4217get_sha1_hex(s, ce->sha1))4218die(_("corrupt patch for submodule%s"), path);4219}else{4220if(!state->cached) {4221if(lstat(path, &st) <0)4222die_errno(_("unable to stat newly created file '%s'"),4223 path);4224fill_stat_cache_info(ce, &st);4225}4226if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4227die(_("unable to create backing store for newly created file%s"), path);4228}4229if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4230die(_("unable to add cache entry for%s"), path);4231}42324233static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4234{4235int fd;4236struct strbuf nbuf = STRBUF_INIT;42374238if(S_ISGITLINK(mode)) {4239struct stat st;4240if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4241return0;4242returnmkdir(path,0777);4243}42444245if(has_symlinks &&S_ISLNK(mode))4246/* Although buf:size is counted string, it also is NUL4247 * terminated.4248 */4249returnsymlink(buf, path);42504251 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4252if(fd <0)4253return-1;42544255if(convert_to_working_tree(path, buf, size, &nbuf)) {4256 size = nbuf.len;4257 buf = nbuf.buf;4258}4259write_or_die(fd, buf, size);4260strbuf_release(&nbuf);42614262if(close(fd) <0)4263die_errno(_("closing file '%s'"), path);4264return0;4265}42664267/*4268 * We optimistically assume that the directories exist,4269 * which is true 99% of the time anyway. If they don't,4270 * we create them and try again.4271 */4272static voidcreate_one_file(struct apply_state *state,4273char*path,4274unsigned mode,4275const char*buf,4276unsigned long size)4277{4278if(state->cached)4279return;4280if(!try_create_file(path, mode, buf, size))4281return;42824283if(errno == ENOENT) {4284if(safe_create_leading_directories(path))4285return;4286if(!try_create_file(path, mode, buf, size))4287return;4288}42894290if(errno == EEXIST || errno == EACCES) {4291/* We may be trying to create a file where a directory4292 * used to be.4293 */4294struct stat st;4295if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4296 errno = EEXIST;4297}42984299if(errno == EEXIST) {4300unsigned int nr =getpid();43014302for(;;) {4303char newpath[PATH_MAX];4304mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4305if(!try_create_file(newpath, mode, buf, size)) {4306if(!rename(newpath, path))4307return;4308unlink_or_warn(newpath);4309break;4310}4311if(errno != EEXIST)4312break;4313++nr;4314}4315}4316die_errno(_("unable to write file '%s' mode%o"), path, mode);4317}43184319static voidadd_conflicted_stages_file(struct apply_state *state,4320struct patch *patch)4321{4322int stage, namelen;4323unsigned ce_size, mode;4324struct cache_entry *ce;43254326if(!state->update_index)4327return;4328 namelen =strlen(patch->new_name);4329 ce_size =cache_entry_size(namelen);4330 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);43314332remove_file_from_cache(patch->new_name);4333for(stage =1; stage <4; stage++) {4334if(is_null_oid(&patch->threeway_stage[stage -1]))4335continue;4336 ce =xcalloc(1, ce_size);4337memcpy(ce->name, patch->new_name, namelen);4338 ce->ce_mode =create_ce_mode(mode);4339 ce->ce_flags =create_ce_flags(stage);4340 ce->ce_namelen = namelen;4341hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4342if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4343die(_("unable to add cache entry for%s"), patch->new_name);4344}4345}43464347static voidcreate_file(struct apply_state *state,struct patch *patch)4348{4349char*path = patch->new_name;4350unsigned mode = patch->new_mode;4351unsigned long size = patch->resultsize;4352char*buf = patch->result;43534354if(!mode)4355 mode = S_IFREG |0644;4356create_one_file(state, path, mode, buf, size);43574358if(patch->conflicted_threeway)4359add_conflicted_stages_file(state, patch);4360else4361add_index_file(state, path, mode, buf, size);4362}43634364/* phase zero is to remove, phase one is to create */4365static voidwrite_out_one_result(struct apply_state *state,4366struct patch *patch,4367int phase)4368{4369if(patch->is_delete >0) {4370if(phase ==0)4371remove_file(state, patch,1);4372return;4373}4374if(patch->is_new >0|| patch->is_copy) {4375if(phase ==1)4376create_file(state, patch);4377return;4378}4379/*4380 * Rename or modification boils down to the same4381 * thing: remove the old, write the new4382 */4383if(phase ==0)4384remove_file(state, patch, patch->is_rename);4385if(phase ==1)4386create_file(state, patch);4387}43884389static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4390{4391FILE*rej;4392char namebuf[PATH_MAX];4393struct fragment *frag;4394int cnt =0;4395struct strbuf sb = STRBUF_INIT;43964397for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4398if(!frag->rejected)4399continue;4400 cnt++;4401}44024403if(!cnt) {4404if(state->apply_verbosely)4405say_patch_name(stderr,4406_("Applied patch%scleanly."), patch);4407return0;4408}44094410/* This should not happen, because a removal patch that leaves4411 * contents are marked "rejected" at the patch level.4412 */4413if(!patch->new_name)4414die(_("internal error"));44154416/* Say this even without --verbose */4417strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4418"Applying patch %%swith%drejects...",4419 cnt),4420 cnt);4421say_patch_name(stderr, sb.buf, patch);4422strbuf_release(&sb);44234424 cnt =strlen(patch->new_name);4425if(ARRAY_SIZE(namebuf) <= cnt +5) {4426 cnt =ARRAY_SIZE(namebuf) -5;4427warning(_("truncating .rej filename to %.*s.rej"),4428 cnt -1, patch->new_name);4429}4430memcpy(namebuf, patch->new_name, cnt);4431memcpy(namebuf + cnt,".rej",5);44324433 rej =fopen(namebuf,"w");4434if(!rej)4435returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));44364437/* Normal git tools never deal with .rej, so do not pretend4438 * this is a git patch by saying --git or giving extended4439 * headers. While at it, maybe please "kompare" that wants4440 * the trailing TAB and some garbage at the end of line ;-).4441 */4442fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4443 patch->new_name, patch->new_name);4444for(cnt =1, frag = patch->fragments;4445 frag;4446 cnt++, frag = frag->next) {4447if(!frag->rejected) {4448fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4449continue;4450}4451fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4452fprintf(rej,"%.*s", frag->size, frag->patch);4453if(frag->patch[frag->size-1] !='\n')4454fputc('\n', rej);4455}4456fclose(rej);4457return-1;4458}44594460static intwrite_out_results(struct apply_state *state,struct patch *list)4461{4462int phase;4463int errs =0;4464struct patch *l;4465struct string_list cpath = STRING_LIST_INIT_DUP;44664467for(phase =0; phase <2; phase++) {4468 l = list;4469while(l) {4470if(l->rejected)4471 errs =1;4472else{4473write_out_one_result(state, l, phase);4474if(phase ==1) {4475if(write_out_one_reject(state, l))4476 errs =1;4477if(l->conflicted_threeway) {4478string_list_append(&cpath, l->new_name);4479 errs =1;4480}4481}4482}4483 l = l->next;4484}4485}44864487if(cpath.nr) {4488struct string_list_item *item;44894490string_list_sort(&cpath);4491for_each_string_list_item(item, &cpath)4492fprintf(stderr,"U%s\n", item->string);4493string_list_clear(&cpath,0);44944495rerere(0);4496}44974498return errs;4499}45004501static struct lock_file lock_file;45024503#define INACCURATE_EOF (1<<0)4504#define RECOUNT (1<<1)45054506static intapply_patch(struct apply_state *state,4507int fd,4508const char*filename,4509int options)4510{4511size_t offset;4512struct strbuf buf = STRBUF_INIT;/* owns the patch text */4513struct patch *list = NULL, **listp = &list;4514int skipped_patch =0;45154516 state->patch_input_file = filename;4517read_patch_file(&buf, fd);4518 offset =0;4519while(offset < buf.len) {4520struct patch *patch;4521int nr;45224523 patch =xcalloc(1,sizeof(*patch));4524 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4525 patch->recount = !!(options & RECOUNT);4526 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4527if(nr <0) {4528free_patch(patch);4529break;4530}4531if(state->apply_in_reverse)4532reverse_patches(patch);4533if(use_patch(state, patch)) {4534patch_stats(state, patch);4535*listp = patch;4536 listp = &patch->next;4537}4538else{4539if(state->apply_verbosely)4540say_patch_name(stderr,_("Skipped patch '%s'."), patch);4541free_patch(patch);4542 skipped_patch++;4543}4544 offset += nr;4545}45464547if(!list && !skipped_patch)4548die(_("unrecognized input"));45494550if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4551 state->apply =0;45524553 state->update_index = state->check_index && state->apply;4554if(state->update_index && state->newfd <0)4555 state->newfd =hold_locked_index(state->lock_file,1);45564557if(state->check_index) {4558if(read_cache() <0)4559die(_("unable to read index file"));4560}45614562if((state->check || state->apply) &&4563check_patch_list(state, list) <0&&4564!state->apply_with_reject)4565exit(1);45664567if(state->apply &&write_out_results(state, list)) {4568if(state->apply_with_reject)4569exit(1);4570/* with --3way, we still need to write the index out */4571return1;4572}45734574if(state->fake_ancestor)4575build_fake_ancestor(list, state->fake_ancestor);45764577if(state->diffstat)4578stat_patch_list(state, list);45794580if(state->numstat)4581numstat_patch_list(state, list);45824583if(state->summary)4584summary_patch_list(list);45854586free_patch_list(list);4587strbuf_release(&buf);4588string_list_clear(&state->fn_table,0);4589return0;4590}45914592static voidgit_apply_config(void)4593{4594git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4595git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4596git_config(git_default_config, NULL);4597}45984599static intoption_parse_exclude(const struct option *opt,4600const char*arg,int unset)4601{4602struct apply_state *state = opt->value;4603add_name_limit(state, arg,1);4604return0;4605}46064607static intoption_parse_include(const struct option *opt,4608const char*arg,int unset)4609{4610struct apply_state *state = opt->value;4611add_name_limit(state, arg,0);4612 state->has_include =1;4613return0;4614}46154616static intoption_parse_p(const struct option *opt,4617const char*arg,4618int unset)4619{4620struct apply_state *state = opt->value;4621 state->p_value =atoi(arg);4622 state->p_value_known =1;4623return0;4624}46254626static intoption_parse_space_change(const struct option *opt,4627const char*arg,int unset)4628{4629struct apply_state *state = opt->value;4630if(unset)4631 state->ws_ignore_action = ignore_ws_none;4632else4633 state->ws_ignore_action = ignore_ws_change;4634return0;4635}46364637static intoption_parse_whitespace(const struct option *opt,4638const char*arg,int unset)4639{4640struct apply_state *state = opt->value;4641 state->whitespace_option = arg;4642parse_whitespace_option(state, arg);4643return0;4644}46454646static intoption_parse_directory(const struct option *opt,4647const char*arg,int unset)4648{4649struct apply_state *state = opt->value;4650strbuf_reset(&state->root);4651strbuf_addstr(&state->root, arg);4652strbuf_complete(&state->root,'/');4653return0;4654}46554656static voidinit_apply_state(struct apply_state *state,4657const char*prefix,4658struct lock_file *lock_file)4659{4660memset(state,0,sizeof(*state));4661 state->prefix = prefix;4662 state->prefix_length = state->prefix ?strlen(state->prefix) :0;4663 state->lock_file = lock_file;4664 state->newfd = -1;4665 state->apply =1;4666 state->line_termination ='\n';4667 state->p_value =1;4668 state->p_context = UINT_MAX;4669 state->squelch_whitespace_errors =5;4670 state->ws_error_action = warn_on_ws_error;4671 state->ws_ignore_action = ignore_ws_none;4672 state->linenr =1;4673strbuf_init(&state->root,0);46744675git_apply_config();4676if(apply_default_whitespace)4677parse_whitespace_option(state, apply_default_whitespace);4678if(apply_default_ignorewhitespace)4679parse_ignorewhitespace_option(state, apply_default_ignorewhitespace);4680}46814682static voidclear_apply_state(struct apply_state *state)4683{4684string_list_clear(&state->limit_by_name,0);4685string_list_clear(&state->symlink_changes,0);4686strbuf_release(&state->root);46874688/* &state->fn_table is cleared at the end of apply_patch() */4689}46904691static voidcheck_apply_state(struct apply_state *state,int force_apply)4692{4693int is_not_gitdir = !startup_info->have_repository;46944695if(state->apply_with_reject && state->threeway)4696die("--reject and --3way cannot be used together.");4697if(state->cached && state->threeway)4698die("--cached and --3way cannot be used together.");4699if(state->threeway) {4700if(is_not_gitdir)4701die(_("--3way outside a repository"));4702 state->check_index =1;4703}4704if(state->apply_with_reject)4705 state->apply = state->apply_verbosely =1;4706if(!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor))4707 state->apply =0;4708if(state->check_index && is_not_gitdir)4709die(_("--index outside a repository"));4710if(state->cached) {4711if(is_not_gitdir)4712die(_("--cached outside a repository"));4713 state->check_index =1;4714}4715if(state->check_index)4716 state->unsafe_paths =0;4717if(!state->lock_file)4718die("BUG: state->lock_file should not be NULL");4719}47204721static intapply_all_patches(struct apply_state *state,4722int argc,4723const char**argv,4724int options)4725{4726int i;4727int errs =0;4728int read_stdin =1;47294730for(i =0; i < argc; i++) {4731const char*arg = argv[i];4732int fd;47334734if(!strcmp(arg,"-")) {4735 errs |=apply_patch(state,0,"<stdin>", options);4736 read_stdin =0;4737continue;4738}else if(0< state->prefix_length)4739 arg =prefix_filename(state->prefix,4740 state->prefix_length,4741 arg);47424743 fd =open(arg, O_RDONLY);4744if(fd <0)4745die_errno(_("can't open patch '%s'"), arg);4746 read_stdin =0;4747set_default_whitespace_mode(state);4748 errs |=apply_patch(state, fd, arg, options);4749close(fd);4750}4751set_default_whitespace_mode(state);4752if(read_stdin)4753 errs |=apply_patch(state,0,"<stdin>", options);47544755if(state->whitespace_error) {4756if(state->squelch_whitespace_errors &&4757 state->squelch_whitespace_errors < state->whitespace_error) {4758int squelched =4759 state->whitespace_error - state->squelch_whitespace_errors;4760warning(Q_("squelched%dwhitespace error",4761"squelched%dwhitespace errors",4762 squelched),4763 squelched);4764}4765if(state->ws_error_action == die_on_ws_error)4766die(Q_("%dline adds whitespace errors.",4767"%dlines add whitespace errors.",4768 state->whitespace_error),4769 state->whitespace_error);4770if(state->applied_after_fixing_ws && state->apply)4771warning("%dline%sapplied after"4772" fixing whitespace errors.",4773 state->applied_after_fixing_ws,4774 state->applied_after_fixing_ws ==1?"":"s");4775else if(state->whitespace_error)4776warning(Q_("%dline adds whitespace errors.",4777"%dlines add whitespace errors.",4778 state->whitespace_error),4779 state->whitespace_error);4780}47814782if(state->update_index) {4783if(write_locked_index(&the_index, state->lock_file, COMMIT_LOCK))4784die(_("Unable to write new index file"));4785 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}