1/* 2 * apply.c 3 * 4 * Copyright (C) Linus Torvalds, 2005 5 * 6 * This applies patches on top of some (arbitrary) version of the SCM. 7 * 8 */ 9#include"cache.h" 10#include"lockfile.h" 11#include"cache-tree.h" 12#include"quote.h" 13#include"blob.h" 14#include"delta.h" 15#include"builtin.h" 16#include"string-list.h" 17#include"dir.h" 18#include"diff.h" 19#include"parse-options.h" 20#include"xdiff-interface.h" 21#include"ll-merge.h" 22#include"rerere.h" 23 24struct apply_state { 25const char*prefix; 26int prefix_length; 27 28/* These control what gets looked at and modified */ 29int apply;/* this is not a dry-run */ 30int cached;/* apply to the index only */ 31int check;/* preimage must match working tree, don't actually apply */ 32int check_index;/* preimage must match the indexed version */ 33int update_index;/* check_index && apply */ 34 35/* These control cosmetic aspect of the output */ 36int diffstat;/* just show a diffstat, and don't actually apply */ 37int numstat;/* just show a numeric diffstat, and don't actually apply */ 38int summary;/* just report creation, deletion, etc, and don't actually apply */ 39 40/* These boolean parameters control how the apply is done */ 41int allow_overlap; 42int apply_in_reverse; 43int apply_with_reject; 44int apply_verbosely; 45int no_add; 46int threeway; 47int unidiff_zero; 48int unsafe_paths; 49 50/* Other non boolean parameters */ 51const char*fake_ancestor; 52const char*patch_input_file; 53int line_termination; 54struct strbuf root; 55int p_value; 56int p_value_known; 57unsigned int p_context; 58 59/* Exclude and include path parameters */ 60struct string_list limit_by_name; 61int has_include; 62 63/* These control whitespace errors */ 64const char*whitespace_option; 65int whitespace_error; 66}; 67 68static int newfd = -1; 69 70static const char*const apply_usage[] = { 71N_("git apply [<options>] [<patch>...]"), 72 NULL 73}; 74 75static enum ws_error_action { 76 nowarn_ws_error, 77 warn_on_ws_error, 78 die_on_ws_error, 79 correct_ws_error 80} ws_error_action = warn_on_ws_error; 81static int squelch_whitespace_errors =5; 82static int applied_after_fixing_ws; 83 84static enum ws_ignore { 85 ignore_ws_none, 86 ignore_ws_change 87} ws_ignore_action = ignore_ws_none; 88 89 90static voidparse_whitespace_option(const char*option) 91{ 92if(!option) { 93 ws_error_action = warn_on_ws_error; 94return; 95} 96if(!strcmp(option,"warn")) { 97 ws_error_action = warn_on_ws_error; 98return; 99} 100if(!strcmp(option,"nowarn")) { 101 ws_error_action = nowarn_ws_error; 102return; 103} 104if(!strcmp(option,"error")) { 105 ws_error_action = die_on_ws_error; 106return; 107} 108if(!strcmp(option,"error-all")) { 109 ws_error_action = die_on_ws_error; 110 squelch_whitespace_errors =0; 111return; 112} 113if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 114 ws_error_action = correct_ws_error; 115return; 116} 117die(_("unrecognized whitespace option '%s'"), option); 118} 119 120static voidparse_ignorewhitespace_option(const char*option) 121{ 122if(!option || !strcmp(option,"no") || 123!strcmp(option,"false") || !strcmp(option,"never") || 124!strcmp(option,"none")) { 125 ws_ignore_action = ignore_ws_none; 126return; 127} 128if(!strcmp(option,"change")) { 129 ws_ignore_action = ignore_ws_change; 130return; 131} 132die(_("unrecognized whitespace ignore option '%s'"), option); 133} 134 135static voidset_default_whitespace_mode(struct apply_state *state, 136const char*whitespace_option) 137{ 138if(!whitespace_option && !apply_default_whitespace) 139 ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 140} 141 142/* 143 * For "diff-stat" like behaviour, we keep track of the biggest change 144 * we've seen, and the longest filename. That allows us to do simple 145 * scaling. 146 */ 147static int max_change, max_len; 148 149/* 150 * Various "current state", notably line numbers and what 151 * file (and how) we're patching right now.. The "is_xxxx" 152 * things are flags, where -1 means "don't know yet". 153 */ 154static int state_linenr =1; 155 156/* 157 * This represents one "hunk" from a patch, starting with 158 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 159 * patch text is pointed at by patch, and its byte length 160 * is stored in size. leading and trailing are the number 161 * of context lines. 162 */ 163struct fragment { 164unsigned long leading, trailing; 165unsigned long oldpos, oldlines; 166unsigned long newpos, newlines; 167/* 168 * 'patch' is usually borrowed from buf in apply_patch(), 169 * but some codepaths store an allocated buffer. 170 */ 171const char*patch; 172unsigned free_patch:1, 173 rejected:1; 174int size; 175int linenr; 176struct fragment *next; 177}; 178 179/* 180 * When dealing with a binary patch, we reuse "leading" field 181 * to store the type of the binary hunk, either deflated "delta" 182 * or deflated "literal". 183 */ 184#define binary_patch_method leading 185#define BINARY_DELTA_DEFLATED 1 186#define BINARY_LITERAL_DEFLATED 2 187 188/* 189 * This represents a "patch" to a file, both metainfo changes 190 * such as creation/deletion, filemode and content changes represented 191 * as a series of fragments. 192 */ 193struct patch { 194char*new_name, *old_name, *def_name; 195unsigned int old_mode, new_mode; 196int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 197int rejected; 198unsigned ws_rule; 199int lines_added, lines_deleted; 200int score; 201unsigned int is_toplevel_relative:1; 202unsigned int inaccurate_eof:1; 203unsigned int is_binary:1; 204unsigned int is_copy:1; 205unsigned int is_rename:1; 206unsigned int recount:1; 207unsigned int conflicted_threeway:1; 208unsigned int direct_to_threeway:1; 209struct fragment *fragments; 210char*result; 211size_t resultsize; 212char old_sha1_prefix[41]; 213char new_sha1_prefix[41]; 214struct patch *next; 215 216/* three-way fallback result */ 217struct object_id threeway_stage[3]; 218}; 219 220static voidfree_fragment_list(struct fragment *list) 221{ 222while(list) { 223struct fragment *next = list->next; 224if(list->free_patch) 225free((char*)list->patch); 226free(list); 227 list = next; 228} 229} 230 231static voidfree_patch(struct patch *patch) 232{ 233free_fragment_list(patch->fragments); 234free(patch->def_name); 235free(patch->old_name); 236free(patch->new_name); 237free(patch->result); 238free(patch); 239} 240 241static voidfree_patch_list(struct patch *list) 242{ 243while(list) { 244struct patch *next = list->next; 245free_patch(list); 246 list = next; 247} 248} 249 250/* 251 * A line in a file, len-bytes long (includes the terminating LF, 252 * except for an incomplete line at the end if the file ends with 253 * one), and its contents hashes to 'hash'. 254 */ 255struct line { 256size_t len; 257unsigned hash :24; 258unsigned flag :8; 259#define LINE_COMMON 1 260#define LINE_PATCHED 2 261}; 262 263/* 264 * This represents a "file", which is an array of "lines". 265 */ 266struct image { 267char*buf; 268size_t len; 269size_t nr; 270size_t alloc; 271struct line *line_allocated; 272struct line *line; 273}; 274 275/* 276 * Records filenames that have been touched, in order to handle 277 * the case where more than one patches touch the same file. 278 */ 279 280static struct string_list fn_table; 281 282static uint32_thash_line(const char*cp,size_t len) 283{ 284size_t i; 285uint32_t h; 286for(i =0, h =0; i < len; i++) { 287if(!isspace(cp[i])) { 288 h = h *3+ (cp[i] &0xff); 289} 290} 291return h; 292} 293 294/* 295 * Compare lines s1 of length n1 and s2 of length n2, ignoring 296 * whitespace difference. Returns 1 if they match, 0 otherwise 297 */ 298static intfuzzy_matchlines(const char*s1,size_t n1, 299const char*s2,size_t n2) 300{ 301const char*last1 = s1 + n1 -1; 302const char*last2 = s2 + n2 -1; 303int result =0; 304 305/* ignore line endings */ 306while((*last1 =='\r') || (*last1 =='\n')) 307 last1--; 308while((*last2 =='\r') || (*last2 =='\n')) 309 last2--; 310 311/* skip leading whitespaces, if both begin with whitespace */ 312if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 313while(isspace(*s1) && (s1 <= last1)) 314 s1++; 315while(isspace(*s2) && (s2 <= last2)) 316 s2++; 317} 318/* early return if both lines are empty */ 319if((s1 > last1) && (s2 > last2)) 320return1; 321while(!result) { 322 result = *s1++ - *s2++; 323/* 324 * Skip whitespace inside. We check for whitespace on 325 * both buffers because we don't want "a b" to match 326 * "ab" 327 */ 328if(isspace(*s1) &&isspace(*s2)) { 329while(isspace(*s1) && s1 <= last1) 330 s1++; 331while(isspace(*s2) && s2 <= last2) 332 s2++; 333} 334/* 335 * If we reached the end on one side only, 336 * lines don't match 337 */ 338if( 339((s2 > last2) && (s1 <= last1)) || 340((s1 > last1) && (s2 <= last2))) 341return0; 342if((s1 > last1) && (s2 > last2)) 343break; 344} 345 346return!result; 347} 348 349static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 350{ 351ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 352 img->line_allocated[img->nr].len = len; 353 img->line_allocated[img->nr].hash =hash_line(bol, len); 354 img->line_allocated[img->nr].flag = flag; 355 img->nr++; 356} 357 358/* 359 * "buf" has the file contents to be patched (read from various sources). 360 * attach it to "image" and add line-based index to it. 361 * "image" now owns the "buf". 362 */ 363static voidprepare_image(struct image *image,char*buf,size_t len, 364int prepare_linetable) 365{ 366const char*cp, *ep; 367 368memset(image,0,sizeof(*image)); 369 image->buf = buf; 370 image->len = len; 371 372if(!prepare_linetable) 373return; 374 375 ep = image->buf + image->len; 376 cp = image->buf; 377while(cp < ep) { 378const char*next; 379for(next = cp; next < ep && *next !='\n'; next++) 380; 381if(next < ep) 382 next++; 383add_line_info(image, cp, next - cp,0); 384 cp = next; 385} 386 image->line = image->line_allocated; 387} 388 389static voidclear_image(struct image *image) 390{ 391free(image->buf); 392free(image->line_allocated); 393memset(image,0,sizeof(*image)); 394} 395 396/* fmt must contain _one_ %s and no other substitution */ 397static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 398{ 399struct strbuf sb = STRBUF_INIT; 400 401if(patch->old_name && patch->new_name && 402strcmp(patch->old_name, patch->new_name)) { 403quote_c_style(patch->old_name, &sb, NULL,0); 404strbuf_addstr(&sb," => "); 405quote_c_style(patch->new_name, &sb, NULL,0); 406}else{ 407const char*n = patch->new_name; 408if(!n) 409 n = patch->old_name; 410quote_c_style(n, &sb, NULL,0); 411} 412fprintf(output, fmt, sb.buf); 413fputc('\n', output); 414strbuf_release(&sb); 415} 416 417#define SLOP (16) 418 419static voidread_patch_file(struct strbuf *sb,int fd) 420{ 421if(strbuf_read(sb, fd,0) <0) 422die_errno("git apply: failed to read"); 423 424/* 425 * Make sure that we have some slop in the buffer 426 * so that we can do speculative "memcmp" etc, and 427 * see to it that it is NUL-filled. 428 */ 429strbuf_grow(sb, SLOP); 430memset(sb->buf + sb->len,0, SLOP); 431} 432 433static unsigned longlinelen(const char*buffer,unsigned long size) 434{ 435unsigned long len =0; 436while(size--) { 437 len++; 438if(*buffer++ =='\n') 439break; 440} 441return len; 442} 443 444static intis_dev_null(const char*str) 445{ 446returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 447} 448 449#define TERM_SPACE 1 450#define TERM_TAB 2 451 452static intname_terminate(const char*name,int namelen,int c,int terminate) 453{ 454if(c ==' '&& !(terminate & TERM_SPACE)) 455return0; 456if(c =='\t'&& !(terminate & TERM_TAB)) 457return0; 458 459return1; 460} 461 462/* remove double slashes to make --index work with such filenames */ 463static char*squash_slash(char*name) 464{ 465int i =0, j =0; 466 467if(!name) 468return NULL; 469 470while(name[i]) { 471if((name[j++] = name[i++]) =='/') 472while(name[i] =='/') 473 i++; 474} 475 name[j] ='\0'; 476return name; 477} 478 479static char*find_name_gnu(struct apply_state *state, 480const char*line, 481const char*def, 482int p_value) 483{ 484struct strbuf name = STRBUF_INIT; 485char*cp; 486 487/* 488 * Proposed "new-style" GNU patch/diff format; see 489 * http://marc.info/?l=git&m=112927316408690&w=2 490 */ 491if(unquote_c_style(&name, line, NULL)) { 492strbuf_release(&name); 493return NULL; 494} 495 496for(cp = name.buf; p_value; p_value--) { 497 cp =strchr(cp,'/'); 498if(!cp) { 499strbuf_release(&name); 500return NULL; 501} 502 cp++; 503} 504 505strbuf_remove(&name,0, cp - name.buf); 506if(state->root.len) 507strbuf_insert(&name,0, state->root.buf, state->root.len); 508returnsquash_slash(strbuf_detach(&name, NULL)); 509} 510 511static size_tsane_tz_len(const char*line,size_t len) 512{ 513const char*tz, *p; 514 515if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 516return0; 517 tz = line + len -strlen(" +0500"); 518 519if(tz[1] !='+'&& tz[1] !='-') 520return0; 521 522for(p = tz +2; p != line + len; p++) 523if(!isdigit(*p)) 524return0; 525 526return line + len - tz; 527} 528 529static size_ttz_with_colon_len(const char*line,size_t len) 530{ 531const char*tz, *p; 532 533if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 534return0; 535 tz = line + len -strlen(" +08:00"); 536 537if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 538return0; 539 p = tz +2; 540if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 541!isdigit(*p++) || !isdigit(*p++)) 542return0; 543 544return line + len - tz; 545} 546 547static size_tdate_len(const char*line,size_t len) 548{ 549const char*date, *p; 550 551if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 552return0; 553 p = date = line + len -strlen("72-02-05"); 554 555if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 556!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 557!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 558return0; 559 560if(date - line >=strlen("19") && 561isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 562 date -=strlen("19"); 563 564return line + len - date; 565} 566 567static size_tshort_time_len(const char*line,size_t len) 568{ 569const char*time, *p; 570 571if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 572return0; 573 p = time = line + len -strlen(" 07:01:32"); 574 575/* Permit 1-digit hours? */ 576if(*p++ !=' '|| 577!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 578!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 579!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 580return0; 581 582return line + len - time; 583} 584 585static size_tfractional_time_len(const char*line,size_t len) 586{ 587const char*p; 588size_t n; 589 590/* Expected format: 19:41:17.620000023 */ 591if(!len || !isdigit(line[len -1])) 592return0; 593 p = line + len -1; 594 595/* Fractional seconds. */ 596while(p > line &&isdigit(*p)) 597 p--; 598if(*p !='.') 599return0; 600 601/* Hours, minutes, and whole seconds. */ 602 n =short_time_len(line, p - line); 603if(!n) 604return0; 605 606return line + len - p + n; 607} 608 609static size_ttrailing_spaces_len(const char*line,size_t len) 610{ 611const char*p; 612 613/* Expected format: ' ' x (1 or more) */ 614if(!len || line[len -1] !=' ') 615return0; 616 617 p = line + len; 618while(p != line) { 619 p--; 620if(*p !=' ') 621return line + len - (p +1); 622} 623 624/* All spaces! */ 625return len; 626} 627 628static size_tdiff_timestamp_len(const char*line,size_t len) 629{ 630const char*end = line + len; 631size_t n; 632 633/* 634 * Posix: 2010-07-05 19:41:17 635 * GNU: 2010-07-05 19:41:17.620000023 -0500 636 */ 637 638if(!isdigit(end[-1])) 639return0; 640 641 n =sane_tz_len(line, end - line); 642if(!n) 643 n =tz_with_colon_len(line, end - line); 644 end -= n; 645 646 n =short_time_len(line, end - line); 647if(!n) 648 n =fractional_time_len(line, end - line); 649 end -= n; 650 651 n =date_len(line, end - line); 652if(!n)/* No date. Too bad. */ 653return0; 654 end -= n; 655 656if(end == line)/* No space before date. */ 657return0; 658if(end[-1] =='\t') {/* Success! */ 659 end--; 660return line + len - end; 661} 662if(end[-1] !=' ')/* No space before date. */ 663return0; 664 665/* Whitespace damage. */ 666 end -=trailing_spaces_len(line, end - line); 667return line + len - end; 668} 669 670static char*find_name_common(struct apply_state *state, 671const char*line, 672const char*def, 673int p_value, 674const char*end, 675int terminate) 676{ 677int len; 678const char*start = NULL; 679 680if(p_value ==0) 681 start = line; 682while(line != end) { 683char c = *line; 684 685if(!end &&isspace(c)) { 686if(c =='\n') 687break; 688if(name_terminate(start, line-start, c, terminate)) 689break; 690} 691 line++; 692if(c =='/'&& !--p_value) 693 start = line; 694} 695if(!start) 696returnsquash_slash(xstrdup_or_null(def)); 697 len = line - start; 698if(!len) 699returnsquash_slash(xstrdup_or_null(def)); 700 701/* 702 * Generally we prefer the shorter name, especially 703 * if the other one is just a variation of that with 704 * something else tacked on to the end (ie "file.orig" 705 * or "file~"). 706 */ 707if(def) { 708int deflen =strlen(def); 709if(deflen < len && !strncmp(start, def, deflen)) 710returnsquash_slash(xstrdup(def)); 711} 712 713if(state->root.len) { 714char*ret =xstrfmt("%s%.*s", state->root.buf, len, start); 715returnsquash_slash(ret); 716} 717 718returnsquash_slash(xmemdupz(start, len)); 719} 720 721static char*find_name(struct apply_state *state, 722const char*line, 723char*def, 724int p_value, 725int terminate) 726{ 727if(*line =='"') { 728char*name =find_name_gnu(state, line, def, p_value); 729if(name) 730return name; 731} 732 733returnfind_name_common(state, line, def, p_value, NULL, terminate); 734} 735 736static char*find_name_traditional(struct apply_state *state, 737const char*line, 738char*def, 739int p_value) 740{ 741size_t len; 742size_t date_len; 743 744if(*line =='"') { 745char*name =find_name_gnu(state, line, def, p_value); 746if(name) 747return name; 748} 749 750 len =strchrnul(line,'\n') - line; 751 date_len =diff_timestamp_len(line, len); 752if(!date_len) 753returnfind_name_common(state, line, def, p_value, NULL, TERM_TAB); 754 len -= date_len; 755 756returnfind_name_common(state, line, def, p_value, line + len,0); 757} 758 759static intcount_slashes(const char*cp) 760{ 761int cnt =0; 762char ch; 763 764while((ch = *cp++)) 765if(ch =='/') 766 cnt++; 767return cnt; 768} 769 770/* 771 * Given the string after "--- " or "+++ ", guess the appropriate 772 * p_value for the given patch. 773 */ 774static intguess_p_value(struct apply_state *state,const char*nameline) 775{ 776char*name, *cp; 777int val = -1; 778 779if(is_dev_null(nameline)) 780return-1; 781 name =find_name_traditional(state, nameline, NULL,0); 782if(!name) 783return-1; 784 cp =strchr(name,'/'); 785if(!cp) 786 val =0; 787else if(state->prefix) { 788/* 789 * Does it begin with "a/$our-prefix" and such? Then this is 790 * very likely to apply to our directory. 791 */ 792if(!strncmp(name, state->prefix, state->prefix_length)) 793 val =count_slashes(state->prefix); 794else{ 795 cp++; 796if(!strncmp(cp, state->prefix, state->prefix_length)) 797 val =count_slashes(state->prefix) +1; 798} 799} 800free(name); 801return val; 802} 803 804/* 805 * Does the ---/+++ line have the POSIX timestamp after the last HT? 806 * GNU diff puts epoch there to signal a creation/deletion event. Is 807 * this such a timestamp? 808 */ 809static inthas_epoch_timestamp(const char*nameline) 810{ 811/* 812 * We are only interested in epoch timestamp; any non-zero 813 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 814 * For the same reason, the date must be either 1969-12-31 or 815 * 1970-01-01, and the seconds part must be "00". 816 */ 817const char stamp_regexp[] = 818"^(1969-12-31|1970-01-01)" 819" " 820"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 821" " 822"([-+][0-2][0-9]:?[0-5][0-9])\n"; 823const char*timestamp = NULL, *cp, *colon; 824static regex_t *stamp; 825 regmatch_t m[10]; 826int zoneoffset; 827int hourminute; 828int status; 829 830for(cp = nameline; *cp !='\n'; cp++) { 831if(*cp =='\t') 832 timestamp = cp +1; 833} 834if(!timestamp) 835return0; 836if(!stamp) { 837 stamp =xmalloc(sizeof(*stamp)); 838if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 839warning(_("Cannot prepare timestamp regexp%s"), 840 stamp_regexp); 841return0; 842} 843} 844 845 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 846if(status) { 847if(status != REG_NOMATCH) 848warning(_("regexec returned%dfor input:%s"), 849 status, timestamp); 850return0; 851} 852 853 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 854if(*colon ==':') 855 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 856else 857 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 858if(timestamp[m[3].rm_so] =='-') 859 zoneoffset = -zoneoffset; 860 861/* 862 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 863 * (west of GMT) or 1970-01-01 (east of GMT) 864 */ 865if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 866(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 867return0; 868 869 hourminute = (strtol(timestamp +11, NULL,10) *60+ 870strtol(timestamp +14, NULL,10) - 871 zoneoffset); 872 873return((zoneoffset <0&& hourminute ==1440) || 874(0<= zoneoffset && !hourminute)); 875} 876 877/* 878 * Get the name etc info from the ---/+++ lines of a traditional patch header 879 * 880 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 881 * files, we can happily check the index for a match, but for creating a 882 * new file we should try to match whatever "patch" does. I have no idea. 883 */ 884static voidparse_traditional_patch(struct apply_state *state, 885const char*first, 886const char*second, 887struct patch *patch) 888{ 889char*name; 890 891 first +=4;/* skip "--- " */ 892 second +=4;/* skip "+++ " */ 893if(!state->p_value_known) { 894int p, q; 895 p =guess_p_value(state, first); 896 q =guess_p_value(state, second); 897if(p <0) p = q; 898if(0<= p && p == q) { 899 state->p_value = p; 900 state->p_value_known =1; 901} 902} 903if(is_dev_null(first)) { 904 patch->is_new =1; 905 patch->is_delete =0; 906 name =find_name_traditional(state, second, NULL, state->p_value); 907 patch->new_name = name; 908}else if(is_dev_null(second)) { 909 patch->is_new =0; 910 patch->is_delete =1; 911 name =find_name_traditional(state, first, NULL, state->p_value); 912 patch->old_name = name; 913}else{ 914char*first_name; 915 first_name =find_name_traditional(state, first, NULL, state->p_value); 916 name =find_name_traditional(state, second, first_name, state->p_value); 917free(first_name); 918if(has_epoch_timestamp(first)) { 919 patch->is_new =1; 920 patch->is_delete =0; 921 patch->new_name = name; 922}else if(has_epoch_timestamp(second)) { 923 patch->is_new =0; 924 patch->is_delete =1; 925 patch->old_name = name; 926}else{ 927 patch->old_name = name; 928 patch->new_name =xstrdup_or_null(name); 929} 930} 931if(!name) 932die(_("unable to find filename in patch at line%d"), state_linenr); 933} 934 935static intgitdiff_hdrend(struct apply_state *state, 936const char*line, 937struct patch *patch) 938{ 939return-1; 940} 941 942/* 943 * We're anal about diff header consistency, to make 944 * sure that we don't end up having strange ambiguous 945 * patches floating around. 946 * 947 * As a result, gitdiff_{old|new}name() will check 948 * their names against any previous information, just 949 * to make sure.. 950 */ 951#define DIFF_OLD_NAME 0 952#define DIFF_NEW_NAME 1 953 954static voidgitdiff_verify_name(struct apply_state *state, 955const char*line, 956int isnull, 957char**name, 958int side) 959{ 960if(!*name && !isnull) { 961*name =find_name(state, line, NULL, state->p_value, TERM_TAB); 962return; 963} 964 965if(*name) { 966int len =strlen(*name); 967char*another; 968if(isnull) 969die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 970*name, state_linenr); 971 another =find_name(state, line, NULL, state->p_value, TERM_TAB); 972if(!another ||memcmp(another, *name, len +1)) 973die((side == DIFF_NEW_NAME) ? 974_("git apply: bad git-diff - inconsistent new filename on line%d") : 975_("git apply: bad git-diff - inconsistent old filename on line%d"), state_linenr); 976free(another); 977}else{ 978/* expect "/dev/null" */ 979if(memcmp("/dev/null", line,9) || line[9] !='\n') 980die(_("git apply: bad git-diff - expected /dev/null on line%d"), state_linenr); 981} 982} 983 984static intgitdiff_oldname(struct apply_state *state, 985const char*line, 986struct patch *patch) 987{ 988gitdiff_verify_name(state, line, 989 patch->is_new, &patch->old_name, 990 DIFF_OLD_NAME); 991return0; 992} 993 994static intgitdiff_newname(struct apply_state *state, 995const char*line, 996struct patch *patch) 997{ 998gitdiff_verify_name(state, line, 999 patch->is_delete, &patch->new_name,1000 DIFF_NEW_NAME);1001return0;1002}10031004static intgitdiff_oldmode(struct apply_state *state,1005const char*line,1006struct patch *patch)1007{1008 patch->old_mode =strtoul(line, NULL,8);1009return0;1010}10111012static intgitdiff_newmode(struct apply_state *state,1013const char*line,1014struct patch *patch)1015{1016 patch->new_mode =strtoul(line, NULL,8);1017return0;1018}10191020static intgitdiff_delete(struct apply_state *state,1021const char*line,1022struct patch *patch)1023{1024 patch->is_delete =1;1025free(patch->old_name);1026 patch->old_name =xstrdup_or_null(patch->def_name);1027returngitdiff_oldmode(state, line, patch);1028}10291030static intgitdiff_newfile(struct apply_state *state,1031const char*line,1032struct patch *patch)1033{1034 patch->is_new =1;1035free(patch->new_name);1036 patch->new_name =xstrdup_or_null(patch->def_name);1037returngitdiff_newmode(state, line, patch);1038}10391040static intgitdiff_copysrc(struct apply_state *state,1041const char*line,1042struct patch *patch)1043{1044 patch->is_copy =1;1045free(patch->old_name);1046 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1047return0;1048}10491050static intgitdiff_copydst(struct apply_state *state,1051const char*line,1052struct patch *patch)1053{1054 patch->is_copy =1;1055free(patch->new_name);1056 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1057return0;1058}10591060static intgitdiff_renamesrc(struct apply_state *state,1061const char*line,1062struct patch *patch)1063{1064 patch->is_rename =1;1065free(patch->old_name);1066 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1067return0;1068}10691070static intgitdiff_renamedst(struct apply_state *state,1071const char*line,1072struct patch *patch)1073{1074 patch->is_rename =1;1075free(patch->new_name);1076 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1077return0;1078}10791080static intgitdiff_similarity(struct apply_state *state,1081const char*line,1082struct patch *patch)1083{1084unsigned long val =strtoul(line, NULL,10);1085if(val <=100)1086 patch->score = val;1087return0;1088}10891090static intgitdiff_dissimilarity(struct apply_state *state,1091const char*line,1092struct patch *patch)1093{1094unsigned long val =strtoul(line, NULL,10);1095if(val <=100)1096 patch->score = val;1097return0;1098}10991100static intgitdiff_index(struct apply_state *state,1101const char*line,1102struct patch *patch)1103{1104/*1105 * index line is N hexadecimal, "..", N hexadecimal,1106 * and optional space with octal mode.1107 */1108const char*ptr, *eol;1109int len;11101111 ptr =strchr(line,'.');1112if(!ptr || ptr[1] !='.'||40< ptr - line)1113return0;1114 len = ptr - line;1115memcpy(patch->old_sha1_prefix, line, len);1116 patch->old_sha1_prefix[len] =0;11171118 line = ptr +2;1119 ptr =strchr(line,' ');1120 eol =strchrnul(line,'\n');11211122if(!ptr || eol < ptr)1123 ptr = eol;1124 len = ptr - line;11251126if(40< len)1127return0;1128memcpy(patch->new_sha1_prefix, line, len);1129 patch->new_sha1_prefix[len] =0;1130if(*ptr ==' ')1131 patch->old_mode =strtoul(ptr+1, NULL,8);1132return0;1133}11341135/*1136 * This is normal for a diff that doesn't change anything: we'll fall through1137 * into the next diff. Tell the parser to break out.1138 */1139static intgitdiff_unrecognized(struct apply_state *state,1140const char*line,1141struct patch *patch)1142{1143return-1;1144}11451146/*1147 * Skip p_value leading components from "line"; as we do not accept1148 * absolute paths, return NULL in that case.1149 */1150static const char*skip_tree_prefix(struct apply_state *state,1151const char*line,1152int llen)1153{1154int nslash;1155int i;11561157if(!state->p_value)1158return(llen && line[0] =='/') ? NULL : line;11591160 nslash = state->p_value;1161for(i =0; i < llen; i++) {1162int ch = line[i];1163if(ch =='/'&& --nslash <=0)1164return(i ==0) ? NULL : &line[i +1];1165}1166return NULL;1167}11681169/*1170 * This is to extract the same name that appears on "diff --git"1171 * line. We do not find and return anything if it is a rename1172 * patch, and it is OK because we will find the name elsewhere.1173 * We need to reliably find name only when it is mode-change only,1174 * creation or deletion of an empty file. In any of these cases,1175 * both sides are the same name under a/ and b/ respectively.1176 */1177static char*git_header_name(struct apply_state *state,1178const char*line,1179int llen)1180{1181const char*name;1182const char*second = NULL;1183size_t len, line_len;11841185 line +=strlen("diff --git ");1186 llen -=strlen("diff --git ");11871188if(*line =='"') {1189const char*cp;1190struct strbuf first = STRBUF_INIT;1191struct strbuf sp = STRBUF_INIT;11921193if(unquote_c_style(&first, line, &second))1194goto free_and_fail1;11951196/* strip the a/b prefix including trailing slash */1197 cp =skip_tree_prefix(state, first.buf, first.len);1198if(!cp)1199goto free_and_fail1;1200strbuf_remove(&first,0, cp - first.buf);12011202/*1203 * second points at one past closing dq of name.1204 * find the second name.1205 */1206while((second < line + llen) &&isspace(*second))1207 second++;12081209if(line + llen <= second)1210goto free_and_fail1;1211if(*second =='"') {1212if(unquote_c_style(&sp, second, NULL))1213goto free_and_fail1;1214 cp =skip_tree_prefix(state, sp.buf, sp.len);1215if(!cp)1216goto free_and_fail1;1217/* They must match, otherwise ignore */1218if(strcmp(cp, first.buf))1219goto free_and_fail1;1220strbuf_release(&sp);1221returnstrbuf_detach(&first, NULL);1222}12231224/* unquoted second */1225 cp =skip_tree_prefix(state, second, line + llen - second);1226if(!cp)1227goto free_and_fail1;1228if(line + llen - cp != first.len ||1229memcmp(first.buf, cp, first.len))1230goto free_and_fail1;1231returnstrbuf_detach(&first, NULL);12321233 free_and_fail1:1234strbuf_release(&first);1235strbuf_release(&sp);1236return NULL;1237}12381239/* unquoted first name */1240 name =skip_tree_prefix(state, line, llen);1241if(!name)1242return NULL;12431244/*1245 * since the first name is unquoted, a dq if exists must be1246 * the beginning of the second name.1247 */1248for(second = name; second < line + llen; second++) {1249if(*second =='"') {1250struct strbuf sp = STRBUF_INIT;1251const char*np;12521253if(unquote_c_style(&sp, second, NULL))1254goto free_and_fail2;12551256 np =skip_tree_prefix(state, sp.buf, sp.len);1257if(!np)1258goto free_and_fail2;12591260 len = sp.buf + sp.len - np;1261if(len < second - name &&1262!strncmp(np, name, len) &&1263isspace(name[len])) {1264/* Good */1265strbuf_remove(&sp,0, np - sp.buf);1266returnstrbuf_detach(&sp, NULL);1267}12681269 free_and_fail2:1270strbuf_release(&sp);1271return NULL;1272}1273}12741275/*1276 * Accept a name only if it shows up twice, exactly the same1277 * form.1278 */1279 second =strchr(name,'\n');1280if(!second)1281return NULL;1282 line_len = second - name;1283for(len =0; ; len++) {1284switch(name[len]) {1285default:1286continue;1287case'\n':1288return NULL;1289case'\t':case' ':1290/*1291 * Is this the separator between the preimage1292 * and the postimage pathname? Again, we are1293 * only interested in the case where there is1294 * no rename, as this is only to set def_name1295 * and a rename patch has the names elsewhere1296 * in an unambiguous form.1297 */1298if(!name[len +1])1299return NULL;/* no postimage name */1300 second =skip_tree_prefix(state, name + len +1,1301 line_len - (len +1));1302if(!second)1303return NULL;1304/*1305 * Does len bytes starting at "name" and "second"1306 * (that are separated by one HT or SP we just1307 * found) exactly match?1308 */1309if(second[len] =='\n'&& !strncmp(name, second, len))1310returnxmemdupz(name, len);1311}1312}1313}13141315/* Verify that we recognize the lines following a git header */1316static intparse_git_header(struct apply_state *state,1317const char*line,1318int len,1319unsigned int size,1320struct patch *patch)1321{1322unsigned long offset;13231324/* A git diff has explicit new/delete information, so we don't guess */1325 patch->is_new =0;1326 patch->is_delete =0;13271328/*1329 * Some things may not have the old name in the1330 * rest of the headers anywhere (pure mode changes,1331 * or removing or adding empty files), so we get1332 * the default name from the header.1333 */1334 patch->def_name =git_header_name(state, line, len);1335if(patch->def_name && state->root.len) {1336char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1337free(patch->def_name);1338 patch->def_name = s;1339}13401341 line += len;1342 size -= len;1343 state_linenr++;1344for(offset = len ; size >0; offset += len, size -= len, line += len, state_linenr++) {1345static const struct opentry {1346const char*str;1347int(*fn)(struct apply_state *,const char*,struct patch *);1348} optable[] = {1349{"@@ -", gitdiff_hdrend },1350{"--- ", gitdiff_oldname },1351{"+++ ", gitdiff_newname },1352{"old mode ", gitdiff_oldmode },1353{"new mode ", gitdiff_newmode },1354{"deleted file mode ", gitdiff_delete },1355{"new file mode ", gitdiff_newfile },1356{"copy from ", gitdiff_copysrc },1357{"copy to ", gitdiff_copydst },1358{"rename old ", gitdiff_renamesrc },1359{"rename new ", gitdiff_renamedst },1360{"rename from ", gitdiff_renamesrc },1361{"rename to ", gitdiff_renamedst },1362{"similarity index ", gitdiff_similarity },1363{"dissimilarity index ", gitdiff_dissimilarity },1364{"index ", gitdiff_index },1365{"", gitdiff_unrecognized },1366};1367int i;13681369 len =linelen(line, size);1370if(!len || line[len-1] !='\n')1371break;1372for(i =0; i <ARRAY_SIZE(optable); i++) {1373const struct opentry *p = optable + i;1374int oplen =strlen(p->str);1375if(len < oplen ||memcmp(p->str, line, oplen))1376continue;1377if(p->fn(state, line + oplen, patch) <0)1378return offset;1379break;1380}1381}13821383return offset;1384}13851386static intparse_num(const char*line,unsigned long*p)1387{1388char*ptr;13891390if(!isdigit(*line))1391return0;1392*p =strtoul(line, &ptr,10);1393return ptr - line;1394}13951396static intparse_range(const char*line,int len,int offset,const char*expect,1397unsigned long*p1,unsigned long*p2)1398{1399int digits, ex;14001401if(offset <0|| offset >= len)1402return-1;1403 line += offset;1404 len -= offset;14051406 digits =parse_num(line, p1);1407if(!digits)1408return-1;14091410 offset += digits;1411 line += digits;1412 len -= digits;14131414*p2 =1;1415if(*line ==',') {1416 digits =parse_num(line+1, p2);1417if(!digits)1418return-1;14191420 offset += digits+1;1421 line += digits+1;1422 len -= digits+1;1423}14241425 ex =strlen(expect);1426if(ex > len)1427return-1;1428if(memcmp(line, expect, ex))1429return-1;14301431return offset + ex;1432}14331434static voidrecount_diff(const char*line,int size,struct fragment *fragment)1435{1436int oldlines =0, newlines =0, ret =0;14371438if(size <1) {1439warning("recount: ignore empty hunk");1440return;1441}14421443for(;;) {1444int len =linelen(line, size);1445 size -= len;1446 line += len;14471448if(size <1)1449break;14501451switch(*line) {1452case' ':case'\n':1453 newlines++;1454/* fall through */1455case'-':1456 oldlines++;1457continue;1458case'+':1459 newlines++;1460continue;1461case'\\':1462continue;1463case'@':1464 ret = size <3|| !starts_with(line,"@@ ");1465break;1466case'd':1467 ret = size <5|| !starts_with(line,"diff ");1468break;1469default:1470 ret = -1;1471break;1472}1473if(ret) {1474warning(_("recount: unexpected line: %.*s"),1475(int)linelen(line, size), line);1476return;1477}1478break;1479}1480 fragment->oldlines = oldlines;1481 fragment->newlines = newlines;1482}14831484/*1485 * Parse a unified diff fragment header of the1486 * form "@@ -a,b +c,d @@"1487 */1488static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1489{1490int offset;14911492if(!len || line[len-1] !='\n')1493return-1;14941495/* Figure out the number of lines in a fragment */1496 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1497 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14981499return offset;1500}15011502static intfind_header(struct apply_state *state,1503const char*line,1504unsigned long size,1505int*hdrsize,1506struct patch *patch)1507{1508unsigned long offset, len;15091510 patch->is_toplevel_relative =0;1511 patch->is_rename = patch->is_copy =0;1512 patch->is_new = patch->is_delete = -1;1513 patch->old_mode = patch->new_mode =0;1514 patch->old_name = patch->new_name = NULL;1515for(offset =0; size >0; offset += len, size -= len, line += len, state_linenr++) {1516unsigned long nextlen;15171518 len =linelen(line, size);1519if(!len)1520break;15211522/* Testing this early allows us to take a few shortcuts.. */1523if(len <6)1524continue;15251526/*1527 * Make sure we don't find any unconnected patch fragments.1528 * That's a sign that we didn't find a header, and that a1529 * patch has become corrupted/broken up.1530 */1531if(!memcmp("@@ -", line,4)) {1532struct fragment dummy;1533if(parse_fragment_header(line, len, &dummy) <0)1534continue;1535die(_("patch fragment without header at line%d: %.*s"),1536 state_linenr, (int)len-1, line);1537}15381539if(size < len +6)1540break;15411542/*1543 * Git patch? It might not have a real patch, just a rename1544 * or mode change, so we handle that specially1545 */1546if(!memcmp("diff --git ", line,11)) {1547int git_hdr_len =parse_git_header(state, line, len, size, patch);1548if(git_hdr_len <= len)1549continue;1550if(!patch->old_name && !patch->new_name) {1551if(!patch->def_name)1552die(Q_("git diff header lacks filename information when removing "1553"%dleading pathname component (line%d)",1554"git diff header lacks filename information when removing "1555"%dleading pathname components (line%d)",1556 state->p_value),1557 state->p_value, state_linenr);1558 patch->old_name =xstrdup(patch->def_name);1559 patch->new_name =xstrdup(patch->def_name);1560}1561if(!patch->is_delete && !patch->new_name)1562die("git diff header lacks filename information "1563"(line%d)", state_linenr);1564 patch->is_toplevel_relative =1;1565*hdrsize = git_hdr_len;1566return offset;1567}15681569/* --- followed by +++ ? */1570if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1571continue;15721573/*1574 * We only accept unified patches, so we want it to1575 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1576 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1577 */1578 nextlen =linelen(line + len, size - len);1579if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1580continue;15811582/* Ok, we'll consider it a patch */1583parse_traditional_patch(state, line, line+len, patch);1584*hdrsize = len + nextlen;1585 state_linenr +=2;1586return offset;1587}1588return-1;1589}15901591static voidrecord_ws_error(struct apply_state *state,1592unsigned result,1593const char*line,1594int len,1595int linenr)1596{1597char*err;15981599if(!result)1600return;16011602 state->whitespace_error++;1603if(squelch_whitespace_errors &&1604 squelch_whitespace_errors < state->whitespace_error)1605return;16061607 err =whitespace_error_string(result);1608fprintf(stderr,"%s:%d:%s.\n%.*s\n",1609 state->patch_input_file, linenr, err, len, line);1610free(err);1611}16121613static voidcheck_whitespace(struct apply_state *state,1614const char*line,1615int len,1616unsigned ws_rule)1617{1618unsigned result =ws_check(line +1, len -1, ws_rule);16191620record_ws_error(state, result, line +1, len -2, state_linenr);1621}16221623/*1624 * Parse a unified diff. Note that this really needs to parse each1625 * fragment separately, since the only way to know the difference1626 * between a "---" that is part of a patch, and a "---" that starts1627 * the next patch is to look at the line counts..1628 */1629static intparse_fragment(struct apply_state *state,1630const char*line,1631unsigned long size,1632struct patch *patch,1633struct fragment *fragment)1634{1635int added, deleted;1636int len =linelen(line, size), offset;1637unsigned long oldlines, newlines;1638unsigned long leading, trailing;16391640 offset =parse_fragment_header(line, len, fragment);1641if(offset <0)1642return-1;1643if(offset >0&& patch->recount)1644recount_diff(line + offset, size - offset, fragment);1645 oldlines = fragment->oldlines;1646 newlines = fragment->newlines;1647 leading =0;1648 trailing =0;16491650/* Parse the thing.. */1651 line += len;1652 size -= len;1653 state_linenr++;1654 added = deleted =0;1655for(offset = len;16560< size;1657 offset += len, size -= len, line += len, state_linenr++) {1658if(!oldlines && !newlines)1659break;1660 len =linelen(line, size);1661if(!len || line[len-1] !='\n')1662return-1;1663switch(*line) {1664default:1665return-1;1666case'\n':/* newer GNU diff, an empty context line */1667case' ':1668 oldlines--;1669 newlines--;1670if(!deleted && !added)1671 leading++;1672 trailing++;1673if(!state->apply_in_reverse &&1674 ws_error_action == correct_ws_error)1675check_whitespace(state, line, len, patch->ws_rule);1676break;1677case'-':1678if(state->apply_in_reverse &&1679 ws_error_action != nowarn_ws_error)1680check_whitespace(state, line, len, patch->ws_rule);1681 deleted++;1682 oldlines--;1683 trailing =0;1684break;1685case'+':1686if(!state->apply_in_reverse &&1687 ws_error_action != nowarn_ws_error)1688check_whitespace(state, line, len, patch->ws_rule);1689 added++;1690 newlines--;1691 trailing =0;1692break;16931694/*1695 * We allow "\ No newline at end of file". Depending1696 * on locale settings when the patch was produced we1697 * don't know what this line looks like. The only1698 * thing we do know is that it begins with "\ ".1699 * Checking for 12 is just for sanity check -- any1700 * l10n of "\ No newline..." is at least that long.1701 */1702case'\\':1703if(len <12||memcmp(line,"\\",2))1704return-1;1705break;1706}1707}1708if(oldlines || newlines)1709return-1;1710if(!deleted && !added)1711return-1;17121713 fragment->leading = leading;1714 fragment->trailing = trailing;17151716/*1717 * If a fragment ends with an incomplete line, we failed to include1718 * it in the above loop because we hit oldlines == newlines == 01719 * before seeing it.1720 */1721if(12< size && !memcmp(line,"\\",2))1722 offset +=linelen(line, size);17231724 patch->lines_added += added;1725 patch->lines_deleted += deleted;17261727if(0< patch->is_new && oldlines)1728returnerror(_("new file depends on old contents"));1729if(0< patch->is_delete && newlines)1730returnerror(_("deleted file still has contents"));1731return offset;1732}17331734/*1735 * We have seen "diff --git a/... b/..." header (or a traditional patch1736 * header). Read hunks that belong to this patch into fragments and hang1737 * them to the given patch structure.1738 *1739 * The (fragment->patch, fragment->size) pair points into the memory given1740 * by the caller, not a copy, when we return.1741 */1742static intparse_single_patch(struct apply_state *state,1743const char*line,1744unsigned long size,1745struct patch *patch)1746{1747unsigned long offset =0;1748unsigned long oldlines =0, newlines =0, context =0;1749struct fragment **fragp = &patch->fragments;17501751while(size >4&& !memcmp(line,"@@ -",4)) {1752struct fragment *fragment;1753int len;17541755 fragment =xcalloc(1,sizeof(*fragment));1756 fragment->linenr = state_linenr;1757 len =parse_fragment(state, line, size, patch, fragment);1758if(len <=0)1759die(_("corrupt patch at line%d"), state_linenr);1760 fragment->patch = line;1761 fragment->size = len;1762 oldlines += fragment->oldlines;1763 newlines += fragment->newlines;1764 context += fragment->leading + fragment->trailing;17651766*fragp = fragment;1767 fragp = &fragment->next;17681769 offset += len;1770 line += len;1771 size -= len;1772}17731774/*1775 * If something was removed (i.e. we have old-lines) it cannot1776 * be creation, and if something was added it cannot be1777 * deletion. However, the reverse is not true; --unified=01778 * patches that only add are not necessarily creation even1779 * though they do not have any old lines, and ones that only1780 * delete are not necessarily deletion.1781 *1782 * Unfortunately, a real creation/deletion patch do _not_ have1783 * any context line by definition, so we cannot safely tell it1784 * apart with --unified=0 insanity. At least if the patch has1785 * more than one hunk it is not creation or deletion.1786 */1787if(patch->is_new <0&&1788(oldlines || (patch->fragments && patch->fragments->next)))1789 patch->is_new =0;1790if(patch->is_delete <0&&1791(newlines || (patch->fragments && patch->fragments->next)))1792 patch->is_delete =0;17931794if(0< patch->is_new && oldlines)1795die(_("new file%sdepends on old contents"), patch->new_name);1796if(0< patch->is_delete && newlines)1797die(_("deleted file%sstill has contents"), patch->old_name);1798if(!patch->is_delete && !newlines && context)1799fprintf_ln(stderr,1800_("** warning: "1801"file%sbecomes empty but is not deleted"),1802 patch->new_name);18031804return offset;1805}18061807staticinlineintmetadata_changes(struct patch *patch)1808{1809return patch->is_rename >0||1810 patch->is_copy >0||1811 patch->is_new >0||1812 patch->is_delete ||1813(patch->old_mode && patch->new_mode &&1814 patch->old_mode != patch->new_mode);1815}18161817static char*inflate_it(const void*data,unsigned long size,1818unsigned long inflated_size)1819{1820 git_zstream stream;1821void*out;1822int st;18231824memset(&stream,0,sizeof(stream));18251826 stream.next_in = (unsigned char*)data;1827 stream.avail_in = size;1828 stream.next_out = out =xmalloc(inflated_size);1829 stream.avail_out = inflated_size;1830git_inflate_init(&stream);1831 st =git_inflate(&stream, Z_FINISH);1832git_inflate_end(&stream);1833if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1834free(out);1835return NULL;1836}1837return out;1838}18391840/*1841 * Read a binary hunk and return a new fragment; fragment->patch1842 * points at an allocated memory that the caller must free, so1843 * it is marked as "->free_patch = 1".1844 */1845static struct fragment *parse_binary_hunk(char**buf_p,1846unsigned long*sz_p,1847int*status_p,1848int*used_p)1849{1850/*1851 * Expect a line that begins with binary patch method ("literal"1852 * or "delta"), followed by the length of data before deflating.1853 * a sequence of 'length-byte' followed by base-85 encoded data1854 * should follow, terminated by a newline.1855 *1856 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1857 * and we would limit the patch line to 66 characters,1858 * so one line can fit up to 13 groups that would decode1859 * to 52 bytes max. The length byte 'A'-'Z' corresponds1860 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1861 */1862int llen, used;1863unsigned long size = *sz_p;1864char*buffer = *buf_p;1865int patch_method;1866unsigned long origlen;1867char*data = NULL;1868int hunk_size =0;1869struct fragment *frag;18701871 llen =linelen(buffer, size);1872 used = llen;18731874*status_p =0;18751876if(starts_with(buffer,"delta ")) {1877 patch_method = BINARY_DELTA_DEFLATED;1878 origlen =strtoul(buffer +6, NULL,10);1879}1880else if(starts_with(buffer,"literal ")) {1881 patch_method = BINARY_LITERAL_DEFLATED;1882 origlen =strtoul(buffer +8, NULL,10);1883}1884else1885return NULL;18861887 state_linenr++;1888 buffer += llen;1889while(1) {1890int byte_length, max_byte_length, newsize;1891 llen =linelen(buffer, size);1892 used += llen;1893 state_linenr++;1894if(llen ==1) {1895/* consume the blank line */1896 buffer++;1897 size--;1898break;1899}1900/*1901 * Minimum line is "A00000\n" which is 7-byte long,1902 * and the line length must be multiple of 5 plus 2.1903 */1904if((llen <7) || (llen-2) %5)1905goto corrupt;1906 max_byte_length = (llen -2) /5*4;1907 byte_length = *buffer;1908if('A'<= byte_length && byte_length <='Z')1909 byte_length = byte_length -'A'+1;1910else if('a'<= byte_length && byte_length <='z')1911 byte_length = byte_length -'a'+27;1912else1913goto corrupt;1914/* if the input length was not multiple of 4, we would1915 * have filler at the end but the filler should never1916 * exceed 3 bytes1917 */1918if(max_byte_length < byte_length ||1919 byte_length <= max_byte_length -4)1920goto corrupt;1921 newsize = hunk_size + byte_length;1922 data =xrealloc(data, newsize);1923if(decode_85(data + hunk_size, buffer +1, byte_length))1924goto corrupt;1925 hunk_size = newsize;1926 buffer += llen;1927 size -= llen;1928}19291930 frag =xcalloc(1,sizeof(*frag));1931 frag->patch =inflate_it(data, hunk_size, origlen);1932 frag->free_patch =1;1933if(!frag->patch)1934goto corrupt;1935free(data);1936 frag->size = origlen;1937*buf_p = buffer;1938*sz_p = size;1939*used_p = used;1940 frag->binary_patch_method = patch_method;1941return frag;19421943 corrupt:1944free(data);1945*status_p = -1;1946error(_("corrupt binary patch at line%d: %.*s"),1947 state_linenr-1, llen-1, buffer);1948return NULL;1949}19501951/*1952 * Returns:1953 * -1 in case of error,1954 * the length of the parsed binary patch otherwise1955 */1956static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1957{1958/*1959 * We have read "GIT binary patch\n"; what follows is a line1960 * that says the patch method (currently, either "literal" or1961 * "delta") and the length of data before deflating; a1962 * sequence of 'length-byte' followed by base-85 encoded data1963 * follows.1964 *1965 * When a binary patch is reversible, there is another binary1966 * hunk in the same format, starting with patch method (either1967 * "literal" or "delta") with the length of data, and a sequence1968 * of length-byte + base-85 encoded data, terminated with another1969 * empty line. This data, when applied to the postimage, produces1970 * the preimage.1971 */1972struct fragment *forward;1973struct fragment *reverse;1974int status;1975int used, used_1;19761977 forward =parse_binary_hunk(&buffer, &size, &status, &used);1978if(!forward && !status)1979/* there has to be one hunk (forward hunk) */1980returnerror(_("unrecognized binary patch at line%d"), state_linenr-1);1981if(status)1982/* otherwise we already gave an error message */1983return status;19841985 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1986if(reverse)1987 used += used_1;1988else if(status) {1989/*1990 * Not having reverse hunk is not an error, but having1991 * a corrupt reverse hunk is.1992 */1993free((void*) forward->patch);1994free(forward);1995return status;1996}1997 forward->next = reverse;1998 patch->fragments = forward;1999 patch->is_binary =1;2000return used;2001}20022003static voidprefix_one(struct apply_state *state,char**name)2004{2005char*old_name = *name;2006if(!old_name)2007return;2008*name =xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));2009free(old_name);2010}20112012static voidprefix_patch(struct apply_state *state,struct patch *p)2013{2014if(!state->prefix || p->is_toplevel_relative)2015return;2016prefix_one(state, &p->new_name);2017prefix_one(state, &p->old_name);2018}20192020/*2021 * include/exclude2022 */20232024static voidadd_name_limit(struct apply_state *state,2025const char*name,2026int exclude)2027{2028struct string_list_item *it;20292030 it =string_list_append(&state->limit_by_name, name);2031 it->util = exclude ? NULL : (void*)1;2032}20332034static intuse_patch(struct apply_state *state,struct patch *p)2035{2036const char*pathname = p->new_name ? p->new_name : p->old_name;2037int i;20382039/* Paths outside are not touched regardless of "--include" */2040if(0< state->prefix_length) {2041int pathlen =strlen(pathname);2042if(pathlen <= state->prefix_length ||2043memcmp(state->prefix, pathname, state->prefix_length))2044return0;2045}20462047/* See if it matches any of exclude/include rule */2048for(i =0; i < state->limit_by_name.nr; i++) {2049struct string_list_item *it = &state->limit_by_name.items[i];2050if(!wildmatch(it->string, pathname,0, NULL))2051return(it->util != NULL);2052}20532054/*2055 * If we had any include, a path that does not match any rule is2056 * not used. Otherwise, we saw bunch of exclude rules (or none)2057 * and such a path is used.2058 */2059return!state->has_include;2060}206120622063/*2064 * Read the patch text in "buffer" that extends for "size" bytes; stop2065 * reading after seeing a single patch (i.e. changes to a single file).2066 * Create fragments (i.e. patch hunks) and hang them to the given patch.2067 * Return the number of bytes consumed, so that the caller can call us2068 * again for the next patch.2069 */2070static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2071{2072int hdrsize, patchsize;2073int offset =find_header(state, buffer, size, &hdrsize, patch);20742075if(offset <0)2076return offset;20772078prefix_patch(state, patch);20792080if(!use_patch(state, patch))2081 patch->ws_rule =0;2082else2083 patch->ws_rule =whitespace_rule(patch->new_name2084? patch->new_name2085: patch->old_name);20862087 patchsize =parse_single_patch(state,2088 buffer + offset + hdrsize,2089 size - offset - hdrsize,2090 patch);20912092if(!patchsize) {2093static const char git_binary[] ="GIT binary patch\n";2094int hd = hdrsize + offset;2095unsigned long llen =linelen(buffer + hd, size - hd);20962097if(llen ==sizeof(git_binary) -1&&2098!memcmp(git_binary, buffer + hd, llen)) {2099int used;2100 state_linenr++;2101 used =parse_binary(buffer + hd + llen,2102 size - hd - llen, patch);2103if(used <0)2104return-1;2105if(used)2106 patchsize = used + llen;2107else2108 patchsize =0;2109}2110else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2111static const char*binhdr[] = {2112"Binary files ",2113"Files ",2114 NULL,2115};2116int i;2117for(i =0; binhdr[i]; i++) {2118int len =strlen(binhdr[i]);2119if(len < size - hd &&2120!memcmp(binhdr[i], buffer + hd, len)) {2121 state_linenr++;2122 patch->is_binary =1;2123 patchsize = llen;2124break;2125}2126}2127}21282129/* Empty patch cannot be applied if it is a text patch2130 * without metadata change. A binary patch appears2131 * empty to us here.2132 */2133if((state->apply || state->check) &&2134(!patch->is_binary && !metadata_changes(patch)))2135die(_("patch with only garbage at line%d"), state_linenr);2136}21372138return offset + hdrsize + patchsize;2139}21402141#define swap(a,b) myswap((a),(b),sizeof(a))21422143#define myswap(a, b, size) do { \2144 unsigned char mytmp[size]; \2145 memcpy(mytmp, &a, size); \2146 memcpy(&a, &b, size); \2147 memcpy(&b, mytmp, size); \2148} while (0)21492150static voidreverse_patches(struct patch *p)2151{2152for(; p; p = p->next) {2153struct fragment *frag = p->fragments;21542155swap(p->new_name, p->old_name);2156swap(p->new_mode, p->old_mode);2157swap(p->is_new, p->is_delete);2158swap(p->lines_added, p->lines_deleted);2159swap(p->old_sha1_prefix, p->new_sha1_prefix);21602161for(; frag; frag = frag->next) {2162swap(frag->newpos, frag->oldpos);2163swap(frag->newlines, frag->oldlines);2164}2165}2166}21672168static const char pluses[] =2169"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2170static const char minuses[]=2171"----------------------------------------------------------------------";21722173static voidshow_stats(struct patch *patch)2174{2175struct strbuf qname = STRBUF_INIT;2176char*cp = patch->new_name ? patch->new_name : patch->old_name;2177int max, add, del;21782179quote_c_style(cp, &qname, NULL,0);21802181/*2182 * "scale" the filename2183 */2184 max = max_len;2185if(max >50)2186 max =50;21872188if(qname.len > max) {2189 cp =strchr(qname.buf + qname.len +3- max,'/');2190if(!cp)2191 cp = qname.buf + qname.len +3- max;2192strbuf_splice(&qname,0, cp - qname.buf,"...",3);2193}21942195if(patch->is_binary) {2196printf(" %-*s | Bin\n", max, qname.buf);2197strbuf_release(&qname);2198return;2199}22002201printf(" %-*s |", max, qname.buf);2202strbuf_release(&qname);22032204/*2205 * scale the add/delete2206 */2207 max = max + max_change >70?70- max : max_change;2208 add = patch->lines_added;2209 del = patch->lines_deleted;22102211if(max_change >0) {2212int total = ((add + del) * max + max_change /2) / max_change;2213 add = (add * max + max_change /2) / max_change;2214 del = total - add;2215}2216printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2217 add, pluses, del, minuses);2218}22192220static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2221{2222switch(st->st_mode & S_IFMT) {2223case S_IFLNK:2224if(strbuf_readlink(buf, path, st->st_size) <0)2225returnerror(_("unable to read symlink%s"), path);2226return0;2227case S_IFREG:2228if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2229returnerror(_("unable to open or read%s"), path);2230convert_to_git(path, buf->buf, buf->len, buf,0);2231return0;2232default:2233return-1;2234}2235}22362237/*2238 * Update the preimage, and the common lines in postimage,2239 * from buffer buf of length len. If postlen is 0 the postimage2240 * is updated in place, otherwise it's updated on a new buffer2241 * of length postlen2242 */22432244static voidupdate_pre_post_images(struct image *preimage,2245struct image *postimage,2246char*buf,2247size_t len,size_t postlen)2248{2249int i, ctx, reduced;2250char*new, *old, *fixed;2251struct image fixed_preimage;22522253/*2254 * Update the preimage with whitespace fixes. Note that we2255 * are not losing preimage->buf -- apply_one_fragment() will2256 * free "oldlines".2257 */2258prepare_image(&fixed_preimage, buf, len,1);2259assert(postlen2260? fixed_preimage.nr == preimage->nr2261: fixed_preimage.nr <= preimage->nr);2262for(i =0; i < fixed_preimage.nr; i++)2263 fixed_preimage.line[i].flag = preimage->line[i].flag;2264free(preimage->line_allocated);2265*preimage = fixed_preimage;22662267/*2268 * Adjust the common context lines in postimage. This can be2269 * done in-place when we are shrinking it with whitespace2270 * fixing, but needs a new buffer when ignoring whitespace or2271 * expanding leading tabs to spaces.2272 *2273 * We trust the caller to tell us if the update can be done2274 * in place (postlen==0) or not.2275 */2276 old = postimage->buf;2277if(postlen)2278new= postimage->buf =xmalloc(postlen);2279else2280new= old;2281 fixed = preimage->buf;22822283for(i = reduced = ctx =0; i < postimage->nr; i++) {2284size_t l_len = postimage->line[i].len;2285if(!(postimage->line[i].flag & LINE_COMMON)) {2286/* an added line -- no counterparts in preimage */2287memmove(new, old, l_len);2288 old += l_len;2289new+= l_len;2290continue;2291}22922293/* a common context -- skip it in the original postimage */2294 old += l_len;22952296/* and find the corresponding one in the fixed preimage */2297while(ctx < preimage->nr &&2298!(preimage->line[ctx].flag & LINE_COMMON)) {2299 fixed += preimage->line[ctx].len;2300 ctx++;2301}23022303/*2304 * preimage is expected to run out, if the caller2305 * fixed addition of trailing blank lines.2306 */2307if(preimage->nr <= ctx) {2308 reduced++;2309continue;2310}23112312/* and copy it in, while fixing the line length */2313 l_len = preimage->line[ctx].len;2314memcpy(new, fixed, l_len);2315new+= l_len;2316 fixed += l_len;2317 postimage->line[i].len = l_len;2318 ctx++;2319}23202321if(postlen2322? postlen <new- postimage->buf2323: postimage->len <new- postimage->buf)2324die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2325(int)postlen, (int) postimage->len, (int)(new- postimage->buf));23262327/* Fix the length of the whole thing */2328 postimage->len =new- postimage->buf;2329 postimage->nr -= reduced;2330}23312332static intline_by_line_fuzzy_match(struct image *img,2333struct image *preimage,2334struct image *postimage,2335unsigned longtry,2336int try_lno,2337int preimage_limit)2338{2339int i;2340size_t imgoff =0;2341size_t preoff =0;2342size_t postlen = postimage->len;2343size_t extra_chars;2344char*buf;2345char*preimage_eof;2346char*preimage_end;2347struct strbuf fixed;2348char*fixed_buf;2349size_t fixed_len;23502351for(i =0; i < preimage_limit; i++) {2352size_t prelen = preimage->line[i].len;2353size_t imglen = img->line[try_lno+i].len;23542355if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2356 preimage->buf + preoff, prelen))2357return0;2358if(preimage->line[i].flag & LINE_COMMON)2359 postlen += imglen - prelen;2360 imgoff += imglen;2361 preoff += prelen;2362}23632364/*2365 * Ok, the preimage matches with whitespace fuzz.2366 *2367 * imgoff now holds the true length of the target that2368 * matches the preimage before the end of the file.2369 *2370 * Count the number of characters in the preimage that fall2371 * beyond the end of the file and make sure that all of them2372 * are whitespace characters. (This can only happen if2373 * we are removing blank lines at the end of the file.)2374 */2375 buf = preimage_eof = preimage->buf + preoff;2376for( ; i < preimage->nr; i++)2377 preoff += preimage->line[i].len;2378 preimage_end = preimage->buf + preoff;2379for( ; buf < preimage_end; buf++)2380if(!isspace(*buf))2381return0;23822383/*2384 * Update the preimage and the common postimage context2385 * lines to use the same whitespace as the target.2386 * If whitespace is missing in the target (i.e.2387 * if the preimage extends beyond the end of the file),2388 * use the whitespace from the preimage.2389 */2390 extra_chars = preimage_end - preimage_eof;2391strbuf_init(&fixed, imgoff + extra_chars);2392strbuf_add(&fixed, img->buf +try, imgoff);2393strbuf_add(&fixed, preimage_eof, extra_chars);2394 fixed_buf =strbuf_detach(&fixed, &fixed_len);2395update_pre_post_images(preimage, postimage,2396 fixed_buf, fixed_len, postlen);2397return1;2398}23992400static intmatch_fragment(struct image *img,2401struct image *preimage,2402struct image *postimage,2403unsigned longtry,2404int try_lno,2405unsigned ws_rule,2406int match_beginning,int match_end)2407{2408int i;2409char*fixed_buf, *buf, *orig, *target;2410struct strbuf fixed;2411size_t fixed_len, postlen;2412int preimage_limit;24132414if(preimage->nr + try_lno <= img->nr) {2415/*2416 * The hunk falls within the boundaries of img.2417 */2418 preimage_limit = preimage->nr;2419if(match_end && (preimage->nr + try_lno != img->nr))2420return0;2421}else if(ws_error_action == correct_ws_error &&2422(ws_rule & WS_BLANK_AT_EOF)) {2423/*2424 * This hunk extends beyond the end of img, and we are2425 * removing blank lines at the end of the file. This2426 * many lines from the beginning of the preimage must2427 * match with img, and the remainder of the preimage2428 * must be blank.2429 */2430 preimage_limit = img->nr - try_lno;2431}else{2432/*2433 * The hunk extends beyond the end of the img and2434 * we are not removing blanks at the end, so we2435 * should reject the hunk at this position.2436 */2437return0;2438}24392440if(match_beginning && try_lno)2441return0;24422443/* Quick hash check */2444for(i =0; i < preimage_limit; i++)2445if((img->line[try_lno + i].flag & LINE_PATCHED) ||2446(preimage->line[i].hash != img->line[try_lno + i].hash))2447return0;24482449if(preimage_limit == preimage->nr) {2450/*2451 * Do we have an exact match? If we were told to match2452 * at the end, size must be exactly at try+fragsize,2453 * otherwise try+fragsize must be still within the preimage,2454 * and either case, the old piece should match the preimage2455 * exactly.2456 */2457if((match_end2458? (try+ preimage->len == img->len)2459: (try+ preimage->len <= img->len)) &&2460!memcmp(img->buf +try, preimage->buf, preimage->len))2461return1;2462}else{2463/*2464 * The preimage extends beyond the end of img, so2465 * there cannot be an exact match.2466 *2467 * There must be one non-blank context line that match2468 * a line before the end of img.2469 */2470char*buf_end;24712472 buf = preimage->buf;2473 buf_end = buf;2474for(i =0; i < preimage_limit; i++)2475 buf_end += preimage->line[i].len;24762477for( ; buf < buf_end; buf++)2478if(!isspace(*buf))2479break;2480if(buf == buf_end)2481return0;2482}24832484/*2485 * No exact match. If we are ignoring whitespace, run a line-by-line2486 * fuzzy matching. We collect all the line length information because2487 * we need it to adjust whitespace if we match.2488 */2489if(ws_ignore_action == ignore_ws_change)2490returnline_by_line_fuzzy_match(img, preimage, postimage,2491try, try_lno, preimage_limit);24922493if(ws_error_action != correct_ws_error)2494return0;24952496/*2497 * The hunk does not apply byte-by-byte, but the hash says2498 * it might with whitespace fuzz. We weren't asked to2499 * ignore whitespace, we were asked to correct whitespace2500 * errors, so let's try matching after whitespace correction.2501 *2502 * While checking the preimage against the target, whitespace2503 * errors in both fixed, we count how large the corresponding2504 * postimage needs to be. The postimage prepared by2505 * apply_one_fragment() has whitespace errors fixed on added2506 * lines already, but the common lines were propagated as-is,2507 * which may become longer when their whitespace errors are2508 * fixed.2509 */25102511/* First count added lines in postimage */2512 postlen =0;2513for(i =0; i < postimage->nr; i++) {2514if(!(postimage->line[i].flag & LINE_COMMON))2515 postlen += postimage->line[i].len;2516}25172518/*2519 * The preimage may extend beyond the end of the file,2520 * but in this loop we will only handle the part of the2521 * preimage that falls within the file.2522 */2523strbuf_init(&fixed, preimage->len +1);2524 orig = preimage->buf;2525 target = img->buf +try;2526for(i =0; i < preimage_limit; i++) {2527size_t oldlen = preimage->line[i].len;2528size_t tgtlen = img->line[try_lno + i].len;2529size_t fixstart = fixed.len;2530struct strbuf tgtfix;2531int match;25322533/* Try fixing the line in the preimage */2534ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25352536/* Try fixing the line in the target */2537strbuf_init(&tgtfix, tgtlen);2538ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);25392540/*2541 * If they match, either the preimage was based on2542 * a version before our tree fixed whitespace breakage,2543 * or we are lacking a whitespace-fix patch the tree2544 * the preimage was based on already had (i.e. target2545 * has whitespace breakage, the preimage doesn't).2546 * In either case, we are fixing the whitespace breakages2547 * so we might as well take the fix together with their2548 * real change.2549 */2550 match = (tgtfix.len == fixed.len - fixstart &&2551!memcmp(tgtfix.buf, fixed.buf + fixstart,2552 fixed.len - fixstart));25532554/* Add the length if this is common with the postimage */2555if(preimage->line[i].flag & LINE_COMMON)2556 postlen += tgtfix.len;25572558strbuf_release(&tgtfix);2559if(!match)2560goto unmatch_exit;25612562 orig += oldlen;2563 target += tgtlen;2564}256525662567/*2568 * Now handle the lines in the preimage that falls beyond the2569 * end of the file (if any). They will only match if they are2570 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2571 * false).2572 */2573for( ; i < preimage->nr; i++) {2574size_t fixstart = fixed.len;/* start of the fixed preimage */2575size_t oldlen = preimage->line[i].len;2576int j;25772578/* Try fixing the line in the preimage */2579ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25802581for(j = fixstart; j < fixed.len; j++)2582if(!isspace(fixed.buf[j]))2583goto unmatch_exit;25842585 orig += oldlen;2586}25872588/*2589 * Yes, the preimage is based on an older version that still2590 * has whitespace breakages unfixed, and fixing them makes the2591 * hunk match. Update the context lines in the postimage.2592 */2593 fixed_buf =strbuf_detach(&fixed, &fixed_len);2594if(postlen < postimage->len)2595 postlen =0;2596update_pre_post_images(preimage, postimage,2597 fixed_buf, fixed_len, postlen);2598return1;25992600 unmatch_exit:2601strbuf_release(&fixed);2602return0;2603}26042605static intfind_pos(struct image *img,2606struct image *preimage,2607struct image *postimage,2608int line,2609unsigned ws_rule,2610int match_beginning,int match_end)2611{2612int i;2613unsigned long backwards, forwards,try;2614int backwards_lno, forwards_lno, try_lno;26152616/*2617 * If match_beginning or match_end is specified, there is no2618 * point starting from a wrong line that will never match and2619 * wander around and wait for a match at the specified end.2620 */2621if(match_beginning)2622 line =0;2623else if(match_end)2624 line = img->nr - preimage->nr;26252626/*2627 * Because the comparison is unsigned, the following test2628 * will also take care of a negative line number that can2629 * result when match_end and preimage is larger than the target.2630 */2631if((size_t) line > img->nr)2632 line = img->nr;26332634try=0;2635for(i =0; i < line; i++)2636try+= img->line[i].len;26372638/*2639 * There's probably some smart way to do this, but I'll leave2640 * that to the smart and beautiful people. I'm simple and stupid.2641 */2642 backwards =try;2643 backwards_lno = line;2644 forwards =try;2645 forwards_lno = line;2646 try_lno = line;26472648for(i =0; ; i++) {2649if(match_fragment(img, preimage, postimage,2650try, try_lno, ws_rule,2651 match_beginning, match_end))2652return try_lno;26532654 again:2655if(backwards_lno ==0&& forwards_lno == img->nr)2656break;26572658if(i &1) {2659if(backwards_lno ==0) {2660 i++;2661goto again;2662}2663 backwards_lno--;2664 backwards -= img->line[backwards_lno].len;2665try= backwards;2666 try_lno = backwards_lno;2667}else{2668if(forwards_lno == img->nr) {2669 i++;2670goto again;2671}2672 forwards += img->line[forwards_lno].len;2673 forwards_lno++;2674try= forwards;2675 try_lno = forwards_lno;2676}26772678}2679return-1;2680}26812682static voidremove_first_line(struct image *img)2683{2684 img->buf += img->line[0].len;2685 img->len -= img->line[0].len;2686 img->line++;2687 img->nr--;2688}26892690static voidremove_last_line(struct image *img)2691{2692 img->len -= img->line[--img->nr].len;2693}26942695/*2696 * The change from "preimage" and "postimage" has been found to2697 * apply at applied_pos (counts in line numbers) in "img".2698 * Update "img" to remove "preimage" and replace it with "postimage".2699 */2700static voidupdate_image(struct apply_state *state,2701struct image *img,2702int applied_pos,2703struct image *preimage,2704struct image *postimage)2705{2706/*2707 * remove the copy of preimage at offset in img2708 * and replace it with postimage2709 */2710int i, nr;2711size_t remove_count, insert_count, applied_at =0;2712char*result;2713int preimage_limit;27142715/*2716 * If we are removing blank lines at the end of img,2717 * the preimage may extend beyond the end.2718 * If that is the case, we must be careful only to2719 * remove the part of the preimage that falls within2720 * the boundaries of img. Initialize preimage_limit2721 * to the number of lines in the preimage that falls2722 * within the boundaries.2723 */2724 preimage_limit = preimage->nr;2725if(preimage_limit > img->nr - applied_pos)2726 preimage_limit = img->nr - applied_pos;27272728for(i =0; i < applied_pos; i++)2729 applied_at += img->line[i].len;27302731 remove_count =0;2732for(i =0; i < preimage_limit; i++)2733 remove_count += img->line[applied_pos + i].len;2734 insert_count = postimage->len;27352736/* Adjust the contents */2737 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2738memcpy(result, img->buf, applied_at);2739memcpy(result + applied_at, postimage->buf, postimage->len);2740memcpy(result + applied_at + postimage->len,2741 img->buf + (applied_at + remove_count),2742 img->len - (applied_at + remove_count));2743free(img->buf);2744 img->buf = result;2745 img->len += insert_count - remove_count;2746 result[img->len] ='\0';27472748/* Adjust the line table */2749 nr = img->nr + postimage->nr - preimage_limit;2750if(preimage_limit < postimage->nr) {2751/*2752 * NOTE: this knows that we never call remove_first_line()2753 * on anything other than pre/post image.2754 */2755REALLOC_ARRAY(img->line, nr);2756 img->line_allocated = img->line;2757}2758if(preimage_limit != postimage->nr)2759memmove(img->line + applied_pos + postimage->nr,2760 img->line + applied_pos + preimage_limit,2761(img->nr - (applied_pos + preimage_limit)) *2762sizeof(*img->line));2763memcpy(img->line + applied_pos,2764 postimage->line,2765 postimage->nr *sizeof(*img->line));2766if(!state->allow_overlap)2767for(i =0; i < postimage->nr; i++)2768 img->line[applied_pos + i].flag |= LINE_PATCHED;2769 img->nr = nr;2770}27712772/*2773 * Use the patch-hunk text in "frag" to prepare two images (preimage and2774 * postimage) for the hunk. Find lines that match "preimage" in "img" and2775 * replace the part of "img" with "postimage" text.2776 */2777static intapply_one_fragment(struct apply_state *state,2778struct image *img,struct fragment *frag,2779int inaccurate_eof,unsigned ws_rule,2780int nth_fragment)2781{2782int match_beginning, match_end;2783const char*patch = frag->patch;2784int size = frag->size;2785char*old, *oldlines;2786struct strbuf newlines;2787int new_blank_lines_at_end =0;2788int found_new_blank_lines_at_end =0;2789int hunk_linenr = frag->linenr;2790unsigned long leading, trailing;2791int pos, applied_pos;2792struct image preimage;2793struct image postimage;27942795memset(&preimage,0,sizeof(preimage));2796memset(&postimage,0,sizeof(postimage));2797 oldlines =xmalloc(size);2798strbuf_init(&newlines, size);27992800 old = oldlines;2801while(size >0) {2802char first;2803int len =linelen(patch, size);2804int plen;2805int added_blank_line =0;2806int is_blank_context =0;2807size_t start;28082809if(!len)2810break;28112812/*2813 * "plen" is how much of the line we should use for2814 * the actual patch data. Normally we just remove the2815 * first character on the line, but if the line is2816 * followed by "\ No newline", then we also remove the2817 * last one (which is the newline, of course).2818 */2819 plen = len -1;2820if(len < size && patch[len] =='\\')2821 plen--;2822 first = *patch;2823if(state->apply_in_reverse) {2824if(first =='-')2825 first ='+';2826else if(first =='+')2827 first ='-';2828}28292830switch(first) {2831case'\n':2832/* Newer GNU diff, empty context line */2833if(plen <0)2834/* ... followed by '\No newline'; nothing */2835break;2836*old++ ='\n';2837strbuf_addch(&newlines,'\n');2838add_line_info(&preimage,"\n",1, LINE_COMMON);2839add_line_info(&postimage,"\n",1, LINE_COMMON);2840 is_blank_context =1;2841break;2842case' ':2843if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2844ws_blank_line(patch +1, plen, ws_rule))2845 is_blank_context =1;2846case'-':2847memcpy(old, patch +1, plen);2848add_line_info(&preimage, old, plen,2849(first ==' '? LINE_COMMON :0));2850 old += plen;2851if(first =='-')2852break;2853/* Fall-through for ' ' */2854case'+':2855/* --no-add does not add new lines */2856if(first =='+'&& state->no_add)2857break;28582859 start = newlines.len;2860if(first !='+'||2861!state->whitespace_error ||2862 ws_error_action != correct_ws_error) {2863strbuf_add(&newlines, patch +1, plen);2864}2865else{2866ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2867}2868add_line_info(&postimage, newlines.buf + start, newlines.len - start,2869(first =='+'?0: LINE_COMMON));2870if(first =='+'&&2871(ws_rule & WS_BLANK_AT_EOF) &&2872ws_blank_line(patch +1, plen, ws_rule))2873 added_blank_line =1;2874break;2875case'@':case'\\':2876/* Ignore it, we already handled it */2877break;2878default:2879if(state->apply_verbosely)2880error(_("invalid start of line: '%c'"), first);2881 applied_pos = -1;2882goto out;2883}2884if(added_blank_line) {2885if(!new_blank_lines_at_end)2886 found_new_blank_lines_at_end = hunk_linenr;2887 new_blank_lines_at_end++;2888}2889else if(is_blank_context)2890;2891else2892 new_blank_lines_at_end =0;2893 patch += len;2894 size -= len;2895 hunk_linenr++;2896}2897if(inaccurate_eof &&2898 old > oldlines && old[-1] =='\n'&&2899 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2900 old--;2901strbuf_setlen(&newlines, newlines.len -1);2902}29032904 leading = frag->leading;2905 trailing = frag->trailing;29062907/*2908 * A hunk to change lines at the beginning would begin with2909 * @@ -1,L +N,M @@2910 * but we need to be careful. -U0 that inserts before the second2911 * line also has this pattern.2912 *2913 * And a hunk to add to an empty file would begin with2914 * @@ -0,0 +N,M @@2915 *2916 * In other words, a hunk that is (frag->oldpos <= 1) with or2917 * without leading context must match at the beginning.2918 */2919 match_beginning = (!frag->oldpos ||2920(frag->oldpos ==1&& !state->unidiff_zero));29212922/*2923 * A hunk without trailing lines must match at the end.2924 * However, we simply cannot tell if a hunk must match end2925 * from the lack of trailing lines if the patch was generated2926 * with unidiff without any context.2927 */2928 match_end = !state->unidiff_zero && !trailing;29292930 pos = frag->newpos ? (frag->newpos -1) :0;2931 preimage.buf = oldlines;2932 preimage.len = old - oldlines;2933 postimage.buf = newlines.buf;2934 postimage.len = newlines.len;2935 preimage.line = preimage.line_allocated;2936 postimage.line = postimage.line_allocated;29372938for(;;) {29392940 applied_pos =find_pos(img, &preimage, &postimage, pos,2941 ws_rule, match_beginning, match_end);29422943if(applied_pos >=0)2944break;29452946/* Am I at my context limits? */2947if((leading <= state->p_context) && (trailing <= state->p_context))2948break;2949if(match_beginning || match_end) {2950 match_beginning = match_end =0;2951continue;2952}29532954/*2955 * Reduce the number of context lines; reduce both2956 * leading and trailing if they are equal otherwise2957 * just reduce the larger context.2958 */2959if(leading >= trailing) {2960remove_first_line(&preimage);2961remove_first_line(&postimage);2962 pos--;2963 leading--;2964}2965if(trailing > leading) {2966remove_last_line(&preimage);2967remove_last_line(&postimage);2968 trailing--;2969}2970}29712972if(applied_pos >=0) {2973if(new_blank_lines_at_end &&2974 preimage.nr + applied_pos >= img->nr &&2975(ws_rule & WS_BLANK_AT_EOF) &&2976 ws_error_action != nowarn_ws_error) {2977record_ws_error(state, WS_BLANK_AT_EOF,"+",1,2978 found_new_blank_lines_at_end);2979if(ws_error_action == correct_ws_error) {2980while(new_blank_lines_at_end--)2981remove_last_line(&postimage);2982}2983/*2984 * We would want to prevent write_out_results()2985 * from taking place in apply_patch() that follows2986 * the callchain led us here, which is:2987 * apply_patch->check_patch_list->check_patch->2988 * apply_data->apply_fragments->apply_one_fragment2989 */2990if(ws_error_action == die_on_ws_error)2991 state->apply =0;2992}29932994if(state->apply_verbosely && applied_pos != pos) {2995int offset = applied_pos - pos;2996if(state->apply_in_reverse)2997 offset =0- offset;2998fprintf_ln(stderr,2999Q_("Hunk #%dsucceeded at%d(offset%dline).",3000"Hunk #%dsucceeded at%d(offset%dlines).",3001 offset),3002 nth_fragment, applied_pos +1, offset);3003}30043005/*3006 * Warn if it was necessary to reduce the number3007 * of context lines.3008 */3009if((leading != frag->leading) ||3010(trailing != frag->trailing))3011fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"3012" to apply fragment at%d"),3013 leading, trailing, applied_pos+1);3014update_image(state, img, applied_pos, &preimage, &postimage);3015}else{3016if(state->apply_verbosely)3017error(_("while searching for:\n%.*s"),3018(int)(old - oldlines), oldlines);3019}30203021out:3022free(oldlines);3023strbuf_release(&newlines);3024free(preimage.line_allocated);3025free(postimage.line_allocated);30263027return(applied_pos <0);3028}30293030static intapply_binary_fragment(struct apply_state *state,3031struct image *img,3032struct patch *patch)3033{3034struct fragment *fragment = patch->fragments;3035unsigned long len;3036void*dst;30373038if(!fragment)3039returnerror(_("missing binary patch data for '%s'"),3040 patch->new_name ?3041 patch->new_name :3042 patch->old_name);30433044/* Binary patch is irreversible without the optional second hunk */3045if(state->apply_in_reverse) {3046if(!fragment->next)3047returnerror("cannot reverse-apply a binary patch "3048"without the reverse hunk to '%s'",3049 patch->new_name3050? patch->new_name : patch->old_name);3051 fragment = fragment->next;3052}3053switch(fragment->binary_patch_method) {3054case BINARY_DELTA_DEFLATED:3055 dst =patch_delta(img->buf, img->len, fragment->patch,3056 fragment->size, &len);3057if(!dst)3058return-1;3059clear_image(img);3060 img->buf = dst;3061 img->len = len;3062return0;3063case BINARY_LITERAL_DEFLATED:3064clear_image(img);3065 img->len = fragment->size;3066 img->buf =xmemdupz(fragment->patch, img->len);3067return0;3068}3069return-1;3070}30713072/*3073 * Replace "img" with the result of applying the binary patch.3074 * The binary patch data itself in patch->fragment is still kept3075 * but the preimage prepared by the caller in "img" is freed here3076 * or in the helper function apply_binary_fragment() this calls.3077 */3078static intapply_binary(struct apply_state *state,3079struct image *img,3080struct patch *patch)3081{3082const char*name = patch->old_name ? patch->old_name : patch->new_name;3083unsigned char sha1[20];30843085/*3086 * For safety, we require patch index line to contain3087 * full 40-byte textual SHA1 for old and new, at least for now.3088 */3089if(strlen(patch->old_sha1_prefix) !=40||3090strlen(patch->new_sha1_prefix) !=40||3091get_sha1_hex(patch->old_sha1_prefix, sha1) ||3092get_sha1_hex(patch->new_sha1_prefix, sha1))3093returnerror("cannot apply binary patch to '%s' "3094"without full index line", name);30953096if(patch->old_name) {3097/*3098 * See if the old one matches what the patch3099 * applies to.3100 */3101hash_sha1_file(img->buf, img->len, blob_type, sha1);3102if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3103returnerror("the patch applies to '%s' (%s), "3104"which does not match the "3105"current contents.",3106 name,sha1_to_hex(sha1));3107}3108else{3109/* Otherwise, the old one must be empty. */3110if(img->len)3111returnerror("the patch applies to an empty "3112"'%s' but it is not empty", name);3113}31143115get_sha1_hex(patch->new_sha1_prefix, sha1);3116if(is_null_sha1(sha1)) {3117clear_image(img);3118return0;/* deletion patch */3119}31203121if(has_sha1_file(sha1)) {3122/* We already have the postimage */3123enum object_type type;3124unsigned long size;3125char*result;31263127 result =read_sha1_file(sha1, &type, &size);3128if(!result)3129returnerror("the necessary postimage%sfor "3130"'%s' cannot be read",3131 patch->new_sha1_prefix, name);3132clear_image(img);3133 img->buf = result;3134 img->len = size;3135}else{3136/*3137 * We have verified buf matches the preimage;3138 * apply the patch data to it, which is stored3139 * in the patch->fragments->{patch,size}.3140 */3141if(apply_binary_fragment(state, img, patch))3142returnerror(_("binary patch does not apply to '%s'"),3143 name);31443145/* verify that the result matches */3146hash_sha1_file(img->buf, img->len, blob_type, sha1);3147if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3148returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3149 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3150}31513152return0;3153}31543155static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3156{3157struct fragment *frag = patch->fragments;3158const char*name = patch->old_name ? patch->old_name : patch->new_name;3159unsigned ws_rule = patch->ws_rule;3160unsigned inaccurate_eof = patch->inaccurate_eof;3161int nth =0;31623163if(patch->is_binary)3164returnapply_binary(state, img, patch);31653166while(frag) {3167 nth++;3168if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3169error(_("patch failed:%s:%ld"), name, frag->oldpos);3170if(!state->apply_with_reject)3171return-1;3172 frag->rejected =1;3173}3174 frag = frag->next;3175}3176return0;3177}31783179static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3180{3181if(S_ISGITLINK(mode)) {3182strbuf_grow(buf,100);3183strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3184}else{3185enum object_type type;3186unsigned long sz;3187char*result;31883189 result =read_sha1_file(sha1, &type, &sz);3190if(!result)3191return-1;3192/* XXX read_sha1_file NUL-terminates */3193strbuf_attach(buf, result, sz, sz +1);3194}3195return0;3196}31973198static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3199{3200if(!ce)3201return0;3202returnread_blob_object(buf, ce->sha1, ce->ce_mode);3203}32043205static struct patch *in_fn_table(const char*name)3206{3207struct string_list_item *item;32083209if(name == NULL)3210return NULL;32113212 item =string_list_lookup(&fn_table, name);3213if(item != NULL)3214return(struct patch *)item->util;32153216return NULL;3217}32183219/*3220 * item->util in the filename table records the status of the path.3221 * Usually it points at a patch (whose result records the contents3222 * of it after applying it), but it could be PATH_WAS_DELETED for a3223 * path that a previously applied patch has already removed, or3224 * PATH_TO_BE_DELETED for a path that a later patch would remove.3225 *3226 * The latter is needed to deal with a case where two paths A and B3227 * are swapped by first renaming A to B and then renaming B to A;3228 * moving A to B should not be prevented due to presence of B as we3229 * will remove it in a later patch.3230 */3231#define PATH_TO_BE_DELETED ((struct patch *) -2)3232#define PATH_WAS_DELETED ((struct patch *) -1)32333234static intto_be_deleted(struct patch *patch)3235{3236return patch == PATH_TO_BE_DELETED;3237}32383239static intwas_deleted(struct patch *patch)3240{3241return patch == PATH_WAS_DELETED;3242}32433244static voidadd_to_fn_table(struct patch *patch)3245{3246struct string_list_item *item;32473248/*3249 * Always add new_name unless patch is a deletion3250 * This should cover the cases for normal diffs,3251 * file creations and copies3252 */3253if(patch->new_name != NULL) {3254 item =string_list_insert(&fn_table, patch->new_name);3255 item->util = patch;3256}32573258/*3259 * store a failure on rename/deletion cases because3260 * later chunks shouldn't patch old names3261 */3262if((patch->new_name == NULL) || (patch->is_rename)) {3263 item =string_list_insert(&fn_table, patch->old_name);3264 item->util = PATH_WAS_DELETED;3265}3266}32673268static voidprepare_fn_table(struct patch *patch)3269{3270/*3271 * store information about incoming file deletion3272 */3273while(patch) {3274if((patch->new_name == NULL) || (patch->is_rename)) {3275struct string_list_item *item;3276 item =string_list_insert(&fn_table, patch->old_name);3277 item->util = PATH_TO_BE_DELETED;3278}3279 patch = patch->next;3280}3281}32823283static intcheckout_target(struct index_state *istate,3284struct cache_entry *ce,struct stat *st)3285{3286struct checkout costate;32873288memset(&costate,0,sizeof(costate));3289 costate.base_dir ="";3290 costate.refresh_cache =1;3291 costate.istate = istate;3292if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3293returnerror(_("cannot checkout%s"), ce->name);3294return0;3295}32963297static struct patch *previous_patch(struct patch *patch,int*gone)3298{3299struct patch *previous;33003301*gone =0;3302if(patch->is_copy || patch->is_rename)3303return NULL;/* "git" patches do not depend on the order */33043305 previous =in_fn_table(patch->old_name);3306if(!previous)3307return NULL;33083309if(to_be_deleted(previous))3310return NULL;/* the deletion hasn't happened yet */33113312if(was_deleted(previous))3313*gone =1;33143315return previous;3316}33173318static intverify_index_match(const struct cache_entry *ce,struct stat *st)3319{3320if(S_ISGITLINK(ce->ce_mode)) {3321if(!S_ISDIR(st->st_mode))3322return-1;3323return0;3324}3325returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3326}33273328#define SUBMODULE_PATCH_WITHOUT_INDEX 133293330static intload_patch_target(struct apply_state *state,3331struct strbuf *buf,3332const struct cache_entry *ce,3333struct stat *st,3334const char*name,3335unsigned expected_mode)3336{3337if(state->cached || state->check_index) {3338if(read_file_or_gitlink(ce, buf))3339returnerror(_("read of%sfailed"), name);3340}else if(name) {3341if(S_ISGITLINK(expected_mode)) {3342if(ce)3343returnread_file_or_gitlink(ce, buf);3344else3345return SUBMODULE_PATCH_WITHOUT_INDEX;3346}else if(has_symlink_leading_path(name,strlen(name))) {3347returnerror(_("reading from '%s' beyond a symbolic link"), name);3348}else{3349if(read_old_data(st, name, buf))3350returnerror(_("read of%sfailed"), name);3351}3352}3353return0;3354}33553356/*3357 * We are about to apply "patch"; populate the "image" with the3358 * current version we have, from the working tree or from the index,3359 * depending on the situation e.g. --cached/--index. If we are3360 * applying a non-git patch that incrementally updates the tree,3361 * we read from the result of a previous diff.3362 */3363static intload_preimage(struct apply_state *state,3364struct image *image,3365struct patch *patch,struct stat *st,3366const struct cache_entry *ce)3367{3368struct strbuf buf = STRBUF_INIT;3369size_t len;3370char*img;3371struct patch *previous;3372int status;33733374 previous =previous_patch(patch, &status);3375if(status)3376returnerror(_("path%shas been renamed/deleted"),3377 patch->old_name);3378if(previous) {3379/* We have a patched copy in memory; use that. */3380strbuf_add(&buf, previous->result, previous->resultsize);3381}else{3382 status =load_patch_target(state, &buf, ce, st,3383 patch->old_name, patch->old_mode);3384if(status <0)3385return status;3386else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3387/*3388 * There is no way to apply subproject3389 * patch without looking at the index.3390 * NEEDSWORK: shouldn't this be flagged3391 * as an error???3392 */3393free_fragment_list(patch->fragments);3394 patch->fragments = NULL;3395}else if(status) {3396returnerror(_("read of%sfailed"), patch->old_name);3397}3398}33993400 img =strbuf_detach(&buf, &len);3401prepare_image(image, img, len, !patch->is_binary);3402return0;3403}34043405static intthree_way_merge(struct image *image,3406char*path,3407const unsigned char*base,3408const unsigned char*ours,3409const unsigned char*theirs)3410{3411 mmfile_t base_file, our_file, their_file;3412 mmbuffer_t result = { NULL };3413int status;34143415read_mmblob(&base_file, base);3416read_mmblob(&our_file, ours);3417read_mmblob(&their_file, theirs);3418 status =ll_merge(&result, path,3419&base_file,"base",3420&our_file,"ours",3421&their_file,"theirs", NULL);3422free(base_file.ptr);3423free(our_file.ptr);3424free(their_file.ptr);3425if(status <0|| !result.ptr) {3426free(result.ptr);3427return-1;3428}3429clear_image(image);3430 image->buf = result.ptr;3431 image->len = result.size;34323433return status;3434}34353436/*3437 * When directly falling back to add/add three-way merge, we read from3438 * the current contents of the new_name. In no cases other than that3439 * this function will be called.3440 */3441static intload_current(struct apply_state *state,3442struct image *image,3443struct patch *patch)3444{3445struct strbuf buf = STRBUF_INIT;3446int status, pos;3447size_t len;3448char*img;3449struct stat st;3450struct cache_entry *ce;3451char*name = patch->new_name;3452unsigned mode = patch->new_mode;34533454if(!patch->is_new)3455die("BUG: patch to%sis not a creation", patch->old_name);34563457 pos =cache_name_pos(name,strlen(name));3458if(pos <0)3459returnerror(_("%s: does not exist in index"), name);3460 ce = active_cache[pos];3461if(lstat(name, &st)) {3462if(errno != ENOENT)3463returnerror(_("%s:%s"), name,strerror(errno));3464if(checkout_target(&the_index, ce, &st))3465return-1;3466}3467if(verify_index_match(ce, &st))3468returnerror(_("%s: does not match index"), name);34693470 status =load_patch_target(state, &buf, ce, &st, name, mode);3471if(status <0)3472return status;3473else if(status)3474return-1;3475 img =strbuf_detach(&buf, &len);3476prepare_image(image, img, len, !patch->is_binary);3477return0;3478}34793480static inttry_threeway(struct apply_state *state,3481struct image *image,3482struct patch *patch,3483struct stat *st,3484const struct cache_entry *ce)3485{3486unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3487struct strbuf buf = STRBUF_INIT;3488size_t len;3489int status;3490char*img;3491struct image tmp_image;34923493/* No point falling back to 3-way merge in these cases */3494if(patch->is_delete ||3495S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3496return-1;34973498/* Preimage the patch was prepared for */3499if(patch->is_new)3500write_sha1_file("",0, blob_type, pre_sha1);3501else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3502read_blob_object(&buf, pre_sha1, patch->old_mode))3503returnerror("repository lacks the necessary blob to fall back on 3-way merge.");35043505fprintf(stderr,"Falling back to three-way merge...\n");35063507 img =strbuf_detach(&buf, &len);3508prepare_image(&tmp_image, img, len,1);3509/* Apply the patch to get the post image */3510if(apply_fragments(state, &tmp_image, patch) <0) {3511clear_image(&tmp_image);3512return-1;3513}3514/* post_sha1[] is theirs */3515write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3516clear_image(&tmp_image);35173518/* our_sha1[] is ours */3519if(patch->is_new) {3520if(load_current(state, &tmp_image, patch))3521returnerror("cannot read the current contents of '%s'",3522 patch->new_name);3523}else{3524if(load_preimage(state, &tmp_image, patch, st, ce))3525returnerror("cannot read the current contents of '%s'",3526 patch->old_name);3527}3528write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3529clear_image(&tmp_image);35303531/* in-core three-way merge between post and our using pre as base */3532 status =three_way_merge(image, patch->new_name,3533 pre_sha1, our_sha1, post_sha1);3534if(status <0) {3535fprintf(stderr,"Failed to fall back on three-way merge...\n");3536return status;3537}35383539if(status) {3540 patch->conflicted_threeway =1;3541if(patch->is_new)3542oidclr(&patch->threeway_stage[0]);3543else3544hashcpy(patch->threeway_stage[0].hash, pre_sha1);3545hashcpy(patch->threeway_stage[1].hash, our_sha1);3546hashcpy(patch->threeway_stage[2].hash, post_sha1);3547fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3548}else{3549fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3550}3551return0;3552}35533554static intapply_data(struct apply_state *state,struct patch *patch,3555struct stat *st,const struct cache_entry *ce)3556{3557struct image image;35583559if(load_preimage(state, &image, patch, st, ce) <0)3560return-1;35613562if(patch->direct_to_threeway ||3563apply_fragments(state, &image, patch) <0) {3564/* Note: with --reject, apply_fragments() returns 0 */3565if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3566return-1;3567}3568 patch->result = image.buf;3569 patch->resultsize = image.len;3570add_to_fn_table(patch);3571free(image.line_allocated);35723573if(0< patch->is_delete && patch->resultsize)3574returnerror(_("removal patch leaves file contents"));35753576return0;3577}35783579/*3580 * If "patch" that we are looking at modifies or deletes what we have,3581 * we would want it not to lose any local modification we have, either3582 * in the working tree or in the index.3583 *3584 * This also decides if a non-git patch is a creation patch or a3585 * modification to an existing empty file. We do not check the state3586 * of the current tree for a creation patch in this function; the caller3587 * check_patch() separately makes sure (and errors out otherwise) that3588 * the path the patch creates does not exist in the current tree.3589 */3590static intcheck_preimage(struct apply_state *state,3591struct patch *patch,3592struct cache_entry **ce,3593struct stat *st)3594{3595const char*old_name = patch->old_name;3596struct patch *previous = NULL;3597int stat_ret =0, status;3598unsigned st_mode =0;35993600if(!old_name)3601return0;36023603assert(patch->is_new <=0);3604 previous =previous_patch(patch, &status);36053606if(status)3607returnerror(_("path%shas been renamed/deleted"), old_name);3608if(previous) {3609 st_mode = previous->new_mode;3610}else if(!state->cached) {3611 stat_ret =lstat(old_name, st);3612if(stat_ret && errno != ENOENT)3613returnerror(_("%s:%s"), old_name,strerror(errno));3614}36153616if(state->check_index && !previous) {3617int pos =cache_name_pos(old_name,strlen(old_name));3618if(pos <0) {3619if(patch->is_new <0)3620goto is_new;3621returnerror(_("%s: does not exist in index"), old_name);3622}3623*ce = active_cache[pos];3624if(stat_ret <0) {3625if(checkout_target(&the_index, *ce, st))3626return-1;3627}3628if(!state->cached &&verify_index_match(*ce, st))3629returnerror(_("%s: does not match index"), old_name);3630if(state->cached)3631 st_mode = (*ce)->ce_mode;3632}else if(stat_ret <0) {3633if(patch->is_new <0)3634goto is_new;3635returnerror(_("%s:%s"), old_name,strerror(errno));3636}36373638if(!state->cached && !previous)3639 st_mode =ce_mode_from_stat(*ce, st->st_mode);36403641if(patch->is_new <0)3642 patch->is_new =0;3643if(!patch->old_mode)3644 patch->old_mode = st_mode;3645if((st_mode ^ patch->old_mode) & S_IFMT)3646returnerror(_("%s: wrong type"), old_name);3647if(st_mode != patch->old_mode)3648warning(_("%shas type%o, expected%o"),3649 old_name, st_mode, patch->old_mode);3650if(!patch->new_mode && !patch->is_delete)3651 patch->new_mode = st_mode;3652return0;36533654 is_new:3655 patch->is_new =1;3656 patch->is_delete =0;3657free(patch->old_name);3658 patch->old_name = NULL;3659return0;3660}366136623663#define EXISTS_IN_INDEX 13664#define EXISTS_IN_WORKTREE 236653666static intcheck_to_create(struct apply_state *state,3667const char*new_name,3668int ok_if_exists)3669{3670struct stat nst;36713672if(state->check_index &&3673cache_name_pos(new_name,strlen(new_name)) >=0&&3674!ok_if_exists)3675return EXISTS_IN_INDEX;3676if(state->cached)3677return0;36783679if(!lstat(new_name, &nst)) {3680if(S_ISDIR(nst.st_mode) || ok_if_exists)3681return0;3682/*3683 * A leading component of new_name might be a symlink3684 * that is going to be removed with this patch, but3685 * still pointing at somewhere that has the path.3686 * In such a case, path "new_name" does not exist as3687 * far as git is concerned.3688 */3689if(has_symlink_leading_path(new_name,strlen(new_name)))3690return0;36913692return EXISTS_IN_WORKTREE;3693}else if((errno != ENOENT) && (errno != ENOTDIR)) {3694returnerror("%s:%s", new_name,strerror(errno));3695}3696return0;3697}36983699/*3700 * We need to keep track of how symlinks in the preimage are3701 * manipulated by the patches. A patch to add a/b/c where a/b3702 * is a symlink should not be allowed to affect the directory3703 * the symlink points at, but if the same patch removes a/b,3704 * it is perfectly fine, as the patch removes a/b to make room3705 * to create a directory a/b so that a/b/c can be created.3706 */3707static struct string_list symlink_changes;3708#define SYMLINK_GOES_AWAY 013709#define SYMLINK_IN_RESULT 0237103711static uintptr_tregister_symlink_changes(const char*path,uintptr_t what)3712{3713struct string_list_item *ent;37143715 ent =string_list_lookup(&symlink_changes, path);3716if(!ent) {3717 ent =string_list_insert(&symlink_changes, path);3718 ent->util = (void*)0;3719}3720 ent->util = (void*)(what | ((uintptr_t)ent->util));3721return(uintptr_t)ent->util;3722}37233724static uintptr_tcheck_symlink_changes(const char*path)3725{3726struct string_list_item *ent;37273728 ent =string_list_lookup(&symlink_changes, path);3729if(!ent)3730return0;3731return(uintptr_t)ent->util;3732}37333734static voidprepare_symlink_changes(struct patch *patch)3735{3736for( ; patch; patch = patch->next) {3737if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3738(patch->is_rename || patch->is_delete))3739/* the symlink at patch->old_name is removed */3740register_symlink_changes(patch->old_name, SYMLINK_GOES_AWAY);37413742if(patch->new_name &&S_ISLNK(patch->new_mode))3743/* the symlink at patch->new_name is created or remains */3744register_symlink_changes(patch->new_name, SYMLINK_IN_RESULT);3745}3746}37473748static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3749{3750do{3751unsigned int change;37523753while(--name->len && name->buf[name->len] !='/')3754;/* scan backwards */3755if(!name->len)3756break;3757 name->buf[name->len] ='\0';3758 change =check_symlink_changes(name->buf);3759if(change & SYMLINK_IN_RESULT)3760return1;3761if(change & SYMLINK_GOES_AWAY)3762/*3763 * This cannot be "return 0", because we may3764 * see a new one created at a higher level.3765 */3766continue;37673768/* otherwise, check the preimage */3769if(state->check_index) {3770struct cache_entry *ce;37713772 ce =cache_file_exists(name->buf, name->len, ignore_case);3773if(ce &&S_ISLNK(ce->ce_mode))3774return1;3775}else{3776struct stat st;3777if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3778return1;3779}3780}while(1);3781return0;3782}37833784static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3785{3786int ret;3787struct strbuf name = STRBUF_INIT;37883789assert(*name_ !='\0');3790strbuf_addstr(&name, name_);3791 ret =path_is_beyond_symlink_1(state, &name);3792strbuf_release(&name);37933794return ret;3795}37963797static voiddie_on_unsafe_path(struct patch *patch)3798{3799const char*old_name = NULL;3800const char*new_name = NULL;3801if(patch->is_delete)3802 old_name = patch->old_name;3803else if(!patch->is_new && !patch->is_copy)3804 old_name = patch->old_name;3805if(!patch->is_delete)3806 new_name = patch->new_name;38073808if(old_name && !verify_path(old_name))3809die(_("invalid path '%s'"), old_name);3810if(new_name && !verify_path(new_name))3811die(_("invalid path '%s'"), new_name);3812}38133814/*3815 * Check and apply the patch in-core; leave the result in patch->result3816 * for the caller to write it out to the final destination.3817 */3818static intcheck_patch(struct apply_state *state,struct patch *patch)3819{3820struct stat st;3821const char*old_name = patch->old_name;3822const char*new_name = patch->new_name;3823const char*name = old_name ? old_name : new_name;3824struct cache_entry *ce = NULL;3825struct patch *tpatch;3826int ok_if_exists;3827int status;38283829 patch->rejected =1;/* we will drop this after we succeed */38303831 status =check_preimage(state, patch, &ce, &st);3832if(status)3833return status;3834 old_name = patch->old_name;38353836/*3837 * A type-change diff is always split into a patch to delete3838 * old, immediately followed by a patch to create new (see3839 * diff.c::run_diff()); in such a case it is Ok that the entry3840 * to be deleted by the previous patch is still in the working3841 * tree and in the index.3842 *3843 * A patch to swap-rename between A and B would first rename A3844 * to B and then rename B to A. While applying the first one,3845 * the presence of B should not stop A from getting renamed to3846 * B; ask to_be_deleted() about the later rename. Removal of3847 * B and rename from A to B is handled the same way by asking3848 * was_deleted().3849 */3850if((tpatch =in_fn_table(new_name)) &&3851(was_deleted(tpatch) ||to_be_deleted(tpatch)))3852 ok_if_exists =1;3853else3854 ok_if_exists =0;38553856if(new_name &&3857((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3858int err =check_to_create(state, new_name, ok_if_exists);38593860if(err && state->threeway) {3861 patch->direct_to_threeway =1;3862}else switch(err) {3863case0:3864break;/* happy */3865case EXISTS_IN_INDEX:3866returnerror(_("%s: already exists in index"), new_name);3867break;3868case EXISTS_IN_WORKTREE:3869returnerror(_("%s: already exists in working directory"),3870 new_name);3871default:3872return err;3873}38743875if(!patch->new_mode) {3876if(0< patch->is_new)3877 patch->new_mode = S_IFREG |0644;3878else3879 patch->new_mode = patch->old_mode;3880}3881}38823883if(new_name && old_name) {3884int same = !strcmp(old_name, new_name);3885if(!patch->new_mode)3886 patch->new_mode = patch->old_mode;3887if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3888if(same)3889returnerror(_("new mode (%o) of%sdoes not "3890"match old mode (%o)"),3891 patch->new_mode, new_name,3892 patch->old_mode);3893else3894returnerror(_("new mode (%o) of%sdoes not "3895"match old mode (%o) of%s"),3896 patch->new_mode, new_name,3897 patch->old_mode, old_name);3898}3899}39003901if(!state->unsafe_paths)3902die_on_unsafe_path(patch);39033904/*3905 * An attempt to read from or delete a path that is beyond a3906 * symbolic link will be prevented by load_patch_target() that3907 * is called at the beginning of apply_data() so we do not3908 * have to worry about a patch marked with "is_delete" bit3909 * here. We however need to make sure that the patch result3910 * is not deposited to a path that is beyond a symbolic link3911 * here.3912 */3913if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3914returnerror(_("affected file '%s' is beyond a symbolic link"),3915 patch->new_name);39163917if(apply_data(state, patch, &st, ce) <0)3918returnerror(_("%s: patch does not apply"), name);3919 patch->rejected =0;3920return0;3921}39223923static intcheck_patch_list(struct apply_state *state,struct patch *patch)3924{3925int err =0;39263927prepare_symlink_changes(patch);3928prepare_fn_table(patch);3929while(patch) {3930if(state->apply_verbosely)3931say_patch_name(stderr,3932_("Checking patch%s..."), patch);3933 err |=check_patch(state, patch);3934 patch = patch->next;3935}3936return err;3937}39383939/* This function tries to read the sha1 from the current index */3940static intget_current_sha1(const char*path,unsigned char*sha1)3941{3942int pos;39433944if(read_cache() <0)3945return-1;3946 pos =cache_name_pos(path,strlen(path));3947if(pos <0)3948return-1;3949hashcpy(sha1, active_cache[pos]->sha1);3950return0;3951}39523953static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3954{3955/*3956 * A usable gitlink patch has only one fragment (hunk) that looks like:3957 * @@ -1 +1 @@3958 * -Subproject commit <old sha1>3959 * +Subproject commit <new sha1>3960 * or3961 * @@ -1 +0,0 @@3962 * -Subproject commit <old sha1>3963 * for a removal patch.3964 */3965struct fragment *hunk = p->fragments;3966static const char heading[] ="-Subproject commit ";3967char*preimage;39683969if(/* does the patch have only one hunk? */3970 hunk && !hunk->next &&3971/* is its preimage one line? */3972 hunk->oldpos ==1&& hunk->oldlines ==1&&3973/* does preimage begin with the heading? */3974(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3975starts_with(++preimage, heading) &&3976/* does it record full SHA-1? */3977!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3978 preimage[sizeof(heading) +40-1] =='\n'&&3979/* does the abbreviated name on the index line agree with it? */3980starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3981return0;/* it all looks fine */39823983/* we may have full object name on the index line */3984returnget_sha1_hex(p->old_sha1_prefix, sha1);3985}39863987/* Build an index that contains the just the files needed for a 3way merge */3988static voidbuild_fake_ancestor(struct patch *list,const char*filename)3989{3990struct patch *patch;3991struct index_state result = { NULL };3992static struct lock_file lock;39933994/* Once we start supporting the reverse patch, it may be3995 * worth showing the new sha1 prefix, but until then...3996 */3997for(patch = list; patch; patch = patch->next) {3998unsigned char sha1[20];3999struct cache_entry *ce;4000const char*name;40014002 name = patch->old_name ? patch->old_name : patch->new_name;4003if(0< patch->is_new)4004continue;40054006if(S_ISGITLINK(patch->old_mode)) {4007if(!preimage_sha1_in_gitlink_patch(patch, sha1))4008;/* ok, the textual part looks sane */4009else4010die("sha1 information is lacking or useless for submodule%s",4011 name);4012}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {4013;/* ok */4014}else if(!patch->lines_added && !patch->lines_deleted) {4015/* mode-only change: update the current */4016if(get_current_sha1(patch->old_name, sha1))4017die("mode change for%s, which is not "4018"in current HEAD", name);4019}else4020die("sha1 information is lacking or useless "4021"(%s).", name);40224023 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);4024if(!ce)4025die(_("make_cache_entry failed for path '%s'"), name);4026if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))4027die("Could not add%sto temporary index", name);4028}40294030hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);4031if(write_locked_index(&result, &lock, COMMIT_LOCK))4032die("Could not write temporary index to%s", filename);40334034discard_index(&result);4035}40364037static voidstat_patch_list(struct patch *patch)4038{4039int files, adds, dels;40404041for(files = adds = dels =0; patch ; patch = patch->next) {4042 files++;4043 adds += patch->lines_added;4044 dels += patch->lines_deleted;4045show_stats(patch);4046}40474048print_stat_summary(stdout, files, adds, dels);4049}40504051static voidnumstat_patch_list(struct apply_state *state,4052struct patch *patch)4053{4054for( ; patch; patch = patch->next) {4055const char*name;4056 name = patch->new_name ? patch->new_name : patch->old_name;4057if(patch->is_binary)4058printf("-\t-\t");4059else4060printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4061write_name_quoted(name, stdout, state->line_termination);4062}4063}40644065static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4066{4067if(mode)4068printf("%smode%06o%s\n", newdelete, mode, name);4069else4070printf("%s %s\n", newdelete, name);4071}40724073static voidshow_mode_change(struct patch *p,int show_name)4074{4075if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4076if(show_name)4077printf(" mode change%06o =>%06o%s\n",4078 p->old_mode, p->new_mode, p->new_name);4079else4080printf(" mode change%06o =>%06o\n",4081 p->old_mode, p->new_mode);4082}4083}40844085static voidshow_rename_copy(struct patch *p)4086{4087const char*renamecopy = p->is_rename ?"rename":"copy";4088const char*old, *new;40894090/* Find common prefix */4091 old = p->old_name;4092new= p->new_name;4093while(1) {4094const char*slash_old, *slash_new;4095 slash_old =strchr(old,'/');4096 slash_new =strchr(new,'/');4097if(!slash_old ||4098!slash_new ||4099 slash_old - old != slash_new -new||4100memcmp(old,new, slash_new -new))4101break;4102 old = slash_old +1;4103new= slash_new +1;4104}4105/* p->old_name thru old is the common prefix, and old and new4106 * through the end of names are renames4107 */4108if(old != p->old_name)4109printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4110(int)(old - p->old_name), p->old_name,4111 old,new, p->score);4112else4113printf("%s %s=>%s(%d%%)\n", renamecopy,4114 p->old_name, p->new_name, p->score);4115show_mode_change(p,0);4116}41174118static voidsummary_patch_list(struct patch *patch)4119{4120struct patch *p;41214122for(p = patch; p; p = p->next) {4123if(p->is_new)4124show_file_mode_name("create", p->new_mode, p->new_name);4125else if(p->is_delete)4126show_file_mode_name("delete", p->old_mode, p->old_name);4127else{4128if(p->is_rename || p->is_copy)4129show_rename_copy(p);4130else{4131if(p->score) {4132printf(" rewrite%s(%d%%)\n",4133 p->new_name, p->score);4134show_mode_change(p,0);4135}4136else4137show_mode_change(p,1);4138}4139}4140}4141}41424143static voidpatch_stats(struct patch *patch)4144{4145int lines = patch->lines_added + patch->lines_deleted;41464147if(lines > max_change)4148 max_change = lines;4149if(patch->old_name) {4150int len =quote_c_style(patch->old_name, NULL, NULL,0);4151if(!len)4152 len =strlen(patch->old_name);4153if(len > max_len)4154 max_len = len;4155}4156if(patch->new_name) {4157int len =quote_c_style(patch->new_name, NULL, NULL,0);4158if(!len)4159 len =strlen(patch->new_name);4160if(len > max_len)4161 max_len = len;4162}4163}41644165static voidremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4166{4167if(state->update_index) {4168if(remove_file_from_cache(patch->old_name) <0)4169die(_("unable to remove%sfrom index"), patch->old_name);4170}4171if(!state->cached) {4172if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4173remove_path(patch->old_name);4174}4175}4176}41774178static voidadd_index_file(struct apply_state *state,4179const char*path,4180unsigned mode,4181void*buf,4182unsigned long size)4183{4184struct stat st;4185struct cache_entry *ce;4186int namelen =strlen(path);4187unsigned ce_size =cache_entry_size(namelen);41884189if(!state->update_index)4190return;41914192 ce =xcalloc(1, ce_size);4193memcpy(ce->name, path, namelen);4194 ce->ce_mode =create_ce_mode(mode);4195 ce->ce_flags =create_ce_flags(0);4196 ce->ce_namelen = namelen;4197if(S_ISGITLINK(mode)) {4198const char*s;41994200if(!skip_prefix(buf,"Subproject commit ", &s) ||4201get_sha1_hex(s, ce->sha1))4202die(_("corrupt patch for submodule%s"), path);4203}else{4204if(!state->cached) {4205if(lstat(path, &st) <0)4206die_errno(_("unable to stat newly created file '%s'"),4207 path);4208fill_stat_cache_info(ce, &st);4209}4210if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4211die(_("unable to create backing store for newly created file%s"), path);4212}4213if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4214die(_("unable to add cache entry for%s"), path);4215}42164217static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4218{4219int fd;4220struct strbuf nbuf = STRBUF_INIT;42214222if(S_ISGITLINK(mode)) {4223struct stat st;4224if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4225return0;4226returnmkdir(path,0777);4227}42284229if(has_symlinks &&S_ISLNK(mode))4230/* Although buf:size is counted string, it also is NUL4231 * terminated.4232 */4233returnsymlink(buf, path);42344235 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4236if(fd <0)4237return-1;42384239if(convert_to_working_tree(path, buf, size, &nbuf)) {4240 size = nbuf.len;4241 buf = nbuf.buf;4242}4243write_or_die(fd, buf, size);4244strbuf_release(&nbuf);42454246if(close(fd) <0)4247die_errno(_("closing file '%s'"), path);4248return0;4249}42504251/*4252 * We optimistically assume that the directories exist,4253 * which is true 99% of the time anyway. If they don't,4254 * we create them and try again.4255 */4256static voidcreate_one_file(struct apply_state *state,4257char*path,4258unsigned mode,4259const char*buf,4260unsigned long size)4261{4262if(state->cached)4263return;4264if(!try_create_file(path, mode, buf, size))4265return;42664267if(errno == ENOENT) {4268if(safe_create_leading_directories(path))4269return;4270if(!try_create_file(path, mode, buf, size))4271return;4272}42734274if(errno == EEXIST || errno == EACCES) {4275/* We may be trying to create a file where a directory4276 * used to be.4277 */4278struct stat st;4279if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4280 errno = EEXIST;4281}42824283if(errno == EEXIST) {4284unsigned int nr =getpid();42854286for(;;) {4287char newpath[PATH_MAX];4288mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4289if(!try_create_file(newpath, mode, buf, size)) {4290if(!rename(newpath, path))4291return;4292unlink_or_warn(newpath);4293break;4294}4295if(errno != EEXIST)4296break;4297++nr;4298}4299}4300die_errno(_("unable to write file '%s' mode%o"), path, mode);4301}43024303static voidadd_conflicted_stages_file(struct apply_state *state,4304struct patch *patch)4305{4306int stage, namelen;4307unsigned ce_size, mode;4308struct cache_entry *ce;43094310if(!state->update_index)4311return;4312 namelen =strlen(patch->new_name);4313 ce_size =cache_entry_size(namelen);4314 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);43154316remove_file_from_cache(patch->new_name);4317for(stage =1; stage <4; stage++) {4318if(is_null_oid(&patch->threeway_stage[stage -1]))4319continue;4320 ce =xcalloc(1, ce_size);4321memcpy(ce->name, patch->new_name, namelen);4322 ce->ce_mode =create_ce_mode(mode);4323 ce->ce_flags =create_ce_flags(stage);4324 ce->ce_namelen = namelen;4325hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4326if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4327die(_("unable to add cache entry for%s"), patch->new_name);4328}4329}43304331static voidcreate_file(struct apply_state *state,struct patch *patch)4332{4333char*path = patch->new_name;4334unsigned mode = patch->new_mode;4335unsigned long size = patch->resultsize;4336char*buf = patch->result;43374338if(!mode)4339 mode = S_IFREG |0644;4340create_one_file(state, path, mode, buf, size);43414342if(patch->conflicted_threeway)4343add_conflicted_stages_file(state, patch);4344else4345add_index_file(state, path, mode, buf, size);4346}43474348/* phase zero is to remove, phase one is to create */4349static voidwrite_out_one_result(struct apply_state *state,4350struct patch *patch,4351int phase)4352{4353if(patch->is_delete >0) {4354if(phase ==0)4355remove_file(state, patch,1);4356return;4357}4358if(patch->is_new >0|| patch->is_copy) {4359if(phase ==1)4360create_file(state, patch);4361return;4362}4363/*4364 * Rename or modification boils down to the same4365 * thing: remove the old, write the new4366 */4367if(phase ==0)4368remove_file(state, patch, patch->is_rename);4369if(phase ==1)4370create_file(state, patch);4371}43724373static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4374{4375FILE*rej;4376char namebuf[PATH_MAX];4377struct fragment *frag;4378int cnt =0;4379struct strbuf sb = STRBUF_INIT;43804381for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4382if(!frag->rejected)4383continue;4384 cnt++;4385}43864387if(!cnt) {4388if(state->apply_verbosely)4389say_patch_name(stderr,4390_("Applied patch%scleanly."), patch);4391return0;4392}43934394/* This should not happen, because a removal patch that leaves4395 * contents are marked "rejected" at the patch level.4396 */4397if(!patch->new_name)4398die(_("internal error"));43994400/* Say this even without --verbose */4401strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4402"Applying patch %%swith%drejects...",4403 cnt),4404 cnt);4405say_patch_name(stderr, sb.buf, patch);4406strbuf_release(&sb);44074408 cnt =strlen(patch->new_name);4409if(ARRAY_SIZE(namebuf) <= cnt +5) {4410 cnt =ARRAY_SIZE(namebuf) -5;4411warning(_("truncating .rej filename to %.*s.rej"),4412 cnt -1, patch->new_name);4413}4414memcpy(namebuf, patch->new_name, cnt);4415memcpy(namebuf + cnt,".rej",5);44164417 rej =fopen(namebuf,"w");4418if(!rej)4419returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));44204421/* Normal git tools never deal with .rej, so do not pretend4422 * this is a git patch by saying --git or giving extended4423 * headers. While at it, maybe please "kompare" that wants4424 * the trailing TAB and some garbage at the end of line ;-).4425 */4426fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4427 patch->new_name, patch->new_name);4428for(cnt =1, frag = patch->fragments;4429 frag;4430 cnt++, frag = frag->next) {4431if(!frag->rejected) {4432fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4433continue;4434}4435fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4436fprintf(rej,"%.*s", frag->size, frag->patch);4437if(frag->patch[frag->size-1] !='\n')4438fputc('\n', rej);4439}4440fclose(rej);4441return-1;4442}44434444static intwrite_out_results(struct apply_state *state,struct patch *list)4445{4446int phase;4447int errs =0;4448struct patch *l;4449struct string_list cpath = STRING_LIST_INIT_DUP;44504451for(phase =0; phase <2; phase++) {4452 l = list;4453while(l) {4454if(l->rejected)4455 errs =1;4456else{4457write_out_one_result(state, l, phase);4458if(phase ==1) {4459if(write_out_one_reject(state, l))4460 errs =1;4461if(l->conflicted_threeway) {4462string_list_append(&cpath, l->new_name);4463 errs =1;4464}4465}4466}4467 l = l->next;4468}4469}44704471if(cpath.nr) {4472struct string_list_item *item;44734474string_list_sort(&cpath);4475for_each_string_list_item(item, &cpath)4476fprintf(stderr,"U%s\n", item->string);4477string_list_clear(&cpath,0);44784479rerere(0);4480}44814482return errs;4483}44844485static struct lock_file lock_file;44864487#define INACCURATE_EOF (1<<0)4488#define RECOUNT (1<<1)44894490static intapply_patch(struct apply_state *state,4491int fd,4492const char*filename,4493int options)4494{4495size_t offset;4496struct strbuf buf = STRBUF_INIT;/* owns the patch text */4497struct patch *list = NULL, **listp = &list;4498int skipped_patch =0;44994500 state->patch_input_file = filename;4501read_patch_file(&buf, fd);4502 offset =0;4503while(offset < buf.len) {4504struct patch *patch;4505int nr;45064507 patch =xcalloc(1,sizeof(*patch));4508 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4509 patch->recount = !!(options & RECOUNT);4510 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4511if(nr <0) {4512free_patch(patch);4513break;4514}4515if(state->apply_in_reverse)4516reverse_patches(patch);4517if(use_patch(state, patch)) {4518patch_stats(patch);4519*listp = patch;4520 listp = &patch->next;4521}4522else{4523if(state->apply_verbosely)4524say_patch_name(stderr,_("Skipped patch '%s'."), patch);4525free_patch(patch);4526 skipped_patch++;4527}4528 offset += nr;4529}45304531if(!list && !skipped_patch)4532die(_("unrecognized input"));45334534if(state->whitespace_error && (ws_error_action == die_on_ws_error))4535 state->apply =0;45364537 state->update_index = state->check_index && state->apply;4538if(state->update_index && newfd <0)4539 newfd =hold_locked_index(&lock_file,1);45404541if(state->check_index) {4542if(read_cache() <0)4543die(_("unable to read index file"));4544}45454546if((state->check || state->apply) &&4547check_patch_list(state, list) <0&&4548!state->apply_with_reject)4549exit(1);45504551if(state->apply &&write_out_results(state, list)) {4552if(state->apply_with_reject)4553exit(1);4554/* with --3way, we still need to write the index out */4555return1;4556}45574558if(state->fake_ancestor)4559build_fake_ancestor(list, state->fake_ancestor);45604561if(state->diffstat)4562stat_patch_list(list);45634564if(state->numstat)4565numstat_patch_list(state, list);45664567if(state->summary)4568summary_patch_list(list);45694570free_patch_list(list);4571strbuf_release(&buf);4572string_list_clear(&fn_table,0);4573return0;4574}45754576static voidgit_apply_config(void)4577{4578git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4579git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4580git_config(git_default_config, NULL);4581}45824583static intoption_parse_exclude(const struct option *opt,4584const char*arg,int unset)4585{4586struct apply_state *state = opt->value;4587add_name_limit(state, arg,1);4588return0;4589}45904591static intoption_parse_include(const struct option *opt,4592const char*arg,int unset)4593{4594struct apply_state *state = opt->value;4595add_name_limit(state, arg,0);4596 state->has_include =1;4597return0;4598}45994600static intoption_parse_p(const struct option *opt,4601const char*arg,4602int unset)4603{4604struct apply_state *state = opt->value;4605 state->p_value =atoi(arg);4606 state->p_value_known =1;4607return0;4608}46094610static intoption_parse_space_change(const struct option *opt,4611const char*arg,int unset)4612{4613if(unset)4614 ws_ignore_action = ignore_ws_none;4615else4616 ws_ignore_action = ignore_ws_change;4617return0;4618}46194620static intoption_parse_whitespace(const struct option *opt,4621const char*arg,int unset)4622{4623struct apply_state *state = opt->value;46244625 state->whitespace_option = arg;4626parse_whitespace_option(arg);4627return0;4628}46294630static intoption_parse_directory(const struct option *opt,4631const char*arg,int unset)4632{4633struct apply_state *state = opt->value;4634strbuf_reset(&state->root);4635strbuf_addstr(&state->root, arg);4636strbuf_complete(&state->root,'/');4637return0;4638}46394640static voidinit_apply_state(struct apply_state *state,const char*prefix)4641{4642memset(state,0,sizeof(*state));4643 state->prefix = prefix;4644 state->prefix_length = state->prefix ?strlen(state->prefix) :0;4645 state->apply =1;4646 state->line_termination ='\n';4647 state->p_value =1;4648 state->p_context = UINT_MAX;4649strbuf_init(&state->root,0);46504651git_apply_config();4652if(apply_default_whitespace)4653parse_whitespace_option(apply_default_whitespace);4654if(apply_default_ignorewhitespace)4655parse_ignorewhitespace_option(apply_default_ignorewhitespace);4656}46574658static voidclear_apply_state(struct apply_state *state)4659{4660string_list_clear(&state->limit_by_name,0);4661strbuf_release(&state->root);4662}46634664intcmd_apply(int argc,const char**argv,const char*prefix)4665{4666int i;4667int errs =0;4668int is_not_gitdir = !startup_info->have_repository;4669int force_apply =0;4670int options =0;4671int read_stdin =1;4672struct apply_state state;46734674struct option builtin_apply_options[] = {4675{ OPTION_CALLBACK,0,"exclude", &state,N_("path"),4676N_("don't apply changes matching the given path"),46770, option_parse_exclude },4678{ OPTION_CALLBACK,0,"include", &state,N_("path"),4679N_("apply changes matching the given path"),46800, option_parse_include },4681{ OPTION_CALLBACK,'p', NULL, &state,N_("num"),4682N_("remove <num> leading slashes from traditional diff paths"),46830, option_parse_p },4684OPT_BOOL(0,"no-add", &state.no_add,4685N_("ignore additions made by the patch")),4686OPT_BOOL(0,"stat", &state.diffstat,4687N_("instead of applying the patch, output diffstat for the input")),4688OPT_NOOP_NOARG(0,"allow-binary-replacement"),4689OPT_NOOP_NOARG(0,"binary"),4690OPT_BOOL(0,"numstat", &state.numstat,4691N_("show number of added and deleted lines in decimal notation")),4692OPT_BOOL(0,"summary", &state.summary,4693N_("instead of applying the patch, output a summary for the input")),4694OPT_BOOL(0,"check", &state.check,4695N_("instead of applying the patch, see if the patch is applicable")),4696OPT_BOOL(0,"index", &state.check_index,4697N_("make sure the patch is applicable to the current index")),4698OPT_BOOL(0,"cached", &state.cached,4699N_("apply a patch without touching the working tree")),4700OPT_BOOL(0,"unsafe-paths", &state.unsafe_paths,4701N_("accept a patch that touches outside the working area")),4702OPT_BOOL(0,"apply", &force_apply,4703N_("also apply the patch (use with --stat/--summary/--check)")),4704OPT_BOOL('3',"3way", &state.threeway,4705N_("attempt three-way merge if a patch does not apply")),4706OPT_FILENAME(0,"build-fake-ancestor", &state.fake_ancestor,4707N_("build a temporary index based on embedded index information")),4708/* Think twice before adding "--nul" synonym to this */4709OPT_SET_INT('z', NULL, &state.line_termination,4710N_("paths are separated with NUL character"),'\0'),4711OPT_INTEGER('C', NULL, &state.p_context,4712N_("ensure at least <n> lines of context match")),4713{ OPTION_CALLBACK,0,"whitespace", &state,N_("action"),4714N_("detect new or modified lines that have whitespace errors"),47150, option_parse_whitespace },4716{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,4717N_("ignore changes in whitespace when finding context"),4718 PARSE_OPT_NOARG, option_parse_space_change },4719{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,4720N_("ignore changes in whitespace when finding context"),4721 PARSE_OPT_NOARG, option_parse_space_change },4722OPT_BOOL('R',"reverse", &state.apply_in_reverse,4723N_("apply the patch in reverse")),4724OPT_BOOL(0,"unidiff-zero", &state.unidiff_zero,4725N_("don't expect at least one line of context")),4726OPT_BOOL(0,"reject", &state.apply_with_reject,4727N_("leave the rejected hunks in corresponding *.rej files")),4728OPT_BOOL(0,"allow-overlap", &state.allow_overlap,4729N_("allow overlapping hunks")),4730OPT__VERBOSE(&state.apply_verbosely,N_("be verbose")),4731OPT_BIT(0,"inaccurate-eof", &options,4732N_("tolerate incorrectly detected missing new-line at the end of file"),4733 INACCURATE_EOF),4734OPT_BIT(0,"recount", &options,4735N_("do not trust the line counts in the hunk headers"),4736 RECOUNT),4737{ OPTION_CALLBACK,0,"directory", &state,N_("root"),4738N_("prepend <root> to all filenames"),47390, option_parse_directory },4740OPT_END()4741};47424743init_apply_state(&state, prefix);47444745 argc =parse_options(argc, argv, state.prefix, builtin_apply_options,4746 apply_usage,0);47474748if(state.apply_with_reject && state.threeway)4749die("--reject and --3way cannot be used together.");4750if(state.cached && state.threeway)4751die("--cached and --3way cannot be used together.");4752if(state.threeway) {4753if(is_not_gitdir)4754die(_("--3way outside a repository"));4755 state.check_index =1;4756}4757if(state.apply_with_reject)4758 state.apply = state.apply_verbosely =1;4759if(!force_apply && (state.diffstat || state.numstat || state.summary || state.check || state.fake_ancestor))4760 state.apply =0;4761if(state.check_index && is_not_gitdir)4762die(_("--index outside a repository"));4763if(state.cached) {4764if(is_not_gitdir)4765die(_("--cached outside a repository"));4766 state.check_index =1;4767}4768if(state.check_index)4769 state.unsafe_paths =0;47704771for(i =0; i < argc; i++) {4772const char*arg = argv[i];4773int fd;47744775if(!strcmp(arg,"-")) {4776 errs |=apply_patch(&state,0,"<stdin>", options);4777 read_stdin =0;4778continue;4779}else if(0< state.prefix_length)4780 arg =prefix_filename(state.prefix,4781 state.prefix_length,4782 arg);47834784 fd =open(arg, O_RDONLY);4785if(fd <0)4786die_errno(_("can't open patch '%s'"), arg);4787 read_stdin =0;4788set_default_whitespace_mode(&state, state.whitespace_option);4789 errs |=apply_patch(&state, fd, arg, options);4790close(fd);4791}4792set_default_whitespace_mode(&state, state.whitespace_option);4793if(read_stdin)4794 errs |=apply_patch(&state,0,"<stdin>", options);4795if(state.whitespace_error) {4796if(squelch_whitespace_errors &&4797 squelch_whitespace_errors < state.whitespace_error) {4798int squelched =4799 state.whitespace_error - squelch_whitespace_errors;4800warning(Q_("squelched%dwhitespace error",4801"squelched%dwhitespace errors",4802 squelched),4803 squelched);4804}4805if(ws_error_action == die_on_ws_error)4806die(Q_("%dline adds whitespace errors.",4807"%dlines add whitespace errors.",4808 state.whitespace_error),4809 state.whitespace_error);4810if(applied_after_fixing_ws && state.apply)4811warning("%dline%sapplied after"4812" fixing whitespace errors.",4813 applied_after_fixing_ws,4814 applied_after_fixing_ws ==1?"":"s");4815else if(state.whitespace_error)4816warning(Q_("%dline adds whitespace errors.",4817"%dlines add whitespace errors.",4818 state.whitespace_error),4819 state.whitespace_error);4820}48214822if(state.update_index) {4823if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK))4824die(_("Unable to write new index file"));4825}48264827clear_apply_state(&state);48284829return!!errs;4830}