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 29/* 30 * --check turns on checking that the working tree matches the 31 * files that are being modified, but doesn't apply the patch 32 * --stat does just a diffstat, and doesn't actually apply 33 * --numstat does numeric diffstat, and doesn't actually apply 34 * --index-info shows the old and new index info for paths if available. 35 * --index updates the cache as well. 36 * --cached updates only the cache without ever touching the working tree. 37 */ 38static int newfd = -1; 39 40static int unidiff_zero; 41static int state_p_value =1; 42static int p_value_known; 43static int check_index; 44static int update_index; 45static int cached; 46static int diffstat; 47static int numstat; 48static int summary; 49static int check; 50static int apply =1; 51static int apply_in_reverse; 52static int apply_with_reject; 53static int apply_verbosely; 54static int allow_overlap; 55static int no_add; 56static int threeway; 57static int unsafe_paths; 58static const char*fake_ancestor; 59static int line_termination ='\n'; 60static unsigned int p_context = UINT_MAX; 61static const char*const apply_usage[] = { 62N_("git apply [<options>] [<patch>...]"), 63 NULL 64}; 65 66static enum ws_error_action { 67 nowarn_ws_error, 68 warn_on_ws_error, 69 die_on_ws_error, 70 correct_ws_error 71} ws_error_action = warn_on_ws_error; 72static int whitespace_error; 73static int squelch_whitespace_errors =5; 74static int applied_after_fixing_ws; 75 76static enum ws_ignore { 77 ignore_ws_none, 78 ignore_ws_change 79} ws_ignore_action = ignore_ws_none; 80 81 82static const char*patch_input_file; 83static struct strbuf root = STRBUF_INIT; 84 85static voidparse_whitespace_option(const char*option) 86{ 87if(!option) { 88 ws_error_action = warn_on_ws_error; 89return; 90} 91if(!strcmp(option,"warn")) { 92 ws_error_action = warn_on_ws_error; 93return; 94} 95if(!strcmp(option,"nowarn")) { 96 ws_error_action = nowarn_ws_error; 97return; 98} 99if(!strcmp(option,"error")) { 100 ws_error_action = die_on_ws_error; 101return; 102} 103if(!strcmp(option,"error-all")) { 104 ws_error_action = die_on_ws_error; 105 squelch_whitespace_errors =0; 106return; 107} 108if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 109 ws_error_action = correct_ws_error; 110return; 111} 112die(_("unrecognized whitespace option '%s'"), option); 113} 114 115static voidparse_ignorewhitespace_option(const char*option) 116{ 117if(!option || !strcmp(option,"no") || 118!strcmp(option,"false") || !strcmp(option,"never") || 119!strcmp(option,"none")) { 120 ws_ignore_action = ignore_ws_none; 121return; 122} 123if(!strcmp(option,"change")) { 124 ws_ignore_action = ignore_ws_change; 125return; 126} 127die(_("unrecognized whitespace ignore option '%s'"), option); 128} 129 130static voidset_default_whitespace_mode(const char*whitespace_option) 131{ 132if(!whitespace_option && !apply_default_whitespace) 133 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 134} 135 136/* 137 * For "diff-stat" like behaviour, we keep track of the biggest change 138 * we've seen, and the longest filename. That allows us to do simple 139 * scaling. 140 */ 141static int max_change, max_len; 142 143/* 144 * Various "current state", notably line numbers and what 145 * file (and how) we're patching right now.. The "is_xxxx" 146 * things are flags, where -1 means "don't know yet". 147 */ 148static int state_linenr =1; 149 150/* 151 * This represents one "hunk" from a patch, starting with 152 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 153 * patch text is pointed at by patch, and its byte length 154 * is stored in size. leading and trailing are the number 155 * of context lines. 156 */ 157struct fragment { 158unsigned long leading, trailing; 159unsigned long oldpos, oldlines; 160unsigned long newpos, newlines; 161/* 162 * 'patch' is usually borrowed from buf in apply_patch(), 163 * but some codepaths store an allocated buffer. 164 */ 165const char*patch; 166unsigned free_patch:1, 167 rejected:1; 168int size; 169int linenr; 170struct fragment *next; 171}; 172 173/* 174 * When dealing with a binary patch, we reuse "leading" field 175 * to store the type of the binary hunk, either deflated "delta" 176 * or deflated "literal". 177 */ 178#define binary_patch_method leading 179#define BINARY_DELTA_DEFLATED 1 180#define BINARY_LITERAL_DEFLATED 2 181 182/* 183 * This represents a "patch" to a file, both metainfo changes 184 * such as creation/deletion, filemode and content changes represented 185 * as a series of fragments. 186 */ 187struct patch { 188char*new_name, *old_name, *def_name; 189unsigned int old_mode, new_mode; 190int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 191int rejected; 192unsigned ws_rule; 193int lines_added, lines_deleted; 194int score; 195unsigned int is_toplevel_relative:1; 196unsigned int inaccurate_eof:1; 197unsigned int is_binary:1; 198unsigned int is_copy:1; 199unsigned int is_rename:1; 200unsigned int recount:1; 201unsigned int conflicted_threeway:1; 202unsigned int direct_to_threeway:1; 203struct fragment *fragments; 204char*result; 205size_t resultsize; 206char old_sha1_prefix[41]; 207char new_sha1_prefix[41]; 208struct patch *next; 209 210/* three-way fallback result */ 211struct object_id threeway_stage[3]; 212}; 213 214static voidfree_fragment_list(struct fragment *list) 215{ 216while(list) { 217struct fragment *next = list->next; 218if(list->free_patch) 219free((char*)list->patch); 220free(list); 221 list = next; 222} 223} 224 225static voidfree_patch(struct patch *patch) 226{ 227free_fragment_list(patch->fragments); 228free(patch->def_name); 229free(patch->old_name); 230free(patch->new_name); 231free(patch->result); 232free(patch); 233} 234 235static voidfree_patch_list(struct patch *list) 236{ 237while(list) { 238struct patch *next = list->next; 239free_patch(list); 240 list = next; 241} 242} 243 244/* 245 * A line in a file, len-bytes long (includes the terminating LF, 246 * except for an incomplete line at the end if the file ends with 247 * one), and its contents hashes to 'hash'. 248 */ 249struct line { 250size_t len; 251unsigned hash :24; 252unsigned flag :8; 253#define LINE_COMMON 1 254#define LINE_PATCHED 2 255}; 256 257/* 258 * This represents a "file", which is an array of "lines". 259 */ 260struct image { 261char*buf; 262size_t len; 263size_t nr; 264size_t alloc; 265struct line *line_allocated; 266struct line *line; 267}; 268 269/* 270 * Records filenames that have been touched, in order to handle 271 * the case where more than one patches touch the same file. 272 */ 273 274static struct string_list fn_table; 275 276static uint32_thash_line(const char*cp,size_t len) 277{ 278size_t i; 279uint32_t h; 280for(i =0, h =0; i < len; i++) { 281if(!isspace(cp[i])) { 282 h = h *3+ (cp[i] &0xff); 283} 284} 285return h; 286} 287 288/* 289 * Compare lines s1 of length n1 and s2 of length n2, ignoring 290 * whitespace difference. Returns 1 if they match, 0 otherwise 291 */ 292static intfuzzy_matchlines(const char*s1,size_t n1, 293const char*s2,size_t n2) 294{ 295const char*last1 = s1 + n1 -1; 296const char*last2 = s2 + n2 -1; 297int result =0; 298 299/* ignore line endings */ 300while((*last1 =='\r') || (*last1 =='\n')) 301 last1--; 302while((*last2 =='\r') || (*last2 =='\n')) 303 last2--; 304 305/* skip leading whitespaces, if both begin with whitespace */ 306if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 307while(isspace(*s1) && (s1 <= last1)) 308 s1++; 309while(isspace(*s2) && (s2 <= last2)) 310 s2++; 311} 312/* early return if both lines are empty */ 313if((s1 > last1) && (s2 > last2)) 314return1; 315while(!result) { 316 result = *s1++ - *s2++; 317/* 318 * Skip whitespace inside. We check for whitespace on 319 * both buffers because we don't want "a b" to match 320 * "ab" 321 */ 322if(isspace(*s1) &&isspace(*s2)) { 323while(isspace(*s1) && s1 <= last1) 324 s1++; 325while(isspace(*s2) && s2 <= last2) 326 s2++; 327} 328/* 329 * If we reached the end on one side only, 330 * lines don't match 331 */ 332if( 333((s2 > last2) && (s1 <= last1)) || 334((s1 > last1) && (s2 <= last2))) 335return0; 336if((s1 > last1) && (s2 > last2)) 337break; 338} 339 340return!result; 341} 342 343static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 344{ 345ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 346 img->line_allocated[img->nr].len = len; 347 img->line_allocated[img->nr].hash =hash_line(bol, len); 348 img->line_allocated[img->nr].flag = flag; 349 img->nr++; 350} 351 352/* 353 * "buf" has the file contents to be patched (read from various sources). 354 * attach it to "image" and add line-based index to it. 355 * "image" now owns the "buf". 356 */ 357static voidprepare_image(struct image *image,char*buf,size_t len, 358int prepare_linetable) 359{ 360const char*cp, *ep; 361 362memset(image,0,sizeof(*image)); 363 image->buf = buf; 364 image->len = len; 365 366if(!prepare_linetable) 367return; 368 369 ep = image->buf + image->len; 370 cp = image->buf; 371while(cp < ep) { 372const char*next; 373for(next = cp; next < ep && *next !='\n'; next++) 374; 375if(next < ep) 376 next++; 377add_line_info(image, cp, next - cp,0); 378 cp = next; 379} 380 image->line = image->line_allocated; 381} 382 383static voidclear_image(struct image *image) 384{ 385free(image->buf); 386free(image->line_allocated); 387memset(image,0,sizeof(*image)); 388} 389 390/* fmt must contain _one_ %s and no other substitution */ 391static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 392{ 393struct strbuf sb = STRBUF_INIT; 394 395if(patch->old_name && patch->new_name && 396strcmp(patch->old_name, patch->new_name)) { 397quote_c_style(patch->old_name, &sb, NULL,0); 398strbuf_addstr(&sb," => "); 399quote_c_style(patch->new_name, &sb, NULL,0); 400}else{ 401const char*n = patch->new_name; 402if(!n) 403 n = patch->old_name; 404quote_c_style(n, &sb, NULL,0); 405} 406fprintf(output, fmt, sb.buf); 407fputc('\n', output); 408strbuf_release(&sb); 409} 410 411#define SLOP (16) 412 413static voidread_patch_file(struct strbuf *sb,int fd) 414{ 415if(strbuf_read(sb, fd,0) <0) 416die_errno("git apply: failed to read"); 417 418/* 419 * Make sure that we have some slop in the buffer 420 * so that we can do speculative "memcmp" etc, and 421 * see to it that it is NUL-filled. 422 */ 423strbuf_grow(sb, SLOP); 424memset(sb->buf + sb->len,0, SLOP); 425} 426 427static unsigned longlinelen(const char*buffer,unsigned long size) 428{ 429unsigned long len =0; 430while(size--) { 431 len++; 432if(*buffer++ =='\n') 433break; 434} 435return len; 436} 437 438static intis_dev_null(const char*str) 439{ 440returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 441} 442 443#define TERM_SPACE 1 444#define TERM_TAB 2 445 446static intname_terminate(const char*name,int namelen,int c,int terminate) 447{ 448if(c ==' '&& !(terminate & TERM_SPACE)) 449return0; 450if(c =='\t'&& !(terminate & TERM_TAB)) 451return0; 452 453return1; 454} 455 456/* remove double slashes to make --index work with such filenames */ 457static char*squash_slash(char*name) 458{ 459int i =0, j =0; 460 461if(!name) 462return NULL; 463 464while(name[i]) { 465if((name[j++] = name[i++]) =='/') 466while(name[i] =='/') 467 i++; 468} 469 name[j] ='\0'; 470return name; 471} 472 473static char*find_name_gnu(const char*line,const char*def,int p_value) 474{ 475struct strbuf name = STRBUF_INIT; 476char*cp; 477 478/* 479 * Proposed "new-style" GNU patch/diff format; see 480 * http://marc.info/?l=git&m=112927316408690&w=2 481 */ 482if(unquote_c_style(&name, line, NULL)) { 483strbuf_release(&name); 484return NULL; 485} 486 487for(cp = name.buf; p_value; p_value--) { 488 cp =strchr(cp,'/'); 489if(!cp) { 490strbuf_release(&name); 491return NULL; 492} 493 cp++; 494} 495 496strbuf_remove(&name,0, cp - name.buf); 497if(root.len) 498strbuf_insert(&name,0, root.buf, root.len); 499returnsquash_slash(strbuf_detach(&name, NULL)); 500} 501 502static size_tsane_tz_len(const char*line,size_t len) 503{ 504const char*tz, *p; 505 506if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 507return0; 508 tz = line + len -strlen(" +0500"); 509 510if(tz[1] !='+'&& tz[1] !='-') 511return0; 512 513for(p = tz +2; p != line + len; p++) 514if(!isdigit(*p)) 515return0; 516 517return line + len - tz; 518} 519 520static size_ttz_with_colon_len(const char*line,size_t len) 521{ 522const char*tz, *p; 523 524if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 525return0; 526 tz = line + len -strlen(" +08:00"); 527 528if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 529return0; 530 p = tz +2; 531if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 532!isdigit(*p++) || !isdigit(*p++)) 533return0; 534 535return line + len - tz; 536} 537 538static size_tdate_len(const char*line,size_t len) 539{ 540const char*date, *p; 541 542if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 543return0; 544 p = date = line + len -strlen("72-02-05"); 545 546if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 547!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 548!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 549return0; 550 551if(date - line >=strlen("19") && 552isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 553 date -=strlen("19"); 554 555return line + len - date; 556} 557 558static size_tshort_time_len(const char*line,size_t len) 559{ 560const char*time, *p; 561 562if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 563return0; 564 p = time = line + len -strlen(" 07:01:32"); 565 566/* Permit 1-digit hours? */ 567if(*p++ !=' '|| 568!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 569!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 570!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 571return0; 572 573return line + len - time; 574} 575 576static size_tfractional_time_len(const char*line,size_t len) 577{ 578const char*p; 579size_t n; 580 581/* Expected format: 19:41:17.620000023 */ 582if(!len || !isdigit(line[len -1])) 583return0; 584 p = line + len -1; 585 586/* Fractional seconds. */ 587while(p > line &&isdigit(*p)) 588 p--; 589if(*p !='.') 590return0; 591 592/* Hours, minutes, and whole seconds. */ 593 n =short_time_len(line, p - line); 594if(!n) 595return0; 596 597return line + len - p + n; 598} 599 600static size_ttrailing_spaces_len(const char*line,size_t len) 601{ 602const char*p; 603 604/* Expected format: ' ' x (1 or more) */ 605if(!len || line[len -1] !=' ') 606return0; 607 608 p = line + len; 609while(p != line) { 610 p--; 611if(*p !=' ') 612return line + len - (p +1); 613} 614 615/* All spaces! */ 616return len; 617} 618 619static size_tdiff_timestamp_len(const char*line,size_t len) 620{ 621const char*end = line + len; 622size_t n; 623 624/* 625 * Posix: 2010-07-05 19:41:17 626 * GNU: 2010-07-05 19:41:17.620000023 -0500 627 */ 628 629if(!isdigit(end[-1])) 630return0; 631 632 n =sane_tz_len(line, end - line); 633if(!n) 634 n =tz_with_colon_len(line, end - line); 635 end -= n; 636 637 n =short_time_len(line, end - line); 638if(!n) 639 n =fractional_time_len(line, end - line); 640 end -= n; 641 642 n =date_len(line, end - line); 643if(!n)/* No date. Too bad. */ 644return0; 645 end -= n; 646 647if(end == line)/* No space before date. */ 648return0; 649if(end[-1] =='\t') {/* Success! */ 650 end--; 651return line + len - end; 652} 653if(end[-1] !=' ')/* No space before date. */ 654return0; 655 656/* Whitespace damage. */ 657 end -=trailing_spaces_len(line, end - line); 658return line + len - end; 659} 660 661static char*find_name_common(const char*line,const char*def, 662int p_value,const char*end,int terminate) 663{ 664int len; 665const char*start = NULL; 666 667if(p_value ==0) 668 start = line; 669while(line != end) { 670char c = *line; 671 672if(!end &&isspace(c)) { 673if(c =='\n') 674break; 675if(name_terminate(start, line-start, c, terminate)) 676break; 677} 678 line++; 679if(c =='/'&& !--p_value) 680 start = line; 681} 682if(!start) 683returnsquash_slash(xstrdup_or_null(def)); 684 len = line - start; 685if(!len) 686returnsquash_slash(xstrdup_or_null(def)); 687 688/* 689 * Generally we prefer the shorter name, especially 690 * if the other one is just a variation of that with 691 * something else tacked on to the end (ie "file.orig" 692 * or "file~"). 693 */ 694if(def) { 695int deflen =strlen(def); 696if(deflen < len && !strncmp(start, def, deflen)) 697returnsquash_slash(xstrdup(def)); 698} 699 700if(root.len) { 701char*ret =xstrfmt("%s%.*s", root.buf, len, start); 702returnsquash_slash(ret); 703} 704 705returnsquash_slash(xmemdupz(start, len)); 706} 707 708static char*find_name(const char*line,char*def,int p_value,int terminate) 709{ 710if(*line =='"') { 711char*name =find_name_gnu(line, def, p_value); 712if(name) 713return name; 714} 715 716returnfind_name_common(line, def, p_value, NULL, terminate); 717} 718 719static char*find_name_traditional(const char*line,char*def,int p_value) 720{ 721size_t len; 722size_t date_len; 723 724if(*line =='"') { 725char*name =find_name_gnu(line, def, p_value); 726if(name) 727return name; 728} 729 730 len =strchrnul(line,'\n') - line; 731 date_len =diff_timestamp_len(line, len); 732if(!date_len) 733returnfind_name_common(line, def, p_value, NULL, TERM_TAB); 734 len -= date_len; 735 736returnfind_name_common(line, def, p_value, line + len,0); 737} 738 739static intcount_slashes(const char*cp) 740{ 741int cnt =0; 742char ch; 743 744while((ch = *cp++)) 745if(ch =='/') 746 cnt++; 747return cnt; 748} 749 750/* 751 * Given the string after "--- " or "+++ ", guess the appropriate 752 * p_value for the given patch. 753 */ 754static intguess_p_value(struct apply_state *state,const char*nameline) 755{ 756char*name, *cp; 757int val = -1; 758 759if(is_dev_null(nameline)) 760return-1; 761 name =find_name_traditional(nameline, NULL,0); 762if(!name) 763return-1; 764 cp =strchr(name,'/'); 765if(!cp) 766 val =0; 767else if(state->prefix) { 768/* 769 * Does it begin with "a/$our-prefix" and such? Then this is 770 * very likely to apply to our directory. 771 */ 772if(!strncmp(name, state->prefix, state->prefix_length)) 773 val =count_slashes(state->prefix); 774else{ 775 cp++; 776if(!strncmp(cp, state->prefix, state->prefix_length)) 777 val =count_slashes(state->prefix) +1; 778} 779} 780free(name); 781return val; 782} 783 784/* 785 * Does the ---/+++ line have the POSIX timestamp after the last HT? 786 * GNU diff puts epoch there to signal a creation/deletion event. Is 787 * this such a timestamp? 788 */ 789static inthas_epoch_timestamp(const char*nameline) 790{ 791/* 792 * We are only interested in epoch timestamp; any non-zero 793 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 794 * For the same reason, the date must be either 1969-12-31 or 795 * 1970-01-01, and the seconds part must be "00". 796 */ 797const char stamp_regexp[] = 798"^(1969-12-31|1970-01-01)" 799" " 800"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 801" " 802"([-+][0-2][0-9]:?[0-5][0-9])\n"; 803const char*timestamp = NULL, *cp, *colon; 804static regex_t *stamp; 805 regmatch_t m[10]; 806int zoneoffset; 807int hourminute; 808int status; 809 810for(cp = nameline; *cp !='\n'; cp++) { 811if(*cp =='\t') 812 timestamp = cp +1; 813} 814if(!timestamp) 815return0; 816if(!stamp) { 817 stamp =xmalloc(sizeof(*stamp)); 818if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 819warning(_("Cannot prepare timestamp regexp%s"), 820 stamp_regexp); 821return0; 822} 823} 824 825 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 826if(status) { 827if(status != REG_NOMATCH) 828warning(_("regexec returned%dfor input:%s"), 829 status, timestamp); 830return0; 831} 832 833 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 834if(*colon ==':') 835 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 836else 837 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 838if(timestamp[m[3].rm_so] =='-') 839 zoneoffset = -zoneoffset; 840 841/* 842 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 843 * (west of GMT) or 1970-01-01 (east of GMT) 844 */ 845if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 846(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 847return0; 848 849 hourminute = (strtol(timestamp +11, NULL,10) *60+ 850strtol(timestamp +14, NULL,10) - 851 zoneoffset); 852 853return((zoneoffset <0&& hourminute ==1440) || 854(0<= zoneoffset && !hourminute)); 855} 856 857/* 858 * Get the name etc info from the ---/+++ lines of a traditional patch header 859 * 860 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 861 * files, we can happily check the index for a match, but for creating a 862 * new file we should try to match whatever "patch" does. I have no idea. 863 */ 864static voidparse_traditional_patch(struct apply_state *state, 865const char*first, 866const char*second, 867struct patch *patch) 868{ 869char*name; 870 871 first +=4;/* skip "--- " */ 872 second +=4;/* skip "+++ " */ 873if(!p_value_known) { 874int p, q; 875 p =guess_p_value(state, first); 876 q =guess_p_value(state, second); 877if(p <0) p = q; 878if(0<= p && p == q) { 879 state_p_value = p; 880 p_value_known =1; 881} 882} 883if(is_dev_null(first)) { 884 patch->is_new =1; 885 patch->is_delete =0; 886 name =find_name_traditional(second, NULL, state_p_value); 887 patch->new_name = name; 888}else if(is_dev_null(second)) { 889 patch->is_new =0; 890 patch->is_delete =1; 891 name =find_name_traditional(first, NULL, state_p_value); 892 patch->old_name = name; 893}else{ 894char*first_name; 895 first_name =find_name_traditional(first, NULL, state_p_value); 896 name =find_name_traditional(second, first_name, state_p_value); 897free(first_name); 898if(has_epoch_timestamp(first)) { 899 patch->is_new =1; 900 patch->is_delete =0; 901 patch->new_name = name; 902}else if(has_epoch_timestamp(second)) { 903 patch->is_new =0; 904 patch->is_delete =1; 905 patch->old_name = name; 906}else{ 907 patch->old_name = name; 908 patch->new_name =xstrdup_or_null(name); 909} 910} 911if(!name) 912die(_("unable to find filename in patch at line%d"), state_linenr); 913} 914 915static intgitdiff_hdrend(const char*line,struct patch *patch) 916{ 917return-1; 918} 919 920/* 921 * We're anal about diff header consistency, to make 922 * sure that we don't end up having strange ambiguous 923 * patches floating around. 924 * 925 * As a result, gitdiff_{old|new}name() will check 926 * their names against any previous information, just 927 * to make sure.. 928 */ 929#define DIFF_OLD_NAME 0 930#define DIFF_NEW_NAME 1 931 932static voidgitdiff_verify_name(const char*line,int isnull,char**name,int side) 933{ 934if(!*name && !isnull) { 935*name =find_name(line, NULL, state_p_value, TERM_TAB); 936return; 937} 938 939if(*name) { 940int len =strlen(*name); 941char*another; 942if(isnull) 943die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 944*name, state_linenr); 945 another =find_name(line, NULL, state_p_value, TERM_TAB); 946if(!another ||memcmp(another, *name, len +1)) 947die((side == DIFF_NEW_NAME) ? 948_("git apply: bad git-diff - inconsistent new filename on line%d") : 949_("git apply: bad git-diff - inconsistent old filename on line%d"), state_linenr); 950free(another); 951}else{ 952/* expect "/dev/null" */ 953if(memcmp("/dev/null", line,9) || line[9] !='\n') 954die(_("git apply: bad git-diff - expected /dev/null on line%d"), state_linenr); 955} 956} 957 958static intgitdiff_oldname(const char*line,struct patch *patch) 959{ 960gitdiff_verify_name(line, patch->is_new, &patch->old_name, 961 DIFF_OLD_NAME); 962return0; 963} 964 965static intgitdiff_newname(const char*line,struct patch *patch) 966{ 967gitdiff_verify_name(line, patch->is_delete, &patch->new_name, 968 DIFF_NEW_NAME); 969return0; 970} 971 972static intgitdiff_oldmode(const char*line,struct patch *patch) 973{ 974 patch->old_mode =strtoul(line, NULL,8); 975return0; 976} 977 978static intgitdiff_newmode(const char*line,struct patch *patch) 979{ 980 patch->new_mode =strtoul(line, NULL,8); 981return0; 982} 983 984static intgitdiff_delete(const char*line,struct patch *patch) 985{ 986 patch->is_delete =1; 987free(patch->old_name); 988 patch->old_name =xstrdup_or_null(patch->def_name); 989returngitdiff_oldmode(line, patch); 990} 991 992static intgitdiff_newfile(const char*line,struct patch *patch) 993{ 994 patch->is_new =1; 995free(patch->new_name); 996 patch->new_name =xstrdup_or_null(patch->def_name); 997returngitdiff_newmode(line, patch); 998} 9991000static intgitdiff_copysrc(const char*line,struct patch *patch)1001{1002 patch->is_copy =1;1003free(patch->old_name);1004 patch->old_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1005return0;1006}10071008static intgitdiff_copydst(const char*line,struct patch *patch)1009{1010 patch->is_copy =1;1011free(patch->new_name);1012 patch->new_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1013return0;1014}10151016static intgitdiff_renamesrc(const char*line,struct patch *patch)1017{1018 patch->is_rename =1;1019free(patch->old_name);1020 patch->old_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1021return0;1022}10231024static intgitdiff_renamedst(const char*line,struct patch *patch)1025{1026 patch->is_rename =1;1027free(patch->new_name);1028 patch->new_name =find_name(line, NULL, state_p_value ? state_p_value -1:0,0);1029return0;1030}10311032static intgitdiff_similarity(const char*line,struct patch *patch)1033{1034unsigned long val =strtoul(line, NULL,10);1035if(val <=100)1036 patch->score = val;1037return0;1038}10391040static intgitdiff_dissimilarity(const char*line,struct patch *patch)1041{1042unsigned long val =strtoul(line, NULL,10);1043if(val <=100)1044 patch->score = val;1045return0;1046}10471048static intgitdiff_index(const char*line,struct patch *patch)1049{1050/*1051 * index line is N hexadecimal, "..", N hexadecimal,1052 * and optional space with octal mode.1053 */1054const char*ptr, *eol;1055int len;10561057 ptr =strchr(line,'.');1058if(!ptr || ptr[1] !='.'||40< ptr - line)1059return0;1060 len = ptr - line;1061memcpy(patch->old_sha1_prefix, line, len);1062 patch->old_sha1_prefix[len] =0;10631064 line = ptr +2;1065 ptr =strchr(line,' ');1066 eol =strchrnul(line,'\n');10671068if(!ptr || eol < ptr)1069 ptr = eol;1070 len = ptr - line;10711072if(40< len)1073return0;1074memcpy(patch->new_sha1_prefix, line, len);1075 patch->new_sha1_prefix[len] =0;1076if(*ptr ==' ')1077 patch->old_mode =strtoul(ptr+1, NULL,8);1078return0;1079}10801081/*1082 * This is normal for a diff that doesn't change anything: we'll fall through1083 * into the next diff. Tell the parser to break out.1084 */1085static intgitdiff_unrecognized(const char*line,struct patch *patch)1086{1087return-1;1088}10891090/*1091 * Skip p_value leading components from "line"; as we do not accept1092 * absolute paths, return NULL in that case.1093 */1094static const char*skip_tree_prefix(const char*line,int llen)1095{1096int nslash;1097int i;10981099if(!state_p_value)1100return(llen && line[0] =='/') ? NULL : line;11011102 nslash = state_p_value;1103for(i =0; i < llen; i++) {1104int ch = line[i];1105if(ch =='/'&& --nslash <=0)1106return(i ==0) ? NULL : &line[i +1];1107}1108return NULL;1109}11101111/*1112 * This is to extract the same name that appears on "diff --git"1113 * line. We do not find and return anything if it is a rename1114 * patch, and it is OK because we will find the name elsewhere.1115 * We need to reliably find name only when it is mode-change only,1116 * creation or deletion of an empty file. In any of these cases,1117 * both sides are the same name under a/ and b/ respectively.1118 */1119static char*git_header_name(const char*line,int llen)1120{1121const char*name;1122const char*second = NULL;1123size_t len, line_len;11241125 line +=strlen("diff --git ");1126 llen -=strlen("diff --git ");11271128if(*line =='"') {1129const char*cp;1130struct strbuf first = STRBUF_INIT;1131struct strbuf sp = STRBUF_INIT;11321133if(unquote_c_style(&first, line, &second))1134goto free_and_fail1;11351136/* strip the a/b prefix including trailing slash */1137 cp =skip_tree_prefix(first.buf, first.len);1138if(!cp)1139goto free_and_fail1;1140strbuf_remove(&first,0, cp - first.buf);11411142/*1143 * second points at one past closing dq of name.1144 * find the second name.1145 */1146while((second < line + llen) &&isspace(*second))1147 second++;11481149if(line + llen <= second)1150goto free_and_fail1;1151if(*second =='"') {1152if(unquote_c_style(&sp, second, NULL))1153goto free_and_fail1;1154 cp =skip_tree_prefix(sp.buf, sp.len);1155if(!cp)1156goto free_and_fail1;1157/* They must match, otherwise ignore */1158if(strcmp(cp, first.buf))1159goto free_and_fail1;1160strbuf_release(&sp);1161returnstrbuf_detach(&first, NULL);1162}11631164/* unquoted second */1165 cp =skip_tree_prefix(second, line + llen - second);1166if(!cp)1167goto free_and_fail1;1168if(line + llen - cp != first.len ||1169memcmp(first.buf, cp, first.len))1170goto free_and_fail1;1171returnstrbuf_detach(&first, NULL);11721173 free_and_fail1:1174strbuf_release(&first);1175strbuf_release(&sp);1176return NULL;1177}11781179/* unquoted first name */1180 name =skip_tree_prefix(line, llen);1181if(!name)1182return NULL;11831184/*1185 * since the first name is unquoted, a dq if exists must be1186 * the beginning of the second name.1187 */1188for(second = name; second < line + llen; second++) {1189if(*second =='"') {1190struct strbuf sp = STRBUF_INIT;1191const char*np;11921193if(unquote_c_style(&sp, second, NULL))1194goto free_and_fail2;11951196 np =skip_tree_prefix(sp.buf, sp.len);1197if(!np)1198goto free_and_fail2;11991200 len = sp.buf + sp.len - np;1201if(len < second - name &&1202!strncmp(np, name, len) &&1203isspace(name[len])) {1204/* Good */1205strbuf_remove(&sp,0, np - sp.buf);1206returnstrbuf_detach(&sp, NULL);1207}12081209 free_and_fail2:1210strbuf_release(&sp);1211return NULL;1212}1213}12141215/*1216 * Accept a name only if it shows up twice, exactly the same1217 * form.1218 */1219 second =strchr(name,'\n');1220if(!second)1221return NULL;1222 line_len = second - name;1223for(len =0; ; len++) {1224switch(name[len]) {1225default:1226continue;1227case'\n':1228return NULL;1229case'\t':case' ':1230/*1231 * Is this the separator between the preimage1232 * and the postimage pathname? Again, we are1233 * only interested in the case where there is1234 * no rename, as this is only to set def_name1235 * and a rename patch has the names elsewhere1236 * in an unambiguous form.1237 */1238if(!name[len +1])1239return NULL;/* no postimage name */1240 second =skip_tree_prefix(name + len +1,1241 line_len - (len +1));1242if(!second)1243return NULL;1244/*1245 * Does len bytes starting at "name" and "second"1246 * (that are separated by one HT or SP we just1247 * found) exactly match?1248 */1249if(second[len] =='\n'&& !strncmp(name, second, len))1250returnxmemdupz(name, len);1251}1252}1253}12541255/* Verify that we recognize the lines following a git header */1256static intparse_git_header(const char*line,int len,unsigned int size,struct patch *patch)1257{1258unsigned long offset;12591260/* A git diff has explicit new/delete information, so we don't guess */1261 patch->is_new =0;1262 patch->is_delete =0;12631264/*1265 * Some things may not have the old name in the1266 * rest of the headers anywhere (pure mode changes,1267 * or removing or adding empty files), so we get1268 * the default name from the header.1269 */1270 patch->def_name =git_header_name(line, len);1271if(patch->def_name && root.len) {1272char*s =xstrfmt("%s%s", root.buf, patch->def_name);1273free(patch->def_name);1274 patch->def_name = s;1275}12761277 line += len;1278 size -= len;1279 state_linenr++;1280for(offset = len ; size >0; offset += len, size -= len, line += len, state_linenr++) {1281static const struct opentry {1282const char*str;1283int(*fn)(const char*,struct patch *);1284} optable[] = {1285{"@@ -", gitdiff_hdrend },1286{"--- ", gitdiff_oldname },1287{"+++ ", gitdiff_newname },1288{"old mode ", gitdiff_oldmode },1289{"new mode ", gitdiff_newmode },1290{"deleted file mode ", gitdiff_delete },1291{"new file mode ", gitdiff_newfile },1292{"copy from ", gitdiff_copysrc },1293{"copy to ", gitdiff_copydst },1294{"rename old ", gitdiff_renamesrc },1295{"rename new ", gitdiff_renamedst },1296{"rename from ", gitdiff_renamesrc },1297{"rename to ", gitdiff_renamedst },1298{"similarity index ", gitdiff_similarity },1299{"dissimilarity index ", gitdiff_dissimilarity },1300{"index ", gitdiff_index },1301{"", gitdiff_unrecognized },1302};1303int i;13041305 len =linelen(line, size);1306if(!len || line[len-1] !='\n')1307break;1308for(i =0; i <ARRAY_SIZE(optable); i++) {1309const struct opentry *p = optable + i;1310int oplen =strlen(p->str);1311if(len < oplen ||memcmp(p->str, line, oplen))1312continue;1313if(p->fn(line + oplen, patch) <0)1314return offset;1315break;1316}1317}13181319return offset;1320}13211322static intparse_num(const char*line,unsigned long*p)1323{1324char*ptr;13251326if(!isdigit(*line))1327return0;1328*p =strtoul(line, &ptr,10);1329return ptr - line;1330}13311332static intparse_range(const char*line,int len,int offset,const char*expect,1333unsigned long*p1,unsigned long*p2)1334{1335int digits, ex;13361337if(offset <0|| offset >= len)1338return-1;1339 line += offset;1340 len -= offset;13411342 digits =parse_num(line, p1);1343if(!digits)1344return-1;13451346 offset += digits;1347 line += digits;1348 len -= digits;13491350*p2 =1;1351if(*line ==',') {1352 digits =parse_num(line+1, p2);1353if(!digits)1354return-1;13551356 offset += digits+1;1357 line += digits+1;1358 len -= digits+1;1359}13601361 ex =strlen(expect);1362if(ex > len)1363return-1;1364if(memcmp(line, expect, ex))1365return-1;13661367return offset + ex;1368}13691370static voidrecount_diff(const char*line,int size,struct fragment *fragment)1371{1372int oldlines =0, newlines =0, ret =0;13731374if(size <1) {1375warning("recount: ignore empty hunk");1376return;1377}13781379for(;;) {1380int len =linelen(line, size);1381 size -= len;1382 line += len;13831384if(size <1)1385break;13861387switch(*line) {1388case' ':case'\n':1389 newlines++;1390/* fall through */1391case'-':1392 oldlines++;1393continue;1394case'+':1395 newlines++;1396continue;1397case'\\':1398continue;1399case'@':1400 ret = size <3|| !starts_with(line,"@@ ");1401break;1402case'd':1403 ret = size <5|| !starts_with(line,"diff ");1404break;1405default:1406 ret = -1;1407break;1408}1409if(ret) {1410warning(_("recount: unexpected line: %.*s"),1411(int)linelen(line, size), line);1412return;1413}1414break;1415}1416 fragment->oldlines = oldlines;1417 fragment->newlines = newlines;1418}14191420/*1421 * Parse a unified diff fragment header of the1422 * form "@@ -a,b +c,d @@"1423 */1424static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1425{1426int offset;14271428if(!len || line[len-1] !='\n')1429return-1;14301431/* Figure out the number of lines in a fragment */1432 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1433 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14341435return offset;1436}14371438static intfind_header(struct apply_state *state,1439const char*line,1440unsigned long size,1441int*hdrsize,1442struct patch *patch)1443{1444unsigned long offset, len;14451446 patch->is_toplevel_relative =0;1447 patch->is_rename = patch->is_copy =0;1448 patch->is_new = patch->is_delete = -1;1449 patch->old_mode = patch->new_mode =0;1450 patch->old_name = patch->new_name = NULL;1451for(offset =0; size >0; offset += len, size -= len, line += len, state_linenr++) {1452unsigned long nextlen;14531454 len =linelen(line, size);1455if(!len)1456break;14571458/* Testing this early allows us to take a few shortcuts.. */1459if(len <6)1460continue;14611462/*1463 * Make sure we don't find any unconnected patch fragments.1464 * That's a sign that we didn't find a header, and that a1465 * patch has become corrupted/broken up.1466 */1467if(!memcmp("@@ -", line,4)) {1468struct fragment dummy;1469if(parse_fragment_header(line, len, &dummy) <0)1470continue;1471die(_("patch fragment without header at line%d: %.*s"),1472 state_linenr, (int)len-1, line);1473}14741475if(size < len +6)1476break;14771478/*1479 * Git patch? It might not have a real patch, just a rename1480 * or mode change, so we handle that specially1481 */1482if(!memcmp("diff --git ", line,11)) {1483int git_hdr_len =parse_git_header(line, len, size, patch);1484if(git_hdr_len <= len)1485continue;1486if(!patch->old_name && !patch->new_name) {1487if(!patch->def_name)1488die(Q_("git diff header lacks filename information when removing "1489"%dleading pathname component (line%d)",1490"git diff header lacks filename information when removing "1491"%dleading pathname components (line%d)",1492 state_p_value),1493 state_p_value, state_linenr);1494 patch->old_name =xstrdup(patch->def_name);1495 patch->new_name =xstrdup(patch->def_name);1496}1497if(!patch->is_delete && !patch->new_name)1498die("git diff header lacks filename information "1499"(line%d)", state_linenr);1500 patch->is_toplevel_relative =1;1501*hdrsize = git_hdr_len;1502return offset;1503}15041505/* --- followed by +++ ? */1506if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1507continue;15081509/*1510 * We only accept unified patches, so we want it to1511 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1512 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1513 */1514 nextlen =linelen(line + len, size - len);1515if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1516continue;15171518/* Ok, we'll consider it a patch */1519parse_traditional_patch(state, line, line+len, patch);1520*hdrsize = len + nextlen;1521 state_linenr +=2;1522return offset;1523}1524return-1;1525}15261527static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1528{1529char*err;15301531if(!result)1532return;15331534 whitespace_error++;1535if(squelch_whitespace_errors &&1536 squelch_whitespace_errors < whitespace_error)1537return;15381539 err =whitespace_error_string(result);1540fprintf(stderr,"%s:%d:%s.\n%.*s\n",1541 patch_input_file, linenr, err, len, line);1542free(err);1543}15441545static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1546{1547unsigned result =ws_check(line +1, len -1, ws_rule);15481549record_ws_error(result, line +1, len -2, state_linenr);1550}15511552/*1553 * Parse a unified diff. Note that this really needs to parse each1554 * fragment separately, since the only way to know the difference1555 * between a "---" that is part of a patch, and a "---" that starts1556 * the next patch is to look at the line counts..1557 */1558static intparse_fragment(const char*line,unsigned long size,1559struct patch *patch,struct fragment *fragment)1560{1561int added, deleted;1562int len =linelen(line, size), offset;1563unsigned long oldlines, newlines;1564unsigned long leading, trailing;15651566 offset =parse_fragment_header(line, len, fragment);1567if(offset <0)1568return-1;1569if(offset >0&& patch->recount)1570recount_diff(line + offset, size - offset, fragment);1571 oldlines = fragment->oldlines;1572 newlines = fragment->newlines;1573 leading =0;1574 trailing =0;15751576/* Parse the thing.. */1577 line += len;1578 size -= len;1579 state_linenr++;1580 added = deleted =0;1581for(offset = len;15820< size;1583 offset += len, size -= len, line += len, state_linenr++) {1584if(!oldlines && !newlines)1585break;1586 len =linelen(line, size);1587if(!len || line[len-1] !='\n')1588return-1;1589switch(*line) {1590default:1591return-1;1592case'\n':/* newer GNU diff, an empty context line */1593case' ':1594 oldlines--;1595 newlines--;1596if(!deleted && !added)1597 leading++;1598 trailing++;1599if(!apply_in_reverse &&1600 ws_error_action == correct_ws_error)1601check_whitespace(line, len, patch->ws_rule);1602break;1603case'-':1604if(apply_in_reverse &&1605 ws_error_action != nowarn_ws_error)1606check_whitespace(line, len, patch->ws_rule);1607 deleted++;1608 oldlines--;1609 trailing =0;1610break;1611case'+':1612if(!apply_in_reverse &&1613 ws_error_action != nowarn_ws_error)1614check_whitespace(line, len, patch->ws_rule);1615 added++;1616 newlines--;1617 trailing =0;1618break;16191620/*1621 * We allow "\ No newline at end of file". Depending1622 * on locale settings when the patch was produced we1623 * don't know what this line looks like. The only1624 * thing we do know is that it begins with "\ ".1625 * Checking for 12 is just for sanity check -- any1626 * l10n of "\ No newline..." is at least that long.1627 */1628case'\\':1629if(len <12||memcmp(line,"\\",2))1630return-1;1631break;1632}1633}1634if(oldlines || newlines)1635return-1;1636if(!deleted && !added)1637return-1;16381639 fragment->leading = leading;1640 fragment->trailing = trailing;16411642/*1643 * If a fragment ends with an incomplete line, we failed to include1644 * it in the above loop because we hit oldlines == newlines == 01645 * before seeing it.1646 */1647if(12< size && !memcmp(line,"\\",2))1648 offset +=linelen(line, size);16491650 patch->lines_added += added;1651 patch->lines_deleted += deleted;16521653if(0< patch->is_new && oldlines)1654returnerror(_("new file depends on old contents"));1655if(0< patch->is_delete && newlines)1656returnerror(_("deleted file still has contents"));1657return offset;1658}16591660/*1661 * We have seen "diff --git a/... b/..." header (or a traditional patch1662 * header). Read hunks that belong to this patch into fragments and hang1663 * them to the given patch structure.1664 *1665 * The (fragment->patch, fragment->size) pair points into the memory given1666 * by the caller, not a copy, when we return.1667 */1668static intparse_single_patch(const char*line,unsigned long size,struct patch *patch)1669{1670unsigned long offset =0;1671unsigned long oldlines =0, newlines =0, context =0;1672struct fragment **fragp = &patch->fragments;16731674while(size >4&& !memcmp(line,"@@ -",4)) {1675struct fragment *fragment;1676int len;16771678 fragment =xcalloc(1,sizeof(*fragment));1679 fragment->linenr = state_linenr;1680 len =parse_fragment(line, size, patch, fragment);1681if(len <=0)1682die(_("corrupt patch at line%d"), state_linenr);1683 fragment->patch = line;1684 fragment->size = len;1685 oldlines += fragment->oldlines;1686 newlines += fragment->newlines;1687 context += fragment->leading + fragment->trailing;16881689*fragp = fragment;1690 fragp = &fragment->next;16911692 offset += len;1693 line += len;1694 size -= len;1695}16961697/*1698 * If something was removed (i.e. we have old-lines) it cannot1699 * be creation, and if something was added it cannot be1700 * deletion. However, the reverse is not true; --unified=01701 * patches that only add are not necessarily creation even1702 * though they do not have any old lines, and ones that only1703 * delete are not necessarily deletion.1704 *1705 * Unfortunately, a real creation/deletion patch do _not_ have1706 * any context line by definition, so we cannot safely tell it1707 * apart with --unified=0 insanity. At least if the patch has1708 * more than one hunk it is not creation or deletion.1709 */1710if(patch->is_new <0&&1711(oldlines || (patch->fragments && patch->fragments->next)))1712 patch->is_new =0;1713if(patch->is_delete <0&&1714(newlines || (patch->fragments && patch->fragments->next)))1715 patch->is_delete =0;17161717if(0< patch->is_new && oldlines)1718die(_("new file%sdepends on old contents"), patch->new_name);1719if(0< patch->is_delete && newlines)1720die(_("deleted file%sstill has contents"), patch->old_name);1721if(!patch->is_delete && !newlines && context)1722fprintf_ln(stderr,1723_("** warning: "1724"file%sbecomes empty but is not deleted"),1725 patch->new_name);17261727return offset;1728}17291730staticinlineintmetadata_changes(struct patch *patch)1731{1732return patch->is_rename >0||1733 patch->is_copy >0||1734 patch->is_new >0||1735 patch->is_delete ||1736(patch->old_mode && patch->new_mode &&1737 patch->old_mode != patch->new_mode);1738}17391740static char*inflate_it(const void*data,unsigned long size,1741unsigned long inflated_size)1742{1743 git_zstream stream;1744void*out;1745int st;17461747memset(&stream,0,sizeof(stream));17481749 stream.next_in = (unsigned char*)data;1750 stream.avail_in = size;1751 stream.next_out = out =xmalloc(inflated_size);1752 stream.avail_out = inflated_size;1753git_inflate_init(&stream);1754 st =git_inflate(&stream, Z_FINISH);1755git_inflate_end(&stream);1756if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1757free(out);1758return NULL;1759}1760return out;1761}17621763/*1764 * Read a binary hunk and return a new fragment; fragment->patch1765 * points at an allocated memory that the caller must free, so1766 * it is marked as "->free_patch = 1".1767 */1768static struct fragment *parse_binary_hunk(char**buf_p,1769unsigned long*sz_p,1770int*status_p,1771int*used_p)1772{1773/*1774 * Expect a line that begins with binary patch method ("literal"1775 * or "delta"), followed by the length of data before deflating.1776 * a sequence of 'length-byte' followed by base-85 encoded data1777 * should follow, terminated by a newline.1778 *1779 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1780 * and we would limit the patch line to 66 characters,1781 * so one line can fit up to 13 groups that would decode1782 * to 52 bytes max. The length byte 'A'-'Z' corresponds1783 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1784 */1785int llen, used;1786unsigned long size = *sz_p;1787char*buffer = *buf_p;1788int patch_method;1789unsigned long origlen;1790char*data = NULL;1791int hunk_size =0;1792struct fragment *frag;17931794 llen =linelen(buffer, size);1795 used = llen;17961797*status_p =0;17981799if(starts_with(buffer,"delta ")) {1800 patch_method = BINARY_DELTA_DEFLATED;1801 origlen =strtoul(buffer +6, NULL,10);1802}1803else if(starts_with(buffer,"literal ")) {1804 patch_method = BINARY_LITERAL_DEFLATED;1805 origlen =strtoul(buffer +8, NULL,10);1806}1807else1808return NULL;18091810 state_linenr++;1811 buffer += llen;1812while(1) {1813int byte_length, max_byte_length, newsize;1814 llen =linelen(buffer, size);1815 used += llen;1816 state_linenr++;1817if(llen ==1) {1818/* consume the blank line */1819 buffer++;1820 size--;1821break;1822}1823/*1824 * Minimum line is "A00000\n" which is 7-byte long,1825 * and the line length must be multiple of 5 plus 2.1826 */1827if((llen <7) || (llen-2) %5)1828goto corrupt;1829 max_byte_length = (llen -2) /5*4;1830 byte_length = *buffer;1831if('A'<= byte_length && byte_length <='Z')1832 byte_length = byte_length -'A'+1;1833else if('a'<= byte_length && byte_length <='z')1834 byte_length = byte_length -'a'+27;1835else1836goto corrupt;1837/* if the input length was not multiple of 4, we would1838 * have filler at the end but the filler should never1839 * exceed 3 bytes1840 */1841if(max_byte_length < byte_length ||1842 byte_length <= max_byte_length -4)1843goto corrupt;1844 newsize = hunk_size + byte_length;1845 data =xrealloc(data, newsize);1846if(decode_85(data + hunk_size, buffer +1, byte_length))1847goto corrupt;1848 hunk_size = newsize;1849 buffer += llen;1850 size -= llen;1851}18521853 frag =xcalloc(1,sizeof(*frag));1854 frag->patch =inflate_it(data, hunk_size, origlen);1855 frag->free_patch =1;1856if(!frag->patch)1857goto corrupt;1858free(data);1859 frag->size = origlen;1860*buf_p = buffer;1861*sz_p = size;1862*used_p = used;1863 frag->binary_patch_method = patch_method;1864return frag;18651866 corrupt:1867free(data);1868*status_p = -1;1869error(_("corrupt binary patch at line%d: %.*s"),1870 state_linenr-1, llen-1, buffer);1871return NULL;1872}18731874/*1875 * Returns:1876 * -1 in case of error,1877 * the length of the parsed binary patch otherwise1878 */1879static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1880{1881/*1882 * We have read "GIT binary patch\n"; what follows is a line1883 * that says the patch method (currently, either "literal" or1884 * "delta") and the length of data before deflating; a1885 * sequence of 'length-byte' followed by base-85 encoded data1886 * follows.1887 *1888 * When a binary patch is reversible, there is another binary1889 * hunk in the same format, starting with patch method (either1890 * "literal" or "delta") with the length of data, and a sequence1891 * of length-byte + base-85 encoded data, terminated with another1892 * empty line. This data, when applied to the postimage, produces1893 * the preimage.1894 */1895struct fragment *forward;1896struct fragment *reverse;1897int status;1898int used, used_1;18991900 forward =parse_binary_hunk(&buffer, &size, &status, &used);1901if(!forward && !status)1902/* there has to be one hunk (forward hunk) */1903returnerror(_("unrecognized binary patch at line%d"), state_linenr-1);1904if(status)1905/* otherwise we already gave an error message */1906return status;19071908 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1909if(reverse)1910 used += used_1;1911else if(status) {1912/*1913 * Not having reverse hunk is not an error, but having1914 * a corrupt reverse hunk is.1915 */1916free((void*) forward->patch);1917free(forward);1918return status;1919}1920 forward->next = reverse;1921 patch->fragments = forward;1922 patch->is_binary =1;1923return used;1924}19251926static voidprefix_one(struct apply_state *state,char**name)1927{1928char*old_name = *name;1929if(!old_name)1930return;1931*name =xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));1932free(old_name);1933}19341935static voidprefix_patch(struct apply_state *state,struct patch *p)1936{1937if(!state->prefix || p->is_toplevel_relative)1938return;1939prefix_one(state, &p->new_name);1940prefix_one(state, &p->old_name);1941}19421943/*1944 * include/exclude1945 */19461947static struct string_list limit_by_name;1948static int has_include;1949static voidadd_name_limit(const char*name,int exclude)1950{1951struct string_list_item *it;19521953 it =string_list_append(&limit_by_name, name);1954 it->util = exclude ? NULL : (void*)1;1955}19561957static intuse_patch(struct apply_state *state,struct patch *p)1958{1959const char*pathname = p->new_name ? p->new_name : p->old_name;1960int i;19611962/* Paths outside are not touched regardless of "--include" */1963if(0< state->prefix_length) {1964int pathlen =strlen(pathname);1965if(pathlen <= state->prefix_length ||1966memcmp(state->prefix, pathname, state->prefix_length))1967return0;1968}19691970/* See if it matches any of exclude/include rule */1971for(i =0; i < limit_by_name.nr; i++) {1972struct string_list_item *it = &limit_by_name.items[i];1973if(!wildmatch(it->string, pathname,0, NULL))1974return(it->util != NULL);1975}19761977/*1978 * If we had any include, a path that does not match any rule is1979 * not used. Otherwise, we saw bunch of exclude rules (or none)1980 * and such a path is used.1981 */1982return!has_include;1983}198419851986/*1987 * Read the patch text in "buffer" that extends for "size" bytes; stop1988 * reading after seeing a single patch (i.e. changes to a single file).1989 * Create fragments (i.e. patch hunks) and hang them to the given patch.1990 * Return the number of bytes consumed, so that the caller can call us1991 * again for the next patch.1992 */1993static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)1994{1995int hdrsize, patchsize;1996int offset =find_header(state, buffer, size, &hdrsize, patch);19971998if(offset <0)1999return offset;20002001prefix_patch(state, patch);20022003if(!use_patch(state, patch))2004 patch->ws_rule =0;2005else2006 patch->ws_rule =whitespace_rule(patch->new_name2007? patch->new_name2008: patch->old_name);20092010 patchsize =parse_single_patch(buffer + offset + hdrsize,2011 size - offset - hdrsize, patch);20122013if(!patchsize) {2014static const char git_binary[] ="GIT binary patch\n";2015int hd = hdrsize + offset;2016unsigned long llen =linelen(buffer + hd, size - hd);20172018if(llen ==sizeof(git_binary) -1&&2019!memcmp(git_binary, buffer + hd, llen)) {2020int used;2021 state_linenr++;2022 used =parse_binary(buffer + hd + llen,2023 size - hd - llen, patch);2024if(used <0)2025return-1;2026if(used)2027 patchsize = used + llen;2028else2029 patchsize =0;2030}2031else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2032static const char*binhdr[] = {2033"Binary files ",2034"Files ",2035 NULL,2036};2037int i;2038for(i =0; binhdr[i]; i++) {2039int len =strlen(binhdr[i]);2040if(len < size - hd &&2041!memcmp(binhdr[i], buffer + hd, len)) {2042 state_linenr++;2043 patch->is_binary =1;2044 patchsize = llen;2045break;2046}2047}2048}20492050/* Empty patch cannot be applied if it is a text patch2051 * without metadata change. A binary patch appears2052 * empty to us here.2053 */2054if((apply || check) &&2055(!patch->is_binary && !metadata_changes(patch)))2056die(_("patch with only garbage at line%d"), state_linenr);2057}20582059return offset + hdrsize + patchsize;2060}20612062#define swap(a,b) myswap((a),(b),sizeof(a))20632064#define myswap(a, b, size) do { \2065 unsigned char mytmp[size]; \2066 memcpy(mytmp, &a, size); \2067 memcpy(&a, &b, size); \2068 memcpy(&b, mytmp, size); \2069} while (0)20702071static voidreverse_patches(struct patch *p)2072{2073for(; p; p = p->next) {2074struct fragment *frag = p->fragments;20752076swap(p->new_name, p->old_name);2077swap(p->new_mode, p->old_mode);2078swap(p->is_new, p->is_delete);2079swap(p->lines_added, p->lines_deleted);2080swap(p->old_sha1_prefix, p->new_sha1_prefix);20812082for(; frag; frag = frag->next) {2083swap(frag->newpos, frag->oldpos);2084swap(frag->newlines, frag->oldlines);2085}2086}2087}20882089static const char pluses[] =2090"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2091static const char minuses[]=2092"----------------------------------------------------------------------";20932094static voidshow_stats(struct patch *patch)2095{2096struct strbuf qname = STRBUF_INIT;2097char*cp = patch->new_name ? patch->new_name : patch->old_name;2098int max, add, del;20992100quote_c_style(cp, &qname, NULL,0);21012102/*2103 * "scale" the filename2104 */2105 max = max_len;2106if(max >50)2107 max =50;21082109if(qname.len > max) {2110 cp =strchr(qname.buf + qname.len +3- max,'/');2111if(!cp)2112 cp = qname.buf + qname.len +3- max;2113strbuf_splice(&qname,0, cp - qname.buf,"...",3);2114}21152116if(patch->is_binary) {2117printf(" %-*s | Bin\n", max, qname.buf);2118strbuf_release(&qname);2119return;2120}21212122printf(" %-*s |", max, qname.buf);2123strbuf_release(&qname);21242125/*2126 * scale the add/delete2127 */2128 max = max + max_change >70?70- max : max_change;2129 add = patch->lines_added;2130 del = patch->lines_deleted;21312132if(max_change >0) {2133int total = ((add + del) * max + max_change /2) / max_change;2134 add = (add * max + max_change /2) / max_change;2135 del = total - add;2136}2137printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2138 add, pluses, del, minuses);2139}21402141static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2142{2143switch(st->st_mode & S_IFMT) {2144case S_IFLNK:2145if(strbuf_readlink(buf, path, st->st_size) <0)2146returnerror(_("unable to read symlink%s"), path);2147return0;2148case S_IFREG:2149if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2150returnerror(_("unable to open or read%s"), path);2151convert_to_git(path, buf->buf, buf->len, buf,0);2152return0;2153default:2154return-1;2155}2156}21572158/*2159 * Update the preimage, and the common lines in postimage,2160 * from buffer buf of length len. If postlen is 0 the postimage2161 * is updated in place, otherwise it's updated on a new buffer2162 * of length postlen2163 */21642165static voidupdate_pre_post_images(struct image *preimage,2166struct image *postimage,2167char*buf,2168size_t len,size_t postlen)2169{2170int i, ctx, reduced;2171char*new, *old, *fixed;2172struct image fixed_preimage;21732174/*2175 * Update the preimage with whitespace fixes. Note that we2176 * are not losing preimage->buf -- apply_one_fragment() will2177 * free "oldlines".2178 */2179prepare_image(&fixed_preimage, buf, len,1);2180assert(postlen2181? fixed_preimage.nr == preimage->nr2182: fixed_preimage.nr <= preimage->nr);2183for(i =0; i < fixed_preimage.nr; i++)2184 fixed_preimage.line[i].flag = preimage->line[i].flag;2185free(preimage->line_allocated);2186*preimage = fixed_preimage;21872188/*2189 * Adjust the common context lines in postimage. This can be2190 * done in-place when we are shrinking it with whitespace2191 * fixing, but needs a new buffer when ignoring whitespace or2192 * expanding leading tabs to spaces.2193 *2194 * We trust the caller to tell us if the update can be done2195 * in place (postlen==0) or not.2196 */2197 old = postimage->buf;2198if(postlen)2199new= postimage->buf =xmalloc(postlen);2200else2201new= old;2202 fixed = preimage->buf;22032204for(i = reduced = ctx =0; i < postimage->nr; i++) {2205size_t l_len = postimage->line[i].len;2206if(!(postimage->line[i].flag & LINE_COMMON)) {2207/* an added line -- no counterparts in preimage */2208memmove(new, old, l_len);2209 old += l_len;2210new+= l_len;2211continue;2212}22132214/* a common context -- skip it in the original postimage */2215 old += l_len;22162217/* and find the corresponding one in the fixed preimage */2218while(ctx < preimage->nr &&2219!(preimage->line[ctx].flag & LINE_COMMON)) {2220 fixed += preimage->line[ctx].len;2221 ctx++;2222}22232224/*2225 * preimage is expected to run out, if the caller2226 * fixed addition of trailing blank lines.2227 */2228if(preimage->nr <= ctx) {2229 reduced++;2230continue;2231}22322233/* and copy it in, while fixing the line length */2234 l_len = preimage->line[ctx].len;2235memcpy(new, fixed, l_len);2236new+= l_len;2237 fixed += l_len;2238 postimage->line[i].len = l_len;2239 ctx++;2240}22412242if(postlen2243? postlen <new- postimage->buf2244: postimage->len <new- postimage->buf)2245die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2246(int)postlen, (int) postimage->len, (int)(new- postimage->buf));22472248/* Fix the length of the whole thing */2249 postimage->len =new- postimage->buf;2250 postimage->nr -= reduced;2251}22522253static intline_by_line_fuzzy_match(struct image *img,2254struct image *preimage,2255struct image *postimage,2256unsigned longtry,2257int try_lno,2258int preimage_limit)2259{2260int i;2261size_t imgoff =0;2262size_t preoff =0;2263size_t postlen = postimage->len;2264size_t extra_chars;2265char*buf;2266char*preimage_eof;2267char*preimage_end;2268struct strbuf fixed;2269char*fixed_buf;2270size_t fixed_len;22712272for(i =0; i < preimage_limit; i++) {2273size_t prelen = preimage->line[i].len;2274size_t imglen = img->line[try_lno+i].len;22752276if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2277 preimage->buf + preoff, prelen))2278return0;2279if(preimage->line[i].flag & LINE_COMMON)2280 postlen += imglen - prelen;2281 imgoff += imglen;2282 preoff += prelen;2283}22842285/*2286 * Ok, the preimage matches with whitespace fuzz.2287 *2288 * imgoff now holds the true length of the target that2289 * matches the preimage before the end of the file.2290 *2291 * Count the number of characters in the preimage that fall2292 * beyond the end of the file and make sure that all of them2293 * are whitespace characters. (This can only happen if2294 * we are removing blank lines at the end of the file.)2295 */2296 buf = preimage_eof = preimage->buf + preoff;2297for( ; i < preimage->nr; i++)2298 preoff += preimage->line[i].len;2299 preimage_end = preimage->buf + preoff;2300for( ; buf < preimage_end; buf++)2301if(!isspace(*buf))2302return0;23032304/*2305 * Update the preimage and the common postimage context2306 * lines to use the same whitespace as the target.2307 * If whitespace is missing in the target (i.e.2308 * if the preimage extends beyond the end of the file),2309 * use the whitespace from the preimage.2310 */2311 extra_chars = preimage_end - preimage_eof;2312strbuf_init(&fixed, imgoff + extra_chars);2313strbuf_add(&fixed, img->buf +try, imgoff);2314strbuf_add(&fixed, preimage_eof, extra_chars);2315 fixed_buf =strbuf_detach(&fixed, &fixed_len);2316update_pre_post_images(preimage, postimage,2317 fixed_buf, fixed_len, postlen);2318return1;2319}23202321static intmatch_fragment(struct image *img,2322struct image *preimage,2323struct image *postimage,2324unsigned longtry,2325int try_lno,2326unsigned ws_rule,2327int match_beginning,int match_end)2328{2329int i;2330char*fixed_buf, *buf, *orig, *target;2331struct strbuf fixed;2332size_t fixed_len, postlen;2333int preimage_limit;23342335if(preimage->nr + try_lno <= img->nr) {2336/*2337 * The hunk falls within the boundaries of img.2338 */2339 preimage_limit = preimage->nr;2340if(match_end && (preimage->nr + try_lno != img->nr))2341return0;2342}else if(ws_error_action == correct_ws_error &&2343(ws_rule & WS_BLANK_AT_EOF)) {2344/*2345 * This hunk extends beyond the end of img, and we are2346 * removing blank lines at the end of the file. This2347 * many lines from the beginning of the preimage must2348 * match with img, and the remainder of the preimage2349 * must be blank.2350 */2351 preimage_limit = img->nr - try_lno;2352}else{2353/*2354 * The hunk extends beyond the end of the img and2355 * we are not removing blanks at the end, so we2356 * should reject the hunk at this position.2357 */2358return0;2359}23602361if(match_beginning && try_lno)2362return0;23632364/* Quick hash check */2365for(i =0; i < preimage_limit; i++)2366if((img->line[try_lno + i].flag & LINE_PATCHED) ||2367(preimage->line[i].hash != img->line[try_lno + i].hash))2368return0;23692370if(preimage_limit == preimage->nr) {2371/*2372 * Do we have an exact match? If we were told to match2373 * at the end, size must be exactly at try+fragsize,2374 * otherwise try+fragsize must be still within the preimage,2375 * and either case, the old piece should match the preimage2376 * exactly.2377 */2378if((match_end2379? (try+ preimage->len == img->len)2380: (try+ preimage->len <= img->len)) &&2381!memcmp(img->buf +try, preimage->buf, preimage->len))2382return1;2383}else{2384/*2385 * The preimage extends beyond the end of img, so2386 * there cannot be an exact match.2387 *2388 * There must be one non-blank context line that match2389 * a line before the end of img.2390 */2391char*buf_end;23922393 buf = preimage->buf;2394 buf_end = buf;2395for(i =0; i < preimage_limit; i++)2396 buf_end += preimage->line[i].len;23972398for( ; buf < buf_end; buf++)2399if(!isspace(*buf))2400break;2401if(buf == buf_end)2402return0;2403}24042405/*2406 * No exact match. If we are ignoring whitespace, run a line-by-line2407 * fuzzy matching. We collect all the line length information because2408 * we need it to adjust whitespace if we match.2409 */2410if(ws_ignore_action == ignore_ws_change)2411returnline_by_line_fuzzy_match(img, preimage, postimage,2412try, try_lno, preimage_limit);24132414if(ws_error_action != correct_ws_error)2415return0;24162417/*2418 * The hunk does not apply byte-by-byte, but the hash says2419 * it might with whitespace fuzz. We weren't asked to2420 * ignore whitespace, we were asked to correct whitespace2421 * errors, so let's try matching after whitespace correction.2422 *2423 * While checking the preimage against the target, whitespace2424 * errors in both fixed, we count how large the corresponding2425 * postimage needs to be. The postimage prepared by2426 * apply_one_fragment() has whitespace errors fixed on added2427 * lines already, but the common lines were propagated as-is,2428 * which may become longer when their whitespace errors are2429 * fixed.2430 */24312432/* First count added lines in postimage */2433 postlen =0;2434for(i =0; i < postimage->nr; i++) {2435if(!(postimage->line[i].flag & LINE_COMMON))2436 postlen += postimage->line[i].len;2437}24382439/*2440 * The preimage may extend beyond the end of the file,2441 * but in this loop we will only handle the part of the2442 * preimage that falls within the file.2443 */2444strbuf_init(&fixed, preimage->len +1);2445 orig = preimage->buf;2446 target = img->buf +try;2447for(i =0; i < preimage_limit; i++) {2448size_t oldlen = preimage->line[i].len;2449size_t tgtlen = img->line[try_lno + i].len;2450size_t fixstart = fixed.len;2451struct strbuf tgtfix;2452int match;24532454/* Try fixing the line in the preimage */2455ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24562457/* Try fixing the line in the target */2458strbuf_init(&tgtfix, tgtlen);2459ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);24602461/*2462 * If they match, either the preimage was based on2463 * a version before our tree fixed whitespace breakage,2464 * or we are lacking a whitespace-fix patch the tree2465 * the preimage was based on already had (i.e. target2466 * has whitespace breakage, the preimage doesn't).2467 * In either case, we are fixing the whitespace breakages2468 * so we might as well take the fix together with their2469 * real change.2470 */2471 match = (tgtfix.len == fixed.len - fixstart &&2472!memcmp(tgtfix.buf, fixed.buf + fixstart,2473 fixed.len - fixstart));24742475/* Add the length if this is common with the postimage */2476if(preimage->line[i].flag & LINE_COMMON)2477 postlen += tgtfix.len;24782479strbuf_release(&tgtfix);2480if(!match)2481goto unmatch_exit;24822483 orig += oldlen;2484 target += tgtlen;2485}248624872488/*2489 * Now handle the lines in the preimage that falls beyond the2490 * end of the file (if any). They will only match if they are2491 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2492 * false).2493 */2494for( ; i < preimage->nr; i++) {2495size_t fixstart = fixed.len;/* start of the fixed preimage */2496size_t oldlen = preimage->line[i].len;2497int j;24982499/* Try fixing the line in the preimage */2500ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25012502for(j = fixstart; j < fixed.len; j++)2503if(!isspace(fixed.buf[j]))2504goto unmatch_exit;25052506 orig += oldlen;2507}25082509/*2510 * Yes, the preimage is based on an older version that still2511 * has whitespace breakages unfixed, and fixing them makes the2512 * hunk match. Update the context lines in the postimage.2513 */2514 fixed_buf =strbuf_detach(&fixed, &fixed_len);2515if(postlen < postimage->len)2516 postlen =0;2517update_pre_post_images(preimage, postimage,2518 fixed_buf, fixed_len, postlen);2519return1;25202521 unmatch_exit:2522strbuf_release(&fixed);2523return0;2524}25252526static intfind_pos(struct image *img,2527struct image *preimage,2528struct image *postimage,2529int line,2530unsigned ws_rule,2531int match_beginning,int match_end)2532{2533int i;2534unsigned long backwards, forwards,try;2535int backwards_lno, forwards_lno, try_lno;25362537/*2538 * If match_beginning or match_end is specified, there is no2539 * point starting from a wrong line that will never match and2540 * wander around and wait for a match at the specified end.2541 */2542if(match_beginning)2543 line =0;2544else if(match_end)2545 line = img->nr - preimage->nr;25462547/*2548 * Because the comparison is unsigned, the following test2549 * will also take care of a negative line number that can2550 * result when match_end and preimage is larger than the target.2551 */2552if((size_t) line > img->nr)2553 line = img->nr;25542555try=0;2556for(i =0; i < line; i++)2557try+= img->line[i].len;25582559/*2560 * There's probably some smart way to do this, but I'll leave2561 * that to the smart and beautiful people. I'm simple and stupid.2562 */2563 backwards =try;2564 backwards_lno = line;2565 forwards =try;2566 forwards_lno = line;2567 try_lno = line;25682569for(i =0; ; i++) {2570if(match_fragment(img, preimage, postimage,2571try, try_lno, ws_rule,2572 match_beginning, match_end))2573return try_lno;25742575 again:2576if(backwards_lno ==0&& forwards_lno == img->nr)2577break;25782579if(i &1) {2580if(backwards_lno ==0) {2581 i++;2582goto again;2583}2584 backwards_lno--;2585 backwards -= img->line[backwards_lno].len;2586try= backwards;2587 try_lno = backwards_lno;2588}else{2589if(forwards_lno == img->nr) {2590 i++;2591goto again;2592}2593 forwards += img->line[forwards_lno].len;2594 forwards_lno++;2595try= forwards;2596 try_lno = forwards_lno;2597}25982599}2600return-1;2601}26022603static voidremove_first_line(struct image *img)2604{2605 img->buf += img->line[0].len;2606 img->len -= img->line[0].len;2607 img->line++;2608 img->nr--;2609}26102611static voidremove_last_line(struct image *img)2612{2613 img->len -= img->line[--img->nr].len;2614}26152616/*2617 * The change from "preimage" and "postimage" has been found to2618 * apply at applied_pos (counts in line numbers) in "img".2619 * Update "img" to remove "preimage" and replace it with "postimage".2620 */2621static voidupdate_image(struct image *img,2622int applied_pos,2623struct image *preimage,2624struct image *postimage)2625{2626/*2627 * remove the copy of preimage at offset in img2628 * and replace it with postimage2629 */2630int i, nr;2631size_t remove_count, insert_count, applied_at =0;2632char*result;2633int preimage_limit;26342635/*2636 * If we are removing blank lines at the end of img,2637 * the preimage may extend beyond the end.2638 * If that is the case, we must be careful only to2639 * remove the part of the preimage that falls within2640 * the boundaries of img. Initialize preimage_limit2641 * to the number of lines in the preimage that falls2642 * within the boundaries.2643 */2644 preimage_limit = preimage->nr;2645if(preimage_limit > img->nr - applied_pos)2646 preimage_limit = img->nr - applied_pos;26472648for(i =0; i < applied_pos; i++)2649 applied_at += img->line[i].len;26502651 remove_count =0;2652for(i =0; i < preimage_limit; i++)2653 remove_count += img->line[applied_pos + i].len;2654 insert_count = postimage->len;26552656/* Adjust the contents */2657 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2658memcpy(result, img->buf, applied_at);2659memcpy(result + applied_at, postimage->buf, postimage->len);2660memcpy(result + applied_at + postimage->len,2661 img->buf + (applied_at + remove_count),2662 img->len - (applied_at + remove_count));2663free(img->buf);2664 img->buf = result;2665 img->len += insert_count - remove_count;2666 result[img->len] ='\0';26672668/* Adjust the line table */2669 nr = img->nr + postimage->nr - preimage_limit;2670if(preimage_limit < postimage->nr) {2671/*2672 * NOTE: this knows that we never call remove_first_line()2673 * on anything other than pre/post image.2674 */2675REALLOC_ARRAY(img->line, nr);2676 img->line_allocated = img->line;2677}2678if(preimage_limit != postimage->nr)2679memmove(img->line + applied_pos + postimage->nr,2680 img->line + applied_pos + preimage_limit,2681(img->nr - (applied_pos + preimage_limit)) *2682sizeof(*img->line));2683memcpy(img->line + applied_pos,2684 postimage->line,2685 postimage->nr *sizeof(*img->line));2686if(!allow_overlap)2687for(i =0; i < postimage->nr; i++)2688 img->line[applied_pos + i].flag |= LINE_PATCHED;2689 img->nr = nr;2690}26912692/*2693 * Use the patch-hunk text in "frag" to prepare two images (preimage and2694 * postimage) for the hunk. Find lines that match "preimage" in "img" and2695 * replace the part of "img" with "postimage" text.2696 */2697static intapply_one_fragment(struct image *img,struct fragment *frag,2698int inaccurate_eof,unsigned ws_rule,2699int nth_fragment)2700{2701int match_beginning, match_end;2702const char*patch = frag->patch;2703int size = frag->size;2704char*old, *oldlines;2705struct strbuf newlines;2706int new_blank_lines_at_end =0;2707int found_new_blank_lines_at_end =0;2708int hunk_linenr = frag->linenr;2709unsigned long leading, trailing;2710int pos, applied_pos;2711struct image preimage;2712struct image postimage;27132714memset(&preimage,0,sizeof(preimage));2715memset(&postimage,0,sizeof(postimage));2716 oldlines =xmalloc(size);2717strbuf_init(&newlines, size);27182719 old = oldlines;2720while(size >0) {2721char first;2722int len =linelen(patch, size);2723int plen;2724int added_blank_line =0;2725int is_blank_context =0;2726size_t start;27272728if(!len)2729break;27302731/*2732 * "plen" is how much of the line we should use for2733 * the actual patch data. Normally we just remove the2734 * first character on the line, but if the line is2735 * followed by "\ No newline", then we also remove the2736 * last one (which is the newline, of course).2737 */2738 plen = len -1;2739if(len < size && patch[len] =='\\')2740 plen--;2741 first = *patch;2742if(apply_in_reverse) {2743if(first =='-')2744 first ='+';2745else if(first =='+')2746 first ='-';2747}27482749switch(first) {2750case'\n':2751/* Newer GNU diff, empty context line */2752if(plen <0)2753/* ... followed by '\No newline'; nothing */2754break;2755*old++ ='\n';2756strbuf_addch(&newlines,'\n');2757add_line_info(&preimage,"\n",1, LINE_COMMON);2758add_line_info(&postimage,"\n",1, LINE_COMMON);2759 is_blank_context =1;2760break;2761case' ':2762if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2763ws_blank_line(patch +1, plen, ws_rule))2764 is_blank_context =1;2765case'-':2766memcpy(old, patch +1, plen);2767add_line_info(&preimage, old, plen,2768(first ==' '? LINE_COMMON :0));2769 old += plen;2770if(first =='-')2771break;2772/* Fall-through for ' ' */2773case'+':2774/* --no-add does not add new lines */2775if(first =='+'&& no_add)2776break;27772778 start = newlines.len;2779if(first !='+'||2780!whitespace_error ||2781 ws_error_action != correct_ws_error) {2782strbuf_add(&newlines, patch +1, plen);2783}2784else{2785ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2786}2787add_line_info(&postimage, newlines.buf + start, newlines.len - start,2788(first =='+'?0: LINE_COMMON));2789if(first =='+'&&2790(ws_rule & WS_BLANK_AT_EOF) &&2791ws_blank_line(patch +1, plen, ws_rule))2792 added_blank_line =1;2793break;2794case'@':case'\\':2795/* Ignore it, we already handled it */2796break;2797default:2798if(apply_verbosely)2799error(_("invalid start of line: '%c'"), first);2800 applied_pos = -1;2801goto out;2802}2803if(added_blank_line) {2804if(!new_blank_lines_at_end)2805 found_new_blank_lines_at_end = hunk_linenr;2806 new_blank_lines_at_end++;2807}2808else if(is_blank_context)2809;2810else2811 new_blank_lines_at_end =0;2812 patch += len;2813 size -= len;2814 hunk_linenr++;2815}2816if(inaccurate_eof &&2817 old > oldlines && old[-1] =='\n'&&2818 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2819 old--;2820strbuf_setlen(&newlines, newlines.len -1);2821}28222823 leading = frag->leading;2824 trailing = frag->trailing;28252826/*2827 * A hunk to change lines at the beginning would begin with2828 * @@ -1,L +N,M @@2829 * but we need to be careful. -U0 that inserts before the second2830 * line also has this pattern.2831 *2832 * And a hunk to add to an empty file would begin with2833 * @@ -0,0 +N,M @@2834 *2835 * In other words, a hunk that is (frag->oldpos <= 1) with or2836 * without leading context must match at the beginning.2837 */2838 match_beginning = (!frag->oldpos ||2839(frag->oldpos ==1&& !unidiff_zero));28402841/*2842 * A hunk without trailing lines must match at the end.2843 * However, we simply cannot tell if a hunk must match end2844 * from the lack of trailing lines if the patch was generated2845 * with unidiff without any context.2846 */2847 match_end = !unidiff_zero && !trailing;28482849 pos = frag->newpos ? (frag->newpos -1) :0;2850 preimage.buf = oldlines;2851 preimage.len = old - oldlines;2852 postimage.buf = newlines.buf;2853 postimage.len = newlines.len;2854 preimage.line = preimage.line_allocated;2855 postimage.line = postimage.line_allocated;28562857for(;;) {28582859 applied_pos =find_pos(img, &preimage, &postimage, pos,2860 ws_rule, match_beginning, match_end);28612862if(applied_pos >=0)2863break;28642865/* Am I at my context limits? */2866if((leading <= p_context) && (trailing <= p_context))2867break;2868if(match_beginning || match_end) {2869 match_beginning = match_end =0;2870continue;2871}28722873/*2874 * Reduce the number of context lines; reduce both2875 * leading and trailing if they are equal otherwise2876 * just reduce the larger context.2877 */2878if(leading >= trailing) {2879remove_first_line(&preimage);2880remove_first_line(&postimage);2881 pos--;2882 leading--;2883}2884if(trailing > leading) {2885remove_last_line(&preimage);2886remove_last_line(&postimage);2887 trailing--;2888}2889}28902891if(applied_pos >=0) {2892if(new_blank_lines_at_end &&2893 preimage.nr + applied_pos >= img->nr &&2894(ws_rule & WS_BLANK_AT_EOF) &&2895 ws_error_action != nowarn_ws_error) {2896record_ws_error(WS_BLANK_AT_EOF,"+",1,2897 found_new_blank_lines_at_end);2898if(ws_error_action == correct_ws_error) {2899while(new_blank_lines_at_end--)2900remove_last_line(&postimage);2901}2902/*2903 * We would want to prevent write_out_results()2904 * from taking place in apply_patch() that follows2905 * the callchain led us here, which is:2906 * apply_patch->check_patch_list->check_patch->2907 * apply_data->apply_fragments->apply_one_fragment2908 */2909if(ws_error_action == die_on_ws_error)2910 apply =0;2911}29122913if(apply_verbosely && applied_pos != pos) {2914int offset = applied_pos - pos;2915if(apply_in_reverse)2916 offset =0- offset;2917fprintf_ln(stderr,2918Q_("Hunk #%dsucceeded at%d(offset%dline).",2919"Hunk #%dsucceeded at%d(offset%dlines).",2920 offset),2921 nth_fragment, applied_pos +1, offset);2922}29232924/*2925 * Warn if it was necessary to reduce the number2926 * of context lines.2927 */2928if((leading != frag->leading) ||2929(trailing != frag->trailing))2930fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2931" to apply fragment at%d"),2932 leading, trailing, applied_pos+1);2933update_image(img, applied_pos, &preimage, &postimage);2934}else{2935if(apply_verbosely)2936error(_("while searching for:\n%.*s"),2937(int)(old - oldlines), oldlines);2938}29392940out:2941free(oldlines);2942strbuf_release(&newlines);2943free(preimage.line_allocated);2944free(postimage.line_allocated);29452946return(applied_pos <0);2947}29482949static intapply_binary_fragment(struct image *img,struct patch *patch)2950{2951struct fragment *fragment = patch->fragments;2952unsigned long len;2953void*dst;29542955if(!fragment)2956returnerror(_("missing binary patch data for '%s'"),2957 patch->new_name ?2958 patch->new_name :2959 patch->old_name);29602961/* Binary patch is irreversible without the optional second hunk */2962if(apply_in_reverse) {2963if(!fragment->next)2964returnerror("cannot reverse-apply a binary patch "2965"without the reverse hunk to '%s'",2966 patch->new_name2967? patch->new_name : patch->old_name);2968 fragment = fragment->next;2969}2970switch(fragment->binary_patch_method) {2971case BINARY_DELTA_DEFLATED:2972 dst =patch_delta(img->buf, img->len, fragment->patch,2973 fragment->size, &len);2974if(!dst)2975return-1;2976clear_image(img);2977 img->buf = dst;2978 img->len = len;2979return0;2980case BINARY_LITERAL_DEFLATED:2981clear_image(img);2982 img->len = fragment->size;2983 img->buf =xmemdupz(fragment->patch, img->len);2984return0;2985}2986return-1;2987}29882989/*2990 * Replace "img" with the result of applying the binary patch.2991 * The binary patch data itself in patch->fragment is still kept2992 * but the preimage prepared by the caller in "img" is freed here2993 * or in the helper function apply_binary_fragment() this calls.2994 */2995static intapply_binary(struct image *img,struct patch *patch)2996{2997const char*name = patch->old_name ? patch->old_name : patch->new_name;2998unsigned char sha1[20];29993000/*3001 * For safety, we require patch index line to contain3002 * full 40-byte textual SHA1 for old and new, at least for now.3003 */3004if(strlen(patch->old_sha1_prefix) !=40||3005strlen(patch->new_sha1_prefix) !=40||3006get_sha1_hex(patch->old_sha1_prefix, sha1) ||3007get_sha1_hex(patch->new_sha1_prefix, sha1))3008returnerror("cannot apply binary patch to '%s' "3009"without full index line", name);30103011if(patch->old_name) {3012/*3013 * See if the old one matches what the patch3014 * applies to.3015 */3016hash_sha1_file(img->buf, img->len, blob_type, sha1);3017if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3018returnerror("the patch applies to '%s' (%s), "3019"which does not match the "3020"current contents.",3021 name,sha1_to_hex(sha1));3022}3023else{3024/* Otherwise, the old one must be empty. */3025if(img->len)3026returnerror("the patch applies to an empty "3027"'%s' but it is not empty", name);3028}30293030get_sha1_hex(patch->new_sha1_prefix, sha1);3031if(is_null_sha1(sha1)) {3032clear_image(img);3033return0;/* deletion patch */3034}30353036if(has_sha1_file(sha1)) {3037/* We already have the postimage */3038enum object_type type;3039unsigned long size;3040char*result;30413042 result =read_sha1_file(sha1, &type, &size);3043if(!result)3044returnerror("the necessary postimage%sfor "3045"'%s' cannot be read",3046 patch->new_sha1_prefix, name);3047clear_image(img);3048 img->buf = result;3049 img->len = size;3050}else{3051/*3052 * We have verified buf matches the preimage;3053 * apply the patch data to it, which is stored3054 * in the patch->fragments->{patch,size}.3055 */3056if(apply_binary_fragment(img, patch))3057returnerror(_("binary patch does not apply to '%s'"),3058 name);30593060/* verify that the result matches */3061hash_sha1_file(img->buf, img->len, blob_type, sha1);3062if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3063returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3064 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3065}30663067return0;3068}30693070static intapply_fragments(struct image *img,struct patch *patch)3071{3072struct fragment *frag = patch->fragments;3073const char*name = patch->old_name ? patch->old_name : patch->new_name;3074unsigned ws_rule = patch->ws_rule;3075unsigned inaccurate_eof = patch->inaccurate_eof;3076int nth =0;30773078if(patch->is_binary)3079returnapply_binary(img, patch);30803081while(frag) {3082 nth++;3083if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {3084error(_("patch failed:%s:%ld"), name, frag->oldpos);3085if(!apply_with_reject)3086return-1;3087 frag->rejected =1;3088}3089 frag = frag->next;3090}3091return0;3092}30933094static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3095{3096if(S_ISGITLINK(mode)) {3097strbuf_grow(buf,100);3098strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3099}else{3100enum object_type type;3101unsigned long sz;3102char*result;31033104 result =read_sha1_file(sha1, &type, &sz);3105if(!result)3106return-1;3107/* XXX read_sha1_file NUL-terminates */3108strbuf_attach(buf, result, sz, sz +1);3109}3110return0;3111}31123113static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3114{3115if(!ce)3116return0;3117returnread_blob_object(buf, ce->sha1, ce->ce_mode);3118}31193120static struct patch *in_fn_table(const char*name)3121{3122struct string_list_item *item;31233124if(name == NULL)3125return NULL;31263127 item =string_list_lookup(&fn_table, name);3128if(item != NULL)3129return(struct patch *)item->util;31303131return NULL;3132}31333134/*3135 * item->util in the filename table records the status of the path.3136 * Usually it points at a patch (whose result records the contents3137 * of it after applying it), but it could be PATH_WAS_DELETED for a3138 * path that a previously applied patch has already removed, or3139 * PATH_TO_BE_DELETED for a path that a later patch would remove.3140 *3141 * The latter is needed to deal with a case where two paths A and B3142 * are swapped by first renaming A to B and then renaming B to A;3143 * moving A to B should not be prevented due to presence of B as we3144 * will remove it in a later patch.3145 */3146#define PATH_TO_BE_DELETED ((struct patch *) -2)3147#define PATH_WAS_DELETED ((struct patch *) -1)31483149static intto_be_deleted(struct patch *patch)3150{3151return patch == PATH_TO_BE_DELETED;3152}31533154static intwas_deleted(struct patch *patch)3155{3156return patch == PATH_WAS_DELETED;3157}31583159static voidadd_to_fn_table(struct patch *patch)3160{3161struct string_list_item *item;31623163/*3164 * Always add new_name unless patch is a deletion3165 * This should cover the cases for normal diffs,3166 * file creations and copies3167 */3168if(patch->new_name != NULL) {3169 item =string_list_insert(&fn_table, patch->new_name);3170 item->util = patch;3171}31723173/*3174 * store a failure on rename/deletion cases because3175 * later chunks shouldn't patch old names3176 */3177if((patch->new_name == NULL) || (patch->is_rename)) {3178 item =string_list_insert(&fn_table, patch->old_name);3179 item->util = PATH_WAS_DELETED;3180}3181}31823183static voidprepare_fn_table(struct patch *patch)3184{3185/*3186 * store information about incoming file deletion3187 */3188while(patch) {3189if((patch->new_name == NULL) || (patch->is_rename)) {3190struct string_list_item *item;3191 item =string_list_insert(&fn_table, patch->old_name);3192 item->util = PATH_TO_BE_DELETED;3193}3194 patch = patch->next;3195}3196}31973198static intcheckout_target(struct index_state *istate,3199struct cache_entry *ce,struct stat *st)3200{3201struct checkout costate;32023203memset(&costate,0,sizeof(costate));3204 costate.base_dir ="";3205 costate.refresh_cache =1;3206 costate.istate = istate;3207if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3208returnerror(_("cannot checkout%s"), ce->name);3209return0;3210}32113212static struct patch *previous_patch(struct patch *patch,int*gone)3213{3214struct patch *previous;32153216*gone =0;3217if(patch->is_copy || patch->is_rename)3218return NULL;/* "git" patches do not depend on the order */32193220 previous =in_fn_table(patch->old_name);3221if(!previous)3222return NULL;32233224if(to_be_deleted(previous))3225return NULL;/* the deletion hasn't happened yet */32263227if(was_deleted(previous))3228*gone =1;32293230return previous;3231}32323233static intverify_index_match(const struct cache_entry *ce,struct stat *st)3234{3235if(S_ISGITLINK(ce->ce_mode)) {3236if(!S_ISDIR(st->st_mode))3237return-1;3238return0;3239}3240returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3241}32423243#define SUBMODULE_PATCH_WITHOUT_INDEX 132443245static intload_patch_target(struct strbuf *buf,3246const struct cache_entry *ce,3247struct stat *st,3248const char*name,3249unsigned expected_mode)3250{3251if(cached || check_index) {3252if(read_file_or_gitlink(ce, buf))3253returnerror(_("read of%sfailed"), name);3254}else if(name) {3255if(S_ISGITLINK(expected_mode)) {3256if(ce)3257returnread_file_or_gitlink(ce, buf);3258else3259return SUBMODULE_PATCH_WITHOUT_INDEX;3260}else if(has_symlink_leading_path(name,strlen(name))) {3261returnerror(_("reading from '%s' beyond a symbolic link"), name);3262}else{3263if(read_old_data(st, name, buf))3264returnerror(_("read of%sfailed"), name);3265}3266}3267return0;3268}32693270/*3271 * We are about to apply "patch"; populate the "image" with the3272 * current version we have, from the working tree or from the index,3273 * depending on the situation e.g. --cached/--index. If we are3274 * applying a non-git patch that incrementally updates the tree,3275 * we read from the result of a previous diff.3276 */3277static intload_preimage(struct image *image,3278struct patch *patch,struct stat *st,3279const struct cache_entry *ce)3280{3281struct strbuf buf = STRBUF_INIT;3282size_t len;3283char*img;3284struct patch *previous;3285int status;32863287 previous =previous_patch(patch, &status);3288if(status)3289returnerror(_("path%shas been renamed/deleted"),3290 patch->old_name);3291if(previous) {3292/* We have a patched copy in memory; use that. */3293strbuf_add(&buf, previous->result, previous->resultsize);3294}else{3295 status =load_patch_target(&buf, ce, st,3296 patch->old_name, patch->old_mode);3297if(status <0)3298return status;3299else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3300/*3301 * There is no way to apply subproject3302 * patch without looking at the index.3303 * NEEDSWORK: shouldn't this be flagged3304 * as an error???3305 */3306free_fragment_list(patch->fragments);3307 patch->fragments = NULL;3308}else if(status) {3309returnerror(_("read of%sfailed"), patch->old_name);3310}3311}33123313 img =strbuf_detach(&buf, &len);3314prepare_image(image, img, len, !patch->is_binary);3315return0;3316}33173318static intthree_way_merge(struct image *image,3319char*path,3320const unsigned char*base,3321const unsigned char*ours,3322const unsigned char*theirs)3323{3324 mmfile_t base_file, our_file, their_file;3325 mmbuffer_t result = { NULL };3326int status;33273328read_mmblob(&base_file, base);3329read_mmblob(&our_file, ours);3330read_mmblob(&their_file, theirs);3331 status =ll_merge(&result, path,3332&base_file,"base",3333&our_file,"ours",3334&their_file,"theirs", NULL);3335free(base_file.ptr);3336free(our_file.ptr);3337free(their_file.ptr);3338if(status <0|| !result.ptr) {3339free(result.ptr);3340return-1;3341}3342clear_image(image);3343 image->buf = result.ptr;3344 image->len = result.size;33453346return status;3347}33483349/*3350 * When directly falling back to add/add three-way merge, we read from3351 * the current contents of the new_name. In no cases other than that3352 * this function will be called.3353 */3354static intload_current(struct image *image,struct patch *patch)3355{3356struct strbuf buf = STRBUF_INIT;3357int status, pos;3358size_t len;3359char*img;3360struct stat st;3361struct cache_entry *ce;3362char*name = patch->new_name;3363unsigned mode = patch->new_mode;33643365if(!patch->is_new)3366die("BUG: patch to%sis not a creation", patch->old_name);33673368 pos =cache_name_pos(name,strlen(name));3369if(pos <0)3370returnerror(_("%s: does not exist in index"), name);3371 ce = active_cache[pos];3372if(lstat(name, &st)) {3373if(errno != ENOENT)3374returnerror(_("%s:%s"), name,strerror(errno));3375if(checkout_target(&the_index, ce, &st))3376return-1;3377}3378if(verify_index_match(ce, &st))3379returnerror(_("%s: does not match index"), name);33803381 status =load_patch_target(&buf, ce, &st, name, mode);3382if(status <0)3383return status;3384else if(status)3385return-1;3386 img =strbuf_detach(&buf, &len);3387prepare_image(image, img, len, !patch->is_binary);3388return0;3389}33903391static inttry_threeway(struct image *image,struct patch *patch,3392struct stat *st,const struct cache_entry *ce)3393{3394unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3395struct strbuf buf = STRBUF_INIT;3396size_t len;3397int status;3398char*img;3399struct image tmp_image;34003401/* No point falling back to 3-way merge in these cases */3402if(patch->is_delete ||3403S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3404return-1;34053406/* Preimage the patch was prepared for */3407if(patch->is_new)3408write_sha1_file("",0, blob_type, pre_sha1);3409else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3410read_blob_object(&buf, pre_sha1, patch->old_mode))3411returnerror("repository lacks the necessary blob to fall back on 3-way merge.");34123413fprintf(stderr,"Falling back to three-way merge...\n");34143415 img =strbuf_detach(&buf, &len);3416prepare_image(&tmp_image, img, len,1);3417/* Apply the patch to get the post image */3418if(apply_fragments(&tmp_image, patch) <0) {3419clear_image(&tmp_image);3420return-1;3421}3422/* post_sha1[] is theirs */3423write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3424clear_image(&tmp_image);34253426/* our_sha1[] is ours */3427if(patch->is_new) {3428if(load_current(&tmp_image, patch))3429returnerror("cannot read the current contents of '%s'",3430 patch->new_name);3431}else{3432if(load_preimage(&tmp_image, patch, st, ce))3433returnerror("cannot read the current contents of '%s'",3434 patch->old_name);3435}3436write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3437clear_image(&tmp_image);34383439/* in-core three-way merge between post and our using pre as base */3440 status =three_way_merge(image, patch->new_name,3441 pre_sha1, our_sha1, post_sha1);3442if(status <0) {3443fprintf(stderr,"Failed to fall back on three-way merge...\n");3444return status;3445}34463447if(status) {3448 patch->conflicted_threeway =1;3449if(patch->is_new)3450oidclr(&patch->threeway_stage[0]);3451else3452hashcpy(patch->threeway_stage[0].hash, pre_sha1);3453hashcpy(patch->threeway_stage[1].hash, our_sha1);3454hashcpy(patch->threeway_stage[2].hash, post_sha1);3455fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3456}else{3457fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3458}3459return0;3460}34613462static intapply_data(struct patch *patch,struct stat *st,const struct cache_entry *ce)3463{3464struct image image;34653466if(load_preimage(&image, patch, st, ce) <0)3467return-1;34683469if(patch->direct_to_threeway ||3470apply_fragments(&image, patch) <0) {3471/* Note: with --reject, apply_fragments() returns 0 */3472if(!threeway ||try_threeway(&image, patch, st, ce) <0)3473return-1;3474}3475 patch->result = image.buf;3476 patch->resultsize = image.len;3477add_to_fn_table(patch);3478free(image.line_allocated);34793480if(0< patch->is_delete && patch->resultsize)3481returnerror(_("removal patch leaves file contents"));34823483return0;3484}34853486/*3487 * If "patch" that we are looking at modifies or deletes what we have,3488 * we would want it not to lose any local modification we have, either3489 * in the working tree or in the index.3490 *3491 * This also decides if a non-git patch is a creation patch or a3492 * modification to an existing empty file. We do not check the state3493 * of the current tree for a creation patch in this function; the caller3494 * check_patch() separately makes sure (and errors out otherwise) that3495 * the path the patch creates does not exist in the current tree.3496 */3497static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)3498{3499const char*old_name = patch->old_name;3500struct patch *previous = NULL;3501int stat_ret =0, status;3502unsigned st_mode =0;35033504if(!old_name)3505return0;35063507assert(patch->is_new <=0);3508 previous =previous_patch(patch, &status);35093510if(status)3511returnerror(_("path%shas been renamed/deleted"), old_name);3512if(previous) {3513 st_mode = previous->new_mode;3514}else if(!cached) {3515 stat_ret =lstat(old_name, st);3516if(stat_ret && errno != ENOENT)3517returnerror(_("%s:%s"), old_name,strerror(errno));3518}35193520if(check_index && !previous) {3521int pos =cache_name_pos(old_name,strlen(old_name));3522if(pos <0) {3523if(patch->is_new <0)3524goto is_new;3525returnerror(_("%s: does not exist in index"), old_name);3526}3527*ce = active_cache[pos];3528if(stat_ret <0) {3529if(checkout_target(&the_index, *ce, st))3530return-1;3531}3532if(!cached &&verify_index_match(*ce, st))3533returnerror(_("%s: does not match index"), old_name);3534if(cached)3535 st_mode = (*ce)->ce_mode;3536}else if(stat_ret <0) {3537if(patch->is_new <0)3538goto is_new;3539returnerror(_("%s:%s"), old_name,strerror(errno));3540}35413542if(!cached && !previous)3543 st_mode =ce_mode_from_stat(*ce, st->st_mode);35443545if(patch->is_new <0)3546 patch->is_new =0;3547if(!patch->old_mode)3548 patch->old_mode = st_mode;3549if((st_mode ^ patch->old_mode) & S_IFMT)3550returnerror(_("%s: wrong type"), old_name);3551if(st_mode != patch->old_mode)3552warning(_("%shas type%o, expected%o"),3553 old_name, st_mode, patch->old_mode);3554if(!patch->new_mode && !patch->is_delete)3555 patch->new_mode = st_mode;3556return0;35573558 is_new:3559 patch->is_new =1;3560 patch->is_delete =0;3561free(patch->old_name);3562 patch->old_name = NULL;3563return0;3564}356535663567#define EXISTS_IN_INDEX 13568#define EXISTS_IN_WORKTREE 235693570static intcheck_to_create(const char*new_name,int ok_if_exists)3571{3572struct stat nst;35733574if(check_index &&3575cache_name_pos(new_name,strlen(new_name)) >=0&&3576!ok_if_exists)3577return EXISTS_IN_INDEX;3578if(cached)3579return0;35803581if(!lstat(new_name, &nst)) {3582if(S_ISDIR(nst.st_mode) || ok_if_exists)3583return0;3584/*3585 * A leading component of new_name might be a symlink3586 * that is going to be removed with this patch, but3587 * still pointing at somewhere that has the path.3588 * In such a case, path "new_name" does not exist as3589 * far as git is concerned.3590 */3591if(has_symlink_leading_path(new_name,strlen(new_name)))3592return0;35933594return EXISTS_IN_WORKTREE;3595}else if((errno != ENOENT) && (errno != ENOTDIR)) {3596returnerror("%s:%s", new_name,strerror(errno));3597}3598return0;3599}36003601/*3602 * We need to keep track of how symlinks in the preimage are3603 * manipulated by the patches. A patch to add a/b/c where a/b3604 * is a symlink should not be allowed to affect the directory3605 * the symlink points at, but if the same patch removes a/b,3606 * it is perfectly fine, as the patch removes a/b to make room3607 * to create a directory a/b so that a/b/c can be created.3608 */3609static struct string_list symlink_changes;3610#define SYMLINK_GOES_AWAY 013611#define SYMLINK_IN_RESULT 0236123613static uintptr_tregister_symlink_changes(const char*path,uintptr_t what)3614{3615struct string_list_item *ent;36163617 ent =string_list_lookup(&symlink_changes, path);3618if(!ent) {3619 ent =string_list_insert(&symlink_changes, path);3620 ent->util = (void*)0;3621}3622 ent->util = (void*)(what | ((uintptr_t)ent->util));3623return(uintptr_t)ent->util;3624}36253626static uintptr_tcheck_symlink_changes(const char*path)3627{3628struct string_list_item *ent;36293630 ent =string_list_lookup(&symlink_changes, path);3631if(!ent)3632return0;3633return(uintptr_t)ent->util;3634}36353636static voidprepare_symlink_changes(struct patch *patch)3637{3638for( ; patch; patch = patch->next) {3639if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3640(patch->is_rename || patch->is_delete))3641/* the symlink at patch->old_name is removed */3642register_symlink_changes(patch->old_name, SYMLINK_GOES_AWAY);36433644if(patch->new_name &&S_ISLNK(patch->new_mode))3645/* the symlink at patch->new_name is created or remains */3646register_symlink_changes(patch->new_name, SYMLINK_IN_RESULT);3647}3648}36493650static intpath_is_beyond_symlink_1(struct strbuf *name)3651{3652do{3653unsigned int change;36543655while(--name->len && name->buf[name->len] !='/')3656;/* scan backwards */3657if(!name->len)3658break;3659 name->buf[name->len] ='\0';3660 change =check_symlink_changes(name->buf);3661if(change & SYMLINK_IN_RESULT)3662return1;3663if(change & SYMLINK_GOES_AWAY)3664/*3665 * This cannot be "return 0", because we may3666 * see a new one created at a higher level.3667 */3668continue;36693670/* otherwise, check the preimage */3671if(check_index) {3672struct cache_entry *ce;36733674 ce =cache_file_exists(name->buf, name->len, ignore_case);3675if(ce &&S_ISLNK(ce->ce_mode))3676return1;3677}else{3678struct stat st;3679if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3680return1;3681}3682}while(1);3683return0;3684}36853686static intpath_is_beyond_symlink(const char*name_)3687{3688int ret;3689struct strbuf name = STRBUF_INIT;36903691assert(*name_ !='\0');3692strbuf_addstr(&name, name_);3693 ret =path_is_beyond_symlink_1(&name);3694strbuf_release(&name);36953696return ret;3697}36983699static voiddie_on_unsafe_path(struct patch *patch)3700{3701const char*old_name = NULL;3702const char*new_name = NULL;3703if(patch->is_delete)3704 old_name = patch->old_name;3705else if(!patch->is_new && !patch->is_copy)3706 old_name = patch->old_name;3707if(!patch->is_delete)3708 new_name = patch->new_name;37093710if(old_name && !verify_path(old_name))3711die(_("invalid path '%s'"), old_name);3712if(new_name && !verify_path(new_name))3713die(_("invalid path '%s'"), new_name);3714}37153716/*3717 * Check and apply the patch in-core; leave the result in patch->result3718 * for the caller to write it out to the final destination.3719 */3720static intcheck_patch(struct patch *patch)3721{3722struct stat st;3723const char*old_name = patch->old_name;3724const char*new_name = patch->new_name;3725const char*name = old_name ? old_name : new_name;3726struct cache_entry *ce = NULL;3727struct patch *tpatch;3728int ok_if_exists;3729int status;37303731 patch->rejected =1;/* we will drop this after we succeed */37323733 status =check_preimage(patch, &ce, &st);3734if(status)3735return status;3736 old_name = patch->old_name;37373738/*3739 * A type-change diff is always split into a patch to delete3740 * old, immediately followed by a patch to create new (see3741 * diff.c::run_diff()); in such a case it is Ok that the entry3742 * to be deleted by the previous patch is still in the working3743 * tree and in the index.3744 *3745 * A patch to swap-rename between A and B would first rename A3746 * to B and then rename B to A. While applying the first one,3747 * the presence of B should not stop A from getting renamed to3748 * B; ask to_be_deleted() about the later rename. Removal of3749 * B and rename from A to B is handled the same way by asking3750 * was_deleted().3751 */3752if((tpatch =in_fn_table(new_name)) &&3753(was_deleted(tpatch) ||to_be_deleted(tpatch)))3754 ok_if_exists =1;3755else3756 ok_if_exists =0;37573758if(new_name &&3759((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3760int err =check_to_create(new_name, ok_if_exists);37613762if(err && threeway) {3763 patch->direct_to_threeway =1;3764}else switch(err) {3765case0:3766break;/* happy */3767case EXISTS_IN_INDEX:3768returnerror(_("%s: already exists in index"), new_name);3769break;3770case EXISTS_IN_WORKTREE:3771returnerror(_("%s: already exists in working directory"),3772 new_name);3773default:3774return err;3775}37763777if(!patch->new_mode) {3778if(0< patch->is_new)3779 patch->new_mode = S_IFREG |0644;3780else3781 patch->new_mode = patch->old_mode;3782}3783}37843785if(new_name && old_name) {3786int same = !strcmp(old_name, new_name);3787if(!patch->new_mode)3788 patch->new_mode = patch->old_mode;3789if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3790if(same)3791returnerror(_("new mode (%o) of%sdoes not "3792"match old mode (%o)"),3793 patch->new_mode, new_name,3794 patch->old_mode);3795else3796returnerror(_("new mode (%o) of%sdoes not "3797"match old mode (%o) of%s"),3798 patch->new_mode, new_name,3799 patch->old_mode, old_name);3800}3801}38023803if(!unsafe_paths)3804die_on_unsafe_path(patch);38053806/*3807 * An attempt to read from or delete a path that is beyond a3808 * symbolic link will be prevented by load_patch_target() that3809 * is called at the beginning of apply_data() so we do not3810 * have to worry about a patch marked with "is_delete" bit3811 * here. We however need to make sure that the patch result3812 * is not deposited to a path that is beyond a symbolic link3813 * here.3814 */3815if(!patch->is_delete &&path_is_beyond_symlink(patch->new_name))3816returnerror(_("affected file '%s' is beyond a symbolic link"),3817 patch->new_name);38183819if(apply_data(patch, &st, ce) <0)3820returnerror(_("%s: patch does not apply"), name);3821 patch->rejected =0;3822return0;3823}38243825static intcheck_patch_list(struct patch *patch)3826{3827int err =0;38283829prepare_symlink_changes(patch);3830prepare_fn_table(patch);3831while(patch) {3832if(apply_verbosely)3833say_patch_name(stderr,3834_("Checking patch%s..."), patch);3835 err |=check_patch(patch);3836 patch = patch->next;3837}3838return err;3839}38403841/* This function tries to read the sha1 from the current index */3842static intget_current_sha1(const char*path,unsigned char*sha1)3843{3844int pos;38453846if(read_cache() <0)3847return-1;3848 pos =cache_name_pos(path,strlen(path));3849if(pos <0)3850return-1;3851hashcpy(sha1, active_cache[pos]->sha1);3852return0;3853}38543855static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3856{3857/*3858 * A usable gitlink patch has only one fragment (hunk) that looks like:3859 * @@ -1 +1 @@3860 * -Subproject commit <old sha1>3861 * +Subproject commit <new sha1>3862 * or3863 * @@ -1 +0,0 @@3864 * -Subproject commit <old sha1>3865 * for a removal patch.3866 */3867struct fragment *hunk = p->fragments;3868static const char heading[] ="-Subproject commit ";3869char*preimage;38703871if(/* does the patch have only one hunk? */3872 hunk && !hunk->next &&3873/* is its preimage one line? */3874 hunk->oldpos ==1&& hunk->oldlines ==1&&3875/* does preimage begin with the heading? */3876(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3877starts_with(++preimage, heading) &&3878/* does it record full SHA-1? */3879!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3880 preimage[sizeof(heading) +40-1] =='\n'&&3881/* does the abbreviated name on the index line agree with it? */3882starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3883return0;/* it all looks fine */38843885/* we may have full object name on the index line */3886returnget_sha1_hex(p->old_sha1_prefix, sha1);3887}38883889/* Build an index that contains the just the files needed for a 3way merge */3890static voidbuild_fake_ancestor(struct patch *list,const char*filename)3891{3892struct patch *patch;3893struct index_state result = { NULL };3894static struct lock_file lock;38953896/* Once we start supporting the reverse patch, it may be3897 * worth showing the new sha1 prefix, but until then...3898 */3899for(patch = list; patch; patch = patch->next) {3900unsigned char sha1[20];3901struct cache_entry *ce;3902const char*name;39033904 name = patch->old_name ? patch->old_name : patch->new_name;3905if(0< patch->is_new)3906continue;39073908if(S_ISGITLINK(patch->old_mode)) {3909if(!preimage_sha1_in_gitlink_patch(patch, sha1))3910;/* ok, the textual part looks sane */3911else3912die("sha1 information is lacking or useless for submodule%s",3913 name);3914}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {3915;/* ok */3916}else if(!patch->lines_added && !patch->lines_deleted) {3917/* mode-only change: update the current */3918if(get_current_sha1(patch->old_name, sha1))3919die("mode change for%s, which is not "3920"in current HEAD", name);3921}else3922die("sha1 information is lacking or useless "3923"(%s).", name);39243925 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);3926if(!ce)3927die(_("make_cache_entry failed for path '%s'"), name);3928if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3929die("Could not add%sto temporary index", name);3930}39313932hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);3933if(write_locked_index(&result, &lock, COMMIT_LOCK))3934die("Could not write temporary index to%s", filename);39353936discard_index(&result);3937}39383939static voidstat_patch_list(struct patch *patch)3940{3941int files, adds, dels;39423943for(files = adds = dels =0; patch ; patch = patch->next) {3944 files++;3945 adds += patch->lines_added;3946 dels += patch->lines_deleted;3947show_stats(patch);3948}39493950print_stat_summary(stdout, files, adds, dels);3951}39523953static voidnumstat_patch_list(struct patch *patch)3954{3955for( ; patch; patch = patch->next) {3956const char*name;3957 name = patch->new_name ? patch->new_name : patch->old_name;3958if(patch->is_binary)3959printf("-\t-\t");3960else3961printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3962write_name_quoted(name, stdout, line_termination);3963}3964}39653966static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3967{3968if(mode)3969printf("%smode%06o%s\n", newdelete, mode, name);3970else3971printf("%s %s\n", newdelete, name);3972}39733974static voidshow_mode_change(struct patch *p,int show_name)3975{3976if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3977if(show_name)3978printf(" mode change%06o =>%06o%s\n",3979 p->old_mode, p->new_mode, p->new_name);3980else3981printf(" mode change%06o =>%06o\n",3982 p->old_mode, p->new_mode);3983}3984}39853986static voidshow_rename_copy(struct patch *p)3987{3988const char*renamecopy = p->is_rename ?"rename":"copy";3989const char*old, *new;39903991/* Find common prefix */3992 old = p->old_name;3993new= p->new_name;3994while(1) {3995const char*slash_old, *slash_new;3996 slash_old =strchr(old,'/');3997 slash_new =strchr(new,'/');3998if(!slash_old ||3999!slash_new ||4000 slash_old - old != slash_new -new||4001memcmp(old,new, slash_new -new))4002break;4003 old = slash_old +1;4004new= slash_new +1;4005}4006/* p->old_name thru old is the common prefix, and old and new4007 * through the end of names are renames4008 */4009if(old != p->old_name)4010printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4011(int)(old - p->old_name), p->old_name,4012 old,new, p->score);4013else4014printf("%s %s=>%s(%d%%)\n", renamecopy,4015 p->old_name, p->new_name, p->score);4016show_mode_change(p,0);4017}40184019static voidsummary_patch_list(struct patch *patch)4020{4021struct patch *p;40224023for(p = patch; p; p = p->next) {4024if(p->is_new)4025show_file_mode_name("create", p->new_mode, p->new_name);4026else if(p->is_delete)4027show_file_mode_name("delete", p->old_mode, p->old_name);4028else{4029if(p->is_rename || p->is_copy)4030show_rename_copy(p);4031else{4032if(p->score) {4033printf(" rewrite%s(%d%%)\n",4034 p->new_name, p->score);4035show_mode_change(p,0);4036}4037else4038show_mode_change(p,1);4039}4040}4041}4042}40434044static voidpatch_stats(struct patch *patch)4045{4046int lines = patch->lines_added + patch->lines_deleted;40474048if(lines > max_change)4049 max_change = lines;4050if(patch->old_name) {4051int len =quote_c_style(patch->old_name, NULL, NULL,0);4052if(!len)4053 len =strlen(patch->old_name);4054if(len > max_len)4055 max_len = len;4056}4057if(patch->new_name) {4058int len =quote_c_style(patch->new_name, NULL, NULL,0);4059if(!len)4060 len =strlen(patch->new_name);4061if(len > max_len)4062 max_len = len;4063}4064}40654066static voidremove_file(struct patch *patch,int rmdir_empty)4067{4068if(update_index) {4069if(remove_file_from_cache(patch->old_name) <0)4070die(_("unable to remove%sfrom index"), patch->old_name);4071}4072if(!cached) {4073if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4074remove_path(patch->old_name);4075}4076}4077}40784079static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)4080{4081struct stat st;4082struct cache_entry *ce;4083int namelen =strlen(path);4084unsigned ce_size =cache_entry_size(namelen);40854086if(!update_index)4087return;40884089 ce =xcalloc(1, ce_size);4090memcpy(ce->name, path, namelen);4091 ce->ce_mode =create_ce_mode(mode);4092 ce->ce_flags =create_ce_flags(0);4093 ce->ce_namelen = namelen;4094if(S_ISGITLINK(mode)) {4095const char*s;40964097if(!skip_prefix(buf,"Subproject commit ", &s) ||4098get_sha1_hex(s, ce->sha1))4099die(_("corrupt patch for submodule%s"), path);4100}else{4101if(!cached) {4102if(lstat(path, &st) <0)4103die_errno(_("unable to stat newly created file '%s'"),4104 path);4105fill_stat_cache_info(ce, &st);4106}4107if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4108die(_("unable to create backing store for newly created file%s"), path);4109}4110if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4111die(_("unable to add cache entry for%s"), path);4112}41134114static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4115{4116int fd;4117struct strbuf nbuf = STRBUF_INIT;41184119if(S_ISGITLINK(mode)) {4120struct stat st;4121if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4122return0;4123returnmkdir(path,0777);4124}41254126if(has_symlinks &&S_ISLNK(mode))4127/* Although buf:size is counted string, it also is NUL4128 * terminated.4129 */4130returnsymlink(buf, path);41314132 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4133if(fd <0)4134return-1;41354136if(convert_to_working_tree(path, buf, size, &nbuf)) {4137 size = nbuf.len;4138 buf = nbuf.buf;4139}4140write_or_die(fd, buf, size);4141strbuf_release(&nbuf);41424143if(close(fd) <0)4144die_errno(_("closing file '%s'"), path);4145return0;4146}41474148/*4149 * We optimistically assume that the directories exist,4150 * which is true 99% of the time anyway. If they don't,4151 * we create them and try again.4152 */4153static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)4154{4155if(cached)4156return;4157if(!try_create_file(path, mode, buf, size))4158return;41594160if(errno == ENOENT) {4161if(safe_create_leading_directories(path))4162return;4163if(!try_create_file(path, mode, buf, size))4164return;4165}41664167if(errno == EEXIST || errno == EACCES) {4168/* We may be trying to create a file where a directory4169 * used to be.4170 */4171struct stat st;4172if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4173 errno = EEXIST;4174}41754176if(errno == EEXIST) {4177unsigned int nr =getpid();41784179for(;;) {4180char newpath[PATH_MAX];4181mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4182if(!try_create_file(newpath, mode, buf, size)) {4183if(!rename(newpath, path))4184return;4185unlink_or_warn(newpath);4186break;4187}4188if(errno != EEXIST)4189break;4190++nr;4191}4192}4193die_errno(_("unable to write file '%s' mode%o"), path, mode);4194}41954196static voidadd_conflicted_stages_file(struct patch *patch)4197{4198int stage, namelen;4199unsigned ce_size, mode;4200struct cache_entry *ce;42014202if(!update_index)4203return;4204 namelen =strlen(patch->new_name);4205 ce_size =cache_entry_size(namelen);4206 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);42074208remove_file_from_cache(patch->new_name);4209for(stage =1; stage <4; stage++) {4210if(is_null_oid(&patch->threeway_stage[stage -1]))4211continue;4212 ce =xcalloc(1, ce_size);4213memcpy(ce->name, patch->new_name, namelen);4214 ce->ce_mode =create_ce_mode(mode);4215 ce->ce_flags =create_ce_flags(stage);4216 ce->ce_namelen = namelen;4217hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4218if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4219die(_("unable to add cache entry for%s"), patch->new_name);4220}4221}42224223static voidcreate_file(struct patch *patch)4224{4225char*path = patch->new_name;4226unsigned mode = patch->new_mode;4227unsigned long size = patch->resultsize;4228char*buf = patch->result;42294230if(!mode)4231 mode = S_IFREG |0644;4232create_one_file(path, mode, buf, size);42334234if(patch->conflicted_threeway)4235add_conflicted_stages_file(patch);4236else4237add_index_file(path, mode, buf, size);4238}42394240/* phase zero is to remove, phase one is to create */4241static voidwrite_out_one_result(struct patch *patch,int phase)4242{4243if(patch->is_delete >0) {4244if(phase ==0)4245remove_file(patch,1);4246return;4247}4248if(patch->is_new >0|| patch->is_copy) {4249if(phase ==1)4250create_file(patch);4251return;4252}4253/*4254 * Rename or modification boils down to the same4255 * thing: remove the old, write the new4256 */4257if(phase ==0)4258remove_file(patch, patch->is_rename);4259if(phase ==1)4260create_file(patch);4261}42624263static intwrite_out_one_reject(struct patch *patch)4264{4265FILE*rej;4266char namebuf[PATH_MAX];4267struct fragment *frag;4268int cnt =0;4269struct strbuf sb = STRBUF_INIT;42704271for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4272if(!frag->rejected)4273continue;4274 cnt++;4275}42764277if(!cnt) {4278if(apply_verbosely)4279say_patch_name(stderr,4280_("Applied patch%scleanly."), patch);4281return0;4282}42834284/* This should not happen, because a removal patch that leaves4285 * contents are marked "rejected" at the patch level.4286 */4287if(!patch->new_name)4288die(_("internal error"));42894290/* Say this even without --verbose */4291strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4292"Applying patch %%swith%drejects...",4293 cnt),4294 cnt);4295say_patch_name(stderr, sb.buf, patch);4296strbuf_release(&sb);42974298 cnt =strlen(patch->new_name);4299if(ARRAY_SIZE(namebuf) <= cnt +5) {4300 cnt =ARRAY_SIZE(namebuf) -5;4301warning(_("truncating .rej filename to %.*s.rej"),4302 cnt -1, patch->new_name);4303}4304memcpy(namebuf, patch->new_name, cnt);4305memcpy(namebuf + cnt,".rej",5);43064307 rej =fopen(namebuf,"w");4308if(!rej)4309returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));43104311/* Normal git tools never deal with .rej, so do not pretend4312 * this is a git patch by saying --git or giving extended4313 * headers. While at it, maybe please "kompare" that wants4314 * the trailing TAB and some garbage at the end of line ;-).4315 */4316fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4317 patch->new_name, patch->new_name);4318for(cnt =1, frag = patch->fragments;4319 frag;4320 cnt++, frag = frag->next) {4321if(!frag->rejected) {4322fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4323continue;4324}4325fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4326fprintf(rej,"%.*s", frag->size, frag->patch);4327if(frag->patch[frag->size-1] !='\n')4328fputc('\n', rej);4329}4330fclose(rej);4331return-1;4332}43334334static intwrite_out_results(struct patch *list)4335{4336int phase;4337int errs =0;4338struct patch *l;4339struct string_list cpath = STRING_LIST_INIT_DUP;43404341for(phase =0; phase <2; phase++) {4342 l = list;4343while(l) {4344if(l->rejected)4345 errs =1;4346else{4347write_out_one_result(l, phase);4348if(phase ==1) {4349if(write_out_one_reject(l))4350 errs =1;4351if(l->conflicted_threeway) {4352string_list_append(&cpath, l->new_name);4353 errs =1;4354}4355}4356}4357 l = l->next;4358}4359}43604361if(cpath.nr) {4362struct string_list_item *item;43634364string_list_sort(&cpath);4365for_each_string_list_item(item, &cpath)4366fprintf(stderr,"U%s\n", item->string);4367string_list_clear(&cpath,0);43684369rerere(0);4370}43714372return errs;4373}43744375static struct lock_file lock_file;43764377#define INACCURATE_EOF (1<<0)4378#define RECOUNT (1<<1)43794380static intapply_patch(struct apply_state *state,4381int fd,4382const char*filename,4383int options)4384{4385size_t offset;4386struct strbuf buf = STRBUF_INIT;/* owns the patch text */4387struct patch *list = NULL, **listp = &list;4388int skipped_patch =0;43894390 patch_input_file = filename;4391read_patch_file(&buf, fd);4392 offset =0;4393while(offset < buf.len) {4394struct patch *patch;4395int nr;43964397 patch =xcalloc(1,sizeof(*patch));4398 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4399 patch->recount = !!(options & RECOUNT);4400 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4401if(nr <0) {4402free_patch(patch);4403break;4404}4405if(apply_in_reverse)4406reverse_patches(patch);4407if(use_patch(state, patch)) {4408patch_stats(patch);4409*listp = patch;4410 listp = &patch->next;4411}4412else{4413if(apply_verbosely)4414say_patch_name(stderr,_("Skipped patch '%s'."), patch);4415free_patch(patch);4416 skipped_patch++;4417}4418 offset += nr;4419}44204421if(!list && !skipped_patch)4422die(_("unrecognized input"));44234424if(whitespace_error && (ws_error_action == die_on_ws_error))4425 apply =0;44264427 update_index = check_index && apply;4428if(update_index && newfd <0)4429 newfd =hold_locked_index(&lock_file,1);44304431if(check_index) {4432if(read_cache() <0)4433die(_("unable to read index file"));4434}44354436if((check || apply) &&4437check_patch_list(list) <0&&4438!apply_with_reject)4439exit(1);44404441if(apply &&write_out_results(list)) {4442if(apply_with_reject)4443exit(1);4444/* with --3way, we still need to write the index out */4445return1;4446}44474448if(fake_ancestor)4449build_fake_ancestor(list, fake_ancestor);44504451if(diffstat)4452stat_patch_list(list);44534454if(numstat)4455numstat_patch_list(list);44564457if(summary)4458summary_patch_list(list);44594460free_patch_list(list);4461strbuf_release(&buf);4462string_list_clear(&fn_table,0);4463return0;4464}44654466static voidgit_apply_config(void)4467{4468git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4469git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4470git_config(git_default_config, NULL);4471}44724473static intoption_parse_exclude(const struct option *opt,4474const char*arg,int unset)4475{4476add_name_limit(arg,1);4477return0;4478}44794480static intoption_parse_include(const struct option *opt,4481const char*arg,int unset)4482{4483add_name_limit(arg,0);4484 has_include =1;4485return0;4486}44874488static intoption_parse_p(const struct option *opt,4489const char*arg,int unset)4490{4491 state_p_value =atoi(arg);4492 p_value_known =1;4493return0;4494}44954496static intoption_parse_space_change(const struct option *opt,4497const char*arg,int unset)4498{4499if(unset)4500 ws_ignore_action = ignore_ws_none;4501else4502 ws_ignore_action = ignore_ws_change;4503return0;4504}45054506static intoption_parse_whitespace(const struct option *opt,4507const char*arg,int unset)4508{4509const char**whitespace_option = opt->value;45104511*whitespace_option = arg;4512parse_whitespace_option(arg);4513return0;4514}45154516static intoption_parse_directory(const struct option *opt,4517const char*arg,int unset)4518{4519strbuf_reset(&root);4520strbuf_addstr(&root, arg);4521strbuf_complete(&root,'/');4522return0;4523}45244525intcmd_apply(int argc,const char**argv,const char*prefix_)4526{4527int i;4528int errs =0;4529int is_not_gitdir = !startup_info->have_repository;4530int force_apply =0;4531int options =0;4532int read_stdin =1;4533struct apply_state state;45344535const char*whitespace_option = NULL;45364537struct option builtin_apply_options[] = {4538{ OPTION_CALLBACK,0,"exclude", NULL,N_("path"),4539N_("don't apply changes matching the given path"),45400, option_parse_exclude },4541{ OPTION_CALLBACK,0,"include", NULL,N_("path"),4542N_("apply changes matching the given path"),45430, option_parse_include },4544{ OPTION_CALLBACK,'p', NULL, NULL,N_("num"),4545N_("remove <num> leading slashes from traditional diff paths"),45460, option_parse_p },4547OPT_BOOL(0,"no-add", &no_add,4548N_("ignore additions made by the patch")),4549OPT_BOOL(0,"stat", &diffstat,4550N_("instead of applying the patch, output diffstat for the input")),4551OPT_NOOP_NOARG(0,"allow-binary-replacement"),4552OPT_NOOP_NOARG(0,"binary"),4553OPT_BOOL(0,"numstat", &numstat,4554N_("show number of added and deleted lines in decimal notation")),4555OPT_BOOL(0,"summary", &summary,4556N_("instead of applying the patch, output a summary for the input")),4557OPT_BOOL(0,"check", &check,4558N_("instead of applying the patch, see if the patch is applicable")),4559OPT_BOOL(0,"index", &check_index,4560N_("make sure the patch is applicable to the current index")),4561OPT_BOOL(0,"cached", &cached,4562N_("apply a patch without touching the working tree")),4563OPT_BOOL(0,"unsafe-paths", &unsafe_paths,4564N_("accept a patch that touches outside the working area")),4565OPT_BOOL(0,"apply", &force_apply,4566N_("also apply the patch (use with --stat/--summary/--check)")),4567OPT_BOOL('3',"3way", &threeway,4568N_("attempt three-way merge if a patch does not apply")),4569OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,4570N_("build a temporary index based on embedded index information")),4571/* Think twice before adding "--nul" synonym to this */4572OPT_SET_INT('z', NULL, &line_termination,4573N_("paths are separated with NUL character"),'\0'),4574OPT_INTEGER('C', NULL, &p_context,4575N_("ensure at least <n> lines of context match")),4576{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,N_("action"),4577N_("detect new or modified lines that have whitespace errors"),45780, option_parse_whitespace },4579{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,4580N_("ignore changes in whitespace when finding context"),4581 PARSE_OPT_NOARG, option_parse_space_change },4582{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,4583N_("ignore changes in whitespace when finding context"),4584 PARSE_OPT_NOARG, option_parse_space_change },4585OPT_BOOL('R',"reverse", &apply_in_reverse,4586N_("apply the patch in reverse")),4587OPT_BOOL(0,"unidiff-zero", &unidiff_zero,4588N_("don't expect at least one line of context")),4589OPT_BOOL(0,"reject", &apply_with_reject,4590N_("leave the rejected hunks in corresponding *.rej files")),4591OPT_BOOL(0,"allow-overlap", &allow_overlap,4592N_("allow overlapping hunks")),4593OPT__VERBOSE(&apply_verbosely,N_("be verbose")),4594OPT_BIT(0,"inaccurate-eof", &options,4595N_("tolerate incorrectly detected missing new-line at the end of file"),4596 INACCURATE_EOF),4597OPT_BIT(0,"recount", &options,4598N_("do not trust the line counts in the hunk headers"),4599 RECOUNT),4600{ OPTION_CALLBACK,0,"directory", NULL,N_("root"),4601N_("prepend <root> to all filenames"),46020, option_parse_directory },4603OPT_END()4604};46054606memset(&state,0,sizeof(state));4607 state.prefix = prefix_;4608 state.prefix_length = state.prefix ?strlen(state.prefix) :0;46094610git_apply_config();4611if(apply_default_whitespace)4612parse_whitespace_option(apply_default_whitespace);4613if(apply_default_ignorewhitespace)4614parse_ignorewhitespace_option(apply_default_ignorewhitespace);46154616 argc =parse_options(argc, argv, state.prefix, builtin_apply_options,4617 apply_usage,0);46184619if(apply_with_reject && threeway)4620die("--reject and --3way cannot be used together.");4621if(cached && threeway)4622die("--cached and --3way cannot be used together.");4623if(threeway) {4624if(is_not_gitdir)4625die(_("--3way outside a repository"));4626 check_index =1;4627}4628if(apply_with_reject)4629 apply = apply_verbosely =1;4630if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))4631 apply =0;4632if(check_index && is_not_gitdir)4633die(_("--index outside a repository"));4634if(cached) {4635if(is_not_gitdir)4636die(_("--cached outside a repository"));4637 check_index =1;4638}4639if(check_index)4640 unsafe_paths =0;46414642for(i =0; i < argc; i++) {4643const char*arg = argv[i];4644int fd;46454646if(!strcmp(arg,"-")) {4647 errs |=apply_patch(&state,0,"<stdin>", options);4648 read_stdin =0;4649continue;4650}else if(0< state.prefix_length)4651 arg =prefix_filename(state.prefix,4652 state.prefix_length,4653 arg);46544655 fd =open(arg, O_RDONLY);4656if(fd <0)4657die_errno(_("can't open patch '%s'"), arg);4658 read_stdin =0;4659set_default_whitespace_mode(whitespace_option);4660 errs |=apply_patch(&state, fd, arg, options);4661close(fd);4662}4663set_default_whitespace_mode(whitespace_option);4664if(read_stdin)4665 errs |=apply_patch(&state,0,"<stdin>", options);4666if(whitespace_error) {4667if(squelch_whitespace_errors &&4668 squelch_whitespace_errors < whitespace_error) {4669int squelched =4670 whitespace_error - squelch_whitespace_errors;4671warning(Q_("squelched%dwhitespace error",4672"squelched%dwhitespace errors",4673 squelched),4674 squelched);4675}4676if(ws_error_action == die_on_ws_error)4677die(Q_("%dline adds whitespace errors.",4678"%dlines add whitespace errors.",4679 whitespace_error),4680 whitespace_error);4681if(applied_after_fixing_ws && apply)4682warning("%dline%sapplied after"4683" fixing whitespace errors.",4684 applied_after_fixing_ws,4685 applied_after_fixing_ws ==1?"":"s");4686else if(whitespace_error)4687warning(Q_("%dline adds whitespace errors.",4688"%dlines add whitespace errors.",4689 whitespace_error),4690 whitespace_error);4691}46924693if(update_index) {4694if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK))4695die(_("Unable to write new index file"));4696}46974698return!!errs;4699}