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 31struct apply_state { 32const char*prefix; 33int prefix_length; 34 35/* These control what gets looked at and modified */ 36int apply;/* this is not a dry-run */ 37int cached;/* apply to the index only */ 38int check;/* preimage must match working tree, don't actually apply */ 39int check_index;/* preimage must match the indexed version */ 40int update_index;/* check_index && apply */ 41 42/* These control cosmetic aspect of the output */ 43int diffstat;/* just show a diffstat, and don't actually apply */ 44int numstat;/* just show a numeric diffstat, and don't actually apply */ 45int summary;/* just report creation, deletion, etc, and don't actually apply */ 46 47/* These boolean parameters control how the apply is done */ 48int allow_overlap; 49int apply_in_reverse; 50int apply_with_reject; 51int apply_verbosely; 52int no_add; 53int threeway; 54int unidiff_zero; 55int unsafe_paths; 56 57/* Other non boolean parameters */ 58const char*fake_ancestor; 59const char*patch_input_file; 60int line_termination; 61struct strbuf root; 62int p_value; 63int p_value_known; 64unsigned int p_context; 65 66/* Exclude and include path parameters */ 67struct string_list limit_by_name; 68int has_include; 69 70/* These control whitespace errors */ 71enum ws_error_action ws_error_action; 72const char*whitespace_option; 73int whitespace_error; 74int squelch_whitespace_errors; 75int applied_after_fixing_ws; 76}; 77 78static int newfd = -1; 79 80static const char*const apply_usage[] = { 81N_("git apply [<options>] [<patch>...]"), 82 NULL 83}; 84 85 86static enum ws_ignore { 87 ignore_ws_none, 88 ignore_ws_change 89} ws_ignore_action = ignore_ws_none; 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(const char*option) 123{ 124if(!option || !strcmp(option,"no") || 125!strcmp(option,"false") || !strcmp(option,"never") || 126!strcmp(option,"none")) { 127 ws_ignore_action = ignore_ws_none; 128return; 129} 130if(!strcmp(option,"change")) { 131 ws_ignore_action = ignore_ws_change; 132return; 133} 134die(_("unrecognized whitespace ignore option '%s'"), option); 135} 136 137static voidset_default_whitespace_mode(struct apply_state *state) 138{ 139if(!state->whitespace_option && !apply_default_whitespace) 140 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 141} 142 143/* 144 * For "diff-stat" like behaviour, we keep track of the biggest change 145 * we've seen, and the longest filename. That allows us to do simple 146 * scaling. 147 */ 148static int max_change, max_len; 149 150/* 151 * Various "current state", notably line numbers and what 152 * file (and how) we're patching right now.. The "is_xxxx" 153 * things are flags, where -1 means "don't know yet". 154 */ 155static int state_linenr =1; 156 157/* 158 * This represents one "hunk" from a patch, starting with 159 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 160 * patch text is pointed at by patch, and its byte length 161 * is stored in size. leading and trailing are the number 162 * of context lines. 163 */ 164struct fragment { 165unsigned long leading, trailing; 166unsigned long oldpos, oldlines; 167unsigned long newpos, newlines; 168/* 169 * 'patch' is usually borrowed from buf in apply_patch(), 170 * but some codepaths store an allocated buffer. 171 */ 172const char*patch; 173unsigned free_patch:1, 174 rejected:1; 175int size; 176int linenr; 177struct fragment *next; 178}; 179 180/* 181 * When dealing with a binary patch, we reuse "leading" field 182 * to store the type of the binary hunk, either deflated "delta" 183 * or deflated "literal". 184 */ 185#define binary_patch_method leading 186#define BINARY_DELTA_DEFLATED 1 187#define BINARY_LITERAL_DEFLATED 2 188 189/* 190 * This represents a "patch" to a file, both metainfo changes 191 * such as creation/deletion, filemode and content changes represented 192 * as a series of fragments. 193 */ 194struct patch { 195char*new_name, *old_name, *def_name; 196unsigned int old_mode, new_mode; 197int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 198int rejected; 199unsigned ws_rule; 200int lines_added, lines_deleted; 201int score; 202unsigned int is_toplevel_relative:1; 203unsigned int inaccurate_eof:1; 204unsigned int is_binary:1; 205unsigned int is_copy:1; 206unsigned int is_rename:1; 207unsigned int recount:1; 208unsigned int conflicted_threeway:1; 209unsigned int direct_to_threeway:1; 210struct fragment *fragments; 211char*result; 212size_t resultsize; 213char old_sha1_prefix[41]; 214char new_sha1_prefix[41]; 215struct patch *next; 216 217/* three-way fallback result */ 218struct object_id threeway_stage[3]; 219}; 220 221static voidfree_fragment_list(struct fragment *list) 222{ 223while(list) { 224struct fragment *next = list->next; 225if(list->free_patch) 226free((char*)list->patch); 227free(list); 228 list = next; 229} 230} 231 232static voidfree_patch(struct patch *patch) 233{ 234free_fragment_list(patch->fragments); 235free(patch->def_name); 236free(patch->old_name); 237free(patch->new_name); 238free(patch->result); 239free(patch); 240} 241 242static voidfree_patch_list(struct patch *list) 243{ 244while(list) { 245struct patch *next = list->next; 246free_patch(list); 247 list = next; 248} 249} 250 251/* 252 * A line in a file, len-bytes long (includes the terminating LF, 253 * except for an incomplete line at the end if the file ends with 254 * one), and its contents hashes to 'hash'. 255 */ 256struct line { 257size_t len; 258unsigned hash :24; 259unsigned flag :8; 260#define LINE_COMMON 1 261#define LINE_PATCHED 2 262}; 263 264/* 265 * This represents a "file", which is an array of "lines". 266 */ 267struct image { 268char*buf; 269size_t len; 270size_t nr; 271size_t alloc; 272struct line *line_allocated; 273struct line *line; 274}; 275 276/* 277 * Records filenames that have been touched, in order to handle 278 * the case where more than one patches touch the same file. 279 */ 280 281static struct string_list fn_table; 282 283static uint32_thash_line(const char*cp,size_t len) 284{ 285size_t i; 286uint32_t h; 287for(i =0, h =0; i < len; i++) { 288if(!isspace(cp[i])) { 289 h = h *3+ (cp[i] &0xff); 290} 291} 292return h; 293} 294 295/* 296 * Compare lines s1 of length n1 and s2 of length n2, ignoring 297 * whitespace difference. Returns 1 if they match, 0 otherwise 298 */ 299static intfuzzy_matchlines(const char*s1,size_t n1, 300const char*s2,size_t n2) 301{ 302const char*last1 = s1 + n1 -1; 303const char*last2 = s2 + n2 -1; 304int result =0; 305 306/* ignore line endings */ 307while((*last1 =='\r') || (*last1 =='\n')) 308 last1--; 309while((*last2 =='\r') || (*last2 =='\n')) 310 last2--; 311 312/* skip leading whitespaces, if both begin with whitespace */ 313if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 314while(isspace(*s1) && (s1 <= last1)) 315 s1++; 316while(isspace(*s2) && (s2 <= last2)) 317 s2++; 318} 319/* early return if both lines are empty */ 320if((s1 > last1) && (s2 > last2)) 321return1; 322while(!result) { 323 result = *s1++ - *s2++; 324/* 325 * Skip whitespace inside. We check for whitespace on 326 * both buffers because we don't want "a b" to match 327 * "ab" 328 */ 329if(isspace(*s1) &&isspace(*s2)) { 330while(isspace(*s1) && s1 <= last1) 331 s1++; 332while(isspace(*s2) && s2 <= last2) 333 s2++; 334} 335/* 336 * If we reached the end on one side only, 337 * lines don't match 338 */ 339if( 340((s2 > last2) && (s1 <= last1)) || 341((s1 > last1) && (s2 <= last2))) 342return0; 343if((s1 > last1) && (s2 > last2)) 344break; 345} 346 347return!result; 348} 349 350static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 351{ 352ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 353 img->line_allocated[img->nr].len = len; 354 img->line_allocated[img->nr].hash =hash_line(bol, len); 355 img->line_allocated[img->nr].flag = flag; 356 img->nr++; 357} 358 359/* 360 * "buf" has the file contents to be patched (read from various sources). 361 * attach it to "image" and add line-based index to it. 362 * "image" now owns the "buf". 363 */ 364static voidprepare_image(struct image *image,char*buf,size_t len, 365int prepare_linetable) 366{ 367const char*cp, *ep; 368 369memset(image,0,sizeof(*image)); 370 image->buf = buf; 371 image->len = len; 372 373if(!prepare_linetable) 374return; 375 376 ep = image->buf + image->len; 377 cp = image->buf; 378while(cp < ep) { 379const char*next; 380for(next = cp; next < ep && *next !='\n'; next++) 381; 382if(next < ep) 383 next++; 384add_line_info(image, cp, next - cp,0); 385 cp = next; 386} 387 image->line = image->line_allocated; 388} 389 390static voidclear_image(struct image *image) 391{ 392free(image->buf); 393free(image->line_allocated); 394memset(image,0,sizeof(*image)); 395} 396 397/* fmt must contain _one_ %s and no other substitution */ 398static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 399{ 400struct strbuf sb = STRBUF_INIT; 401 402if(patch->old_name && patch->new_name && 403strcmp(patch->old_name, patch->new_name)) { 404quote_c_style(patch->old_name, &sb, NULL,0); 405strbuf_addstr(&sb," => "); 406quote_c_style(patch->new_name, &sb, NULL,0); 407}else{ 408const char*n = patch->new_name; 409if(!n) 410 n = patch->old_name; 411quote_c_style(n, &sb, NULL,0); 412} 413fprintf(output, fmt, sb.buf); 414fputc('\n', output); 415strbuf_release(&sb); 416} 417 418#define SLOP (16) 419 420static voidread_patch_file(struct strbuf *sb,int fd) 421{ 422if(strbuf_read(sb, fd,0) <0) 423die_errno("git apply: failed to read"); 424 425/* 426 * Make sure that we have some slop in the buffer 427 * so that we can do speculative "memcmp" etc, and 428 * see to it that it is NUL-filled. 429 */ 430strbuf_grow(sb, SLOP); 431memset(sb->buf + sb->len,0, SLOP); 432} 433 434static unsigned longlinelen(const char*buffer,unsigned long size) 435{ 436unsigned long len =0; 437while(size--) { 438 len++; 439if(*buffer++ =='\n') 440break; 441} 442return len; 443} 444 445static intis_dev_null(const char*str) 446{ 447returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 448} 449 450#define TERM_SPACE 1 451#define TERM_TAB 2 452 453static intname_terminate(const char*name,int namelen,int c,int terminate) 454{ 455if(c ==' '&& !(terminate & TERM_SPACE)) 456return0; 457if(c =='\t'&& !(terminate & TERM_TAB)) 458return0; 459 460return1; 461} 462 463/* remove double slashes to make --index work with such filenames */ 464static char*squash_slash(char*name) 465{ 466int i =0, j =0; 467 468if(!name) 469return NULL; 470 471while(name[i]) { 472if((name[j++] = name[i++]) =='/') 473while(name[i] =='/') 474 i++; 475} 476 name[j] ='\0'; 477return name; 478} 479 480static char*find_name_gnu(struct apply_state *state, 481const char*line, 482const char*def, 483int p_value) 484{ 485struct strbuf name = STRBUF_INIT; 486char*cp; 487 488/* 489 * Proposed "new-style" GNU patch/diff format; see 490 * http://marc.info/?l=git&m=112927316408690&w=2 491 */ 492if(unquote_c_style(&name, line, NULL)) { 493strbuf_release(&name); 494return NULL; 495} 496 497for(cp = name.buf; p_value; p_value--) { 498 cp =strchr(cp,'/'); 499if(!cp) { 500strbuf_release(&name); 501return NULL; 502} 503 cp++; 504} 505 506strbuf_remove(&name,0, cp - name.buf); 507if(state->root.len) 508strbuf_insert(&name,0, state->root.buf, state->root.len); 509returnsquash_slash(strbuf_detach(&name, NULL)); 510} 511 512static size_tsane_tz_len(const char*line,size_t len) 513{ 514const char*tz, *p; 515 516if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 517return0; 518 tz = line + len -strlen(" +0500"); 519 520if(tz[1] !='+'&& tz[1] !='-') 521return0; 522 523for(p = tz +2; p != line + len; p++) 524if(!isdigit(*p)) 525return0; 526 527return line + len - tz; 528} 529 530static size_ttz_with_colon_len(const char*line,size_t len) 531{ 532const char*tz, *p; 533 534if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 535return0; 536 tz = line + len -strlen(" +08:00"); 537 538if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 539return0; 540 p = tz +2; 541if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 542!isdigit(*p++) || !isdigit(*p++)) 543return0; 544 545return line + len - tz; 546} 547 548static size_tdate_len(const char*line,size_t len) 549{ 550const char*date, *p; 551 552if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 553return0; 554 p = date = line + len -strlen("72-02-05"); 555 556if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 557!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 558!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 559return0; 560 561if(date - line >=strlen("19") && 562isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 563 date -=strlen("19"); 564 565return line + len - date; 566} 567 568static size_tshort_time_len(const char*line,size_t len) 569{ 570const char*time, *p; 571 572if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 573return0; 574 p = time = line + len -strlen(" 07:01:32"); 575 576/* Permit 1-digit hours? */ 577if(*p++ !=' '|| 578!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 579!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 580!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 581return0; 582 583return line + len - time; 584} 585 586static size_tfractional_time_len(const char*line,size_t len) 587{ 588const char*p; 589size_t n; 590 591/* Expected format: 19:41:17.620000023 */ 592if(!len || !isdigit(line[len -1])) 593return0; 594 p = line + len -1; 595 596/* Fractional seconds. */ 597while(p > line &&isdigit(*p)) 598 p--; 599if(*p !='.') 600return0; 601 602/* Hours, minutes, and whole seconds. */ 603 n =short_time_len(line, p - line); 604if(!n) 605return0; 606 607return line + len - p + n; 608} 609 610static size_ttrailing_spaces_len(const char*line,size_t len) 611{ 612const char*p; 613 614/* Expected format: ' ' x (1 or more) */ 615if(!len || line[len -1] !=' ') 616return0; 617 618 p = line + len; 619while(p != line) { 620 p--; 621if(*p !=' ') 622return line + len - (p +1); 623} 624 625/* All spaces! */ 626return len; 627} 628 629static size_tdiff_timestamp_len(const char*line,size_t len) 630{ 631const char*end = line + len; 632size_t n; 633 634/* 635 * Posix: 2010-07-05 19:41:17 636 * GNU: 2010-07-05 19:41:17.620000023 -0500 637 */ 638 639if(!isdigit(end[-1])) 640return0; 641 642 n =sane_tz_len(line, end - line); 643if(!n) 644 n =tz_with_colon_len(line, end - line); 645 end -= n; 646 647 n =short_time_len(line, end - line); 648if(!n) 649 n =fractional_time_len(line, end - line); 650 end -= n; 651 652 n =date_len(line, end - line); 653if(!n)/* No date. Too bad. */ 654return0; 655 end -= n; 656 657if(end == line)/* No space before date. */ 658return0; 659if(end[-1] =='\t') {/* Success! */ 660 end--; 661return line + len - end; 662} 663if(end[-1] !=' ')/* No space before date. */ 664return0; 665 666/* Whitespace damage. */ 667 end -=trailing_spaces_len(line, end - line); 668return line + len - end; 669} 670 671static char*find_name_common(struct apply_state *state, 672const char*line, 673const char*def, 674int p_value, 675const char*end, 676int terminate) 677{ 678int len; 679const char*start = NULL; 680 681if(p_value ==0) 682 start = line; 683while(line != end) { 684char c = *line; 685 686if(!end &&isspace(c)) { 687if(c =='\n') 688break; 689if(name_terminate(start, line-start, c, terminate)) 690break; 691} 692 line++; 693if(c =='/'&& !--p_value) 694 start = line; 695} 696if(!start) 697returnsquash_slash(xstrdup_or_null(def)); 698 len = line - start; 699if(!len) 700returnsquash_slash(xstrdup_or_null(def)); 701 702/* 703 * Generally we prefer the shorter name, especially 704 * if the other one is just a variation of that with 705 * something else tacked on to the end (ie "file.orig" 706 * or "file~"). 707 */ 708if(def) { 709int deflen =strlen(def); 710if(deflen < len && !strncmp(start, def, deflen)) 711returnsquash_slash(xstrdup(def)); 712} 713 714if(state->root.len) { 715char*ret =xstrfmt("%s%.*s", state->root.buf, len, start); 716returnsquash_slash(ret); 717} 718 719returnsquash_slash(xmemdupz(start, len)); 720} 721 722static char*find_name(struct apply_state *state, 723const char*line, 724char*def, 725int p_value, 726int terminate) 727{ 728if(*line =='"') { 729char*name =find_name_gnu(state, line, def, p_value); 730if(name) 731return name; 732} 733 734returnfind_name_common(state, line, def, p_value, NULL, terminate); 735} 736 737static char*find_name_traditional(struct apply_state *state, 738const char*line, 739char*def, 740int p_value) 741{ 742size_t len; 743size_t date_len; 744 745if(*line =='"') { 746char*name =find_name_gnu(state, line, def, p_value); 747if(name) 748return name; 749} 750 751 len =strchrnul(line,'\n') - line; 752 date_len =diff_timestamp_len(line, len); 753if(!date_len) 754returnfind_name_common(state, line, def, p_value, NULL, TERM_TAB); 755 len -= date_len; 756 757returnfind_name_common(state, line, def, p_value, line + len,0); 758} 759 760static intcount_slashes(const char*cp) 761{ 762int cnt =0; 763char ch; 764 765while((ch = *cp++)) 766if(ch =='/') 767 cnt++; 768return cnt; 769} 770 771/* 772 * Given the string after "--- " or "+++ ", guess the appropriate 773 * p_value for the given patch. 774 */ 775static intguess_p_value(struct apply_state *state,const char*nameline) 776{ 777char*name, *cp; 778int val = -1; 779 780if(is_dev_null(nameline)) 781return-1; 782 name =find_name_traditional(state, nameline, NULL,0); 783if(!name) 784return-1; 785 cp =strchr(name,'/'); 786if(!cp) 787 val =0; 788else if(state->prefix) { 789/* 790 * Does it begin with "a/$our-prefix" and such? Then this is 791 * very likely to apply to our directory. 792 */ 793if(!strncmp(name, state->prefix, state->prefix_length)) 794 val =count_slashes(state->prefix); 795else{ 796 cp++; 797if(!strncmp(cp, state->prefix, state->prefix_length)) 798 val =count_slashes(state->prefix) +1; 799} 800} 801free(name); 802return val; 803} 804 805/* 806 * Does the ---/+++ line have the POSIX timestamp after the last HT? 807 * GNU diff puts epoch there to signal a creation/deletion event. Is 808 * this such a timestamp? 809 */ 810static inthas_epoch_timestamp(const char*nameline) 811{ 812/* 813 * We are only interested in epoch timestamp; any non-zero 814 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 815 * For the same reason, the date must be either 1969-12-31 or 816 * 1970-01-01, and the seconds part must be "00". 817 */ 818const char stamp_regexp[] = 819"^(1969-12-31|1970-01-01)" 820" " 821"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 822" " 823"([-+][0-2][0-9]:?[0-5][0-9])\n"; 824const char*timestamp = NULL, *cp, *colon; 825static regex_t *stamp; 826 regmatch_t m[10]; 827int zoneoffset; 828int hourminute; 829int status; 830 831for(cp = nameline; *cp !='\n'; cp++) { 832if(*cp =='\t') 833 timestamp = cp +1; 834} 835if(!timestamp) 836return0; 837if(!stamp) { 838 stamp =xmalloc(sizeof(*stamp)); 839if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 840warning(_("Cannot prepare timestamp regexp%s"), 841 stamp_regexp); 842return0; 843} 844} 845 846 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 847if(status) { 848if(status != REG_NOMATCH) 849warning(_("regexec returned%dfor input:%s"), 850 status, timestamp); 851return0; 852} 853 854 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 855if(*colon ==':') 856 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 857else 858 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 859if(timestamp[m[3].rm_so] =='-') 860 zoneoffset = -zoneoffset; 861 862/* 863 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 864 * (west of GMT) or 1970-01-01 (east of GMT) 865 */ 866if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 867(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 868return0; 869 870 hourminute = (strtol(timestamp +11, NULL,10) *60+ 871strtol(timestamp +14, NULL,10) - 872 zoneoffset); 873 874return((zoneoffset <0&& hourminute ==1440) || 875(0<= zoneoffset && !hourminute)); 876} 877 878/* 879 * Get the name etc info from the ---/+++ lines of a traditional patch header 880 * 881 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 882 * files, we can happily check the index for a match, but for creating a 883 * new file we should try to match whatever "patch" does. I have no idea. 884 */ 885static voidparse_traditional_patch(struct apply_state *state, 886const char*first, 887const char*second, 888struct patch *patch) 889{ 890char*name; 891 892 first +=4;/* skip "--- " */ 893 second +=4;/* skip "+++ " */ 894if(!state->p_value_known) { 895int p, q; 896 p =guess_p_value(state, first); 897 q =guess_p_value(state, second); 898if(p <0) p = q; 899if(0<= p && p == q) { 900 state->p_value = p; 901 state->p_value_known =1; 902} 903} 904if(is_dev_null(first)) { 905 patch->is_new =1; 906 patch->is_delete =0; 907 name =find_name_traditional(state, second, NULL, state->p_value); 908 patch->new_name = name; 909}else if(is_dev_null(second)) { 910 patch->is_new =0; 911 patch->is_delete =1; 912 name =find_name_traditional(state, first, NULL, state->p_value); 913 patch->old_name = name; 914}else{ 915char*first_name; 916 first_name =find_name_traditional(state, first, NULL, state->p_value); 917 name =find_name_traditional(state, second, first_name, state->p_value); 918free(first_name); 919if(has_epoch_timestamp(first)) { 920 patch->is_new =1; 921 patch->is_delete =0; 922 patch->new_name = name; 923}else if(has_epoch_timestamp(second)) { 924 patch->is_new =0; 925 patch->is_delete =1; 926 patch->old_name = name; 927}else{ 928 patch->old_name = name; 929 patch->new_name =xstrdup_or_null(name); 930} 931} 932if(!name) 933die(_("unable to find filename in patch at line%d"), state_linenr); 934} 935 936static intgitdiff_hdrend(struct apply_state *state, 937const char*line, 938struct patch *patch) 939{ 940return-1; 941} 942 943/* 944 * We're anal about diff header consistency, to make 945 * sure that we don't end up having strange ambiguous 946 * patches floating around. 947 * 948 * As a result, gitdiff_{old|new}name() will check 949 * their names against any previous information, just 950 * to make sure.. 951 */ 952#define DIFF_OLD_NAME 0 953#define DIFF_NEW_NAME 1 954 955static voidgitdiff_verify_name(struct apply_state *state, 956const char*line, 957int isnull, 958char**name, 959int side) 960{ 961if(!*name && !isnull) { 962*name =find_name(state, line, NULL, state->p_value, TERM_TAB); 963return; 964} 965 966if(*name) { 967int len =strlen(*name); 968char*another; 969if(isnull) 970die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 971*name, state_linenr); 972 another =find_name(state, line, NULL, state->p_value, TERM_TAB); 973if(!another ||memcmp(another, *name, len +1)) 974die((side == DIFF_NEW_NAME) ? 975_("git apply: bad git-diff - inconsistent new filename on line%d") : 976_("git apply: bad git-diff - inconsistent old filename on line%d"), state_linenr); 977free(another); 978}else{ 979/* expect "/dev/null" */ 980if(memcmp("/dev/null", line,9) || line[9] !='\n') 981die(_("git apply: bad git-diff - expected /dev/null on line%d"), state_linenr); 982} 983} 984 985static intgitdiff_oldname(struct apply_state *state, 986const char*line, 987struct patch *patch) 988{ 989gitdiff_verify_name(state, line, 990 patch->is_new, &patch->old_name, 991 DIFF_OLD_NAME); 992return0; 993} 994 995static intgitdiff_newname(struct apply_state *state, 996const char*line, 997struct patch *patch) 998{ 999gitdiff_verify_name(state, line,1000 patch->is_delete, &patch->new_name,1001 DIFF_NEW_NAME);1002return0;1003}10041005static intgitdiff_oldmode(struct apply_state *state,1006const char*line,1007struct patch *patch)1008{1009 patch->old_mode =strtoul(line, NULL,8);1010return0;1011}10121013static intgitdiff_newmode(struct apply_state *state,1014const char*line,1015struct patch *patch)1016{1017 patch->new_mode =strtoul(line, NULL,8);1018return0;1019}10201021static intgitdiff_delete(struct apply_state *state,1022const char*line,1023struct patch *patch)1024{1025 patch->is_delete =1;1026free(patch->old_name);1027 patch->old_name =xstrdup_or_null(patch->def_name);1028returngitdiff_oldmode(state, line, patch);1029}10301031static intgitdiff_newfile(struct apply_state *state,1032const char*line,1033struct patch *patch)1034{1035 patch->is_new =1;1036free(patch->new_name);1037 patch->new_name =xstrdup_or_null(patch->def_name);1038returngitdiff_newmode(state, line, patch);1039}10401041static intgitdiff_copysrc(struct apply_state *state,1042const char*line,1043struct patch *patch)1044{1045 patch->is_copy =1;1046free(patch->old_name);1047 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1048return0;1049}10501051static intgitdiff_copydst(struct apply_state *state,1052const char*line,1053struct patch *patch)1054{1055 patch->is_copy =1;1056free(patch->new_name);1057 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1058return0;1059}10601061static intgitdiff_renamesrc(struct apply_state *state,1062const char*line,1063struct patch *patch)1064{1065 patch->is_rename =1;1066free(patch->old_name);1067 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1068return0;1069}10701071static intgitdiff_renamedst(struct apply_state *state,1072const char*line,1073struct patch *patch)1074{1075 patch->is_rename =1;1076free(patch->new_name);1077 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1078return0;1079}10801081static intgitdiff_similarity(struct apply_state *state,1082const char*line,1083struct patch *patch)1084{1085unsigned long val =strtoul(line, NULL,10);1086if(val <=100)1087 patch->score = val;1088return0;1089}10901091static intgitdiff_dissimilarity(struct apply_state *state,1092const char*line,1093struct patch *patch)1094{1095unsigned long val =strtoul(line, NULL,10);1096if(val <=100)1097 patch->score = val;1098return0;1099}11001101static intgitdiff_index(struct apply_state *state,1102const char*line,1103struct patch *patch)1104{1105/*1106 * index line is N hexadecimal, "..", N hexadecimal,1107 * and optional space with octal mode.1108 */1109const char*ptr, *eol;1110int len;11111112 ptr =strchr(line,'.');1113if(!ptr || ptr[1] !='.'||40< ptr - line)1114return0;1115 len = ptr - line;1116memcpy(patch->old_sha1_prefix, line, len);1117 patch->old_sha1_prefix[len] =0;11181119 line = ptr +2;1120 ptr =strchr(line,' ');1121 eol =strchrnul(line,'\n');11221123if(!ptr || eol < ptr)1124 ptr = eol;1125 len = ptr - line;11261127if(40< len)1128return0;1129memcpy(patch->new_sha1_prefix, line, len);1130 patch->new_sha1_prefix[len] =0;1131if(*ptr ==' ')1132 patch->old_mode =strtoul(ptr+1, NULL,8);1133return0;1134}11351136/*1137 * This is normal for a diff that doesn't change anything: we'll fall through1138 * into the next diff. Tell the parser to break out.1139 */1140static intgitdiff_unrecognized(struct apply_state *state,1141const char*line,1142struct patch *patch)1143{1144return-1;1145}11461147/*1148 * Skip p_value leading components from "line"; as we do not accept1149 * absolute paths, return NULL in that case.1150 */1151static const char*skip_tree_prefix(struct apply_state *state,1152const char*line,1153int llen)1154{1155int nslash;1156int i;11571158if(!state->p_value)1159return(llen && line[0] =='/') ? NULL : line;11601161 nslash = state->p_value;1162for(i =0; i < llen; i++) {1163int ch = line[i];1164if(ch =='/'&& --nslash <=0)1165return(i ==0) ? NULL : &line[i +1];1166}1167return NULL;1168}11691170/*1171 * This is to extract the same name that appears on "diff --git"1172 * line. We do not find and return anything if it is a rename1173 * patch, and it is OK because we will find the name elsewhere.1174 * We need to reliably find name only when it is mode-change only,1175 * creation or deletion of an empty file. In any of these cases,1176 * both sides are the same name under a/ and b/ respectively.1177 */1178static char*git_header_name(struct apply_state *state,1179const char*line,1180int llen)1181{1182const char*name;1183const char*second = NULL;1184size_t len, line_len;11851186 line +=strlen("diff --git ");1187 llen -=strlen("diff --git ");11881189if(*line =='"') {1190const char*cp;1191struct strbuf first = STRBUF_INIT;1192struct strbuf sp = STRBUF_INIT;11931194if(unquote_c_style(&first, line, &second))1195goto free_and_fail1;11961197/* strip the a/b prefix including trailing slash */1198 cp =skip_tree_prefix(state, first.buf, first.len);1199if(!cp)1200goto free_and_fail1;1201strbuf_remove(&first,0, cp - first.buf);12021203/*1204 * second points at one past closing dq of name.1205 * find the second name.1206 */1207while((second < line + llen) &&isspace(*second))1208 second++;12091210if(line + llen <= second)1211goto free_and_fail1;1212if(*second =='"') {1213if(unquote_c_style(&sp, second, NULL))1214goto free_and_fail1;1215 cp =skip_tree_prefix(state, sp.buf, sp.len);1216if(!cp)1217goto free_and_fail1;1218/* They must match, otherwise ignore */1219if(strcmp(cp, first.buf))1220goto free_and_fail1;1221strbuf_release(&sp);1222returnstrbuf_detach(&first, NULL);1223}12241225/* unquoted second */1226 cp =skip_tree_prefix(state, second, line + llen - second);1227if(!cp)1228goto free_and_fail1;1229if(line + llen - cp != first.len ||1230memcmp(first.buf, cp, first.len))1231goto free_and_fail1;1232returnstrbuf_detach(&first, NULL);12331234 free_and_fail1:1235strbuf_release(&first);1236strbuf_release(&sp);1237return NULL;1238}12391240/* unquoted first name */1241 name =skip_tree_prefix(state, line, llen);1242if(!name)1243return NULL;12441245/*1246 * since the first name is unquoted, a dq if exists must be1247 * the beginning of the second name.1248 */1249for(second = name; second < line + llen; second++) {1250if(*second =='"') {1251struct strbuf sp = STRBUF_INIT;1252const char*np;12531254if(unquote_c_style(&sp, second, NULL))1255goto free_and_fail2;12561257 np =skip_tree_prefix(state, sp.buf, sp.len);1258if(!np)1259goto free_and_fail2;12601261 len = sp.buf + sp.len - np;1262if(len < second - name &&1263!strncmp(np, name, len) &&1264isspace(name[len])) {1265/* Good */1266strbuf_remove(&sp,0, np - sp.buf);1267returnstrbuf_detach(&sp, NULL);1268}12691270 free_and_fail2:1271strbuf_release(&sp);1272return NULL;1273}1274}12751276/*1277 * Accept a name only if it shows up twice, exactly the same1278 * form.1279 */1280 second =strchr(name,'\n');1281if(!second)1282return NULL;1283 line_len = second - name;1284for(len =0; ; len++) {1285switch(name[len]) {1286default:1287continue;1288case'\n':1289return NULL;1290case'\t':case' ':1291/*1292 * Is this the separator between the preimage1293 * and the postimage pathname? Again, we are1294 * only interested in the case where there is1295 * no rename, as this is only to set def_name1296 * and a rename patch has the names elsewhere1297 * in an unambiguous form.1298 */1299if(!name[len +1])1300return NULL;/* no postimage name */1301 second =skip_tree_prefix(state, name + len +1,1302 line_len - (len +1));1303if(!second)1304return NULL;1305/*1306 * Does len bytes starting at "name" and "second"1307 * (that are separated by one HT or SP we just1308 * found) exactly match?1309 */1310if(second[len] =='\n'&& !strncmp(name, second, len))1311returnxmemdupz(name, len);1312}1313}1314}13151316/* Verify that we recognize the lines following a git header */1317static intparse_git_header(struct apply_state *state,1318const char*line,1319int len,1320unsigned int size,1321struct patch *patch)1322{1323unsigned long offset;13241325/* A git diff has explicit new/delete information, so we don't guess */1326 patch->is_new =0;1327 patch->is_delete =0;13281329/*1330 * Some things may not have the old name in the1331 * rest of the headers anywhere (pure mode changes,1332 * or removing or adding empty files), so we get1333 * the default name from the header.1334 */1335 patch->def_name =git_header_name(state, line, len);1336if(patch->def_name && state->root.len) {1337char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1338free(patch->def_name);1339 patch->def_name = s;1340}13411342 line += len;1343 size -= len;1344 state_linenr++;1345for(offset = len ; size >0; offset += len, size -= len, line += len, state_linenr++) {1346static const struct opentry {1347const char*str;1348int(*fn)(struct apply_state *,const char*,struct patch *);1349} optable[] = {1350{"@@ -", gitdiff_hdrend },1351{"--- ", gitdiff_oldname },1352{"+++ ", gitdiff_newname },1353{"old mode ", gitdiff_oldmode },1354{"new mode ", gitdiff_newmode },1355{"deleted file mode ", gitdiff_delete },1356{"new file mode ", gitdiff_newfile },1357{"copy from ", gitdiff_copysrc },1358{"copy to ", gitdiff_copydst },1359{"rename old ", gitdiff_renamesrc },1360{"rename new ", gitdiff_renamedst },1361{"rename from ", gitdiff_renamesrc },1362{"rename to ", gitdiff_renamedst },1363{"similarity index ", gitdiff_similarity },1364{"dissimilarity index ", gitdiff_dissimilarity },1365{"index ", gitdiff_index },1366{"", gitdiff_unrecognized },1367};1368int i;13691370 len =linelen(line, size);1371if(!len || line[len-1] !='\n')1372break;1373for(i =0; i <ARRAY_SIZE(optable); i++) {1374const struct opentry *p = optable + i;1375int oplen =strlen(p->str);1376if(len < oplen ||memcmp(p->str, line, oplen))1377continue;1378if(p->fn(state, line + oplen, patch) <0)1379return offset;1380break;1381}1382}13831384return offset;1385}13861387static intparse_num(const char*line,unsigned long*p)1388{1389char*ptr;13901391if(!isdigit(*line))1392return0;1393*p =strtoul(line, &ptr,10);1394return ptr - line;1395}13961397static intparse_range(const char*line,int len,int offset,const char*expect,1398unsigned long*p1,unsigned long*p2)1399{1400int digits, ex;14011402if(offset <0|| offset >= len)1403return-1;1404 line += offset;1405 len -= offset;14061407 digits =parse_num(line, p1);1408if(!digits)1409return-1;14101411 offset += digits;1412 line += digits;1413 len -= digits;14141415*p2 =1;1416if(*line ==',') {1417 digits =parse_num(line+1, p2);1418if(!digits)1419return-1;14201421 offset += digits+1;1422 line += digits+1;1423 len -= digits+1;1424}14251426 ex =strlen(expect);1427if(ex > len)1428return-1;1429if(memcmp(line, expect, ex))1430return-1;14311432return offset + ex;1433}14341435static voidrecount_diff(const char*line,int size,struct fragment *fragment)1436{1437int oldlines =0, newlines =0, ret =0;14381439if(size <1) {1440warning("recount: ignore empty hunk");1441return;1442}14431444for(;;) {1445int len =linelen(line, size);1446 size -= len;1447 line += len;14481449if(size <1)1450break;14511452switch(*line) {1453case' ':case'\n':1454 newlines++;1455/* fall through */1456case'-':1457 oldlines++;1458continue;1459case'+':1460 newlines++;1461continue;1462case'\\':1463continue;1464case'@':1465 ret = size <3|| !starts_with(line,"@@ ");1466break;1467case'd':1468 ret = size <5|| !starts_with(line,"diff ");1469break;1470default:1471 ret = -1;1472break;1473}1474if(ret) {1475warning(_("recount: unexpected line: %.*s"),1476(int)linelen(line, size), line);1477return;1478}1479break;1480}1481 fragment->oldlines = oldlines;1482 fragment->newlines = newlines;1483}14841485/*1486 * Parse a unified diff fragment header of the1487 * form "@@ -a,b +c,d @@"1488 */1489static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1490{1491int offset;14921493if(!len || line[len-1] !='\n')1494return-1;14951496/* Figure out the number of lines in a fragment */1497 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1498 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14991500return offset;1501}15021503static intfind_header(struct apply_state *state,1504const char*line,1505unsigned long size,1506int*hdrsize,1507struct patch *patch)1508{1509unsigned long offset, len;15101511 patch->is_toplevel_relative =0;1512 patch->is_rename = patch->is_copy =0;1513 patch->is_new = patch->is_delete = -1;1514 patch->old_mode = patch->new_mode =0;1515 patch->old_name = patch->new_name = NULL;1516for(offset =0; size >0; offset += len, size -= len, line += len, state_linenr++) {1517unsigned long nextlen;15181519 len =linelen(line, size);1520if(!len)1521break;15221523/* Testing this early allows us to take a few shortcuts.. */1524if(len <6)1525continue;15261527/*1528 * Make sure we don't find any unconnected patch fragments.1529 * That's a sign that we didn't find a header, and that a1530 * patch has become corrupted/broken up.1531 */1532if(!memcmp("@@ -", line,4)) {1533struct fragment dummy;1534if(parse_fragment_header(line, len, &dummy) <0)1535continue;1536die(_("patch fragment without header at line%d: %.*s"),1537 state_linenr, (int)len-1, line);1538}15391540if(size < len +6)1541break;15421543/*1544 * Git patch? It might not have a real patch, just a rename1545 * or mode change, so we handle that specially1546 */1547if(!memcmp("diff --git ", line,11)) {1548int git_hdr_len =parse_git_header(state, line, len, size, patch);1549if(git_hdr_len <= len)1550continue;1551if(!patch->old_name && !patch->new_name) {1552if(!patch->def_name)1553die(Q_("git diff header lacks filename information when removing "1554"%dleading pathname component (line%d)",1555"git diff header lacks filename information when removing "1556"%dleading pathname components (line%d)",1557 state->p_value),1558 state->p_value, state_linenr);1559 patch->old_name =xstrdup(patch->def_name);1560 patch->new_name =xstrdup(patch->def_name);1561}1562if(!patch->is_delete && !patch->new_name)1563die("git diff header lacks filename information "1564"(line%d)", state_linenr);1565 patch->is_toplevel_relative =1;1566*hdrsize = git_hdr_len;1567return offset;1568}15691570/* --- followed by +++ ? */1571if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1572continue;15731574/*1575 * We only accept unified patches, so we want it to1576 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1577 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1578 */1579 nextlen =linelen(line + len, size - len);1580if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1581continue;15821583/* Ok, we'll consider it a patch */1584parse_traditional_patch(state, line, line+len, patch);1585*hdrsize = len + nextlen;1586 state_linenr +=2;1587return offset;1588}1589return-1;1590}15911592static voidrecord_ws_error(struct apply_state *state,1593unsigned result,1594const char*line,1595int len,1596int linenr)1597{1598char*err;15991600if(!result)1601return;16021603 state->whitespace_error++;1604if(state->squelch_whitespace_errors &&1605 state->squelch_whitespace_errors < state->whitespace_error)1606return;16071608 err =whitespace_error_string(result);1609fprintf(stderr,"%s:%d:%s.\n%.*s\n",1610 state->patch_input_file, linenr, err, len, line);1611free(err);1612}16131614static voidcheck_whitespace(struct apply_state *state,1615const char*line,1616int len,1617unsigned ws_rule)1618{1619unsigned result =ws_check(line +1, len -1, ws_rule);16201621record_ws_error(state, result, line +1, len -2, state_linenr);1622}16231624/*1625 * Parse a unified diff. Note that this really needs to parse each1626 * fragment separately, since the only way to know the difference1627 * between a "---" that is part of a patch, and a "---" that starts1628 * the next patch is to look at the line counts..1629 */1630static intparse_fragment(struct apply_state *state,1631const char*line,1632unsigned long size,1633struct patch *patch,1634struct fragment *fragment)1635{1636int added, deleted;1637int len =linelen(line, size), offset;1638unsigned long oldlines, newlines;1639unsigned long leading, trailing;16401641 offset =parse_fragment_header(line, len, fragment);1642if(offset <0)1643return-1;1644if(offset >0&& patch->recount)1645recount_diff(line + offset, size - offset, fragment);1646 oldlines = fragment->oldlines;1647 newlines = fragment->newlines;1648 leading =0;1649 trailing =0;16501651/* Parse the thing.. */1652 line += len;1653 size -= len;1654 state_linenr++;1655 added = deleted =0;1656for(offset = len;16570< size;1658 offset += len, size -= len, line += len, state_linenr++) {1659if(!oldlines && !newlines)1660break;1661 len =linelen(line, size);1662if(!len || line[len-1] !='\n')1663return-1;1664switch(*line) {1665default:1666return-1;1667case'\n':/* newer GNU diff, an empty context line */1668case' ':1669 oldlines--;1670 newlines--;1671if(!deleted && !added)1672 leading++;1673 trailing++;1674if(!state->apply_in_reverse &&1675 state->ws_error_action == correct_ws_error)1676check_whitespace(state, line, len, patch->ws_rule);1677break;1678case'-':1679if(state->apply_in_reverse &&1680 state->ws_error_action != nowarn_ws_error)1681check_whitespace(state, line, len, patch->ws_rule);1682 deleted++;1683 oldlines--;1684 trailing =0;1685break;1686case'+':1687if(!state->apply_in_reverse &&1688 state->ws_error_action != nowarn_ws_error)1689check_whitespace(state, line, len, patch->ws_rule);1690 added++;1691 newlines--;1692 trailing =0;1693break;16941695/*1696 * We allow "\ No newline at end of file". Depending1697 * on locale settings when the patch was produced we1698 * don't know what this line looks like. The only1699 * thing we do know is that it begins with "\ ".1700 * Checking for 12 is just for sanity check -- any1701 * l10n of "\ No newline..." is at least that long.1702 */1703case'\\':1704if(len <12||memcmp(line,"\\",2))1705return-1;1706break;1707}1708}1709if(oldlines || newlines)1710return-1;1711if(!deleted && !added)1712return-1;17131714 fragment->leading = leading;1715 fragment->trailing = trailing;17161717/*1718 * If a fragment ends with an incomplete line, we failed to include1719 * it in the above loop because we hit oldlines == newlines == 01720 * before seeing it.1721 */1722if(12< size && !memcmp(line,"\\",2))1723 offset +=linelen(line, size);17241725 patch->lines_added += added;1726 patch->lines_deleted += deleted;17271728if(0< patch->is_new && oldlines)1729returnerror(_("new file depends on old contents"));1730if(0< patch->is_delete && newlines)1731returnerror(_("deleted file still has contents"));1732return offset;1733}17341735/*1736 * We have seen "diff --git a/... b/..." header (or a traditional patch1737 * header). Read hunks that belong to this patch into fragments and hang1738 * them to the given patch structure.1739 *1740 * The (fragment->patch, fragment->size) pair points into the memory given1741 * by the caller, not a copy, when we return.1742 */1743static intparse_single_patch(struct apply_state *state,1744const char*line,1745unsigned long size,1746struct patch *patch)1747{1748unsigned long offset =0;1749unsigned long oldlines =0, newlines =0, context =0;1750struct fragment **fragp = &patch->fragments;17511752while(size >4&& !memcmp(line,"@@ -",4)) {1753struct fragment *fragment;1754int len;17551756 fragment =xcalloc(1,sizeof(*fragment));1757 fragment->linenr = state_linenr;1758 len =parse_fragment(state, line, size, patch, fragment);1759if(len <=0)1760die(_("corrupt patch at line%d"), state_linenr);1761 fragment->patch = line;1762 fragment->size = len;1763 oldlines += fragment->oldlines;1764 newlines += fragment->newlines;1765 context += fragment->leading + fragment->trailing;17661767*fragp = fragment;1768 fragp = &fragment->next;17691770 offset += len;1771 line += len;1772 size -= len;1773}17741775/*1776 * If something was removed (i.e. we have old-lines) it cannot1777 * be creation, and if something was added it cannot be1778 * deletion. However, the reverse is not true; --unified=01779 * patches that only add are not necessarily creation even1780 * though they do not have any old lines, and ones that only1781 * delete are not necessarily deletion.1782 *1783 * Unfortunately, a real creation/deletion patch do _not_ have1784 * any context line by definition, so we cannot safely tell it1785 * apart with --unified=0 insanity. At least if the patch has1786 * more than one hunk it is not creation or deletion.1787 */1788if(patch->is_new <0&&1789(oldlines || (patch->fragments && patch->fragments->next)))1790 patch->is_new =0;1791if(patch->is_delete <0&&1792(newlines || (patch->fragments && patch->fragments->next)))1793 patch->is_delete =0;17941795if(0< patch->is_new && oldlines)1796die(_("new file%sdepends on old contents"), patch->new_name);1797if(0< patch->is_delete && newlines)1798die(_("deleted file%sstill has contents"), patch->old_name);1799if(!patch->is_delete && !newlines && context)1800fprintf_ln(stderr,1801_("** warning: "1802"file%sbecomes empty but is not deleted"),1803 patch->new_name);18041805return offset;1806}18071808staticinlineintmetadata_changes(struct patch *patch)1809{1810return patch->is_rename >0||1811 patch->is_copy >0||1812 patch->is_new >0||1813 patch->is_delete ||1814(patch->old_mode && patch->new_mode &&1815 patch->old_mode != patch->new_mode);1816}18171818static char*inflate_it(const void*data,unsigned long size,1819unsigned long inflated_size)1820{1821 git_zstream stream;1822void*out;1823int st;18241825memset(&stream,0,sizeof(stream));18261827 stream.next_in = (unsigned char*)data;1828 stream.avail_in = size;1829 stream.next_out = out =xmalloc(inflated_size);1830 stream.avail_out = inflated_size;1831git_inflate_init(&stream);1832 st =git_inflate(&stream, Z_FINISH);1833git_inflate_end(&stream);1834if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1835free(out);1836return NULL;1837}1838return out;1839}18401841/*1842 * Read a binary hunk and return a new fragment; fragment->patch1843 * points at an allocated memory that the caller must free, so1844 * it is marked as "->free_patch = 1".1845 */1846static struct fragment *parse_binary_hunk(char**buf_p,1847unsigned long*sz_p,1848int*status_p,1849int*used_p)1850{1851/*1852 * Expect a line that begins with binary patch method ("literal"1853 * or "delta"), followed by the length of data before deflating.1854 * a sequence of 'length-byte' followed by base-85 encoded data1855 * should follow, terminated by a newline.1856 *1857 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1858 * and we would limit the patch line to 66 characters,1859 * so one line can fit up to 13 groups that would decode1860 * to 52 bytes max. The length byte 'A'-'Z' corresponds1861 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1862 */1863int llen, used;1864unsigned long size = *sz_p;1865char*buffer = *buf_p;1866int patch_method;1867unsigned long origlen;1868char*data = NULL;1869int hunk_size =0;1870struct fragment *frag;18711872 llen =linelen(buffer, size);1873 used = llen;18741875*status_p =0;18761877if(starts_with(buffer,"delta ")) {1878 patch_method = BINARY_DELTA_DEFLATED;1879 origlen =strtoul(buffer +6, NULL,10);1880}1881else if(starts_with(buffer,"literal ")) {1882 patch_method = BINARY_LITERAL_DEFLATED;1883 origlen =strtoul(buffer +8, NULL,10);1884}1885else1886return NULL;18871888 state_linenr++;1889 buffer += llen;1890while(1) {1891int byte_length, max_byte_length, newsize;1892 llen =linelen(buffer, size);1893 used += llen;1894 state_linenr++;1895if(llen ==1) {1896/* consume the blank line */1897 buffer++;1898 size--;1899break;1900}1901/*1902 * Minimum line is "A00000\n" which is 7-byte long,1903 * and the line length must be multiple of 5 plus 2.1904 */1905if((llen <7) || (llen-2) %5)1906goto corrupt;1907 max_byte_length = (llen -2) /5*4;1908 byte_length = *buffer;1909if('A'<= byte_length && byte_length <='Z')1910 byte_length = byte_length -'A'+1;1911else if('a'<= byte_length && byte_length <='z')1912 byte_length = byte_length -'a'+27;1913else1914goto corrupt;1915/* if the input length was not multiple of 4, we would1916 * have filler at the end but the filler should never1917 * exceed 3 bytes1918 */1919if(max_byte_length < byte_length ||1920 byte_length <= max_byte_length -4)1921goto corrupt;1922 newsize = hunk_size + byte_length;1923 data =xrealloc(data, newsize);1924if(decode_85(data + hunk_size, buffer +1, byte_length))1925goto corrupt;1926 hunk_size = newsize;1927 buffer += llen;1928 size -= llen;1929}19301931 frag =xcalloc(1,sizeof(*frag));1932 frag->patch =inflate_it(data, hunk_size, origlen);1933 frag->free_patch =1;1934if(!frag->patch)1935goto corrupt;1936free(data);1937 frag->size = origlen;1938*buf_p = buffer;1939*sz_p = size;1940*used_p = used;1941 frag->binary_patch_method = patch_method;1942return frag;19431944 corrupt:1945free(data);1946*status_p = -1;1947error(_("corrupt binary patch at line%d: %.*s"),1948 state_linenr-1, llen-1, buffer);1949return NULL;1950}19511952/*1953 * Returns:1954 * -1 in case of error,1955 * the length of the parsed binary patch otherwise1956 */1957static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1958{1959/*1960 * We have read "GIT binary patch\n"; what follows is a line1961 * that says the patch method (currently, either "literal" or1962 * "delta") and the length of data before deflating; a1963 * sequence of 'length-byte' followed by base-85 encoded data1964 * follows.1965 *1966 * When a binary patch is reversible, there is another binary1967 * hunk in the same format, starting with patch method (either1968 * "literal" or "delta") with the length of data, and a sequence1969 * of length-byte + base-85 encoded data, terminated with another1970 * empty line. This data, when applied to the postimage, produces1971 * the preimage.1972 */1973struct fragment *forward;1974struct fragment *reverse;1975int status;1976int used, used_1;19771978 forward =parse_binary_hunk(&buffer, &size, &status, &used);1979if(!forward && !status)1980/* there has to be one hunk (forward hunk) */1981returnerror(_("unrecognized binary patch at line%d"), state_linenr-1);1982if(status)1983/* otherwise we already gave an error message */1984return status;19851986 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1987if(reverse)1988 used += used_1;1989else if(status) {1990/*1991 * Not having reverse hunk is not an error, but having1992 * a corrupt reverse hunk is.1993 */1994free((void*) forward->patch);1995free(forward);1996return status;1997}1998 forward->next = reverse;1999 patch->fragments = forward;2000 patch->is_binary =1;2001return used;2002}20032004static voidprefix_one(struct apply_state *state,char**name)2005{2006char*old_name = *name;2007if(!old_name)2008return;2009*name =xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));2010free(old_name);2011}20122013static voidprefix_patch(struct apply_state *state,struct patch *p)2014{2015if(!state->prefix || p->is_toplevel_relative)2016return;2017prefix_one(state, &p->new_name);2018prefix_one(state, &p->old_name);2019}20202021/*2022 * include/exclude2023 */20242025static voidadd_name_limit(struct apply_state *state,2026const char*name,2027int exclude)2028{2029struct string_list_item *it;20302031 it =string_list_append(&state->limit_by_name, name);2032 it->util = exclude ? NULL : (void*)1;2033}20342035static intuse_patch(struct apply_state *state,struct patch *p)2036{2037const char*pathname = p->new_name ? p->new_name : p->old_name;2038int i;20392040/* Paths outside are not touched regardless of "--include" */2041if(0< state->prefix_length) {2042int pathlen =strlen(pathname);2043if(pathlen <= state->prefix_length ||2044memcmp(state->prefix, pathname, state->prefix_length))2045return0;2046}20472048/* See if it matches any of exclude/include rule */2049for(i =0; i < state->limit_by_name.nr; i++) {2050struct string_list_item *it = &state->limit_by_name.items[i];2051if(!wildmatch(it->string, pathname,0, NULL))2052return(it->util != NULL);2053}20542055/*2056 * If we had any include, a path that does not match any rule is2057 * not used. Otherwise, we saw bunch of exclude rules (or none)2058 * and such a path is used.2059 */2060return!state->has_include;2061}206220632064/*2065 * Read the patch text in "buffer" that extends for "size" bytes; stop2066 * reading after seeing a single patch (i.e. changes to a single file).2067 * Create fragments (i.e. patch hunks) and hang them to the given patch.2068 * Return the number of bytes consumed, so that the caller can call us2069 * again for the next patch.2070 */2071static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2072{2073int hdrsize, patchsize;2074int offset =find_header(state, buffer, size, &hdrsize, patch);20752076if(offset <0)2077return offset;20782079prefix_patch(state, patch);20802081if(!use_patch(state, patch))2082 patch->ws_rule =0;2083else2084 patch->ws_rule =whitespace_rule(patch->new_name2085? patch->new_name2086: patch->old_name);20872088 patchsize =parse_single_patch(state,2089 buffer + offset + hdrsize,2090 size - offset - hdrsize,2091 patch);20922093if(!patchsize) {2094static const char git_binary[] ="GIT binary patch\n";2095int hd = hdrsize + offset;2096unsigned long llen =linelen(buffer + hd, size - hd);20972098if(llen ==sizeof(git_binary) -1&&2099!memcmp(git_binary, buffer + hd, llen)) {2100int used;2101 state_linenr++;2102 used =parse_binary(buffer + hd + llen,2103 size - hd - llen, patch);2104if(used <0)2105return-1;2106if(used)2107 patchsize = used + llen;2108else2109 patchsize =0;2110}2111else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2112static const char*binhdr[] = {2113"Binary files ",2114"Files ",2115 NULL,2116};2117int i;2118for(i =0; binhdr[i]; i++) {2119int len =strlen(binhdr[i]);2120if(len < size - hd &&2121!memcmp(binhdr[i], buffer + hd, len)) {2122 state_linenr++;2123 patch->is_binary =1;2124 patchsize = llen;2125break;2126}2127}2128}21292130/* Empty patch cannot be applied if it is a text patch2131 * without metadata change. A binary patch appears2132 * empty to us here.2133 */2134if((state->apply || state->check) &&2135(!patch->is_binary && !metadata_changes(patch)))2136die(_("patch with only garbage at line%d"), state_linenr);2137}21382139return offset + hdrsize + patchsize;2140}21412142#define swap(a,b) myswap((a),(b),sizeof(a))21432144#define myswap(a, b, size) do { \2145 unsigned char mytmp[size]; \2146 memcpy(mytmp, &a, size); \2147 memcpy(&a, &b, size); \2148 memcpy(&b, mytmp, size); \2149} while (0)21502151static voidreverse_patches(struct patch *p)2152{2153for(; p; p = p->next) {2154struct fragment *frag = p->fragments;21552156swap(p->new_name, p->old_name);2157swap(p->new_mode, p->old_mode);2158swap(p->is_new, p->is_delete);2159swap(p->lines_added, p->lines_deleted);2160swap(p->old_sha1_prefix, p->new_sha1_prefix);21612162for(; frag; frag = frag->next) {2163swap(frag->newpos, frag->oldpos);2164swap(frag->newlines, frag->oldlines);2165}2166}2167}21682169static const char pluses[] =2170"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2171static const char minuses[]=2172"----------------------------------------------------------------------";21732174static voidshow_stats(struct patch *patch)2175{2176struct strbuf qname = STRBUF_INIT;2177char*cp = patch->new_name ? patch->new_name : patch->old_name;2178int max, add, del;21792180quote_c_style(cp, &qname, NULL,0);21812182/*2183 * "scale" the filename2184 */2185 max = max_len;2186if(max >50)2187 max =50;21882189if(qname.len > max) {2190 cp =strchr(qname.buf + qname.len +3- max,'/');2191if(!cp)2192 cp = qname.buf + qname.len +3- max;2193strbuf_splice(&qname,0, cp - qname.buf,"...",3);2194}21952196if(patch->is_binary) {2197printf(" %-*s | Bin\n", max, qname.buf);2198strbuf_release(&qname);2199return;2200}22012202printf(" %-*s |", max, qname.buf);2203strbuf_release(&qname);22042205/*2206 * scale the add/delete2207 */2208 max = max + max_change >70?70- max : max_change;2209 add = patch->lines_added;2210 del = patch->lines_deleted;22112212if(max_change >0) {2213int total = ((add + del) * max + max_change /2) / max_change;2214 add = (add * max + max_change /2) / max_change;2215 del = total - add;2216}2217printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2218 add, pluses, del, minuses);2219}22202221static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2222{2223switch(st->st_mode & S_IFMT) {2224case S_IFLNK:2225if(strbuf_readlink(buf, path, st->st_size) <0)2226returnerror(_("unable to read symlink%s"), path);2227return0;2228case S_IFREG:2229if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2230returnerror(_("unable to open or read%s"), path);2231convert_to_git(path, buf->buf, buf->len, buf,0);2232return0;2233default:2234return-1;2235}2236}22372238/*2239 * Update the preimage, and the common lines in postimage,2240 * from buffer buf of length len. If postlen is 0 the postimage2241 * is updated in place, otherwise it's updated on a new buffer2242 * of length postlen2243 */22442245static voidupdate_pre_post_images(struct image *preimage,2246struct image *postimage,2247char*buf,2248size_t len,size_t postlen)2249{2250int i, ctx, reduced;2251char*new, *old, *fixed;2252struct image fixed_preimage;22532254/*2255 * Update the preimage with whitespace fixes. Note that we2256 * are not losing preimage->buf -- apply_one_fragment() will2257 * free "oldlines".2258 */2259prepare_image(&fixed_preimage, buf, len,1);2260assert(postlen2261? fixed_preimage.nr == preimage->nr2262: fixed_preimage.nr <= preimage->nr);2263for(i =0; i < fixed_preimage.nr; i++)2264 fixed_preimage.line[i].flag = preimage->line[i].flag;2265free(preimage->line_allocated);2266*preimage = fixed_preimage;22672268/*2269 * Adjust the common context lines in postimage. This can be2270 * done in-place when we are shrinking it with whitespace2271 * fixing, but needs a new buffer when ignoring whitespace or2272 * expanding leading tabs to spaces.2273 *2274 * We trust the caller to tell us if the update can be done2275 * in place (postlen==0) or not.2276 */2277 old = postimage->buf;2278if(postlen)2279new= postimage->buf =xmalloc(postlen);2280else2281new= old;2282 fixed = preimage->buf;22832284for(i = reduced = ctx =0; i < postimage->nr; i++) {2285size_t l_len = postimage->line[i].len;2286if(!(postimage->line[i].flag & LINE_COMMON)) {2287/* an added line -- no counterparts in preimage */2288memmove(new, old, l_len);2289 old += l_len;2290new+= l_len;2291continue;2292}22932294/* a common context -- skip it in the original postimage */2295 old += l_len;22962297/* and find the corresponding one in the fixed preimage */2298while(ctx < preimage->nr &&2299!(preimage->line[ctx].flag & LINE_COMMON)) {2300 fixed += preimage->line[ctx].len;2301 ctx++;2302}23032304/*2305 * preimage is expected to run out, if the caller2306 * fixed addition of trailing blank lines.2307 */2308if(preimage->nr <= ctx) {2309 reduced++;2310continue;2311}23122313/* and copy it in, while fixing the line length */2314 l_len = preimage->line[ctx].len;2315memcpy(new, fixed, l_len);2316new+= l_len;2317 fixed += l_len;2318 postimage->line[i].len = l_len;2319 ctx++;2320}23212322if(postlen2323? postlen <new- postimage->buf2324: postimage->len <new- postimage->buf)2325die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2326(int)postlen, (int) postimage->len, (int)(new- postimage->buf));23272328/* Fix the length of the whole thing */2329 postimage->len =new- postimage->buf;2330 postimage->nr -= reduced;2331}23322333static intline_by_line_fuzzy_match(struct image *img,2334struct image *preimage,2335struct image *postimage,2336unsigned longtry,2337int try_lno,2338int preimage_limit)2339{2340int i;2341size_t imgoff =0;2342size_t preoff =0;2343size_t postlen = postimage->len;2344size_t extra_chars;2345char*buf;2346char*preimage_eof;2347char*preimage_end;2348struct strbuf fixed;2349char*fixed_buf;2350size_t fixed_len;23512352for(i =0; i < preimage_limit; i++) {2353size_t prelen = preimage->line[i].len;2354size_t imglen = img->line[try_lno+i].len;23552356if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2357 preimage->buf + preoff, prelen))2358return0;2359if(preimage->line[i].flag & LINE_COMMON)2360 postlen += imglen - prelen;2361 imgoff += imglen;2362 preoff += prelen;2363}23642365/*2366 * Ok, the preimage matches with whitespace fuzz.2367 *2368 * imgoff now holds the true length of the target that2369 * matches the preimage before the end of the file.2370 *2371 * Count the number of characters in the preimage that fall2372 * beyond the end of the file and make sure that all of them2373 * are whitespace characters. (This can only happen if2374 * we are removing blank lines at the end of the file.)2375 */2376 buf = preimage_eof = preimage->buf + preoff;2377for( ; i < preimage->nr; i++)2378 preoff += preimage->line[i].len;2379 preimage_end = preimage->buf + preoff;2380for( ; buf < preimage_end; buf++)2381if(!isspace(*buf))2382return0;23832384/*2385 * Update the preimage and the common postimage context2386 * lines to use the same whitespace as the target.2387 * If whitespace is missing in the target (i.e.2388 * if the preimage extends beyond the end of the file),2389 * use the whitespace from the preimage.2390 */2391 extra_chars = preimage_end - preimage_eof;2392strbuf_init(&fixed, imgoff + extra_chars);2393strbuf_add(&fixed, img->buf +try, imgoff);2394strbuf_add(&fixed, preimage_eof, extra_chars);2395 fixed_buf =strbuf_detach(&fixed, &fixed_len);2396update_pre_post_images(preimage, postimage,2397 fixed_buf, fixed_len, postlen);2398return1;2399}24002401static intmatch_fragment(struct apply_state *state,2402struct image *img,2403struct image *preimage,2404struct image *postimage,2405unsigned longtry,2406int try_lno,2407unsigned ws_rule,2408int match_beginning,int match_end)2409{2410int i;2411char*fixed_buf, *buf, *orig, *target;2412struct strbuf fixed;2413size_t fixed_len, postlen;2414int preimage_limit;24152416if(preimage->nr + try_lno <= img->nr) {2417/*2418 * The hunk falls within the boundaries of img.2419 */2420 preimage_limit = preimage->nr;2421if(match_end && (preimage->nr + try_lno != img->nr))2422return0;2423}else if(state->ws_error_action == correct_ws_error &&2424(ws_rule & WS_BLANK_AT_EOF)) {2425/*2426 * This hunk extends beyond the end of img, and we are2427 * removing blank lines at the end of the file. This2428 * many lines from the beginning of the preimage must2429 * match with img, and the remainder of the preimage2430 * must be blank.2431 */2432 preimage_limit = img->nr - try_lno;2433}else{2434/*2435 * The hunk extends beyond the end of the img and2436 * we are not removing blanks at the end, so we2437 * should reject the hunk at this position.2438 */2439return0;2440}24412442if(match_beginning && try_lno)2443return0;24442445/* Quick hash check */2446for(i =0; i < preimage_limit; i++)2447if((img->line[try_lno + i].flag & LINE_PATCHED) ||2448(preimage->line[i].hash != img->line[try_lno + i].hash))2449return0;24502451if(preimage_limit == preimage->nr) {2452/*2453 * Do we have an exact match? If we were told to match2454 * at the end, size must be exactly at try+fragsize,2455 * otherwise try+fragsize must be still within the preimage,2456 * and either case, the old piece should match the preimage2457 * exactly.2458 */2459if((match_end2460? (try+ preimage->len == img->len)2461: (try+ preimage->len <= img->len)) &&2462!memcmp(img->buf +try, preimage->buf, preimage->len))2463return1;2464}else{2465/*2466 * The preimage extends beyond the end of img, so2467 * there cannot be an exact match.2468 *2469 * There must be one non-blank context line that match2470 * a line before the end of img.2471 */2472char*buf_end;24732474 buf = preimage->buf;2475 buf_end = buf;2476for(i =0; i < preimage_limit; i++)2477 buf_end += preimage->line[i].len;24782479for( ; buf < buf_end; buf++)2480if(!isspace(*buf))2481break;2482if(buf == buf_end)2483return0;2484}24852486/*2487 * No exact match. If we are ignoring whitespace, run a line-by-line2488 * fuzzy matching. We collect all the line length information because2489 * we need it to adjust whitespace if we match.2490 */2491if(ws_ignore_action == ignore_ws_change)2492returnline_by_line_fuzzy_match(img, preimage, postimage,2493try, try_lno, preimage_limit);24942495if(state->ws_error_action != correct_ws_error)2496return0;24972498/*2499 * The hunk does not apply byte-by-byte, but the hash says2500 * it might with whitespace fuzz. We weren't asked to2501 * ignore whitespace, we were asked to correct whitespace2502 * errors, so let's try matching after whitespace correction.2503 *2504 * While checking the preimage against the target, whitespace2505 * errors in both fixed, we count how large the corresponding2506 * postimage needs to be. The postimage prepared by2507 * apply_one_fragment() has whitespace errors fixed on added2508 * lines already, but the common lines were propagated as-is,2509 * which may become longer when their whitespace errors are2510 * fixed.2511 */25122513/* First count added lines in postimage */2514 postlen =0;2515for(i =0; i < postimage->nr; i++) {2516if(!(postimage->line[i].flag & LINE_COMMON))2517 postlen += postimage->line[i].len;2518}25192520/*2521 * The preimage may extend beyond the end of the file,2522 * but in this loop we will only handle the part of the2523 * preimage that falls within the file.2524 */2525strbuf_init(&fixed, preimage->len +1);2526 orig = preimage->buf;2527 target = img->buf +try;2528for(i =0; i < preimage_limit; i++) {2529size_t oldlen = preimage->line[i].len;2530size_t tgtlen = img->line[try_lno + i].len;2531size_t fixstart = fixed.len;2532struct strbuf tgtfix;2533int match;25342535/* Try fixing the line in the preimage */2536ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25372538/* Try fixing the line in the target */2539strbuf_init(&tgtfix, tgtlen);2540ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);25412542/*2543 * If they match, either the preimage was based on2544 * a version before our tree fixed whitespace breakage,2545 * or we are lacking a whitespace-fix patch the tree2546 * the preimage was based on already had (i.e. target2547 * has whitespace breakage, the preimage doesn't).2548 * In either case, we are fixing the whitespace breakages2549 * so we might as well take the fix together with their2550 * real change.2551 */2552 match = (tgtfix.len == fixed.len - fixstart &&2553!memcmp(tgtfix.buf, fixed.buf + fixstart,2554 fixed.len - fixstart));25552556/* Add the length if this is common with the postimage */2557if(preimage->line[i].flag & LINE_COMMON)2558 postlen += tgtfix.len;25592560strbuf_release(&tgtfix);2561if(!match)2562goto unmatch_exit;25632564 orig += oldlen;2565 target += tgtlen;2566}256725682569/*2570 * Now handle the lines in the preimage that falls beyond the2571 * end of the file (if any). They will only match if they are2572 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2573 * false).2574 */2575for( ; i < preimage->nr; i++) {2576size_t fixstart = fixed.len;/* start of the fixed preimage */2577size_t oldlen = preimage->line[i].len;2578int j;25792580/* Try fixing the line in the preimage */2581ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25822583for(j = fixstart; j < fixed.len; j++)2584if(!isspace(fixed.buf[j]))2585goto unmatch_exit;25862587 orig += oldlen;2588}25892590/*2591 * Yes, the preimage is based on an older version that still2592 * has whitespace breakages unfixed, and fixing them makes the2593 * hunk match. Update the context lines in the postimage.2594 */2595 fixed_buf =strbuf_detach(&fixed, &fixed_len);2596if(postlen < postimage->len)2597 postlen =0;2598update_pre_post_images(preimage, postimage,2599 fixed_buf, fixed_len, postlen);2600return1;26012602 unmatch_exit:2603strbuf_release(&fixed);2604return0;2605}26062607static intfind_pos(struct apply_state *state,2608struct image *img,2609struct image *preimage,2610struct image *postimage,2611int line,2612unsigned ws_rule,2613int match_beginning,int match_end)2614{2615int i;2616unsigned long backwards, forwards,try;2617int backwards_lno, forwards_lno, try_lno;26182619/*2620 * If match_beginning or match_end is specified, there is no2621 * point starting from a wrong line that will never match and2622 * wander around and wait for a match at the specified end.2623 */2624if(match_beginning)2625 line =0;2626else if(match_end)2627 line = img->nr - preimage->nr;26282629/*2630 * Because the comparison is unsigned, the following test2631 * will also take care of a negative line number that can2632 * result when match_end and preimage is larger than the target.2633 */2634if((size_t) line > img->nr)2635 line = img->nr;26362637try=0;2638for(i =0; i < line; i++)2639try+= img->line[i].len;26402641/*2642 * There's probably some smart way to do this, but I'll leave2643 * that to the smart and beautiful people. I'm simple and stupid.2644 */2645 backwards =try;2646 backwards_lno = line;2647 forwards =try;2648 forwards_lno = line;2649 try_lno = line;26502651for(i =0; ; i++) {2652if(match_fragment(state, img, preimage, postimage,2653try, try_lno, ws_rule,2654 match_beginning, match_end))2655return try_lno;26562657 again:2658if(backwards_lno ==0&& forwards_lno == img->nr)2659break;26602661if(i &1) {2662if(backwards_lno ==0) {2663 i++;2664goto again;2665}2666 backwards_lno--;2667 backwards -= img->line[backwards_lno].len;2668try= backwards;2669 try_lno = backwards_lno;2670}else{2671if(forwards_lno == img->nr) {2672 i++;2673goto again;2674}2675 forwards += img->line[forwards_lno].len;2676 forwards_lno++;2677try= forwards;2678 try_lno = forwards_lno;2679}26802681}2682return-1;2683}26842685static voidremove_first_line(struct image *img)2686{2687 img->buf += img->line[0].len;2688 img->len -= img->line[0].len;2689 img->line++;2690 img->nr--;2691}26922693static voidremove_last_line(struct image *img)2694{2695 img->len -= img->line[--img->nr].len;2696}26972698/*2699 * The change from "preimage" and "postimage" has been found to2700 * apply at applied_pos (counts in line numbers) in "img".2701 * Update "img" to remove "preimage" and replace it with "postimage".2702 */2703static voidupdate_image(struct apply_state *state,2704struct image *img,2705int applied_pos,2706struct image *preimage,2707struct image *postimage)2708{2709/*2710 * remove the copy of preimage at offset in img2711 * and replace it with postimage2712 */2713int i, nr;2714size_t remove_count, insert_count, applied_at =0;2715char*result;2716int preimage_limit;27172718/*2719 * If we are removing blank lines at the end of img,2720 * the preimage may extend beyond the end.2721 * If that is the case, we must be careful only to2722 * remove the part of the preimage that falls within2723 * the boundaries of img. Initialize preimage_limit2724 * to the number of lines in the preimage that falls2725 * within the boundaries.2726 */2727 preimage_limit = preimage->nr;2728if(preimage_limit > img->nr - applied_pos)2729 preimage_limit = img->nr - applied_pos;27302731for(i =0; i < applied_pos; i++)2732 applied_at += img->line[i].len;27332734 remove_count =0;2735for(i =0; i < preimage_limit; i++)2736 remove_count += img->line[applied_pos + i].len;2737 insert_count = postimage->len;27382739/* Adjust the contents */2740 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2741memcpy(result, img->buf, applied_at);2742memcpy(result + applied_at, postimage->buf, postimage->len);2743memcpy(result + applied_at + postimage->len,2744 img->buf + (applied_at + remove_count),2745 img->len - (applied_at + remove_count));2746free(img->buf);2747 img->buf = result;2748 img->len += insert_count - remove_count;2749 result[img->len] ='\0';27502751/* Adjust the line table */2752 nr = img->nr + postimage->nr - preimage_limit;2753if(preimage_limit < postimage->nr) {2754/*2755 * NOTE: this knows that we never call remove_first_line()2756 * on anything other than pre/post image.2757 */2758REALLOC_ARRAY(img->line, nr);2759 img->line_allocated = img->line;2760}2761if(preimage_limit != postimage->nr)2762memmove(img->line + applied_pos + postimage->nr,2763 img->line + applied_pos + preimage_limit,2764(img->nr - (applied_pos + preimage_limit)) *2765sizeof(*img->line));2766memcpy(img->line + applied_pos,2767 postimage->line,2768 postimage->nr *sizeof(*img->line));2769if(!state->allow_overlap)2770for(i =0; i < postimage->nr; i++)2771 img->line[applied_pos + i].flag |= LINE_PATCHED;2772 img->nr = nr;2773}27742775/*2776 * Use the patch-hunk text in "frag" to prepare two images (preimage and2777 * postimage) for the hunk. Find lines that match "preimage" in "img" and2778 * replace the part of "img" with "postimage" text.2779 */2780static intapply_one_fragment(struct apply_state *state,2781struct image *img,struct fragment *frag,2782int inaccurate_eof,unsigned ws_rule,2783int nth_fragment)2784{2785int match_beginning, match_end;2786const char*patch = frag->patch;2787int size = frag->size;2788char*old, *oldlines;2789struct strbuf newlines;2790int new_blank_lines_at_end =0;2791int found_new_blank_lines_at_end =0;2792int hunk_linenr = frag->linenr;2793unsigned long leading, trailing;2794int pos, applied_pos;2795struct image preimage;2796struct image postimage;27972798memset(&preimage,0,sizeof(preimage));2799memset(&postimage,0,sizeof(postimage));2800 oldlines =xmalloc(size);2801strbuf_init(&newlines, size);28022803 old = oldlines;2804while(size >0) {2805char first;2806int len =linelen(patch, size);2807int plen;2808int added_blank_line =0;2809int is_blank_context =0;2810size_t start;28112812if(!len)2813break;28142815/*2816 * "plen" is how much of the line we should use for2817 * the actual patch data. Normally we just remove the2818 * first character on the line, but if the line is2819 * followed by "\ No newline", then we also remove the2820 * last one (which is the newline, of course).2821 */2822 plen = len -1;2823if(len < size && patch[len] =='\\')2824 plen--;2825 first = *patch;2826if(state->apply_in_reverse) {2827if(first =='-')2828 first ='+';2829else if(first =='+')2830 first ='-';2831}28322833switch(first) {2834case'\n':2835/* Newer GNU diff, empty context line */2836if(plen <0)2837/* ... followed by '\No newline'; nothing */2838break;2839*old++ ='\n';2840strbuf_addch(&newlines,'\n');2841add_line_info(&preimage,"\n",1, LINE_COMMON);2842add_line_info(&postimage,"\n",1, LINE_COMMON);2843 is_blank_context =1;2844break;2845case' ':2846if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2847ws_blank_line(patch +1, plen, ws_rule))2848 is_blank_context =1;2849case'-':2850memcpy(old, patch +1, plen);2851add_line_info(&preimage, old, plen,2852(first ==' '? LINE_COMMON :0));2853 old += plen;2854if(first =='-')2855break;2856/* Fall-through for ' ' */2857case'+':2858/* --no-add does not add new lines */2859if(first =='+'&& state->no_add)2860break;28612862 start = newlines.len;2863if(first !='+'||2864!state->whitespace_error ||2865 state->ws_error_action != correct_ws_error) {2866strbuf_add(&newlines, patch +1, plen);2867}2868else{2869ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2870}2871add_line_info(&postimage, newlines.buf + start, newlines.len - start,2872(first =='+'?0: LINE_COMMON));2873if(first =='+'&&2874(ws_rule & WS_BLANK_AT_EOF) &&2875ws_blank_line(patch +1, plen, ws_rule))2876 added_blank_line =1;2877break;2878case'@':case'\\':2879/* Ignore it, we already handled it */2880break;2881default:2882if(state->apply_verbosely)2883error(_("invalid start of line: '%c'"), first);2884 applied_pos = -1;2885goto out;2886}2887if(added_blank_line) {2888if(!new_blank_lines_at_end)2889 found_new_blank_lines_at_end = hunk_linenr;2890 new_blank_lines_at_end++;2891}2892else if(is_blank_context)2893;2894else2895 new_blank_lines_at_end =0;2896 patch += len;2897 size -= len;2898 hunk_linenr++;2899}2900if(inaccurate_eof &&2901 old > oldlines && old[-1] =='\n'&&2902 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2903 old--;2904strbuf_setlen(&newlines, newlines.len -1);2905}29062907 leading = frag->leading;2908 trailing = frag->trailing;29092910/*2911 * A hunk to change lines at the beginning would begin with2912 * @@ -1,L +N,M @@2913 * but we need to be careful. -U0 that inserts before the second2914 * line also has this pattern.2915 *2916 * And a hunk to add to an empty file would begin with2917 * @@ -0,0 +N,M @@2918 *2919 * In other words, a hunk that is (frag->oldpos <= 1) with or2920 * without leading context must match at the beginning.2921 */2922 match_beginning = (!frag->oldpos ||2923(frag->oldpos ==1&& !state->unidiff_zero));29242925/*2926 * A hunk without trailing lines must match at the end.2927 * However, we simply cannot tell if a hunk must match end2928 * from the lack of trailing lines if the patch was generated2929 * with unidiff without any context.2930 */2931 match_end = !state->unidiff_zero && !trailing;29322933 pos = frag->newpos ? (frag->newpos -1) :0;2934 preimage.buf = oldlines;2935 preimage.len = old - oldlines;2936 postimage.buf = newlines.buf;2937 postimage.len = newlines.len;2938 preimage.line = preimage.line_allocated;2939 postimage.line = postimage.line_allocated;29402941for(;;) {29422943 applied_pos =find_pos(state, img, &preimage, &postimage, pos,2944 ws_rule, match_beginning, match_end);29452946if(applied_pos >=0)2947break;29482949/* Am I at my context limits? */2950if((leading <= state->p_context) && (trailing <= state->p_context))2951break;2952if(match_beginning || match_end) {2953 match_beginning = match_end =0;2954continue;2955}29562957/*2958 * Reduce the number of context lines; reduce both2959 * leading and trailing if they are equal otherwise2960 * just reduce the larger context.2961 */2962if(leading >= trailing) {2963remove_first_line(&preimage);2964remove_first_line(&postimage);2965 pos--;2966 leading--;2967}2968if(trailing > leading) {2969remove_last_line(&preimage);2970remove_last_line(&postimage);2971 trailing--;2972}2973}29742975if(applied_pos >=0) {2976if(new_blank_lines_at_end &&2977 preimage.nr + applied_pos >= img->nr &&2978(ws_rule & WS_BLANK_AT_EOF) &&2979 state->ws_error_action != nowarn_ws_error) {2980record_ws_error(state, WS_BLANK_AT_EOF,"+",1,2981 found_new_blank_lines_at_end);2982if(state->ws_error_action == correct_ws_error) {2983while(new_blank_lines_at_end--)2984remove_last_line(&postimage);2985}2986/*2987 * We would want to prevent write_out_results()2988 * from taking place in apply_patch() that follows2989 * the callchain led us here, which is:2990 * apply_patch->check_patch_list->check_patch->2991 * apply_data->apply_fragments->apply_one_fragment2992 */2993if(state->ws_error_action == die_on_ws_error)2994 state->apply =0;2995}29962997if(state->apply_verbosely && applied_pos != pos) {2998int offset = applied_pos - pos;2999if(state->apply_in_reverse)3000 offset =0- offset;3001fprintf_ln(stderr,3002Q_("Hunk #%dsucceeded at%d(offset%dline).",3003"Hunk #%dsucceeded at%d(offset%dlines).",3004 offset),3005 nth_fragment, applied_pos +1, offset);3006}30073008/*3009 * Warn if it was necessary to reduce the number3010 * of context lines.3011 */3012if((leading != frag->leading) ||3013(trailing != frag->trailing))3014fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"3015" to apply fragment at%d"),3016 leading, trailing, applied_pos+1);3017update_image(state, img, applied_pos, &preimage, &postimage);3018}else{3019if(state->apply_verbosely)3020error(_("while searching for:\n%.*s"),3021(int)(old - oldlines), oldlines);3022}30233024out:3025free(oldlines);3026strbuf_release(&newlines);3027free(preimage.line_allocated);3028free(postimage.line_allocated);30293030return(applied_pos <0);3031}30323033static intapply_binary_fragment(struct apply_state *state,3034struct image *img,3035struct patch *patch)3036{3037struct fragment *fragment = patch->fragments;3038unsigned long len;3039void*dst;30403041if(!fragment)3042returnerror(_("missing binary patch data for '%s'"),3043 patch->new_name ?3044 patch->new_name :3045 patch->old_name);30463047/* Binary patch is irreversible without the optional second hunk */3048if(state->apply_in_reverse) {3049if(!fragment->next)3050returnerror("cannot reverse-apply a binary patch "3051"without the reverse hunk to '%s'",3052 patch->new_name3053? patch->new_name : patch->old_name);3054 fragment = fragment->next;3055}3056switch(fragment->binary_patch_method) {3057case BINARY_DELTA_DEFLATED:3058 dst =patch_delta(img->buf, img->len, fragment->patch,3059 fragment->size, &len);3060if(!dst)3061return-1;3062clear_image(img);3063 img->buf = dst;3064 img->len = len;3065return0;3066case BINARY_LITERAL_DEFLATED:3067clear_image(img);3068 img->len = fragment->size;3069 img->buf =xmemdupz(fragment->patch, img->len);3070return0;3071}3072return-1;3073}30743075/*3076 * Replace "img" with the result of applying the binary patch.3077 * The binary patch data itself in patch->fragment is still kept3078 * but the preimage prepared by the caller in "img" is freed here3079 * or in the helper function apply_binary_fragment() this calls.3080 */3081static intapply_binary(struct apply_state *state,3082struct image *img,3083struct patch *patch)3084{3085const char*name = patch->old_name ? patch->old_name : patch->new_name;3086unsigned char sha1[20];30873088/*3089 * For safety, we require patch index line to contain3090 * full 40-byte textual SHA1 for old and new, at least for now.3091 */3092if(strlen(patch->old_sha1_prefix) !=40||3093strlen(patch->new_sha1_prefix) !=40||3094get_sha1_hex(patch->old_sha1_prefix, sha1) ||3095get_sha1_hex(patch->new_sha1_prefix, sha1))3096returnerror("cannot apply binary patch to '%s' "3097"without full index line", name);30983099if(patch->old_name) {3100/*3101 * See if the old one matches what the patch3102 * applies to.3103 */3104hash_sha1_file(img->buf, img->len, blob_type, sha1);3105if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3106returnerror("the patch applies to '%s' (%s), "3107"which does not match the "3108"current contents.",3109 name,sha1_to_hex(sha1));3110}3111else{3112/* Otherwise, the old one must be empty. */3113if(img->len)3114returnerror("the patch applies to an empty "3115"'%s' but it is not empty", name);3116}31173118get_sha1_hex(patch->new_sha1_prefix, sha1);3119if(is_null_sha1(sha1)) {3120clear_image(img);3121return0;/* deletion patch */3122}31233124if(has_sha1_file(sha1)) {3125/* We already have the postimage */3126enum object_type type;3127unsigned long size;3128char*result;31293130 result =read_sha1_file(sha1, &type, &size);3131if(!result)3132returnerror("the necessary postimage%sfor "3133"'%s' cannot be read",3134 patch->new_sha1_prefix, name);3135clear_image(img);3136 img->buf = result;3137 img->len = size;3138}else{3139/*3140 * We have verified buf matches the preimage;3141 * apply the patch data to it, which is stored3142 * in the patch->fragments->{patch,size}.3143 */3144if(apply_binary_fragment(state, img, patch))3145returnerror(_("binary patch does not apply to '%s'"),3146 name);31473148/* verify that the result matches */3149hash_sha1_file(img->buf, img->len, blob_type, sha1);3150if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3151returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3152 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3153}31543155return0;3156}31573158static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3159{3160struct fragment *frag = patch->fragments;3161const char*name = patch->old_name ? patch->old_name : patch->new_name;3162unsigned ws_rule = patch->ws_rule;3163unsigned inaccurate_eof = patch->inaccurate_eof;3164int nth =0;31653166if(patch->is_binary)3167returnapply_binary(state, img, patch);31683169while(frag) {3170 nth++;3171if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3172error(_("patch failed:%s:%ld"), name, frag->oldpos);3173if(!state->apply_with_reject)3174return-1;3175 frag->rejected =1;3176}3177 frag = frag->next;3178}3179return0;3180}31813182static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3183{3184if(S_ISGITLINK(mode)) {3185strbuf_grow(buf,100);3186strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3187}else{3188enum object_type type;3189unsigned long sz;3190char*result;31913192 result =read_sha1_file(sha1, &type, &sz);3193if(!result)3194return-1;3195/* XXX read_sha1_file NUL-terminates */3196strbuf_attach(buf, result, sz, sz +1);3197}3198return0;3199}32003201static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3202{3203if(!ce)3204return0;3205returnread_blob_object(buf, ce->sha1, ce->ce_mode);3206}32073208static struct patch *in_fn_table(const char*name)3209{3210struct string_list_item *item;32113212if(name == NULL)3213return NULL;32143215 item =string_list_lookup(&fn_table, name);3216if(item != NULL)3217return(struct patch *)item->util;32183219return NULL;3220}32213222/*3223 * item->util in the filename table records the status of the path.3224 * Usually it points at a patch (whose result records the contents3225 * of it after applying it), but it could be PATH_WAS_DELETED for a3226 * path that a previously applied patch has already removed, or3227 * PATH_TO_BE_DELETED for a path that a later patch would remove.3228 *3229 * The latter is needed to deal with a case where two paths A and B3230 * are swapped by first renaming A to B and then renaming B to A;3231 * moving A to B should not be prevented due to presence of B as we3232 * will remove it in a later patch.3233 */3234#define PATH_TO_BE_DELETED ((struct patch *) -2)3235#define PATH_WAS_DELETED ((struct patch *) -1)32363237static intto_be_deleted(struct patch *patch)3238{3239return patch == PATH_TO_BE_DELETED;3240}32413242static intwas_deleted(struct patch *patch)3243{3244return patch == PATH_WAS_DELETED;3245}32463247static voidadd_to_fn_table(struct patch *patch)3248{3249struct string_list_item *item;32503251/*3252 * Always add new_name unless patch is a deletion3253 * This should cover the cases for normal diffs,3254 * file creations and copies3255 */3256if(patch->new_name != NULL) {3257 item =string_list_insert(&fn_table, patch->new_name);3258 item->util = patch;3259}32603261/*3262 * store a failure on rename/deletion cases because3263 * later chunks shouldn't patch old names3264 */3265if((patch->new_name == NULL) || (patch->is_rename)) {3266 item =string_list_insert(&fn_table, patch->old_name);3267 item->util = PATH_WAS_DELETED;3268}3269}32703271static voidprepare_fn_table(struct patch *patch)3272{3273/*3274 * store information about incoming file deletion3275 */3276while(patch) {3277if((patch->new_name == NULL) || (patch->is_rename)) {3278struct string_list_item *item;3279 item =string_list_insert(&fn_table, patch->old_name);3280 item->util = PATH_TO_BE_DELETED;3281}3282 patch = patch->next;3283}3284}32853286static intcheckout_target(struct index_state *istate,3287struct cache_entry *ce,struct stat *st)3288{3289struct checkout costate;32903291memset(&costate,0,sizeof(costate));3292 costate.base_dir ="";3293 costate.refresh_cache =1;3294 costate.istate = istate;3295if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3296returnerror(_("cannot checkout%s"), ce->name);3297return0;3298}32993300static struct patch *previous_patch(struct patch *patch,int*gone)3301{3302struct patch *previous;33033304*gone =0;3305if(patch->is_copy || patch->is_rename)3306return NULL;/* "git" patches do not depend on the order */33073308 previous =in_fn_table(patch->old_name);3309if(!previous)3310return NULL;33113312if(to_be_deleted(previous))3313return NULL;/* the deletion hasn't happened yet */33143315if(was_deleted(previous))3316*gone =1;33173318return previous;3319}33203321static intverify_index_match(const struct cache_entry *ce,struct stat *st)3322{3323if(S_ISGITLINK(ce->ce_mode)) {3324if(!S_ISDIR(st->st_mode))3325return-1;3326return0;3327}3328returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3329}33303331#define SUBMODULE_PATCH_WITHOUT_INDEX 133323333static intload_patch_target(struct apply_state *state,3334struct strbuf *buf,3335const struct cache_entry *ce,3336struct stat *st,3337const char*name,3338unsigned expected_mode)3339{3340if(state->cached || state->check_index) {3341if(read_file_or_gitlink(ce, buf))3342returnerror(_("read of%sfailed"), name);3343}else if(name) {3344if(S_ISGITLINK(expected_mode)) {3345if(ce)3346returnread_file_or_gitlink(ce, buf);3347else3348return SUBMODULE_PATCH_WITHOUT_INDEX;3349}else if(has_symlink_leading_path(name,strlen(name))) {3350returnerror(_("reading from '%s' beyond a symbolic link"), name);3351}else{3352if(read_old_data(st, name, buf))3353returnerror(_("read of%sfailed"), name);3354}3355}3356return0;3357}33583359/*3360 * We are about to apply "patch"; populate the "image" with the3361 * current version we have, from the working tree or from the index,3362 * depending on the situation e.g. --cached/--index. If we are3363 * applying a non-git patch that incrementally updates the tree,3364 * we read from the result of a previous diff.3365 */3366static intload_preimage(struct apply_state *state,3367struct image *image,3368struct patch *patch,struct stat *st,3369const struct cache_entry *ce)3370{3371struct strbuf buf = STRBUF_INIT;3372size_t len;3373char*img;3374struct patch *previous;3375int status;33763377 previous =previous_patch(patch, &status);3378if(status)3379returnerror(_("path%shas been renamed/deleted"),3380 patch->old_name);3381if(previous) {3382/* We have a patched copy in memory; use that. */3383strbuf_add(&buf, previous->result, previous->resultsize);3384}else{3385 status =load_patch_target(state, &buf, ce, st,3386 patch->old_name, patch->old_mode);3387if(status <0)3388return status;3389else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3390/*3391 * There is no way to apply subproject3392 * patch without looking at the index.3393 * NEEDSWORK: shouldn't this be flagged3394 * as an error???3395 */3396free_fragment_list(patch->fragments);3397 patch->fragments = NULL;3398}else if(status) {3399returnerror(_("read of%sfailed"), patch->old_name);3400}3401}34023403 img =strbuf_detach(&buf, &len);3404prepare_image(image, img, len, !patch->is_binary);3405return0;3406}34073408static intthree_way_merge(struct image *image,3409char*path,3410const unsigned char*base,3411const unsigned char*ours,3412const unsigned char*theirs)3413{3414 mmfile_t base_file, our_file, their_file;3415 mmbuffer_t result = { NULL };3416int status;34173418read_mmblob(&base_file, base);3419read_mmblob(&our_file, ours);3420read_mmblob(&their_file, theirs);3421 status =ll_merge(&result, path,3422&base_file,"base",3423&our_file,"ours",3424&their_file,"theirs", NULL);3425free(base_file.ptr);3426free(our_file.ptr);3427free(their_file.ptr);3428if(status <0|| !result.ptr) {3429free(result.ptr);3430return-1;3431}3432clear_image(image);3433 image->buf = result.ptr;3434 image->len = result.size;34353436return status;3437}34383439/*3440 * When directly falling back to add/add three-way merge, we read from3441 * the current contents of the new_name. In no cases other than that3442 * this function will be called.3443 */3444static intload_current(struct apply_state *state,3445struct image *image,3446struct patch *patch)3447{3448struct strbuf buf = STRBUF_INIT;3449int status, pos;3450size_t len;3451char*img;3452struct stat st;3453struct cache_entry *ce;3454char*name = patch->new_name;3455unsigned mode = patch->new_mode;34563457if(!patch->is_new)3458die("BUG: patch to%sis not a creation", patch->old_name);34593460 pos =cache_name_pos(name,strlen(name));3461if(pos <0)3462returnerror(_("%s: does not exist in index"), name);3463 ce = active_cache[pos];3464if(lstat(name, &st)) {3465if(errno != ENOENT)3466returnerror(_("%s:%s"), name,strerror(errno));3467if(checkout_target(&the_index, ce, &st))3468return-1;3469}3470if(verify_index_match(ce, &st))3471returnerror(_("%s: does not match index"), name);34723473 status =load_patch_target(state, &buf, ce, &st, name, mode);3474if(status <0)3475return status;3476else if(status)3477return-1;3478 img =strbuf_detach(&buf, &len);3479prepare_image(image, img, len, !patch->is_binary);3480return0;3481}34823483static inttry_threeway(struct apply_state *state,3484struct image *image,3485struct patch *patch,3486struct stat *st,3487const struct cache_entry *ce)3488{3489unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3490struct strbuf buf = STRBUF_INIT;3491size_t len;3492int status;3493char*img;3494struct image tmp_image;34953496/* No point falling back to 3-way merge in these cases */3497if(patch->is_delete ||3498S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3499return-1;35003501/* Preimage the patch was prepared for */3502if(patch->is_new)3503write_sha1_file("",0, blob_type, pre_sha1);3504else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3505read_blob_object(&buf, pre_sha1, patch->old_mode))3506returnerror("repository lacks the necessary blob to fall back on 3-way merge.");35073508fprintf(stderr,"Falling back to three-way merge...\n");35093510 img =strbuf_detach(&buf, &len);3511prepare_image(&tmp_image, img, len,1);3512/* Apply the patch to get the post image */3513if(apply_fragments(state, &tmp_image, patch) <0) {3514clear_image(&tmp_image);3515return-1;3516}3517/* post_sha1[] is theirs */3518write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3519clear_image(&tmp_image);35203521/* our_sha1[] is ours */3522if(patch->is_new) {3523if(load_current(state, &tmp_image, patch))3524returnerror("cannot read the current contents of '%s'",3525 patch->new_name);3526}else{3527if(load_preimage(state, &tmp_image, patch, st, ce))3528returnerror("cannot read the current contents of '%s'",3529 patch->old_name);3530}3531write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3532clear_image(&tmp_image);35333534/* in-core three-way merge between post and our using pre as base */3535 status =three_way_merge(image, patch->new_name,3536 pre_sha1, our_sha1, post_sha1);3537if(status <0) {3538fprintf(stderr,"Failed to fall back on three-way merge...\n");3539return status;3540}35413542if(status) {3543 patch->conflicted_threeway =1;3544if(patch->is_new)3545oidclr(&patch->threeway_stage[0]);3546else3547hashcpy(patch->threeway_stage[0].hash, pre_sha1);3548hashcpy(patch->threeway_stage[1].hash, our_sha1);3549hashcpy(patch->threeway_stage[2].hash, post_sha1);3550fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3551}else{3552fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3553}3554return0;3555}35563557static intapply_data(struct apply_state *state,struct patch *patch,3558struct stat *st,const struct cache_entry *ce)3559{3560struct image image;35613562if(load_preimage(state, &image, patch, st, ce) <0)3563return-1;35643565if(patch->direct_to_threeway ||3566apply_fragments(state, &image, patch) <0) {3567/* Note: with --reject, apply_fragments() returns 0 */3568if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3569return-1;3570}3571 patch->result = image.buf;3572 patch->resultsize = image.len;3573add_to_fn_table(patch);3574free(image.line_allocated);35753576if(0< patch->is_delete && patch->resultsize)3577returnerror(_("removal patch leaves file contents"));35783579return0;3580}35813582/*3583 * If "patch" that we are looking at modifies or deletes what we have,3584 * we would want it not to lose any local modification we have, either3585 * in the working tree or in the index.3586 *3587 * This also decides if a non-git patch is a creation patch or a3588 * modification to an existing empty file. We do not check the state3589 * of the current tree for a creation patch in this function; the caller3590 * check_patch() separately makes sure (and errors out otherwise) that3591 * the path the patch creates does not exist in the current tree.3592 */3593static intcheck_preimage(struct apply_state *state,3594struct patch *patch,3595struct cache_entry **ce,3596struct stat *st)3597{3598const char*old_name = patch->old_name;3599struct patch *previous = NULL;3600int stat_ret =0, status;3601unsigned st_mode =0;36023603if(!old_name)3604return0;36053606assert(patch->is_new <=0);3607 previous =previous_patch(patch, &status);36083609if(status)3610returnerror(_("path%shas been renamed/deleted"), old_name);3611if(previous) {3612 st_mode = previous->new_mode;3613}else if(!state->cached) {3614 stat_ret =lstat(old_name, st);3615if(stat_ret && errno != ENOENT)3616returnerror(_("%s:%s"), old_name,strerror(errno));3617}36183619if(state->check_index && !previous) {3620int pos =cache_name_pos(old_name,strlen(old_name));3621if(pos <0) {3622if(patch->is_new <0)3623goto is_new;3624returnerror(_("%s: does not exist in index"), old_name);3625}3626*ce = active_cache[pos];3627if(stat_ret <0) {3628if(checkout_target(&the_index, *ce, st))3629return-1;3630}3631if(!state->cached &&verify_index_match(*ce, st))3632returnerror(_("%s: does not match index"), old_name);3633if(state->cached)3634 st_mode = (*ce)->ce_mode;3635}else if(stat_ret <0) {3636if(patch->is_new <0)3637goto is_new;3638returnerror(_("%s:%s"), old_name,strerror(errno));3639}36403641if(!state->cached && !previous)3642 st_mode =ce_mode_from_stat(*ce, st->st_mode);36433644if(patch->is_new <0)3645 patch->is_new =0;3646if(!patch->old_mode)3647 patch->old_mode = st_mode;3648if((st_mode ^ patch->old_mode) & S_IFMT)3649returnerror(_("%s: wrong type"), old_name);3650if(st_mode != patch->old_mode)3651warning(_("%shas type%o, expected%o"),3652 old_name, st_mode, patch->old_mode);3653if(!patch->new_mode && !patch->is_delete)3654 patch->new_mode = st_mode;3655return0;36563657 is_new:3658 patch->is_new =1;3659 patch->is_delete =0;3660free(patch->old_name);3661 patch->old_name = NULL;3662return0;3663}366436653666#define EXISTS_IN_INDEX 13667#define EXISTS_IN_WORKTREE 236683669static intcheck_to_create(struct apply_state *state,3670const char*new_name,3671int ok_if_exists)3672{3673struct stat nst;36743675if(state->check_index &&3676cache_name_pos(new_name,strlen(new_name)) >=0&&3677!ok_if_exists)3678return EXISTS_IN_INDEX;3679if(state->cached)3680return0;36813682if(!lstat(new_name, &nst)) {3683if(S_ISDIR(nst.st_mode) || ok_if_exists)3684return0;3685/*3686 * A leading component of new_name might be a symlink3687 * that is going to be removed with this patch, but3688 * still pointing at somewhere that has the path.3689 * In such a case, path "new_name" does not exist as3690 * far as git is concerned.3691 */3692if(has_symlink_leading_path(new_name,strlen(new_name)))3693return0;36943695return EXISTS_IN_WORKTREE;3696}else if((errno != ENOENT) && (errno != ENOTDIR)) {3697returnerror("%s:%s", new_name,strerror(errno));3698}3699return0;3700}37013702/*3703 * We need to keep track of how symlinks in the preimage are3704 * manipulated by the patches. A patch to add a/b/c where a/b3705 * is a symlink should not be allowed to affect the directory3706 * the symlink points at, but if the same patch removes a/b,3707 * it is perfectly fine, as the patch removes a/b to make room3708 * to create a directory a/b so that a/b/c can be created.3709 */3710static struct string_list symlink_changes;3711#define SYMLINK_GOES_AWAY 013712#define SYMLINK_IN_RESULT 0237133714static uintptr_tregister_symlink_changes(const char*path,uintptr_t what)3715{3716struct string_list_item *ent;37173718 ent =string_list_lookup(&symlink_changes, path);3719if(!ent) {3720 ent =string_list_insert(&symlink_changes, path);3721 ent->util = (void*)0;3722}3723 ent->util = (void*)(what | ((uintptr_t)ent->util));3724return(uintptr_t)ent->util;3725}37263727static uintptr_tcheck_symlink_changes(const char*path)3728{3729struct string_list_item *ent;37303731 ent =string_list_lookup(&symlink_changes, path);3732if(!ent)3733return0;3734return(uintptr_t)ent->util;3735}37363737static voidprepare_symlink_changes(struct patch *patch)3738{3739for( ; patch; patch = patch->next) {3740if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3741(patch->is_rename || patch->is_delete))3742/* the symlink at patch->old_name is removed */3743register_symlink_changes(patch->old_name, SYMLINK_GOES_AWAY);37443745if(patch->new_name &&S_ISLNK(patch->new_mode))3746/* the symlink at patch->new_name is created or remains */3747register_symlink_changes(patch->new_name, SYMLINK_IN_RESULT);3748}3749}37503751static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3752{3753do{3754unsigned int change;37553756while(--name->len && name->buf[name->len] !='/')3757;/* scan backwards */3758if(!name->len)3759break;3760 name->buf[name->len] ='\0';3761 change =check_symlink_changes(name->buf);3762if(change & SYMLINK_IN_RESULT)3763return1;3764if(change & SYMLINK_GOES_AWAY)3765/*3766 * This cannot be "return 0", because we may3767 * see a new one created at a higher level.3768 */3769continue;37703771/* otherwise, check the preimage */3772if(state->check_index) {3773struct cache_entry *ce;37743775 ce =cache_file_exists(name->buf, name->len, ignore_case);3776if(ce &&S_ISLNK(ce->ce_mode))3777return1;3778}else{3779struct stat st;3780if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3781return1;3782}3783}while(1);3784return0;3785}37863787static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3788{3789int ret;3790struct strbuf name = STRBUF_INIT;37913792assert(*name_ !='\0');3793strbuf_addstr(&name, name_);3794 ret =path_is_beyond_symlink_1(state, &name);3795strbuf_release(&name);37963797return ret;3798}37993800static voiddie_on_unsafe_path(struct patch *patch)3801{3802const char*old_name = NULL;3803const char*new_name = NULL;3804if(patch->is_delete)3805 old_name = patch->old_name;3806else if(!patch->is_new && !patch->is_copy)3807 old_name = patch->old_name;3808if(!patch->is_delete)3809 new_name = patch->new_name;38103811if(old_name && !verify_path(old_name))3812die(_("invalid path '%s'"), old_name);3813if(new_name && !verify_path(new_name))3814die(_("invalid path '%s'"), new_name);3815}38163817/*3818 * Check and apply the patch in-core; leave the result in patch->result3819 * for the caller to write it out to the final destination.3820 */3821static intcheck_patch(struct apply_state *state,struct patch *patch)3822{3823struct stat st;3824const char*old_name = patch->old_name;3825const char*new_name = patch->new_name;3826const char*name = old_name ? old_name : new_name;3827struct cache_entry *ce = NULL;3828struct patch *tpatch;3829int ok_if_exists;3830int status;38313832 patch->rejected =1;/* we will drop this after we succeed */38333834 status =check_preimage(state, patch, &ce, &st);3835if(status)3836return status;3837 old_name = patch->old_name;38383839/*3840 * A type-change diff is always split into a patch to delete3841 * old, immediately followed by a patch to create new (see3842 * diff.c::run_diff()); in such a case it is Ok that the entry3843 * to be deleted by the previous patch is still in the working3844 * tree and in the index.3845 *3846 * A patch to swap-rename between A and B would first rename A3847 * to B and then rename B to A. While applying the first one,3848 * the presence of B should not stop A from getting renamed to3849 * B; ask to_be_deleted() about the later rename. Removal of3850 * B and rename from A to B is handled the same way by asking3851 * was_deleted().3852 */3853if((tpatch =in_fn_table(new_name)) &&3854(was_deleted(tpatch) ||to_be_deleted(tpatch)))3855 ok_if_exists =1;3856else3857 ok_if_exists =0;38583859if(new_name &&3860((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3861int err =check_to_create(state, new_name, ok_if_exists);38623863if(err && state->threeway) {3864 patch->direct_to_threeway =1;3865}else switch(err) {3866case0:3867break;/* happy */3868case EXISTS_IN_INDEX:3869returnerror(_("%s: already exists in index"), new_name);3870break;3871case EXISTS_IN_WORKTREE:3872returnerror(_("%s: already exists in working directory"),3873 new_name);3874default:3875return err;3876}38773878if(!patch->new_mode) {3879if(0< patch->is_new)3880 patch->new_mode = S_IFREG |0644;3881else3882 patch->new_mode = patch->old_mode;3883}3884}38853886if(new_name && old_name) {3887int same = !strcmp(old_name, new_name);3888if(!patch->new_mode)3889 patch->new_mode = patch->old_mode;3890if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3891if(same)3892returnerror(_("new mode (%o) of%sdoes not "3893"match old mode (%o)"),3894 patch->new_mode, new_name,3895 patch->old_mode);3896else3897returnerror(_("new mode (%o) of%sdoes not "3898"match old mode (%o) of%s"),3899 patch->new_mode, new_name,3900 patch->old_mode, old_name);3901}3902}39033904if(!state->unsafe_paths)3905die_on_unsafe_path(patch);39063907/*3908 * An attempt to read from or delete a path that is beyond a3909 * symbolic link will be prevented by load_patch_target() that3910 * is called at the beginning of apply_data() so we do not3911 * have to worry about a patch marked with "is_delete" bit3912 * here. We however need to make sure that the patch result3913 * is not deposited to a path that is beyond a symbolic link3914 * here.3915 */3916if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3917returnerror(_("affected file '%s' is beyond a symbolic link"),3918 patch->new_name);39193920if(apply_data(state, patch, &st, ce) <0)3921returnerror(_("%s: patch does not apply"), name);3922 patch->rejected =0;3923return0;3924}39253926static intcheck_patch_list(struct apply_state *state,struct patch *patch)3927{3928int err =0;39293930prepare_symlink_changes(patch);3931prepare_fn_table(patch);3932while(patch) {3933if(state->apply_verbosely)3934say_patch_name(stderr,3935_("Checking patch%s..."), patch);3936 err |=check_patch(state, patch);3937 patch = patch->next;3938}3939return err;3940}39413942/* This function tries to read the sha1 from the current index */3943static intget_current_sha1(const char*path,unsigned char*sha1)3944{3945int pos;39463947if(read_cache() <0)3948return-1;3949 pos =cache_name_pos(path,strlen(path));3950if(pos <0)3951return-1;3952hashcpy(sha1, active_cache[pos]->sha1);3953return0;3954}39553956static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3957{3958/*3959 * A usable gitlink patch has only one fragment (hunk) that looks like:3960 * @@ -1 +1 @@3961 * -Subproject commit <old sha1>3962 * +Subproject commit <new sha1>3963 * or3964 * @@ -1 +0,0 @@3965 * -Subproject commit <old sha1>3966 * for a removal patch.3967 */3968struct fragment *hunk = p->fragments;3969static const char heading[] ="-Subproject commit ";3970char*preimage;39713972if(/* does the patch have only one hunk? */3973 hunk && !hunk->next &&3974/* is its preimage one line? */3975 hunk->oldpos ==1&& hunk->oldlines ==1&&3976/* does preimage begin with the heading? */3977(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3978starts_with(++preimage, heading) &&3979/* does it record full SHA-1? */3980!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3981 preimage[sizeof(heading) +40-1] =='\n'&&3982/* does the abbreviated name on the index line agree with it? */3983starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3984return0;/* it all looks fine */39853986/* we may have full object name on the index line */3987returnget_sha1_hex(p->old_sha1_prefix, sha1);3988}39893990/* Build an index that contains the just the files needed for a 3way merge */3991static voidbuild_fake_ancestor(struct patch *list,const char*filename)3992{3993struct patch *patch;3994struct index_state result = { NULL };3995static struct lock_file lock;39963997/* Once we start supporting the reverse patch, it may be3998 * worth showing the new sha1 prefix, but until then...3999 */4000for(patch = list; patch; patch = patch->next) {4001unsigned char sha1[20];4002struct cache_entry *ce;4003const char*name;40044005 name = patch->old_name ? patch->old_name : patch->new_name;4006if(0< patch->is_new)4007continue;40084009if(S_ISGITLINK(patch->old_mode)) {4010if(!preimage_sha1_in_gitlink_patch(patch, sha1))4011;/* ok, the textual part looks sane */4012else4013die("sha1 information is lacking or useless for submodule%s",4014 name);4015}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {4016;/* ok */4017}else if(!patch->lines_added && !patch->lines_deleted) {4018/* mode-only change: update the current */4019if(get_current_sha1(patch->old_name, sha1))4020die("mode change for%s, which is not "4021"in current HEAD", name);4022}else4023die("sha1 information is lacking or useless "4024"(%s).", name);40254026 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);4027if(!ce)4028die(_("make_cache_entry failed for path '%s'"), name);4029if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))4030die("Could not add%sto temporary index", name);4031}40324033hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);4034if(write_locked_index(&result, &lock, COMMIT_LOCK))4035die("Could not write temporary index to%s", filename);40364037discard_index(&result);4038}40394040static voidstat_patch_list(struct patch *patch)4041{4042int files, adds, dels;40434044for(files = adds = dels =0; patch ; patch = patch->next) {4045 files++;4046 adds += patch->lines_added;4047 dels += patch->lines_deleted;4048show_stats(patch);4049}40504051print_stat_summary(stdout, files, adds, dels);4052}40534054static voidnumstat_patch_list(struct apply_state *state,4055struct patch *patch)4056{4057for( ; patch; patch = patch->next) {4058const char*name;4059 name = patch->new_name ? patch->new_name : patch->old_name;4060if(patch->is_binary)4061printf("-\t-\t");4062else4063printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4064write_name_quoted(name, stdout, state->line_termination);4065}4066}40674068static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4069{4070if(mode)4071printf("%smode%06o%s\n", newdelete, mode, name);4072else4073printf("%s %s\n", newdelete, name);4074}40754076static voidshow_mode_change(struct patch *p,int show_name)4077{4078if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4079if(show_name)4080printf(" mode change%06o =>%06o%s\n",4081 p->old_mode, p->new_mode, p->new_name);4082else4083printf(" mode change%06o =>%06o\n",4084 p->old_mode, p->new_mode);4085}4086}40874088static voidshow_rename_copy(struct patch *p)4089{4090const char*renamecopy = p->is_rename ?"rename":"copy";4091const char*old, *new;40924093/* Find common prefix */4094 old = p->old_name;4095new= p->new_name;4096while(1) {4097const char*slash_old, *slash_new;4098 slash_old =strchr(old,'/');4099 slash_new =strchr(new,'/');4100if(!slash_old ||4101!slash_new ||4102 slash_old - old != slash_new -new||4103memcmp(old,new, slash_new -new))4104break;4105 old = slash_old +1;4106new= slash_new +1;4107}4108/* p->old_name thru old is the common prefix, and old and new4109 * through the end of names are renames4110 */4111if(old != p->old_name)4112printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4113(int)(old - p->old_name), p->old_name,4114 old,new, p->score);4115else4116printf("%s %s=>%s(%d%%)\n", renamecopy,4117 p->old_name, p->new_name, p->score);4118show_mode_change(p,0);4119}41204121static voidsummary_patch_list(struct patch *patch)4122{4123struct patch *p;41244125for(p = patch; p; p = p->next) {4126if(p->is_new)4127show_file_mode_name("create", p->new_mode, p->new_name);4128else if(p->is_delete)4129show_file_mode_name("delete", p->old_mode, p->old_name);4130else{4131if(p->is_rename || p->is_copy)4132show_rename_copy(p);4133else{4134if(p->score) {4135printf(" rewrite%s(%d%%)\n",4136 p->new_name, p->score);4137show_mode_change(p,0);4138}4139else4140show_mode_change(p,1);4141}4142}4143}4144}41454146static voidpatch_stats(struct patch *patch)4147{4148int lines = patch->lines_added + patch->lines_deleted;41494150if(lines > max_change)4151 max_change = lines;4152if(patch->old_name) {4153int len =quote_c_style(patch->old_name, NULL, NULL,0);4154if(!len)4155 len =strlen(patch->old_name);4156if(len > max_len)4157 max_len = len;4158}4159if(patch->new_name) {4160int len =quote_c_style(patch->new_name, NULL, NULL,0);4161if(!len)4162 len =strlen(patch->new_name);4163if(len > max_len)4164 max_len = len;4165}4166}41674168static voidremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4169{4170if(state->update_index) {4171if(remove_file_from_cache(patch->old_name) <0)4172die(_("unable to remove%sfrom index"), patch->old_name);4173}4174if(!state->cached) {4175if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4176remove_path(patch->old_name);4177}4178}4179}41804181static voidadd_index_file(struct apply_state *state,4182const char*path,4183unsigned mode,4184void*buf,4185unsigned long size)4186{4187struct stat st;4188struct cache_entry *ce;4189int namelen =strlen(path);4190unsigned ce_size =cache_entry_size(namelen);41914192if(!state->update_index)4193return;41944195 ce =xcalloc(1, ce_size);4196memcpy(ce->name, path, namelen);4197 ce->ce_mode =create_ce_mode(mode);4198 ce->ce_flags =create_ce_flags(0);4199 ce->ce_namelen = namelen;4200if(S_ISGITLINK(mode)) {4201const char*s;42024203if(!skip_prefix(buf,"Subproject commit ", &s) ||4204get_sha1_hex(s, ce->sha1))4205die(_("corrupt patch for submodule%s"), path);4206}else{4207if(!state->cached) {4208if(lstat(path, &st) <0)4209die_errno(_("unable to stat newly created file '%s'"),4210 path);4211fill_stat_cache_info(ce, &st);4212}4213if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4214die(_("unable to create backing store for newly created file%s"), path);4215}4216if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4217die(_("unable to add cache entry for%s"), path);4218}42194220static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4221{4222int fd;4223struct strbuf nbuf = STRBUF_INIT;42244225if(S_ISGITLINK(mode)) {4226struct stat st;4227if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4228return0;4229returnmkdir(path,0777);4230}42314232if(has_symlinks &&S_ISLNK(mode))4233/* Although buf:size is counted string, it also is NUL4234 * terminated.4235 */4236returnsymlink(buf, path);42374238 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4239if(fd <0)4240return-1;42414242if(convert_to_working_tree(path, buf, size, &nbuf)) {4243 size = nbuf.len;4244 buf = nbuf.buf;4245}4246write_or_die(fd, buf, size);4247strbuf_release(&nbuf);42484249if(close(fd) <0)4250die_errno(_("closing file '%s'"), path);4251return0;4252}42534254/*4255 * We optimistically assume that the directories exist,4256 * which is true 99% of the time anyway. If they don't,4257 * we create them and try again.4258 */4259static voidcreate_one_file(struct apply_state *state,4260char*path,4261unsigned mode,4262const char*buf,4263unsigned long size)4264{4265if(state->cached)4266return;4267if(!try_create_file(path, mode, buf, size))4268return;42694270if(errno == ENOENT) {4271if(safe_create_leading_directories(path))4272return;4273if(!try_create_file(path, mode, buf, size))4274return;4275}42764277if(errno == EEXIST || errno == EACCES) {4278/* We may be trying to create a file where a directory4279 * used to be.4280 */4281struct stat st;4282if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4283 errno = EEXIST;4284}42854286if(errno == EEXIST) {4287unsigned int nr =getpid();42884289for(;;) {4290char newpath[PATH_MAX];4291mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4292if(!try_create_file(newpath, mode, buf, size)) {4293if(!rename(newpath, path))4294return;4295unlink_or_warn(newpath);4296break;4297}4298if(errno != EEXIST)4299break;4300++nr;4301}4302}4303die_errno(_("unable to write file '%s' mode%o"), path, mode);4304}43054306static voidadd_conflicted_stages_file(struct apply_state *state,4307struct patch *patch)4308{4309int stage, namelen;4310unsigned ce_size, mode;4311struct cache_entry *ce;43124313if(!state->update_index)4314return;4315 namelen =strlen(patch->new_name);4316 ce_size =cache_entry_size(namelen);4317 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);43184319remove_file_from_cache(patch->new_name);4320for(stage =1; stage <4; stage++) {4321if(is_null_oid(&patch->threeway_stage[stage -1]))4322continue;4323 ce =xcalloc(1, ce_size);4324memcpy(ce->name, patch->new_name, namelen);4325 ce->ce_mode =create_ce_mode(mode);4326 ce->ce_flags =create_ce_flags(stage);4327 ce->ce_namelen = namelen;4328hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4329if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4330die(_("unable to add cache entry for%s"), patch->new_name);4331}4332}43334334static voidcreate_file(struct apply_state *state,struct patch *patch)4335{4336char*path = patch->new_name;4337unsigned mode = patch->new_mode;4338unsigned long size = patch->resultsize;4339char*buf = patch->result;43404341if(!mode)4342 mode = S_IFREG |0644;4343create_one_file(state, path, mode, buf, size);43444345if(patch->conflicted_threeway)4346add_conflicted_stages_file(state, patch);4347else4348add_index_file(state, path, mode, buf, size);4349}43504351/* phase zero is to remove, phase one is to create */4352static voidwrite_out_one_result(struct apply_state *state,4353struct patch *patch,4354int phase)4355{4356if(patch->is_delete >0) {4357if(phase ==0)4358remove_file(state, patch,1);4359return;4360}4361if(patch->is_new >0|| patch->is_copy) {4362if(phase ==1)4363create_file(state, patch);4364return;4365}4366/*4367 * Rename or modification boils down to the same4368 * thing: remove the old, write the new4369 */4370if(phase ==0)4371remove_file(state, patch, patch->is_rename);4372if(phase ==1)4373create_file(state, patch);4374}43754376static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4377{4378FILE*rej;4379char namebuf[PATH_MAX];4380struct fragment *frag;4381int cnt =0;4382struct strbuf sb = STRBUF_INIT;43834384for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4385if(!frag->rejected)4386continue;4387 cnt++;4388}43894390if(!cnt) {4391if(state->apply_verbosely)4392say_patch_name(stderr,4393_("Applied patch%scleanly."), patch);4394return0;4395}43964397/* This should not happen, because a removal patch that leaves4398 * contents are marked "rejected" at the patch level.4399 */4400if(!patch->new_name)4401die(_("internal error"));44024403/* Say this even without --verbose */4404strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4405"Applying patch %%swith%drejects...",4406 cnt),4407 cnt);4408say_patch_name(stderr, sb.buf, patch);4409strbuf_release(&sb);44104411 cnt =strlen(patch->new_name);4412if(ARRAY_SIZE(namebuf) <= cnt +5) {4413 cnt =ARRAY_SIZE(namebuf) -5;4414warning(_("truncating .rej filename to %.*s.rej"),4415 cnt -1, patch->new_name);4416}4417memcpy(namebuf, patch->new_name, cnt);4418memcpy(namebuf + cnt,".rej",5);44194420 rej =fopen(namebuf,"w");4421if(!rej)4422returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));44234424/* Normal git tools never deal with .rej, so do not pretend4425 * this is a git patch by saying --git or giving extended4426 * headers. While at it, maybe please "kompare" that wants4427 * the trailing TAB and some garbage at the end of line ;-).4428 */4429fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4430 patch->new_name, patch->new_name);4431for(cnt =1, frag = patch->fragments;4432 frag;4433 cnt++, frag = frag->next) {4434if(!frag->rejected) {4435fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4436continue;4437}4438fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4439fprintf(rej,"%.*s", frag->size, frag->patch);4440if(frag->patch[frag->size-1] !='\n')4441fputc('\n', rej);4442}4443fclose(rej);4444return-1;4445}44464447static intwrite_out_results(struct apply_state *state,struct patch *list)4448{4449int phase;4450int errs =0;4451struct patch *l;4452struct string_list cpath = STRING_LIST_INIT_DUP;44534454for(phase =0; phase <2; phase++) {4455 l = list;4456while(l) {4457if(l->rejected)4458 errs =1;4459else{4460write_out_one_result(state, l, phase);4461if(phase ==1) {4462if(write_out_one_reject(state, l))4463 errs =1;4464if(l->conflicted_threeway) {4465string_list_append(&cpath, l->new_name);4466 errs =1;4467}4468}4469}4470 l = l->next;4471}4472}44734474if(cpath.nr) {4475struct string_list_item *item;44764477string_list_sort(&cpath);4478for_each_string_list_item(item, &cpath)4479fprintf(stderr,"U%s\n", item->string);4480string_list_clear(&cpath,0);44814482rerere(0);4483}44844485return errs;4486}44874488static struct lock_file lock_file;44894490#define INACCURATE_EOF (1<<0)4491#define RECOUNT (1<<1)44924493static intapply_patch(struct apply_state *state,4494int fd,4495const char*filename,4496int options)4497{4498size_t offset;4499struct strbuf buf = STRBUF_INIT;/* owns the patch text */4500struct patch *list = NULL, **listp = &list;4501int skipped_patch =0;45024503 state->patch_input_file = filename;4504read_patch_file(&buf, fd);4505 offset =0;4506while(offset < buf.len) {4507struct patch *patch;4508int nr;45094510 patch =xcalloc(1,sizeof(*patch));4511 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4512 patch->recount = !!(options & RECOUNT);4513 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4514if(nr <0) {4515free_patch(patch);4516break;4517}4518if(state->apply_in_reverse)4519reverse_patches(patch);4520if(use_patch(state, patch)) {4521patch_stats(patch);4522*listp = patch;4523 listp = &patch->next;4524}4525else{4526if(state->apply_verbosely)4527say_patch_name(stderr,_("Skipped patch '%s'."), patch);4528free_patch(patch);4529 skipped_patch++;4530}4531 offset += nr;4532}45334534if(!list && !skipped_patch)4535die(_("unrecognized input"));45364537if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4538 state->apply =0;45394540 state->update_index = state->check_index && state->apply;4541if(state->update_index && newfd <0)4542 newfd =hold_locked_index(&lock_file,1);45434544if(state->check_index) {4545if(read_cache() <0)4546die(_("unable to read index file"));4547}45484549if((state->check || state->apply) &&4550check_patch_list(state, list) <0&&4551!state->apply_with_reject)4552exit(1);45534554if(state->apply &&write_out_results(state, list)) {4555if(state->apply_with_reject)4556exit(1);4557/* with --3way, we still need to write the index out */4558return1;4559}45604561if(state->fake_ancestor)4562build_fake_ancestor(list, state->fake_ancestor);45634564if(state->diffstat)4565stat_patch_list(list);45664567if(state->numstat)4568numstat_patch_list(state, list);45694570if(state->summary)4571summary_patch_list(list);45724573free_patch_list(list);4574strbuf_release(&buf);4575string_list_clear(&fn_table,0);4576return0;4577}45784579static voidgit_apply_config(void)4580{4581git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4582git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4583git_config(git_default_config, NULL);4584}45854586static intoption_parse_exclude(const struct option *opt,4587const char*arg,int unset)4588{4589struct apply_state *state = opt->value;4590add_name_limit(state, arg,1);4591return0;4592}45934594static intoption_parse_include(const struct option *opt,4595const char*arg,int unset)4596{4597struct apply_state *state = opt->value;4598add_name_limit(state, arg,0);4599 state->has_include =1;4600return0;4601}46024603static intoption_parse_p(const struct option *opt,4604const char*arg,4605int unset)4606{4607struct apply_state *state = opt->value;4608 state->p_value =atoi(arg);4609 state->p_value_known =1;4610return0;4611}46124613static intoption_parse_space_change(const struct option *opt,4614const char*arg,int unset)4615{4616if(unset)4617 ws_ignore_action = ignore_ws_none;4618else4619 ws_ignore_action = ignore_ws_change;4620return0;4621}46224623static intoption_parse_whitespace(const struct option *opt,4624const char*arg,int unset)4625{4626struct apply_state *state = opt->value;4627 state->whitespace_option = arg;4628parse_whitespace_option(state, arg);4629return0;4630}46314632static intoption_parse_directory(const struct option *opt,4633const char*arg,int unset)4634{4635struct apply_state *state = opt->value;4636strbuf_reset(&state->root);4637strbuf_addstr(&state->root, arg);4638strbuf_complete(&state->root,'/');4639return0;4640}46414642static voidinit_apply_state(struct apply_state *state,const char*prefix)4643{4644memset(state,0,sizeof(*state));4645 state->prefix = prefix;4646 state->prefix_length = state->prefix ?strlen(state->prefix) :0;4647 state->apply =1;4648 state->line_termination ='\n';4649 state->p_value =1;4650 state->p_context = UINT_MAX;4651 state->squelch_whitespace_errors =5;4652 state->ws_error_action = warn_on_ws_error;4653strbuf_init(&state->root,0);46544655git_apply_config();4656if(apply_default_whitespace)4657parse_whitespace_option(state, apply_default_whitespace);4658if(apply_default_ignorewhitespace)4659parse_ignorewhitespace_option(apply_default_ignorewhitespace);4660}46614662static voidclear_apply_state(struct apply_state *state)4663{4664string_list_clear(&state->limit_by_name,0);4665strbuf_release(&state->root);4666}46674668intcmd_apply(int argc,const char**argv,const char*prefix)4669{4670int i;4671int errs =0;4672int is_not_gitdir = !startup_info->have_repository;4673int force_apply =0;4674int options =0;4675int read_stdin =1;4676struct apply_state state;46774678struct option builtin_apply_options[] = {4679{ OPTION_CALLBACK,0,"exclude", &state,N_("path"),4680N_("don't apply changes matching the given path"),46810, option_parse_exclude },4682{ OPTION_CALLBACK,0,"include", &state,N_("path"),4683N_("apply changes matching the given path"),46840, option_parse_include },4685{ OPTION_CALLBACK,'p', NULL, &state,N_("num"),4686N_("remove <num> leading slashes from traditional diff paths"),46870, option_parse_p },4688OPT_BOOL(0,"no-add", &state.no_add,4689N_("ignore additions made by the patch")),4690OPT_BOOL(0,"stat", &state.diffstat,4691N_("instead of applying the patch, output diffstat for the input")),4692OPT_NOOP_NOARG(0,"allow-binary-replacement"),4693OPT_NOOP_NOARG(0,"binary"),4694OPT_BOOL(0,"numstat", &state.numstat,4695N_("show number of added and deleted lines in decimal notation")),4696OPT_BOOL(0,"summary", &state.summary,4697N_("instead of applying the patch, output a summary for the input")),4698OPT_BOOL(0,"check", &state.check,4699N_("instead of applying the patch, see if the patch is applicable")),4700OPT_BOOL(0,"index", &state.check_index,4701N_("make sure the patch is applicable to the current index")),4702OPT_BOOL(0,"cached", &state.cached,4703N_("apply a patch without touching the working tree")),4704OPT_BOOL(0,"unsafe-paths", &state.unsafe_paths,4705N_("accept a patch that touches outside the working area")),4706OPT_BOOL(0,"apply", &force_apply,4707N_("also apply the patch (use with --stat/--summary/--check)")),4708OPT_BOOL('3',"3way", &state.threeway,4709N_("attempt three-way merge if a patch does not apply")),4710OPT_FILENAME(0,"build-fake-ancestor", &state.fake_ancestor,4711N_("build a temporary index based on embedded index information")),4712/* Think twice before adding "--nul" synonym to this */4713OPT_SET_INT('z', NULL, &state.line_termination,4714N_("paths are separated with NUL character"),'\0'),4715OPT_INTEGER('C', NULL, &state.p_context,4716N_("ensure at least <n> lines of context match")),4717{ OPTION_CALLBACK,0,"whitespace", &state,N_("action"),4718N_("detect new or modified lines that have whitespace errors"),47190, option_parse_whitespace },4720{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,4721N_("ignore changes in whitespace when finding context"),4722 PARSE_OPT_NOARG, option_parse_space_change },4723{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,4724N_("ignore changes in whitespace when finding context"),4725 PARSE_OPT_NOARG, option_parse_space_change },4726OPT_BOOL('R',"reverse", &state.apply_in_reverse,4727N_("apply the patch in reverse")),4728OPT_BOOL(0,"unidiff-zero", &state.unidiff_zero,4729N_("don't expect at least one line of context")),4730OPT_BOOL(0,"reject", &state.apply_with_reject,4731N_("leave the rejected hunks in corresponding *.rej files")),4732OPT_BOOL(0,"allow-overlap", &state.allow_overlap,4733N_("allow overlapping hunks")),4734OPT__VERBOSE(&state.apply_verbosely,N_("be verbose")),4735OPT_BIT(0,"inaccurate-eof", &options,4736N_("tolerate incorrectly detected missing new-line at the end of file"),4737 INACCURATE_EOF),4738OPT_BIT(0,"recount", &options,4739N_("do not trust the line counts in the hunk headers"),4740 RECOUNT),4741{ OPTION_CALLBACK,0,"directory", &state,N_("root"),4742N_("prepend <root> to all filenames"),47430, option_parse_directory },4744OPT_END()4745};47464747init_apply_state(&state, prefix);47484749 argc =parse_options(argc, argv, state.prefix, builtin_apply_options,4750 apply_usage,0);47514752if(state.apply_with_reject && state.threeway)4753die("--reject and --3way cannot be used together.");4754if(state.cached && state.threeway)4755die("--cached and --3way cannot be used together.");4756if(state.threeway) {4757if(is_not_gitdir)4758die(_("--3way outside a repository"));4759 state.check_index =1;4760}4761if(state.apply_with_reject)4762 state.apply = state.apply_verbosely =1;4763if(!force_apply && (state.diffstat || state.numstat || state.summary || state.check || state.fake_ancestor))4764 state.apply =0;4765if(state.check_index && is_not_gitdir)4766die(_("--index outside a repository"));4767if(state.cached) {4768if(is_not_gitdir)4769die(_("--cached outside a repository"));4770 state.check_index =1;4771}4772if(state.check_index)4773 state.unsafe_paths =0;47744775for(i =0; i < argc; i++) {4776const char*arg = argv[i];4777int fd;47784779if(!strcmp(arg,"-")) {4780 errs |=apply_patch(&state,0,"<stdin>", options);4781 read_stdin =0;4782continue;4783}else if(0< state.prefix_length)4784 arg =prefix_filename(state.prefix,4785 state.prefix_length,4786 arg);47874788 fd =open(arg, O_RDONLY);4789if(fd <0)4790die_errno(_("can't open patch '%s'"), arg);4791 read_stdin =0;4792set_default_whitespace_mode(&state);4793 errs |=apply_patch(&state, fd, arg, options);4794close(fd);4795}4796set_default_whitespace_mode(&state);4797if(read_stdin)4798 errs |=apply_patch(&state,0,"<stdin>", options);4799if(state.whitespace_error) {4800if(state.squelch_whitespace_errors &&4801 state.squelch_whitespace_errors < state.whitespace_error) {4802int squelched =4803 state.whitespace_error - state.squelch_whitespace_errors;4804warning(Q_("squelched%dwhitespace error",4805"squelched%dwhitespace errors",4806 squelched),4807 squelched);4808}4809if(state.ws_error_action == die_on_ws_error)4810die(Q_("%dline adds whitespace errors.",4811"%dlines add whitespace errors.",4812 state.whitespace_error),4813 state.whitespace_error);4814if(state.applied_after_fixing_ws && state.apply)4815warning("%dline%sapplied after"4816" fixing whitespace errors.",4817 state.applied_after_fixing_ws,4818 state.applied_after_fixing_ws ==1?"":"s");4819else if(state.whitespace_error)4820warning(Q_("%dline adds whitespace errors.",4821"%dlines add whitespace errors.",4822 state.whitespace_error),4823 state.whitespace_error);4824}48254826if(state.update_index) {4827if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK))4828die(_("Unable to write new index file"));4829}48304831clear_apply_state(&state);48324833return!!errs;4834}