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) 136{ 137if(!state->whitespace_option && !apply_default_whitespace) 138 ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 139} 140 141/* 142 * For "diff-stat" like behaviour, we keep track of the biggest change 143 * we've seen, and the longest filename. That allows us to do simple 144 * scaling. 145 */ 146static int max_change, max_len; 147 148/* 149 * Various "current state", notably line numbers and what 150 * file (and how) we're patching right now.. The "is_xxxx" 151 * things are flags, where -1 means "don't know yet". 152 */ 153static int state_linenr =1; 154 155/* 156 * This represents one "hunk" from a patch, starting with 157 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 158 * patch text is pointed at by patch, and its byte length 159 * is stored in size. leading and trailing are the number 160 * of context lines. 161 */ 162struct fragment { 163unsigned long leading, trailing; 164unsigned long oldpos, oldlines; 165unsigned long newpos, newlines; 166/* 167 * 'patch' is usually borrowed from buf in apply_patch(), 168 * but some codepaths store an allocated buffer. 169 */ 170const char*patch; 171unsigned free_patch:1, 172 rejected:1; 173int size; 174int linenr; 175struct fragment *next; 176}; 177 178/* 179 * When dealing with a binary patch, we reuse "leading" field 180 * to store the type of the binary hunk, either deflated "delta" 181 * or deflated "literal". 182 */ 183#define binary_patch_method leading 184#define BINARY_DELTA_DEFLATED 1 185#define BINARY_LITERAL_DEFLATED 2 186 187/* 188 * This represents a "patch" to a file, both metainfo changes 189 * such as creation/deletion, filemode and content changes represented 190 * as a series of fragments. 191 */ 192struct patch { 193char*new_name, *old_name, *def_name; 194unsigned int old_mode, new_mode; 195int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 196int rejected; 197unsigned ws_rule; 198int lines_added, lines_deleted; 199int score; 200unsigned int is_toplevel_relative:1; 201unsigned int inaccurate_eof:1; 202unsigned int is_binary:1; 203unsigned int is_copy:1; 204unsigned int is_rename:1; 205unsigned int recount:1; 206unsigned int conflicted_threeway:1; 207unsigned int direct_to_threeway:1; 208struct fragment *fragments; 209char*result; 210size_t resultsize; 211char old_sha1_prefix[41]; 212char new_sha1_prefix[41]; 213struct patch *next; 214 215/* three-way fallback result */ 216struct object_id threeway_stage[3]; 217}; 218 219static voidfree_fragment_list(struct fragment *list) 220{ 221while(list) { 222struct fragment *next = list->next; 223if(list->free_patch) 224free((char*)list->patch); 225free(list); 226 list = next; 227} 228} 229 230static voidfree_patch(struct patch *patch) 231{ 232free_fragment_list(patch->fragments); 233free(patch->def_name); 234free(patch->old_name); 235free(patch->new_name); 236free(patch->result); 237free(patch); 238} 239 240static voidfree_patch_list(struct patch *list) 241{ 242while(list) { 243struct patch *next = list->next; 244free_patch(list); 245 list = next; 246} 247} 248 249/* 250 * A line in a file, len-bytes long (includes the terminating LF, 251 * except for an incomplete line at the end if the file ends with 252 * one), and its contents hashes to 'hash'. 253 */ 254struct line { 255size_t len; 256unsigned hash :24; 257unsigned flag :8; 258#define LINE_COMMON 1 259#define LINE_PATCHED 2 260}; 261 262/* 263 * This represents a "file", which is an array of "lines". 264 */ 265struct image { 266char*buf; 267size_t len; 268size_t nr; 269size_t alloc; 270struct line *line_allocated; 271struct line *line; 272}; 273 274/* 275 * Records filenames that have been touched, in order to handle 276 * the case where more than one patches touch the same file. 277 */ 278 279static struct string_list fn_table; 280 281static uint32_thash_line(const char*cp,size_t len) 282{ 283size_t i; 284uint32_t h; 285for(i =0, h =0; i < len; i++) { 286if(!isspace(cp[i])) { 287 h = h *3+ (cp[i] &0xff); 288} 289} 290return h; 291} 292 293/* 294 * Compare lines s1 of length n1 and s2 of length n2, ignoring 295 * whitespace difference. Returns 1 if they match, 0 otherwise 296 */ 297static intfuzzy_matchlines(const char*s1,size_t n1, 298const char*s2,size_t n2) 299{ 300const char*last1 = s1 + n1 -1; 301const char*last2 = s2 + n2 -1; 302int result =0; 303 304/* ignore line endings */ 305while((*last1 =='\r') || (*last1 =='\n')) 306 last1--; 307while((*last2 =='\r') || (*last2 =='\n')) 308 last2--; 309 310/* skip leading whitespaces, if both begin with whitespace */ 311if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 312while(isspace(*s1) && (s1 <= last1)) 313 s1++; 314while(isspace(*s2) && (s2 <= last2)) 315 s2++; 316} 317/* early return if both lines are empty */ 318if((s1 > last1) && (s2 > last2)) 319return1; 320while(!result) { 321 result = *s1++ - *s2++; 322/* 323 * Skip whitespace inside. We check for whitespace on 324 * both buffers because we don't want "a b" to match 325 * "ab" 326 */ 327if(isspace(*s1) &&isspace(*s2)) { 328while(isspace(*s1) && s1 <= last1) 329 s1++; 330while(isspace(*s2) && s2 <= last2) 331 s2++; 332} 333/* 334 * If we reached the end on one side only, 335 * lines don't match 336 */ 337if( 338((s2 > last2) && (s1 <= last1)) || 339((s1 > last1) && (s2 <= last2))) 340return0; 341if((s1 > last1) && (s2 > last2)) 342break; 343} 344 345return!result; 346} 347 348static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 349{ 350ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 351 img->line_allocated[img->nr].len = len; 352 img->line_allocated[img->nr].hash =hash_line(bol, len); 353 img->line_allocated[img->nr].flag = flag; 354 img->nr++; 355} 356 357/* 358 * "buf" has the file contents to be patched (read from various sources). 359 * attach it to "image" and add line-based index to it. 360 * "image" now owns the "buf". 361 */ 362static voidprepare_image(struct image *image,char*buf,size_t len, 363int prepare_linetable) 364{ 365const char*cp, *ep; 366 367memset(image,0,sizeof(*image)); 368 image->buf = buf; 369 image->len = len; 370 371if(!prepare_linetable) 372return; 373 374 ep = image->buf + image->len; 375 cp = image->buf; 376while(cp < ep) { 377const char*next; 378for(next = cp; next < ep && *next !='\n'; next++) 379; 380if(next < ep) 381 next++; 382add_line_info(image, cp, next - cp,0); 383 cp = next; 384} 385 image->line = image->line_allocated; 386} 387 388static voidclear_image(struct image *image) 389{ 390free(image->buf); 391free(image->line_allocated); 392memset(image,0,sizeof(*image)); 393} 394 395/* fmt must contain _one_ %s and no other substitution */ 396static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 397{ 398struct strbuf sb = STRBUF_INIT; 399 400if(patch->old_name && patch->new_name && 401strcmp(patch->old_name, patch->new_name)) { 402quote_c_style(patch->old_name, &sb, NULL,0); 403strbuf_addstr(&sb," => "); 404quote_c_style(patch->new_name, &sb, NULL,0); 405}else{ 406const char*n = patch->new_name; 407if(!n) 408 n = patch->old_name; 409quote_c_style(n, &sb, NULL,0); 410} 411fprintf(output, fmt, sb.buf); 412fputc('\n', output); 413strbuf_release(&sb); 414} 415 416#define SLOP (16) 417 418static voidread_patch_file(struct strbuf *sb,int fd) 419{ 420if(strbuf_read(sb, fd,0) <0) 421die_errno("git apply: failed to read"); 422 423/* 424 * Make sure that we have some slop in the buffer 425 * so that we can do speculative "memcmp" etc, and 426 * see to it that it is NUL-filled. 427 */ 428strbuf_grow(sb, SLOP); 429memset(sb->buf + sb->len,0, SLOP); 430} 431 432static unsigned longlinelen(const char*buffer,unsigned long size) 433{ 434unsigned long len =0; 435while(size--) { 436 len++; 437if(*buffer++ =='\n') 438break; 439} 440return len; 441} 442 443static intis_dev_null(const char*str) 444{ 445returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 446} 447 448#define TERM_SPACE 1 449#define TERM_TAB 2 450 451static intname_terminate(const char*name,int namelen,int c,int terminate) 452{ 453if(c ==' '&& !(terminate & TERM_SPACE)) 454return0; 455if(c =='\t'&& !(terminate & TERM_TAB)) 456return0; 457 458return1; 459} 460 461/* remove double slashes to make --index work with such filenames */ 462static char*squash_slash(char*name) 463{ 464int i =0, j =0; 465 466if(!name) 467return NULL; 468 469while(name[i]) { 470if((name[j++] = name[i++]) =='/') 471while(name[i] =='/') 472 i++; 473} 474 name[j] ='\0'; 475return name; 476} 477 478static char*find_name_gnu(struct apply_state *state, 479const char*line, 480const char*def, 481int p_value) 482{ 483struct strbuf name = STRBUF_INIT; 484char*cp; 485 486/* 487 * Proposed "new-style" GNU patch/diff format; see 488 * http://marc.info/?l=git&m=112927316408690&w=2 489 */ 490if(unquote_c_style(&name, line, NULL)) { 491strbuf_release(&name); 492return NULL; 493} 494 495for(cp = name.buf; p_value; p_value--) { 496 cp =strchr(cp,'/'); 497if(!cp) { 498strbuf_release(&name); 499return NULL; 500} 501 cp++; 502} 503 504strbuf_remove(&name,0, cp - name.buf); 505if(state->root.len) 506strbuf_insert(&name,0, state->root.buf, state->root.len); 507returnsquash_slash(strbuf_detach(&name, NULL)); 508} 509 510static size_tsane_tz_len(const char*line,size_t len) 511{ 512const char*tz, *p; 513 514if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 515return0; 516 tz = line + len -strlen(" +0500"); 517 518if(tz[1] !='+'&& tz[1] !='-') 519return0; 520 521for(p = tz +2; p != line + len; p++) 522if(!isdigit(*p)) 523return0; 524 525return line + len - tz; 526} 527 528static size_ttz_with_colon_len(const char*line,size_t len) 529{ 530const char*tz, *p; 531 532if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 533return0; 534 tz = line + len -strlen(" +08:00"); 535 536if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 537return0; 538 p = tz +2; 539if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 540!isdigit(*p++) || !isdigit(*p++)) 541return0; 542 543return line + len - tz; 544} 545 546static size_tdate_len(const char*line,size_t len) 547{ 548const char*date, *p; 549 550if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 551return0; 552 p = date = line + len -strlen("72-02-05"); 553 554if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 555!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 556!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 557return0; 558 559if(date - line >=strlen("19") && 560isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 561 date -=strlen("19"); 562 563return line + len - date; 564} 565 566static size_tshort_time_len(const char*line,size_t len) 567{ 568const char*time, *p; 569 570if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 571return0; 572 p = time = line + len -strlen(" 07:01:32"); 573 574/* Permit 1-digit hours? */ 575if(*p++ !=' '|| 576!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 577!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 578!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 579return0; 580 581return line + len - time; 582} 583 584static size_tfractional_time_len(const char*line,size_t len) 585{ 586const char*p; 587size_t n; 588 589/* Expected format: 19:41:17.620000023 */ 590if(!len || !isdigit(line[len -1])) 591return0; 592 p = line + len -1; 593 594/* Fractional seconds. */ 595while(p > line &&isdigit(*p)) 596 p--; 597if(*p !='.') 598return0; 599 600/* Hours, minutes, and whole seconds. */ 601 n =short_time_len(line, p - line); 602if(!n) 603return0; 604 605return line + len - p + n; 606} 607 608static size_ttrailing_spaces_len(const char*line,size_t len) 609{ 610const char*p; 611 612/* Expected format: ' ' x (1 or more) */ 613if(!len || line[len -1] !=' ') 614return0; 615 616 p = line + len; 617while(p != line) { 618 p--; 619if(*p !=' ') 620return line + len - (p +1); 621} 622 623/* All spaces! */ 624return len; 625} 626 627static size_tdiff_timestamp_len(const char*line,size_t len) 628{ 629const char*end = line + len; 630size_t n; 631 632/* 633 * Posix: 2010-07-05 19:41:17 634 * GNU: 2010-07-05 19:41:17.620000023 -0500 635 */ 636 637if(!isdigit(end[-1])) 638return0; 639 640 n =sane_tz_len(line, end - line); 641if(!n) 642 n =tz_with_colon_len(line, end - line); 643 end -= n; 644 645 n =short_time_len(line, end - line); 646if(!n) 647 n =fractional_time_len(line, end - line); 648 end -= n; 649 650 n =date_len(line, end - line); 651if(!n)/* No date. Too bad. */ 652return0; 653 end -= n; 654 655if(end == line)/* No space before date. */ 656return0; 657if(end[-1] =='\t') {/* Success! */ 658 end--; 659return line + len - end; 660} 661if(end[-1] !=' ')/* No space before date. */ 662return0; 663 664/* Whitespace damage. */ 665 end -=trailing_spaces_len(line, end - line); 666return line + len - end; 667} 668 669static char*find_name_common(struct apply_state *state, 670const char*line, 671const char*def, 672int p_value, 673const char*end, 674int terminate) 675{ 676int len; 677const char*start = NULL; 678 679if(p_value ==0) 680 start = line; 681while(line != end) { 682char c = *line; 683 684if(!end &&isspace(c)) { 685if(c =='\n') 686break; 687if(name_terminate(start, line-start, c, terminate)) 688break; 689} 690 line++; 691if(c =='/'&& !--p_value) 692 start = line; 693} 694if(!start) 695returnsquash_slash(xstrdup_or_null(def)); 696 len = line - start; 697if(!len) 698returnsquash_slash(xstrdup_or_null(def)); 699 700/* 701 * Generally we prefer the shorter name, especially 702 * if the other one is just a variation of that with 703 * something else tacked on to the end (ie "file.orig" 704 * or "file~"). 705 */ 706if(def) { 707int deflen =strlen(def); 708if(deflen < len && !strncmp(start, def, deflen)) 709returnsquash_slash(xstrdup(def)); 710} 711 712if(state->root.len) { 713char*ret =xstrfmt("%s%.*s", state->root.buf, len, start); 714returnsquash_slash(ret); 715} 716 717returnsquash_slash(xmemdupz(start, len)); 718} 719 720static char*find_name(struct apply_state *state, 721const char*line, 722char*def, 723int p_value, 724int terminate) 725{ 726if(*line =='"') { 727char*name =find_name_gnu(state, line, def, p_value); 728if(name) 729return name; 730} 731 732returnfind_name_common(state, line, def, p_value, NULL, terminate); 733} 734 735static char*find_name_traditional(struct apply_state *state, 736const char*line, 737char*def, 738int p_value) 739{ 740size_t len; 741size_t date_len; 742 743if(*line =='"') { 744char*name =find_name_gnu(state, line, def, p_value); 745if(name) 746return name; 747} 748 749 len =strchrnul(line,'\n') - line; 750 date_len =diff_timestamp_len(line, len); 751if(!date_len) 752returnfind_name_common(state, line, def, p_value, NULL, TERM_TAB); 753 len -= date_len; 754 755returnfind_name_common(state, line, def, p_value, line + len,0); 756} 757 758static intcount_slashes(const char*cp) 759{ 760int cnt =0; 761char ch; 762 763while((ch = *cp++)) 764if(ch =='/') 765 cnt++; 766return cnt; 767} 768 769/* 770 * Given the string after "--- " or "+++ ", guess the appropriate 771 * p_value for the given patch. 772 */ 773static intguess_p_value(struct apply_state *state,const char*nameline) 774{ 775char*name, *cp; 776int val = -1; 777 778if(is_dev_null(nameline)) 779return-1; 780 name =find_name_traditional(state, nameline, NULL,0); 781if(!name) 782return-1; 783 cp =strchr(name,'/'); 784if(!cp) 785 val =0; 786else if(state->prefix) { 787/* 788 * Does it begin with "a/$our-prefix" and such? Then this is 789 * very likely to apply to our directory. 790 */ 791if(!strncmp(name, state->prefix, state->prefix_length)) 792 val =count_slashes(state->prefix); 793else{ 794 cp++; 795if(!strncmp(cp, state->prefix, state->prefix_length)) 796 val =count_slashes(state->prefix) +1; 797} 798} 799free(name); 800return val; 801} 802 803/* 804 * Does the ---/+++ line have the POSIX timestamp after the last HT? 805 * GNU diff puts epoch there to signal a creation/deletion event. Is 806 * this such a timestamp? 807 */ 808static inthas_epoch_timestamp(const char*nameline) 809{ 810/* 811 * We are only interested in epoch timestamp; any non-zero 812 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 813 * For the same reason, the date must be either 1969-12-31 or 814 * 1970-01-01, and the seconds part must be "00". 815 */ 816const char stamp_regexp[] = 817"^(1969-12-31|1970-01-01)" 818" " 819"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 820" " 821"([-+][0-2][0-9]:?[0-5][0-9])\n"; 822const char*timestamp = NULL, *cp, *colon; 823static regex_t *stamp; 824 regmatch_t m[10]; 825int zoneoffset; 826int hourminute; 827int status; 828 829for(cp = nameline; *cp !='\n'; cp++) { 830if(*cp =='\t') 831 timestamp = cp +1; 832} 833if(!timestamp) 834return0; 835if(!stamp) { 836 stamp =xmalloc(sizeof(*stamp)); 837if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 838warning(_("Cannot prepare timestamp regexp%s"), 839 stamp_regexp); 840return0; 841} 842} 843 844 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 845if(status) { 846if(status != REG_NOMATCH) 847warning(_("regexec returned%dfor input:%s"), 848 status, timestamp); 849return0; 850} 851 852 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 853if(*colon ==':') 854 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 855else 856 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 857if(timestamp[m[3].rm_so] =='-') 858 zoneoffset = -zoneoffset; 859 860/* 861 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 862 * (west of GMT) or 1970-01-01 (east of GMT) 863 */ 864if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 865(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 866return0; 867 868 hourminute = (strtol(timestamp +11, NULL,10) *60+ 869strtol(timestamp +14, NULL,10) - 870 zoneoffset); 871 872return((zoneoffset <0&& hourminute ==1440) || 873(0<= zoneoffset && !hourminute)); 874} 875 876/* 877 * Get the name etc info from the ---/+++ lines of a traditional patch header 878 * 879 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 880 * files, we can happily check the index for a match, but for creating a 881 * new file we should try to match whatever "patch" does. I have no idea. 882 */ 883static voidparse_traditional_patch(struct apply_state *state, 884const char*first, 885const char*second, 886struct patch *patch) 887{ 888char*name; 889 890 first +=4;/* skip "--- " */ 891 second +=4;/* skip "+++ " */ 892if(!state->p_value_known) { 893int p, q; 894 p =guess_p_value(state, first); 895 q =guess_p_value(state, second); 896if(p <0) p = q; 897if(0<= p && p == q) { 898 state->p_value = p; 899 state->p_value_known =1; 900} 901} 902if(is_dev_null(first)) { 903 patch->is_new =1; 904 patch->is_delete =0; 905 name =find_name_traditional(state, second, NULL, state->p_value); 906 patch->new_name = name; 907}else if(is_dev_null(second)) { 908 patch->is_new =0; 909 patch->is_delete =1; 910 name =find_name_traditional(state, first, NULL, state->p_value); 911 patch->old_name = name; 912}else{ 913char*first_name; 914 first_name =find_name_traditional(state, first, NULL, state->p_value); 915 name =find_name_traditional(state, second, first_name, state->p_value); 916free(first_name); 917if(has_epoch_timestamp(first)) { 918 patch->is_new =1; 919 patch->is_delete =0; 920 patch->new_name = name; 921}else if(has_epoch_timestamp(second)) { 922 patch->is_new =0; 923 patch->is_delete =1; 924 patch->old_name = name; 925}else{ 926 patch->old_name = name; 927 patch->new_name =xstrdup_or_null(name); 928} 929} 930if(!name) 931die(_("unable to find filename in patch at line%d"), state_linenr); 932} 933 934static intgitdiff_hdrend(struct apply_state *state, 935const char*line, 936struct patch *patch) 937{ 938return-1; 939} 940 941/* 942 * We're anal about diff header consistency, to make 943 * sure that we don't end up having strange ambiguous 944 * patches floating around. 945 * 946 * As a result, gitdiff_{old|new}name() will check 947 * their names against any previous information, just 948 * to make sure.. 949 */ 950#define DIFF_OLD_NAME 0 951#define DIFF_NEW_NAME 1 952 953static voidgitdiff_verify_name(struct apply_state *state, 954const char*line, 955int isnull, 956char**name, 957int side) 958{ 959if(!*name && !isnull) { 960*name =find_name(state, line, NULL, state->p_value, TERM_TAB); 961return; 962} 963 964if(*name) { 965int len =strlen(*name); 966char*another; 967if(isnull) 968die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 969*name, state_linenr); 970 another =find_name(state, line, NULL, state->p_value, TERM_TAB); 971if(!another ||memcmp(another, *name, len +1)) 972die((side == DIFF_NEW_NAME) ? 973_("git apply: bad git-diff - inconsistent new filename on line%d") : 974_("git apply: bad git-diff - inconsistent old filename on line%d"), state_linenr); 975free(another); 976}else{ 977/* expect "/dev/null" */ 978if(memcmp("/dev/null", line,9) || line[9] !='\n') 979die(_("git apply: bad git-diff - expected /dev/null on line%d"), state_linenr); 980} 981} 982 983static intgitdiff_oldname(struct apply_state *state, 984const char*line, 985struct patch *patch) 986{ 987gitdiff_verify_name(state, line, 988 patch->is_new, &patch->old_name, 989 DIFF_OLD_NAME); 990return0; 991} 992 993static intgitdiff_newname(struct apply_state *state, 994const char*line, 995struct patch *patch) 996{ 997gitdiff_verify_name(state, line, 998 patch->is_delete, &patch->new_name, 999 DIFF_NEW_NAME);1000return0;1001}10021003static intgitdiff_oldmode(struct apply_state *state,1004const char*line,1005struct patch *patch)1006{1007 patch->old_mode =strtoul(line, NULL,8);1008return0;1009}10101011static intgitdiff_newmode(struct apply_state *state,1012const char*line,1013struct patch *patch)1014{1015 patch->new_mode =strtoul(line, NULL,8);1016return0;1017}10181019static intgitdiff_delete(struct apply_state *state,1020const char*line,1021struct patch *patch)1022{1023 patch->is_delete =1;1024free(patch->old_name);1025 patch->old_name =xstrdup_or_null(patch->def_name);1026returngitdiff_oldmode(state, line, patch);1027}10281029static intgitdiff_newfile(struct apply_state *state,1030const char*line,1031struct patch *patch)1032{1033 patch->is_new =1;1034free(patch->new_name);1035 patch->new_name =xstrdup_or_null(patch->def_name);1036returngitdiff_newmode(state, line, patch);1037}10381039static intgitdiff_copysrc(struct apply_state *state,1040const char*line,1041struct patch *patch)1042{1043 patch->is_copy =1;1044free(patch->old_name);1045 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1046return0;1047}10481049static intgitdiff_copydst(struct apply_state *state,1050const char*line,1051struct patch *patch)1052{1053 patch->is_copy =1;1054free(patch->new_name);1055 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1056return0;1057}10581059static intgitdiff_renamesrc(struct apply_state *state,1060const char*line,1061struct patch *patch)1062{1063 patch->is_rename =1;1064free(patch->old_name);1065 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1066return0;1067}10681069static intgitdiff_renamedst(struct apply_state *state,1070const char*line,1071struct patch *patch)1072{1073 patch->is_rename =1;1074free(patch->new_name);1075 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1076return0;1077}10781079static intgitdiff_similarity(struct apply_state *state,1080const char*line,1081struct patch *patch)1082{1083unsigned long val =strtoul(line, NULL,10);1084if(val <=100)1085 patch->score = val;1086return0;1087}10881089static intgitdiff_dissimilarity(struct apply_state *state,1090const char*line,1091struct patch *patch)1092{1093unsigned long val =strtoul(line, NULL,10);1094if(val <=100)1095 patch->score = val;1096return0;1097}10981099static intgitdiff_index(struct apply_state *state,1100const char*line,1101struct patch *patch)1102{1103/*1104 * index line is N hexadecimal, "..", N hexadecimal,1105 * and optional space with octal mode.1106 */1107const char*ptr, *eol;1108int len;11091110 ptr =strchr(line,'.');1111if(!ptr || ptr[1] !='.'||40< ptr - line)1112return0;1113 len = ptr - line;1114memcpy(patch->old_sha1_prefix, line, len);1115 patch->old_sha1_prefix[len] =0;11161117 line = ptr +2;1118 ptr =strchr(line,' ');1119 eol =strchrnul(line,'\n');11201121if(!ptr || eol < ptr)1122 ptr = eol;1123 len = ptr - line;11241125if(40< len)1126return0;1127memcpy(patch->new_sha1_prefix, line, len);1128 patch->new_sha1_prefix[len] =0;1129if(*ptr ==' ')1130 patch->old_mode =strtoul(ptr+1, NULL,8);1131return0;1132}11331134/*1135 * This is normal for a diff that doesn't change anything: we'll fall through1136 * into the next diff. Tell the parser to break out.1137 */1138static intgitdiff_unrecognized(struct apply_state *state,1139const char*line,1140struct patch *patch)1141{1142return-1;1143}11441145/*1146 * Skip p_value leading components from "line"; as we do not accept1147 * absolute paths, return NULL in that case.1148 */1149static const char*skip_tree_prefix(struct apply_state *state,1150const char*line,1151int llen)1152{1153int nslash;1154int i;11551156if(!state->p_value)1157return(llen && line[0] =='/') ? NULL : line;11581159 nslash = state->p_value;1160for(i =0; i < llen; i++) {1161int ch = line[i];1162if(ch =='/'&& --nslash <=0)1163return(i ==0) ? NULL : &line[i +1];1164}1165return NULL;1166}11671168/*1169 * This is to extract the same name that appears on "diff --git"1170 * line. We do not find and return anything if it is a rename1171 * patch, and it is OK because we will find the name elsewhere.1172 * We need to reliably find name only when it is mode-change only,1173 * creation or deletion of an empty file. In any of these cases,1174 * both sides are the same name under a/ and b/ respectively.1175 */1176static char*git_header_name(struct apply_state *state,1177const char*line,1178int llen)1179{1180const char*name;1181const char*second = NULL;1182size_t len, line_len;11831184 line +=strlen("diff --git ");1185 llen -=strlen("diff --git ");11861187if(*line =='"') {1188const char*cp;1189struct strbuf first = STRBUF_INIT;1190struct strbuf sp = STRBUF_INIT;11911192if(unquote_c_style(&first, line, &second))1193goto free_and_fail1;11941195/* strip the a/b prefix including trailing slash */1196 cp =skip_tree_prefix(state, first.buf, first.len);1197if(!cp)1198goto free_and_fail1;1199strbuf_remove(&first,0, cp - first.buf);12001201/*1202 * second points at one past closing dq of name.1203 * find the second name.1204 */1205while((second < line + llen) &&isspace(*second))1206 second++;12071208if(line + llen <= second)1209goto free_and_fail1;1210if(*second =='"') {1211if(unquote_c_style(&sp, second, NULL))1212goto free_and_fail1;1213 cp =skip_tree_prefix(state, sp.buf, sp.len);1214if(!cp)1215goto free_and_fail1;1216/* They must match, otherwise ignore */1217if(strcmp(cp, first.buf))1218goto free_and_fail1;1219strbuf_release(&sp);1220returnstrbuf_detach(&first, NULL);1221}12221223/* unquoted second */1224 cp =skip_tree_prefix(state, second, line + llen - second);1225if(!cp)1226goto free_and_fail1;1227if(line + llen - cp != first.len ||1228memcmp(first.buf, cp, first.len))1229goto free_and_fail1;1230returnstrbuf_detach(&first, NULL);12311232 free_and_fail1:1233strbuf_release(&first);1234strbuf_release(&sp);1235return NULL;1236}12371238/* unquoted first name */1239 name =skip_tree_prefix(state, line, llen);1240if(!name)1241return NULL;12421243/*1244 * since the first name is unquoted, a dq if exists must be1245 * the beginning of the second name.1246 */1247for(second = name; second < line + llen; second++) {1248if(*second =='"') {1249struct strbuf sp = STRBUF_INIT;1250const char*np;12511252if(unquote_c_style(&sp, second, NULL))1253goto free_and_fail2;12541255 np =skip_tree_prefix(state, sp.buf, sp.len);1256if(!np)1257goto free_and_fail2;12581259 len = sp.buf + sp.len - np;1260if(len < second - name &&1261!strncmp(np, name, len) &&1262isspace(name[len])) {1263/* Good */1264strbuf_remove(&sp,0, np - sp.buf);1265returnstrbuf_detach(&sp, NULL);1266}12671268 free_and_fail2:1269strbuf_release(&sp);1270return NULL;1271}1272}12731274/*1275 * Accept a name only if it shows up twice, exactly the same1276 * form.1277 */1278 second =strchr(name,'\n');1279if(!second)1280return NULL;1281 line_len = second - name;1282for(len =0; ; len++) {1283switch(name[len]) {1284default:1285continue;1286case'\n':1287return NULL;1288case'\t':case' ':1289/*1290 * Is this the separator between the preimage1291 * and the postimage pathname? Again, we are1292 * only interested in the case where there is1293 * no rename, as this is only to set def_name1294 * and a rename patch has the names elsewhere1295 * in an unambiguous form.1296 */1297if(!name[len +1])1298return NULL;/* no postimage name */1299 second =skip_tree_prefix(state, name + len +1,1300 line_len - (len +1));1301if(!second)1302return NULL;1303/*1304 * Does len bytes starting at "name" and "second"1305 * (that are separated by one HT or SP we just1306 * found) exactly match?1307 */1308if(second[len] =='\n'&& !strncmp(name, second, len))1309returnxmemdupz(name, len);1310}1311}1312}13131314/* Verify that we recognize the lines following a git header */1315static intparse_git_header(struct apply_state *state,1316const char*line,1317int len,1318unsigned int size,1319struct patch *patch)1320{1321unsigned long offset;13221323/* A git diff has explicit new/delete information, so we don't guess */1324 patch->is_new =0;1325 patch->is_delete =0;13261327/*1328 * Some things may not have the old name in the1329 * rest of the headers anywhere (pure mode changes,1330 * or removing or adding empty files), so we get1331 * the default name from the header.1332 */1333 patch->def_name =git_header_name(state, line, len);1334if(patch->def_name && state->root.len) {1335char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1336free(patch->def_name);1337 patch->def_name = s;1338}13391340 line += len;1341 size -= len;1342 state_linenr++;1343for(offset = len ; size >0; offset += len, size -= len, line += len, state_linenr++) {1344static const struct opentry {1345const char*str;1346int(*fn)(struct apply_state *,const char*,struct patch *);1347} optable[] = {1348{"@@ -", gitdiff_hdrend },1349{"--- ", gitdiff_oldname },1350{"+++ ", gitdiff_newname },1351{"old mode ", gitdiff_oldmode },1352{"new mode ", gitdiff_newmode },1353{"deleted file mode ", gitdiff_delete },1354{"new file mode ", gitdiff_newfile },1355{"copy from ", gitdiff_copysrc },1356{"copy to ", gitdiff_copydst },1357{"rename old ", gitdiff_renamesrc },1358{"rename new ", gitdiff_renamedst },1359{"rename from ", gitdiff_renamesrc },1360{"rename to ", gitdiff_renamedst },1361{"similarity index ", gitdiff_similarity },1362{"dissimilarity index ", gitdiff_dissimilarity },1363{"index ", gitdiff_index },1364{"", gitdiff_unrecognized },1365};1366int i;13671368 len =linelen(line, size);1369if(!len || line[len-1] !='\n')1370break;1371for(i =0; i <ARRAY_SIZE(optable); i++) {1372const struct opentry *p = optable + i;1373int oplen =strlen(p->str);1374if(len < oplen ||memcmp(p->str, line, oplen))1375continue;1376if(p->fn(state, line + oplen, patch) <0)1377return offset;1378break;1379}1380}13811382return offset;1383}13841385static intparse_num(const char*line,unsigned long*p)1386{1387char*ptr;13881389if(!isdigit(*line))1390return0;1391*p =strtoul(line, &ptr,10);1392return ptr - line;1393}13941395static intparse_range(const char*line,int len,int offset,const char*expect,1396unsigned long*p1,unsigned long*p2)1397{1398int digits, ex;13991400if(offset <0|| offset >= len)1401return-1;1402 line += offset;1403 len -= offset;14041405 digits =parse_num(line, p1);1406if(!digits)1407return-1;14081409 offset += digits;1410 line += digits;1411 len -= digits;14121413*p2 =1;1414if(*line ==',') {1415 digits =parse_num(line+1, p2);1416if(!digits)1417return-1;14181419 offset += digits+1;1420 line += digits+1;1421 len -= digits+1;1422}14231424 ex =strlen(expect);1425if(ex > len)1426return-1;1427if(memcmp(line, expect, ex))1428return-1;14291430return offset + ex;1431}14321433static voidrecount_diff(const char*line,int size,struct fragment *fragment)1434{1435int oldlines =0, newlines =0, ret =0;14361437if(size <1) {1438warning("recount: ignore empty hunk");1439return;1440}14411442for(;;) {1443int len =linelen(line, size);1444 size -= len;1445 line += len;14461447if(size <1)1448break;14491450switch(*line) {1451case' ':case'\n':1452 newlines++;1453/* fall through */1454case'-':1455 oldlines++;1456continue;1457case'+':1458 newlines++;1459continue;1460case'\\':1461continue;1462case'@':1463 ret = size <3|| !starts_with(line,"@@ ");1464break;1465case'd':1466 ret = size <5|| !starts_with(line,"diff ");1467break;1468default:1469 ret = -1;1470break;1471}1472if(ret) {1473warning(_("recount: unexpected line: %.*s"),1474(int)linelen(line, size), line);1475return;1476}1477break;1478}1479 fragment->oldlines = oldlines;1480 fragment->newlines = newlines;1481}14821483/*1484 * Parse a unified diff fragment header of the1485 * form "@@ -a,b +c,d @@"1486 */1487static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1488{1489int offset;14901491if(!len || line[len-1] !='\n')1492return-1;14931494/* Figure out the number of lines in a fragment */1495 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1496 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14971498return offset;1499}15001501static intfind_header(struct apply_state *state,1502const char*line,1503unsigned long size,1504int*hdrsize,1505struct patch *patch)1506{1507unsigned long offset, len;15081509 patch->is_toplevel_relative =0;1510 patch->is_rename = patch->is_copy =0;1511 patch->is_new = patch->is_delete = -1;1512 patch->old_mode = patch->new_mode =0;1513 patch->old_name = patch->new_name = NULL;1514for(offset =0; size >0; offset += len, size -= len, line += len, state_linenr++) {1515unsigned long nextlen;15161517 len =linelen(line, size);1518if(!len)1519break;15201521/* Testing this early allows us to take a few shortcuts.. */1522if(len <6)1523continue;15241525/*1526 * Make sure we don't find any unconnected patch fragments.1527 * That's a sign that we didn't find a header, and that a1528 * patch has become corrupted/broken up.1529 */1530if(!memcmp("@@ -", line,4)) {1531struct fragment dummy;1532if(parse_fragment_header(line, len, &dummy) <0)1533continue;1534die(_("patch fragment without header at line%d: %.*s"),1535 state_linenr, (int)len-1, line);1536}15371538if(size < len +6)1539break;15401541/*1542 * Git patch? It might not have a real patch, just a rename1543 * or mode change, so we handle that specially1544 */1545if(!memcmp("diff --git ", line,11)) {1546int git_hdr_len =parse_git_header(state, line, len, size, patch);1547if(git_hdr_len <= len)1548continue;1549if(!patch->old_name && !patch->new_name) {1550if(!patch->def_name)1551die(Q_("git diff header lacks filename information when removing "1552"%dleading pathname component (line%d)",1553"git diff header lacks filename information when removing "1554"%dleading pathname components (line%d)",1555 state->p_value),1556 state->p_value, state_linenr);1557 patch->old_name =xstrdup(patch->def_name);1558 patch->new_name =xstrdup(patch->def_name);1559}1560if(!patch->is_delete && !patch->new_name)1561die("git diff header lacks filename information "1562"(line%d)", state_linenr);1563 patch->is_toplevel_relative =1;1564*hdrsize = git_hdr_len;1565return offset;1566}15671568/* --- followed by +++ ? */1569if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1570continue;15711572/*1573 * We only accept unified patches, so we want it to1574 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1575 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1576 */1577 nextlen =linelen(line + len, size - len);1578if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1579continue;15801581/* Ok, we'll consider it a patch */1582parse_traditional_patch(state, line, line+len, patch);1583*hdrsize = len + nextlen;1584 state_linenr +=2;1585return offset;1586}1587return-1;1588}15891590static voidrecord_ws_error(struct apply_state *state,1591unsigned result,1592const char*line,1593int len,1594int linenr)1595{1596char*err;15971598if(!result)1599return;16001601 state->whitespace_error++;1602if(squelch_whitespace_errors &&1603 squelch_whitespace_errors < state->whitespace_error)1604return;16051606 err =whitespace_error_string(result);1607fprintf(stderr,"%s:%d:%s.\n%.*s\n",1608 state->patch_input_file, linenr, err, len, line);1609free(err);1610}16111612static voidcheck_whitespace(struct apply_state *state,1613const char*line,1614int len,1615unsigned ws_rule)1616{1617unsigned result =ws_check(line +1, len -1, ws_rule);16181619record_ws_error(state, result, line +1, len -2, state_linenr);1620}16211622/*1623 * Parse a unified diff. Note that this really needs to parse each1624 * fragment separately, since the only way to know the difference1625 * between a "---" that is part of a patch, and a "---" that starts1626 * the next patch is to look at the line counts..1627 */1628static intparse_fragment(struct apply_state *state,1629const char*line,1630unsigned long size,1631struct patch *patch,1632struct fragment *fragment)1633{1634int added, deleted;1635int len =linelen(line, size), offset;1636unsigned long oldlines, newlines;1637unsigned long leading, trailing;16381639 offset =parse_fragment_header(line, len, fragment);1640if(offset <0)1641return-1;1642if(offset >0&& patch->recount)1643recount_diff(line + offset, size - offset, fragment);1644 oldlines = fragment->oldlines;1645 newlines = fragment->newlines;1646 leading =0;1647 trailing =0;16481649/* Parse the thing.. */1650 line += len;1651 size -= len;1652 state_linenr++;1653 added = deleted =0;1654for(offset = len;16550< size;1656 offset += len, size -= len, line += len, state_linenr++) {1657if(!oldlines && !newlines)1658break;1659 len =linelen(line, size);1660if(!len || line[len-1] !='\n')1661return-1;1662switch(*line) {1663default:1664return-1;1665case'\n':/* newer GNU diff, an empty context line */1666case' ':1667 oldlines--;1668 newlines--;1669if(!deleted && !added)1670 leading++;1671 trailing++;1672if(!state->apply_in_reverse &&1673 ws_error_action == correct_ws_error)1674check_whitespace(state, line, len, patch->ws_rule);1675break;1676case'-':1677if(state->apply_in_reverse &&1678 ws_error_action != nowarn_ws_error)1679check_whitespace(state, line, len, patch->ws_rule);1680 deleted++;1681 oldlines--;1682 trailing =0;1683break;1684case'+':1685if(!state->apply_in_reverse &&1686 ws_error_action != nowarn_ws_error)1687check_whitespace(state, line, len, patch->ws_rule);1688 added++;1689 newlines--;1690 trailing =0;1691break;16921693/*1694 * We allow "\ No newline at end of file". Depending1695 * on locale settings when the patch was produced we1696 * don't know what this line looks like. The only1697 * thing we do know is that it begins with "\ ".1698 * Checking for 12 is just for sanity check -- any1699 * l10n of "\ No newline..." is at least that long.1700 */1701case'\\':1702if(len <12||memcmp(line,"\\",2))1703return-1;1704break;1705}1706}1707if(oldlines || newlines)1708return-1;1709if(!deleted && !added)1710return-1;17111712 fragment->leading = leading;1713 fragment->trailing = trailing;17141715/*1716 * If a fragment ends with an incomplete line, we failed to include1717 * it in the above loop because we hit oldlines == newlines == 01718 * before seeing it.1719 */1720if(12< size && !memcmp(line,"\\",2))1721 offset +=linelen(line, size);17221723 patch->lines_added += added;1724 patch->lines_deleted += deleted;17251726if(0< patch->is_new && oldlines)1727returnerror(_("new file depends on old contents"));1728if(0< patch->is_delete && newlines)1729returnerror(_("deleted file still has contents"));1730return offset;1731}17321733/*1734 * We have seen "diff --git a/... b/..." header (or a traditional patch1735 * header). Read hunks that belong to this patch into fragments and hang1736 * them to the given patch structure.1737 *1738 * The (fragment->patch, fragment->size) pair points into the memory given1739 * by the caller, not a copy, when we return.1740 */1741static intparse_single_patch(struct apply_state *state,1742const char*line,1743unsigned long size,1744struct patch *patch)1745{1746unsigned long offset =0;1747unsigned long oldlines =0, newlines =0, context =0;1748struct fragment **fragp = &patch->fragments;17491750while(size >4&& !memcmp(line,"@@ -",4)) {1751struct fragment *fragment;1752int len;17531754 fragment =xcalloc(1,sizeof(*fragment));1755 fragment->linenr = state_linenr;1756 len =parse_fragment(state, line, size, patch, fragment);1757if(len <=0)1758die(_("corrupt patch at line%d"), state_linenr);1759 fragment->patch = line;1760 fragment->size = len;1761 oldlines += fragment->oldlines;1762 newlines += fragment->newlines;1763 context += fragment->leading + fragment->trailing;17641765*fragp = fragment;1766 fragp = &fragment->next;17671768 offset += len;1769 line += len;1770 size -= len;1771}17721773/*1774 * If something was removed (i.e. we have old-lines) it cannot1775 * be creation, and if something was added it cannot be1776 * deletion. However, the reverse is not true; --unified=01777 * patches that only add are not necessarily creation even1778 * though they do not have any old lines, and ones that only1779 * delete are not necessarily deletion.1780 *1781 * Unfortunately, a real creation/deletion patch do _not_ have1782 * any context line by definition, so we cannot safely tell it1783 * apart with --unified=0 insanity. At least if the patch has1784 * more than one hunk it is not creation or deletion.1785 */1786if(patch->is_new <0&&1787(oldlines || (patch->fragments && patch->fragments->next)))1788 patch->is_new =0;1789if(patch->is_delete <0&&1790(newlines || (patch->fragments && patch->fragments->next)))1791 patch->is_delete =0;17921793if(0< patch->is_new && oldlines)1794die(_("new file%sdepends on old contents"), patch->new_name);1795if(0< patch->is_delete && newlines)1796die(_("deleted file%sstill has contents"), patch->old_name);1797if(!patch->is_delete && !newlines && context)1798fprintf_ln(stderr,1799_("** warning: "1800"file%sbecomes empty but is not deleted"),1801 patch->new_name);18021803return offset;1804}18051806staticinlineintmetadata_changes(struct patch *patch)1807{1808return patch->is_rename >0||1809 patch->is_copy >0||1810 patch->is_new >0||1811 patch->is_delete ||1812(patch->old_mode && patch->new_mode &&1813 patch->old_mode != patch->new_mode);1814}18151816static char*inflate_it(const void*data,unsigned long size,1817unsigned long inflated_size)1818{1819 git_zstream stream;1820void*out;1821int st;18221823memset(&stream,0,sizeof(stream));18241825 stream.next_in = (unsigned char*)data;1826 stream.avail_in = size;1827 stream.next_out = out =xmalloc(inflated_size);1828 stream.avail_out = inflated_size;1829git_inflate_init(&stream);1830 st =git_inflate(&stream, Z_FINISH);1831git_inflate_end(&stream);1832if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1833free(out);1834return NULL;1835}1836return out;1837}18381839/*1840 * Read a binary hunk and return a new fragment; fragment->patch1841 * points at an allocated memory that the caller must free, so1842 * it is marked as "->free_patch = 1".1843 */1844static struct fragment *parse_binary_hunk(char**buf_p,1845unsigned long*sz_p,1846int*status_p,1847int*used_p)1848{1849/*1850 * Expect a line that begins with binary patch method ("literal"1851 * or "delta"), followed by the length of data before deflating.1852 * a sequence of 'length-byte' followed by base-85 encoded data1853 * should follow, terminated by a newline.1854 *1855 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1856 * and we would limit the patch line to 66 characters,1857 * so one line can fit up to 13 groups that would decode1858 * to 52 bytes max. The length byte 'A'-'Z' corresponds1859 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1860 */1861int llen, used;1862unsigned long size = *sz_p;1863char*buffer = *buf_p;1864int patch_method;1865unsigned long origlen;1866char*data = NULL;1867int hunk_size =0;1868struct fragment *frag;18691870 llen =linelen(buffer, size);1871 used = llen;18721873*status_p =0;18741875if(starts_with(buffer,"delta ")) {1876 patch_method = BINARY_DELTA_DEFLATED;1877 origlen =strtoul(buffer +6, NULL,10);1878}1879else if(starts_with(buffer,"literal ")) {1880 patch_method = BINARY_LITERAL_DEFLATED;1881 origlen =strtoul(buffer +8, NULL,10);1882}1883else1884return NULL;18851886 state_linenr++;1887 buffer += llen;1888while(1) {1889int byte_length, max_byte_length, newsize;1890 llen =linelen(buffer, size);1891 used += llen;1892 state_linenr++;1893if(llen ==1) {1894/* consume the blank line */1895 buffer++;1896 size--;1897break;1898}1899/*1900 * Minimum line is "A00000\n" which is 7-byte long,1901 * and the line length must be multiple of 5 plus 2.1902 */1903if((llen <7) || (llen-2) %5)1904goto corrupt;1905 max_byte_length = (llen -2) /5*4;1906 byte_length = *buffer;1907if('A'<= byte_length && byte_length <='Z')1908 byte_length = byte_length -'A'+1;1909else if('a'<= byte_length && byte_length <='z')1910 byte_length = byte_length -'a'+27;1911else1912goto corrupt;1913/* if the input length was not multiple of 4, we would1914 * have filler at the end but the filler should never1915 * exceed 3 bytes1916 */1917if(max_byte_length < byte_length ||1918 byte_length <= max_byte_length -4)1919goto corrupt;1920 newsize = hunk_size + byte_length;1921 data =xrealloc(data, newsize);1922if(decode_85(data + hunk_size, buffer +1, byte_length))1923goto corrupt;1924 hunk_size = newsize;1925 buffer += llen;1926 size -= llen;1927}19281929 frag =xcalloc(1,sizeof(*frag));1930 frag->patch =inflate_it(data, hunk_size, origlen);1931 frag->free_patch =1;1932if(!frag->patch)1933goto corrupt;1934free(data);1935 frag->size = origlen;1936*buf_p = buffer;1937*sz_p = size;1938*used_p = used;1939 frag->binary_patch_method = patch_method;1940return frag;19411942 corrupt:1943free(data);1944*status_p = -1;1945error(_("corrupt binary patch at line%d: %.*s"),1946 state_linenr-1, llen-1, buffer);1947return NULL;1948}19491950/*1951 * Returns:1952 * -1 in case of error,1953 * the length of the parsed binary patch otherwise1954 */1955static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1956{1957/*1958 * We have read "GIT binary patch\n"; what follows is a line1959 * that says the patch method (currently, either "literal" or1960 * "delta") and the length of data before deflating; a1961 * sequence of 'length-byte' followed by base-85 encoded data1962 * follows.1963 *1964 * When a binary patch is reversible, there is another binary1965 * hunk in the same format, starting with patch method (either1966 * "literal" or "delta") with the length of data, and a sequence1967 * of length-byte + base-85 encoded data, terminated with another1968 * empty line. This data, when applied to the postimage, produces1969 * the preimage.1970 */1971struct fragment *forward;1972struct fragment *reverse;1973int status;1974int used, used_1;19751976 forward =parse_binary_hunk(&buffer, &size, &status, &used);1977if(!forward && !status)1978/* there has to be one hunk (forward hunk) */1979returnerror(_("unrecognized binary patch at line%d"), state_linenr-1);1980if(status)1981/* otherwise we already gave an error message */1982return status;19831984 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1985if(reverse)1986 used += used_1;1987else if(status) {1988/*1989 * Not having reverse hunk is not an error, but having1990 * a corrupt reverse hunk is.1991 */1992free((void*) forward->patch);1993free(forward);1994return status;1995}1996 forward->next = reverse;1997 patch->fragments = forward;1998 patch->is_binary =1;1999return used;2000}20012002static voidprefix_one(struct apply_state *state,char**name)2003{2004char*old_name = *name;2005if(!old_name)2006return;2007*name =xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));2008free(old_name);2009}20102011static voidprefix_patch(struct apply_state *state,struct patch *p)2012{2013if(!state->prefix || p->is_toplevel_relative)2014return;2015prefix_one(state, &p->new_name);2016prefix_one(state, &p->old_name);2017}20182019/*2020 * include/exclude2021 */20222023static voidadd_name_limit(struct apply_state *state,2024const char*name,2025int exclude)2026{2027struct string_list_item *it;20282029 it =string_list_append(&state->limit_by_name, name);2030 it->util = exclude ? NULL : (void*)1;2031}20322033static intuse_patch(struct apply_state *state,struct patch *p)2034{2035const char*pathname = p->new_name ? p->new_name : p->old_name;2036int i;20372038/* Paths outside are not touched regardless of "--include" */2039if(0< state->prefix_length) {2040int pathlen =strlen(pathname);2041if(pathlen <= state->prefix_length ||2042memcmp(state->prefix, pathname, state->prefix_length))2043return0;2044}20452046/* See if it matches any of exclude/include rule */2047for(i =0; i < state->limit_by_name.nr; i++) {2048struct string_list_item *it = &state->limit_by_name.items[i];2049if(!wildmatch(it->string, pathname,0, NULL))2050return(it->util != NULL);2051}20522053/*2054 * If we had any include, a path that does not match any rule is2055 * not used. Otherwise, we saw bunch of exclude rules (or none)2056 * and such a path is used.2057 */2058return!state->has_include;2059}206020612062/*2063 * Read the patch text in "buffer" that extends for "size" bytes; stop2064 * reading after seeing a single patch (i.e. changes to a single file).2065 * Create fragments (i.e. patch hunks) and hang them to the given patch.2066 * Return the number of bytes consumed, so that the caller can call us2067 * again for the next patch.2068 */2069static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2070{2071int hdrsize, patchsize;2072int offset =find_header(state, buffer, size, &hdrsize, patch);20732074if(offset <0)2075return offset;20762077prefix_patch(state, patch);20782079if(!use_patch(state, patch))2080 patch->ws_rule =0;2081else2082 patch->ws_rule =whitespace_rule(patch->new_name2083? patch->new_name2084: patch->old_name);20852086 patchsize =parse_single_patch(state,2087 buffer + offset + hdrsize,2088 size - offset - hdrsize,2089 patch);20902091if(!patchsize) {2092static const char git_binary[] ="GIT binary patch\n";2093int hd = hdrsize + offset;2094unsigned long llen =linelen(buffer + hd, size - hd);20952096if(llen ==sizeof(git_binary) -1&&2097!memcmp(git_binary, buffer + hd, llen)) {2098int used;2099 state_linenr++;2100 used =parse_binary(buffer + hd + llen,2101 size - hd - llen, patch);2102if(used <0)2103return-1;2104if(used)2105 patchsize = used + llen;2106else2107 patchsize =0;2108}2109else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2110static const char*binhdr[] = {2111"Binary files ",2112"Files ",2113 NULL,2114};2115int i;2116for(i =0; binhdr[i]; i++) {2117int len =strlen(binhdr[i]);2118if(len < size - hd &&2119!memcmp(binhdr[i], buffer + hd, len)) {2120 state_linenr++;2121 patch->is_binary =1;2122 patchsize = llen;2123break;2124}2125}2126}21272128/* Empty patch cannot be applied if it is a text patch2129 * without metadata change. A binary patch appears2130 * empty to us here.2131 */2132if((state->apply || state->check) &&2133(!patch->is_binary && !metadata_changes(patch)))2134die(_("patch with only garbage at line%d"), state_linenr);2135}21362137return offset + hdrsize + patchsize;2138}21392140#define swap(a,b) myswap((a),(b),sizeof(a))21412142#define myswap(a, b, size) do { \2143 unsigned char mytmp[size]; \2144 memcpy(mytmp, &a, size); \2145 memcpy(&a, &b, size); \2146 memcpy(&b, mytmp, size); \2147} while (0)21482149static voidreverse_patches(struct patch *p)2150{2151for(; p; p = p->next) {2152struct fragment *frag = p->fragments;21532154swap(p->new_name, p->old_name);2155swap(p->new_mode, p->old_mode);2156swap(p->is_new, p->is_delete);2157swap(p->lines_added, p->lines_deleted);2158swap(p->old_sha1_prefix, p->new_sha1_prefix);21592160for(; frag; frag = frag->next) {2161swap(frag->newpos, frag->oldpos);2162swap(frag->newlines, frag->oldlines);2163}2164}2165}21662167static const char pluses[] =2168"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2169static const char minuses[]=2170"----------------------------------------------------------------------";21712172static voidshow_stats(struct patch *patch)2173{2174struct strbuf qname = STRBUF_INIT;2175char*cp = patch->new_name ? patch->new_name : patch->old_name;2176int max, add, del;21772178quote_c_style(cp, &qname, NULL,0);21792180/*2181 * "scale" the filename2182 */2183 max = max_len;2184if(max >50)2185 max =50;21862187if(qname.len > max) {2188 cp =strchr(qname.buf + qname.len +3- max,'/');2189if(!cp)2190 cp = qname.buf + qname.len +3- max;2191strbuf_splice(&qname,0, cp - qname.buf,"...",3);2192}21932194if(patch->is_binary) {2195printf(" %-*s | Bin\n", max, qname.buf);2196strbuf_release(&qname);2197return;2198}21992200printf(" %-*s |", max, qname.buf);2201strbuf_release(&qname);22022203/*2204 * scale the add/delete2205 */2206 max = max + max_change >70?70- max : max_change;2207 add = patch->lines_added;2208 del = patch->lines_deleted;22092210if(max_change >0) {2211int total = ((add + del) * max + max_change /2) / max_change;2212 add = (add * max + max_change /2) / max_change;2213 del = total - add;2214}2215printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2216 add, pluses, del, minuses);2217}22182219static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2220{2221switch(st->st_mode & S_IFMT) {2222case S_IFLNK:2223if(strbuf_readlink(buf, path, st->st_size) <0)2224returnerror(_("unable to read symlink%s"), path);2225return0;2226case S_IFREG:2227if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2228returnerror(_("unable to open or read%s"), path);2229convert_to_git(path, buf->buf, buf->len, buf,0);2230return0;2231default:2232return-1;2233}2234}22352236/*2237 * Update the preimage, and the common lines in postimage,2238 * from buffer buf of length len. If postlen is 0 the postimage2239 * is updated in place, otherwise it's updated on a new buffer2240 * of length postlen2241 */22422243static voidupdate_pre_post_images(struct image *preimage,2244struct image *postimage,2245char*buf,2246size_t len,size_t postlen)2247{2248int i, ctx, reduced;2249char*new, *old, *fixed;2250struct image fixed_preimage;22512252/*2253 * Update the preimage with whitespace fixes. Note that we2254 * are not losing preimage->buf -- apply_one_fragment() will2255 * free "oldlines".2256 */2257prepare_image(&fixed_preimage, buf, len,1);2258assert(postlen2259? fixed_preimage.nr == preimage->nr2260: fixed_preimage.nr <= preimage->nr);2261for(i =0; i < fixed_preimage.nr; i++)2262 fixed_preimage.line[i].flag = preimage->line[i].flag;2263free(preimage->line_allocated);2264*preimage = fixed_preimage;22652266/*2267 * Adjust the common context lines in postimage. This can be2268 * done in-place when we are shrinking it with whitespace2269 * fixing, but needs a new buffer when ignoring whitespace or2270 * expanding leading tabs to spaces.2271 *2272 * We trust the caller to tell us if the update can be done2273 * in place (postlen==0) or not.2274 */2275 old = postimage->buf;2276if(postlen)2277new= postimage->buf =xmalloc(postlen);2278else2279new= old;2280 fixed = preimage->buf;22812282for(i = reduced = ctx =0; i < postimage->nr; i++) {2283size_t l_len = postimage->line[i].len;2284if(!(postimage->line[i].flag & LINE_COMMON)) {2285/* an added line -- no counterparts in preimage */2286memmove(new, old, l_len);2287 old += l_len;2288new+= l_len;2289continue;2290}22912292/* a common context -- skip it in the original postimage */2293 old += l_len;22942295/* and find the corresponding one in the fixed preimage */2296while(ctx < preimage->nr &&2297!(preimage->line[ctx].flag & LINE_COMMON)) {2298 fixed += preimage->line[ctx].len;2299 ctx++;2300}23012302/*2303 * preimage is expected to run out, if the caller2304 * fixed addition of trailing blank lines.2305 */2306if(preimage->nr <= ctx) {2307 reduced++;2308continue;2309}23102311/* and copy it in, while fixing the line length */2312 l_len = preimage->line[ctx].len;2313memcpy(new, fixed, l_len);2314new+= l_len;2315 fixed += l_len;2316 postimage->line[i].len = l_len;2317 ctx++;2318}23192320if(postlen2321? postlen <new- postimage->buf2322: postimage->len <new- postimage->buf)2323die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2324(int)postlen, (int) postimage->len, (int)(new- postimage->buf));23252326/* Fix the length of the whole thing */2327 postimage->len =new- postimage->buf;2328 postimage->nr -= reduced;2329}23302331static intline_by_line_fuzzy_match(struct image *img,2332struct image *preimage,2333struct image *postimage,2334unsigned longtry,2335int try_lno,2336int preimage_limit)2337{2338int i;2339size_t imgoff =0;2340size_t preoff =0;2341size_t postlen = postimage->len;2342size_t extra_chars;2343char*buf;2344char*preimage_eof;2345char*preimage_end;2346struct strbuf fixed;2347char*fixed_buf;2348size_t fixed_len;23492350for(i =0; i < preimage_limit; i++) {2351size_t prelen = preimage->line[i].len;2352size_t imglen = img->line[try_lno+i].len;23532354if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2355 preimage->buf + preoff, prelen))2356return0;2357if(preimage->line[i].flag & LINE_COMMON)2358 postlen += imglen - prelen;2359 imgoff += imglen;2360 preoff += prelen;2361}23622363/*2364 * Ok, the preimage matches with whitespace fuzz.2365 *2366 * imgoff now holds the true length of the target that2367 * matches the preimage before the end of the file.2368 *2369 * Count the number of characters in the preimage that fall2370 * beyond the end of the file and make sure that all of them2371 * are whitespace characters. (This can only happen if2372 * we are removing blank lines at the end of the file.)2373 */2374 buf = preimage_eof = preimage->buf + preoff;2375for( ; i < preimage->nr; i++)2376 preoff += preimage->line[i].len;2377 preimage_end = preimage->buf + preoff;2378for( ; buf < preimage_end; buf++)2379if(!isspace(*buf))2380return0;23812382/*2383 * Update the preimage and the common postimage context2384 * lines to use the same whitespace as the target.2385 * If whitespace is missing in the target (i.e.2386 * if the preimage extends beyond the end of the file),2387 * use the whitespace from the preimage.2388 */2389 extra_chars = preimage_end - preimage_eof;2390strbuf_init(&fixed, imgoff + extra_chars);2391strbuf_add(&fixed, img->buf +try, imgoff);2392strbuf_add(&fixed, preimage_eof, extra_chars);2393 fixed_buf =strbuf_detach(&fixed, &fixed_len);2394update_pre_post_images(preimage, postimage,2395 fixed_buf, fixed_len, postlen);2396return1;2397}23982399static intmatch_fragment(struct image *img,2400struct image *preimage,2401struct image *postimage,2402unsigned longtry,2403int try_lno,2404unsigned ws_rule,2405int match_beginning,int match_end)2406{2407int i;2408char*fixed_buf, *buf, *orig, *target;2409struct strbuf fixed;2410size_t fixed_len, postlen;2411int preimage_limit;24122413if(preimage->nr + try_lno <= img->nr) {2414/*2415 * The hunk falls within the boundaries of img.2416 */2417 preimage_limit = preimage->nr;2418if(match_end && (preimage->nr + try_lno != img->nr))2419return0;2420}else if(ws_error_action == correct_ws_error &&2421(ws_rule & WS_BLANK_AT_EOF)) {2422/*2423 * This hunk extends beyond the end of img, and we are2424 * removing blank lines at the end of the file. This2425 * many lines from the beginning of the preimage must2426 * match with img, and the remainder of the preimage2427 * must be blank.2428 */2429 preimage_limit = img->nr - try_lno;2430}else{2431/*2432 * The hunk extends beyond the end of the img and2433 * we are not removing blanks at the end, so we2434 * should reject the hunk at this position.2435 */2436return0;2437}24382439if(match_beginning && try_lno)2440return0;24412442/* Quick hash check */2443for(i =0; i < preimage_limit; i++)2444if((img->line[try_lno + i].flag & LINE_PATCHED) ||2445(preimage->line[i].hash != img->line[try_lno + i].hash))2446return0;24472448if(preimage_limit == preimage->nr) {2449/*2450 * Do we have an exact match? If we were told to match2451 * at the end, size must be exactly at try+fragsize,2452 * otherwise try+fragsize must be still within the preimage,2453 * and either case, the old piece should match the preimage2454 * exactly.2455 */2456if((match_end2457? (try+ preimage->len == img->len)2458: (try+ preimage->len <= img->len)) &&2459!memcmp(img->buf +try, preimage->buf, preimage->len))2460return1;2461}else{2462/*2463 * The preimage extends beyond the end of img, so2464 * there cannot be an exact match.2465 *2466 * There must be one non-blank context line that match2467 * a line before the end of img.2468 */2469char*buf_end;24702471 buf = preimage->buf;2472 buf_end = buf;2473for(i =0; i < preimage_limit; i++)2474 buf_end += preimage->line[i].len;24752476for( ; buf < buf_end; buf++)2477if(!isspace(*buf))2478break;2479if(buf == buf_end)2480return0;2481}24822483/*2484 * No exact match. If we are ignoring whitespace, run a line-by-line2485 * fuzzy matching. We collect all the line length information because2486 * we need it to adjust whitespace if we match.2487 */2488if(ws_ignore_action == ignore_ws_change)2489returnline_by_line_fuzzy_match(img, preimage, postimage,2490try, try_lno, preimage_limit);24912492if(ws_error_action != correct_ws_error)2493return0;24942495/*2496 * The hunk does not apply byte-by-byte, but the hash says2497 * it might with whitespace fuzz. We weren't asked to2498 * ignore whitespace, we were asked to correct whitespace2499 * errors, so let's try matching after whitespace correction.2500 *2501 * While checking the preimage against the target, whitespace2502 * errors in both fixed, we count how large the corresponding2503 * postimage needs to be. The postimage prepared by2504 * apply_one_fragment() has whitespace errors fixed on added2505 * lines already, but the common lines were propagated as-is,2506 * which may become longer when their whitespace errors are2507 * fixed.2508 */25092510/* First count added lines in postimage */2511 postlen =0;2512for(i =0; i < postimage->nr; i++) {2513if(!(postimage->line[i].flag & LINE_COMMON))2514 postlen += postimage->line[i].len;2515}25162517/*2518 * The preimage may extend beyond the end of the file,2519 * but in this loop we will only handle the part of the2520 * preimage that falls within the file.2521 */2522strbuf_init(&fixed, preimage->len +1);2523 orig = preimage->buf;2524 target = img->buf +try;2525for(i =0; i < preimage_limit; i++) {2526size_t oldlen = preimage->line[i].len;2527size_t tgtlen = img->line[try_lno + i].len;2528size_t fixstart = fixed.len;2529struct strbuf tgtfix;2530int match;25312532/* Try fixing the line in the preimage */2533ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25342535/* Try fixing the line in the target */2536strbuf_init(&tgtfix, tgtlen);2537ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);25382539/*2540 * If they match, either the preimage was based on2541 * a version before our tree fixed whitespace breakage,2542 * or we are lacking a whitespace-fix patch the tree2543 * the preimage was based on already had (i.e. target2544 * has whitespace breakage, the preimage doesn't).2545 * In either case, we are fixing the whitespace breakages2546 * so we might as well take the fix together with their2547 * real change.2548 */2549 match = (tgtfix.len == fixed.len - fixstart &&2550!memcmp(tgtfix.buf, fixed.buf + fixstart,2551 fixed.len - fixstart));25522553/* Add the length if this is common with the postimage */2554if(preimage->line[i].flag & LINE_COMMON)2555 postlen += tgtfix.len;25562557strbuf_release(&tgtfix);2558if(!match)2559goto unmatch_exit;25602561 orig += oldlen;2562 target += tgtlen;2563}256425652566/*2567 * Now handle the lines in the preimage that falls beyond the2568 * end of the file (if any). They will only match if they are2569 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2570 * false).2571 */2572for( ; i < preimage->nr; i++) {2573size_t fixstart = fixed.len;/* start of the fixed preimage */2574size_t oldlen = preimage->line[i].len;2575int j;25762577/* Try fixing the line in the preimage */2578ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25792580for(j = fixstart; j < fixed.len; j++)2581if(!isspace(fixed.buf[j]))2582goto unmatch_exit;25832584 orig += oldlen;2585}25862587/*2588 * Yes, the preimage is based on an older version that still2589 * has whitespace breakages unfixed, and fixing them makes the2590 * hunk match. Update the context lines in the postimage.2591 */2592 fixed_buf =strbuf_detach(&fixed, &fixed_len);2593if(postlen < postimage->len)2594 postlen =0;2595update_pre_post_images(preimage, postimage,2596 fixed_buf, fixed_len, postlen);2597return1;25982599 unmatch_exit:2600strbuf_release(&fixed);2601return0;2602}26032604static intfind_pos(struct image *img,2605struct image *preimage,2606struct image *postimage,2607int line,2608unsigned ws_rule,2609int match_beginning,int match_end)2610{2611int i;2612unsigned long backwards, forwards,try;2613int backwards_lno, forwards_lno, try_lno;26142615/*2616 * If match_beginning or match_end is specified, there is no2617 * point starting from a wrong line that will never match and2618 * wander around and wait for a match at the specified end.2619 */2620if(match_beginning)2621 line =0;2622else if(match_end)2623 line = img->nr - preimage->nr;26242625/*2626 * Because the comparison is unsigned, the following test2627 * will also take care of a negative line number that can2628 * result when match_end and preimage is larger than the target.2629 */2630if((size_t) line > img->nr)2631 line = img->nr;26322633try=0;2634for(i =0; i < line; i++)2635try+= img->line[i].len;26362637/*2638 * There's probably some smart way to do this, but I'll leave2639 * that to the smart and beautiful people. I'm simple and stupid.2640 */2641 backwards =try;2642 backwards_lno = line;2643 forwards =try;2644 forwards_lno = line;2645 try_lno = line;26462647for(i =0; ; i++) {2648if(match_fragment(img, preimage, postimage,2649try, try_lno, ws_rule,2650 match_beginning, match_end))2651return try_lno;26522653 again:2654if(backwards_lno ==0&& forwards_lno == img->nr)2655break;26562657if(i &1) {2658if(backwards_lno ==0) {2659 i++;2660goto again;2661}2662 backwards_lno--;2663 backwards -= img->line[backwards_lno].len;2664try= backwards;2665 try_lno = backwards_lno;2666}else{2667if(forwards_lno == img->nr) {2668 i++;2669goto again;2670}2671 forwards += img->line[forwards_lno].len;2672 forwards_lno++;2673try= forwards;2674 try_lno = forwards_lno;2675}26762677}2678return-1;2679}26802681static voidremove_first_line(struct image *img)2682{2683 img->buf += img->line[0].len;2684 img->len -= img->line[0].len;2685 img->line++;2686 img->nr--;2687}26882689static voidremove_last_line(struct image *img)2690{2691 img->len -= img->line[--img->nr].len;2692}26932694/*2695 * The change from "preimage" and "postimage" has been found to2696 * apply at applied_pos (counts in line numbers) in "img".2697 * Update "img" to remove "preimage" and replace it with "postimage".2698 */2699static voidupdate_image(struct apply_state *state,2700struct image *img,2701int applied_pos,2702struct image *preimage,2703struct image *postimage)2704{2705/*2706 * remove the copy of preimage at offset in img2707 * and replace it with postimage2708 */2709int i, nr;2710size_t remove_count, insert_count, applied_at =0;2711char*result;2712int preimage_limit;27132714/*2715 * If we are removing blank lines at the end of img,2716 * the preimage may extend beyond the end.2717 * If that is the case, we must be careful only to2718 * remove the part of the preimage that falls within2719 * the boundaries of img. Initialize preimage_limit2720 * to the number of lines in the preimage that falls2721 * within the boundaries.2722 */2723 preimage_limit = preimage->nr;2724if(preimage_limit > img->nr - applied_pos)2725 preimage_limit = img->nr - applied_pos;27262727for(i =0; i < applied_pos; i++)2728 applied_at += img->line[i].len;27292730 remove_count =0;2731for(i =0; i < preimage_limit; i++)2732 remove_count += img->line[applied_pos + i].len;2733 insert_count = postimage->len;27342735/* Adjust the contents */2736 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2737memcpy(result, img->buf, applied_at);2738memcpy(result + applied_at, postimage->buf, postimage->len);2739memcpy(result + applied_at + postimage->len,2740 img->buf + (applied_at + remove_count),2741 img->len - (applied_at + remove_count));2742free(img->buf);2743 img->buf = result;2744 img->len += insert_count - remove_count;2745 result[img->len] ='\0';27462747/* Adjust the line table */2748 nr = img->nr + postimage->nr - preimage_limit;2749if(preimage_limit < postimage->nr) {2750/*2751 * NOTE: this knows that we never call remove_first_line()2752 * on anything other than pre/post image.2753 */2754REALLOC_ARRAY(img->line, nr);2755 img->line_allocated = img->line;2756}2757if(preimage_limit != postimage->nr)2758memmove(img->line + applied_pos + postimage->nr,2759 img->line + applied_pos + preimage_limit,2760(img->nr - (applied_pos + preimage_limit)) *2761sizeof(*img->line));2762memcpy(img->line + applied_pos,2763 postimage->line,2764 postimage->nr *sizeof(*img->line));2765if(!state->allow_overlap)2766for(i =0; i < postimage->nr; i++)2767 img->line[applied_pos + i].flag |= LINE_PATCHED;2768 img->nr = nr;2769}27702771/*2772 * Use the patch-hunk text in "frag" to prepare two images (preimage and2773 * postimage) for the hunk. Find lines that match "preimage" in "img" and2774 * replace the part of "img" with "postimage" text.2775 */2776static intapply_one_fragment(struct apply_state *state,2777struct image *img,struct fragment *frag,2778int inaccurate_eof,unsigned ws_rule,2779int nth_fragment)2780{2781int match_beginning, match_end;2782const char*patch = frag->patch;2783int size = frag->size;2784char*old, *oldlines;2785struct strbuf newlines;2786int new_blank_lines_at_end =0;2787int found_new_blank_lines_at_end =0;2788int hunk_linenr = frag->linenr;2789unsigned long leading, trailing;2790int pos, applied_pos;2791struct image preimage;2792struct image postimage;27932794memset(&preimage,0,sizeof(preimage));2795memset(&postimage,0,sizeof(postimage));2796 oldlines =xmalloc(size);2797strbuf_init(&newlines, size);27982799 old = oldlines;2800while(size >0) {2801char first;2802int len =linelen(patch, size);2803int plen;2804int added_blank_line =0;2805int is_blank_context =0;2806size_t start;28072808if(!len)2809break;28102811/*2812 * "plen" is how much of the line we should use for2813 * the actual patch data. Normally we just remove the2814 * first character on the line, but if the line is2815 * followed by "\ No newline", then we also remove the2816 * last one (which is the newline, of course).2817 */2818 plen = len -1;2819if(len < size && patch[len] =='\\')2820 plen--;2821 first = *patch;2822if(state->apply_in_reverse) {2823if(first =='-')2824 first ='+';2825else if(first =='+')2826 first ='-';2827}28282829switch(first) {2830case'\n':2831/* Newer GNU diff, empty context line */2832if(plen <0)2833/* ... followed by '\No newline'; nothing */2834break;2835*old++ ='\n';2836strbuf_addch(&newlines,'\n');2837add_line_info(&preimage,"\n",1, LINE_COMMON);2838add_line_info(&postimage,"\n",1, LINE_COMMON);2839 is_blank_context =1;2840break;2841case' ':2842if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2843ws_blank_line(patch +1, plen, ws_rule))2844 is_blank_context =1;2845case'-':2846memcpy(old, patch +1, plen);2847add_line_info(&preimage, old, plen,2848(first ==' '? LINE_COMMON :0));2849 old += plen;2850if(first =='-')2851break;2852/* Fall-through for ' ' */2853case'+':2854/* --no-add does not add new lines */2855if(first =='+'&& state->no_add)2856break;28572858 start = newlines.len;2859if(first !='+'||2860!state->whitespace_error ||2861 ws_error_action != correct_ws_error) {2862strbuf_add(&newlines, patch +1, plen);2863}2864else{2865ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2866}2867add_line_info(&postimage, newlines.buf + start, newlines.len - start,2868(first =='+'?0: LINE_COMMON));2869if(first =='+'&&2870(ws_rule & WS_BLANK_AT_EOF) &&2871ws_blank_line(patch +1, plen, ws_rule))2872 added_blank_line =1;2873break;2874case'@':case'\\':2875/* Ignore it, we already handled it */2876break;2877default:2878if(state->apply_verbosely)2879error(_("invalid start of line: '%c'"), first);2880 applied_pos = -1;2881goto out;2882}2883if(added_blank_line) {2884if(!new_blank_lines_at_end)2885 found_new_blank_lines_at_end = hunk_linenr;2886 new_blank_lines_at_end++;2887}2888else if(is_blank_context)2889;2890else2891 new_blank_lines_at_end =0;2892 patch += len;2893 size -= len;2894 hunk_linenr++;2895}2896if(inaccurate_eof &&2897 old > oldlines && old[-1] =='\n'&&2898 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2899 old--;2900strbuf_setlen(&newlines, newlines.len -1);2901}29022903 leading = frag->leading;2904 trailing = frag->trailing;29052906/*2907 * A hunk to change lines at the beginning would begin with2908 * @@ -1,L +N,M @@2909 * but we need to be careful. -U0 that inserts before the second2910 * line also has this pattern.2911 *2912 * And a hunk to add to an empty file would begin with2913 * @@ -0,0 +N,M @@2914 *2915 * In other words, a hunk that is (frag->oldpos <= 1) with or2916 * without leading context must match at the beginning.2917 */2918 match_beginning = (!frag->oldpos ||2919(frag->oldpos ==1&& !state->unidiff_zero));29202921/*2922 * A hunk without trailing lines must match at the end.2923 * However, we simply cannot tell if a hunk must match end2924 * from the lack of trailing lines if the patch was generated2925 * with unidiff without any context.2926 */2927 match_end = !state->unidiff_zero && !trailing;29282929 pos = frag->newpos ? (frag->newpos -1) :0;2930 preimage.buf = oldlines;2931 preimage.len = old - oldlines;2932 postimage.buf = newlines.buf;2933 postimage.len = newlines.len;2934 preimage.line = preimage.line_allocated;2935 postimage.line = postimage.line_allocated;29362937for(;;) {29382939 applied_pos =find_pos(img, &preimage, &postimage, pos,2940 ws_rule, match_beginning, match_end);29412942if(applied_pos >=0)2943break;29442945/* Am I at my context limits? */2946if((leading <= state->p_context) && (trailing <= state->p_context))2947break;2948if(match_beginning || match_end) {2949 match_beginning = match_end =0;2950continue;2951}29522953/*2954 * Reduce the number of context lines; reduce both2955 * leading and trailing if they are equal otherwise2956 * just reduce the larger context.2957 */2958if(leading >= trailing) {2959remove_first_line(&preimage);2960remove_first_line(&postimage);2961 pos--;2962 leading--;2963}2964if(trailing > leading) {2965remove_last_line(&preimage);2966remove_last_line(&postimage);2967 trailing--;2968}2969}29702971if(applied_pos >=0) {2972if(new_blank_lines_at_end &&2973 preimage.nr + applied_pos >= img->nr &&2974(ws_rule & WS_BLANK_AT_EOF) &&2975 ws_error_action != nowarn_ws_error) {2976record_ws_error(state, WS_BLANK_AT_EOF,"+",1,2977 found_new_blank_lines_at_end);2978if(ws_error_action == correct_ws_error) {2979while(new_blank_lines_at_end--)2980remove_last_line(&postimage);2981}2982/*2983 * We would want to prevent write_out_results()2984 * from taking place in apply_patch() that follows2985 * the callchain led us here, which is:2986 * apply_patch->check_patch_list->check_patch->2987 * apply_data->apply_fragments->apply_one_fragment2988 */2989if(ws_error_action == die_on_ws_error)2990 state->apply =0;2991}29922993if(state->apply_verbosely && applied_pos != pos) {2994int offset = applied_pos - pos;2995if(state->apply_in_reverse)2996 offset =0- offset;2997fprintf_ln(stderr,2998Q_("Hunk #%dsucceeded at%d(offset%dline).",2999"Hunk #%dsucceeded at%d(offset%dlines).",3000 offset),3001 nth_fragment, applied_pos +1, offset);3002}30033004/*3005 * Warn if it was necessary to reduce the number3006 * of context lines.3007 */3008if((leading != frag->leading) ||3009(trailing != frag->trailing))3010fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"3011" to apply fragment at%d"),3012 leading, trailing, applied_pos+1);3013update_image(state, img, applied_pos, &preimage, &postimage);3014}else{3015if(state->apply_verbosely)3016error(_("while searching for:\n%.*s"),3017(int)(old - oldlines), oldlines);3018}30193020out:3021free(oldlines);3022strbuf_release(&newlines);3023free(preimage.line_allocated);3024free(postimage.line_allocated);30253026return(applied_pos <0);3027}30283029static intapply_binary_fragment(struct apply_state *state,3030struct image *img,3031struct patch *patch)3032{3033struct fragment *fragment = patch->fragments;3034unsigned long len;3035void*dst;30363037if(!fragment)3038returnerror(_("missing binary patch data for '%s'"),3039 patch->new_name ?3040 patch->new_name :3041 patch->old_name);30423043/* Binary patch is irreversible without the optional second hunk */3044if(state->apply_in_reverse) {3045if(!fragment->next)3046returnerror("cannot reverse-apply a binary patch "3047"without the reverse hunk to '%s'",3048 patch->new_name3049? patch->new_name : patch->old_name);3050 fragment = fragment->next;3051}3052switch(fragment->binary_patch_method) {3053case BINARY_DELTA_DEFLATED:3054 dst =patch_delta(img->buf, img->len, fragment->patch,3055 fragment->size, &len);3056if(!dst)3057return-1;3058clear_image(img);3059 img->buf = dst;3060 img->len = len;3061return0;3062case BINARY_LITERAL_DEFLATED:3063clear_image(img);3064 img->len = fragment->size;3065 img->buf =xmemdupz(fragment->patch, img->len);3066return0;3067}3068return-1;3069}30703071/*3072 * Replace "img" with the result of applying the binary patch.3073 * The binary patch data itself in patch->fragment is still kept3074 * but the preimage prepared by the caller in "img" is freed here3075 * or in the helper function apply_binary_fragment() this calls.3076 */3077static intapply_binary(struct apply_state *state,3078struct image *img,3079struct patch *patch)3080{3081const char*name = patch->old_name ? patch->old_name : patch->new_name;3082unsigned char sha1[20];30833084/*3085 * For safety, we require patch index line to contain3086 * full 40-byte textual SHA1 for old and new, at least for now.3087 */3088if(strlen(patch->old_sha1_prefix) !=40||3089strlen(patch->new_sha1_prefix) !=40||3090get_sha1_hex(patch->old_sha1_prefix, sha1) ||3091get_sha1_hex(patch->new_sha1_prefix, sha1))3092returnerror("cannot apply binary patch to '%s' "3093"without full index line", name);30943095if(patch->old_name) {3096/*3097 * See if the old one matches what the patch3098 * applies to.3099 */3100hash_sha1_file(img->buf, img->len, blob_type, sha1);3101if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3102returnerror("the patch applies to '%s' (%s), "3103"which does not match the "3104"current contents.",3105 name,sha1_to_hex(sha1));3106}3107else{3108/* Otherwise, the old one must be empty. */3109if(img->len)3110returnerror("the patch applies to an empty "3111"'%s' but it is not empty", name);3112}31133114get_sha1_hex(patch->new_sha1_prefix, sha1);3115if(is_null_sha1(sha1)) {3116clear_image(img);3117return0;/* deletion patch */3118}31193120if(has_sha1_file(sha1)) {3121/* We already have the postimage */3122enum object_type type;3123unsigned long size;3124char*result;31253126 result =read_sha1_file(sha1, &type, &size);3127if(!result)3128returnerror("the necessary postimage%sfor "3129"'%s' cannot be read",3130 patch->new_sha1_prefix, name);3131clear_image(img);3132 img->buf = result;3133 img->len = size;3134}else{3135/*3136 * We have verified buf matches the preimage;3137 * apply the patch data to it, which is stored3138 * in the patch->fragments->{patch,size}.3139 */3140if(apply_binary_fragment(state, img, patch))3141returnerror(_("binary patch does not apply to '%s'"),3142 name);31433144/* verify that the result matches */3145hash_sha1_file(img->buf, img->len, blob_type, sha1);3146if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3147returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3148 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3149}31503151return0;3152}31533154static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3155{3156struct fragment *frag = patch->fragments;3157const char*name = patch->old_name ? patch->old_name : patch->new_name;3158unsigned ws_rule = patch->ws_rule;3159unsigned inaccurate_eof = patch->inaccurate_eof;3160int nth =0;31613162if(patch->is_binary)3163returnapply_binary(state, img, patch);31643165while(frag) {3166 nth++;3167if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3168error(_("patch failed:%s:%ld"), name, frag->oldpos);3169if(!state->apply_with_reject)3170return-1;3171 frag->rejected =1;3172}3173 frag = frag->next;3174}3175return0;3176}31773178static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3179{3180if(S_ISGITLINK(mode)) {3181strbuf_grow(buf,100);3182strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3183}else{3184enum object_type type;3185unsigned long sz;3186char*result;31873188 result =read_sha1_file(sha1, &type, &sz);3189if(!result)3190return-1;3191/* XXX read_sha1_file NUL-terminates */3192strbuf_attach(buf, result, sz, sz +1);3193}3194return0;3195}31963197static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3198{3199if(!ce)3200return0;3201returnread_blob_object(buf, ce->sha1, ce->ce_mode);3202}32033204static struct patch *in_fn_table(const char*name)3205{3206struct string_list_item *item;32073208if(name == NULL)3209return NULL;32103211 item =string_list_lookup(&fn_table, name);3212if(item != NULL)3213return(struct patch *)item->util;32143215return NULL;3216}32173218/*3219 * item->util in the filename table records the status of the path.3220 * Usually it points at a patch (whose result records the contents3221 * of it after applying it), but it could be PATH_WAS_DELETED for a3222 * path that a previously applied patch has already removed, or3223 * PATH_TO_BE_DELETED for a path that a later patch would remove.3224 *3225 * The latter is needed to deal with a case where two paths A and B3226 * are swapped by first renaming A to B and then renaming B to A;3227 * moving A to B should not be prevented due to presence of B as we3228 * will remove it in a later patch.3229 */3230#define PATH_TO_BE_DELETED ((struct patch *) -2)3231#define PATH_WAS_DELETED ((struct patch *) -1)32323233static intto_be_deleted(struct patch *patch)3234{3235return patch == PATH_TO_BE_DELETED;3236}32373238static intwas_deleted(struct patch *patch)3239{3240return patch == PATH_WAS_DELETED;3241}32423243static voidadd_to_fn_table(struct patch *patch)3244{3245struct string_list_item *item;32463247/*3248 * Always add new_name unless patch is a deletion3249 * This should cover the cases for normal diffs,3250 * file creations and copies3251 */3252if(patch->new_name != NULL) {3253 item =string_list_insert(&fn_table, patch->new_name);3254 item->util = patch;3255}32563257/*3258 * store a failure on rename/deletion cases because3259 * later chunks shouldn't patch old names3260 */3261if((patch->new_name == NULL) || (patch->is_rename)) {3262 item =string_list_insert(&fn_table, patch->old_name);3263 item->util = PATH_WAS_DELETED;3264}3265}32663267static voidprepare_fn_table(struct patch *patch)3268{3269/*3270 * store information about incoming file deletion3271 */3272while(patch) {3273if((patch->new_name == NULL) || (patch->is_rename)) {3274struct string_list_item *item;3275 item =string_list_insert(&fn_table, patch->old_name);3276 item->util = PATH_TO_BE_DELETED;3277}3278 patch = patch->next;3279}3280}32813282static intcheckout_target(struct index_state *istate,3283struct cache_entry *ce,struct stat *st)3284{3285struct checkout costate;32863287memset(&costate,0,sizeof(costate));3288 costate.base_dir ="";3289 costate.refresh_cache =1;3290 costate.istate = istate;3291if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3292returnerror(_("cannot checkout%s"), ce->name);3293return0;3294}32953296static struct patch *previous_patch(struct patch *patch,int*gone)3297{3298struct patch *previous;32993300*gone =0;3301if(patch->is_copy || patch->is_rename)3302return NULL;/* "git" patches do not depend on the order */33033304 previous =in_fn_table(patch->old_name);3305if(!previous)3306return NULL;33073308if(to_be_deleted(previous))3309return NULL;/* the deletion hasn't happened yet */33103311if(was_deleted(previous))3312*gone =1;33133314return previous;3315}33163317static intverify_index_match(const struct cache_entry *ce,struct stat *st)3318{3319if(S_ISGITLINK(ce->ce_mode)) {3320if(!S_ISDIR(st->st_mode))3321return-1;3322return0;3323}3324returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3325}33263327#define SUBMODULE_PATCH_WITHOUT_INDEX 133283329static intload_patch_target(struct apply_state *state,3330struct strbuf *buf,3331const struct cache_entry *ce,3332struct stat *st,3333const char*name,3334unsigned expected_mode)3335{3336if(state->cached || state->check_index) {3337if(read_file_or_gitlink(ce, buf))3338returnerror(_("read of%sfailed"), name);3339}else if(name) {3340if(S_ISGITLINK(expected_mode)) {3341if(ce)3342returnread_file_or_gitlink(ce, buf);3343else3344return SUBMODULE_PATCH_WITHOUT_INDEX;3345}else if(has_symlink_leading_path(name,strlen(name))) {3346returnerror(_("reading from '%s' beyond a symbolic link"), name);3347}else{3348if(read_old_data(st, name, buf))3349returnerror(_("read of%sfailed"), name);3350}3351}3352return0;3353}33543355/*3356 * We are about to apply "patch"; populate the "image" with the3357 * current version we have, from the working tree or from the index,3358 * depending on the situation e.g. --cached/--index. If we are3359 * applying a non-git patch that incrementally updates the tree,3360 * we read from the result of a previous diff.3361 */3362static intload_preimage(struct apply_state *state,3363struct image *image,3364struct patch *patch,struct stat *st,3365const struct cache_entry *ce)3366{3367struct strbuf buf = STRBUF_INIT;3368size_t len;3369char*img;3370struct patch *previous;3371int status;33723373 previous =previous_patch(patch, &status);3374if(status)3375returnerror(_("path%shas been renamed/deleted"),3376 patch->old_name);3377if(previous) {3378/* We have a patched copy in memory; use that. */3379strbuf_add(&buf, previous->result, previous->resultsize);3380}else{3381 status =load_patch_target(state, &buf, ce, st,3382 patch->old_name, patch->old_mode);3383if(status <0)3384return status;3385else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3386/*3387 * There is no way to apply subproject3388 * patch without looking at the index.3389 * NEEDSWORK: shouldn't this be flagged3390 * as an error???3391 */3392free_fragment_list(patch->fragments);3393 patch->fragments = NULL;3394}else if(status) {3395returnerror(_("read of%sfailed"), patch->old_name);3396}3397}33983399 img =strbuf_detach(&buf, &len);3400prepare_image(image, img, len, !patch->is_binary);3401return0;3402}34033404static intthree_way_merge(struct image *image,3405char*path,3406const unsigned char*base,3407const unsigned char*ours,3408const unsigned char*theirs)3409{3410 mmfile_t base_file, our_file, their_file;3411 mmbuffer_t result = { NULL };3412int status;34133414read_mmblob(&base_file, base);3415read_mmblob(&our_file, ours);3416read_mmblob(&their_file, theirs);3417 status =ll_merge(&result, path,3418&base_file,"base",3419&our_file,"ours",3420&their_file,"theirs", NULL);3421free(base_file.ptr);3422free(our_file.ptr);3423free(their_file.ptr);3424if(status <0|| !result.ptr) {3425free(result.ptr);3426return-1;3427}3428clear_image(image);3429 image->buf = result.ptr;3430 image->len = result.size;34313432return status;3433}34343435/*3436 * When directly falling back to add/add three-way merge, we read from3437 * the current contents of the new_name. In no cases other than that3438 * this function will be called.3439 */3440static intload_current(struct apply_state *state,3441struct image *image,3442struct patch *patch)3443{3444struct strbuf buf = STRBUF_INIT;3445int status, pos;3446size_t len;3447char*img;3448struct stat st;3449struct cache_entry *ce;3450char*name = patch->new_name;3451unsigned mode = patch->new_mode;34523453if(!patch->is_new)3454die("BUG: patch to%sis not a creation", patch->old_name);34553456 pos =cache_name_pos(name,strlen(name));3457if(pos <0)3458returnerror(_("%s: does not exist in index"), name);3459 ce = active_cache[pos];3460if(lstat(name, &st)) {3461if(errno != ENOENT)3462returnerror(_("%s:%s"), name,strerror(errno));3463if(checkout_target(&the_index, ce, &st))3464return-1;3465}3466if(verify_index_match(ce, &st))3467returnerror(_("%s: does not match index"), name);34683469 status =load_patch_target(state, &buf, ce, &st, name, mode);3470if(status <0)3471return status;3472else if(status)3473return-1;3474 img =strbuf_detach(&buf, &len);3475prepare_image(image, img, len, !patch->is_binary);3476return0;3477}34783479static inttry_threeway(struct apply_state *state,3480struct image *image,3481struct patch *patch,3482struct stat *st,3483const struct cache_entry *ce)3484{3485unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3486struct strbuf buf = STRBUF_INIT;3487size_t len;3488int status;3489char*img;3490struct image tmp_image;34913492/* No point falling back to 3-way merge in these cases */3493if(patch->is_delete ||3494S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3495return-1;34963497/* Preimage the patch was prepared for */3498if(patch->is_new)3499write_sha1_file("",0, blob_type, pre_sha1);3500else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3501read_blob_object(&buf, pre_sha1, patch->old_mode))3502returnerror("repository lacks the necessary blob to fall back on 3-way merge.");35033504fprintf(stderr,"Falling back to three-way merge...\n");35053506 img =strbuf_detach(&buf, &len);3507prepare_image(&tmp_image, img, len,1);3508/* Apply the patch to get the post image */3509if(apply_fragments(state, &tmp_image, patch) <0) {3510clear_image(&tmp_image);3511return-1;3512}3513/* post_sha1[] is theirs */3514write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3515clear_image(&tmp_image);35163517/* our_sha1[] is ours */3518if(patch->is_new) {3519if(load_current(state, &tmp_image, patch))3520returnerror("cannot read the current contents of '%s'",3521 patch->new_name);3522}else{3523if(load_preimage(state, &tmp_image, patch, st, ce))3524returnerror("cannot read the current contents of '%s'",3525 patch->old_name);3526}3527write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3528clear_image(&tmp_image);35293530/* in-core three-way merge between post and our using pre as base */3531 status =three_way_merge(image, patch->new_name,3532 pre_sha1, our_sha1, post_sha1);3533if(status <0) {3534fprintf(stderr,"Failed to fall back on three-way merge...\n");3535return status;3536}35373538if(status) {3539 patch->conflicted_threeway =1;3540if(patch->is_new)3541oidclr(&patch->threeway_stage[0]);3542else3543hashcpy(patch->threeway_stage[0].hash, pre_sha1);3544hashcpy(patch->threeway_stage[1].hash, our_sha1);3545hashcpy(patch->threeway_stage[2].hash, post_sha1);3546fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3547}else{3548fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3549}3550return0;3551}35523553static intapply_data(struct apply_state *state,struct patch *patch,3554struct stat *st,const struct cache_entry *ce)3555{3556struct image image;35573558if(load_preimage(state, &image, patch, st, ce) <0)3559return-1;35603561if(patch->direct_to_threeway ||3562apply_fragments(state, &image, patch) <0) {3563/* Note: with --reject, apply_fragments() returns 0 */3564if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3565return-1;3566}3567 patch->result = image.buf;3568 patch->resultsize = image.len;3569add_to_fn_table(patch);3570free(image.line_allocated);35713572if(0< patch->is_delete && patch->resultsize)3573returnerror(_("removal patch leaves file contents"));35743575return0;3576}35773578/*3579 * If "patch" that we are looking at modifies or deletes what we have,3580 * we would want it not to lose any local modification we have, either3581 * in the working tree or in the index.3582 *3583 * This also decides if a non-git patch is a creation patch or a3584 * modification to an existing empty file. We do not check the state3585 * of the current tree for a creation patch in this function; the caller3586 * check_patch() separately makes sure (and errors out otherwise) that3587 * the path the patch creates does not exist in the current tree.3588 */3589static intcheck_preimage(struct apply_state *state,3590struct patch *patch,3591struct cache_entry **ce,3592struct stat *st)3593{3594const char*old_name = patch->old_name;3595struct patch *previous = NULL;3596int stat_ret =0, status;3597unsigned st_mode =0;35983599if(!old_name)3600return0;36013602assert(patch->is_new <=0);3603 previous =previous_patch(patch, &status);36043605if(status)3606returnerror(_("path%shas been renamed/deleted"), old_name);3607if(previous) {3608 st_mode = previous->new_mode;3609}else if(!state->cached) {3610 stat_ret =lstat(old_name, st);3611if(stat_ret && errno != ENOENT)3612returnerror(_("%s:%s"), old_name,strerror(errno));3613}36143615if(state->check_index && !previous) {3616int pos =cache_name_pos(old_name,strlen(old_name));3617if(pos <0) {3618if(patch->is_new <0)3619goto is_new;3620returnerror(_("%s: does not exist in index"), old_name);3621}3622*ce = active_cache[pos];3623if(stat_ret <0) {3624if(checkout_target(&the_index, *ce, st))3625return-1;3626}3627if(!state->cached &&verify_index_match(*ce, st))3628returnerror(_("%s: does not match index"), old_name);3629if(state->cached)3630 st_mode = (*ce)->ce_mode;3631}else if(stat_ret <0) {3632if(patch->is_new <0)3633goto is_new;3634returnerror(_("%s:%s"), old_name,strerror(errno));3635}36363637if(!state->cached && !previous)3638 st_mode =ce_mode_from_stat(*ce, st->st_mode);36393640if(patch->is_new <0)3641 patch->is_new =0;3642if(!patch->old_mode)3643 patch->old_mode = st_mode;3644if((st_mode ^ patch->old_mode) & S_IFMT)3645returnerror(_("%s: wrong type"), old_name);3646if(st_mode != patch->old_mode)3647warning(_("%shas type%o, expected%o"),3648 old_name, st_mode, patch->old_mode);3649if(!patch->new_mode && !patch->is_delete)3650 patch->new_mode = st_mode;3651return0;36523653 is_new:3654 patch->is_new =1;3655 patch->is_delete =0;3656free(patch->old_name);3657 patch->old_name = NULL;3658return0;3659}366036613662#define EXISTS_IN_INDEX 13663#define EXISTS_IN_WORKTREE 236643665static intcheck_to_create(struct apply_state *state,3666const char*new_name,3667int ok_if_exists)3668{3669struct stat nst;36703671if(state->check_index &&3672cache_name_pos(new_name,strlen(new_name)) >=0&&3673!ok_if_exists)3674return EXISTS_IN_INDEX;3675if(state->cached)3676return0;36773678if(!lstat(new_name, &nst)) {3679if(S_ISDIR(nst.st_mode) || ok_if_exists)3680return0;3681/*3682 * A leading component of new_name might be a symlink3683 * that is going to be removed with this patch, but3684 * still pointing at somewhere that has the path.3685 * In such a case, path "new_name" does not exist as3686 * far as git is concerned.3687 */3688if(has_symlink_leading_path(new_name,strlen(new_name)))3689return0;36903691return EXISTS_IN_WORKTREE;3692}else if((errno != ENOENT) && (errno != ENOTDIR)) {3693returnerror("%s:%s", new_name,strerror(errno));3694}3695return0;3696}36973698/*3699 * We need to keep track of how symlinks in the preimage are3700 * manipulated by the patches. A patch to add a/b/c where a/b3701 * is a symlink should not be allowed to affect the directory3702 * the symlink points at, but if the same patch removes a/b,3703 * it is perfectly fine, as the patch removes a/b to make room3704 * to create a directory a/b so that a/b/c can be created.3705 */3706static struct string_list symlink_changes;3707#define SYMLINK_GOES_AWAY 013708#define SYMLINK_IN_RESULT 0237093710static uintptr_tregister_symlink_changes(const char*path,uintptr_t what)3711{3712struct string_list_item *ent;37133714 ent =string_list_lookup(&symlink_changes, path);3715if(!ent) {3716 ent =string_list_insert(&symlink_changes, path);3717 ent->util = (void*)0;3718}3719 ent->util = (void*)(what | ((uintptr_t)ent->util));3720return(uintptr_t)ent->util;3721}37223723static uintptr_tcheck_symlink_changes(const char*path)3724{3725struct string_list_item *ent;37263727 ent =string_list_lookup(&symlink_changes, path);3728if(!ent)3729return0;3730return(uintptr_t)ent->util;3731}37323733static voidprepare_symlink_changes(struct patch *patch)3734{3735for( ; patch; patch = patch->next) {3736if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3737(patch->is_rename || patch->is_delete))3738/* the symlink at patch->old_name is removed */3739register_symlink_changes(patch->old_name, SYMLINK_GOES_AWAY);37403741if(patch->new_name &&S_ISLNK(patch->new_mode))3742/* the symlink at patch->new_name is created or remains */3743register_symlink_changes(patch->new_name, SYMLINK_IN_RESULT);3744}3745}37463747static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3748{3749do{3750unsigned int change;37513752while(--name->len && name->buf[name->len] !='/')3753;/* scan backwards */3754if(!name->len)3755break;3756 name->buf[name->len] ='\0';3757 change =check_symlink_changes(name->buf);3758if(change & SYMLINK_IN_RESULT)3759return1;3760if(change & SYMLINK_GOES_AWAY)3761/*3762 * This cannot be "return 0", because we may3763 * see a new one created at a higher level.3764 */3765continue;37663767/* otherwise, check the preimage */3768if(state->check_index) {3769struct cache_entry *ce;37703771 ce =cache_file_exists(name->buf, name->len, ignore_case);3772if(ce &&S_ISLNK(ce->ce_mode))3773return1;3774}else{3775struct stat st;3776if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3777return1;3778}3779}while(1);3780return0;3781}37823783static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3784{3785int ret;3786struct strbuf name = STRBUF_INIT;37873788assert(*name_ !='\0');3789strbuf_addstr(&name, name_);3790 ret =path_is_beyond_symlink_1(state, &name);3791strbuf_release(&name);37923793return ret;3794}37953796static voiddie_on_unsafe_path(struct patch *patch)3797{3798const char*old_name = NULL;3799const char*new_name = NULL;3800if(patch->is_delete)3801 old_name = patch->old_name;3802else if(!patch->is_new && !patch->is_copy)3803 old_name = patch->old_name;3804if(!patch->is_delete)3805 new_name = patch->new_name;38063807if(old_name && !verify_path(old_name))3808die(_("invalid path '%s'"), old_name);3809if(new_name && !verify_path(new_name))3810die(_("invalid path '%s'"), new_name);3811}38123813/*3814 * Check and apply the patch in-core; leave the result in patch->result3815 * for the caller to write it out to the final destination.3816 */3817static intcheck_patch(struct apply_state *state,struct patch *patch)3818{3819struct stat st;3820const char*old_name = patch->old_name;3821const char*new_name = patch->new_name;3822const char*name = old_name ? old_name : new_name;3823struct cache_entry *ce = NULL;3824struct patch *tpatch;3825int ok_if_exists;3826int status;38273828 patch->rejected =1;/* we will drop this after we succeed */38293830 status =check_preimage(state, patch, &ce, &st);3831if(status)3832return status;3833 old_name = patch->old_name;38343835/*3836 * A type-change diff is always split into a patch to delete3837 * old, immediately followed by a patch to create new (see3838 * diff.c::run_diff()); in such a case it is Ok that the entry3839 * to be deleted by the previous patch is still in the working3840 * tree and in the index.3841 *3842 * A patch to swap-rename between A and B would first rename A3843 * to B and then rename B to A. While applying the first one,3844 * the presence of B should not stop A from getting renamed to3845 * B; ask to_be_deleted() about the later rename. Removal of3846 * B and rename from A to B is handled the same way by asking3847 * was_deleted().3848 */3849if((tpatch =in_fn_table(new_name)) &&3850(was_deleted(tpatch) ||to_be_deleted(tpatch)))3851 ok_if_exists =1;3852else3853 ok_if_exists =0;38543855if(new_name &&3856((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3857int err =check_to_create(state, new_name, ok_if_exists);38583859if(err && state->threeway) {3860 patch->direct_to_threeway =1;3861}else switch(err) {3862case0:3863break;/* happy */3864case EXISTS_IN_INDEX:3865returnerror(_("%s: already exists in index"), new_name);3866break;3867case EXISTS_IN_WORKTREE:3868returnerror(_("%s: already exists in working directory"),3869 new_name);3870default:3871return err;3872}38733874if(!patch->new_mode) {3875if(0< patch->is_new)3876 patch->new_mode = S_IFREG |0644;3877else3878 patch->new_mode = patch->old_mode;3879}3880}38813882if(new_name && old_name) {3883int same = !strcmp(old_name, new_name);3884if(!patch->new_mode)3885 patch->new_mode = patch->old_mode;3886if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3887if(same)3888returnerror(_("new mode (%o) of%sdoes not "3889"match old mode (%o)"),3890 patch->new_mode, new_name,3891 patch->old_mode);3892else3893returnerror(_("new mode (%o) of%sdoes not "3894"match old mode (%o) of%s"),3895 patch->new_mode, new_name,3896 patch->old_mode, old_name);3897}3898}38993900if(!state->unsafe_paths)3901die_on_unsafe_path(patch);39023903/*3904 * An attempt to read from or delete a path that is beyond a3905 * symbolic link will be prevented by load_patch_target() that3906 * is called at the beginning of apply_data() so we do not3907 * have to worry about a patch marked with "is_delete" bit3908 * here. We however need to make sure that the patch result3909 * is not deposited to a path that is beyond a symbolic link3910 * here.3911 */3912if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3913returnerror(_("affected file '%s' is beyond a symbolic link"),3914 patch->new_name);39153916if(apply_data(state, patch, &st, ce) <0)3917returnerror(_("%s: patch does not apply"), name);3918 patch->rejected =0;3919return0;3920}39213922static intcheck_patch_list(struct apply_state *state,struct patch *patch)3923{3924int err =0;39253926prepare_symlink_changes(patch);3927prepare_fn_table(patch);3928while(patch) {3929if(state->apply_verbosely)3930say_patch_name(stderr,3931_("Checking patch%s..."), patch);3932 err |=check_patch(state, patch);3933 patch = patch->next;3934}3935return err;3936}39373938/* This function tries to read the sha1 from the current index */3939static intget_current_sha1(const char*path,unsigned char*sha1)3940{3941int pos;39423943if(read_cache() <0)3944return-1;3945 pos =cache_name_pos(path,strlen(path));3946if(pos <0)3947return-1;3948hashcpy(sha1, active_cache[pos]->sha1);3949return0;3950}39513952static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3953{3954/*3955 * A usable gitlink patch has only one fragment (hunk) that looks like:3956 * @@ -1 +1 @@3957 * -Subproject commit <old sha1>3958 * +Subproject commit <new sha1>3959 * or3960 * @@ -1 +0,0 @@3961 * -Subproject commit <old sha1>3962 * for a removal patch.3963 */3964struct fragment *hunk = p->fragments;3965static const char heading[] ="-Subproject commit ";3966char*preimage;39673968if(/* does the patch have only one hunk? */3969 hunk && !hunk->next &&3970/* is its preimage one line? */3971 hunk->oldpos ==1&& hunk->oldlines ==1&&3972/* does preimage begin with the heading? */3973(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3974starts_with(++preimage, heading) &&3975/* does it record full SHA-1? */3976!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3977 preimage[sizeof(heading) +40-1] =='\n'&&3978/* does the abbreviated name on the index line agree with it? */3979starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3980return0;/* it all looks fine */39813982/* we may have full object name on the index line */3983returnget_sha1_hex(p->old_sha1_prefix, sha1);3984}39853986/* Build an index that contains the just the files needed for a 3way merge */3987static voidbuild_fake_ancestor(struct patch *list,const char*filename)3988{3989struct patch *patch;3990struct index_state result = { NULL };3991static struct lock_file lock;39923993/* Once we start supporting the reverse patch, it may be3994 * worth showing the new sha1 prefix, but until then...3995 */3996for(patch = list; patch; patch = patch->next) {3997unsigned char sha1[20];3998struct cache_entry *ce;3999const char*name;40004001 name = patch->old_name ? patch->old_name : patch->new_name;4002if(0< patch->is_new)4003continue;40044005if(S_ISGITLINK(patch->old_mode)) {4006if(!preimage_sha1_in_gitlink_patch(patch, sha1))4007;/* ok, the textual part looks sane */4008else4009die("sha1 information is lacking or useless for submodule%s",4010 name);4011}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {4012;/* ok */4013}else if(!patch->lines_added && !patch->lines_deleted) {4014/* mode-only change: update the current */4015if(get_current_sha1(patch->old_name, sha1))4016die("mode change for%s, which is not "4017"in current HEAD", name);4018}else4019die("sha1 information is lacking or useless "4020"(%s).", name);40214022 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);4023if(!ce)4024die(_("make_cache_entry failed for path '%s'"), name);4025if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))4026die("Could not add%sto temporary index", name);4027}40284029hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);4030if(write_locked_index(&result, &lock, COMMIT_LOCK))4031die("Could not write temporary index to%s", filename);40324033discard_index(&result);4034}40354036static voidstat_patch_list(struct patch *patch)4037{4038int files, adds, dels;40394040for(files = adds = dels =0; patch ; patch = patch->next) {4041 files++;4042 adds += patch->lines_added;4043 dels += patch->lines_deleted;4044show_stats(patch);4045}40464047print_stat_summary(stdout, files, adds, dels);4048}40494050static voidnumstat_patch_list(struct apply_state *state,4051struct patch *patch)4052{4053for( ; patch; patch = patch->next) {4054const char*name;4055 name = patch->new_name ? patch->new_name : patch->old_name;4056if(patch->is_binary)4057printf("-\t-\t");4058else4059printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4060write_name_quoted(name, stdout, state->line_termination);4061}4062}40634064static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4065{4066if(mode)4067printf("%smode%06o%s\n", newdelete, mode, name);4068else4069printf("%s %s\n", newdelete, name);4070}40714072static voidshow_mode_change(struct patch *p,int show_name)4073{4074if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4075if(show_name)4076printf(" mode change%06o =>%06o%s\n",4077 p->old_mode, p->new_mode, p->new_name);4078else4079printf(" mode change%06o =>%06o\n",4080 p->old_mode, p->new_mode);4081}4082}40834084static voidshow_rename_copy(struct patch *p)4085{4086const char*renamecopy = p->is_rename ?"rename":"copy";4087const char*old, *new;40884089/* Find common prefix */4090 old = p->old_name;4091new= p->new_name;4092while(1) {4093const char*slash_old, *slash_new;4094 slash_old =strchr(old,'/');4095 slash_new =strchr(new,'/');4096if(!slash_old ||4097!slash_new ||4098 slash_old - old != slash_new -new||4099memcmp(old,new, slash_new -new))4100break;4101 old = slash_old +1;4102new= slash_new +1;4103}4104/* p->old_name thru old is the common prefix, and old and new4105 * through the end of names are renames4106 */4107if(old != p->old_name)4108printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4109(int)(old - p->old_name), p->old_name,4110 old,new, p->score);4111else4112printf("%s %s=>%s(%d%%)\n", renamecopy,4113 p->old_name, p->new_name, p->score);4114show_mode_change(p,0);4115}41164117static voidsummary_patch_list(struct patch *patch)4118{4119struct patch *p;41204121for(p = patch; p; p = p->next) {4122if(p->is_new)4123show_file_mode_name("create", p->new_mode, p->new_name);4124else if(p->is_delete)4125show_file_mode_name("delete", p->old_mode, p->old_name);4126else{4127if(p->is_rename || p->is_copy)4128show_rename_copy(p);4129else{4130if(p->score) {4131printf(" rewrite%s(%d%%)\n",4132 p->new_name, p->score);4133show_mode_change(p,0);4134}4135else4136show_mode_change(p,1);4137}4138}4139}4140}41414142static voidpatch_stats(struct patch *patch)4143{4144int lines = patch->lines_added + patch->lines_deleted;41454146if(lines > max_change)4147 max_change = lines;4148if(patch->old_name) {4149int len =quote_c_style(patch->old_name, NULL, NULL,0);4150if(!len)4151 len =strlen(patch->old_name);4152if(len > max_len)4153 max_len = len;4154}4155if(patch->new_name) {4156int len =quote_c_style(patch->new_name, NULL, NULL,0);4157if(!len)4158 len =strlen(patch->new_name);4159if(len > max_len)4160 max_len = len;4161}4162}41634164static voidremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4165{4166if(state->update_index) {4167if(remove_file_from_cache(patch->old_name) <0)4168die(_("unable to remove%sfrom index"), patch->old_name);4169}4170if(!state->cached) {4171if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4172remove_path(patch->old_name);4173}4174}4175}41764177static voidadd_index_file(struct apply_state *state,4178const char*path,4179unsigned mode,4180void*buf,4181unsigned long size)4182{4183struct stat st;4184struct cache_entry *ce;4185int namelen =strlen(path);4186unsigned ce_size =cache_entry_size(namelen);41874188if(!state->update_index)4189return;41904191 ce =xcalloc(1, ce_size);4192memcpy(ce->name, path, namelen);4193 ce->ce_mode =create_ce_mode(mode);4194 ce->ce_flags =create_ce_flags(0);4195 ce->ce_namelen = namelen;4196if(S_ISGITLINK(mode)) {4197const char*s;41984199if(!skip_prefix(buf,"Subproject commit ", &s) ||4200get_sha1_hex(s, ce->sha1))4201die(_("corrupt patch for submodule%s"), path);4202}else{4203if(!state->cached) {4204if(lstat(path, &st) <0)4205die_errno(_("unable to stat newly created file '%s'"),4206 path);4207fill_stat_cache_info(ce, &st);4208}4209if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4210die(_("unable to create backing store for newly created file%s"), path);4211}4212if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4213die(_("unable to add cache entry for%s"), path);4214}42154216static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4217{4218int fd;4219struct strbuf nbuf = STRBUF_INIT;42204221if(S_ISGITLINK(mode)) {4222struct stat st;4223if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4224return0;4225returnmkdir(path,0777);4226}42274228if(has_symlinks &&S_ISLNK(mode))4229/* Although buf:size is counted string, it also is NUL4230 * terminated.4231 */4232returnsymlink(buf, path);42334234 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4235if(fd <0)4236return-1;42374238if(convert_to_working_tree(path, buf, size, &nbuf)) {4239 size = nbuf.len;4240 buf = nbuf.buf;4241}4242write_or_die(fd, buf, size);4243strbuf_release(&nbuf);42444245if(close(fd) <0)4246die_errno(_("closing file '%s'"), path);4247return0;4248}42494250/*4251 * We optimistically assume that the directories exist,4252 * which is true 99% of the time anyway. If they don't,4253 * we create them and try again.4254 */4255static voidcreate_one_file(struct apply_state *state,4256char*path,4257unsigned mode,4258const char*buf,4259unsigned long size)4260{4261if(state->cached)4262return;4263if(!try_create_file(path, mode, buf, size))4264return;42654266if(errno == ENOENT) {4267if(safe_create_leading_directories(path))4268return;4269if(!try_create_file(path, mode, buf, size))4270return;4271}42724273if(errno == EEXIST || errno == EACCES) {4274/* We may be trying to create a file where a directory4275 * used to be.4276 */4277struct stat st;4278if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4279 errno = EEXIST;4280}42814282if(errno == EEXIST) {4283unsigned int nr =getpid();42844285for(;;) {4286char newpath[PATH_MAX];4287mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4288if(!try_create_file(newpath, mode, buf, size)) {4289if(!rename(newpath, path))4290return;4291unlink_or_warn(newpath);4292break;4293}4294if(errno != EEXIST)4295break;4296++nr;4297}4298}4299die_errno(_("unable to write file '%s' mode%o"), path, mode);4300}43014302static voidadd_conflicted_stages_file(struct apply_state *state,4303struct patch *patch)4304{4305int stage, namelen;4306unsigned ce_size, mode;4307struct cache_entry *ce;43084309if(!state->update_index)4310return;4311 namelen =strlen(patch->new_name);4312 ce_size =cache_entry_size(namelen);4313 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);43144315remove_file_from_cache(patch->new_name);4316for(stage =1; stage <4; stage++) {4317if(is_null_oid(&patch->threeway_stage[stage -1]))4318continue;4319 ce =xcalloc(1, ce_size);4320memcpy(ce->name, patch->new_name, namelen);4321 ce->ce_mode =create_ce_mode(mode);4322 ce->ce_flags =create_ce_flags(stage);4323 ce->ce_namelen = namelen;4324hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4325if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4326die(_("unable to add cache entry for%s"), patch->new_name);4327}4328}43294330static voidcreate_file(struct apply_state *state,struct patch *patch)4331{4332char*path = patch->new_name;4333unsigned mode = patch->new_mode;4334unsigned long size = patch->resultsize;4335char*buf = patch->result;43364337if(!mode)4338 mode = S_IFREG |0644;4339create_one_file(state, path, mode, buf, size);43404341if(patch->conflicted_threeway)4342add_conflicted_stages_file(state, patch);4343else4344add_index_file(state, path, mode, buf, size);4345}43464347/* phase zero is to remove, phase one is to create */4348static voidwrite_out_one_result(struct apply_state *state,4349struct patch *patch,4350int phase)4351{4352if(patch->is_delete >0) {4353if(phase ==0)4354remove_file(state, patch,1);4355return;4356}4357if(patch->is_new >0|| patch->is_copy) {4358if(phase ==1)4359create_file(state, patch);4360return;4361}4362/*4363 * Rename or modification boils down to the same4364 * thing: remove the old, write the new4365 */4366if(phase ==0)4367remove_file(state, patch, patch->is_rename);4368if(phase ==1)4369create_file(state, patch);4370}43714372static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4373{4374FILE*rej;4375char namebuf[PATH_MAX];4376struct fragment *frag;4377int cnt =0;4378struct strbuf sb = STRBUF_INIT;43794380for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4381if(!frag->rejected)4382continue;4383 cnt++;4384}43854386if(!cnt) {4387if(state->apply_verbosely)4388say_patch_name(stderr,4389_("Applied patch%scleanly."), patch);4390return0;4391}43924393/* This should not happen, because a removal patch that leaves4394 * contents are marked "rejected" at the patch level.4395 */4396if(!patch->new_name)4397die(_("internal error"));43984399/* Say this even without --verbose */4400strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4401"Applying patch %%swith%drejects...",4402 cnt),4403 cnt);4404say_patch_name(stderr, sb.buf, patch);4405strbuf_release(&sb);44064407 cnt =strlen(patch->new_name);4408if(ARRAY_SIZE(namebuf) <= cnt +5) {4409 cnt =ARRAY_SIZE(namebuf) -5;4410warning(_("truncating .rej filename to %.*s.rej"),4411 cnt -1, patch->new_name);4412}4413memcpy(namebuf, patch->new_name, cnt);4414memcpy(namebuf + cnt,".rej",5);44154416 rej =fopen(namebuf,"w");4417if(!rej)4418returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));44194420/* Normal git tools never deal with .rej, so do not pretend4421 * this is a git patch by saying --git or giving extended4422 * headers. While at it, maybe please "kompare" that wants4423 * the trailing TAB and some garbage at the end of line ;-).4424 */4425fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4426 patch->new_name, patch->new_name);4427for(cnt =1, frag = patch->fragments;4428 frag;4429 cnt++, frag = frag->next) {4430if(!frag->rejected) {4431fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4432continue;4433}4434fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4435fprintf(rej,"%.*s", frag->size, frag->patch);4436if(frag->patch[frag->size-1] !='\n')4437fputc('\n', rej);4438}4439fclose(rej);4440return-1;4441}44424443static intwrite_out_results(struct apply_state *state,struct patch *list)4444{4445int phase;4446int errs =0;4447struct patch *l;4448struct string_list cpath = STRING_LIST_INIT_DUP;44494450for(phase =0; phase <2; phase++) {4451 l = list;4452while(l) {4453if(l->rejected)4454 errs =1;4455else{4456write_out_one_result(state, l, phase);4457if(phase ==1) {4458if(write_out_one_reject(state, l))4459 errs =1;4460if(l->conflicted_threeway) {4461string_list_append(&cpath, l->new_name);4462 errs =1;4463}4464}4465}4466 l = l->next;4467}4468}44694470if(cpath.nr) {4471struct string_list_item *item;44724473string_list_sort(&cpath);4474for_each_string_list_item(item, &cpath)4475fprintf(stderr,"U%s\n", item->string);4476string_list_clear(&cpath,0);44774478rerere(0);4479}44804481return errs;4482}44834484static struct lock_file lock_file;44854486#define INACCURATE_EOF (1<<0)4487#define RECOUNT (1<<1)44884489static intapply_patch(struct apply_state *state,4490int fd,4491const char*filename,4492int options)4493{4494size_t offset;4495struct strbuf buf = STRBUF_INIT;/* owns the patch text */4496struct patch *list = NULL, **listp = &list;4497int skipped_patch =0;44984499 state->patch_input_file = filename;4500read_patch_file(&buf, fd);4501 offset =0;4502while(offset < buf.len) {4503struct patch *patch;4504int nr;45054506 patch =xcalloc(1,sizeof(*patch));4507 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4508 patch->recount = !!(options & RECOUNT);4509 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4510if(nr <0) {4511free_patch(patch);4512break;4513}4514if(state->apply_in_reverse)4515reverse_patches(patch);4516if(use_patch(state, patch)) {4517patch_stats(patch);4518*listp = patch;4519 listp = &patch->next;4520}4521else{4522if(state->apply_verbosely)4523say_patch_name(stderr,_("Skipped patch '%s'."), patch);4524free_patch(patch);4525 skipped_patch++;4526}4527 offset += nr;4528}45294530if(!list && !skipped_patch)4531die(_("unrecognized input"));45324533if(state->whitespace_error && (ws_error_action == die_on_ws_error))4534 state->apply =0;45354536 state->update_index = state->check_index && state->apply;4537if(state->update_index && newfd <0)4538 newfd =hold_locked_index(&lock_file,1);45394540if(state->check_index) {4541if(read_cache() <0)4542die(_("unable to read index file"));4543}45444545if((state->check || state->apply) &&4546check_patch_list(state, list) <0&&4547!state->apply_with_reject)4548exit(1);45494550if(state->apply &&write_out_results(state, list)) {4551if(state->apply_with_reject)4552exit(1);4553/* with --3way, we still need to write the index out */4554return1;4555}45564557if(state->fake_ancestor)4558build_fake_ancestor(list, state->fake_ancestor);45594560if(state->diffstat)4561stat_patch_list(list);45624563if(state->numstat)4564numstat_patch_list(state, list);45654566if(state->summary)4567summary_patch_list(list);45684569free_patch_list(list);4570strbuf_release(&buf);4571string_list_clear(&fn_table,0);4572return0;4573}45744575static voidgit_apply_config(void)4576{4577git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4578git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4579git_config(git_default_config, NULL);4580}45814582static intoption_parse_exclude(const struct option *opt,4583const char*arg,int unset)4584{4585struct apply_state *state = opt->value;4586add_name_limit(state, arg,1);4587return0;4588}45894590static intoption_parse_include(const struct option *opt,4591const char*arg,int unset)4592{4593struct apply_state *state = opt->value;4594add_name_limit(state, arg,0);4595 state->has_include =1;4596return0;4597}45984599static intoption_parse_p(const struct option *opt,4600const char*arg,4601int unset)4602{4603struct apply_state *state = opt->value;4604 state->p_value =atoi(arg);4605 state->p_value_known =1;4606return0;4607}46084609static intoption_parse_space_change(const struct option *opt,4610const char*arg,int unset)4611{4612if(unset)4613 ws_ignore_action = ignore_ws_none;4614else4615 ws_ignore_action = ignore_ws_change;4616return0;4617}46184619static intoption_parse_whitespace(const struct option *opt,4620const char*arg,int unset)4621{4622struct apply_state *state = opt->value;46234624 state->whitespace_option = arg;4625parse_whitespace_option(arg);4626return0;4627}46284629static intoption_parse_directory(const struct option *opt,4630const char*arg,int unset)4631{4632struct apply_state *state = opt->value;4633strbuf_reset(&state->root);4634strbuf_addstr(&state->root, arg);4635strbuf_complete(&state->root,'/');4636return0;4637}46384639static voidinit_apply_state(struct apply_state *state,const char*prefix)4640{4641memset(state,0,sizeof(*state));4642 state->prefix = prefix;4643 state->prefix_length = state->prefix ?strlen(state->prefix) :0;4644 state->apply =1;4645 state->line_termination ='\n';4646 state->p_value =1;4647 state->p_context = UINT_MAX;4648strbuf_init(&state->root,0);46494650git_apply_config();4651if(apply_default_whitespace)4652parse_whitespace_option(apply_default_whitespace);4653if(apply_default_ignorewhitespace)4654parse_ignorewhitespace_option(apply_default_ignorewhitespace);4655}46564657static voidclear_apply_state(struct apply_state *state)4658{4659string_list_clear(&state->limit_by_name,0);4660strbuf_release(&state->root);4661}46624663intcmd_apply(int argc,const char**argv,const char*prefix)4664{4665int i;4666int errs =0;4667int is_not_gitdir = !startup_info->have_repository;4668int force_apply =0;4669int options =0;4670int read_stdin =1;4671struct apply_state state;46724673struct option builtin_apply_options[] = {4674{ OPTION_CALLBACK,0,"exclude", &state,N_("path"),4675N_("don't apply changes matching the given path"),46760, option_parse_exclude },4677{ OPTION_CALLBACK,0,"include", &state,N_("path"),4678N_("apply changes matching the given path"),46790, option_parse_include },4680{ OPTION_CALLBACK,'p', NULL, &state,N_("num"),4681N_("remove <num> leading slashes from traditional diff paths"),46820, option_parse_p },4683OPT_BOOL(0,"no-add", &state.no_add,4684N_("ignore additions made by the patch")),4685OPT_BOOL(0,"stat", &state.diffstat,4686N_("instead of applying the patch, output diffstat for the input")),4687OPT_NOOP_NOARG(0,"allow-binary-replacement"),4688OPT_NOOP_NOARG(0,"binary"),4689OPT_BOOL(0,"numstat", &state.numstat,4690N_("show number of added and deleted lines in decimal notation")),4691OPT_BOOL(0,"summary", &state.summary,4692N_("instead of applying the patch, output a summary for the input")),4693OPT_BOOL(0,"check", &state.check,4694N_("instead of applying the patch, see if the patch is applicable")),4695OPT_BOOL(0,"index", &state.check_index,4696N_("make sure the patch is applicable to the current index")),4697OPT_BOOL(0,"cached", &state.cached,4698N_("apply a patch without touching the working tree")),4699OPT_BOOL(0,"unsafe-paths", &state.unsafe_paths,4700N_("accept a patch that touches outside the working area")),4701OPT_BOOL(0,"apply", &force_apply,4702N_("also apply the patch (use with --stat/--summary/--check)")),4703OPT_BOOL('3',"3way", &state.threeway,4704N_("attempt three-way merge if a patch does not apply")),4705OPT_FILENAME(0,"build-fake-ancestor", &state.fake_ancestor,4706N_("build a temporary index based on embedded index information")),4707/* Think twice before adding "--nul" synonym to this */4708OPT_SET_INT('z', NULL, &state.line_termination,4709N_("paths are separated with NUL character"),'\0'),4710OPT_INTEGER('C', NULL, &state.p_context,4711N_("ensure at least <n> lines of context match")),4712{ OPTION_CALLBACK,0,"whitespace", &state,N_("action"),4713N_("detect new or modified lines that have whitespace errors"),47140, option_parse_whitespace },4715{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,4716N_("ignore changes in whitespace when finding context"),4717 PARSE_OPT_NOARG, option_parse_space_change },4718{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,4719N_("ignore changes in whitespace when finding context"),4720 PARSE_OPT_NOARG, option_parse_space_change },4721OPT_BOOL('R',"reverse", &state.apply_in_reverse,4722N_("apply the patch in reverse")),4723OPT_BOOL(0,"unidiff-zero", &state.unidiff_zero,4724N_("don't expect at least one line of context")),4725OPT_BOOL(0,"reject", &state.apply_with_reject,4726N_("leave the rejected hunks in corresponding *.rej files")),4727OPT_BOOL(0,"allow-overlap", &state.allow_overlap,4728N_("allow overlapping hunks")),4729OPT__VERBOSE(&state.apply_verbosely,N_("be verbose")),4730OPT_BIT(0,"inaccurate-eof", &options,4731N_("tolerate incorrectly detected missing new-line at the end of file"),4732 INACCURATE_EOF),4733OPT_BIT(0,"recount", &options,4734N_("do not trust the line counts in the hunk headers"),4735 RECOUNT),4736{ OPTION_CALLBACK,0,"directory", &state,N_("root"),4737N_("prepend <root> to all filenames"),47380, option_parse_directory },4739OPT_END()4740};47414742init_apply_state(&state, prefix);47434744 argc =parse_options(argc, argv, state.prefix, builtin_apply_options,4745 apply_usage,0);47464747if(state.apply_with_reject && state.threeway)4748die("--reject and --3way cannot be used together.");4749if(state.cached && state.threeway)4750die("--cached and --3way cannot be used together.");4751if(state.threeway) {4752if(is_not_gitdir)4753die(_("--3way outside a repository"));4754 state.check_index =1;4755}4756if(state.apply_with_reject)4757 state.apply = state.apply_verbosely =1;4758if(!force_apply && (state.diffstat || state.numstat || state.summary || state.check || state.fake_ancestor))4759 state.apply =0;4760if(state.check_index && is_not_gitdir)4761die(_("--index outside a repository"));4762if(state.cached) {4763if(is_not_gitdir)4764die(_("--cached outside a repository"));4765 state.check_index =1;4766}4767if(state.check_index)4768 state.unsafe_paths =0;47694770for(i =0; i < argc; i++) {4771const char*arg = argv[i];4772int fd;47734774if(!strcmp(arg,"-")) {4775 errs |=apply_patch(&state,0,"<stdin>", options);4776 read_stdin =0;4777continue;4778}else if(0< state.prefix_length)4779 arg =prefix_filename(state.prefix,4780 state.prefix_length,4781 arg);47824783 fd =open(arg, O_RDONLY);4784if(fd <0)4785die_errno(_("can't open patch '%s'"), arg);4786 read_stdin =0;4787set_default_whitespace_mode(&state);4788 errs |=apply_patch(&state, fd, arg, options);4789close(fd);4790}4791set_default_whitespace_mode(&state);4792if(read_stdin)4793 errs |=apply_patch(&state,0,"<stdin>", options);4794if(state.whitespace_error) {4795if(squelch_whitespace_errors &&4796 squelch_whitespace_errors < state.whitespace_error) {4797int squelched =4798 state.whitespace_error - squelch_whitespace_errors;4799warning(Q_("squelched%dwhitespace error",4800"squelched%dwhitespace errors",4801 squelched),4802 squelched);4803}4804if(ws_error_action == die_on_ws_error)4805die(Q_("%dline adds whitespace errors.",4806"%dlines add whitespace errors.",4807 state.whitespace_error),4808 state.whitespace_error);4809if(applied_after_fixing_ws && state.apply)4810warning("%dline%sapplied after"4811" fixing whitespace errors.",4812 applied_after_fixing_ws,4813 applied_after_fixing_ws ==1?"":"s");4814else if(state.whitespace_error)4815warning(Q_("%dline adds whitespace errors.",4816"%dlines add whitespace errors.",4817 state.whitespace_error),4818 state.whitespace_error);4819}48204821if(state.update_index) {4822if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK))4823die(_("Unable to write new index file"));4824}48254826clear_apply_state(&state);48274828return!!errs;4829}