1/* 2 * apply.c 3 * 4 * Copyright (C) Linus Torvalds, 2005 5 * 6 * This applies patches on top of some (arbitrary) version of the SCM. 7 * 8 */ 9#include"cache.h" 10#include"lockfile.h" 11#include"cache-tree.h" 12#include"quote.h" 13#include"blob.h" 14#include"delta.h" 15#include"builtin.h" 16#include"string-list.h" 17#include"dir.h" 18#include"diff.h" 19#include"parse-options.h" 20#include"xdiff-interface.h" 21#include"ll-merge.h" 22#include"rerere.h" 23 24enum ws_error_action { 25 nowarn_ws_error, 26 warn_on_ws_error, 27 die_on_ws_error, 28 correct_ws_error 29}; 30 31 32enum ws_ignore { 33 ignore_ws_none, 34 ignore_ws_change 35}; 36 37struct apply_state { 38const char*prefix; 39int prefix_length; 40 41/* These control what gets looked at and modified */ 42int apply;/* this is not a dry-run */ 43int cached;/* apply to the index only */ 44int check;/* preimage must match working tree, don't actually apply */ 45int check_index;/* preimage must match the indexed version */ 46int update_index;/* check_index && apply */ 47 48/* These control cosmetic aspect of the output */ 49int diffstat;/* just show a diffstat, and don't actually apply */ 50int numstat;/* just show a numeric diffstat, and don't actually apply */ 51int summary;/* just report creation, deletion, etc, and don't actually apply */ 52 53/* These boolean parameters control how the apply is done */ 54int allow_overlap; 55int apply_in_reverse; 56int apply_with_reject; 57int apply_verbosely; 58int no_add; 59int threeway; 60int unidiff_zero; 61int unsafe_paths; 62 63/* Other non boolean parameters */ 64const char*fake_ancestor; 65const char*patch_input_file; 66int line_termination; 67struct strbuf root; 68int p_value; 69int p_value_known; 70unsigned int p_context; 71 72/* Exclude and include path parameters */ 73struct string_list limit_by_name; 74int has_include; 75 76/* These control whitespace errors */ 77enum ws_error_action ws_error_action; 78enum ws_ignore ws_ignore_action; 79const char*whitespace_option; 80int whitespace_error; 81int squelch_whitespace_errors; 82int applied_after_fixing_ws; 83}; 84 85static int newfd = -1; 86 87static const char*const apply_usage[] = { 88N_("git apply [<options>] [<patch>...]"), 89 NULL 90}; 91 92static voidparse_whitespace_option(struct apply_state *state,const char*option) 93{ 94if(!option) { 95 state->ws_error_action = warn_on_ws_error; 96return; 97} 98if(!strcmp(option,"warn")) { 99 state->ws_error_action = warn_on_ws_error; 100return; 101} 102if(!strcmp(option,"nowarn")) { 103 state->ws_error_action = nowarn_ws_error; 104return; 105} 106if(!strcmp(option,"error")) { 107 state->ws_error_action = die_on_ws_error; 108return; 109} 110if(!strcmp(option,"error-all")) { 111 state->ws_error_action = die_on_ws_error; 112 state->squelch_whitespace_errors =0; 113return; 114} 115if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 116 state->ws_error_action = correct_ws_error; 117return; 118} 119die(_("unrecognized whitespace option '%s'"), option); 120} 121 122static voidparse_ignorewhitespace_option(struct apply_state *state, 123const char*option) 124{ 125if(!option || !strcmp(option,"no") || 126!strcmp(option,"false") || !strcmp(option,"never") || 127!strcmp(option,"none")) { 128 state->ws_ignore_action = ignore_ws_none; 129return; 130} 131if(!strcmp(option,"change")) { 132 state->ws_ignore_action = ignore_ws_change; 133return; 134} 135die(_("unrecognized whitespace ignore option '%s'"), option); 136} 137 138static voidset_default_whitespace_mode(struct apply_state *state) 139{ 140if(!state->whitespace_option && !apply_default_whitespace) 141 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 142} 143 144/* 145 * For "diff-stat" like behaviour, we keep track of the biggest change 146 * we've seen, and the longest filename. That allows us to do simple 147 * scaling. 148 */ 149static int max_change, max_len; 150 151/* 152 * Various "current state", notably line numbers and what 153 * file (and how) we're patching right now.. The "is_xxxx" 154 * things are flags, where -1 means "don't know yet". 155 */ 156static int state_linenr =1; 157 158/* 159 * This represents one "hunk" from a patch, starting with 160 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 161 * patch text is pointed at by patch, and its byte length 162 * is stored in size. leading and trailing are the number 163 * of context lines. 164 */ 165struct fragment { 166unsigned long leading, trailing; 167unsigned long oldpos, oldlines; 168unsigned long newpos, newlines; 169/* 170 * 'patch' is usually borrowed from buf in apply_patch(), 171 * but some codepaths store an allocated buffer. 172 */ 173const char*patch; 174unsigned free_patch:1, 175 rejected:1; 176int size; 177int linenr; 178struct fragment *next; 179}; 180 181/* 182 * When dealing with a binary patch, we reuse "leading" field 183 * to store the type of the binary hunk, either deflated "delta" 184 * or deflated "literal". 185 */ 186#define binary_patch_method leading 187#define BINARY_DELTA_DEFLATED 1 188#define BINARY_LITERAL_DEFLATED 2 189 190/* 191 * This represents a "patch" to a file, both metainfo changes 192 * such as creation/deletion, filemode and content changes represented 193 * as a series of fragments. 194 */ 195struct patch { 196char*new_name, *old_name, *def_name; 197unsigned int old_mode, new_mode; 198int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 199int rejected; 200unsigned ws_rule; 201int lines_added, lines_deleted; 202int score; 203unsigned int is_toplevel_relative:1; 204unsigned int inaccurate_eof:1; 205unsigned int is_binary:1; 206unsigned int is_copy:1; 207unsigned int is_rename:1; 208unsigned int recount:1; 209unsigned int conflicted_threeway:1; 210unsigned int direct_to_threeway:1; 211struct fragment *fragments; 212char*result; 213size_t resultsize; 214char old_sha1_prefix[41]; 215char new_sha1_prefix[41]; 216struct patch *next; 217 218/* three-way fallback result */ 219struct object_id threeway_stage[3]; 220}; 221 222static voidfree_fragment_list(struct fragment *list) 223{ 224while(list) { 225struct fragment *next = list->next; 226if(list->free_patch) 227free((char*)list->patch); 228free(list); 229 list = next; 230} 231} 232 233static voidfree_patch(struct patch *patch) 234{ 235free_fragment_list(patch->fragments); 236free(patch->def_name); 237free(patch->old_name); 238free(patch->new_name); 239free(patch->result); 240free(patch); 241} 242 243static voidfree_patch_list(struct patch *list) 244{ 245while(list) { 246struct patch *next = list->next; 247free_patch(list); 248 list = next; 249} 250} 251 252/* 253 * A line in a file, len-bytes long (includes the terminating LF, 254 * except for an incomplete line at the end if the file ends with 255 * one), and its contents hashes to 'hash'. 256 */ 257struct line { 258size_t len; 259unsigned hash :24; 260unsigned flag :8; 261#define LINE_COMMON 1 262#define LINE_PATCHED 2 263}; 264 265/* 266 * This represents a "file", which is an array of "lines". 267 */ 268struct image { 269char*buf; 270size_t len; 271size_t nr; 272size_t alloc; 273struct line *line_allocated; 274struct line *line; 275}; 276 277/* 278 * Records filenames that have been touched, in order to handle 279 * the case where more than one patches touch the same file. 280 */ 281 282static struct string_list fn_table; 283 284static uint32_thash_line(const char*cp,size_t len) 285{ 286size_t i; 287uint32_t h; 288for(i =0, h =0; i < len; i++) { 289if(!isspace(cp[i])) { 290 h = h *3+ (cp[i] &0xff); 291} 292} 293return h; 294} 295 296/* 297 * Compare lines s1 of length n1 and s2 of length n2, ignoring 298 * whitespace difference. Returns 1 if they match, 0 otherwise 299 */ 300static intfuzzy_matchlines(const char*s1,size_t n1, 301const char*s2,size_t n2) 302{ 303const char*last1 = s1 + n1 -1; 304const char*last2 = s2 + n2 -1; 305int result =0; 306 307/* ignore line endings */ 308while((*last1 =='\r') || (*last1 =='\n')) 309 last1--; 310while((*last2 =='\r') || (*last2 =='\n')) 311 last2--; 312 313/* skip leading whitespaces, if both begin with whitespace */ 314if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 315while(isspace(*s1) && (s1 <= last1)) 316 s1++; 317while(isspace(*s2) && (s2 <= last2)) 318 s2++; 319} 320/* early return if both lines are empty */ 321if((s1 > last1) && (s2 > last2)) 322return1; 323while(!result) { 324 result = *s1++ - *s2++; 325/* 326 * Skip whitespace inside. We check for whitespace on 327 * both buffers because we don't want "a b" to match 328 * "ab" 329 */ 330if(isspace(*s1) &&isspace(*s2)) { 331while(isspace(*s1) && s1 <= last1) 332 s1++; 333while(isspace(*s2) && s2 <= last2) 334 s2++; 335} 336/* 337 * If we reached the end on one side only, 338 * lines don't match 339 */ 340if( 341((s2 > last2) && (s1 <= last1)) || 342((s1 > last1) && (s2 <= last2))) 343return0; 344if((s1 > last1) && (s2 > last2)) 345break; 346} 347 348return!result; 349} 350 351static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 352{ 353ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 354 img->line_allocated[img->nr].len = len; 355 img->line_allocated[img->nr].hash =hash_line(bol, len); 356 img->line_allocated[img->nr].flag = flag; 357 img->nr++; 358} 359 360/* 361 * "buf" has the file contents to be patched (read from various sources). 362 * attach it to "image" and add line-based index to it. 363 * "image" now owns the "buf". 364 */ 365static voidprepare_image(struct image *image,char*buf,size_t len, 366int prepare_linetable) 367{ 368const char*cp, *ep; 369 370memset(image,0,sizeof(*image)); 371 image->buf = buf; 372 image->len = len; 373 374if(!prepare_linetable) 375return; 376 377 ep = image->buf + image->len; 378 cp = image->buf; 379while(cp < ep) { 380const char*next; 381for(next = cp; next < ep && *next !='\n'; next++) 382; 383if(next < ep) 384 next++; 385add_line_info(image, cp, next - cp,0); 386 cp = next; 387} 388 image->line = image->line_allocated; 389} 390 391static voidclear_image(struct image *image) 392{ 393free(image->buf); 394free(image->line_allocated); 395memset(image,0,sizeof(*image)); 396} 397 398/* fmt must contain _one_ %s and no other substitution */ 399static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 400{ 401struct strbuf sb = STRBUF_INIT; 402 403if(patch->old_name && patch->new_name && 404strcmp(patch->old_name, patch->new_name)) { 405quote_c_style(patch->old_name, &sb, NULL,0); 406strbuf_addstr(&sb," => "); 407quote_c_style(patch->new_name, &sb, NULL,0); 408}else{ 409const char*n = patch->new_name; 410if(!n) 411 n = patch->old_name; 412quote_c_style(n, &sb, NULL,0); 413} 414fprintf(output, fmt, sb.buf); 415fputc('\n', output); 416strbuf_release(&sb); 417} 418 419#define SLOP (16) 420 421static voidread_patch_file(struct strbuf *sb,int fd) 422{ 423if(strbuf_read(sb, fd,0) <0) 424die_errno("git apply: failed to read"); 425 426/* 427 * Make sure that we have some slop in the buffer 428 * so that we can do speculative "memcmp" etc, and 429 * see to it that it is NUL-filled. 430 */ 431strbuf_grow(sb, SLOP); 432memset(sb->buf + sb->len,0, SLOP); 433} 434 435static unsigned longlinelen(const char*buffer,unsigned long size) 436{ 437unsigned long len =0; 438while(size--) { 439 len++; 440if(*buffer++ =='\n') 441break; 442} 443return len; 444} 445 446static intis_dev_null(const char*str) 447{ 448returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 449} 450 451#define TERM_SPACE 1 452#define TERM_TAB 2 453 454static intname_terminate(const char*name,int namelen,int c,int terminate) 455{ 456if(c ==' '&& !(terminate & TERM_SPACE)) 457return0; 458if(c =='\t'&& !(terminate & TERM_TAB)) 459return0; 460 461return1; 462} 463 464/* remove double slashes to make --index work with such filenames */ 465static char*squash_slash(char*name) 466{ 467int i =0, j =0; 468 469if(!name) 470return NULL; 471 472while(name[i]) { 473if((name[j++] = name[i++]) =='/') 474while(name[i] =='/') 475 i++; 476} 477 name[j] ='\0'; 478return name; 479} 480 481static char*find_name_gnu(struct apply_state *state, 482const char*line, 483const char*def, 484int p_value) 485{ 486struct strbuf name = STRBUF_INIT; 487char*cp; 488 489/* 490 * Proposed "new-style" GNU patch/diff format; see 491 * http://marc.info/?l=git&m=112927316408690&w=2 492 */ 493if(unquote_c_style(&name, line, NULL)) { 494strbuf_release(&name); 495return NULL; 496} 497 498for(cp = name.buf; p_value; p_value--) { 499 cp =strchr(cp,'/'); 500if(!cp) { 501strbuf_release(&name); 502return NULL; 503} 504 cp++; 505} 506 507strbuf_remove(&name,0, cp - name.buf); 508if(state->root.len) 509strbuf_insert(&name,0, state->root.buf, state->root.len); 510returnsquash_slash(strbuf_detach(&name, NULL)); 511} 512 513static size_tsane_tz_len(const char*line,size_t len) 514{ 515const char*tz, *p; 516 517if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 518return0; 519 tz = line + len -strlen(" +0500"); 520 521if(tz[1] !='+'&& tz[1] !='-') 522return0; 523 524for(p = tz +2; p != line + len; p++) 525if(!isdigit(*p)) 526return0; 527 528return line + len - tz; 529} 530 531static size_ttz_with_colon_len(const char*line,size_t len) 532{ 533const char*tz, *p; 534 535if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 536return0; 537 tz = line + len -strlen(" +08:00"); 538 539if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 540return0; 541 p = tz +2; 542if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 543!isdigit(*p++) || !isdigit(*p++)) 544return0; 545 546return line + len - tz; 547} 548 549static size_tdate_len(const char*line,size_t len) 550{ 551const char*date, *p; 552 553if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 554return0; 555 p = date = line + len -strlen("72-02-05"); 556 557if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 558!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 559!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 560return0; 561 562if(date - line >=strlen("19") && 563isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 564 date -=strlen("19"); 565 566return line + len - date; 567} 568 569static size_tshort_time_len(const char*line,size_t len) 570{ 571const char*time, *p; 572 573if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 574return0; 575 p = time = line + len -strlen(" 07:01:32"); 576 577/* Permit 1-digit hours? */ 578if(*p++ !=' '|| 579!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 580!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 581!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 582return0; 583 584return line + len - time; 585} 586 587static size_tfractional_time_len(const char*line,size_t len) 588{ 589const char*p; 590size_t n; 591 592/* Expected format: 19:41:17.620000023 */ 593if(!len || !isdigit(line[len -1])) 594return0; 595 p = line + len -1; 596 597/* Fractional seconds. */ 598while(p > line &&isdigit(*p)) 599 p--; 600if(*p !='.') 601return0; 602 603/* Hours, minutes, and whole seconds. */ 604 n =short_time_len(line, p - line); 605if(!n) 606return0; 607 608return line + len - p + n; 609} 610 611static size_ttrailing_spaces_len(const char*line,size_t len) 612{ 613const char*p; 614 615/* Expected format: ' ' x (1 or more) */ 616if(!len || line[len -1] !=' ') 617return0; 618 619 p = line + len; 620while(p != line) { 621 p--; 622if(*p !=' ') 623return line + len - (p +1); 624} 625 626/* All spaces! */ 627return len; 628} 629 630static size_tdiff_timestamp_len(const char*line,size_t len) 631{ 632const char*end = line + len; 633size_t n; 634 635/* 636 * Posix: 2010-07-05 19:41:17 637 * GNU: 2010-07-05 19:41:17.620000023 -0500 638 */ 639 640if(!isdigit(end[-1])) 641return0; 642 643 n =sane_tz_len(line, end - line); 644if(!n) 645 n =tz_with_colon_len(line, end - line); 646 end -= n; 647 648 n =short_time_len(line, end - line); 649if(!n) 650 n =fractional_time_len(line, end - line); 651 end -= n; 652 653 n =date_len(line, end - line); 654if(!n)/* No date. Too bad. */ 655return0; 656 end -= n; 657 658if(end == line)/* No space before date. */ 659return0; 660if(end[-1] =='\t') {/* Success! */ 661 end--; 662return line + len - end; 663} 664if(end[-1] !=' ')/* No space before date. */ 665return0; 666 667/* Whitespace damage. */ 668 end -=trailing_spaces_len(line, end - line); 669return line + len - end; 670} 671 672static char*find_name_common(struct apply_state *state, 673const char*line, 674const char*def, 675int p_value, 676const char*end, 677int terminate) 678{ 679int len; 680const char*start = NULL; 681 682if(p_value ==0) 683 start = line; 684while(line != end) { 685char c = *line; 686 687if(!end &&isspace(c)) { 688if(c =='\n') 689break; 690if(name_terminate(start, line-start, c, terminate)) 691break; 692} 693 line++; 694if(c =='/'&& !--p_value) 695 start = line; 696} 697if(!start) 698returnsquash_slash(xstrdup_or_null(def)); 699 len = line - start; 700if(!len) 701returnsquash_slash(xstrdup_or_null(def)); 702 703/* 704 * Generally we prefer the shorter name, especially 705 * if the other one is just a variation of that with 706 * something else tacked on to the end (ie "file.orig" 707 * or "file~"). 708 */ 709if(def) { 710int deflen =strlen(def); 711if(deflen < len && !strncmp(start, def, deflen)) 712returnsquash_slash(xstrdup(def)); 713} 714 715if(state->root.len) { 716char*ret =xstrfmt("%s%.*s", state->root.buf, len, start); 717returnsquash_slash(ret); 718} 719 720returnsquash_slash(xmemdupz(start, len)); 721} 722 723static char*find_name(struct apply_state *state, 724const char*line, 725char*def, 726int p_value, 727int terminate) 728{ 729if(*line =='"') { 730char*name =find_name_gnu(state, line, def, p_value); 731if(name) 732return name; 733} 734 735returnfind_name_common(state, line, def, p_value, NULL, terminate); 736} 737 738static char*find_name_traditional(struct apply_state *state, 739const char*line, 740char*def, 741int p_value) 742{ 743size_t len; 744size_t date_len; 745 746if(*line =='"') { 747char*name =find_name_gnu(state, line, def, p_value); 748if(name) 749return name; 750} 751 752 len =strchrnul(line,'\n') - line; 753 date_len =diff_timestamp_len(line, len); 754if(!date_len) 755returnfind_name_common(state, line, def, p_value, NULL, TERM_TAB); 756 len -= date_len; 757 758returnfind_name_common(state, line, def, p_value, line + len,0); 759} 760 761static intcount_slashes(const char*cp) 762{ 763int cnt =0; 764char ch; 765 766while((ch = *cp++)) 767if(ch =='/') 768 cnt++; 769return cnt; 770} 771 772/* 773 * Given the string after "--- " or "+++ ", guess the appropriate 774 * p_value for the given patch. 775 */ 776static intguess_p_value(struct apply_state *state,const char*nameline) 777{ 778char*name, *cp; 779int val = -1; 780 781if(is_dev_null(nameline)) 782return-1; 783 name =find_name_traditional(state, nameline, NULL,0); 784if(!name) 785return-1; 786 cp =strchr(name,'/'); 787if(!cp) 788 val =0; 789else if(state->prefix) { 790/* 791 * Does it begin with "a/$our-prefix" and such? Then this is 792 * very likely to apply to our directory. 793 */ 794if(!strncmp(name, state->prefix, state->prefix_length)) 795 val =count_slashes(state->prefix); 796else{ 797 cp++; 798if(!strncmp(cp, state->prefix, state->prefix_length)) 799 val =count_slashes(state->prefix) +1; 800} 801} 802free(name); 803return val; 804} 805 806/* 807 * Does the ---/+++ line have the POSIX timestamp after the last HT? 808 * GNU diff puts epoch there to signal a creation/deletion event. Is 809 * this such a timestamp? 810 */ 811static inthas_epoch_timestamp(const char*nameline) 812{ 813/* 814 * We are only interested in epoch timestamp; any non-zero 815 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 816 * For the same reason, the date must be either 1969-12-31 or 817 * 1970-01-01, and the seconds part must be "00". 818 */ 819const char stamp_regexp[] = 820"^(1969-12-31|1970-01-01)" 821" " 822"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 823" " 824"([-+][0-2][0-9]:?[0-5][0-9])\n"; 825const char*timestamp = NULL, *cp, *colon; 826static regex_t *stamp; 827 regmatch_t m[10]; 828int zoneoffset; 829int hourminute; 830int status; 831 832for(cp = nameline; *cp !='\n'; cp++) { 833if(*cp =='\t') 834 timestamp = cp +1; 835} 836if(!timestamp) 837return0; 838if(!stamp) { 839 stamp =xmalloc(sizeof(*stamp)); 840if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 841warning(_("Cannot prepare timestamp regexp%s"), 842 stamp_regexp); 843return0; 844} 845} 846 847 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 848if(status) { 849if(status != REG_NOMATCH) 850warning(_("regexec returned%dfor input:%s"), 851 status, timestamp); 852return0; 853} 854 855 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 856if(*colon ==':') 857 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 858else 859 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 860if(timestamp[m[3].rm_so] =='-') 861 zoneoffset = -zoneoffset; 862 863/* 864 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 865 * (west of GMT) or 1970-01-01 (east of GMT) 866 */ 867if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 868(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 869return0; 870 871 hourminute = (strtol(timestamp +11, NULL,10) *60+ 872strtol(timestamp +14, NULL,10) - 873 zoneoffset); 874 875return((zoneoffset <0&& hourminute ==1440) || 876(0<= zoneoffset && !hourminute)); 877} 878 879/* 880 * Get the name etc info from the ---/+++ lines of a traditional patch header 881 * 882 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 883 * files, we can happily check the index for a match, but for creating a 884 * new file we should try to match whatever "patch" does. I have no idea. 885 */ 886static voidparse_traditional_patch(struct apply_state *state, 887const char*first, 888const char*second, 889struct patch *patch) 890{ 891char*name; 892 893 first +=4;/* skip "--- " */ 894 second +=4;/* skip "+++ " */ 895if(!state->p_value_known) { 896int p, q; 897 p =guess_p_value(state, first); 898 q =guess_p_value(state, second); 899if(p <0) p = q; 900if(0<= p && p == q) { 901 state->p_value = p; 902 state->p_value_known =1; 903} 904} 905if(is_dev_null(first)) { 906 patch->is_new =1; 907 patch->is_delete =0; 908 name =find_name_traditional(state, second, NULL, state->p_value); 909 patch->new_name = name; 910}else if(is_dev_null(second)) { 911 patch->is_new =0; 912 patch->is_delete =1; 913 name =find_name_traditional(state, first, NULL, state->p_value); 914 patch->old_name = name; 915}else{ 916char*first_name; 917 first_name =find_name_traditional(state, first, NULL, state->p_value); 918 name =find_name_traditional(state, second, first_name, state->p_value); 919free(first_name); 920if(has_epoch_timestamp(first)) { 921 patch->is_new =1; 922 patch->is_delete =0; 923 patch->new_name = name; 924}else if(has_epoch_timestamp(second)) { 925 patch->is_new =0; 926 patch->is_delete =1; 927 patch->old_name = name; 928}else{ 929 patch->old_name = name; 930 patch->new_name =xstrdup_or_null(name); 931} 932} 933if(!name) 934die(_("unable to find filename in patch at line%d"), state_linenr); 935} 936 937static intgitdiff_hdrend(struct apply_state *state, 938const char*line, 939struct patch *patch) 940{ 941return-1; 942} 943 944/* 945 * We're anal about diff header consistency, to make 946 * sure that we don't end up having strange ambiguous 947 * patches floating around. 948 * 949 * As a result, gitdiff_{old|new}name() will check 950 * their names against any previous information, just 951 * to make sure.. 952 */ 953#define DIFF_OLD_NAME 0 954#define DIFF_NEW_NAME 1 955 956static voidgitdiff_verify_name(struct apply_state *state, 957const char*line, 958int isnull, 959char**name, 960int side) 961{ 962if(!*name && !isnull) { 963*name =find_name(state, line, NULL, state->p_value, TERM_TAB); 964return; 965} 966 967if(*name) { 968int len =strlen(*name); 969char*another; 970if(isnull) 971die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 972*name, state_linenr); 973 another =find_name(state, line, NULL, state->p_value, TERM_TAB); 974if(!another ||memcmp(another, *name, len +1)) 975die((side == DIFF_NEW_NAME) ? 976_("git apply: bad git-diff - inconsistent new filename on line%d") : 977_("git apply: bad git-diff - inconsistent old filename on line%d"), state_linenr); 978free(another); 979}else{ 980/* expect "/dev/null" */ 981if(memcmp("/dev/null", line,9) || line[9] !='\n') 982die(_("git apply: bad git-diff - expected /dev/null on line%d"), state_linenr); 983} 984} 985 986static intgitdiff_oldname(struct apply_state *state, 987const char*line, 988struct patch *patch) 989{ 990gitdiff_verify_name(state, line, 991 patch->is_new, &patch->old_name, 992 DIFF_OLD_NAME); 993return0; 994} 995 996static intgitdiff_newname(struct apply_state *state, 997const char*line, 998struct patch *patch) 999{1000gitdiff_verify_name(state, line,1001 patch->is_delete, &patch->new_name,1002 DIFF_NEW_NAME);1003return0;1004}10051006static intgitdiff_oldmode(struct apply_state *state,1007const char*line,1008struct patch *patch)1009{1010 patch->old_mode =strtoul(line, NULL,8);1011return0;1012}10131014static intgitdiff_newmode(struct apply_state *state,1015const char*line,1016struct patch *patch)1017{1018 patch->new_mode =strtoul(line, NULL,8);1019return0;1020}10211022static intgitdiff_delete(struct apply_state *state,1023const char*line,1024struct patch *patch)1025{1026 patch->is_delete =1;1027free(patch->old_name);1028 patch->old_name =xstrdup_or_null(patch->def_name);1029returngitdiff_oldmode(state, line, patch);1030}10311032static intgitdiff_newfile(struct apply_state *state,1033const char*line,1034struct patch *patch)1035{1036 patch->is_new =1;1037free(patch->new_name);1038 patch->new_name =xstrdup_or_null(patch->def_name);1039returngitdiff_newmode(state, line, patch);1040}10411042static intgitdiff_copysrc(struct apply_state *state,1043const char*line,1044struct patch *patch)1045{1046 patch->is_copy =1;1047free(patch->old_name);1048 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1049return0;1050}10511052static intgitdiff_copydst(struct apply_state *state,1053const char*line,1054struct patch *patch)1055{1056 patch->is_copy =1;1057free(patch->new_name);1058 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1059return0;1060}10611062static intgitdiff_renamesrc(struct apply_state *state,1063const char*line,1064struct patch *patch)1065{1066 patch->is_rename =1;1067free(patch->old_name);1068 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1069return0;1070}10711072static intgitdiff_renamedst(struct apply_state *state,1073const char*line,1074struct patch *patch)1075{1076 patch->is_rename =1;1077free(patch->new_name);1078 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1079return0;1080}10811082static intgitdiff_similarity(struct apply_state *state,1083const char*line,1084struct patch *patch)1085{1086unsigned long val =strtoul(line, NULL,10);1087if(val <=100)1088 patch->score = val;1089return0;1090}10911092static intgitdiff_dissimilarity(struct apply_state *state,1093const char*line,1094struct patch *patch)1095{1096unsigned long val =strtoul(line, NULL,10);1097if(val <=100)1098 patch->score = val;1099return0;1100}11011102static intgitdiff_index(struct apply_state *state,1103const char*line,1104struct patch *patch)1105{1106/*1107 * index line is N hexadecimal, "..", N hexadecimal,1108 * and optional space with octal mode.1109 */1110const char*ptr, *eol;1111int len;11121113 ptr =strchr(line,'.');1114if(!ptr || ptr[1] !='.'||40< ptr - line)1115return0;1116 len = ptr - line;1117memcpy(patch->old_sha1_prefix, line, len);1118 patch->old_sha1_prefix[len] =0;11191120 line = ptr +2;1121 ptr =strchr(line,' ');1122 eol =strchrnul(line,'\n');11231124if(!ptr || eol < ptr)1125 ptr = eol;1126 len = ptr - line;11271128if(40< len)1129return0;1130memcpy(patch->new_sha1_prefix, line, len);1131 patch->new_sha1_prefix[len] =0;1132if(*ptr ==' ')1133 patch->old_mode =strtoul(ptr+1, NULL,8);1134return0;1135}11361137/*1138 * This is normal for a diff that doesn't change anything: we'll fall through1139 * into the next diff. Tell the parser to break out.1140 */1141static intgitdiff_unrecognized(struct apply_state *state,1142const char*line,1143struct patch *patch)1144{1145return-1;1146}11471148/*1149 * Skip p_value leading components from "line"; as we do not accept1150 * absolute paths, return NULL in that case.1151 */1152static const char*skip_tree_prefix(struct apply_state *state,1153const char*line,1154int llen)1155{1156int nslash;1157int i;11581159if(!state->p_value)1160return(llen && line[0] =='/') ? NULL : line;11611162 nslash = state->p_value;1163for(i =0; i < llen; i++) {1164int ch = line[i];1165if(ch =='/'&& --nslash <=0)1166return(i ==0) ? NULL : &line[i +1];1167}1168return NULL;1169}11701171/*1172 * This is to extract the same name that appears on "diff --git"1173 * line. We do not find and return anything if it is a rename1174 * patch, and it is OK because we will find the name elsewhere.1175 * We need to reliably find name only when it is mode-change only,1176 * creation or deletion of an empty file. In any of these cases,1177 * both sides are the same name under a/ and b/ respectively.1178 */1179static char*git_header_name(struct apply_state *state,1180const char*line,1181int llen)1182{1183const char*name;1184const char*second = NULL;1185size_t len, line_len;11861187 line +=strlen("diff --git ");1188 llen -=strlen("diff --git ");11891190if(*line =='"') {1191const char*cp;1192struct strbuf first = STRBUF_INIT;1193struct strbuf sp = STRBUF_INIT;11941195if(unquote_c_style(&first, line, &second))1196goto free_and_fail1;11971198/* strip the a/b prefix including trailing slash */1199 cp =skip_tree_prefix(state, first.buf, first.len);1200if(!cp)1201goto free_and_fail1;1202strbuf_remove(&first,0, cp - first.buf);12031204/*1205 * second points at one past closing dq of name.1206 * find the second name.1207 */1208while((second < line + llen) &&isspace(*second))1209 second++;12101211if(line + llen <= second)1212goto free_and_fail1;1213if(*second =='"') {1214if(unquote_c_style(&sp, second, NULL))1215goto free_and_fail1;1216 cp =skip_tree_prefix(state, sp.buf, sp.len);1217if(!cp)1218goto free_and_fail1;1219/* They must match, otherwise ignore */1220if(strcmp(cp, first.buf))1221goto free_and_fail1;1222strbuf_release(&sp);1223returnstrbuf_detach(&first, NULL);1224}12251226/* unquoted second */1227 cp =skip_tree_prefix(state, second, line + llen - second);1228if(!cp)1229goto free_and_fail1;1230if(line + llen - cp != first.len ||1231memcmp(first.buf, cp, first.len))1232goto free_and_fail1;1233returnstrbuf_detach(&first, NULL);12341235 free_and_fail1:1236strbuf_release(&first);1237strbuf_release(&sp);1238return NULL;1239}12401241/* unquoted first name */1242 name =skip_tree_prefix(state, line, llen);1243if(!name)1244return NULL;12451246/*1247 * since the first name is unquoted, a dq if exists must be1248 * the beginning of the second name.1249 */1250for(second = name; second < line + llen; second++) {1251if(*second =='"') {1252struct strbuf sp = STRBUF_INIT;1253const char*np;12541255if(unquote_c_style(&sp, second, NULL))1256goto free_and_fail2;12571258 np =skip_tree_prefix(state, sp.buf, sp.len);1259if(!np)1260goto free_and_fail2;12611262 len = sp.buf + sp.len - np;1263if(len < second - name &&1264!strncmp(np, name, len) &&1265isspace(name[len])) {1266/* Good */1267strbuf_remove(&sp,0, np - sp.buf);1268returnstrbuf_detach(&sp, NULL);1269}12701271 free_and_fail2:1272strbuf_release(&sp);1273return NULL;1274}1275}12761277/*1278 * Accept a name only if it shows up twice, exactly the same1279 * form.1280 */1281 second =strchr(name,'\n');1282if(!second)1283return NULL;1284 line_len = second - name;1285for(len =0; ; len++) {1286switch(name[len]) {1287default:1288continue;1289case'\n':1290return NULL;1291case'\t':case' ':1292/*1293 * Is this the separator between the preimage1294 * and the postimage pathname? Again, we are1295 * only interested in the case where there is1296 * no rename, as this is only to set def_name1297 * and a rename patch has the names elsewhere1298 * in an unambiguous form.1299 */1300if(!name[len +1])1301return NULL;/* no postimage name */1302 second =skip_tree_prefix(state, name + len +1,1303 line_len - (len +1));1304if(!second)1305return NULL;1306/*1307 * Does len bytes starting at "name" and "second"1308 * (that are separated by one HT or SP we just1309 * found) exactly match?1310 */1311if(second[len] =='\n'&& !strncmp(name, second, len))1312returnxmemdupz(name, len);1313}1314}1315}13161317/* Verify that we recognize the lines following a git header */1318static intparse_git_header(struct apply_state *state,1319const char*line,1320int len,1321unsigned int size,1322struct patch *patch)1323{1324unsigned long offset;13251326/* A git diff has explicit new/delete information, so we don't guess */1327 patch->is_new =0;1328 patch->is_delete =0;13291330/*1331 * Some things may not have the old name in the1332 * rest of the headers anywhere (pure mode changes,1333 * or removing or adding empty files), so we get1334 * the default name from the header.1335 */1336 patch->def_name =git_header_name(state, line, len);1337if(patch->def_name && state->root.len) {1338char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1339free(patch->def_name);1340 patch->def_name = s;1341}13421343 line += len;1344 size -= len;1345 state_linenr++;1346for(offset = len ; size >0; offset += len, size -= len, line += len, state_linenr++) {1347static const struct opentry {1348const char*str;1349int(*fn)(struct apply_state *,const char*,struct patch *);1350} optable[] = {1351{"@@ -", gitdiff_hdrend },1352{"--- ", gitdiff_oldname },1353{"+++ ", gitdiff_newname },1354{"old mode ", gitdiff_oldmode },1355{"new mode ", gitdiff_newmode },1356{"deleted file mode ", gitdiff_delete },1357{"new file mode ", gitdiff_newfile },1358{"copy from ", gitdiff_copysrc },1359{"copy to ", gitdiff_copydst },1360{"rename old ", gitdiff_renamesrc },1361{"rename new ", gitdiff_renamedst },1362{"rename from ", gitdiff_renamesrc },1363{"rename to ", gitdiff_renamedst },1364{"similarity index ", gitdiff_similarity },1365{"dissimilarity index ", gitdiff_dissimilarity },1366{"index ", gitdiff_index },1367{"", gitdiff_unrecognized },1368};1369int i;13701371 len =linelen(line, size);1372if(!len || line[len-1] !='\n')1373break;1374for(i =0; i <ARRAY_SIZE(optable); i++) {1375const struct opentry *p = optable + i;1376int oplen =strlen(p->str);1377if(len < oplen ||memcmp(p->str, line, oplen))1378continue;1379if(p->fn(state, line + oplen, patch) <0)1380return offset;1381break;1382}1383}13841385return offset;1386}13871388static intparse_num(const char*line,unsigned long*p)1389{1390char*ptr;13911392if(!isdigit(*line))1393return0;1394*p =strtoul(line, &ptr,10);1395return ptr - line;1396}13971398static intparse_range(const char*line,int len,int offset,const char*expect,1399unsigned long*p1,unsigned long*p2)1400{1401int digits, ex;14021403if(offset <0|| offset >= len)1404return-1;1405 line += offset;1406 len -= offset;14071408 digits =parse_num(line, p1);1409if(!digits)1410return-1;14111412 offset += digits;1413 line += digits;1414 len -= digits;14151416*p2 =1;1417if(*line ==',') {1418 digits =parse_num(line+1, p2);1419if(!digits)1420return-1;14211422 offset += digits+1;1423 line += digits+1;1424 len -= digits+1;1425}14261427 ex =strlen(expect);1428if(ex > len)1429return-1;1430if(memcmp(line, expect, ex))1431return-1;14321433return offset + ex;1434}14351436static voidrecount_diff(const char*line,int size,struct fragment *fragment)1437{1438int oldlines =0, newlines =0, ret =0;14391440if(size <1) {1441warning("recount: ignore empty hunk");1442return;1443}14441445for(;;) {1446int len =linelen(line, size);1447 size -= len;1448 line += len;14491450if(size <1)1451break;14521453switch(*line) {1454case' ':case'\n':1455 newlines++;1456/* fall through */1457case'-':1458 oldlines++;1459continue;1460case'+':1461 newlines++;1462continue;1463case'\\':1464continue;1465case'@':1466 ret = size <3|| !starts_with(line,"@@ ");1467break;1468case'd':1469 ret = size <5|| !starts_with(line,"diff ");1470break;1471default:1472 ret = -1;1473break;1474}1475if(ret) {1476warning(_("recount: unexpected line: %.*s"),1477(int)linelen(line, size), line);1478return;1479}1480break;1481}1482 fragment->oldlines = oldlines;1483 fragment->newlines = newlines;1484}14851486/*1487 * Parse a unified diff fragment header of the1488 * form "@@ -a,b +c,d @@"1489 */1490static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1491{1492int offset;14931494if(!len || line[len-1] !='\n')1495return-1;14961497/* Figure out the number of lines in a fragment */1498 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1499 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);15001501return offset;1502}15031504static intfind_header(struct apply_state *state,1505const char*line,1506unsigned long size,1507int*hdrsize,1508struct patch *patch)1509{1510unsigned long offset, len;15111512 patch->is_toplevel_relative =0;1513 patch->is_rename = patch->is_copy =0;1514 patch->is_new = patch->is_delete = -1;1515 patch->old_mode = patch->new_mode =0;1516 patch->old_name = patch->new_name = NULL;1517for(offset =0; size >0; offset += len, size -= len, line += len, state_linenr++) {1518unsigned long nextlen;15191520 len =linelen(line, size);1521if(!len)1522break;15231524/* Testing this early allows us to take a few shortcuts.. */1525if(len <6)1526continue;15271528/*1529 * Make sure we don't find any unconnected patch fragments.1530 * That's a sign that we didn't find a header, and that a1531 * patch has become corrupted/broken up.1532 */1533if(!memcmp("@@ -", line,4)) {1534struct fragment dummy;1535if(parse_fragment_header(line, len, &dummy) <0)1536continue;1537die(_("patch fragment without header at line%d: %.*s"),1538 state_linenr, (int)len-1, line);1539}15401541if(size < len +6)1542break;15431544/*1545 * Git patch? It might not have a real patch, just a rename1546 * or mode change, so we handle that specially1547 */1548if(!memcmp("diff --git ", line,11)) {1549int git_hdr_len =parse_git_header(state, line, len, size, patch);1550if(git_hdr_len <= len)1551continue;1552if(!patch->old_name && !patch->new_name) {1553if(!patch->def_name)1554die(Q_("git diff header lacks filename information when removing "1555"%dleading pathname component (line%d)",1556"git diff header lacks filename information when removing "1557"%dleading pathname components (line%d)",1558 state->p_value),1559 state->p_value, state_linenr);1560 patch->old_name =xstrdup(patch->def_name);1561 patch->new_name =xstrdup(patch->def_name);1562}1563if(!patch->is_delete && !patch->new_name)1564die("git diff header lacks filename information "1565"(line%d)", state_linenr);1566 patch->is_toplevel_relative =1;1567*hdrsize = git_hdr_len;1568return offset;1569}15701571/* --- followed by +++ ? */1572if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1573continue;15741575/*1576 * We only accept unified patches, so we want it to1577 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1578 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1579 */1580 nextlen =linelen(line + len, size - len);1581if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1582continue;15831584/* Ok, we'll consider it a patch */1585parse_traditional_patch(state, line, line+len, patch);1586*hdrsize = len + nextlen;1587 state_linenr +=2;1588return offset;1589}1590return-1;1591}15921593static voidrecord_ws_error(struct apply_state *state,1594unsigned result,1595const char*line,1596int len,1597int linenr)1598{1599char*err;16001601if(!result)1602return;16031604 state->whitespace_error++;1605if(state->squelch_whitespace_errors &&1606 state->squelch_whitespace_errors < state->whitespace_error)1607return;16081609 err =whitespace_error_string(result);1610fprintf(stderr,"%s:%d:%s.\n%.*s\n",1611 state->patch_input_file, linenr, err, len, line);1612free(err);1613}16141615static voidcheck_whitespace(struct apply_state *state,1616const char*line,1617int len,1618unsigned ws_rule)1619{1620unsigned result =ws_check(line +1, len -1, ws_rule);16211622record_ws_error(state, result, line +1, len -2, state_linenr);1623}16241625/*1626 * Parse a unified diff. Note that this really needs to parse each1627 * fragment separately, since the only way to know the difference1628 * between a "---" that is part of a patch, and a "---" that starts1629 * the next patch is to look at the line counts..1630 */1631static intparse_fragment(struct apply_state *state,1632const char*line,1633unsigned long size,1634struct patch *patch,1635struct fragment *fragment)1636{1637int added, deleted;1638int len =linelen(line, size), offset;1639unsigned long oldlines, newlines;1640unsigned long leading, trailing;16411642 offset =parse_fragment_header(line, len, fragment);1643if(offset <0)1644return-1;1645if(offset >0&& patch->recount)1646recount_diff(line + offset, size - offset, fragment);1647 oldlines = fragment->oldlines;1648 newlines = fragment->newlines;1649 leading =0;1650 trailing =0;16511652/* Parse the thing.. */1653 line += len;1654 size -= len;1655 state_linenr++;1656 added = deleted =0;1657for(offset = len;16580< size;1659 offset += len, size -= len, line += len, state_linenr++) {1660if(!oldlines && !newlines)1661break;1662 len =linelen(line, size);1663if(!len || line[len-1] !='\n')1664return-1;1665switch(*line) {1666default:1667return-1;1668case'\n':/* newer GNU diff, an empty context line */1669case' ':1670 oldlines--;1671 newlines--;1672if(!deleted && !added)1673 leading++;1674 trailing++;1675if(!state->apply_in_reverse &&1676 state->ws_error_action == correct_ws_error)1677check_whitespace(state, line, len, patch->ws_rule);1678break;1679case'-':1680if(state->apply_in_reverse &&1681 state->ws_error_action != nowarn_ws_error)1682check_whitespace(state, line, len, patch->ws_rule);1683 deleted++;1684 oldlines--;1685 trailing =0;1686break;1687case'+':1688if(!state->apply_in_reverse &&1689 state->ws_error_action != nowarn_ws_error)1690check_whitespace(state, line, len, patch->ws_rule);1691 added++;1692 newlines--;1693 trailing =0;1694break;16951696/*1697 * We allow "\ No newline at end of file". Depending1698 * on locale settings when the patch was produced we1699 * don't know what this line looks like. The only1700 * thing we do know is that it begins with "\ ".1701 * Checking for 12 is just for sanity check -- any1702 * l10n of "\ No newline..." is at least that long.1703 */1704case'\\':1705if(len <12||memcmp(line,"\\",2))1706return-1;1707break;1708}1709}1710if(oldlines || newlines)1711return-1;1712if(!deleted && !added)1713return-1;17141715 fragment->leading = leading;1716 fragment->trailing = trailing;17171718/*1719 * If a fragment ends with an incomplete line, we failed to include1720 * it in the above loop because we hit oldlines == newlines == 01721 * before seeing it.1722 */1723if(12< size && !memcmp(line,"\\",2))1724 offset +=linelen(line, size);17251726 patch->lines_added += added;1727 patch->lines_deleted += deleted;17281729if(0< patch->is_new && oldlines)1730returnerror(_("new file depends on old contents"));1731if(0< patch->is_delete && newlines)1732returnerror(_("deleted file still has contents"));1733return offset;1734}17351736/*1737 * We have seen "diff --git a/... b/..." header (or a traditional patch1738 * header). Read hunks that belong to this patch into fragments and hang1739 * them to the given patch structure.1740 *1741 * The (fragment->patch, fragment->size) pair points into the memory given1742 * by the caller, not a copy, when we return.1743 */1744static intparse_single_patch(struct apply_state *state,1745const char*line,1746unsigned long size,1747struct patch *patch)1748{1749unsigned long offset =0;1750unsigned long oldlines =0, newlines =0, context =0;1751struct fragment **fragp = &patch->fragments;17521753while(size >4&& !memcmp(line,"@@ -",4)) {1754struct fragment *fragment;1755int len;17561757 fragment =xcalloc(1,sizeof(*fragment));1758 fragment->linenr = state_linenr;1759 len =parse_fragment(state, line, size, patch, fragment);1760if(len <=0)1761die(_("corrupt patch at line%d"), state_linenr);1762 fragment->patch = line;1763 fragment->size = len;1764 oldlines += fragment->oldlines;1765 newlines += fragment->newlines;1766 context += fragment->leading + fragment->trailing;17671768*fragp = fragment;1769 fragp = &fragment->next;17701771 offset += len;1772 line += len;1773 size -= len;1774}17751776/*1777 * If something was removed (i.e. we have old-lines) it cannot1778 * be creation, and if something was added it cannot be1779 * deletion. However, the reverse is not true; --unified=01780 * patches that only add are not necessarily creation even1781 * though they do not have any old lines, and ones that only1782 * delete are not necessarily deletion.1783 *1784 * Unfortunately, a real creation/deletion patch do _not_ have1785 * any context line by definition, so we cannot safely tell it1786 * apart with --unified=0 insanity. At least if the patch has1787 * more than one hunk it is not creation or deletion.1788 */1789if(patch->is_new <0&&1790(oldlines || (patch->fragments && patch->fragments->next)))1791 patch->is_new =0;1792if(patch->is_delete <0&&1793(newlines || (patch->fragments && patch->fragments->next)))1794 patch->is_delete =0;17951796if(0< patch->is_new && oldlines)1797die(_("new file%sdepends on old contents"), patch->new_name);1798if(0< patch->is_delete && newlines)1799die(_("deleted file%sstill has contents"), patch->old_name);1800if(!patch->is_delete && !newlines && context)1801fprintf_ln(stderr,1802_("** warning: "1803"file%sbecomes empty but is not deleted"),1804 patch->new_name);18051806return offset;1807}18081809staticinlineintmetadata_changes(struct patch *patch)1810{1811return patch->is_rename >0||1812 patch->is_copy >0||1813 patch->is_new >0||1814 patch->is_delete ||1815(patch->old_mode && patch->new_mode &&1816 patch->old_mode != patch->new_mode);1817}18181819static char*inflate_it(const void*data,unsigned long size,1820unsigned long inflated_size)1821{1822 git_zstream stream;1823void*out;1824int st;18251826memset(&stream,0,sizeof(stream));18271828 stream.next_in = (unsigned char*)data;1829 stream.avail_in = size;1830 stream.next_out = out =xmalloc(inflated_size);1831 stream.avail_out = inflated_size;1832git_inflate_init(&stream);1833 st =git_inflate(&stream, Z_FINISH);1834git_inflate_end(&stream);1835if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1836free(out);1837return NULL;1838}1839return out;1840}18411842/*1843 * Read a binary hunk and return a new fragment; fragment->patch1844 * points at an allocated memory that the caller must free, so1845 * it is marked as "->free_patch = 1".1846 */1847static struct fragment *parse_binary_hunk(char**buf_p,1848unsigned long*sz_p,1849int*status_p,1850int*used_p)1851{1852/*1853 * Expect a line that begins with binary patch method ("literal"1854 * or "delta"), followed by the length of data before deflating.1855 * a sequence of 'length-byte' followed by base-85 encoded data1856 * should follow, terminated by a newline.1857 *1858 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1859 * and we would limit the patch line to 66 characters,1860 * so one line can fit up to 13 groups that would decode1861 * to 52 bytes max. The length byte 'A'-'Z' corresponds1862 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1863 */1864int llen, used;1865unsigned long size = *sz_p;1866char*buffer = *buf_p;1867int patch_method;1868unsigned long origlen;1869char*data = NULL;1870int hunk_size =0;1871struct fragment *frag;18721873 llen =linelen(buffer, size);1874 used = llen;18751876*status_p =0;18771878if(starts_with(buffer,"delta ")) {1879 patch_method = BINARY_DELTA_DEFLATED;1880 origlen =strtoul(buffer +6, NULL,10);1881}1882else if(starts_with(buffer,"literal ")) {1883 patch_method = BINARY_LITERAL_DEFLATED;1884 origlen =strtoul(buffer +8, NULL,10);1885}1886else1887return NULL;18881889 state_linenr++;1890 buffer += llen;1891while(1) {1892int byte_length, max_byte_length, newsize;1893 llen =linelen(buffer, size);1894 used += llen;1895 state_linenr++;1896if(llen ==1) {1897/* consume the blank line */1898 buffer++;1899 size--;1900break;1901}1902/*1903 * Minimum line is "A00000\n" which is 7-byte long,1904 * and the line length must be multiple of 5 plus 2.1905 */1906if((llen <7) || (llen-2) %5)1907goto corrupt;1908 max_byte_length = (llen -2) /5*4;1909 byte_length = *buffer;1910if('A'<= byte_length && byte_length <='Z')1911 byte_length = byte_length -'A'+1;1912else if('a'<= byte_length && byte_length <='z')1913 byte_length = byte_length -'a'+27;1914else1915goto corrupt;1916/* if the input length was not multiple of 4, we would1917 * have filler at the end but the filler should never1918 * exceed 3 bytes1919 */1920if(max_byte_length < byte_length ||1921 byte_length <= max_byte_length -4)1922goto corrupt;1923 newsize = hunk_size + byte_length;1924 data =xrealloc(data, newsize);1925if(decode_85(data + hunk_size, buffer +1, byte_length))1926goto corrupt;1927 hunk_size = newsize;1928 buffer += llen;1929 size -= llen;1930}19311932 frag =xcalloc(1,sizeof(*frag));1933 frag->patch =inflate_it(data, hunk_size, origlen);1934 frag->free_patch =1;1935if(!frag->patch)1936goto corrupt;1937free(data);1938 frag->size = origlen;1939*buf_p = buffer;1940*sz_p = size;1941*used_p = used;1942 frag->binary_patch_method = patch_method;1943return frag;19441945 corrupt:1946free(data);1947*status_p = -1;1948error(_("corrupt binary patch at line%d: %.*s"),1949 state_linenr-1, llen-1, buffer);1950return NULL;1951}19521953/*1954 * Returns:1955 * -1 in case of error,1956 * the length of the parsed binary patch otherwise1957 */1958static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1959{1960/*1961 * We have read "GIT binary patch\n"; what follows is a line1962 * that says the patch method (currently, either "literal" or1963 * "delta") and the length of data before deflating; a1964 * sequence of 'length-byte' followed by base-85 encoded data1965 * follows.1966 *1967 * When a binary patch is reversible, there is another binary1968 * hunk in the same format, starting with patch method (either1969 * "literal" or "delta") with the length of data, and a sequence1970 * of length-byte + base-85 encoded data, terminated with another1971 * empty line. This data, when applied to the postimage, produces1972 * the preimage.1973 */1974struct fragment *forward;1975struct fragment *reverse;1976int status;1977int used, used_1;19781979 forward =parse_binary_hunk(&buffer, &size, &status, &used);1980if(!forward && !status)1981/* there has to be one hunk (forward hunk) */1982returnerror(_("unrecognized binary patch at line%d"), state_linenr-1);1983if(status)1984/* otherwise we already gave an error message */1985return status;19861987 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1988if(reverse)1989 used += used_1;1990else if(status) {1991/*1992 * Not having reverse hunk is not an error, but having1993 * a corrupt reverse hunk is.1994 */1995free((void*) forward->patch);1996free(forward);1997return status;1998}1999 forward->next = reverse;2000 patch->fragments = forward;2001 patch->is_binary =1;2002return used;2003}20042005static voidprefix_one(struct apply_state *state,char**name)2006{2007char*old_name = *name;2008if(!old_name)2009return;2010*name =xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));2011free(old_name);2012}20132014static voidprefix_patch(struct apply_state *state,struct patch *p)2015{2016if(!state->prefix || p->is_toplevel_relative)2017return;2018prefix_one(state, &p->new_name);2019prefix_one(state, &p->old_name);2020}20212022/*2023 * include/exclude2024 */20252026static voidadd_name_limit(struct apply_state *state,2027const char*name,2028int exclude)2029{2030struct string_list_item *it;20312032 it =string_list_append(&state->limit_by_name, name);2033 it->util = exclude ? NULL : (void*)1;2034}20352036static intuse_patch(struct apply_state *state,struct patch *p)2037{2038const char*pathname = p->new_name ? p->new_name : p->old_name;2039int i;20402041/* Paths outside are not touched regardless of "--include" */2042if(0< state->prefix_length) {2043int pathlen =strlen(pathname);2044if(pathlen <= state->prefix_length ||2045memcmp(state->prefix, pathname, state->prefix_length))2046return0;2047}20482049/* See if it matches any of exclude/include rule */2050for(i =0; i < state->limit_by_name.nr; i++) {2051struct string_list_item *it = &state->limit_by_name.items[i];2052if(!wildmatch(it->string, pathname,0, NULL))2053return(it->util != NULL);2054}20552056/*2057 * If we had any include, a path that does not match any rule is2058 * not used. Otherwise, we saw bunch of exclude rules (or none)2059 * and such a path is used.2060 */2061return!state->has_include;2062}206320642065/*2066 * Read the patch text in "buffer" that extends for "size" bytes; stop2067 * reading after seeing a single patch (i.e. changes to a single file).2068 * Create fragments (i.e. patch hunks) and hang them to the given patch.2069 * Return the number of bytes consumed, so that the caller can call us2070 * again for the next patch.2071 */2072static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2073{2074int hdrsize, patchsize;2075int offset =find_header(state, buffer, size, &hdrsize, patch);20762077if(offset <0)2078return offset;20792080prefix_patch(state, patch);20812082if(!use_patch(state, patch))2083 patch->ws_rule =0;2084else2085 patch->ws_rule =whitespace_rule(patch->new_name2086? patch->new_name2087: patch->old_name);20882089 patchsize =parse_single_patch(state,2090 buffer + offset + hdrsize,2091 size - offset - hdrsize,2092 patch);20932094if(!patchsize) {2095static const char git_binary[] ="GIT binary patch\n";2096int hd = hdrsize + offset;2097unsigned long llen =linelen(buffer + hd, size - hd);20982099if(llen ==sizeof(git_binary) -1&&2100!memcmp(git_binary, buffer + hd, llen)) {2101int used;2102 state_linenr++;2103 used =parse_binary(buffer + hd + llen,2104 size - hd - llen, patch);2105if(used <0)2106return-1;2107if(used)2108 patchsize = used + llen;2109else2110 patchsize =0;2111}2112else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2113static const char*binhdr[] = {2114"Binary files ",2115"Files ",2116 NULL,2117};2118int i;2119for(i =0; binhdr[i]; i++) {2120int len =strlen(binhdr[i]);2121if(len < size - hd &&2122!memcmp(binhdr[i], buffer + hd, len)) {2123 state_linenr++;2124 patch->is_binary =1;2125 patchsize = llen;2126break;2127}2128}2129}21302131/* Empty patch cannot be applied if it is a text patch2132 * without metadata change. A binary patch appears2133 * empty to us here.2134 */2135if((state->apply || state->check) &&2136(!patch->is_binary && !metadata_changes(patch)))2137die(_("patch with only garbage at line%d"), state_linenr);2138}21392140return offset + hdrsize + patchsize;2141}21422143#define swap(a,b) myswap((a),(b),sizeof(a))21442145#define myswap(a, b, size) do { \2146 unsigned char mytmp[size]; \2147 memcpy(mytmp, &a, size); \2148 memcpy(&a, &b, size); \2149 memcpy(&b, mytmp, size); \2150} while (0)21512152static voidreverse_patches(struct patch *p)2153{2154for(; p; p = p->next) {2155struct fragment *frag = p->fragments;21562157swap(p->new_name, p->old_name);2158swap(p->new_mode, p->old_mode);2159swap(p->is_new, p->is_delete);2160swap(p->lines_added, p->lines_deleted);2161swap(p->old_sha1_prefix, p->new_sha1_prefix);21622163for(; frag; frag = frag->next) {2164swap(frag->newpos, frag->oldpos);2165swap(frag->newlines, frag->oldlines);2166}2167}2168}21692170static const char pluses[] =2171"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2172static const char minuses[]=2173"----------------------------------------------------------------------";21742175static voidshow_stats(struct patch *patch)2176{2177struct strbuf qname = STRBUF_INIT;2178char*cp = patch->new_name ? patch->new_name : patch->old_name;2179int max, add, del;21802181quote_c_style(cp, &qname, NULL,0);21822183/*2184 * "scale" the filename2185 */2186 max = max_len;2187if(max >50)2188 max =50;21892190if(qname.len > max) {2191 cp =strchr(qname.buf + qname.len +3- max,'/');2192if(!cp)2193 cp = qname.buf + qname.len +3- max;2194strbuf_splice(&qname,0, cp - qname.buf,"...",3);2195}21962197if(patch->is_binary) {2198printf(" %-*s | Bin\n", max, qname.buf);2199strbuf_release(&qname);2200return;2201}22022203printf(" %-*s |", max, qname.buf);2204strbuf_release(&qname);22052206/*2207 * scale the add/delete2208 */2209 max = max + max_change >70?70- max : max_change;2210 add = patch->lines_added;2211 del = patch->lines_deleted;22122213if(max_change >0) {2214int total = ((add + del) * max + max_change /2) / max_change;2215 add = (add * max + max_change /2) / max_change;2216 del = total - add;2217}2218printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2219 add, pluses, del, minuses);2220}22212222static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2223{2224switch(st->st_mode & S_IFMT) {2225case S_IFLNK:2226if(strbuf_readlink(buf, path, st->st_size) <0)2227returnerror(_("unable to read symlink%s"), path);2228return0;2229case S_IFREG:2230if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2231returnerror(_("unable to open or read%s"), path);2232convert_to_git(path, buf->buf, buf->len, buf,0);2233return0;2234default:2235return-1;2236}2237}22382239/*2240 * Update the preimage, and the common lines in postimage,2241 * from buffer buf of length len. If postlen is 0 the postimage2242 * is updated in place, otherwise it's updated on a new buffer2243 * of length postlen2244 */22452246static voidupdate_pre_post_images(struct image *preimage,2247struct image *postimage,2248char*buf,2249size_t len,size_t postlen)2250{2251int i, ctx, reduced;2252char*new, *old, *fixed;2253struct image fixed_preimage;22542255/*2256 * Update the preimage with whitespace fixes. Note that we2257 * are not losing preimage->buf -- apply_one_fragment() will2258 * free "oldlines".2259 */2260prepare_image(&fixed_preimage, buf, len,1);2261assert(postlen2262? fixed_preimage.nr == preimage->nr2263: fixed_preimage.nr <= preimage->nr);2264for(i =0; i < fixed_preimage.nr; i++)2265 fixed_preimage.line[i].flag = preimage->line[i].flag;2266free(preimage->line_allocated);2267*preimage = fixed_preimage;22682269/*2270 * Adjust the common context lines in postimage. This can be2271 * done in-place when we are shrinking it with whitespace2272 * fixing, but needs a new buffer when ignoring whitespace or2273 * expanding leading tabs to spaces.2274 *2275 * We trust the caller to tell us if the update can be done2276 * in place (postlen==0) or not.2277 */2278 old = postimage->buf;2279if(postlen)2280new= postimage->buf =xmalloc(postlen);2281else2282new= old;2283 fixed = preimage->buf;22842285for(i = reduced = ctx =0; i < postimage->nr; i++) {2286size_t l_len = postimage->line[i].len;2287if(!(postimage->line[i].flag & LINE_COMMON)) {2288/* an added line -- no counterparts in preimage */2289memmove(new, old, l_len);2290 old += l_len;2291new+= l_len;2292continue;2293}22942295/* a common context -- skip it in the original postimage */2296 old += l_len;22972298/* and find the corresponding one in the fixed preimage */2299while(ctx < preimage->nr &&2300!(preimage->line[ctx].flag & LINE_COMMON)) {2301 fixed += preimage->line[ctx].len;2302 ctx++;2303}23042305/*2306 * preimage is expected to run out, if the caller2307 * fixed addition of trailing blank lines.2308 */2309if(preimage->nr <= ctx) {2310 reduced++;2311continue;2312}23132314/* and copy it in, while fixing the line length */2315 l_len = preimage->line[ctx].len;2316memcpy(new, fixed, l_len);2317new+= l_len;2318 fixed += l_len;2319 postimage->line[i].len = l_len;2320 ctx++;2321}23222323if(postlen2324? postlen <new- postimage->buf2325: postimage->len <new- postimage->buf)2326die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2327(int)postlen, (int) postimage->len, (int)(new- postimage->buf));23282329/* Fix the length of the whole thing */2330 postimage->len =new- postimage->buf;2331 postimage->nr -= reduced;2332}23332334static intline_by_line_fuzzy_match(struct image *img,2335struct image *preimage,2336struct image *postimage,2337unsigned longtry,2338int try_lno,2339int preimage_limit)2340{2341int i;2342size_t imgoff =0;2343size_t preoff =0;2344size_t postlen = postimage->len;2345size_t extra_chars;2346char*buf;2347char*preimage_eof;2348char*preimage_end;2349struct strbuf fixed;2350char*fixed_buf;2351size_t fixed_len;23522353for(i =0; i < preimage_limit; i++) {2354size_t prelen = preimage->line[i].len;2355size_t imglen = img->line[try_lno+i].len;23562357if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2358 preimage->buf + preoff, prelen))2359return0;2360if(preimage->line[i].flag & LINE_COMMON)2361 postlen += imglen - prelen;2362 imgoff += imglen;2363 preoff += prelen;2364}23652366/*2367 * Ok, the preimage matches with whitespace fuzz.2368 *2369 * imgoff now holds the true length of the target that2370 * matches the preimage before the end of the file.2371 *2372 * Count the number of characters in the preimage that fall2373 * beyond the end of the file and make sure that all of them2374 * are whitespace characters. (This can only happen if2375 * we are removing blank lines at the end of the file.)2376 */2377 buf = preimage_eof = preimage->buf + preoff;2378for( ; i < preimage->nr; i++)2379 preoff += preimage->line[i].len;2380 preimage_end = preimage->buf + preoff;2381for( ; buf < preimage_end; buf++)2382if(!isspace(*buf))2383return0;23842385/*2386 * Update the preimage and the common postimage context2387 * lines to use the same whitespace as the target.2388 * If whitespace is missing in the target (i.e.2389 * if the preimage extends beyond the end of the file),2390 * use the whitespace from the preimage.2391 */2392 extra_chars = preimage_end - preimage_eof;2393strbuf_init(&fixed, imgoff + extra_chars);2394strbuf_add(&fixed, img->buf +try, imgoff);2395strbuf_add(&fixed, preimage_eof, extra_chars);2396 fixed_buf =strbuf_detach(&fixed, &fixed_len);2397update_pre_post_images(preimage, postimage,2398 fixed_buf, fixed_len, postlen);2399return1;2400}24012402static intmatch_fragment(struct apply_state *state,2403struct image *img,2404struct image *preimage,2405struct image *postimage,2406unsigned longtry,2407int try_lno,2408unsigned ws_rule,2409int match_beginning,int match_end)2410{2411int i;2412char*fixed_buf, *buf, *orig, *target;2413struct strbuf fixed;2414size_t fixed_len, postlen;2415int preimage_limit;24162417if(preimage->nr + try_lno <= img->nr) {2418/*2419 * The hunk falls within the boundaries of img.2420 */2421 preimage_limit = preimage->nr;2422if(match_end && (preimage->nr + try_lno != img->nr))2423return0;2424}else if(state->ws_error_action == correct_ws_error &&2425(ws_rule & WS_BLANK_AT_EOF)) {2426/*2427 * This hunk extends beyond the end of img, and we are2428 * removing blank lines at the end of the file. This2429 * many lines from the beginning of the preimage must2430 * match with img, and the remainder of the preimage2431 * must be blank.2432 */2433 preimage_limit = img->nr - try_lno;2434}else{2435/*2436 * The hunk extends beyond the end of the img and2437 * we are not removing blanks at the end, so we2438 * should reject the hunk at this position.2439 */2440return0;2441}24422443if(match_beginning && try_lno)2444return0;24452446/* Quick hash check */2447for(i =0; i < preimage_limit; i++)2448if((img->line[try_lno + i].flag & LINE_PATCHED) ||2449(preimage->line[i].hash != img->line[try_lno + i].hash))2450return0;24512452if(preimage_limit == preimage->nr) {2453/*2454 * Do we have an exact match? If we were told to match2455 * at the end, size must be exactly at try+fragsize,2456 * otherwise try+fragsize must be still within the preimage,2457 * and either case, the old piece should match the preimage2458 * exactly.2459 */2460if((match_end2461? (try+ preimage->len == img->len)2462: (try+ preimage->len <= img->len)) &&2463!memcmp(img->buf +try, preimage->buf, preimage->len))2464return1;2465}else{2466/*2467 * The preimage extends beyond the end of img, so2468 * there cannot be an exact match.2469 *2470 * There must be one non-blank context line that match2471 * a line before the end of img.2472 */2473char*buf_end;24742475 buf = preimage->buf;2476 buf_end = buf;2477for(i =0; i < preimage_limit; i++)2478 buf_end += preimage->line[i].len;24792480for( ; buf < buf_end; buf++)2481if(!isspace(*buf))2482break;2483if(buf == buf_end)2484return0;2485}24862487/*2488 * No exact match. If we are ignoring whitespace, run a line-by-line2489 * fuzzy matching. We collect all the line length information because2490 * we need it to adjust whitespace if we match.2491 */2492if(state->ws_ignore_action == ignore_ws_change)2493returnline_by_line_fuzzy_match(img, preimage, postimage,2494try, try_lno, preimage_limit);24952496if(state->ws_error_action != correct_ws_error)2497return0;24982499/*2500 * The hunk does not apply byte-by-byte, but the hash says2501 * it might with whitespace fuzz. We weren't asked to2502 * ignore whitespace, we were asked to correct whitespace2503 * errors, so let's try matching after whitespace correction.2504 *2505 * While checking the preimage against the target, whitespace2506 * errors in both fixed, we count how large the corresponding2507 * postimage needs to be. The postimage prepared by2508 * apply_one_fragment() has whitespace errors fixed on added2509 * lines already, but the common lines were propagated as-is,2510 * which may become longer when their whitespace errors are2511 * fixed.2512 */25132514/* First count added lines in postimage */2515 postlen =0;2516for(i =0; i < postimage->nr; i++) {2517if(!(postimage->line[i].flag & LINE_COMMON))2518 postlen += postimage->line[i].len;2519}25202521/*2522 * The preimage may extend beyond the end of the file,2523 * but in this loop we will only handle the part of the2524 * preimage that falls within the file.2525 */2526strbuf_init(&fixed, preimage->len +1);2527 orig = preimage->buf;2528 target = img->buf +try;2529for(i =0; i < preimage_limit; i++) {2530size_t oldlen = preimage->line[i].len;2531size_t tgtlen = img->line[try_lno + i].len;2532size_t fixstart = fixed.len;2533struct strbuf tgtfix;2534int match;25352536/* Try fixing the line in the preimage */2537ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25382539/* Try fixing the line in the target */2540strbuf_init(&tgtfix, tgtlen);2541ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);25422543/*2544 * If they match, either the preimage was based on2545 * a version before our tree fixed whitespace breakage,2546 * or we are lacking a whitespace-fix patch the tree2547 * the preimage was based on already had (i.e. target2548 * has whitespace breakage, the preimage doesn't).2549 * In either case, we are fixing the whitespace breakages2550 * so we might as well take the fix together with their2551 * real change.2552 */2553 match = (tgtfix.len == fixed.len - fixstart &&2554!memcmp(tgtfix.buf, fixed.buf + fixstart,2555 fixed.len - fixstart));25562557/* Add the length if this is common with the postimage */2558if(preimage->line[i].flag & LINE_COMMON)2559 postlen += tgtfix.len;25602561strbuf_release(&tgtfix);2562if(!match)2563goto unmatch_exit;25642565 orig += oldlen;2566 target += tgtlen;2567}256825692570/*2571 * Now handle the lines in the preimage that falls beyond the2572 * end of the file (if any). They will only match if they are2573 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2574 * false).2575 */2576for( ; i < preimage->nr; i++) {2577size_t fixstart = fixed.len;/* start of the fixed preimage */2578size_t oldlen = preimage->line[i].len;2579int j;25802581/* Try fixing the line in the preimage */2582ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25832584for(j = fixstart; j < fixed.len; j++)2585if(!isspace(fixed.buf[j]))2586goto unmatch_exit;25872588 orig += oldlen;2589}25902591/*2592 * Yes, the preimage is based on an older version that still2593 * has whitespace breakages unfixed, and fixing them makes the2594 * hunk match. Update the context lines in the postimage.2595 */2596 fixed_buf =strbuf_detach(&fixed, &fixed_len);2597if(postlen < postimage->len)2598 postlen =0;2599update_pre_post_images(preimage, postimage,2600 fixed_buf, fixed_len, postlen);2601return1;26022603 unmatch_exit:2604strbuf_release(&fixed);2605return0;2606}26072608static intfind_pos(struct apply_state *state,2609struct image *img,2610struct image *preimage,2611struct image *postimage,2612int line,2613unsigned ws_rule,2614int match_beginning,int match_end)2615{2616int i;2617unsigned long backwards, forwards,try;2618int backwards_lno, forwards_lno, try_lno;26192620/*2621 * If match_beginning or match_end is specified, there is no2622 * point starting from a wrong line that will never match and2623 * wander around and wait for a match at the specified end.2624 */2625if(match_beginning)2626 line =0;2627else if(match_end)2628 line = img->nr - preimage->nr;26292630/*2631 * Because the comparison is unsigned, the following test2632 * will also take care of a negative line number that can2633 * result when match_end and preimage is larger than the target.2634 */2635if((size_t) line > img->nr)2636 line = img->nr;26372638try=0;2639for(i =0; i < line; i++)2640try+= img->line[i].len;26412642/*2643 * There's probably some smart way to do this, but I'll leave2644 * that to the smart and beautiful people. I'm simple and stupid.2645 */2646 backwards =try;2647 backwards_lno = line;2648 forwards =try;2649 forwards_lno = line;2650 try_lno = line;26512652for(i =0; ; i++) {2653if(match_fragment(state, img, preimage, postimage,2654try, try_lno, ws_rule,2655 match_beginning, match_end))2656return try_lno;26572658 again:2659if(backwards_lno ==0&& forwards_lno == img->nr)2660break;26612662if(i &1) {2663if(backwards_lno ==0) {2664 i++;2665goto again;2666}2667 backwards_lno--;2668 backwards -= img->line[backwards_lno].len;2669try= backwards;2670 try_lno = backwards_lno;2671}else{2672if(forwards_lno == img->nr) {2673 i++;2674goto again;2675}2676 forwards += img->line[forwards_lno].len;2677 forwards_lno++;2678try= forwards;2679 try_lno = forwards_lno;2680}26812682}2683return-1;2684}26852686static voidremove_first_line(struct image *img)2687{2688 img->buf += img->line[0].len;2689 img->len -= img->line[0].len;2690 img->line++;2691 img->nr--;2692}26932694static voidremove_last_line(struct image *img)2695{2696 img->len -= img->line[--img->nr].len;2697}26982699/*2700 * The change from "preimage" and "postimage" has been found to2701 * apply at applied_pos (counts in line numbers) in "img".2702 * Update "img" to remove "preimage" and replace it with "postimage".2703 */2704static voidupdate_image(struct apply_state *state,2705struct image *img,2706int applied_pos,2707struct image *preimage,2708struct image *postimage)2709{2710/*2711 * remove the copy of preimage at offset in img2712 * and replace it with postimage2713 */2714int i, nr;2715size_t remove_count, insert_count, applied_at =0;2716char*result;2717int preimage_limit;27182719/*2720 * If we are removing blank lines at the end of img,2721 * the preimage may extend beyond the end.2722 * If that is the case, we must be careful only to2723 * remove the part of the preimage that falls within2724 * the boundaries of img. Initialize preimage_limit2725 * to the number of lines in the preimage that falls2726 * within the boundaries.2727 */2728 preimage_limit = preimage->nr;2729if(preimage_limit > img->nr - applied_pos)2730 preimage_limit = img->nr - applied_pos;27312732for(i =0; i < applied_pos; i++)2733 applied_at += img->line[i].len;27342735 remove_count =0;2736for(i =0; i < preimage_limit; i++)2737 remove_count += img->line[applied_pos + i].len;2738 insert_count = postimage->len;27392740/* Adjust the contents */2741 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2742memcpy(result, img->buf, applied_at);2743memcpy(result + applied_at, postimage->buf, postimage->len);2744memcpy(result + applied_at + postimage->len,2745 img->buf + (applied_at + remove_count),2746 img->len - (applied_at + remove_count));2747free(img->buf);2748 img->buf = result;2749 img->len += insert_count - remove_count;2750 result[img->len] ='\0';27512752/* Adjust the line table */2753 nr = img->nr + postimage->nr - preimage_limit;2754if(preimage_limit < postimage->nr) {2755/*2756 * NOTE: this knows that we never call remove_first_line()2757 * on anything other than pre/post image.2758 */2759REALLOC_ARRAY(img->line, nr);2760 img->line_allocated = img->line;2761}2762if(preimage_limit != postimage->nr)2763memmove(img->line + applied_pos + postimage->nr,2764 img->line + applied_pos + preimage_limit,2765(img->nr - (applied_pos + preimage_limit)) *2766sizeof(*img->line));2767memcpy(img->line + applied_pos,2768 postimage->line,2769 postimage->nr *sizeof(*img->line));2770if(!state->allow_overlap)2771for(i =0; i < postimage->nr; i++)2772 img->line[applied_pos + i].flag |= LINE_PATCHED;2773 img->nr = nr;2774}27752776/*2777 * Use the patch-hunk text in "frag" to prepare two images (preimage and2778 * postimage) for the hunk. Find lines that match "preimage" in "img" and2779 * replace the part of "img" with "postimage" text.2780 */2781static intapply_one_fragment(struct apply_state *state,2782struct image *img,struct fragment *frag,2783int inaccurate_eof,unsigned ws_rule,2784int nth_fragment)2785{2786int match_beginning, match_end;2787const char*patch = frag->patch;2788int size = frag->size;2789char*old, *oldlines;2790struct strbuf newlines;2791int new_blank_lines_at_end =0;2792int found_new_blank_lines_at_end =0;2793int hunk_linenr = frag->linenr;2794unsigned long leading, trailing;2795int pos, applied_pos;2796struct image preimage;2797struct image postimage;27982799memset(&preimage,0,sizeof(preimage));2800memset(&postimage,0,sizeof(postimage));2801 oldlines =xmalloc(size);2802strbuf_init(&newlines, size);28032804 old = oldlines;2805while(size >0) {2806char first;2807int len =linelen(patch, size);2808int plen;2809int added_blank_line =0;2810int is_blank_context =0;2811size_t start;28122813if(!len)2814break;28152816/*2817 * "plen" is how much of the line we should use for2818 * the actual patch data. Normally we just remove the2819 * first character on the line, but if the line is2820 * followed by "\ No newline", then we also remove the2821 * last one (which is the newline, of course).2822 */2823 plen = len -1;2824if(len < size && patch[len] =='\\')2825 plen--;2826 first = *patch;2827if(state->apply_in_reverse) {2828if(first =='-')2829 first ='+';2830else if(first =='+')2831 first ='-';2832}28332834switch(first) {2835case'\n':2836/* Newer GNU diff, empty context line */2837if(plen <0)2838/* ... followed by '\No newline'; nothing */2839break;2840*old++ ='\n';2841strbuf_addch(&newlines,'\n');2842add_line_info(&preimage,"\n",1, LINE_COMMON);2843add_line_info(&postimage,"\n",1, LINE_COMMON);2844 is_blank_context =1;2845break;2846case' ':2847if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2848ws_blank_line(patch +1, plen, ws_rule))2849 is_blank_context =1;2850case'-':2851memcpy(old, patch +1, plen);2852add_line_info(&preimage, old, plen,2853(first ==' '? LINE_COMMON :0));2854 old += plen;2855if(first =='-')2856break;2857/* Fall-through for ' ' */2858case'+':2859/* --no-add does not add new lines */2860if(first =='+'&& state->no_add)2861break;28622863 start = newlines.len;2864if(first !='+'||2865!state->whitespace_error ||2866 state->ws_error_action != correct_ws_error) {2867strbuf_add(&newlines, patch +1, plen);2868}2869else{2870ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2871}2872add_line_info(&postimage, newlines.buf + start, newlines.len - start,2873(first =='+'?0: LINE_COMMON));2874if(first =='+'&&2875(ws_rule & WS_BLANK_AT_EOF) &&2876ws_blank_line(patch +1, plen, ws_rule))2877 added_blank_line =1;2878break;2879case'@':case'\\':2880/* Ignore it, we already handled it */2881break;2882default:2883if(state->apply_verbosely)2884error(_("invalid start of line: '%c'"), first);2885 applied_pos = -1;2886goto out;2887}2888if(added_blank_line) {2889if(!new_blank_lines_at_end)2890 found_new_blank_lines_at_end = hunk_linenr;2891 new_blank_lines_at_end++;2892}2893else if(is_blank_context)2894;2895else2896 new_blank_lines_at_end =0;2897 patch += len;2898 size -= len;2899 hunk_linenr++;2900}2901if(inaccurate_eof &&2902 old > oldlines && old[-1] =='\n'&&2903 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2904 old--;2905strbuf_setlen(&newlines, newlines.len -1);2906}29072908 leading = frag->leading;2909 trailing = frag->trailing;29102911/*2912 * A hunk to change lines at the beginning would begin with2913 * @@ -1,L +N,M @@2914 * but we need to be careful. -U0 that inserts before the second2915 * line also has this pattern.2916 *2917 * And a hunk to add to an empty file would begin with2918 * @@ -0,0 +N,M @@2919 *2920 * In other words, a hunk that is (frag->oldpos <= 1) with or2921 * without leading context must match at the beginning.2922 */2923 match_beginning = (!frag->oldpos ||2924(frag->oldpos ==1&& !state->unidiff_zero));29252926/*2927 * A hunk without trailing lines must match at the end.2928 * However, we simply cannot tell if a hunk must match end2929 * from the lack of trailing lines if the patch was generated2930 * with unidiff without any context.2931 */2932 match_end = !state->unidiff_zero && !trailing;29332934 pos = frag->newpos ? (frag->newpos -1) :0;2935 preimage.buf = oldlines;2936 preimage.len = old - oldlines;2937 postimage.buf = newlines.buf;2938 postimage.len = newlines.len;2939 preimage.line = preimage.line_allocated;2940 postimage.line = postimage.line_allocated;29412942for(;;) {29432944 applied_pos =find_pos(state, img, &preimage, &postimage, pos,2945 ws_rule, match_beginning, match_end);29462947if(applied_pos >=0)2948break;29492950/* Am I at my context limits? */2951if((leading <= state->p_context) && (trailing <= state->p_context))2952break;2953if(match_beginning || match_end) {2954 match_beginning = match_end =0;2955continue;2956}29572958/*2959 * Reduce the number of context lines; reduce both2960 * leading and trailing if they are equal otherwise2961 * just reduce the larger context.2962 */2963if(leading >= trailing) {2964remove_first_line(&preimage);2965remove_first_line(&postimage);2966 pos--;2967 leading--;2968}2969if(trailing > leading) {2970remove_last_line(&preimage);2971remove_last_line(&postimage);2972 trailing--;2973}2974}29752976if(applied_pos >=0) {2977if(new_blank_lines_at_end &&2978 preimage.nr + applied_pos >= img->nr &&2979(ws_rule & WS_BLANK_AT_EOF) &&2980 state->ws_error_action != nowarn_ws_error) {2981record_ws_error(state, WS_BLANK_AT_EOF,"+",1,2982 found_new_blank_lines_at_end);2983if(state->ws_error_action == correct_ws_error) {2984while(new_blank_lines_at_end--)2985remove_last_line(&postimage);2986}2987/*2988 * We would want to prevent write_out_results()2989 * from taking place in apply_patch() that follows2990 * the callchain led us here, which is:2991 * apply_patch->check_patch_list->check_patch->2992 * apply_data->apply_fragments->apply_one_fragment2993 */2994if(state->ws_error_action == die_on_ws_error)2995 state->apply =0;2996}29972998if(state->apply_verbosely && applied_pos != pos) {2999int offset = applied_pos - pos;3000if(state->apply_in_reverse)3001 offset =0- offset;3002fprintf_ln(stderr,3003Q_("Hunk #%dsucceeded at%d(offset%dline).",3004"Hunk #%dsucceeded at%d(offset%dlines).",3005 offset),3006 nth_fragment, applied_pos +1, offset);3007}30083009/*3010 * Warn if it was necessary to reduce the number3011 * of context lines.3012 */3013if((leading != frag->leading) ||3014(trailing != frag->trailing))3015fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"3016" to apply fragment at%d"),3017 leading, trailing, applied_pos+1);3018update_image(state, img, applied_pos, &preimage, &postimage);3019}else{3020if(state->apply_verbosely)3021error(_("while searching for:\n%.*s"),3022(int)(old - oldlines), oldlines);3023}30243025out:3026free(oldlines);3027strbuf_release(&newlines);3028free(preimage.line_allocated);3029free(postimage.line_allocated);30303031return(applied_pos <0);3032}30333034static intapply_binary_fragment(struct apply_state *state,3035struct image *img,3036struct patch *patch)3037{3038struct fragment *fragment = patch->fragments;3039unsigned long len;3040void*dst;30413042if(!fragment)3043returnerror(_("missing binary patch data for '%s'"),3044 patch->new_name ?3045 patch->new_name :3046 patch->old_name);30473048/* Binary patch is irreversible without the optional second hunk */3049if(state->apply_in_reverse) {3050if(!fragment->next)3051returnerror("cannot reverse-apply a binary patch "3052"without the reverse hunk to '%s'",3053 patch->new_name3054? patch->new_name : patch->old_name);3055 fragment = fragment->next;3056}3057switch(fragment->binary_patch_method) {3058case BINARY_DELTA_DEFLATED:3059 dst =patch_delta(img->buf, img->len, fragment->patch,3060 fragment->size, &len);3061if(!dst)3062return-1;3063clear_image(img);3064 img->buf = dst;3065 img->len = len;3066return0;3067case BINARY_LITERAL_DEFLATED:3068clear_image(img);3069 img->len = fragment->size;3070 img->buf =xmemdupz(fragment->patch, img->len);3071return0;3072}3073return-1;3074}30753076/*3077 * Replace "img" with the result of applying the binary patch.3078 * The binary patch data itself in patch->fragment is still kept3079 * but the preimage prepared by the caller in "img" is freed here3080 * or in the helper function apply_binary_fragment() this calls.3081 */3082static intapply_binary(struct apply_state *state,3083struct image *img,3084struct patch *patch)3085{3086const char*name = patch->old_name ? patch->old_name : patch->new_name;3087unsigned char sha1[20];30883089/*3090 * For safety, we require patch index line to contain3091 * full 40-byte textual SHA1 for old and new, at least for now.3092 */3093if(strlen(patch->old_sha1_prefix) !=40||3094strlen(patch->new_sha1_prefix) !=40||3095get_sha1_hex(patch->old_sha1_prefix, sha1) ||3096get_sha1_hex(patch->new_sha1_prefix, sha1))3097returnerror("cannot apply binary patch to '%s' "3098"without full index line", name);30993100if(patch->old_name) {3101/*3102 * See if the old one matches what the patch3103 * applies to.3104 */3105hash_sha1_file(img->buf, img->len, blob_type, sha1);3106if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3107returnerror("the patch applies to '%s' (%s), "3108"which does not match the "3109"current contents.",3110 name,sha1_to_hex(sha1));3111}3112else{3113/* Otherwise, the old one must be empty. */3114if(img->len)3115returnerror("the patch applies to an empty "3116"'%s' but it is not empty", name);3117}31183119get_sha1_hex(patch->new_sha1_prefix, sha1);3120if(is_null_sha1(sha1)) {3121clear_image(img);3122return0;/* deletion patch */3123}31243125if(has_sha1_file(sha1)) {3126/* We already have the postimage */3127enum object_type type;3128unsigned long size;3129char*result;31303131 result =read_sha1_file(sha1, &type, &size);3132if(!result)3133returnerror("the necessary postimage%sfor "3134"'%s' cannot be read",3135 patch->new_sha1_prefix, name);3136clear_image(img);3137 img->buf = result;3138 img->len = size;3139}else{3140/*3141 * We have verified buf matches the preimage;3142 * apply the patch data to it, which is stored3143 * in the patch->fragments->{patch,size}.3144 */3145if(apply_binary_fragment(state, img, patch))3146returnerror(_("binary patch does not apply to '%s'"),3147 name);31483149/* verify that the result matches */3150hash_sha1_file(img->buf, img->len, blob_type, sha1);3151if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3152returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3153 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3154}31553156return0;3157}31583159static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3160{3161struct fragment *frag = patch->fragments;3162const char*name = patch->old_name ? patch->old_name : patch->new_name;3163unsigned ws_rule = patch->ws_rule;3164unsigned inaccurate_eof = patch->inaccurate_eof;3165int nth =0;31663167if(patch->is_binary)3168returnapply_binary(state, img, patch);31693170while(frag) {3171 nth++;3172if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3173error(_("patch failed:%s:%ld"), name, frag->oldpos);3174if(!state->apply_with_reject)3175return-1;3176 frag->rejected =1;3177}3178 frag = frag->next;3179}3180return0;3181}31823183static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3184{3185if(S_ISGITLINK(mode)) {3186strbuf_grow(buf,100);3187strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3188}else{3189enum object_type type;3190unsigned long sz;3191char*result;31923193 result =read_sha1_file(sha1, &type, &sz);3194if(!result)3195return-1;3196/* XXX read_sha1_file NUL-terminates */3197strbuf_attach(buf, result, sz, sz +1);3198}3199return0;3200}32013202static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3203{3204if(!ce)3205return0;3206returnread_blob_object(buf, ce->sha1, ce->ce_mode);3207}32083209static struct patch *in_fn_table(const char*name)3210{3211struct string_list_item *item;32123213if(name == NULL)3214return NULL;32153216 item =string_list_lookup(&fn_table, name);3217if(item != NULL)3218return(struct patch *)item->util;32193220return NULL;3221}32223223/*3224 * item->util in the filename table records the status of the path.3225 * Usually it points at a patch (whose result records the contents3226 * of it after applying it), but it could be PATH_WAS_DELETED for a3227 * path that a previously applied patch has already removed, or3228 * PATH_TO_BE_DELETED for a path that a later patch would remove.3229 *3230 * The latter is needed to deal with a case where two paths A and B3231 * are swapped by first renaming A to B and then renaming B to A;3232 * moving A to B should not be prevented due to presence of B as we3233 * will remove it in a later patch.3234 */3235#define PATH_TO_BE_DELETED ((struct patch *) -2)3236#define PATH_WAS_DELETED ((struct patch *) -1)32373238static intto_be_deleted(struct patch *patch)3239{3240return patch == PATH_TO_BE_DELETED;3241}32423243static intwas_deleted(struct patch *patch)3244{3245return patch == PATH_WAS_DELETED;3246}32473248static voidadd_to_fn_table(struct patch *patch)3249{3250struct string_list_item *item;32513252/*3253 * Always add new_name unless patch is a deletion3254 * This should cover the cases for normal diffs,3255 * file creations and copies3256 */3257if(patch->new_name != NULL) {3258 item =string_list_insert(&fn_table, patch->new_name);3259 item->util = patch;3260}32613262/*3263 * store a failure on rename/deletion cases because3264 * later chunks shouldn't patch old names3265 */3266if((patch->new_name == NULL) || (patch->is_rename)) {3267 item =string_list_insert(&fn_table, patch->old_name);3268 item->util = PATH_WAS_DELETED;3269}3270}32713272static voidprepare_fn_table(struct patch *patch)3273{3274/*3275 * store information about incoming file deletion3276 */3277while(patch) {3278if((patch->new_name == NULL) || (patch->is_rename)) {3279struct string_list_item *item;3280 item =string_list_insert(&fn_table, patch->old_name);3281 item->util = PATH_TO_BE_DELETED;3282}3283 patch = patch->next;3284}3285}32863287static intcheckout_target(struct index_state *istate,3288struct cache_entry *ce,struct stat *st)3289{3290struct checkout costate;32913292memset(&costate,0,sizeof(costate));3293 costate.base_dir ="";3294 costate.refresh_cache =1;3295 costate.istate = istate;3296if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3297returnerror(_("cannot checkout%s"), ce->name);3298return0;3299}33003301static struct patch *previous_patch(struct patch *patch,int*gone)3302{3303struct patch *previous;33043305*gone =0;3306if(patch->is_copy || patch->is_rename)3307return NULL;/* "git" patches do not depend on the order */33083309 previous =in_fn_table(patch->old_name);3310if(!previous)3311return NULL;33123313if(to_be_deleted(previous))3314return NULL;/* the deletion hasn't happened yet */33153316if(was_deleted(previous))3317*gone =1;33183319return previous;3320}33213322static intverify_index_match(const struct cache_entry *ce,struct stat *st)3323{3324if(S_ISGITLINK(ce->ce_mode)) {3325if(!S_ISDIR(st->st_mode))3326return-1;3327return0;3328}3329returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3330}33313332#define SUBMODULE_PATCH_WITHOUT_INDEX 133333334static intload_patch_target(struct apply_state *state,3335struct strbuf *buf,3336const struct cache_entry *ce,3337struct stat *st,3338const char*name,3339unsigned expected_mode)3340{3341if(state->cached || state->check_index) {3342if(read_file_or_gitlink(ce, buf))3343returnerror(_("read of%sfailed"), name);3344}else if(name) {3345if(S_ISGITLINK(expected_mode)) {3346if(ce)3347returnread_file_or_gitlink(ce, buf);3348else3349return SUBMODULE_PATCH_WITHOUT_INDEX;3350}else if(has_symlink_leading_path(name,strlen(name))) {3351returnerror(_("reading from '%s' beyond a symbolic link"), name);3352}else{3353if(read_old_data(st, name, buf))3354returnerror(_("read of%sfailed"), name);3355}3356}3357return0;3358}33593360/*3361 * We are about to apply "patch"; populate the "image" with the3362 * current version we have, from the working tree or from the index,3363 * depending on the situation e.g. --cached/--index. If we are3364 * applying a non-git patch that incrementally updates the tree,3365 * we read from the result of a previous diff.3366 */3367static intload_preimage(struct apply_state *state,3368struct image *image,3369struct patch *patch,struct stat *st,3370const struct cache_entry *ce)3371{3372struct strbuf buf = STRBUF_INIT;3373size_t len;3374char*img;3375struct patch *previous;3376int status;33773378 previous =previous_patch(patch, &status);3379if(status)3380returnerror(_("path%shas been renamed/deleted"),3381 patch->old_name);3382if(previous) {3383/* We have a patched copy in memory; use that. */3384strbuf_add(&buf, previous->result, previous->resultsize);3385}else{3386 status =load_patch_target(state, &buf, ce, st,3387 patch->old_name, patch->old_mode);3388if(status <0)3389return status;3390else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3391/*3392 * There is no way to apply subproject3393 * patch without looking at the index.3394 * NEEDSWORK: shouldn't this be flagged3395 * as an error???3396 */3397free_fragment_list(patch->fragments);3398 patch->fragments = NULL;3399}else if(status) {3400returnerror(_("read of%sfailed"), patch->old_name);3401}3402}34033404 img =strbuf_detach(&buf, &len);3405prepare_image(image, img, len, !patch->is_binary);3406return0;3407}34083409static intthree_way_merge(struct image *image,3410char*path,3411const unsigned char*base,3412const unsigned char*ours,3413const unsigned char*theirs)3414{3415 mmfile_t base_file, our_file, their_file;3416 mmbuffer_t result = { NULL };3417int status;34183419read_mmblob(&base_file, base);3420read_mmblob(&our_file, ours);3421read_mmblob(&their_file, theirs);3422 status =ll_merge(&result, path,3423&base_file,"base",3424&our_file,"ours",3425&their_file,"theirs", NULL);3426free(base_file.ptr);3427free(our_file.ptr);3428free(their_file.ptr);3429if(status <0|| !result.ptr) {3430free(result.ptr);3431return-1;3432}3433clear_image(image);3434 image->buf = result.ptr;3435 image->len = result.size;34363437return status;3438}34393440/*3441 * When directly falling back to add/add three-way merge, we read from3442 * the current contents of the new_name. In no cases other than that3443 * this function will be called.3444 */3445static intload_current(struct apply_state *state,3446struct image *image,3447struct patch *patch)3448{3449struct strbuf buf = STRBUF_INIT;3450int status, pos;3451size_t len;3452char*img;3453struct stat st;3454struct cache_entry *ce;3455char*name = patch->new_name;3456unsigned mode = patch->new_mode;34573458if(!patch->is_new)3459die("BUG: patch to%sis not a creation", patch->old_name);34603461 pos =cache_name_pos(name,strlen(name));3462if(pos <0)3463returnerror(_("%s: does not exist in index"), name);3464 ce = active_cache[pos];3465if(lstat(name, &st)) {3466if(errno != ENOENT)3467returnerror(_("%s:%s"), name,strerror(errno));3468if(checkout_target(&the_index, ce, &st))3469return-1;3470}3471if(verify_index_match(ce, &st))3472returnerror(_("%s: does not match index"), name);34733474 status =load_patch_target(state, &buf, ce, &st, name, mode);3475if(status <0)3476return status;3477else if(status)3478return-1;3479 img =strbuf_detach(&buf, &len);3480prepare_image(image, img, len, !patch->is_binary);3481return0;3482}34833484static inttry_threeway(struct apply_state *state,3485struct image *image,3486struct patch *patch,3487struct stat *st,3488const struct cache_entry *ce)3489{3490unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3491struct strbuf buf = STRBUF_INIT;3492size_t len;3493int status;3494char*img;3495struct image tmp_image;34963497/* No point falling back to 3-way merge in these cases */3498if(patch->is_delete ||3499S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3500return-1;35013502/* Preimage the patch was prepared for */3503if(patch->is_new)3504write_sha1_file("",0, blob_type, pre_sha1);3505else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3506read_blob_object(&buf, pre_sha1, patch->old_mode))3507returnerror("repository lacks the necessary blob to fall back on 3-way merge.");35083509fprintf(stderr,"Falling back to three-way merge...\n");35103511 img =strbuf_detach(&buf, &len);3512prepare_image(&tmp_image, img, len,1);3513/* Apply the patch to get the post image */3514if(apply_fragments(state, &tmp_image, patch) <0) {3515clear_image(&tmp_image);3516return-1;3517}3518/* post_sha1[] is theirs */3519write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3520clear_image(&tmp_image);35213522/* our_sha1[] is ours */3523if(patch->is_new) {3524if(load_current(state, &tmp_image, patch))3525returnerror("cannot read the current contents of '%s'",3526 patch->new_name);3527}else{3528if(load_preimage(state, &tmp_image, patch, st, ce))3529returnerror("cannot read the current contents of '%s'",3530 patch->old_name);3531}3532write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3533clear_image(&tmp_image);35343535/* in-core three-way merge between post and our using pre as base */3536 status =three_way_merge(image, patch->new_name,3537 pre_sha1, our_sha1, post_sha1);3538if(status <0) {3539fprintf(stderr,"Failed to fall back on three-way merge...\n");3540return status;3541}35423543if(status) {3544 patch->conflicted_threeway =1;3545if(patch->is_new)3546oidclr(&patch->threeway_stage[0]);3547else3548hashcpy(patch->threeway_stage[0].hash, pre_sha1);3549hashcpy(patch->threeway_stage[1].hash, our_sha1);3550hashcpy(patch->threeway_stage[2].hash, post_sha1);3551fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3552}else{3553fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3554}3555return0;3556}35573558static intapply_data(struct apply_state *state,struct patch *patch,3559struct stat *st,const struct cache_entry *ce)3560{3561struct image image;35623563if(load_preimage(state, &image, patch, st, ce) <0)3564return-1;35653566if(patch->direct_to_threeway ||3567apply_fragments(state, &image, patch) <0) {3568/* Note: with --reject, apply_fragments() returns 0 */3569if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3570return-1;3571}3572 patch->result = image.buf;3573 patch->resultsize = image.len;3574add_to_fn_table(patch);3575free(image.line_allocated);35763577if(0< patch->is_delete && patch->resultsize)3578returnerror(_("removal patch leaves file contents"));35793580return0;3581}35823583/*3584 * If "patch" that we are looking at modifies or deletes what we have,3585 * we would want it not to lose any local modification we have, either3586 * in the working tree or in the index.3587 *3588 * This also decides if a non-git patch is a creation patch or a3589 * modification to an existing empty file. We do not check the state3590 * of the current tree for a creation patch in this function; the caller3591 * check_patch() separately makes sure (and errors out otherwise) that3592 * the path the patch creates does not exist in the current tree.3593 */3594static intcheck_preimage(struct apply_state *state,3595struct patch *patch,3596struct cache_entry **ce,3597struct stat *st)3598{3599const char*old_name = patch->old_name;3600struct patch *previous = NULL;3601int stat_ret =0, status;3602unsigned st_mode =0;36033604if(!old_name)3605return0;36063607assert(patch->is_new <=0);3608 previous =previous_patch(patch, &status);36093610if(status)3611returnerror(_("path%shas been renamed/deleted"), old_name);3612if(previous) {3613 st_mode = previous->new_mode;3614}else if(!state->cached) {3615 stat_ret =lstat(old_name, st);3616if(stat_ret && errno != ENOENT)3617returnerror(_("%s:%s"), old_name,strerror(errno));3618}36193620if(state->check_index && !previous) {3621int pos =cache_name_pos(old_name,strlen(old_name));3622if(pos <0) {3623if(patch->is_new <0)3624goto is_new;3625returnerror(_("%s: does not exist in index"), old_name);3626}3627*ce = active_cache[pos];3628if(stat_ret <0) {3629if(checkout_target(&the_index, *ce, st))3630return-1;3631}3632if(!state->cached &&verify_index_match(*ce, st))3633returnerror(_("%s: does not match index"), old_name);3634if(state->cached)3635 st_mode = (*ce)->ce_mode;3636}else if(stat_ret <0) {3637if(patch->is_new <0)3638goto is_new;3639returnerror(_("%s:%s"), old_name,strerror(errno));3640}36413642if(!state->cached && !previous)3643 st_mode =ce_mode_from_stat(*ce, st->st_mode);36443645if(patch->is_new <0)3646 patch->is_new =0;3647if(!patch->old_mode)3648 patch->old_mode = st_mode;3649if((st_mode ^ patch->old_mode) & S_IFMT)3650returnerror(_("%s: wrong type"), old_name);3651if(st_mode != patch->old_mode)3652warning(_("%shas type%o, expected%o"),3653 old_name, st_mode, patch->old_mode);3654if(!patch->new_mode && !patch->is_delete)3655 patch->new_mode = st_mode;3656return0;36573658 is_new:3659 patch->is_new =1;3660 patch->is_delete =0;3661free(patch->old_name);3662 patch->old_name = NULL;3663return0;3664}366536663667#define EXISTS_IN_INDEX 13668#define EXISTS_IN_WORKTREE 236693670static intcheck_to_create(struct apply_state *state,3671const char*new_name,3672int ok_if_exists)3673{3674struct stat nst;36753676if(state->check_index &&3677cache_name_pos(new_name,strlen(new_name)) >=0&&3678!ok_if_exists)3679return EXISTS_IN_INDEX;3680if(state->cached)3681return0;36823683if(!lstat(new_name, &nst)) {3684if(S_ISDIR(nst.st_mode) || ok_if_exists)3685return0;3686/*3687 * A leading component of new_name might be a symlink3688 * that is going to be removed with this patch, but3689 * still pointing at somewhere that has the path.3690 * In such a case, path "new_name" does not exist as3691 * far as git is concerned.3692 */3693if(has_symlink_leading_path(new_name,strlen(new_name)))3694return0;36953696return EXISTS_IN_WORKTREE;3697}else if((errno != ENOENT) && (errno != ENOTDIR)) {3698returnerror("%s:%s", new_name,strerror(errno));3699}3700return0;3701}37023703/*3704 * We need to keep track of how symlinks in the preimage are3705 * manipulated by the patches. A patch to add a/b/c where a/b3706 * is a symlink should not be allowed to affect the directory3707 * the symlink points at, but if the same patch removes a/b,3708 * it is perfectly fine, as the patch removes a/b to make room3709 * to create a directory a/b so that a/b/c can be created.3710 */3711static struct string_list symlink_changes;3712#define SYMLINK_GOES_AWAY 013713#define SYMLINK_IN_RESULT 0237143715static uintptr_tregister_symlink_changes(const char*path,uintptr_t what)3716{3717struct string_list_item *ent;37183719 ent =string_list_lookup(&symlink_changes, path);3720if(!ent) {3721 ent =string_list_insert(&symlink_changes, path);3722 ent->util = (void*)0;3723}3724 ent->util = (void*)(what | ((uintptr_t)ent->util));3725return(uintptr_t)ent->util;3726}37273728static uintptr_tcheck_symlink_changes(const char*path)3729{3730struct string_list_item *ent;37313732 ent =string_list_lookup(&symlink_changes, path);3733if(!ent)3734return0;3735return(uintptr_t)ent->util;3736}37373738static voidprepare_symlink_changes(struct patch *patch)3739{3740for( ; patch; patch = patch->next) {3741if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3742(patch->is_rename || patch->is_delete))3743/* the symlink at patch->old_name is removed */3744register_symlink_changes(patch->old_name, SYMLINK_GOES_AWAY);37453746if(patch->new_name &&S_ISLNK(patch->new_mode))3747/* the symlink at patch->new_name is created or remains */3748register_symlink_changes(patch->new_name, SYMLINK_IN_RESULT);3749}3750}37513752static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3753{3754do{3755unsigned int change;37563757while(--name->len && name->buf[name->len] !='/')3758;/* scan backwards */3759if(!name->len)3760break;3761 name->buf[name->len] ='\0';3762 change =check_symlink_changes(name->buf);3763if(change & SYMLINK_IN_RESULT)3764return1;3765if(change & SYMLINK_GOES_AWAY)3766/*3767 * This cannot be "return 0", because we may3768 * see a new one created at a higher level.3769 */3770continue;37713772/* otherwise, check the preimage */3773if(state->check_index) {3774struct cache_entry *ce;37753776 ce =cache_file_exists(name->buf, name->len, ignore_case);3777if(ce &&S_ISLNK(ce->ce_mode))3778return1;3779}else{3780struct stat st;3781if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3782return1;3783}3784}while(1);3785return0;3786}37873788static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3789{3790int ret;3791struct strbuf name = STRBUF_INIT;37923793assert(*name_ !='\0');3794strbuf_addstr(&name, name_);3795 ret =path_is_beyond_symlink_1(state, &name);3796strbuf_release(&name);37973798return ret;3799}38003801static voiddie_on_unsafe_path(struct patch *patch)3802{3803const char*old_name = NULL;3804const char*new_name = NULL;3805if(patch->is_delete)3806 old_name = patch->old_name;3807else if(!patch->is_new && !patch->is_copy)3808 old_name = patch->old_name;3809if(!patch->is_delete)3810 new_name = patch->new_name;38113812if(old_name && !verify_path(old_name))3813die(_("invalid path '%s'"), old_name);3814if(new_name && !verify_path(new_name))3815die(_("invalid path '%s'"), new_name);3816}38173818/*3819 * Check and apply the patch in-core; leave the result in patch->result3820 * for the caller to write it out to the final destination.3821 */3822static intcheck_patch(struct apply_state *state,struct patch *patch)3823{3824struct stat st;3825const char*old_name = patch->old_name;3826const char*new_name = patch->new_name;3827const char*name = old_name ? old_name : new_name;3828struct cache_entry *ce = NULL;3829struct patch *tpatch;3830int ok_if_exists;3831int status;38323833 patch->rejected =1;/* we will drop this after we succeed */38343835 status =check_preimage(state, patch, &ce, &st);3836if(status)3837return status;3838 old_name = patch->old_name;38393840/*3841 * A type-change diff is always split into a patch to delete3842 * old, immediately followed by a patch to create new (see3843 * diff.c::run_diff()); in such a case it is Ok that the entry3844 * to be deleted by the previous patch is still in the working3845 * tree and in the index.3846 *3847 * A patch to swap-rename between A and B would first rename A3848 * to B and then rename B to A. While applying the first one,3849 * the presence of B should not stop A from getting renamed to3850 * B; ask to_be_deleted() about the later rename. Removal of3851 * B and rename from A to B is handled the same way by asking3852 * was_deleted().3853 */3854if((tpatch =in_fn_table(new_name)) &&3855(was_deleted(tpatch) ||to_be_deleted(tpatch)))3856 ok_if_exists =1;3857else3858 ok_if_exists =0;38593860if(new_name &&3861((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3862int err =check_to_create(state, new_name, ok_if_exists);38633864if(err && state->threeway) {3865 patch->direct_to_threeway =1;3866}else switch(err) {3867case0:3868break;/* happy */3869case EXISTS_IN_INDEX:3870returnerror(_("%s: already exists in index"), new_name);3871break;3872case EXISTS_IN_WORKTREE:3873returnerror(_("%s: already exists in working directory"),3874 new_name);3875default:3876return err;3877}38783879if(!patch->new_mode) {3880if(0< patch->is_new)3881 patch->new_mode = S_IFREG |0644;3882else3883 patch->new_mode = patch->old_mode;3884}3885}38863887if(new_name && old_name) {3888int same = !strcmp(old_name, new_name);3889if(!patch->new_mode)3890 patch->new_mode = patch->old_mode;3891if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3892if(same)3893returnerror(_("new mode (%o) of%sdoes not "3894"match old mode (%o)"),3895 patch->new_mode, new_name,3896 patch->old_mode);3897else3898returnerror(_("new mode (%o) of%sdoes not "3899"match old mode (%o) of%s"),3900 patch->new_mode, new_name,3901 patch->old_mode, old_name);3902}3903}39043905if(!state->unsafe_paths)3906die_on_unsafe_path(patch);39073908/*3909 * An attempt to read from or delete a path that is beyond a3910 * symbolic link will be prevented by load_patch_target() that3911 * is called at the beginning of apply_data() so we do not3912 * have to worry about a patch marked with "is_delete" bit3913 * here. We however need to make sure that the patch result3914 * is not deposited to a path that is beyond a symbolic link3915 * here.3916 */3917if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3918returnerror(_("affected file '%s' is beyond a symbolic link"),3919 patch->new_name);39203921if(apply_data(state, patch, &st, ce) <0)3922returnerror(_("%s: patch does not apply"), name);3923 patch->rejected =0;3924return0;3925}39263927static intcheck_patch_list(struct apply_state *state,struct patch *patch)3928{3929int err =0;39303931prepare_symlink_changes(patch);3932prepare_fn_table(patch);3933while(patch) {3934if(state->apply_verbosely)3935say_patch_name(stderr,3936_("Checking patch%s..."), patch);3937 err |=check_patch(state, patch);3938 patch = patch->next;3939}3940return err;3941}39423943/* This function tries to read the sha1 from the current index */3944static intget_current_sha1(const char*path,unsigned char*sha1)3945{3946int pos;39473948if(read_cache() <0)3949return-1;3950 pos =cache_name_pos(path,strlen(path));3951if(pos <0)3952return-1;3953hashcpy(sha1, active_cache[pos]->sha1);3954return0;3955}39563957static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3958{3959/*3960 * A usable gitlink patch has only one fragment (hunk) that looks like:3961 * @@ -1 +1 @@3962 * -Subproject commit <old sha1>3963 * +Subproject commit <new sha1>3964 * or3965 * @@ -1 +0,0 @@3966 * -Subproject commit <old sha1>3967 * for a removal patch.3968 */3969struct fragment *hunk = p->fragments;3970static const char heading[] ="-Subproject commit ";3971char*preimage;39723973if(/* does the patch have only one hunk? */3974 hunk && !hunk->next &&3975/* is its preimage one line? */3976 hunk->oldpos ==1&& hunk->oldlines ==1&&3977/* does preimage begin with the heading? */3978(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3979starts_with(++preimage, heading) &&3980/* does it record full SHA-1? */3981!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3982 preimage[sizeof(heading) +40-1] =='\n'&&3983/* does the abbreviated name on the index line agree with it? */3984starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3985return0;/* it all looks fine */39863987/* we may have full object name on the index line */3988returnget_sha1_hex(p->old_sha1_prefix, sha1);3989}39903991/* Build an index that contains the just the files needed for a 3way merge */3992static voidbuild_fake_ancestor(struct patch *list,const char*filename)3993{3994struct patch *patch;3995struct index_state result = { NULL };3996static struct lock_file lock;39973998/* Once we start supporting the reverse patch, it may be3999 * worth showing the new sha1 prefix, but until then...4000 */4001for(patch = list; patch; patch = patch->next) {4002unsigned char sha1[20];4003struct cache_entry *ce;4004const char*name;40054006 name = patch->old_name ? patch->old_name : patch->new_name;4007if(0< patch->is_new)4008continue;40094010if(S_ISGITLINK(patch->old_mode)) {4011if(!preimage_sha1_in_gitlink_patch(patch, sha1))4012;/* ok, the textual part looks sane */4013else4014die("sha1 information is lacking or useless for submodule%s",4015 name);4016}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {4017;/* ok */4018}else if(!patch->lines_added && !patch->lines_deleted) {4019/* mode-only change: update the current */4020if(get_current_sha1(patch->old_name, sha1))4021die("mode change for%s, which is not "4022"in current HEAD", name);4023}else4024die("sha1 information is lacking or useless "4025"(%s).", name);40264027 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);4028if(!ce)4029die(_("make_cache_entry failed for path '%s'"), name);4030if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))4031die("Could not add%sto temporary index", name);4032}40334034hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);4035if(write_locked_index(&result, &lock, COMMIT_LOCK))4036die("Could not write temporary index to%s", filename);40374038discard_index(&result);4039}40404041static voidstat_patch_list(struct patch *patch)4042{4043int files, adds, dels;40444045for(files = adds = dels =0; patch ; patch = patch->next) {4046 files++;4047 adds += patch->lines_added;4048 dels += patch->lines_deleted;4049show_stats(patch);4050}40514052print_stat_summary(stdout, files, adds, dels);4053}40544055static voidnumstat_patch_list(struct apply_state *state,4056struct patch *patch)4057{4058for( ; patch; patch = patch->next) {4059const char*name;4060 name = patch->new_name ? patch->new_name : patch->old_name;4061if(patch->is_binary)4062printf("-\t-\t");4063else4064printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4065write_name_quoted(name, stdout, state->line_termination);4066}4067}40684069static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4070{4071if(mode)4072printf("%smode%06o%s\n", newdelete, mode, name);4073else4074printf("%s %s\n", newdelete, name);4075}40764077static voidshow_mode_change(struct patch *p,int show_name)4078{4079if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4080if(show_name)4081printf(" mode change%06o =>%06o%s\n",4082 p->old_mode, p->new_mode, p->new_name);4083else4084printf(" mode change%06o =>%06o\n",4085 p->old_mode, p->new_mode);4086}4087}40884089static voidshow_rename_copy(struct patch *p)4090{4091const char*renamecopy = p->is_rename ?"rename":"copy";4092const char*old, *new;40934094/* Find common prefix */4095 old = p->old_name;4096new= p->new_name;4097while(1) {4098const char*slash_old, *slash_new;4099 slash_old =strchr(old,'/');4100 slash_new =strchr(new,'/');4101if(!slash_old ||4102!slash_new ||4103 slash_old - old != slash_new -new||4104memcmp(old,new, slash_new -new))4105break;4106 old = slash_old +1;4107new= slash_new +1;4108}4109/* p->old_name thru old is the common prefix, and old and new4110 * through the end of names are renames4111 */4112if(old != p->old_name)4113printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4114(int)(old - p->old_name), p->old_name,4115 old,new, p->score);4116else4117printf("%s %s=>%s(%d%%)\n", renamecopy,4118 p->old_name, p->new_name, p->score);4119show_mode_change(p,0);4120}41214122static voidsummary_patch_list(struct patch *patch)4123{4124struct patch *p;41254126for(p = patch; p; p = p->next) {4127if(p->is_new)4128show_file_mode_name("create", p->new_mode, p->new_name);4129else if(p->is_delete)4130show_file_mode_name("delete", p->old_mode, p->old_name);4131else{4132if(p->is_rename || p->is_copy)4133show_rename_copy(p);4134else{4135if(p->score) {4136printf(" rewrite%s(%d%%)\n",4137 p->new_name, p->score);4138show_mode_change(p,0);4139}4140else4141show_mode_change(p,1);4142}4143}4144}4145}41464147static voidpatch_stats(struct patch *patch)4148{4149int lines = patch->lines_added + patch->lines_deleted;41504151if(lines > max_change)4152 max_change = lines;4153if(patch->old_name) {4154int len =quote_c_style(patch->old_name, NULL, NULL,0);4155if(!len)4156 len =strlen(patch->old_name);4157if(len > max_len)4158 max_len = len;4159}4160if(patch->new_name) {4161int len =quote_c_style(patch->new_name, NULL, NULL,0);4162if(!len)4163 len =strlen(patch->new_name);4164if(len > max_len)4165 max_len = len;4166}4167}41684169static voidremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4170{4171if(state->update_index) {4172if(remove_file_from_cache(patch->old_name) <0)4173die(_("unable to remove%sfrom index"), patch->old_name);4174}4175if(!state->cached) {4176if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4177remove_path(patch->old_name);4178}4179}4180}41814182static voidadd_index_file(struct apply_state *state,4183const char*path,4184unsigned mode,4185void*buf,4186unsigned long size)4187{4188struct stat st;4189struct cache_entry *ce;4190int namelen =strlen(path);4191unsigned ce_size =cache_entry_size(namelen);41924193if(!state->update_index)4194return;41954196 ce =xcalloc(1, ce_size);4197memcpy(ce->name, path, namelen);4198 ce->ce_mode =create_ce_mode(mode);4199 ce->ce_flags =create_ce_flags(0);4200 ce->ce_namelen = namelen;4201if(S_ISGITLINK(mode)) {4202const char*s;42034204if(!skip_prefix(buf,"Subproject commit ", &s) ||4205get_sha1_hex(s, ce->sha1))4206die(_("corrupt patch for submodule%s"), path);4207}else{4208if(!state->cached) {4209if(lstat(path, &st) <0)4210die_errno(_("unable to stat newly created file '%s'"),4211 path);4212fill_stat_cache_info(ce, &st);4213}4214if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4215die(_("unable to create backing store for newly created file%s"), path);4216}4217if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4218die(_("unable to add cache entry for%s"), path);4219}42204221static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4222{4223int fd;4224struct strbuf nbuf = STRBUF_INIT;42254226if(S_ISGITLINK(mode)) {4227struct stat st;4228if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4229return0;4230returnmkdir(path,0777);4231}42324233if(has_symlinks &&S_ISLNK(mode))4234/* Although buf:size is counted string, it also is NUL4235 * terminated.4236 */4237returnsymlink(buf, path);42384239 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4240if(fd <0)4241return-1;42424243if(convert_to_working_tree(path, buf, size, &nbuf)) {4244 size = nbuf.len;4245 buf = nbuf.buf;4246}4247write_or_die(fd, buf, size);4248strbuf_release(&nbuf);42494250if(close(fd) <0)4251die_errno(_("closing file '%s'"), path);4252return0;4253}42544255/*4256 * We optimistically assume that the directories exist,4257 * which is true 99% of the time anyway. If they don't,4258 * we create them and try again.4259 */4260static voidcreate_one_file(struct apply_state *state,4261char*path,4262unsigned mode,4263const char*buf,4264unsigned long size)4265{4266if(state->cached)4267return;4268if(!try_create_file(path, mode, buf, size))4269return;42704271if(errno == ENOENT) {4272if(safe_create_leading_directories(path))4273return;4274if(!try_create_file(path, mode, buf, size))4275return;4276}42774278if(errno == EEXIST || errno == EACCES) {4279/* We may be trying to create a file where a directory4280 * used to be.4281 */4282struct stat st;4283if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4284 errno = EEXIST;4285}42864287if(errno == EEXIST) {4288unsigned int nr =getpid();42894290for(;;) {4291char newpath[PATH_MAX];4292mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4293if(!try_create_file(newpath, mode, buf, size)) {4294if(!rename(newpath, path))4295return;4296unlink_or_warn(newpath);4297break;4298}4299if(errno != EEXIST)4300break;4301++nr;4302}4303}4304die_errno(_("unable to write file '%s' mode%o"), path, mode);4305}43064307static voidadd_conflicted_stages_file(struct apply_state *state,4308struct patch *patch)4309{4310int stage, namelen;4311unsigned ce_size, mode;4312struct cache_entry *ce;43134314if(!state->update_index)4315return;4316 namelen =strlen(patch->new_name);4317 ce_size =cache_entry_size(namelen);4318 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);43194320remove_file_from_cache(patch->new_name);4321for(stage =1; stage <4; stage++) {4322if(is_null_oid(&patch->threeway_stage[stage -1]))4323continue;4324 ce =xcalloc(1, ce_size);4325memcpy(ce->name, patch->new_name, namelen);4326 ce->ce_mode =create_ce_mode(mode);4327 ce->ce_flags =create_ce_flags(stage);4328 ce->ce_namelen = namelen;4329hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4330if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4331die(_("unable to add cache entry for%s"), patch->new_name);4332}4333}43344335static voidcreate_file(struct apply_state *state,struct patch *patch)4336{4337char*path = patch->new_name;4338unsigned mode = patch->new_mode;4339unsigned long size = patch->resultsize;4340char*buf = patch->result;43414342if(!mode)4343 mode = S_IFREG |0644;4344create_one_file(state, path, mode, buf, size);43454346if(patch->conflicted_threeway)4347add_conflicted_stages_file(state, patch);4348else4349add_index_file(state, path, mode, buf, size);4350}43514352/* phase zero is to remove, phase one is to create */4353static voidwrite_out_one_result(struct apply_state *state,4354struct patch *patch,4355int phase)4356{4357if(patch->is_delete >0) {4358if(phase ==0)4359remove_file(state, patch,1);4360return;4361}4362if(patch->is_new >0|| patch->is_copy) {4363if(phase ==1)4364create_file(state, patch);4365return;4366}4367/*4368 * Rename or modification boils down to the same4369 * thing: remove the old, write the new4370 */4371if(phase ==0)4372remove_file(state, patch, patch->is_rename);4373if(phase ==1)4374create_file(state, patch);4375}43764377static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4378{4379FILE*rej;4380char namebuf[PATH_MAX];4381struct fragment *frag;4382int cnt =0;4383struct strbuf sb = STRBUF_INIT;43844385for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4386if(!frag->rejected)4387continue;4388 cnt++;4389}43904391if(!cnt) {4392if(state->apply_verbosely)4393say_patch_name(stderr,4394_("Applied patch%scleanly."), patch);4395return0;4396}43974398/* This should not happen, because a removal patch that leaves4399 * contents are marked "rejected" at the patch level.4400 */4401if(!patch->new_name)4402die(_("internal error"));44034404/* Say this even without --verbose */4405strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4406"Applying patch %%swith%drejects...",4407 cnt),4408 cnt);4409say_patch_name(stderr, sb.buf, patch);4410strbuf_release(&sb);44114412 cnt =strlen(patch->new_name);4413if(ARRAY_SIZE(namebuf) <= cnt +5) {4414 cnt =ARRAY_SIZE(namebuf) -5;4415warning(_("truncating .rej filename to %.*s.rej"),4416 cnt -1, patch->new_name);4417}4418memcpy(namebuf, patch->new_name, cnt);4419memcpy(namebuf + cnt,".rej",5);44204421 rej =fopen(namebuf,"w");4422if(!rej)4423returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));44244425/* Normal git tools never deal with .rej, so do not pretend4426 * this is a git patch by saying --git or giving extended4427 * headers. While at it, maybe please "kompare" that wants4428 * the trailing TAB and some garbage at the end of line ;-).4429 */4430fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4431 patch->new_name, patch->new_name);4432for(cnt =1, frag = patch->fragments;4433 frag;4434 cnt++, frag = frag->next) {4435if(!frag->rejected) {4436fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4437continue;4438}4439fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4440fprintf(rej,"%.*s", frag->size, frag->patch);4441if(frag->patch[frag->size-1] !='\n')4442fputc('\n', rej);4443}4444fclose(rej);4445return-1;4446}44474448static intwrite_out_results(struct apply_state *state,struct patch *list)4449{4450int phase;4451int errs =0;4452struct patch *l;4453struct string_list cpath = STRING_LIST_INIT_DUP;44544455for(phase =0; phase <2; phase++) {4456 l = list;4457while(l) {4458if(l->rejected)4459 errs =1;4460else{4461write_out_one_result(state, l, phase);4462if(phase ==1) {4463if(write_out_one_reject(state, l))4464 errs =1;4465if(l->conflicted_threeway) {4466string_list_append(&cpath, l->new_name);4467 errs =1;4468}4469}4470}4471 l = l->next;4472}4473}44744475if(cpath.nr) {4476struct string_list_item *item;44774478string_list_sort(&cpath);4479for_each_string_list_item(item, &cpath)4480fprintf(stderr,"U%s\n", item->string);4481string_list_clear(&cpath,0);44824483rerere(0);4484}44854486return errs;4487}44884489static struct lock_file lock_file;44904491#define INACCURATE_EOF (1<<0)4492#define RECOUNT (1<<1)44934494static intapply_patch(struct apply_state *state,4495int fd,4496const char*filename,4497int options)4498{4499size_t offset;4500struct strbuf buf = STRBUF_INIT;/* owns the patch text */4501struct patch *list = NULL, **listp = &list;4502int skipped_patch =0;45034504 state->patch_input_file = filename;4505read_patch_file(&buf, fd);4506 offset =0;4507while(offset < buf.len) {4508struct patch *patch;4509int nr;45104511 patch =xcalloc(1,sizeof(*patch));4512 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4513 patch->recount = !!(options & RECOUNT);4514 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4515if(nr <0) {4516free_patch(patch);4517break;4518}4519if(state->apply_in_reverse)4520reverse_patches(patch);4521if(use_patch(state, patch)) {4522patch_stats(patch);4523*listp = patch;4524 listp = &patch->next;4525}4526else{4527if(state->apply_verbosely)4528say_patch_name(stderr,_("Skipped patch '%s'."), patch);4529free_patch(patch);4530 skipped_patch++;4531}4532 offset += nr;4533}45344535if(!list && !skipped_patch)4536die(_("unrecognized input"));45374538if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4539 state->apply =0;45404541 state->update_index = state->check_index && state->apply;4542if(state->update_index && newfd <0)4543 newfd =hold_locked_index(&lock_file,1);45444545if(state->check_index) {4546if(read_cache() <0)4547die(_("unable to read index file"));4548}45494550if((state->check || state->apply) &&4551check_patch_list(state, list) <0&&4552!state->apply_with_reject)4553exit(1);45544555if(state->apply &&write_out_results(state, list)) {4556if(state->apply_with_reject)4557exit(1);4558/* with --3way, we still need to write the index out */4559return1;4560}45614562if(state->fake_ancestor)4563build_fake_ancestor(list, state->fake_ancestor);45644565if(state->diffstat)4566stat_patch_list(list);45674568if(state->numstat)4569numstat_patch_list(state, list);45704571if(state->summary)4572summary_patch_list(list);45734574free_patch_list(list);4575strbuf_release(&buf);4576string_list_clear(&fn_table,0);4577return0;4578}45794580static voidgit_apply_config(void)4581{4582git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4583git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4584git_config(git_default_config, NULL);4585}45864587static intoption_parse_exclude(const struct option *opt,4588const char*arg,int unset)4589{4590struct apply_state *state = opt->value;4591add_name_limit(state, arg,1);4592return0;4593}45944595static intoption_parse_include(const struct option *opt,4596const char*arg,int unset)4597{4598struct apply_state *state = opt->value;4599add_name_limit(state, arg,0);4600 state->has_include =1;4601return0;4602}46034604static intoption_parse_p(const struct option *opt,4605const char*arg,4606int unset)4607{4608struct apply_state *state = opt->value;4609 state->p_value =atoi(arg);4610 state->p_value_known =1;4611return0;4612}46134614static intoption_parse_space_change(const struct option *opt,4615const char*arg,int unset)4616{4617struct apply_state *state = opt->value;4618if(unset)4619 state->ws_ignore_action = ignore_ws_none;4620else4621 state->ws_ignore_action = ignore_ws_change;4622return0;4623}46244625static intoption_parse_whitespace(const struct option *opt,4626const char*arg,int unset)4627{4628struct apply_state *state = opt->value;4629 state->whitespace_option = arg;4630parse_whitespace_option(state, arg);4631return0;4632}46334634static intoption_parse_directory(const struct option *opt,4635const char*arg,int unset)4636{4637struct apply_state *state = opt->value;4638strbuf_reset(&state->root);4639strbuf_addstr(&state->root, arg);4640strbuf_complete(&state->root,'/');4641return0;4642}46434644static voidinit_apply_state(struct apply_state *state,const char*prefix)4645{4646memset(state,0,sizeof(*state));4647 state->prefix = prefix;4648 state->prefix_length = state->prefix ?strlen(state->prefix) :0;4649 state->apply =1;4650 state->line_termination ='\n';4651 state->p_value =1;4652 state->p_context = UINT_MAX;4653 state->squelch_whitespace_errors =5;4654 state->ws_error_action = warn_on_ws_error;4655 state->ws_ignore_action = ignore_ws_none;4656strbuf_init(&state->root,0);46574658git_apply_config();4659if(apply_default_whitespace)4660parse_whitespace_option(state, apply_default_whitespace);4661if(apply_default_ignorewhitespace)4662parse_ignorewhitespace_option(state, apply_default_ignorewhitespace);4663}46644665static voidclear_apply_state(struct apply_state *state)4666{4667string_list_clear(&state->limit_by_name,0);4668strbuf_release(&state->root);4669}46704671intcmd_apply(int argc,const char**argv,const char*prefix)4672{4673int i;4674int errs =0;4675int is_not_gitdir = !startup_info->have_repository;4676int force_apply =0;4677int options =0;4678int read_stdin =1;4679struct apply_state state;46804681struct option builtin_apply_options[] = {4682{ OPTION_CALLBACK,0,"exclude", &state,N_("path"),4683N_("don't apply changes matching the given path"),46840, option_parse_exclude },4685{ OPTION_CALLBACK,0,"include", &state,N_("path"),4686N_("apply changes matching the given path"),46870, option_parse_include },4688{ OPTION_CALLBACK,'p', NULL, &state,N_("num"),4689N_("remove <num> leading slashes from traditional diff paths"),46900, option_parse_p },4691OPT_BOOL(0,"no-add", &state.no_add,4692N_("ignore additions made by the patch")),4693OPT_BOOL(0,"stat", &state.diffstat,4694N_("instead of applying the patch, output diffstat for the input")),4695OPT_NOOP_NOARG(0,"allow-binary-replacement"),4696OPT_NOOP_NOARG(0,"binary"),4697OPT_BOOL(0,"numstat", &state.numstat,4698N_("show number of added and deleted lines in decimal notation")),4699OPT_BOOL(0,"summary", &state.summary,4700N_("instead of applying the patch, output a summary for the input")),4701OPT_BOOL(0,"check", &state.check,4702N_("instead of applying the patch, see if the patch is applicable")),4703OPT_BOOL(0,"index", &state.check_index,4704N_("make sure the patch is applicable to the current index")),4705OPT_BOOL(0,"cached", &state.cached,4706N_("apply a patch without touching the working tree")),4707OPT_BOOL(0,"unsafe-paths", &state.unsafe_paths,4708N_("accept a patch that touches outside the working area")),4709OPT_BOOL(0,"apply", &force_apply,4710N_("also apply the patch (use with --stat/--summary/--check)")),4711OPT_BOOL('3',"3way", &state.threeway,4712N_("attempt three-way merge if a patch does not apply")),4713OPT_FILENAME(0,"build-fake-ancestor", &state.fake_ancestor,4714N_("build a temporary index based on embedded index information")),4715/* Think twice before adding "--nul" synonym to this */4716OPT_SET_INT('z', NULL, &state.line_termination,4717N_("paths are separated with NUL character"),'\0'),4718OPT_INTEGER('C', NULL, &state.p_context,4719N_("ensure at least <n> lines of context match")),4720{ OPTION_CALLBACK,0,"whitespace", &state,N_("action"),4721N_("detect new or modified lines that have whitespace errors"),47220, option_parse_whitespace },4723{ OPTION_CALLBACK,0,"ignore-space-change", &state, NULL,4724N_("ignore changes in whitespace when finding context"),4725 PARSE_OPT_NOARG, option_parse_space_change },4726{ OPTION_CALLBACK,0,"ignore-whitespace", &state, NULL,4727N_("ignore changes in whitespace when finding context"),4728 PARSE_OPT_NOARG, option_parse_space_change },4729OPT_BOOL('R',"reverse", &state.apply_in_reverse,4730N_("apply the patch in reverse")),4731OPT_BOOL(0,"unidiff-zero", &state.unidiff_zero,4732N_("don't expect at least one line of context")),4733OPT_BOOL(0,"reject", &state.apply_with_reject,4734N_("leave the rejected hunks in corresponding *.rej files")),4735OPT_BOOL(0,"allow-overlap", &state.allow_overlap,4736N_("allow overlapping hunks")),4737OPT__VERBOSE(&state.apply_verbosely,N_("be verbose")),4738OPT_BIT(0,"inaccurate-eof", &options,4739N_("tolerate incorrectly detected missing new-line at the end of file"),4740 INACCURATE_EOF),4741OPT_BIT(0,"recount", &options,4742N_("do not trust the line counts in the hunk headers"),4743 RECOUNT),4744{ OPTION_CALLBACK,0,"directory", &state,N_("root"),4745N_("prepend <root> to all filenames"),47460, option_parse_directory },4747OPT_END()4748};47494750init_apply_state(&state, prefix);47514752 argc =parse_options(argc, argv, state.prefix, builtin_apply_options,4753 apply_usage,0);47544755if(state.apply_with_reject && state.threeway)4756die("--reject and --3way cannot be used together.");4757if(state.cached && state.threeway)4758die("--cached and --3way cannot be used together.");4759if(state.threeway) {4760if(is_not_gitdir)4761die(_("--3way outside a repository"));4762 state.check_index =1;4763}4764if(state.apply_with_reject)4765 state.apply = state.apply_verbosely =1;4766if(!force_apply && (state.diffstat || state.numstat || state.summary || state.check || state.fake_ancestor))4767 state.apply =0;4768if(state.check_index && is_not_gitdir)4769die(_("--index outside a repository"));4770if(state.cached) {4771if(is_not_gitdir)4772die(_("--cached outside a repository"));4773 state.check_index =1;4774}4775if(state.check_index)4776 state.unsafe_paths =0;47774778for(i =0; i < argc; i++) {4779const char*arg = argv[i];4780int fd;47814782if(!strcmp(arg,"-")) {4783 errs |=apply_patch(&state,0,"<stdin>", options);4784 read_stdin =0;4785continue;4786}else if(0< state.prefix_length)4787 arg =prefix_filename(state.prefix,4788 state.prefix_length,4789 arg);47904791 fd =open(arg, O_RDONLY);4792if(fd <0)4793die_errno(_("can't open patch '%s'"), arg);4794 read_stdin =0;4795set_default_whitespace_mode(&state);4796 errs |=apply_patch(&state, fd, arg, options);4797close(fd);4798}4799set_default_whitespace_mode(&state);4800if(read_stdin)4801 errs |=apply_patch(&state,0,"<stdin>", options);4802if(state.whitespace_error) {4803if(state.squelch_whitespace_errors &&4804 state.squelch_whitespace_errors < state.whitespace_error) {4805int squelched =4806 state.whitespace_error - state.squelch_whitespace_errors;4807warning(Q_("squelched%dwhitespace error",4808"squelched%dwhitespace errors",4809 squelched),4810 squelched);4811}4812if(state.ws_error_action == die_on_ws_error)4813die(Q_("%dline adds whitespace errors.",4814"%dlines add whitespace errors.",4815 state.whitespace_error),4816 state.whitespace_error);4817if(state.applied_after_fixing_ws && state.apply)4818warning("%dline%sapplied after"4819" fixing whitespace errors.",4820 state.applied_after_fixing_ws,4821 state.applied_after_fixing_ws ==1?"":"s");4822else if(state.whitespace_error)4823warning(Q_("%dline adds whitespace errors.",4824"%dlines add whitespace errors.",4825 state.whitespace_error),4826 state.whitespace_error);4827}48284829if(state.update_index) {4830if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK))4831die(_("Unable to write new index file"));4832}48334834clear_apply_state(&state);48354836return!!errs;4837}