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; 54unsigned int p_context; 55 56/* Exclude and include path parameters */ 57struct string_list limit_by_name; 58}; 59 60static int newfd = -1; 61 62static int state_p_value =1; 63static int p_value_known; 64 65static const char*const apply_usage[] = { 66N_("git apply [<options>] [<patch>...]"), 67 NULL 68}; 69 70static enum ws_error_action { 71 nowarn_ws_error, 72 warn_on_ws_error, 73 die_on_ws_error, 74 correct_ws_error 75} ws_error_action = warn_on_ws_error; 76static int whitespace_error; 77static int squelch_whitespace_errors =5; 78static int applied_after_fixing_ws; 79 80static enum ws_ignore { 81 ignore_ws_none, 82 ignore_ws_change 83} ws_ignore_action = ignore_ws_none; 84 85 86static struct strbuf root = STRBUF_INIT; 87 88static voidparse_whitespace_option(const char*option) 89{ 90if(!option) { 91 ws_error_action = warn_on_ws_error; 92return; 93} 94if(!strcmp(option,"warn")) { 95 ws_error_action = warn_on_ws_error; 96return; 97} 98if(!strcmp(option,"nowarn")) { 99 ws_error_action = nowarn_ws_error; 100return; 101} 102if(!strcmp(option,"error")) { 103 ws_error_action = die_on_ws_error; 104return; 105} 106if(!strcmp(option,"error-all")) { 107 ws_error_action = die_on_ws_error; 108 squelch_whitespace_errors =0; 109return; 110} 111if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 112 ws_error_action = correct_ws_error; 113return; 114} 115die(_("unrecognized whitespace option '%s'"), option); 116} 117 118static voidparse_ignorewhitespace_option(const char*option) 119{ 120if(!option || !strcmp(option,"no") || 121!strcmp(option,"false") || !strcmp(option,"never") || 122!strcmp(option,"none")) { 123 ws_ignore_action = ignore_ws_none; 124return; 125} 126if(!strcmp(option,"change")) { 127 ws_ignore_action = ignore_ws_change; 128return; 129} 130die(_("unrecognized whitespace ignore option '%s'"), option); 131} 132 133static voidset_default_whitespace_mode(struct apply_state *state, 134const char*whitespace_option) 135{ 136if(!whitespace_option && !apply_default_whitespace) 137 ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 138} 139 140/* 141 * For "diff-stat" like behaviour, we keep track of the biggest change 142 * we've seen, and the longest filename. That allows us to do simple 143 * scaling. 144 */ 145static int max_change, max_len; 146 147/* 148 * Various "current state", notably line numbers and what 149 * file (and how) we're patching right now.. The "is_xxxx" 150 * things are flags, where -1 means "don't know yet". 151 */ 152static int state_linenr =1; 153 154/* 155 * This represents one "hunk" from a patch, starting with 156 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 157 * patch text is pointed at by patch, and its byte length 158 * is stored in size. leading and trailing are the number 159 * of context lines. 160 */ 161struct fragment { 162unsigned long leading, trailing; 163unsigned long oldpos, oldlines; 164unsigned long newpos, newlines; 165/* 166 * 'patch' is usually borrowed from buf in apply_patch(), 167 * but some codepaths store an allocated buffer. 168 */ 169const char*patch; 170unsigned free_patch:1, 171 rejected:1; 172int size; 173int linenr; 174struct fragment *next; 175}; 176 177/* 178 * When dealing with a binary patch, we reuse "leading" field 179 * to store the type of the binary hunk, either deflated "delta" 180 * or deflated "literal". 181 */ 182#define binary_patch_method leading 183#define BINARY_DELTA_DEFLATED 1 184#define BINARY_LITERAL_DEFLATED 2 185 186/* 187 * This represents a "patch" to a file, both metainfo changes 188 * such as creation/deletion, filemode and content changes represented 189 * as a series of fragments. 190 */ 191struct patch { 192char*new_name, *old_name, *def_name; 193unsigned int old_mode, new_mode; 194int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 195int rejected; 196unsigned ws_rule; 197int lines_added, lines_deleted; 198int score; 199unsigned int is_toplevel_relative:1; 200unsigned int inaccurate_eof:1; 201unsigned int is_binary:1; 202unsigned int is_copy:1; 203unsigned int is_rename:1; 204unsigned int recount:1; 205unsigned int conflicted_threeway:1; 206unsigned int direct_to_threeway:1; 207struct fragment *fragments; 208char*result; 209size_t resultsize; 210char old_sha1_prefix[41]; 211char new_sha1_prefix[41]; 212struct patch *next; 213 214/* three-way fallback result */ 215struct object_id threeway_stage[3]; 216}; 217 218static voidfree_fragment_list(struct fragment *list) 219{ 220while(list) { 221struct fragment *next = list->next; 222if(list->free_patch) 223free((char*)list->patch); 224free(list); 225 list = next; 226} 227} 228 229static voidfree_patch(struct patch *patch) 230{ 231free_fragment_list(patch->fragments); 232free(patch->def_name); 233free(patch->old_name); 234free(patch->new_name); 235free(patch->result); 236free(patch); 237} 238 239static voidfree_patch_list(struct patch *list) 240{ 241while(list) { 242struct patch *next = list->next; 243free_patch(list); 244 list = next; 245} 246} 247 248/* 249 * A line in a file, len-bytes long (includes the terminating LF, 250 * except for an incomplete line at the end if the file ends with 251 * one), and its contents hashes to 'hash'. 252 */ 253struct line { 254size_t len; 255unsigned hash :24; 256unsigned flag :8; 257#define LINE_COMMON 1 258#define LINE_PATCHED 2 259}; 260 261/* 262 * This represents a "file", which is an array of "lines". 263 */ 264struct image { 265char*buf; 266size_t len; 267size_t nr; 268size_t alloc; 269struct line *line_allocated; 270struct line *line; 271}; 272 273/* 274 * Records filenames that have been touched, in order to handle 275 * the case where more than one patches touch the same file. 276 */ 277 278static struct string_list fn_table; 279 280static uint32_thash_line(const char*cp,size_t len) 281{ 282size_t i; 283uint32_t h; 284for(i =0, h =0; i < len; i++) { 285if(!isspace(cp[i])) { 286 h = h *3+ (cp[i] &0xff); 287} 288} 289return h; 290} 291 292/* 293 * Compare lines s1 of length n1 and s2 of length n2, ignoring 294 * whitespace difference. Returns 1 if they match, 0 otherwise 295 */ 296static intfuzzy_matchlines(const char*s1,size_t n1, 297const char*s2,size_t n2) 298{ 299const char*last1 = s1 + n1 -1; 300const char*last2 = s2 + n2 -1; 301int result =0; 302 303/* ignore line endings */ 304while((*last1 =='\r') || (*last1 =='\n')) 305 last1--; 306while((*last2 =='\r') || (*last2 =='\n')) 307 last2--; 308 309/* skip leading whitespaces, if both begin with whitespace */ 310if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 311while(isspace(*s1) && (s1 <= last1)) 312 s1++; 313while(isspace(*s2) && (s2 <= last2)) 314 s2++; 315} 316/* early return if both lines are empty */ 317if((s1 > last1) && (s2 > last2)) 318return1; 319while(!result) { 320 result = *s1++ - *s2++; 321/* 322 * Skip whitespace inside. We check for whitespace on 323 * both buffers because we don't want "a b" to match 324 * "ab" 325 */ 326if(isspace(*s1) &&isspace(*s2)) { 327while(isspace(*s1) && s1 <= last1) 328 s1++; 329while(isspace(*s2) && s2 <= last2) 330 s2++; 331} 332/* 333 * If we reached the end on one side only, 334 * lines don't match 335 */ 336if( 337((s2 > last2) && (s1 <= last1)) || 338((s1 > last1) && (s2 <= last2))) 339return0; 340if((s1 > last1) && (s2 > last2)) 341break; 342} 343 344return!result; 345} 346 347static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 348{ 349ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 350 img->line_allocated[img->nr].len = len; 351 img->line_allocated[img->nr].hash =hash_line(bol, len); 352 img->line_allocated[img->nr].flag = flag; 353 img->nr++; 354} 355 356/* 357 * "buf" has the file contents to be patched (read from various sources). 358 * attach it to "image" and add line-based index to it. 359 * "image" now owns the "buf". 360 */ 361static voidprepare_image(struct image *image,char*buf,size_t len, 362int prepare_linetable) 363{ 364const char*cp, *ep; 365 366memset(image,0,sizeof(*image)); 367 image->buf = buf; 368 image->len = len; 369 370if(!prepare_linetable) 371return; 372 373 ep = image->buf + image->len; 374 cp = image->buf; 375while(cp < ep) { 376const char*next; 377for(next = cp; next < ep && *next !='\n'; next++) 378; 379if(next < ep) 380 next++; 381add_line_info(image, cp, next - cp,0); 382 cp = next; 383} 384 image->line = image->line_allocated; 385} 386 387static voidclear_image(struct image *image) 388{ 389free(image->buf); 390free(image->line_allocated); 391memset(image,0,sizeof(*image)); 392} 393 394/* fmt must contain _one_ %s and no other substitution */ 395static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 396{ 397struct strbuf sb = STRBUF_INIT; 398 399if(patch->old_name && patch->new_name && 400strcmp(patch->old_name, patch->new_name)) { 401quote_c_style(patch->old_name, &sb, NULL,0); 402strbuf_addstr(&sb," => "); 403quote_c_style(patch->new_name, &sb, NULL,0); 404}else{ 405const char*n = patch->new_name; 406if(!n) 407 n = patch->old_name; 408quote_c_style(n, &sb, NULL,0); 409} 410fprintf(output, fmt, sb.buf); 411fputc('\n', output); 412strbuf_release(&sb); 413} 414 415#define SLOP (16) 416 417static voidread_patch_file(struct strbuf *sb,int fd) 418{ 419if(strbuf_read(sb, fd,0) <0) 420die_errno("git apply: failed to read"); 421 422/* 423 * Make sure that we have some slop in the buffer 424 * so that we can do speculative "memcmp" etc, and 425 * see to it that it is NUL-filled. 426 */ 427strbuf_grow(sb, SLOP); 428memset(sb->buf + sb->len,0, SLOP); 429} 430 431static unsigned longlinelen(const char*buffer,unsigned long size) 432{ 433unsigned long len =0; 434while(size--) { 435 len++; 436if(*buffer++ =='\n') 437break; 438} 439return len; 440} 441 442static intis_dev_null(const char*str) 443{ 444returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 445} 446 447#define TERM_SPACE 1 448#define TERM_TAB 2 449 450static intname_terminate(const char*name,int namelen,int c,int terminate) 451{ 452if(c ==' '&& !(terminate & TERM_SPACE)) 453return0; 454if(c =='\t'&& !(terminate & TERM_TAB)) 455return0; 456 457return1; 458} 459 460/* remove double slashes to make --index work with such filenames */ 461static char*squash_slash(char*name) 462{ 463int i =0, j =0; 464 465if(!name) 466return NULL; 467 468while(name[i]) { 469if((name[j++] = name[i++]) =='/') 470while(name[i] =='/') 471 i++; 472} 473 name[j] ='\0'; 474return name; 475} 476 477static char*find_name_gnu(const char*line,const char*def,int p_value) 478{ 479struct strbuf name = STRBUF_INIT; 480char*cp; 481 482/* 483 * Proposed "new-style" GNU patch/diff format; see 484 * http://marc.info/?l=git&m=112927316408690&w=2 485 */ 486if(unquote_c_style(&name, line, NULL)) { 487strbuf_release(&name); 488return NULL; 489} 490 491for(cp = name.buf; p_value; p_value--) { 492 cp =strchr(cp,'/'); 493if(!cp) { 494strbuf_release(&name); 495return NULL; 496} 497 cp++; 498} 499 500strbuf_remove(&name,0, cp - name.buf); 501if(root.len) 502strbuf_insert(&name,0, root.buf, root.len); 503returnsquash_slash(strbuf_detach(&name, NULL)); 504} 505 506static size_tsane_tz_len(const char*line,size_t len) 507{ 508const char*tz, *p; 509 510if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 511return0; 512 tz = line + len -strlen(" +0500"); 513 514if(tz[1] !='+'&& tz[1] !='-') 515return0; 516 517for(p = tz +2; p != line + len; p++) 518if(!isdigit(*p)) 519return0; 520 521return line + len - tz; 522} 523 524static size_ttz_with_colon_len(const char*line,size_t len) 525{ 526const char*tz, *p; 527 528if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 529return0; 530 tz = line + len -strlen(" +08:00"); 531 532if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 533return0; 534 p = tz +2; 535if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 536!isdigit(*p++) || !isdigit(*p++)) 537return0; 538 539return line + len - tz; 540} 541 542static size_tdate_len(const char*line,size_t len) 543{ 544const char*date, *p; 545 546if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 547return0; 548 p = date = line + len -strlen("72-02-05"); 549 550if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 551!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 552!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 553return0; 554 555if(date - line >=strlen("19") && 556isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 557 date -=strlen("19"); 558 559return line + len - date; 560} 561 562static size_tshort_time_len(const char*line,size_t len) 563{ 564const char*time, *p; 565 566if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 567return0; 568 p = time = line + len -strlen(" 07:01:32"); 569 570/* Permit 1-digit hours? */ 571if(*p++ !=' '|| 572!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 573!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 574!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 575return0; 576 577return line + len - time; 578} 579 580static size_tfractional_time_len(const char*line,size_t len) 581{ 582const char*p; 583size_t n; 584 585/* Expected format: 19:41:17.620000023 */ 586if(!len || !isdigit(line[len -1])) 587return0; 588 p = line + len -1; 589 590/* Fractional seconds. */ 591while(p > line &&isdigit(*p)) 592 p--; 593if(*p !='.') 594return0; 595 596/* Hours, minutes, and whole seconds. */ 597 n =short_time_len(line, p - line); 598if(!n) 599return0; 600 601return line + len - p + n; 602} 603 604static size_ttrailing_spaces_len(const char*line,size_t len) 605{ 606const char*p; 607 608/* Expected format: ' ' x (1 or more) */ 609if(!len || line[len -1] !=' ') 610return0; 611 612 p = line + len; 613while(p != line) { 614 p--; 615if(*p !=' ') 616return line + len - (p +1); 617} 618 619/* All spaces! */ 620return len; 621} 622 623static size_tdiff_timestamp_len(const char*line,size_t len) 624{ 625const char*end = line + len; 626size_t n; 627 628/* 629 * Posix: 2010-07-05 19:41:17 630 * GNU: 2010-07-05 19:41:17.620000023 -0500 631 */ 632 633if(!isdigit(end[-1])) 634return0; 635 636 n =sane_tz_len(line, end - line); 637if(!n) 638 n =tz_with_colon_len(line, end - line); 639 end -= n; 640 641 n =short_time_len(line, end - line); 642if(!n) 643 n =fractional_time_len(line, end - line); 644 end -= n; 645 646 n =date_len(line, end - line); 647if(!n)/* No date. Too bad. */ 648return0; 649 end -= n; 650 651if(end == line)/* No space before date. */ 652return0; 653if(end[-1] =='\t') {/* Success! */ 654 end--; 655return line + len - end; 656} 657if(end[-1] !=' ')/* No space before date. */ 658return0; 659 660/* Whitespace damage. */ 661 end -=trailing_spaces_len(line, end - line); 662return line + len - end; 663} 664 665static char*find_name_common(const char*line,const char*def, 666int p_value,const char*end,int terminate) 667{ 668int len; 669const char*start = NULL; 670 671if(p_value ==0) 672 start = line; 673while(line != end) { 674char c = *line; 675 676if(!end &&isspace(c)) { 677if(c =='\n') 678break; 679if(name_terminate(start, line-start, c, terminate)) 680break; 681} 682 line++; 683if(c =='/'&& !--p_value) 684 start = line; 685} 686if(!start) 687returnsquash_slash(xstrdup_or_null(def)); 688 len = line - start; 689if(!len) 690returnsquash_slash(xstrdup_or_null(def)); 691 692/* 693 * Generally we prefer the shorter name, especially 694 * if the other one is just a variation of that with 695 * something else tacked on to the end (ie "file.orig" 696 * or "file~"). 697 */ 698if(def) { 699int deflen =strlen(def); 700if(deflen < len && !strncmp(start, def, deflen)) 701returnsquash_slash(xstrdup(def)); 702} 703 704if(root.len) { 705char*ret =xstrfmt("%s%.*s", root.buf, len, start); 706returnsquash_slash(ret); 707} 708 709returnsquash_slash(xmemdupz(start, len)); 710} 711 712static char*find_name(const char*line,char*def,int p_value,int terminate) 713{ 714if(*line =='"') { 715char*name =find_name_gnu(line, def, p_value); 716if(name) 717return name; 718} 719 720returnfind_name_common(line, def, p_value, NULL, terminate); 721} 722 723static char*find_name_traditional(const char*line,char*def,int p_value) 724{ 725size_t len; 726size_t date_len; 727 728if(*line =='"') { 729char*name =find_name_gnu(line, def, p_value); 730if(name) 731return name; 732} 733 734 len =strchrnul(line,'\n') - line; 735 date_len =diff_timestamp_len(line, len); 736if(!date_len) 737returnfind_name_common(line, def, p_value, NULL, TERM_TAB); 738 len -= date_len; 739 740returnfind_name_common(line, def, p_value, line + len,0); 741} 742 743static intcount_slashes(const char*cp) 744{ 745int cnt =0; 746char ch; 747 748while((ch = *cp++)) 749if(ch =='/') 750 cnt++; 751return cnt; 752} 753 754/* 755 * Given the string after "--- " or "+++ ", guess the appropriate 756 * p_value for the given patch. 757 */ 758static intguess_p_value(struct apply_state *state,const char*nameline) 759{ 760char*name, *cp; 761int val = -1; 762 763if(is_dev_null(nameline)) 764return-1; 765 name =find_name_traditional(nameline, NULL,0); 766if(!name) 767return-1; 768 cp =strchr(name,'/'); 769if(!cp) 770 val =0; 771else if(state->prefix) { 772/* 773 * Does it begin with "a/$our-prefix" and such? Then this is 774 * very likely to apply to our directory. 775 */ 776if(!strncmp(name, state->prefix, state->prefix_length)) 777 val =count_slashes(state->prefix); 778else{ 779 cp++; 780if(!strncmp(cp, state->prefix, state->prefix_length)) 781 val =count_slashes(state->prefix) +1; 782} 783} 784free(name); 785return val; 786} 787 788/* 789 * Does the ---/+++ line have the POSIX timestamp after the last HT? 790 * GNU diff puts epoch there to signal a creation/deletion event. Is 791 * this such a timestamp? 792 */ 793static inthas_epoch_timestamp(const char*nameline) 794{ 795/* 796 * We are only interested in epoch timestamp; any non-zero 797 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 798 * For the same reason, the date must be either 1969-12-31 or 799 * 1970-01-01, and the seconds part must be "00". 800 */ 801const char stamp_regexp[] = 802"^(1969-12-31|1970-01-01)" 803" " 804"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 805" " 806"([-+][0-2][0-9]:?[0-5][0-9])\n"; 807const char*timestamp = NULL, *cp, *colon; 808static regex_t *stamp; 809 regmatch_t m[10]; 810int zoneoffset; 811int hourminute; 812int status; 813 814for(cp = nameline; *cp !='\n'; cp++) { 815if(*cp =='\t') 816 timestamp = cp +1; 817} 818if(!timestamp) 819return0; 820if(!stamp) { 821 stamp =xmalloc(sizeof(*stamp)); 822if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 823warning(_("Cannot prepare timestamp regexp%s"), 824 stamp_regexp); 825return0; 826} 827} 828 829 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 830if(status) { 831if(status != REG_NOMATCH) 832warning(_("regexec returned%dfor input:%s"), 833 status, timestamp); 834return0; 835} 836 837 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 838if(*colon ==':') 839 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 840else 841 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 842if(timestamp[m[3].rm_so] =='-') 843 zoneoffset = -zoneoffset; 844 845/* 846 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 847 * (west of GMT) or 1970-01-01 (east of GMT) 848 */ 849if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 850(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 851return0; 852 853 hourminute = (strtol(timestamp +11, NULL,10) *60+ 854strtol(timestamp +14, NULL,10) - 855 zoneoffset); 856 857return((zoneoffset <0&& hourminute ==1440) || 858(0<= zoneoffset && !hourminute)); 859} 860 861/* 862 * Get the name etc info from the ---/+++ lines of a traditional patch header 863 * 864 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 865 * files, we can happily check the index for a match, but for creating a 866 * new file we should try to match whatever "patch" does. I have no idea. 867 */ 868static voidparse_traditional_patch(struct apply_state *state, 869const char*first, 870const char*second, 871struct patch *patch) 872{ 873char*name; 874 875 first +=4;/* skip "--- " */ 876 second +=4;/* skip "+++ " */ 877if(!p_value_known) { 878int p, q; 879 p =guess_p_value(state, first); 880 q =guess_p_value(state, second); 881if(p <0) p = q; 882if(0<= p && p == q) { 883 state_p_value = p; 884 p_value_known =1; 885} 886} 887if(is_dev_null(first)) { 888 patch->is_new =1; 889 patch->is_delete =0; 890 name =find_name_traditional(second, NULL, state_p_value); 891 patch->new_name = name; 892}else if(is_dev_null(second)) { 893 patch->is_new =0; 894 patch->is_delete =1; 895 name =find_name_traditional(first, NULL, state_p_value); 896 patch->old_name = name; 897}else{ 898char*first_name; 899 first_name =find_name_traditional(first, NULL, state_p_value); 900 name =find_name_traditional(second, first_name, state_p_value); 901free(first_name); 902if(has_epoch_timestamp(first)) { 903 patch->is_new =1; 904 patch->is_delete =0; 905 patch->new_name = name; 906}else if(has_epoch_timestamp(second)) { 907 patch->is_new =0; 908 patch->is_delete =1; 909 patch->old_name = name; 910}else{ 911 patch->old_name = name; 912 patch->new_name =xstrdup_or_null(name); 913} 914} 915if(!name) 916die(_("unable to find filename in patch at line%d"), state_linenr); 917} 918 919static intgitdiff_hdrend(const char*line,struct patch *patch) 920{ 921return-1; 922} 923 924/* 925 * We're anal about diff header consistency, to make 926 * sure that we don't end up having strange ambiguous 927 * patches floating around. 928 * 929 * As a result, gitdiff_{old|new}name() will check 930 * their names against any previous information, just 931 * to make sure.. 932 */ 933#define DIFF_OLD_NAME 0 934#define DIFF_NEW_NAME 1 935 936static voidgitdiff_verify_name(const char*line,int isnull,char**name,int side) 937{ 938if(!*name && !isnull) { 939*name =find_name(line, NULL, state_p_value, TERM_TAB); 940return; 941} 942 943if(*name) { 944int len =strlen(*name); 945char*another; 946if(isnull) 947die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 948*name, state_linenr); 949 another =find_name(line, NULL, state_p_value, TERM_TAB); 950if(!another ||memcmp(another, *name, len +1)) 951die((side == DIFF_NEW_NAME) ? 952_("git apply: bad git-diff - inconsistent new filename on line%d") : 953_("git apply: bad git-diff - inconsistent old filename on line%d"), state_linenr); 954free(another); 955}else{ 956/* expect "/dev/null" */ 957if(memcmp("/dev/null", line,9) || line[9] !='\n') 958die(_("git apply: bad git-diff - expected /dev/null on line%d"), state_linenr); 959} 960} 961 962static intgitdiff_oldname(const char*line,struct patch *patch) 963{ 964gitdiff_verify_name(line, patch->is_new, &patch->old_name, 965 DIFF_OLD_NAME); 966return0; 967} 968 969static intgitdiff_newname(const char*line,struct patch *patch) 970{ 971gitdiff_verify_name(line, patch->is_delete, &patch->new_name, 972 DIFF_NEW_NAME); 973return0; 974} 975 976static intgitdiff_oldmode(const char*line,struct patch *patch) 977{ 978 patch->old_mode =strtoul(line, NULL,8); 979return0; 980} 981 982static intgitdiff_newmode(const char*line,struct patch *patch) 983{ 984 patch->new_mode =strtoul(line, NULL,8); 985return0; 986} 987 988static intgitdiff_delete(const char*line,struct patch *patch) 989{ 990 patch->is_delete =1; 991free(patch->old_name); 992 patch->old_name =xstrdup_or_null(patch->def_name); 993returngitdiff_oldmode(line, patch); 994} 995 996static intgitdiff_newfile(const char*line,struct patch *patch) 997{ 998 patch->is_new =1; 999free(patch->new_name);1000 patch->new_name =xstrdup_or_null(patch->def_name);1001returngitdiff_newmode(line, patch);1002}10031004static intgitdiff_copysrc(const char*line,struct patch *patch)1005{1006 patch->is_copy =1;1007free(patch->old_name);1008 patch->old_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1009return0;1010}10111012static intgitdiff_copydst(const char*line,struct patch *patch)1013{1014 patch->is_copy =1;1015free(patch->new_name);1016 patch->new_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1017return0;1018}10191020static intgitdiff_renamesrc(const char*line,struct patch *patch)1021{1022 patch->is_rename =1;1023free(patch->old_name);1024 patch->old_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1025return0;1026}10271028static intgitdiff_renamedst(const char*line,struct patch *patch)1029{1030 patch->is_rename =1;1031free(patch->new_name);1032 patch->new_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1033return0;1034}10351036static intgitdiff_similarity(const char*line,struct patch *patch)1037{1038unsigned long val =strtoul(line, NULL,10);1039if(val <=100)1040 patch->score = val;1041return0;1042}10431044static intgitdiff_dissimilarity(const char*line,struct patch *patch)1045{1046unsigned long val =strtoul(line, NULL,10);1047if(val <=100)1048 patch->score = val;1049return0;1050}10511052static intgitdiff_index(const char*line,struct patch *patch)1053{1054/*1055 * index line is N hexadecimal, "..", N hexadecimal,1056 * and optional space with octal mode.1057 */1058const char*ptr, *eol;1059int len;10601061 ptr =strchr(line,'.');1062if(!ptr || ptr[1] !='.'||40< ptr - line)1063return0;1064 len = ptr - line;1065memcpy(patch->old_sha1_prefix, line, len);1066 patch->old_sha1_prefix[len] =0;10671068 line = ptr +2;1069 ptr =strchr(line,' ');1070 eol =strchrnul(line,'\n');10711072if(!ptr || eol < ptr)1073 ptr = eol;1074 len = ptr - line;10751076if(40< len)1077return0;1078memcpy(patch->new_sha1_prefix, line, len);1079 patch->new_sha1_prefix[len] =0;1080if(*ptr ==' ')1081 patch->old_mode =strtoul(ptr+1, NULL,8);1082return0;1083}10841085/*1086 * This is normal for a diff that doesn't change anything: we'll fall through1087 * into the next diff. Tell the parser to break out.1088 */1089static intgitdiff_unrecognized(const char*line,struct patch *patch)1090{1091return-1;1092}10931094/*1095 * Skip p_value leading components from "line"; as we do not accept1096 * absolute paths, return NULL in that case.1097 */1098static const char*skip_tree_prefix(const char*line,int llen)1099{1100int nslash;1101int i;11021103if(!state_p_value)1104return(llen && line[0] =='/') ? NULL : line;11051106 nslash = state_p_value;1107for(i =0; i < llen; i++) {1108int ch = line[i];1109if(ch =='/'&& --nslash <=0)1110return(i ==0) ? NULL : &line[i +1];1111}1112return NULL;1113}11141115/*1116 * This is to extract the same name that appears on "diff --git"1117 * line. We do not find and return anything if it is a rename1118 * patch, and it is OK because we will find the name elsewhere.1119 * We need to reliably find name only when it is mode-change only,1120 * creation or deletion of an empty file. In any of these cases,1121 * both sides are the same name under a/ and b/ respectively.1122 */1123static char*git_header_name(const char*line,int llen)1124{1125const char*name;1126const char*second = NULL;1127size_t len, line_len;11281129 line +=strlen("diff --git ");1130 llen -=strlen("diff --git ");11311132if(*line =='"') {1133const char*cp;1134struct strbuf first = STRBUF_INIT;1135struct strbuf sp = STRBUF_INIT;11361137if(unquote_c_style(&first, line, &second))1138goto free_and_fail1;11391140/* strip the a/b prefix including trailing slash */1141 cp =skip_tree_prefix(first.buf, first.len);1142if(!cp)1143goto free_and_fail1;1144strbuf_remove(&first,0, cp - first.buf);11451146/*1147 * second points at one past closing dq of name.1148 * find the second name.1149 */1150while((second < line + llen) &&isspace(*second))1151 second++;11521153if(line + llen <= second)1154goto free_and_fail1;1155if(*second =='"') {1156if(unquote_c_style(&sp, second, NULL))1157goto free_and_fail1;1158 cp =skip_tree_prefix(sp.buf, sp.len);1159if(!cp)1160goto free_and_fail1;1161/* They must match, otherwise ignore */1162if(strcmp(cp, first.buf))1163goto free_and_fail1;1164strbuf_release(&sp);1165returnstrbuf_detach(&first, NULL);1166}11671168/* unquoted second */1169 cp =skip_tree_prefix(second, line + llen - second);1170if(!cp)1171goto free_and_fail1;1172if(line + llen - cp != first.len ||1173memcmp(first.buf, cp, first.len))1174goto free_and_fail1;1175returnstrbuf_detach(&first, NULL);11761177 free_and_fail1:1178strbuf_release(&first);1179strbuf_release(&sp);1180return NULL;1181}11821183/* unquoted first name */1184 name =skip_tree_prefix(line, llen);1185if(!name)1186return NULL;11871188/*1189 * since the first name is unquoted, a dq if exists must be1190 * the beginning of the second name.1191 */1192for(second = name; second < line + llen; second++) {1193if(*second =='"') {1194struct strbuf sp = STRBUF_INIT;1195const char*np;11961197if(unquote_c_style(&sp, second, NULL))1198goto free_and_fail2;11991200 np =skip_tree_prefix(sp.buf, sp.len);1201if(!np)1202goto free_and_fail2;12031204 len = sp.buf + sp.len - np;1205if(len < second - name &&1206!strncmp(np, name, len) &&1207isspace(name[len])) {1208/* Good */1209strbuf_remove(&sp,0, np - sp.buf);1210returnstrbuf_detach(&sp, NULL);1211}12121213 free_and_fail2:1214strbuf_release(&sp);1215return NULL;1216}1217}12181219/*1220 * Accept a name only if it shows up twice, exactly the same1221 * form.1222 */1223 second =strchr(name,'\n');1224if(!second)1225return NULL;1226 line_len = second - name;1227for(len =0; ; len++) {1228switch(name[len]) {1229default:1230continue;1231case'\n':1232return NULL;1233case'\t':case' ':1234/*1235 * Is this the separator between the preimage1236 * and the postimage pathname? Again, we are1237 * only interested in the case where there is1238 * no rename, as this is only to set def_name1239 * and a rename patch has the names elsewhere1240 * in an unambiguous form.1241 */1242if(!name[len +1])1243return NULL;/* no postimage name */1244 second =skip_tree_prefix(name + len +1,1245 line_len - (len +1));1246if(!second)1247return NULL;1248/*1249 * Does len bytes starting at "name" and "second"1250 * (that are separated by one HT or SP we just1251 * found) exactly match?1252 */1253if(second[len] =='\n'&& !strncmp(name, second, len))1254returnxmemdupz(name, len);1255}1256}1257}12581259/* Verify that we recognize the lines following a git header */1260static intparse_git_header(const char*line,int len,unsigned int size,struct patch *patch)1261{1262unsigned long offset;12631264/* A git diff has explicit new/delete information, so we don't guess */1265 patch->is_new =0;1266 patch->is_delete =0;12671268/*1269 * Some things may not have the old name in the1270 * rest of the headers anywhere (pure mode changes,1271 * or removing or adding empty files), so we get1272 * the default name from the header.1273 */1274 patch->def_name =git_header_name(line, len);1275if(patch->def_name && root.len) {1276char*s =xstrfmt("%s%s", root.buf, patch->def_name);1277free(patch->def_name);1278 patch->def_name = s;1279}12801281 line += len;1282 size -= len;1283 state_linenr++;1284for(offset = len ; size >0; offset += len, size -= len, line += len, state_linenr++) {1285static const struct opentry {1286const char*str;1287int(*fn)(const char*,struct patch *);1288} optable[] = {1289{"@@ -", gitdiff_hdrend },1290{"--- ", gitdiff_oldname },1291{"+++ ", gitdiff_newname },1292{"old mode ", gitdiff_oldmode },1293{"new mode ", gitdiff_newmode },1294{"deleted file mode ", gitdiff_delete },1295{"new file mode ", gitdiff_newfile },1296{"copy from ", gitdiff_copysrc },1297{"copy to ", gitdiff_copydst },1298{"rename old ", gitdiff_renamesrc },1299{"rename new ", gitdiff_renamedst },1300{"rename from ", gitdiff_renamesrc },1301{"rename to ", gitdiff_renamedst },1302{"similarity index ", gitdiff_similarity },1303{"dissimilarity index ", gitdiff_dissimilarity },1304{"index ", gitdiff_index },1305{"", gitdiff_unrecognized },1306};1307int i;13081309 len =linelen(line, size);1310if(!len || line[len-1] !='\n')1311break;1312for(i =0; i <ARRAY_SIZE(optable); i++) {1313const struct opentry *p = optable + i;1314int oplen =strlen(p->str);1315if(len < oplen ||memcmp(p->str, line, oplen))1316continue;1317if(p->fn(line + oplen, patch) <0)1318return offset;1319break;1320}1321}13221323return offset;1324}13251326static intparse_num(const char*line,unsigned long*p)1327{1328char*ptr;13291330if(!isdigit(*line))1331return0;1332*p =strtoul(line, &ptr,10);1333return ptr - line;1334}13351336static intparse_range(const char*line,int len,int offset,const char*expect,1337unsigned long*p1,unsigned long*p2)1338{1339int digits, ex;13401341if(offset <0|| offset >= len)1342return-1;1343 line += offset;1344 len -= offset;13451346 digits =parse_num(line, p1);1347if(!digits)1348return-1;13491350 offset += digits;1351 line += digits;1352 len -= digits;13531354*p2 =1;1355if(*line ==',') {1356 digits =parse_num(line+1, p2);1357if(!digits)1358return-1;13591360 offset += digits+1;1361 line += digits+1;1362 len -= digits+1;1363}13641365 ex =strlen(expect);1366if(ex > len)1367return-1;1368if(memcmp(line, expect, ex))1369return-1;13701371return offset + ex;1372}13731374static voidrecount_diff(const char*line,int size,struct fragment *fragment)1375{1376int oldlines =0, newlines =0, ret =0;13771378if(size <1) {1379warning("recount: ignore empty hunk");1380return;1381}13821383for(;;) {1384int len =linelen(line, size);1385 size -= len;1386 line += len;13871388if(size <1)1389break;13901391switch(*line) {1392case' ':case'\n':1393 newlines++;1394/* fall through */1395case'-':1396 oldlines++;1397continue;1398case'+':1399 newlines++;1400continue;1401case'\\':1402continue;1403case'@':1404 ret = size <3|| !starts_with(line,"@@ ");1405break;1406case'd':1407 ret = size <5|| !starts_with(line,"diff ");1408break;1409default:1410 ret = -1;1411break;1412}1413if(ret) {1414warning(_("recount: unexpected line: %.*s"),1415(int)linelen(line, size), line);1416return;1417}1418break;1419}1420 fragment->oldlines = oldlines;1421 fragment->newlines = newlines;1422}14231424/*1425 * Parse a unified diff fragment header of the1426 * form "@@ -a,b +c,d @@"1427 */1428static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1429{1430int offset;14311432if(!len || line[len-1] !='\n')1433return-1;14341435/* Figure out the number of lines in a fragment */1436 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1437 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14381439return offset;1440}14411442static intfind_header(struct apply_state *state,1443const char*line,1444unsigned long size,1445int*hdrsize,1446struct patch *patch)1447{1448unsigned long offset, len;14491450 patch->is_toplevel_relative =0;1451 patch->is_rename = patch->is_copy =0;1452 patch->is_new = patch->is_delete = -1;1453 patch->old_mode = patch->new_mode =0;1454 patch->old_name = patch->new_name = NULL;1455for(offset =0; size >0; offset += len, size -= len, line += len, state_linenr++) {1456unsigned long nextlen;14571458 len =linelen(line, size);1459if(!len)1460break;14611462/* Testing this early allows us to take a few shortcuts.. */1463if(len <6)1464continue;14651466/*1467 * Make sure we don't find any unconnected patch fragments.1468 * That's a sign that we didn't find a header, and that a1469 * patch has become corrupted/broken up.1470 */1471if(!memcmp("@@ -", line,4)) {1472struct fragment dummy;1473if(parse_fragment_header(line, len, &dummy) <0)1474continue;1475die(_("patch fragment without header at line%d: %.*s"),1476 state_linenr, (int)len-1, line);1477}14781479if(size < len +6)1480break;14811482/*1483 * Git patch? It might not have a real patch, just a rename1484 * or mode change, so we handle that specially1485 */1486if(!memcmp("diff --git ", line,11)) {1487int git_hdr_len =parse_git_header(line, len, size, patch);1488if(git_hdr_len <= len)1489continue;1490if(!patch->old_name && !patch->new_name) {1491if(!patch->def_name)1492die(Q_("git diff header lacks filename information when removing "1493"%dleading pathname component (line%d)",1494"git diff header lacks filename information when removing "1495"%dleading pathname components (line%d)",1496 state_p_value),1497 state_p_value, state_linenr);1498 patch->old_name =xstrdup(patch->def_name);1499 patch->new_name =xstrdup(patch->def_name);1500}1501if(!patch->is_delete && !patch->new_name)1502die("git diff header lacks filename information "1503"(line%d)", state_linenr);1504 patch->is_toplevel_relative =1;1505*hdrsize = git_hdr_len;1506return offset;1507}15081509/* --- followed by +++ ? */1510if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1511continue;15121513/*1514 * We only accept unified patches, so we want it to1515 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1516 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1517 */1518 nextlen =linelen(line + len, size - len);1519if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1520continue;15211522/* Ok, we'll consider it a patch */1523parse_traditional_patch(state, line, line+len, patch);1524*hdrsize = len + nextlen;1525 state_linenr +=2;1526return offset;1527}1528return-1;1529}15301531static voidrecord_ws_error(struct apply_state *state,1532unsigned result,1533const char*line,1534int len,1535int linenr)1536{1537char*err;15381539if(!result)1540return;15411542 whitespace_error++;1543if(squelch_whitespace_errors &&1544 squelch_whitespace_errors < whitespace_error)1545return;15461547 err =whitespace_error_string(result);1548fprintf(stderr,"%s:%d:%s.\n%.*s\n",1549 state->patch_input_file, linenr, err, len, line);1550free(err);1551}15521553static voidcheck_whitespace(struct apply_state *state,1554const char*line,1555int len,1556unsigned ws_rule)1557{1558unsigned result =ws_check(line +1, len -1, ws_rule);15591560record_ws_error(state, result, line +1, len -2, state_linenr);1561}15621563/*1564 * Parse a unified diff. Note that this really needs to parse each1565 * fragment separately, since the only way to know the difference1566 * between a "---" that is part of a patch, and a "---" that starts1567 * the next patch is to look at the line counts..1568 */1569static intparse_fragment(struct apply_state *state,1570const char*line,1571unsigned long size,1572struct patch *patch,1573struct fragment *fragment)1574{1575int added, deleted;1576int len =linelen(line, size), offset;1577unsigned long oldlines, newlines;1578unsigned long leading, trailing;15791580 offset =parse_fragment_header(line, len, fragment);1581if(offset <0)1582return-1;1583if(offset >0&& patch->recount)1584recount_diff(line + offset, size - offset, fragment);1585 oldlines = fragment->oldlines;1586 newlines = fragment->newlines;1587 leading =0;1588 trailing =0;15891590/* Parse the thing.. */1591 line += len;1592 size -= len;1593 state_linenr++;1594 added = deleted =0;1595for(offset = len;15960< size;1597 offset += len, size -= len, line += len, state_linenr++) {1598if(!oldlines && !newlines)1599break;1600 len =linelen(line, size);1601if(!len || line[len-1] !='\n')1602return-1;1603switch(*line) {1604default:1605return-1;1606case'\n':/* newer GNU diff, an empty context line */1607case' ':1608 oldlines--;1609 newlines--;1610if(!deleted && !added)1611 leading++;1612 trailing++;1613if(!state->apply_in_reverse &&1614 ws_error_action == correct_ws_error)1615check_whitespace(state, line, len, patch->ws_rule);1616break;1617case'-':1618if(state->apply_in_reverse &&1619 ws_error_action != nowarn_ws_error)1620check_whitespace(state, line, len, patch->ws_rule);1621 deleted++;1622 oldlines--;1623 trailing =0;1624break;1625case'+':1626if(!state->apply_in_reverse &&1627 ws_error_action != nowarn_ws_error)1628check_whitespace(state, line, len, patch->ws_rule);1629 added++;1630 newlines--;1631 trailing =0;1632break;16331634/*1635 * We allow "\ No newline at end of file". Depending1636 * on locale settings when the patch was produced we1637 * don't know what this line looks like. The only1638 * thing we do know is that it begins with "\ ".1639 * Checking for 12 is just for sanity check -- any1640 * l10n of "\ No newline..." is at least that long.1641 */1642case'\\':1643if(len <12||memcmp(line,"\\",2))1644return-1;1645break;1646}1647}1648if(oldlines || newlines)1649return-1;1650if(!deleted && !added)1651return-1;16521653 fragment->leading = leading;1654 fragment->trailing = trailing;16551656/*1657 * If a fragment ends with an incomplete line, we failed to include1658 * it in the above loop because we hit oldlines == newlines == 01659 * before seeing it.1660 */1661if(12< size && !memcmp(line,"\\",2))1662 offset +=linelen(line, size);16631664 patch->lines_added += added;1665 patch->lines_deleted += deleted;16661667if(0< patch->is_new && oldlines)1668returnerror(_("new file depends on old contents"));1669if(0< patch->is_delete && newlines)1670returnerror(_("deleted file still has contents"));1671return offset;1672}16731674/*1675 * We have seen "diff --git a/... b/..." header (or a traditional patch1676 * header). Read hunks that belong to this patch into fragments and hang1677 * them to the given patch structure.1678 *1679 * The (fragment->patch, fragment->size) pair points into the memory given1680 * by the caller, not a copy, when we return.1681 */1682static intparse_single_patch(struct apply_state *state,1683const char*line,1684unsigned long size,1685struct patch *patch)1686{1687unsigned long offset =0;1688unsigned long oldlines =0, newlines =0, context =0;1689struct fragment **fragp = &patch->fragments;16901691while(size >4&& !memcmp(line,"@@ -",4)) {1692struct fragment *fragment;1693int len;16941695 fragment =xcalloc(1,sizeof(*fragment));1696 fragment->linenr = state_linenr;1697 len =parse_fragment(state, line, size, patch, fragment);1698if(len <=0)1699die(_("corrupt patch at line%d"), state_linenr);1700 fragment->patch = line;1701 fragment->size = len;1702 oldlines += fragment->oldlines;1703 newlines += fragment->newlines;1704 context += fragment->leading + fragment->trailing;17051706*fragp = fragment;1707 fragp = &fragment->next;17081709 offset += len;1710 line += len;1711 size -= len;1712}17131714/*1715 * If something was removed (i.e. we have old-lines) it cannot1716 * be creation, and if something was added it cannot be1717 * deletion. However, the reverse is not true; --unified=01718 * patches that only add are not necessarily creation even1719 * though they do not have any old lines, and ones that only1720 * delete are not necessarily deletion.1721 *1722 * Unfortunately, a real creation/deletion patch do _not_ have1723 * any context line by definition, so we cannot safely tell it1724 * apart with --unified=0 insanity. At least if the patch has1725 * more than one hunk it is not creation or deletion.1726 */1727if(patch->is_new <0&&1728(oldlines || (patch->fragments && patch->fragments->next)))1729 patch->is_new =0;1730if(patch->is_delete <0&&1731(newlines || (patch->fragments && patch->fragments->next)))1732 patch->is_delete =0;17331734if(0< patch->is_new && oldlines)1735die(_("new file%sdepends on old contents"), patch->new_name);1736if(0< patch->is_delete && newlines)1737die(_("deleted file%sstill has contents"), patch->old_name);1738if(!patch->is_delete && !newlines && context)1739fprintf_ln(stderr,1740_("** warning: "1741"file%sbecomes empty but is not deleted"),1742 patch->new_name);17431744return offset;1745}17461747staticinlineintmetadata_changes(struct patch *patch)1748{1749return patch->is_rename >0||1750 patch->is_copy >0||1751 patch->is_new >0||1752 patch->is_delete ||1753(patch->old_mode && patch->new_mode &&1754 patch->old_mode != patch->new_mode);1755}17561757static char*inflate_it(const void*data,unsigned long size,1758unsigned long inflated_size)1759{1760 git_zstream stream;1761void*out;1762int st;17631764memset(&stream,0,sizeof(stream));17651766 stream.next_in = (unsigned char*)data;1767 stream.avail_in = size;1768 stream.next_out = out =xmalloc(inflated_size);1769 stream.avail_out = inflated_size;1770git_inflate_init(&stream);1771 st =git_inflate(&stream, Z_FINISH);1772git_inflate_end(&stream);1773if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1774free(out);1775return NULL;1776}1777return out;1778}17791780/*1781 * Read a binary hunk and return a new fragment; fragment->patch1782 * points at an allocated memory that the caller must free, so1783 * it is marked as "->free_patch = 1".1784 */1785static struct fragment *parse_binary_hunk(char**buf_p,1786unsigned long*sz_p,1787int*status_p,1788int*used_p)1789{1790/*1791 * Expect a line that begins with binary patch method ("literal"1792 * or "delta"), followed by the length of data before deflating.1793 * a sequence of 'length-byte' followed by base-85 encoded data1794 * should follow, terminated by a newline.1795 *1796 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1797 * and we would limit the patch line to 66 characters,1798 * so one line can fit up to 13 groups that would decode1799 * to 52 bytes max. The length byte 'A'-'Z' corresponds1800 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1801 */1802int llen, used;1803unsigned long size = *sz_p;1804char*buffer = *buf_p;1805int patch_method;1806unsigned long origlen;1807char*data = NULL;1808int hunk_size =0;1809struct fragment *frag;18101811 llen =linelen(buffer, size);1812 used = llen;18131814*status_p =0;18151816if(starts_with(buffer,"delta ")) {1817 patch_method = BINARY_DELTA_DEFLATED;1818 origlen =strtoul(buffer +6, NULL,10);1819}1820else if(starts_with(buffer,"literal ")) {1821 patch_method = BINARY_LITERAL_DEFLATED;1822 origlen =strtoul(buffer +8, NULL,10);1823}1824else1825return NULL;18261827 state_linenr++;1828 buffer += llen;1829while(1) {1830int byte_length, max_byte_length, newsize;1831 llen =linelen(buffer, size);1832 used += llen;1833 state_linenr++;1834if(llen ==1) {1835/* consume the blank line */1836 buffer++;1837 size--;1838break;1839}1840/*1841 * Minimum line is "A00000\n" which is 7-byte long,1842 * and the line length must be multiple of 5 plus 2.1843 */1844if((llen <7) || (llen-2) %5)1845goto corrupt;1846 max_byte_length = (llen -2) /5*4;1847 byte_length = *buffer;1848if('A'<= byte_length && byte_length <='Z')1849 byte_length = byte_length -'A'+1;1850else if('a'<= byte_length && byte_length <='z')1851 byte_length = byte_length -'a'+27;1852else1853goto corrupt;1854/* if the input length was not multiple of 4, we would1855 * have filler at the end but the filler should never1856 * exceed 3 bytes1857 */1858if(max_byte_length < byte_length ||1859 byte_length <= max_byte_length -4)1860goto corrupt;1861 newsize = hunk_size + byte_length;1862 data =xrealloc(data, newsize);1863if(decode_85(data + hunk_size, buffer +1, byte_length))1864goto corrupt;1865 hunk_size = newsize;1866 buffer += llen;1867 size -= llen;1868}18691870 frag =xcalloc(1,sizeof(*frag));1871 frag->patch =inflate_it(data, hunk_size, origlen);1872 frag->free_patch =1;1873if(!frag->patch)1874goto corrupt;1875free(data);1876 frag->size = origlen;1877*buf_p = buffer;1878*sz_p = size;1879*used_p = used;1880 frag->binary_patch_method = patch_method;1881return frag;18821883 corrupt:1884free(data);1885*status_p = -1;1886error(_("corrupt binary patch at line%d: %.*s"),1887 state_linenr-1, llen-1, buffer);1888return NULL;1889}18901891/*1892 * Returns:1893 * -1 in case of error,1894 * the length of the parsed binary patch otherwise1895 */1896static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1897{1898/*1899 * We have read "GIT binary patch\n"; what follows is a line1900 * that says the patch method (currently, either "literal" or1901 * "delta") and the length of data before deflating; a1902 * sequence of 'length-byte' followed by base-85 encoded data1903 * follows.1904 *1905 * When a binary patch is reversible, there is another binary1906 * hunk in the same format, starting with patch method (either1907 * "literal" or "delta") with the length of data, and a sequence1908 * of length-byte + base-85 encoded data, terminated with another1909 * empty line. This data, when applied to the postimage, produces1910 * the preimage.1911 */1912struct fragment *forward;1913struct fragment *reverse;1914int status;1915int used, used_1;19161917 forward =parse_binary_hunk(&buffer, &size, &status, &used);1918if(!forward && !status)1919/* there has to be one hunk (forward hunk) */1920returnerror(_("unrecognized binary patch at line%d"), state_linenr-1);1921if(status)1922/* otherwise we already gave an error message */1923return status;19241925 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1926if(reverse)1927 used += used_1;1928else if(status) {1929/*1930 * Not having reverse hunk is not an error, but having1931 * a corrupt reverse hunk is.1932 */1933free((void*) forward->patch);1934free(forward);1935return status;1936}1937 forward->next = reverse;1938 patch->fragments = forward;1939 patch->is_binary =1;1940return used;1941}19421943static voidprefix_one(struct apply_state *state,char**name)1944{1945char*old_name = *name;1946if(!old_name)1947return;1948*name =xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));1949free(old_name);1950}19511952static voidprefix_patch(struct apply_state *state,struct patch *p)1953{1954if(!state->prefix || p->is_toplevel_relative)1955return;1956prefix_one(state, &p->new_name);1957prefix_one(state, &p->old_name);1958}19591960/*1961 * include/exclude1962 */19631964static int has_include;1965static voidadd_name_limit(struct apply_state *state,1966const char*name,1967int exclude)1968{1969struct string_list_item *it;19701971 it =string_list_append(&state->limit_by_name, name);1972 it->util = exclude ? NULL : (void*)1;1973}19741975static intuse_patch(struct apply_state *state,struct patch *p)1976{1977const char*pathname = p->new_name ? p->new_name : p->old_name;1978int i;19791980/* Paths outside are not touched regardless of "--include" */1981if(0< state->prefix_length) {1982int pathlen =strlen(pathname);1983if(pathlen <= state->prefix_length ||1984memcmp(state->prefix, pathname, state->prefix_length))1985return0;1986}19871988/* See if it matches any of exclude/include rule */1989for(i =0; i < state->limit_by_name.nr; i++) {1990struct string_list_item *it = &state->limit_by_name.items[i];1991if(!wildmatch(it->string, pathname,0, NULL))1992return(it->util != NULL);1993}19941995/*1996 * If we had any include, a path that does not match any rule is1997 * not used. Otherwise, we saw bunch of exclude rules (or none)1998 * and such a path is used.1999 */2000return!has_include;2001}200220032004/*2005 * Read the patch text in "buffer" that extends for "size" bytes; stop2006 * reading after seeing a single patch (i.e. changes to a single file).2007 * Create fragments (i.e. patch hunks) and hang them to the given patch.2008 * Return the number of bytes consumed, so that the caller can call us2009 * again for the next patch.2010 */2011static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2012{2013int hdrsize, patchsize;2014int offset =find_header(state, buffer, size, &hdrsize, patch);20152016if(offset <0)2017return offset;20182019prefix_patch(state, patch);20202021if(!use_patch(state, patch))2022 patch->ws_rule =0;2023else2024 patch->ws_rule =whitespace_rule(patch->new_name2025? patch->new_name2026: patch->old_name);20272028 patchsize =parse_single_patch(state,2029 buffer + offset + hdrsize,2030 size - offset - hdrsize,2031 patch);20322033if(!patchsize) {2034static const char git_binary[] ="GIT binary patch\n";2035int hd = hdrsize + offset;2036unsigned long llen =linelen(buffer + hd, size - hd);20372038if(llen ==sizeof(git_binary) -1&&2039!memcmp(git_binary, buffer + hd, llen)) {2040int used;2041 state_linenr++;2042 used =parse_binary(buffer + hd + llen,2043 size - hd - llen, patch);2044if(used <0)2045return-1;2046if(used)2047 patchsize = used + llen;2048else2049 patchsize =0;2050}2051else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2052static const char*binhdr[] = {2053"Binary files ",2054"Files ",2055 NULL,2056};2057int i;2058for(i =0; binhdr[i]; i++) {2059int len =strlen(binhdr[i]);2060if(len < size - hd &&2061!memcmp(binhdr[i], buffer + hd, len)) {2062 state_linenr++;2063 patch->is_binary =1;2064 patchsize = llen;2065break;2066}2067}2068}20692070/* Empty patch cannot be applied if it is a text patch2071 * without metadata change. A binary patch appears2072 * empty to us here.2073 */2074if((state->apply || state->check) &&2075(!patch->is_binary && !metadata_changes(patch)))2076die(_("patch with only garbage at line%d"), state_linenr);2077}20782079return offset + hdrsize + patchsize;2080}20812082#define swap(a,b) myswap((a),(b),sizeof(a))20832084#define myswap(a, b, size) do { \2085 unsigned char mytmp[size]; \2086 memcpy(mytmp, &a, size); \2087 memcpy(&a, &b, size); \2088 memcpy(&b, mytmp, size); \2089} while (0)20902091static voidreverse_patches(struct patch *p)2092{2093for(; p; p = p->next) {2094struct fragment *frag = p->fragments;20952096swap(p->new_name, p->old_name);2097swap(p->new_mode, p->old_mode);2098swap(p->is_new, p->is_delete);2099swap(p->lines_added, p->lines_deleted);2100swap(p->old_sha1_prefix, p->new_sha1_prefix);21012102for(; frag; frag = frag->next) {2103swap(frag->newpos, frag->oldpos);2104swap(frag->newlines, frag->oldlines);2105}2106}2107}21082109static const char pluses[] =2110"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2111static const char minuses[]=2112"----------------------------------------------------------------------";21132114static voidshow_stats(struct patch *patch)2115{2116struct strbuf qname = STRBUF_INIT;2117char*cp = patch->new_name ? patch->new_name : patch->old_name;2118int max, add, del;21192120quote_c_style(cp, &qname, NULL,0);21212122/*2123 * "scale" the filename2124 */2125 max = max_len;2126if(max >50)2127 max =50;21282129if(qname.len > max) {2130 cp =strchr(qname.buf + qname.len +3- max,'/');2131if(!cp)2132 cp = qname.buf + qname.len +3- max;2133strbuf_splice(&qname,0, cp - qname.buf,"...",3);2134}21352136if(patch->is_binary) {2137printf(" %-*s | Bin\n", max, qname.buf);2138strbuf_release(&qname);2139return;2140}21412142printf(" %-*s |", max, qname.buf);2143strbuf_release(&qname);21442145/*2146 * scale the add/delete2147 */2148 max = max + max_change >70?70- max : max_change;2149 add = patch->lines_added;2150 del = patch->lines_deleted;21512152if(max_change >0) {2153int total = ((add + del) * max + max_change /2) / max_change;2154 add = (add * max + max_change /2) / max_change;2155 del = total - add;2156}2157printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2158 add, pluses, del, minuses);2159}21602161static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2162{2163switch(st->st_mode & S_IFMT) {2164case S_IFLNK:2165if(strbuf_readlink(buf, path, st->st_size) <0)2166returnerror(_("unable to read symlink%s"), path);2167return0;2168case S_IFREG:2169if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2170returnerror(_("unable to open or read%s"), path);2171convert_to_git(path, buf->buf, buf->len, buf,0);2172return0;2173default:2174return-1;2175}2176}21772178/*2179 * Update the preimage, and the common lines in postimage,2180 * from buffer buf of length len. If postlen is 0 the postimage2181 * is updated in place, otherwise it's updated on a new buffer2182 * of length postlen2183 */21842185static voidupdate_pre_post_images(struct image *preimage,2186struct image *postimage,2187char*buf,2188size_t len,size_t postlen)2189{2190int i, ctx, reduced;2191char*new, *old, *fixed;2192struct image fixed_preimage;21932194/*2195 * Update the preimage with whitespace fixes. Note that we2196 * are not losing preimage->buf -- apply_one_fragment() will2197 * free "oldlines".2198 */2199prepare_image(&fixed_preimage, buf, len,1);2200assert(postlen2201? fixed_preimage.nr == preimage->nr2202: fixed_preimage.nr <= preimage->nr);2203for(i =0; i < fixed_preimage.nr; i++)2204 fixed_preimage.line[i].flag = preimage->line[i].flag;2205free(preimage->line_allocated);2206*preimage = fixed_preimage;22072208/*2209 * Adjust the common context lines in postimage. This can be2210 * done in-place when we are shrinking it with whitespace2211 * fixing, but needs a new buffer when ignoring whitespace or2212 * expanding leading tabs to spaces.2213 *2214 * We trust the caller to tell us if the update can be done2215 * in place (postlen==0) or not.2216 */2217 old = postimage->buf;2218if(postlen)2219new= postimage->buf =xmalloc(postlen);2220else2221new= old;2222 fixed = preimage->buf;22232224for(i = reduced = ctx =0; i < postimage->nr; i++) {2225size_t l_len = postimage->line[i].len;2226if(!(postimage->line[i].flag & LINE_COMMON)) {2227/* an added line -- no counterparts in preimage */2228memmove(new, old, l_len);2229 old += l_len;2230new+= l_len;2231continue;2232}22332234/* a common context -- skip it in the original postimage */2235 old += l_len;22362237/* and find the corresponding one in the fixed preimage */2238while(ctx < preimage->nr &&2239!(preimage->line[ctx].flag & LINE_COMMON)) {2240 fixed += preimage->line[ctx].len;2241 ctx++;2242}22432244/*2245 * preimage is expected to run out, if the caller2246 * fixed addition of trailing blank lines.2247 */2248if(preimage->nr <= ctx) {2249 reduced++;2250continue;2251}22522253/* and copy it in, while fixing the line length */2254 l_len = preimage->line[ctx].len;2255memcpy(new, fixed, l_len);2256new+= l_len;2257 fixed += l_len;2258 postimage->line[i].len = l_len;2259 ctx++;2260}22612262if(postlen2263? postlen <new- postimage->buf2264: postimage->len <new- postimage->buf)2265die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2266(int)postlen, (int) postimage->len, (int)(new- postimage->buf));22672268/* Fix the length of the whole thing */2269 postimage->len =new- postimage->buf;2270 postimage->nr -= reduced;2271}22722273static intline_by_line_fuzzy_match(struct image *img,2274struct image *preimage,2275struct image *postimage,2276unsigned longtry,2277int try_lno,2278int preimage_limit)2279{2280int i;2281size_t imgoff =0;2282size_t preoff =0;2283size_t postlen = postimage->len;2284size_t extra_chars;2285char*buf;2286char*preimage_eof;2287char*preimage_end;2288struct strbuf fixed;2289char*fixed_buf;2290size_t fixed_len;22912292for(i =0; i < preimage_limit; i++) {2293size_t prelen = preimage->line[i].len;2294size_t imglen = img->line[try_lno+i].len;22952296if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2297 preimage->buf + preoff, prelen))2298return0;2299if(preimage->line[i].flag & LINE_COMMON)2300 postlen += imglen - prelen;2301 imgoff += imglen;2302 preoff += prelen;2303}23042305/*2306 * Ok, the preimage matches with whitespace fuzz.2307 *2308 * imgoff now holds the true length of the target that2309 * matches the preimage before the end of the file.2310 *2311 * Count the number of characters in the preimage that fall2312 * beyond the end of the file and make sure that all of them2313 * are whitespace characters. (This can only happen if2314 * we are removing blank lines at the end of the file.)2315 */2316 buf = preimage_eof = preimage->buf + preoff;2317for( ; i < preimage->nr; i++)2318 preoff += preimage->line[i].len;2319 preimage_end = preimage->buf + preoff;2320for( ; buf < preimage_end; buf++)2321if(!isspace(*buf))2322return0;23232324/*2325 * Update the preimage and the common postimage context2326 * lines to use the same whitespace as the target.2327 * If whitespace is missing in the target (i.e.2328 * if the preimage extends beyond the end of the file),2329 * use the whitespace from the preimage.2330 */2331 extra_chars = preimage_end - preimage_eof;2332strbuf_init(&fixed, imgoff + extra_chars);2333strbuf_add(&fixed, img->buf +try, imgoff);2334strbuf_add(&fixed, preimage_eof, extra_chars);2335 fixed_buf =strbuf_detach(&fixed, &fixed_len);2336update_pre_post_images(preimage, postimage,2337 fixed_buf, fixed_len, postlen);2338return1;2339}23402341static intmatch_fragment(struct image *img,2342struct image *preimage,2343struct image *postimage,2344unsigned longtry,2345int try_lno,2346unsigned ws_rule,2347int match_beginning,int match_end)2348{2349int i;2350char*fixed_buf, *buf, *orig, *target;2351struct strbuf fixed;2352size_t fixed_len, postlen;2353int preimage_limit;23542355if(preimage->nr + try_lno <= img->nr) {2356/*2357 * The hunk falls within the boundaries of img.2358 */2359 preimage_limit = preimage->nr;2360if(match_end && (preimage->nr + try_lno != img->nr))2361return0;2362}else if(ws_error_action == correct_ws_error &&2363(ws_rule & WS_BLANK_AT_EOF)) {2364/*2365 * This hunk extends beyond the end of img, and we are2366 * removing blank lines at the end of the file. This2367 * many lines from the beginning of the preimage must2368 * match with img, and the remainder of the preimage2369 * must be blank.2370 */2371 preimage_limit = img->nr - try_lno;2372}else{2373/*2374 * The hunk extends beyond the end of the img and2375 * we are not removing blanks at the end, so we2376 * should reject the hunk at this position.2377 */2378return0;2379}23802381if(match_beginning && try_lno)2382return0;23832384/* Quick hash check */2385for(i =0; i < preimage_limit; i++)2386if((img->line[try_lno + i].flag & LINE_PATCHED) ||2387(preimage->line[i].hash != img->line[try_lno + i].hash))2388return0;23892390if(preimage_limit == preimage->nr) {2391/*2392 * Do we have an exact match? If we were told to match2393 * at the end, size must be exactly at try+fragsize,2394 * otherwise try+fragsize must be still within the preimage,2395 * and either case, the old piece should match the preimage2396 * exactly.2397 */2398if((match_end2399? (try+ preimage->len == img->len)2400: (try+ preimage->len <= img->len)) &&2401!memcmp(img->buf +try, preimage->buf, preimage->len))2402return1;2403}else{2404/*2405 * The preimage extends beyond the end of img, so2406 * there cannot be an exact match.2407 *2408 * There must be one non-blank context line that match2409 * a line before the end of img.2410 */2411char*buf_end;24122413 buf = preimage->buf;2414 buf_end = buf;2415for(i =0; i < preimage_limit; i++)2416 buf_end += preimage->line[i].len;24172418for( ; buf < buf_end; buf++)2419if(!isspace(*buf))2420break;2421if(buf == buf_end)2422return0;2423}24242425/*2426 * No exact match. If we are ignoring whitespace, run a line-by-line2427 * fuzzy matching. We collect all the line length information because2428 * we need it to adjust whitespace if we match.2429 */2430if(ws_ignore_action == ignore_ws_change)2431returnline_by_line_fuzzy_match(img, preimage, postimage,2432try, try_lno, preimage_limit);24332434if(ws_error_action != correct_ws_error)2435return0;24362437/*2438 * The hunk does not apply byte-by-byte, but the hash says2439 * it might with whitespace fuzz. We weren't asked to2440 * ignore whitespace, we were asked to correct whitespace2441 * errors, so let's try matching after whitespace correction.2442 *2443 * While checking the preimage against the target, whitespace2444 * errors in both fixed, we count how large the corresponding2445 * postimage needs to be. The postimage prepared by2446 * apply_one_fragment() has whitespace errors fixed on added2447 * lines already, but the common lines were propagated as-is,2448 * which may become longer when their whitespace errors are2449 * fixed.2450 */24512452/* First count added lines in postimage */2453 postlen =0;2454for(i =0; i < postimage->nr; i++) {2455if(!(postimage->line[i].flag & LINE_COMMON))2456 postlen += postimage->line[i].len;2457}24582459/*2460 * The preimage may extend beyond the end of the file,2461 * but in this loop we will only handle the part of the2462 * preimage that falls within the file.2463 */2464strbuf_init(&fixed, preimage->len +1);2465 orig = preimage->buf;2466 target = img->buf +try;2467for(i =0; i < preimage_limit; i++) {2468size_t oldlen = preimage->line[i].len;2469size_t tgtlen = img->line[try_lno + i].len;2470size_t fixstart = fixed.len;2471struct strbuf tgtfix;2472int match;24732474/* Try fixing the line in the preimage */2475ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24762477/* Try fixing the line in the target */2478strbuf_init(&tgtfix, tgtlen);2479ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);24802481/*2482 * If they match, either the preimage was based on2483 * a version before our tree fixed whitespace breakage,2484 * or we are lacking a whitespace-fix patch the tree2485 * the preimage was based on already had (i.e. target2486 * has whitespace breakage, the preimage doesn't).2487 * In either case, we are fixing the whitespace breakages2488 * so we might as well take the fix together with their2489 * real change.2490 */2491 match = (tgtfix.len == fixed.len - fixstart &&2492!memcmp(tgtfix.buf, fixed.buf + fixstart,2493 fixed.len - fixstart));24942495/* Add the length if this is common with the postimage */2496if(preimage->line[i].flag & LINE_COMMON)2497 postlen += tgtfix.len;24982499strbuf_release(&tgtfix);2500if(!match)2501goto unmatch_exit;25022503 orig += oldlen;2504 target += tgtlen;2505}250625072508/*2509 * Now handle the lines in the preimage that falls beyond the2510 * end of the file (if any). They will only match if they are2511 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2512 * false).2513 */2514for( ; i < preimage->nr; i++) {2515size_t fixstart = fixed.len;/* start of the fixed preimage */2516size_t oldlen = preimage->line[i].len;2517int j;25182519/* Try fixing the line in the preimage */2520ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25212522for(j = fixstart; j < fixed.len; j++)2523if(!isspace(fixed.buf[j]))2524goto unmatch_exit;25252526 orig += oldlen;2527}25282529/*2530 * Yes, the preimage is based on an older version that still2531 * has whitespace breakages unfixed, and fixing them makes the2532 * hunk match. Update the context lines in the postimage.2533 */2534 fixed_buf =strbuf_detach(&fixed, &fixed_len);2535if(postlen < postimage->len)2536 postlen =0;2537update_pre_post_images(preimage, postimage,2538 fixed_buf, fixed_len, postlen);2539return1;25402541 unmatch_exit:2542strbuf_release(&fixed);2543return0;2544}25452546static intfind_pos(struct image *img,2547struct image *preimage,2548struct image *postimage,2549int line,2550unsigned ws_rule,2551int match_beginning,int match_end)2552{2553int i;2554unsigned long backwards, forwards,try;2555int backwards_lno, forwards_lno, try_lno;25562557/*2558 * If match_beginning or match_end is specified, there is no2559 * point starting from a wrong line that will never match and2560 * wander around and wait for a match at the specified end.2561 */2562if(match_beginning)2563 line =0;2564else if(match_end)2565 line = img->nr - preimage->nr;25662567/*2568 * Because the comparison is unsigned, the following test2569 * will also take care of a negative line number that can2570 * result when match_end and preimage is larger than the target.2571 */2572if((size_t) line > img->nr)2573 line = img->nr;25742575try=0;2576for(i =0; i < line; i++)2577try+= img->line[i].len;25782579/*2580 * There's probably some smart way to do this, but I'll leave2581 * that to the smart and beautiful people. I'm simple and stupid.2582 */2583 backwards =try;2584 backwards_lno = line;2585 forwards =try;2586 forwards_lno = line;2587 try_lno = line;25882589for(i =0; ; i++) {2590if(match_fragment(img, preimage, postimage,2591try, try_lno, ws_rule,2592 match_beginning, match_end))2593return try_lno;25942595 again:2596if(backwards_lno ==0&& forwards_lno == img->nr)2597break;25982599if(i &1) {2600if(backwards_lno ==0) {2601 i++;2602goto again;2603}2604 backwards_lno--;2605 backwards -= img->line[backwards_lno].len;2606try= backwards;2607 try_lno = backwards_lno;2608}else{2609if(forwards_lno == img->nr) {2610 i++;2611goto again;2612}2613 forwards += img->line[forwards_lno].len;2614 forwards_lno++;2615try= forwards;2616 try_lno = forwards_lno;2617}26182619}2620return-1;2621}26222623static voidremove_first_line(struct image *img)2624{2625 img->buf += img->line[0].len;2626 img->len -= img->line[0].len;2627 img->line++;2628 img->nr--;2629}26302631static voidremove_last_line(struct image *img)2632{2633 img->len -= img->line[--img->nr].len;2634}26352636/*2637 * The change from "preimage" and "postimage" has been found to2638 * apply at applied_pos (counts in line numbers) in "img".2639 * Update "img" to remove "preimage" and replace it with "postimage".2640 */2641static voidupdate_image(struct apply_state *state,2642struct image *img,2643int applied_pos,2644struct image *preimage,2645struct image *postimage)2646{2647/*2648 * remove the copy of preimage at offset in img2649 * and replace it with postimage2650 */2651int i, nr;2652size_t remove_count, insert_count, applied_at =0;2653char*result;2654int preimage_limit;26552656/*2657 * If we are removing blank lines at the end of img,2658 * the preimage may extend beyond the end.2659 * If that is the case, we must be careful only to2660 * remove the part of the preimage that falls within2661 * the boundaries of img. Initialize preimage_limit2662 * to the number of lines in the preimage that falls2663 * within the boundaries.2664 */2665 preimage_limit = preimage->nr;2666if(preimage_limit > img->nr - applied_pos)2667 preimage_limit = img->nr - applied_pos;26682669for(i =0; i < applied_pos; i++)2670 applied_at += img->line[i].len;26712672 remove_count =0;2673for(i =0; i < preimage_limit; i++)2674 remove_count += img->line[applied_pos + i].len;2675 insert_count = postimage->len;26762677/* Adjust the contents */2678 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2679memcpy(result, img->buf, applied_at);2680memcpy(result + applied_at, postimage->buf, postimage->len);2681memcpy(result + applied_at + postimage->len,2682 img->buf + (applied_at + remove_count),2683 img->len - (applied_at + remove_count));2684free(img->buf);2685 img->buf = result;2686 img->len += insert_count - remove_count;2687 result[img->len] ='\0';26882689/* Adjust the line table */2690 nr = img->nr + postimage->nr - preimage_limit;2691if(preimage_limit < postimage->nr) {2692/*2693 * NOTE: this knows that we never call remove_first_line()2694 * on anything other than pre/post image.2695 */2696REALLOC_ARRAY(img->line, nr);2697 img->line_allocated = img->line;2698}2699if(preimage_limit != postimage->nr)2700memmove(img->line + applied_pos + postimage->nr,2701 img->line + applied_pos + preimage_limit,2702(img->nr - (applied_pos + preimage_limit)) *2703sizeof(*img->line));2704memcpy(img->line + applied_pos,2705 postimage->line,2706 postimage->nr *sizeof(*img->line));2707if(!state->allow_overlap)2708for(i =0; i < postimage->nr; i++)2709 img->line[applied_pos + i].flag |= LINE_PATCHED;2710 img->nr = nr;2711}27122713/*2714 * Use the patch-hunk text in "frag" to prepare two images (preimage and2715 * postimage) for the hunk. Find lines that match "preimage" in "img" and2716 * replace the part of "img" with "postimage" text.2717 */2718static intapply_one_fragment(struct apply_state *state,2719struct image *img,struct fragment *frag,2720int inaccurate_eof,unsigned ws_rule,2721int nth_fragment)2722{2723int match_beginning, match_end;2724const char*patch = frag->patch;2725int size = frag->size;2726char*old, *oldlines;2727struct strbuf newlines;2728int new_blank_lines_at_end =0;2729int found_new_blank_lines_at_end =0;2730int hunk_linenr = frag->linenr;2731unsigned long leading, trailing;2732int pos, applied_pos;2733struct image preimage;2734struct image postimage;27352736memset(&preimage,0,sizeof(preimage));2737memset(&postimage,0,sizeof(postimage));2738 oldlines =xmalloc(size);2739strbuf_init(&newlines, size);27402741 old = oldlines;2742while(size >0) {2743char first;2744int len =linelen(patch, size);2745int plen;2746int added_blank_line =0;2747int is_blank_context =0;2748size_t start;27492750if(!len)2751break;27522753/*2754 * "plen" is how much of the line we should use for2755 * the actual patch data. Normally we just remove the2756 * first character on the line, but if the line is2757 * followed by "\ No newline", then we also remove the2758 * last one (which is the newline, of course).2759 */2760 plen = len -1;2761if(len < size && patch[len] =='\\')2762 plen--;2763 first = *patch;2764if(state->apply_in_reverse) {2765if(first =='-')2766 first ='+';2767else if(first =='+')2768 first ='-';2769}27702771switch(first) {2772case'\n':2773/* Newer GNU diff, empty context line */2774if(plen <0)2775/* ... followed by '\No newline'; nothing */2776break;2777*old++ ='\n';2778strbuf_addch(&newlines,'\n');2779add_line_info(&preimage,"\n",1, LINE_COMMON);2780add_line_info(&postimage,"\n",1, LINE_COMMON);2781 is_blank_context =1;2782break;2783case' ':2784if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2785ws_blank_line(patch +1, plen, ws_rule))2786 is_blank_context =1;2787case'-':2788memcpy(old, patch +1, plen);2789add_line_info(&preimage, old, plen,2790(first ==' '? LINE_COMMON :0));2791 old += plen;2792if(first =='-')2793break;2794/* Fall-through for ' ' */2795case'+':2796/* --no-add does not add new lines */2797if(first =='+'&& state->no_add)2798break;27992800 start = newlines.len;2801if(first !='+'||2802!whitespace_error ||2803 ws_error_action != correct_ws_error) {2804strbuf_add(&newlines, patch +1, plen);2805}2806else{2807ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2808}2809add_line_info(&postimage, newlines.buf + start, newlines.len - start,2810(first =='+'?0: LINE_COMMON));2811if(first =='+'&&2812(ws_rule & WS_BLANK_AT_EOF) &&2813ws_blank_line(patch +1, plen, ws_rule))2814 added_blank_line =1;2815break;2816case'@':case'\\':2817/* Ignore it, we already handled it */2818break;2819default:2820if(state->apply_verbosely)2821error(_("invalid start of line: '%c'"), first);2822 applied_pos = -1;2823goto out;2824}2825if(added_blank_line) {2826if(!new_blank_lines_at_end)2827 found_new_blank_lines_at_end = hunk_linenr;2828 new_blank_lines_at_end++;2829}2830else if(is_blank_context)2831;2832else2833 new_blank_lines_at_end =0;2834 patch += len;2835 size -= len;2836 hunk_linenr++;2837}2838if(inaccurate_eof &&2839 old > oldlines && old[-1] =='\n'&&2840 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2841 old--;2842strbuf_setlen(&newlines, newlines.len -1);2843}28442845 leading = frag->leading;2846 trailing = frag->trailing;28472848/*2849 * A hunk to change lines at the beginning would begin with2850 * @@ -1,L +N,M @@2851 * but we need to be careful. -U0 that inserts before the second2852 * line also has this pattern.2853 *2854 * And a hunk to add to an empty file would begin with2855 * @@ -0,0 +N,M @@2856 *2857 * In other words, a hunk that is (frag->oldpos <= 1) with or2858 * without leading context must match at the beginning.2859 */2860 match_beginning = (!frag->oldpos ||2861(frag->oldpos ==1&& !state->unidiff_zero));28622863/*2864 * A hunk without trailing lines must match at the end.2865 * However, we simply cannot tell if a hunk must match end2866 * from the lack of trailing lines if the patch was generated2867 * with unidiff without any context.2868 */2869 match_end = !state->unidiff_zero && !trailing;28702871 pos = frag->newpos ? (frag->newpos -1) :0;2872 preimage.buf = oldlines;2873 preimage.len = old - oldlines;2874 postimage.buf = newlines.buf;2875 postimage.len = newlines.len;2876 preimage.line = preimage.line_allocated;2877 postimage.line = postimage.line_allocated;28782879for(;;) {28802881 applied_pos =find_pos(img, &preimage, &postimage, pos,2882 ws_rule, match_beginning, match_end);28832884if(applied_pos >=0)2885break;28862887/* Am I at my context limits? */2888if((leading <= state->p_context) && (trailing <= state->p_context))2889break;2890if(match_beginning || match_end) {2891 match_beginning = match_end =0;2892continue;2893}28942895/*2896 * Reduce the number of context lines; reduce both2897 * leading and trailing if they are equal otherwise2898 * just reduce the larger context.2899 */2900if(leading >= trailing) {2901remove_first_line(&preimage);2902remove_first_line(&postimage);2903 pos--;2904 leading--;2905}2906if(trailing > leading) {2907remove_last_line(&preimage);2908remove_last_line(&postimage);2909 trailing--;2910}2911}29122913if(applied_pos >=0) {2914if(new_blank_lines_at_end &&2915 preimage.nr + applied_pos >= img->nr &&2916(ws_rule & WS_BLANK_AT_EOF) &&2917 ws_error_action != nowarn_ws_error) {2918record_ws_error(state, WS_BLANK_AT_EOF,"+",1,2919 found_new_blank_lines_at_end);2920if(ws_error_action == correct_ws_error) {2921while(new_blank_lines_at_end--)2922remove_last_line(&postimage);2923}2924/*2925 * We would want to prevent write_out_results()2926 * from taking place in apply_patch() that follows2927 * the callchain led us here, which is:2928 * apply_patch->check_patch_list->check_patch->2929 * apply_data->apply_fragments->apply_one_fragment2930 */2931if(ws_error_action == die_on_ws_error)2932 state->apply =0;2933}29342935if(state->apply_verbosely && applied_pos != pos) {2936int offset = applied_pos - pos;2937if(state->apply_in_reverse)2938 offset =0- offset;2939fprintf_ln(stderr,2940Q_("Hunk #%dsucceeded at%d(offset%dline).",2941"Hunk #%dsucceeded at%d(offset%dlines).",2942 offset),2943 nth_fragment, applied_pos +1, offset);2944}29452946/*2947 * Warn if it was necessary to reduce the number2948 * of context lines.2949 */2950if((leading != frag->leading) ||2951(trailing != frag->trailing))2952fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2953" to apply fragment at%d"),2954 leading, trailing, applied_pos+1);2955update_image(state, img, applied_pos, &preimage, &postimage);2956}else{2957if(state->apply_verbosely)2958error(_("while searching for:\n%.*s"),2959(int)(old - oldlines), oldlines);2960}29612962out:2963free(oldlines);2964strbuf_release(&newlines);2965free(preimage.line_allocated);2966free(postimage.line_allocated);29672968return(applied_pos <0);2969}29702971static intapply_binary_fragment(struct apply_state *state,2972struct image *img,2973struct patch *patch)2974{2975struct fragment *fragment = patch->fragments;2976unsigned long len;2977void*dst;29782979if(!fragment)2980returnerror(_("missing binary patch data for '%s'"),2981 patch->new_name ?2982 patch->new_name :2983 patch->old_name);29842985/* Binary patch is irreversible without the optional second hunk */2986if(state->apply_in_reverse) {2987if(!fragment->next)2988returnerror("cannot reverse-apply a binary patch "2989"without the reverse hunk to '%s'",2990 patch->new_name2991? patch->new_name : patch->old_name);2992 fragment = fragment->next;2993}2994switch(fragment->binary_patch_method) {2995case BINARY_DELTA_DEFLATED:2996 dst =patch_delta(img->buf, img->len, fragment->patch,2997 fragment->size, &len);2998if(!dst)2999return-1;3000clear_image(img);3001 img->buf = dst;3002 img->len = len;3003return0;3004case BINARY_LITERAL_DEFLATED:3005clear_image(img);3006 img->len = fragment->size;3007 img->buf =xmemdupz(fragment->patch, img->len);3008return0;3009}3010return-1;3011}30123013/*3014 * Replace "img" with the result of applying the binary patch.3015 * The binary patch data itself in patch->fragment is still kept3016 * but the preimage prepared by the caller in "img" is freed here3017 * or in the helper function apply_binary_fragment() this calls.3018 */3019static intapply_binary(struct apply_state *state,3020struct image *img,3021struct patch *patch)3022{3023const char*name = patch->old_name ? patch->old_name : patch->new_name;3024unsigned char sha1[20];30253026/*3027 * For safety, we require patch index line to contain3028 * full 40-byte textual SHA1 for old and new, at least for now.3029 */3030if(strlen(patch->old_sha1_prefix) !=40||3031strlen(patch->new_sha1_prefix) !=40||3032get_sha1_hex(patch->old_sha1_prefix, sha1) ||3033get_sha1_hex(patch->new_sha1_prefix, sha1))3034returnerror("cannot apply binary patch to '%s' "3035"without full index line", name);30363037if(patch->old_name) {3038/*3039 * See if the old one matches what the patch3040 * applies to.3041 */3042hash_sha1_file(img->buf, img->len, blob_type, sha1);3043if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3044returnerror("the patch applies to '%s' (%s), "3045"which does not match the "3046"current contents.",3047 name,sha1_to_hex(sha1));3048}3049else{3050/* Otherwise, the old one must be empty. */3051if(img->len)3052returnerror("the patch applies to an empty "3053"'%s' but it is not empty", name);3054}30553056get_sha1_hex(patch->new_sha1_prefix, sha1);3057if(is_null_sha1(sha1)) {3058clear_image(img);3059return0;/* deletion patch */3060}30613062if(has_sha1_file(sha1)) {3063/* We already have the postimage */3064enum object_type type;3065unsigned long size;3066char*result;30673068 result =read_sha1_file(sha1, &type, &size);3069if(!result)3070returnerror("the necessary postimage%sfor "3071"'%s' cannot be read",3072 patch->new_sha1_prefix, name);3073clear_image(img);3074 img->buf = result;3075 img->len = size;3076}else{3077/*3078 * We have verified buf matches the preimage;3079 * apply the patch data to it, which is stored3080 * in the patch->fragments->{patch,size}.3081 */3082if(apply_binary_fragment(state, img, patch))3083returnerror(_("binary patch does not apply to '%s'"),3084 name);30853086/* verify that the result matches */3087hash_sha1_file(img->buf, img->len, blob_type, sha1);3088if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3089returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3090 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3091}30923093return0;3094}30953096static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3097{3098struct fragment *frag = patch->fragments;3099const char*name = patch->old_name ? patch->old_name : patch->new_name;3100unsigned ws_rule = patch->ws_rule;3101unsigned inaccurate_eof = patch->inaccurate_eof;3102int nth =0;31033104if(patch->is_binary)3105returnapply_binary(state, img, patch);31063107while(frag) {3108 nth++;3109if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3110error(_("patch failed:%s:%ld"), name, frag->oldpos);3111if(!state->apply_with_reject)3112return-1;3113 frag->rejected =1;3114}3115 frag = frag->next;3116}3117return0;3118}31193120static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3121{3122if(S_ISGITLINK(mode)) {3123strbuf_grow(buf,100);3124strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3125}else{3126enum object_type type;3127unsigned long sz;3128char*result;31293130 result =read_sha1_file(sha1, &type, &sz);3131if(!result)3132return-1;3133/* XXX read_sha1_file NUL-terminates */3134strbuf_attach(buf, result, sz, sz +1);3135}3136return0;3137}31383139static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3140{3141if(!ce)3142return0;3143returnread_blob_object(buf, ce->sha1, ce->ce_mode);3144}31453146static struct patch *in_fn_table(const char*name)3147{3148struct string_list_item *item;31493150if(name == NULL)3151return NULL;31523153 item =string_list_lookup(&fn_table, name);3154if(item != NULL)3155return(struct patch *)item->util;31563157return NULL;3158}31593160/*3161 * item->util in the filename table records the status of the path.3162 * Usually it points at a patch (whose result records the contents3163 * of it after applying it), but it could be PATH_WAS_DELETED for a3164 * path that a previously applied patch has already removed, or3165 * PATH_TO_BE_DELETED for a path that a later patch would remove.3166 *3167 * The latter is needed to deal with a case where two paths A and B3168 * are swapped by first renaming A to B and then renaming B to A;3169 * moving A to B should not be prevented due to presence of B as we3170 * will remove it in a later patch.3171 */3172#define PATH_TO_BE_DELETED ((struct patch *) -2)3173#define PATH_WAS_DELETED ((struct patch *) -1)31743175static intto_be_deleted(struct patch *patch)3176{3177return patch == PATH_TO_BE_DELETED;3178}31793180static intwas_deleted(struct patch *patch)3181{3182return patch == PATH_WAS_DELETED;3183}31843185static voidadd_to_fn_table(struct patch *patch)3186{3187struct string_list_item *item;31883189/*3190 * Always add new_name unless patch is a deletion3191 * This should cover the cases for normal diffs,3192 * file creations and copies3193 */3194if(patch->new_name != NULL) {3195 item =string_list_insert(&fn_table, patch->new_name);3196 item->util = patch;3197}31983199/*3200 * store a failure on rename/deletion cases because3201 * later chunks shouldn't patch old names3202 */3203if((patch->new_name == NULL) || (patch->is_rename)) {3204 item =string_list_insert(&fn_table, patch->old_name);3205 item->util = PATH_WAS_DELETED;3206}3207}32083209static voidprepare_fn_table(struct patch *patch)3210{3211/*3212 * store information about incoming file deletion3213 */3214while(patch) {3215if((patch->new_name == NULL) || (patch->is_rename)) {3216struct string_list_item *item;3217 item =string_list_insert(&fn_table, patch->old_name);3218 item->util = PATH_TO_BE_DELETED;3219}3220 patch = patch->next;3221}3222}32233224static intcheckout_target(struct index_state *istate,3225struct cache_entry *ce,struct stat *st)3226{3227struct checkout costate;32283229memset(&costate,0,sizeof(costate));3230 costate.base_dir ="";3231 costate.refresh_cache =1;3232 costate.istate = istate;3233if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3234returnerror(_("cannot checkout%s"), ce->name);3235return0;3236}32373238static struct patch *previous_patch(struct patch *patch,int*gone)3239{3240struct patch *previous;32413242*gone =0;3243if(patch->is_copy || patch->is_rename)3244return NULL;/* "git" patches do not depend on the order */32453246 previous =in_fn_table(patch->old_name);3247if(!previous)3248return NULL;32493250if(to_be_deleted(previous))3251return NULL;/* the deletion hasn't happened yet */32523253if(was_deleted(previous))3254*gone =1;32553256return previous;3257}32583259static intverify_index_match(const struct cache_entry *ce,struct stat *st)3260{3261if(S_ISGITLINK(ce->ce_mode)) {3262if(!S_ISDIR(st->st_mode))3263return-1;3264return0;3265}3266returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3267}32683269#define SUBMODULE_PATCH_WITHOUT_INDEX 132703271static intload_patch_target(struct apply_state *state,3272struct strbuf *buf,3273const struct cache_entry *ce,3274struct stat *st,3275const char*name,3276unsigned expected_mode)3277{3278if(state->cached || state->check_index) {3279if(read_file_or_gitlink(ce, buf))3280returnerror(_("read of%sfailed"), name);3281}else if(name) {3282if(S_ISGITLINK(expected_mode)) {3283if(ce)3284returnread_file_or_gitlink(ce, buf);3285else3286return SUBMODULE_PATCH_WITHOUT_INDEX;3287}else if(has_symlink_leading_path(name,strlen(name))) {3288returnerror(_("reading from '%s' beyond a symbolic link"), name);3289}else{3290if(read_old_data(st, name, buf))3291returnerror(_("read of%sfailed"), name);3292}3293}3294return0;3295}32963297/*3298 * We are about to apply "patch"; populate the "image" with the3299 * current version we have, from the working tree or from the index,3300 * depending on the situation e.g. --cached/--index. If we are3301 * applying a non-git patch that incrementally updates the tree,3302 * we read from the result of a previous diff.3303 */3304static intload_preimage(struct apply_state *state,3305struct image *image,3306struct patch *patch,struct stat *st,3307const struct cache_entry *ce)3308{3309struct strbuf buf = STRBUF_INIT;3310size_t len;3311char*img;3312struct patch *previous;3313int status;33143315 previous =previous_patch(patch, &status);3316if(status)3317returnerror(_("path%shas been renamed/deleted"),3318 patch->old_name);3319if(previous) {3320/* We have a patched copy in memory; use that. */3321strbuf_add(&buf, previous->result, previous->resultsize);3322}else{3323 status =load_patch_target(state, &buf, ce, st,3324 patch->old_name, patch->old_mode);3325if(status <0)3326return status;3327else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3328/*3329 * There is no way to apply subproject3330 * patch without looking at the index.3331 * NEEDSWORK: shouldn't this be flagged3332 * as an error???3333 */3334free_fragment_list(patch->fragments);3335 patch->fragments = NULL;3336}else if(status) {3337returnerror(_("read of%sfailed"), patch->old_name);3338}3339}33403341 img =strbuf_detach(&buf, &len);3342prepare_image(image, img, len, !patch->is_binary);3343return0;3344}33453346static intthree_way_merge(struct image *image,3347char*path,3348const unsigned char*base,3349const unsigned char*ours,3350const unsigned char*theirs)3351{3352 mmfile_t base_file, our_file, their_file;3353 mmbuffer_t result = { NULL };3354int status;33553356read_mmblob(&base_file, base);3357read_mmblob(&our_file, ours);3358read_mmblob(&their_file, theirs);3359 status =ll_merge(&result, path,3360&base_file,"base",3361&our_file,"ours",3362&their_file,"theirs", NULL);3363free(base_file.ptr);3364free(our_file.ptr);3365free(their_file.ptr);3366if(status <0|| !result.ptr) {3367free(result.ptr);3368return-1;3369}3370clear_image(image);3371 image->buf = result.ptr;3372 image->len = result.size;33733374return status;3375}33763377/*3378 * When directly falling back to add/add three-way merge, we read from3379 * the current contents of the new_name. In no cases other than that3380 * this function will be called.3381 */3382static intload_current(struct apply_state *state,3383struct image *image,3384struct patch *patch)3385{3386struct strbuf buf = STRBUF_INIT;3387int status, pos;3388size_t len;3389char*img;3390struct stat st;3391struct cache_entry *ce;3392char*name = patch->new_name;3393unsigned mode = patch->new_mode;33943395if(!patch->is_new)3396die("BUG: patch to%sis not a creation", patch->old_name);33973398 pos =cache_name_pos(name,strlen(name));3399if(pos <0)3400returnerror(_("%s: does not exist in index"), name);3401 ce = active_cache[pos];3402if(lstat(name, &st)) {3403if(errno != ENOENT)3404returnerror(_("%s:%s"), name,strerror(errno));3405if(checkout_target(&the_index, ce, &st))3406return-1;3407}3408if(verify_index_match(ce, &st))3409returnerror(_("%s: does not match index"), name);34103411 status =load_patch_target(state, &buf, ce, &st, name, mode);3412if(status <0)3413return status;3414else if(status)3415return-1;3416 img =strbuf_detach(&buf, &len);3417prepare_image(image, img, len, !patch->is_binary);3418return0;3419}34203421static inttry_threeway(struct apply_state *state,3422struct image *image,3423struct patch *patch,3424struct stat *st,3425const struct cache_entry *ce)3426{3427unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3428struct strbuf buf = STRBUF_INIT;3429size_t len;3430int status;3431char*img;3432struct image tmp_image;34333434/* No point falling back to 3-way merge in these cases */3435if(patch->is_delete ||3436S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3437return-1;34383439/* Preimage the patch was prepared for */3440if(patch->is_new)3441write_sha1_file("",0, blob_type, pre_sha1);3442else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3443read_blob_object(&buf, pre_sha1, patch->old_mode))3444returnerror("repository lacks the necessary blob to fall back on 3-way merge.");34453446fprintf(stderr,"Falling back to three-way merge...\n");34473448 img =strbuf_detach(&buf, &len);3449prepare_image(&tmp_image, img, len,1);3450/* Apply the patch to get the post image */3451if(apply_fragments(state, &tmp_image, patch) <0) {3452clear_image(&tmp_image);3453return-1;3454}3455/* post_sha1[] is theirs */3456write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3457clear_image(&tmp_image);34583459/* our_sha1[] is ours */3460if(patch->is_new) {3461if(load_current(state, &tmp_image, patch))3462returnerror("cannot read the current contents of '%s'",3463 patch->new_name);3464}else{3465if(load_preimage(state, &tmp_image, patch, st, ce))3466returnerror("cannot read the current contents of '%s'",3467 patch->old_name);3468}3469write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3470clear_image(&tmp_image);34713472/* in-core three-way merge between post and our using pre as base */3473 status =three_way_merge(image, patch->new_name,3474 pre_sha1, our_sha1, post_sha1);3475if(status <0) {3476fprintf(stderr,"Failed to fall back on three-way merge...\n");3477return status;3478}34793480if(status) {3481 patch->conflicted_threeway =1;3482if(patch->is_new)3483oidclr(&patch->threeway_stage[0]);3484else3485hashcpy(patch->threeway_stage[0].hash, pre_sha1);3486hashcpy(patch->threeway_stage[1].hash, our_sha1);3487hashcpy(patch->threeway_stage[2].hash, post_sha1);3488fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3489}else{3490fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3491}3492return0;3493}34943495static intapply_data(struct apply_state *state,struct patch *patch,3496struct stat *st,const struct cache_entry *ce)3497{3498struct image image;34993500if(load_preimage(state, &image, patch, st, ce) <0)3501return-1;35023503if(patch->direct_to_threeway ||3504apply_fragments(state, &image, patch) <0) {3505/* Note: with --reject, apply_fragments() returns 0 */3506if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3507return-1;3508}3509 patch->result = image.buf;3510 patch->resultsize = image.len;3511add_to_fn_table(patch);3512free(image.line_allocated);35133514if(0< patch->is_delete && patch->resultsize)3515returnerror(_("removal patch leaves file contents"));35163517return0;3518}35193520/*3521 * If "patch" that we are looking at modifies or deletes what we have,3522 * we would want it not to lose any local modification we have, either3523 * in the working tree or in the index.3524 *3525 * This also decides if a non-git patch is a creation patch or a3526 * modification to an existing empty file. We do not check the state3527 * of the current tree for a creation patch in this function; the caller3528 * check_patch() separately makes sure (and errors out otherwise) that3529 * the path the patch creates does not exist in the current tree.3530 */3531static intcheck_preimage(struct apply_state *state,3532struct patch *patch,3533struct cache_entry **ce,3534struct stat *st)3535{3536const char*old_name = patch->old_name;3537struct patch *previous = NULL;3538int stat_ret =0, status;3539unsigned st_mode =0;35403541if(!old_name)3542return0;35433544assert(patch->is_new <=0);3545 previous =previous_patch(patch, &status);35463547if(status)3548returnerror(_("path%shas been renamed/deleted"), old_name);3549if(previous) {3550 st_mode = previous->new_mode;3551}else if(!state->cached) {3552 stat_ret =lstat(old_name, st);3553if(stat_ret && errno != ENOENT)3554returnerror(_("%s:%s"), old_name,strerror(errno));3555}35563557if(state->check_index && !previous) {3558int pos =cache_name_pos(old_name,strlen(old_name));3559if(pos <0) {3560if(patch->is_new <0)3561goto is_new;3562returnerror(_("%s: does not exist in index"), old_name);3563}3564*ce = active_cache[pos];3565if(stat_ret <0) {3566if(checkout_target(&the_index, *ce, st))3567return-1;3568}3569if(!state->cached &&verify_index_match(*ce, st))3570returnerror(_("%s: does not match index"), old_name);3571if(state->cached)3572 st_mode = (*ce)->ce_mode;3573}else if(stat_ret <0) {3574if(patch->is_new <0)3575goto is_new;3576returnerror(_("%s:%s"), old_name,strerror(errno));3577}35783579if(!state->cached && !previous)3580 st_mode =ce_mode_from_stat(*ce, st->st_mode);35813582if(patch->is_new <0)3583 patch->is_new =0;3584if(!patch->old_mode)3585 patch->old_mode = st_mode;3586if((st_mode ^ patch->old_mode) & S_IFMT)3587returnerror(_("%s: wrong type"), old_name);3588if(st_mode != patch->old_mode)3589warning(_("%shas type%o, expected%o"),3590 old_name, st_mode, patch->old_mode);3591if(!patch->new_mode && !patch->is_delete)3592 patch->new_mode = st_mode;3593return0;35943595 is_new:3596 patch->is_new =1;3597 patch->is_delete =0;3598free(patch->old_name);3599 patch->old_name = NULL;3600return0;3601}360236033604#define EXISTS_IN_INDEX 13605#define EXISTS_IN_WORKTREE 236063607static intcheck_to_create(struct apply_state *state,3608const char*new_name,3609int ok_if_exists)3610{3611struct stat nst;36123613if(state->check_index &&3614cache_name_pos(new_name,strlen(new_name)) >=0&&3615!ok_if_exists)3616return EXISTS_IN_INDEX;3617if(state->cached)3618return0;36193620if(!lstat(new_name, &nst)) {3621if(S_ISDIR(nst.st_mode) || ok_if_exists)3622return0;3623/*3624 * A leading component of new_name might be a symlink3625 * that is going to be removed with this patch, but3626 * still pointing at somewhere that has the path.3627 * In such a case, path "new_name" does not exist as3628 * far as git is concerned.3629 */3630if(has_symlink_leading_path(new_name,strlen(new_name)))3631return0;36323633return EXISTS_IN_WORKTREE;3634}else if((errno != ENOENT) && (errno != ENOTDIR)) {3635returnerror("%s:%s", new_name,strerror(errno));3636}3637return0;3638}36393640/*3641 * We need to keep track of how symlinks in the preimage are3642 * manipulated by the patches. A patch to add a/b/c where a/b3643 * is a symlink should not be allowed to affect the directory3644 * the symlink points at, but if the same patch removes a/b,3645 * it is perfectly fine, as the patch removes a/b to make room3646 * to create a directory a/b so that a/b/c can be created.3647 */3648static struct string_list symlink_changes;3649#define SYMLINK_GOES_AWAY 013650#define SYMLINK_IN_RESULT 0236513652static uintptr_tregister_symlink_changes(const char*path,uintptr_t what)3653{3654struct string_list_item *ent;36553656 ent =string_list_lookup(&symlink_changes, path);3657if(!ent) {3658 ent =string_list_insert(&symlink_changes, path);3659 ent->util = (void*)0;3660}3661 ent->util = (void*)(what | ((uintptr_t)ent->util));3662return(uintptr_t)ent->util;3663}36643665static uintptr_tcheck_symlink_changes(const char*path)3666{3667struct string_list_item *ent;36683669 ent =string_list_lookup(&symlink_changes, path);3670if(!ent)3671return0;3672return(uintptr_t)ent->util;3673}36743675static voidprepare_symlink_changes(struct patch *patch)3676{3677for( ; patch; patch = patch->next) {3678if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3679(patch->is_rename || patch->is_delete))3680/* the symlink at patch->old_name is removed */3681register_symlink_changes(patch->old_name, SYMLINK_GOES_AWAY);36823683if(patch->new_name &&S_ISLNK(patch->new_mode))3684/* the symlink at patch->new_name is created or remains */3685register_symlink_changes(patch->new_name, SYMLINK_IN_RESULT);3686}3687}36883689static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3690{3691do{3692unsigned int change;36933694while(--name->len && name->buf[name->len] !='/')3695;/* scan backwards */3696if(!name->len)3697break;3698 name->buf[name->len] ='\0';3699 change =check_symlink_changes(name->buf);3700if(change & SYMLINK_IN_RESULT)3701return1;3702if(change & SYMLINK_GOES_AWAY)3703/*3704 * This cannot be "return 0", because we may3705 * see a new one created at a higher level.3706 */3707continue;37083709/* otherwise, check the preimage */3710if(state->check_index) {3711struct cache_entry *ce;37123713 ce =cache_file_exists(name->buf, name->len, ignore_case);3714if(ce &&S_ISLNK(ce->ce_mode))3715return1;3716}else{3717struct stat st;3718if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3719return1;3720}3721}while(1);3722return0;3723}37243725static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3726{3727int ret;3728struct strbuf name = STRBUF_INIT;37293730assert(*name_ !='\0');3731strbuf_addstr(&name, name_);3732 ret =path_is_beyond_symlink_1(state, &name);3733strbuf_release(&name);37343735return ret;3736}37373738static voiddie_on_unsafe_path(struct patch *patch)3739{3740const char*old_name = NULL;3741const char*new_name = NULL;3742if(patch->is_delete)3743 old_name = patch->old_name;3744else if(!patch->is_new && !patch->is_copy)3745 old_name = patch->old_name;3746if(!patch->is_delete)3747 new_name = patch->new_name;37483749if(old_name && !verify_path(old_name))3750die(_("invalid path '%s'"), old_name);3751if(new_name && !verify_path(new_name))3752die(_("invalid path '%s'"), new_name);3753}37543755/*3756 * Check and apply the patch in-core; leave the result in patch->result3757 * for the caller to write it out to the final destination.3758 */3759static intcheck_patch(struct apply_state *state,struct patch *patch)3760{3761struct stat st;3762const char*old_name = patch->old_name;3763const char*new_name = patch->new_name;3764const char*name = old_name ? old_name : new_name;3765struct cache_entry *ce = NULL;3766struct patch *tpatch;3767int ok_if_exists;3768int status;37693770 patch->rejected =1;/* we will drop this after we succeed */37713772 status =check_preimage(state, patch, &ce, &st);3773if(status)3774return status;3775 old_name = patch->old_name;37763777/*3778 * A type-change diff is always split into a patch to delete3779 * old, immediately followed by a patch to create new (see3780 * diff.c::run_diff()); in such a case it is Ok that the entry3781 * to be deleted by the previous patch is still in the working3782 * tree and in the index.3783 *3784 * A patch to swap-rename between A and B would first rename A3785 * to B and then rename B to A. While applying the first one,3786 * the presence of B should not stop A from getting renamed to3787 * B; ask to_be_deleted() about the later rename. Removal of3788 * B and rename from A to B is handled the same way by asking3789 * was_deleted().3790 */3791if((tpatch =in_fn_table(new_name)) &&3792(was_deleted(tpatch) ||to_be_deleted(tpatch)))3793 ok_if_exists =1;3794else3795 ok_if_exists =0;37963797if(new_name &&3798((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3799int err =check_to_create(state, new_name, ok_if_exists);38003801if(err && state->threeway) {3802 patch->direct_to_threeway =1;3803}else switch(err) {3804case0:3805break;/* happy */3806case EXISTS_IN_INDEX:3807returnerror(_("%s: already exists in index"), new_name);3808break;3809case EXISTS_IN_WORKTREE:3810returnerror(_("%s: already exists in working directory"),3811 new_name);3812default:3813return err;3814}38153816if(!patch->new_mode) {3817if(0< patch->is_new)3818 patch->new_mode = S_IFREG |0644;3819else3820 patch->new_mode = patch->old_mode;3821}3822}38233824if(new_name && old_name) {3825int same = !strcmp(old_name, new_name);3826if(!patch->new_mode)3827 patch->new_mode = patch->old_mode;3828if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3829if(same)3830returnerror(_("new mode (%o) of%sdoes not "3831"match old mode (%o)"),3832 patch->new_mode, new_name,3833 patch->old_mode);3834else3835returnerror(_("new mode (%o) of%sdoes not "3836"match old mode (%o) of%s"),3837 patch->new_mode, new_name,3838 patch->old_mode, old_name);3839}3840}38413842if(!state->unsafe_paths)3843die_on_unsafe_path(patch);38443845/*3846 * An attempt to read from or delete a path that is beyond a3847 * symbolic link will be prevented by load_patch_target() that3848 * is called at the beginning of apply_data() so we do not3849 * have to worry about a patch marked with "is_delete" bit3850 * here. We however need to make sure that the patch result3851 * is not deposited to a path that is beyond a symbolic link3852 * here.3853 */3854if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3855returnerror(_("affected file '%s' is beyond a symbolic link"),3856 patch->new_name);38573858if(apply_data(state, patch, &st, ce) <0)3859returnerror(_("%s: patch does not apply"), name);3860 patch->rejected =0;3861return0;3862}38633864static intcheck_patch_list(struct apply_state *state,struct patch *patch)3865{3866int err =0;38673868prepare_symlink_changes(patch);3869prepare_fn_table(patch);3870while(patch) {3871if(state->apply_verbosely)3872say_patch_name(stderr,3873_("Checking patch%s..."), patch);3874 err |=check_patch(state, patch);3875 patch = patch->next;3876}3877return err;3878}38793880/* This function tries to read the sha1 from the current index */3881static intget_current_sha1(const char*path,unsigned char*sha1)3882{3883int pos;38843885if(read_cache() <0)3886return-1;3887 pos =cache_name_pos(path,strlen(path));3888if(pos <0)3889return-1;3890hashcpy(sha1, active_cache[pos]->sha1);3891return0;3892}38933894static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3895{3896/*3897 * A usable gitlink patch has only one fragment (hunk) that looks like:3898 * @@ -1 +1 @@3899 * -Subproject commit <old sha1>3900 * +Subproject commit <new sha1>3901 * or3902 * @@ -1 +0,0 @@3903 * -Subproject commit <old sha1>3904 * for a removal patch.3905 */3906struct fragment *hunk = p->fragments;3907static const char heading[] ="-Subproject commit ";3908char*preimage;39093910if(/* does the patch have only one hunk? */3911 hunk && !hunk->next &&3912/* is its preimage one line? */3913 hunk->oldpos ==1&& hunk->oldlines ==1&&3914/* does preimage begin with the heading? */3915(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3916starts_with(++preimage, heading) &&3917/* does it record full SHA-1? */3918!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3919 preimage[sizeof(heading) +40-1] =='\n'&&3920/* does the abbreviated name on the index line agree with it? */3921starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3922return0;/* it all looks fine */39233924/* we may have full object name on the index line */3925returnget_sha1_hex(p->old_sha1_prefix, sha1);3926}39273928/* Build an index that contains the just the files needed for a 3way merge */3929static voidbuild_fake_ancestor(struct patch *list,const char*filename)3930{3931struct patch *patch;3932struct index_state result = { NULL };3933static struct lock_file lock;39343935/* Once we start supporting the reverse patch, it may be3936 * worth showing the new sha1 prefix, but until then...3937 */3938for(patch = list; patch; patch = patch->next) {3939unsigned char sha1[20];3940struct cache_entry *ce;3941const char*name;39423943 name = patch->old_name ? patch->old_name : patch->new_name;3944if(0< patch->is_new)3945continue;39463947if(S_ISGITLINK(patch->old_mode)) {3948if(!preimage_sha1_in_gitlink_patch(patch, sha1))3949;/* ok, the textual part looks sane */3950else3951die("sha1 information is lacking or useless for submodule%s",3952 name);3953}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {3954;/* ok */3955}else if(!patch->lines_added && !patch->lines_deleted) {3956/* mode-only change: update the current */3957if(get_current_sha1(patch->old_name, sha1))3958die("mode change for%s, which is not "3959"in current HEAD", name);3960}else3961die("sha1 information is lacking or useless "3962"(%s).", name);39633964 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);3965if(!ce)3966die(_("make_cache_entry failed for path '%s'"), name);3967if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3968die("Could not add%sto temporary index", name);3969}39703971hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);3972if(write_locked_index(&result, &lock, COMMIT_LOCK))3973die("Could not write temporary index to%s", filename);39743975discard_index(&result);3976}39773978static voidstat_patch_list(struct patch *patch)3979{3980int files, adds, dels;39813982for(files = adds = dels =0; patch ; patch = patch->next) {3983 files++;3984 adds += patch->lines_added;3985 dels += patch->lines_deleted;3986show_stats(patch);3987}39883989print_stat_summary(stdout, files, adds, dels);3990}39913992static voidnumstat_patch_list(struct apply_state *state,3993struct patch *patch)3994{3995for( ; patch; patch = patch->next) {3996const char*name;3997 name = patch->new_name ? patch->new_name : patch->old_name;3998if(patch->is_binary)3999printf("-\t-\t");4000else4001printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4002write_name_quoted(name, stdout, state->line_termination);4003}4004}40054006static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4007{4008if(mode)4009printf("%smode%06o%s\n", newdelete, mode, name);4010else4011printf("%s %s\n", newdelete, name);4012}40134014static voidshow_mode_change(struct patch *p,int show_name)4015{4016if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4017if(show_name)4018printf(" mode change%06o =>%06o%s\n",4019 p->old_mode, p->new_mode, p->new_name);4020else4021printf(" mode change%06o =>%06o\n",4022 p->old_mode, p->new_mode);4023}4024}40254026static voidshow_rename_copy(struct patch *p)4027{4028const char*renamecopy = p->is_rename ?"rename":"copy";4029const char*old, *new;40304031/* Find common prefix */4032 old = p->old_name;4033new= p->new_name;4034while(1) {4035const char*slash_old, *slash_new;4036 slash_old =strchr(old,'/');4037 slash_new =strchr(new,'/');4038if(!slash_old ||4039!slash_new ||4040 slash_old - old != slash_new -new||4041memcmp(old,new, slash_new -new))4042break;4043 old = slash_old +1;4044new= slash_new +1;4045}4046/* p->old_name thru old is the common prefix, and old and new4047 * through the end of names are renames4048 */4049if(old != p->old_name)4050printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4051(int)(old - p->old_name), p->old_name,4052 old,new, p->score);4053else4054printf("%s %s=>%s(%d%%)\n", renamecopy,4055 p->old_name, p->new_name, p->score);4056show_mode_change(p,0);4057}40584059static voidsummary_patch_list(struct patch *patch)4060{4061struct patch *p;40624063for(p = patch; p; p = p->next) {4064if(p->is_new)4065show_file_mode_name("create", p->new_mode, p->new_name);4066else if(p->is_delete)4067show_file_mode_name("delete", p->old_mode, p->old_name);4068else{4069if(p->is_rename || p->is_copy)4070show_rename_copy(p);4071else{4072if(p->score) {4073printf(" rewrite%s(%d%%)\n",4074 p->new_name, p->score);4075show_mode_change(p,0);4076}4077else4078show_mode_change(p,1);4079}4080}4081}4082}40834084static voidpatch_stats(struct patch *patch)4085{4086int lines = patch->lines_added + patch->lines_deleted;40874088if(lines > max_change)4089 max_change = lines;4090if(patch->old_name) {4091int len =quote_c_style(patch->old_name, NULL, NULL,0);4092if(!len)4093 len =strlen(patch->old_name);4094if(len > max_len)4095 max_len = len;4096}4097if(patch->new_name) {4098int len =quote_c_style(patch->new_name, NULL, NULL,0);4099if(!len)4100 len =strlen(patch->new_name);4101if(len > max_len)4102 max_len = len;4103}4104}41054106static voidremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4107{4108if(state->update_index) {4109if(remove_file_from_cache(patch->old_name) <0)4110die(_("unable to remove%sfrom index"), patch->old_name);4111}4112if(!state->cached) {4113if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4114remove_path(patch->old_name);4115}4116}4117}41184119static voidadd_index_file(struct apply_state *state,4120const char*path,4121unsigned mode,4122void*buf,4123unsigned long size)4124{4125struct stat st;4126struct cache_entry *ce;4127int namelen =strlen(path);4128unsigned ce_size =cache_entry_size(namelen);41294130if(!state->update_index)4131return;41324133 ce =xcalloc(1, ce_size);4134memcpy(ce->name, path, namelen);4135 ce->ce_mode =create_ce_mode(mode);4136 ce->ce_flags =create_ce_flags(0);4137 ce->ce_namelen = namelen;4138if(S_ISGITLINK(mode)) {4139const char*s;41404141if(!skip_prefix(buf,"Subproject commit ", &s) ||4142get_sha1_hex(s, ce->sha1))4143die(_("corrupt patch for submodule%s"), path);4144}else{4145if(!state->cached) {4146if(lstat(path, &st) <0)4147die_errno(_("unable to stat newly created file '%s'"),4148 path);4149fill_stat_cache_info(ce, &st);4150}4151if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4152die(_("unable to create backing store for newly created file%s"), path);4153}4154if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4155die(_("unable to add cache entry for%s"), path);4156}41574158static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4159{4160int fd;4161struct strbuf nbuf = STRBUF_INIT;41624163if(S_ISGITLINK(mode)) {4164struct stat st;4165if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4166return0;4167returnmkdir(path,0777);4168}41694170if(has_symlinks &&S_ISLNK(mode))4171/* Although buf:size is counted string, it also is NUL4172 * terminated.4173 */4174returnsymlink(buf, path);41754176 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4177if(fd <0)4178return-1;41794180if(convert_to_working_tree(path, buf, size, &nbuf)) {4181 size = nbuf.len;4182 buf = nbuf.buf;4183}4184write_or_die(fd, buf, size);4185strbuf_release(&nbuf);41864187if(close(fd) <0)4188die_errno(_("closing file '%s'"), path);4189return0;4190}41914192/*4193 * We optimistically assume that the directories exist,4194 * which is true 99% of the time anyway. If they don't,4195 * we create them and try again.4196 */4197static voidcreate_one_file(struct apply_state *state,4198char*path,4199unsigned mode,4200const char*buf,4201unsigned long size)4202{4203if(state->cached)4204return;4205if(!try_create_file(path, mode, buf, size))4206return;42074208if(errno == ENOENT) {4209if(safe_create_leading_directories(path))4210return;4211if(!try_create_file(path, mode, buf, size))4212return;4213}42144215if(errno == EEXIST || errno == EACCES) {4216/* We may be trying to create a file where a directory4217 * used to be.4218 */4219struct stat st;4220if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4221 errno = EEXIST;4222}42234224if(errno == EEXIST) {4225unsigned int nr =getpid();42264227for(;;) {4228char newpath[PATH_MAX];4229mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4230if(!try_create_file(newpath, mode, buf, size)) {4231if(!rename(newpath, path))4232return;4233unlink_or_warn(newpath);4234break;4235}4236if(errno != EEXIST)4237break;4238++nr;4239}4240}4241die_errno(_("unable to write file '%s' mode%o"), path, mode);4242}42434244static voidadd_conflicted_stages_file(struct apply_state *state,4245struct patch *patch)4246{4247int stage, namelen;4248unsigned ce_size, mode;4249struct cache_entry *ce;42504251if(!state->update_index)4252return;4253 namelen =strlen(patch->new_name);4254 ce_size =cache_entry_size(namelen);4255 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);42564257remove_file_from_cache(patch->new_name);4258for(stage =1; stage <4; stage++) {4259if(is_null_oid(&patch->threeway_stage[stage -1]))4260continue;4261 ce =xcalloc(1, ce_size);4262memcpy(ce->name, patch->new_name, namelen);4263 ce->ce_mode =create_ce_mode(mode);4264 ce->ce_flags =create_ce_flags(stage);4265 ce->ce_namelen = namelen;4266hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4267if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4268die(_("unable to add cache entry for%s"), patch->new_name);4269}4270}42714272static voidcreate_file(struct apply_state *state,struct patch *patch)4273{4274char*path = patch->new_name;4275unsigned mode = patch->new_mode;4276unsigned long size = patch->resultsize;4277char*buf = patch->result;42784279if(!mode)4280 mode = S_IFREG |0644;4281create_one_file(state, path, mode, buf, size);42824283if(patch->conflicted_threeway)4284add_conflicted_stages_file(state, patch);4285else4286add_index_file(state, path, mode, buf, size);4287}42884289/* phase zero is to remove, phase one is to create */4290static voidwrite_out_one_result(struct apply_state *state,4291struct patch *patch,4292int phase)4293{4294if(patch->is_delete >0) {4295if(phase ==0)4296remove_file(state, patch,1);4297return;4298}4299if(patch->is_new >0|| patch->is_copy) {4300if(phase ==1)4301create_file(state, patch);4302return;4303}4304/*4305 * Rename or modification boils down to the same4306 * thing: remove the old, write the new4307 */4308if(phase ==0)4309remove_file(state, patch, patch->is_rename);4310if(phase ==1)4311create_file(state, patch);4312}43134314static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4315{4316FILE*rej;4317char namebuf[PATH_MAX];4318struct fragment *frag;4319int cnt =0;4320struct strbuf sb = STRBUF_INIT;43214322for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4323if(!frag->rejected)4324continue;4325 cnt++;4326}43274328if(!cnt) {4329if(state->apply_verbosely)4330say_patch_name(stderr,4331_("Applied patch%scleanly."), patch);4332return0;4333}43344335/* This should not happen, because a removal patch that leaves4336 * contents are marked "rejected" at the patch level.4337 */4338if(!patch->new_name)4339die(_("internal error"));43404341/* Say this even without --verbose */4342strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4343"Applying patch %%swith%drejects...",4344 cnt),4345 cnt);4346say_patch_name(stderr, sb.buf, patch);4347strbuf_release(&sb);43484349 cnt =strlen(patch->new_name);4350if(ARRAY_SIZE(namebuf) <= cnt +5) {4351 cnt =ARRAY_SIZE(namebuf) -5;4352warning(_("truncating .rej filename to %.*s.rej"),4353 cnt -1, patch->new_name);4354}4355memcpy(namebuf, patch->new_name, cnt);4356memcpy(namebuf + cnt,".rej",5);43574358 rej =fopen(namebuf,"w");4359if(!rej)4360returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));43614362/* Normal git tools never deal with .rej, so do not pretend4363 * this is a git patch by saying --git or giving extended4364 * headers. While at it, maybe please "kompare" that wants4365 * the trailing TAB and some garbage at the end of line ;-).4366 */4367fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4368 patch->new_name, patch->new_name);4369for(cnt =1, frag = patch->fragments;4370 frag;4371 cnt++, frag = frag->next) {4372if(!frag->rejected) {4373fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4374continue;4375}4376fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4377fprintf(rej,"%.*s", frag->size, frag->patch);4378if(frag->patch[frag->size-1] !='\n')4379fputc('\n', rej);4380}4381fclose(rej);4382return-1;4383}43844385static intwrite_out_results(struct apply_state *state,struct patch *list)4386{4387int phase;4388int errs =0;4389struct patch *l;4390struct string_list cpath = STRING_LIST_INIT_DUP;43914392for(phase =0; phase <2; phase++) {4393 l = list;4394while(l) {4395if(l->rejected)4396 errs =1;4397else{4398write_out_one_result(state, l, phase);4399if(phase ==1) {4400if(write_out_one_reject(state, l))4401 errs =1;4402if(l->conflicted_threeway) {4403string_list_append(&cpath, l->new_name);4404 errs =1;4405}4406}4407}4408 l = l->next;4409}4410}44114412if(cpath.nr) {4413struct string_list_item *item;44144415string_list_sort(&cpath);4416for_each_string_list_item(item, &cpath)4417fprintf(stderr,"U%s\n", item->string);4418string_list_clear(&cpath,0);44194420rerere(0);4421}44224423return errs;4424}44254426static struct lock_file lock_file;44274428#define INACCURATE_EOF (1<<0)4429#define RECOUNT (1<<1)44304431static intapply_patch(struct apply_state *state,4432int fd,4433const char*filename,4434int options)4435{4436size_t offset;4437struct strbuf buf = STRBUF_INIT;/* owns the patch text */4438struct patch *list = NULL, **listp = &list;4439int skipped_patch =0;44404441 state->patch_input_file = filename;4442read_patch_file(&buf, fd);4443 offset =0;4444while(offset < buf.len) {4445struct patch *patch;4446int nr;44474448 patch =xcalloc(1,sizeof(*patch));4449 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4450 patch->recount = !!(options & RECOUNT);4451 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4452if(nr <0) {4453free_patch(patch);4454break;4455}4456if(state->apply_in_reverse)4457reverse_patches(patch);4458if(use_patch(state, patch)) {4459patch_stats(patch);4460*listp = patch;4461 listp = &patch->next;4462}4463else{4464if(state->apply_verbosely)4465say_patch_name(stderr,_("Skipped patch '%s'."), patch);4466free_patch(patch);4467 skipped_patch++;4468}4469 offset += nr;4470}44714472if(!list && !skipped_patch)4473die(_("unrecognized input"));44744475if(whitespace_error && (ws_error_action == die_on_ws_error))4476 state->apply =0;44774478 state->update_index = state->check_index && state->apply;4479if(state->update_index && newfd <0)4480 newfd =hold_locked_index(&lock_file,1);44814482if(state->check_index) {4483if(read_cache() <0)4484die(_("unable to read index file"));4485}44864487if((state->check || state->apply) &&4488check_patch_list(state, list) <0&&4489!state->apply_with_reject)4490exit(1);44914492if(state->apply &&write_out_results(state, list)) {4493if(state->apply_with_reject)4494exit(1);4495/* with --3way, we still need to write the index out */4496return1;4497}44984499if(state->fake_ancestor)4500build_fake_ancestor(list, state->fake_ancestor);45014502if(state->diffstat)4503stat_patch_list(list);45044505if(state->numstat)4506numstat_patch_list(state, list);45074508if(state->summary)4509summary_patch_list(list);45104511free_patch_list(list);4512strbuf_release(&buf);4513string_list_clear(&fn_table,0);4514return0;4515}45164517static voidgit_apply_config(void)4518{4519git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4520git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4521git_config(git_default_config, NULL);4522}45234524static intoption_parse_exclude(const struct option *opt,4525const char*arg,int unset)4526{4527struct apply_state *state = opt->value;4528add_name_limit(state, arg,1);4529return0;4530}45314532static intoption_parse_include(const struct option *opt,4533const char*arg,int unset)4534{4535struct apply_state *state = opt->value;4536add_name_limit(state, arg,0);4537 has_include =1;4538return0;4539}45404541static intoption_parse_p(const struct option *opt,4542const char*arg,int unset)4543{4544 state_p_value =atoi(arg);4545 p_value_known =1;4546return0;4547}45484549static intoption_parse_space_change(const struct option *opt,4550const char*arg,int unset)4551{4552if(unset)4553 ws_ignore_action = ignore_ws_none;4554else4555 ws_ignore_action = ignore_ws_change;4556return0;4557}45584559static intoption_parse_whitespace(const struct option *opt,4560const char*arg,int unset)4561{4562const char**whitespace_option = opt->value;45634564*whitespace_option = arg;4565parse_whitespace_option(arg);4566return0;4567}45684569static intoption_parse_directory(const struct option *opt,4570const char*arg,int unset)4571{4572strbuf_reset(&root);4573strbuf_addstr(&root, arg);4574strbuf_complete(&root,'/');4575return0;4576}45774578static voidinit_apply_state(struct apply_state *state,const char*prefix)4579{4580memset(state,0,sizeof(*state));4581 state->prefix = prefix;4582 state->prefix_length = state->prefix ?strlen(state->prefix) :0;4583 state->apply =1;4584 state->line_termination ='\n';4585 state->p_context = UINT_MAX;45864587git_apply_config();4588if(apply_default_whitespace)4589parse_whitespace_option(apply_default_whitespace);4590if(apply_default_ignorewhitespace)4591parse_ignorewhitespace_option(apply_default_ignorewhitespace);4592}45934594static voidclear_apply_state(struct apply_state *state)4595{4596string_list_clear(&state->limit_by_name,0);4597}45984599intcmd_apply(int argc,const char**argv,const char*prefix)4600{4601int i;4602int errs =0;4603int is_not_gitdir = !startup_info->have_repository;4604int force_apply =0;4605int options =0;4606int read_stdin =1;4607struct apply_state state;46084609const char*whitespace_option = NULL;46104611struct option builtin_apply_options[] = {4612{ OPTION_CALLBACK,0,"exclude", &state,N_("path"),4613N_("don't apply changes matching the given path"),46140, option_parse_exclude },4615{ OPTION_CALLBACK,0,"include", &state,N_("path"),4616N_("apply changes matching the given path"),46170, option_parse_include },4618{ OPTION_CALLBACK,'p', NULL, NULL,N_("num"),4619N_("remove <num> leading slashes from traditional diff paths"),46200, option_parse_p },4621OPT_BOOL(0,"no-add", &state.no_add,4622N_("ignore additions made by the patch")),4623OPT_BOOL(0,"stat", &state.diffstat,4624N_("instead of applying the patch, output diffstat for the input")),4625OPT_NOOP_NOARG(0,"allow-binary-replacement"),4626OPT_NOOP_NOARG(0,"binary"),4627OPT_BOOL(0,"numstat", &state.numstat,4628N_("show number of added and deleted lines in decimal notation")),4629OPT_BOOL(0,"summary", &state.summary,4630N_("instead of applying the patch, output a summary for the input")),4631OPT_BOOL(0,"check", &state.check,4632N_("instead of applying the patch, see if the patch is applicable")),4633OPT_BOOL(0,"index", &state.check_index,4634N_("make sure the patch is applicable to the current index")),4635OPT_BOOL(0,"cached", &state.cached,4636N_("apply a patch without touching the working tree")),4637OPT_BOOL(0,"unsafe-paths", &state.unsafe_paths,4638N_("accept a patch that touches outside the working area")),4639OPT_BOOL(0,"apply", &force_apply,4640N_("also apply the patch (use with --stat/--summary/--check)")),4641OPT_BOOL('3',"3way", &state.threeway,4642N_("attempt three-way merge if a patch does not apply")),4643OPT_FILENAME(0,"build-fake-ancestor", &state.fake_ancestor,4644N_("build a temporary index based on embedded index information")),4645/* Think twice before adding "--nul" synonym to this */4646OPT_SET_INT('z', NULL, &state.line_termination,4647N_("paths are separated with NUL character"),'\0'),4648OPT_INTEGER('C', NULL, &state.p_context,4649N_("ensure at least <n> lines of context match")),4650{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,N_("action"),4651N_("detect new or modified lines that have whitespace errors"),46520, option_parse_whitespace },4653{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,4654N_("ignore changes in whitespace when finding context"),4655 PARSE_OPT_NOARG, option_parse_space_change },4656{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,4657N_("ignore changes in whitespace when finding context"),4658 PARSE_OPT_NOARG, option_parse_space_change },4659OPT_BOOL('R',"reverse", &state.apply_in_reverse,4660N_("apply the patch in reverse")),4661OPT_BOOL(0,"unidiff-zero", &state.unidiff_zero,4662N_("don't expect at least one line of context")),4663OPT_BOOL(0,"reject", &state.apply_with_reject,4664N_("leave the rejected hunks in corresponding *.rej files")),4665OPT_BOOL(0,"allow-overlap", &state.allow_overlap,4666N_("allow overlapping hunks")),4667OPT__VERBOSE(&state.apply_verbosely,N_("be verbose")),4668OPT_BIT(0,"inaccurate-eof", &options,4669N_("tolerate incorrectly detected missing new-line at the end of file"),4670 INACCURATE_EOF),4671OPT_BIT(0,"recount", &options,4672N_("do not trust the line counts in the hunk headers"),4673 RECOUNT),4674{ OPTION_CALLBACK,0,"directory", NULL,N_("root"),4675N_("prepend <root> to all filenames"),46760, option_parse_directory },4677OPT_END()4678};46794680init_apply_state(&state, prefix);46814682 argc =parse_options(argc, argv, state.prefix, builtin_apply_options,4683 apply_usage,0);46844685if(state.apply_with_reject && state.threeway)4686die("--reject and --3way cannot be used together.");4687if(state.cached && state.threeway)4688die("--cached and --3way cannot be used together.");4689if(state.threeway) {4690if(is_not_gitdir)4691die(_("--3way outside a repository"));4692 state.check_index =1;4693}4694if(state.apply_with_reject)4695 state.apply = state.apply_verbosely =1;4696if(!force_apply && (state.diffstat || state.numstat || state.summary || state.check || state.fake_ancestor))4697 state.apply =0;4698if(state.check_index && is_not_gitdir)4699die(_("--index outside a repository"));4700if(state.cached) {4701if(is_not_gitdir)4702die(_("--cached outside a repository"));4703 state.check_index =1;4704}4705if(state.check_index)4706 state.unsafe_paths =0;47074708for(i =0; i < argc; i++) {4709const char*arg = argv[i];4710int fd;47114712if(!strcmp(arg,"-")) {4713 errs |=apply_patch(&state,0,"<stdin>", options);4714 read_stdin =0;4715continue;4716}else if(0< state.prefix_length)4717 arg =prefix_filename(state.prefix,4718 state.prefix_length,4719 arg);47204721 fd =open(arg, O_RDONLY);4722if(fd <0)4723die_errno(_("can't open patch '%s'"), arg);4724 read_stdin =0;4725set_default_whitespace_mode(&state, whitespace_option);4726 errs |=apply_patch(&state, fd, arg, options);4727close(fd);4728}4729set_default_whitespace_mode(&state, whitespace_option);4730if(read_stdin)4731 errs |=apply_patch(&state,0,"<stdin>", options);4732if(whitespace_error) {4733if(squelch_whitespace_errors &&4734 squelch_whitespace_errors < whitespace_error) {4735int squelched =4736 whitespace_error - squelch_whitespace_errors;4737warning(Q_("squelched%dwhitespace error",4738"squelched%dwhitespace errors",4739 squelched),4740 squelched);4741}4742if(ws_error_action == die_on_ws_error)4743die(Q_("%dline adds whitespace errors.",4744"%dlines add whitespace errors.",4745 whitespace_error),4746 whitespace_error);4747if(applied_after_fixing_ws && state.apply)4748warning("%dline%sapplied after"4749" fixing whitespace errors.",4750 applied_after_fixing_ws,4751 applied_after_fixing_ws ==1?"":"s");4752else if(whitespace_error)4753warning(Q_("%dline adds whitespace errors.",4754"%dlines add whitespace errors.",4755 whitespace_error),4756 whitespace_error);4757}47584759if(state.update_index) {4760if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK))4761die(_("Unable to write new index file"));4762}47634764clear_apply_state(&state);47654766return!!errs;4767}