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 10#include"cache.h" 11#include"blob.h" 12#include"delta.h" 13#include"diff.h" 14#include"dir.h" 15#include"xdiff-interface.h" 16#include"ll-merge.h" 17#include"lockfile.h" 18#include"parse-options.h" 19#include"quote.h" 20#include"rerere.h" 21#include"apply.h" 22 23static voidgit_apply_config(void) 24{ 25git_config_get_string_const("apply.whitespace", &apply_default_whitespace); 26git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace); 27git_config(git_default_config, NULL); 28} 29 30static intparse_whitespace_option(struct apply_state *state,const char*option) 31{ 32if(!option) { 33 state->ws_error_action = warn_on_ws_error; 34return0; 35} 36if(!strcmp(option,"warn")) { 37 state->ws_error_action = warn_on_ws_error; 38return0; 39} 40if(!strcmp(option,"nowarn")) { 41 state->ws_error_action = nowarn_ws_error; 42return0; 43} 44if(!strcmp(option,"error")) { 45 state->ws_error_action = die_on_ws_error; 46return0; 47} 48if(!strcmp(option,"error-all")) { 49 state->ws_error_action = die_on_ws_error; 50 state->squelch_whitespace_errors =0; 51return0; 52} 53if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 54 state->ws_error_action = correct_ws_error; 55return0; 56} 57returnerror(_("unrecognized whitespace option '%s'"), option); 58} 59 60static intparse_ignorewhitespace_option(struct apply_state *state, 61const char*option) 62{ 63if(!option || !strcmp(option,"no") || 64!strcmp(option,"false") || !strcmp(option,"never") || 65!strcmp(option,"none")) { 66 state->ws_ignore_action = ignore_ws_none; 67return0; 68} 69if(!strcmp(option,"change")) { 70 state->ws_ignore_action = ignore_ws_change; 71return0; 72} 73returnerror(_("unrecognized whitespace ignore option '%s'"), option); 74} 75 76intinit_apply_state(struct apply_state *state, 77const char*prefix, 78struct lock_file *lock_file) 79{ 80memset(state,0,sizeof(*state)); 81 state->prefix = prefix; 82 state->prefix_length = state->prefix ?strlen(state->prefix) :0; 83 state->lock_file = lock_file; 84 state->newfd = -1; 85 state->apply =1; 86 state->line_termination ='\n'; 87 state->p_value =1; 88 state->p_context = UINT_MAX; 89 state->squelch_whitespace_errors =5; 90 state->ws_error_action = warn_on_ws_error; 91 state->ws_ignore_action = ignore_ws_none; 92 state->linenr =1; 93string_list_init(&state->fn_table,0); 94string_list_init(&state->limit_by_name,0); 95string_list_init(&state->symlink_changes,0); 96strbuf_init(&state->root,0); 97 98git_apply_config(); 99if(apply_default_whitespace &&parse_whitespace_option(state, apply_default_whitespace)) 100return-1; 101if(apply_default_ignorewhitespace &&parse_ignorewhitespace_option(state, apply_default_ignorewhitespace)) 102return-1; 103return0; 104} 105 106voidclear_apply_state(struct apply_state *state) 107{ 108string_list_clear(&state->limit_by_name,0); 109string_list_clear(&state->symlink_changes,0); 110strbuf_release(&state->root); 111 112/* &state->fn_table is cleared at the end of apply_patch() */ 113} 114 115intcheck_apply_state(struct apply_state *state,int force_apply) 116{ 117int is_not_gitdir = !startup_info->have_repository; 118 119if(state->apply_with_reject && state->threeway) 120returnerror("--reject and --3way cannot be used together."); 121if(state->cached && state->threeway) 122returnerror("--cached and --3way cannot be used together."); 123if(state->threeway) { 124if(is_not_gitdir) 125returnerror(_("--3way outside a repository")); 126 state->check_index =1; 127} 128if(state->apply_with_reject) { 129 state->apply =1; 130if(state->apply_verbosity == verbosity_normal) 131 state->apply_verbosity = verbosity_verbose; 132} 133if(!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor)) 134 state->apply =0; 135if(state->check_index && is_not_gitdir) 136returnerror(_("--index outside a repository")); 137if(state->cached) { 138if(is_not_gitdir) 139returnerror(_("--cached outside a repository")); 140 state->check_index =1; 141} 142if(state->check_index) 143 state->unsafe_paths =0; 144if(!state->lock_file) 145returnerror("BUG: state->lock_file should not be NULL"); 146 147return0; 148} 149 150static voidset_default_whitespace_mode(struct apply_state *state) 151{ 152if(!state->whitespace_option && !apply_default_whitespace) 153 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 154} 155 156/* 157 * This represents one "hunk" from a patch, starting with 158 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 159 * patch text is pointed at by patch, and its byte length 160 * is stored in size. leading and trailing are the number 161 * of context lines. 162 */ 163struct fragment { 164unsigned long leading, trailing; 165unsigned long oldpos, oldlines; 166unsigned long newpos, newlines; 167/* 168 * 'patch' is usually borrowed from buf in apply_patch(), 169 * but some codepaths store an allocated buffer. 170 */ 171const char*patch; 172unsigned free_patch:1, 173 rejected:1; 174int size; 175int linenr; 176struct fragment *next; 177}; 178 179/* 180 * When dealing with a binary patch, we reuse "leading" field 181 * to store the type of the binary hunk, either deflated "delta" 182 * or deflated "literal". 183 */ 184#define binary_patch_method leading 185#define BINARY_DELTA_DEFLATED 1 186#define BINARY_LITERAL_DEFLATED 2 187 188/* 189 * This represents a "patch" to a file, both metainfo changes 190 * such as creation/deletion, filemode and content changes represented 191 * as a series of fragments. 192 */ 193struct patch { 194char*new_name, *old_name, *def_name; 195unsigned int old_mode, new_mode; 196int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 197int rejected; 198unsigned ws_rule; 199int lines_added, lines_deleted; 200int score; 201unsigned int is_toplevel_relative:1; 202unsigned int inaccurate_eof:1; 203unsigned int is_binary:1; 204unsigned int is_copy:1; 205unsigned int is_rename:1; 206unsigned int recount:1; 207unsigned int conflicted_threeway:1; 208unsigned int direct_to_threeway:1; 209struct fragment *fragments; 210char*result; 211size_t resultsize; 212char old_sha1_prefix[41]; 213char new_sha1_prefix[41]; 214struct patch *next; 215 216/* three-way fallback result */ 217struct object_id threeway_stage[3]; 218}; 219 220static voidfree_fragment_list(struct fragment *list) 221{ 222while(list) { 223struct fragment *next = list->next; 224if(list->free_patch) 225free((char*)list->patch); 226free(list); 227 list = next; 228} 229} 230 231static voidfree_patch(struct patch *patch) 232{ 233free_fragment_list(patch->fragments); 234free(patch->def_name); 235free(patch->old_name); 236free(patch->new_name); 237free(patch->result); 238free(patch); 239} 240 241static voidfree_patch_list(struct patch *list) 242{ 243while(list) { 244struct patch *next = list->next; 245free_patch(list); 246 list = next; 247} 248} 249 250/* 251 * A line in a file, len-bytes long (includes the terminating LF, 252 * except for an incomplete line at the end if the file ends with 253 * one), and its contents hashes to 'hash'. 254 */ 255struct line { 256size_t len; 257unsigned hash :24; 258unsigned flag :8; 259#define LINE_COMMON 1 260#define LINE_PATCHED 2 261}; 262 263/* 264 * This represents a "file", which is an array of "lines". 265 */ 266struct image { 267char*buf; 268size_t len; 269size_t nr; 270size_t alloc; 271struct line *line_allocated; 272struct line *line; 273}; 274 275static uint32_thash_line(const char*cp,size_t len) 276{ 277size_t i; 278uint32_t h; 279for(i =0, h =0; i < len; i++) { 280if(!isspace(cp[i])) { 281 h = h *3+ (cp[i] &0xff); 282} 283} 284return h; 285} 286 287/* 288 * Compare lines s1 of length n1 and s2 of length n2, ignoring 289 * whitespace difference. Returns 1 if they match, 0 otherwise 290 */ 291static intfuzzy_matchlines(const char*s1,size_t n1, 292const char*s2,size_t n2) 293{ 294const char*last1 = s1 + n1 -1; 295const char*last2 = s2 + n2 -1; 296int result =0; 297 298/* ignore line endings */ 299while((*last1 =='\r') || (*last1 =='\n')) 300 last1--; 301while((*last2 =='\r') || (*last2 =='\n')) 302 last2--; 303 304/* skip leading whitespaces, if both begin with whitespace */ 305if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 306while(isspace(*s1) && (s1 <= last1)) 307 s1++; 308while(isspace(*s2) && (s2 <= last2)) 309 s2++; 310} 311/* early return if both lines are empty */ 312if((s1 > last1) && (s2 > last2)) 313return1; 314while(!result) { 315 result = *s1++ - *s2++; 316/* 317 * Skip whitespace inside. We check for whitespace on 318 * both buffers because we don't want "a b" to match 319 * "ab" 320 */ 321if(isspace(*s1) &&isspace(*s2)) { 322while(isspace(*s1) && s1 <= last1) 323 s1++; 324while(isspace(*s2) && s2 <= last2) 325 s2++; 326} 327/* 328 * If we reached the end on one side only, 329 * lines don't match 330 */ 331if( 332((s2 > last2) && (s1 <= last1)) || 333((s1 > last1) && (s2 <= last2))) 334return0; 335if((s1 > last1) && (s2 > last2)) 336break; 337} 338 339return!result; 340} 341 342static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 343{ 344ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 345 img->line_allocated[img->nr].len = len; 346 img->line_allocated[img->nr].hash =hash_line(bol, len); 347 img->line_allocated[img->nr].flag = flag; 348 img->nr++; 349} 350 351/* 352 * "buf" has the file contents to be patched (read from various sources). 353 * attach it to "image" and add line-based index to it. 354 * "image" now owns the "buf". 355 */ 356static voidprepare_image(struct image *image,char*buf,size_t len, 357int prepare_linetable) 358{ 359const char*cp, *ep; 360 361memset(image,0,sizeof(*image)); 362 image->buf = buf; 363 image->len = len; 364 365if(!prepare_linetable) 366return; 367 368 ep = image->buf + image->len; 369 cp = image->buf; 370while(cp < ep) { 371const char*next; 372for(next = cp; next < ep && *next !='\n'; next++) 373; 374if(next < ep) 375 next++; 376add_line_info(image, cp, next - cp,0); 377 cp = next; 378} 379 image->line = image->line_allocated; 380} 381 382static voidclear_image(struct image *image) 383{ 384free(image->buf); 385free(image->line_allocated); 386memset(image,0,sizeof(*image)); 387} 388 389/* fmt must contain _one_ %s and no other substitution */ 390static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 391{ 392struct strbuf sb = STRBUF_INIT; 393 394if(patch->old_name && patch->new_name && 395strcmp(patch->old_name, patch->new_name)) { 396quote_c_style(patch->old_name, &sb, NULL,0); 397strbuf_addstr(&sb," => "); 398quote_c_style(patch->new_name, &sb, NULL,0); 399}else{ 400const char*n = patch->new_name; 401if(!n) 402 n = patch->old_name; 403quote_c_style(n, &sb, NULL,0); 404} 405fprintf(output, fmt, sb.buf); 406fputc('\n', output); 407strbuf_release(&sb); 408} 409 410#define SLOP (16) 411 412static intread_patch_file(struct strbuf *sb,int fd) 413{ 414if(strbuf_read(sb, fd,0) <0) 415returnerror_errno("git apply: failed to read"); 416 417/* 418 * Make sure that we have some slop in the buffer 419 * so that we can do speculative "memcmp" etc, and 420 * see to it that it is NUL-filled. 421 */ 422strbuf_grow(sb, SLOP); 423memset(sb->buf + sb->len,0, SLOP); 424return0; 425} 426 427static unsigned longlinelen(const char*buffer,unsigned long size) 428{ 429unsigned long len =0; 430while(size--) { 431 len++; 432if(*buffer++ =='\n') 433break; 434} 435return len; 436} 437 438static intis_dev_null(const char*str) 439{ 440returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 441} 442 443#define TERM_SPACE 1 444#define TERM_TAB 2 445 446static intname_terminate(int c,int terminate) 447{ 448if(c ==' '&& !(terminate & TERM_SPACE)) 449return0; 450if(c =='\t'&& !(terminate & TERM_TAB)) 451return0; 452 453return1; 454} 455 456/* remove double slashes to make --index work with such filenames */ 457static char*squash_slash(char*name) 458{ 459int i =0, j =0; 460 461if(!name) 462return NULL; 463 464while(name[i]) { 465if((name[j++] = name[i++]) =='/') 466while(name[i] =='/') 467 i++; 468} 469 name[j] ='\0'; 470return name; 471} 472 473static char*find_name_gnu(struct apply_state *state, 474const char*line, 475const char*def, 476int p_value) 477{ 478struct strbuf name = STRBUF_INIT; 479char*cp; 480 481/* 482 * Proposed "new-style" GNU patch/diff format; see 483 * http://marc.info/?l=git&m=112927316408690&w=2 484 */ 485if(unquote_c_style(&name, line, NULL)) { 486strbuf_release(&name); 487return NULL; 488} 489 490for(cp = name.buf; p_value; p_value--) { 491 cp =strchr(cp,'/'); 492if(!cp) { 493strbuf_release(&name); 494return NULL; 495} 496 cp++; 497} 498 499strbuf_remove(&name,0, cp - name.buf); 500if(state->root.len) 501strbuf_insert(&name,0, state->root.buf, state->root.len); 502returnsquash_slash(strbuf_detach(&name, NULL)); 503} 504 505static size_tsane_tz_len(const char*line,size_t len) 506{ 507const char*tz, *p; 508 509if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 510return0; 511 tz = line + len -strlen(" +0500"); 512 513if(tz[1] !='+'&& tz[1] !='-') 514return0; 515 516for(p = tz +2; p != line + len; p++) 517if(!isdigit(*p)) 518return0; 519 520return line + len - tz; 521} 522 523static size_ttz_with_colon_len(const char*line,size_t len) 524{ 525const char*tz, *p; 526 527if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 528return0; 529 tz = line + len -strlen(" +08:00"); 530 531if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 532return0; 533 p = tz +2; 534if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 535!isdigit(*p++) || !isdigit(*p++)) 536return0; 537 538return line + len - tz; 539} 540 541static size_tdate_len(const char*line,size_t len) 542{ 543const char*date, *p; 544 545if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 546return0; 547 p = date = line + len -strlen("72-02-05"); 548 549if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 550!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 551!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 552return0; 553 554if(date - line >=strlen("19") && 555isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 556 date -=strlen("19"); 557 558return line + len - date; 559} 560 561static size_tshort_time_len(const char*line,size_t len) 562{ 563const char*time, *p; 564 565if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 566return0; 567 p = time = line + len -strlen(" 07:01:32"); 568 569/* Permit 1-digit hours? */ 570if(*p++ !=' '|| 571!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 572!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 573!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 574return0; 575 576return line + len - time; 577} 578 579static size_tfractional_time_len(const char*line,size_t len) 580{ 581const char*p; 582size_t n; 583 584/* Expected format: 19:41:17.620000023 */ 585if(!len || !isdigit(line[len -1])) 586return0; 587 p = line + len -1; 588 589/* Fractional seconds. */ 590while(p > line &&isdigit(*p)) 591 p--; 592if(*p !='.') 593return0; 594 595/* Hours, minutes, and whole seconds. */ 596 n =short_time_len(line, p - line); 597if(!n) 598return0; 599 600return line + len - p + n; 601} 602 603static size_ttrailing_spaces_len(const char*line,size_t len) 604{ 605const char*p; 606 607/* Expected format: ' ' x (1 or more) */ 608if(!len || line[len -1] !=' ') 609return0; 610 611 p = line + len; 612while(p != line) { 613 p--; 614if(*p !=' ') 615return line + len - (p +1); 616} 617 618/* All spaces! */ 619return len; 620} 621 622static size_tdiff_timestamp_len(const char*line,size_t len) 623{ 624const char*end = line + len; 625size_t n; 626 627/* 628 * Posix: 2010-07-05 19:41:17 629 * GNU: 2010-07-05 19:41:17.620000023 -0500 630 */ 631 632if(!isdigit(end[-1])) 633return0; 634 635 n =sane_tz_len(line, end - line); 636if(!n) 637 n =tz_with_colon_len(line, end - line); 638 end -= n; 639 640 n =short_time_len(line, end - line); 641if(!n) 642 n =fractional_time_len(line, end - line); 643 end -= n; 644 645 n =date_len(line, end - line); 646if(!n)/* No date. Too bad. */ 647return0; 648 end -= n; 649 650if(end == line)/* No space before date. */ 651return0; 652if(end[-1] =='\t') {/* Success! */ 653 end--; 654return line + len - end; 655} 656if(end[-1] !=' ')/* No space before date. */ 657return0; 658 659/* Whitespace damage. */ 660 end -=trailing_spaces_len(line, end - line); 661return line + len - end; 662} 663 664static char*find_name_common(struct apply_state *state, 665const char*line, 666const char*def, 667int p_value, 668const char*end, 669int terminate) 670{ 671int len; 672const char*start = NULL; 673 674if(p_value ==0) 675 start = line; 676while(line != end) { 677char c = *line; 678 679if(!end &&isspace(c)) { 680if(c =='\n') 681break; 682if(name_terminate(c, terminate)) 683break; 684} 685 line++; 686if(c =='/'&& !--p_value) 687 start = line; 688} 689if(!start) 690returnsquash_slash(xstrdup_or_null(def)); 691 len = line - start; 692if(!len) 693returnsquash_slash(xstrdup_or_null(def)); 694 695/* 696 * Generally we prefer the shorter name, especially 697 * if the other one is just a variation of that with 698 * something else tacked on to the end (ie "file.orig" 699 * or "file~"). 700 */ 701if(def) { 702int deflen =strlen(def); 703if(deflen < len && !strncmp(start, def, deflen)) 704returnsquash_slash(xstrdup(def)); 705} 706 707if(state->root.len) { 708char*ret =xstrfmt("%s%.*s", state->root.buf, len, start); 709returnsquash_slash(ret); 710} 711 712returnsquash_slash(xmemdupz(start, len)); 713} 714 715static char*find_name(struct apply_state *state, 716const char*line, 717char*def, 718int p_value, 719int terminate) 720{ 721if(*line =='"') { 722char*name =find_name_gnu(state, line, def, p_value); 723if(name) 724return name; 725} 726 727returnfind_name_common(state, line, def, p_value, NULL, terminate); 728} 729 730static char*find_name_traditional(struct apply_state *state, 731const char*line, 732char*def, 733int p_value) 734{ 735size_t len; 736size_t date_len; 737 738if(*line =='"') { 739char*name =find_name_gnu(state, line, def, p_value); 740if(name) 741return name; 742} 743 744 len =strchrnul(line,'\n') - line; 745 date_len =diff_timestamp_len(line, len); 746if(!date_len) 747returnfind_name_common(state, line, def, p_value, NULL, TERM_TAB); 748 len -= date_len; 749 750returnfind_name_common(state, line, def, p_value, line + len,0); 751} 752 753static intcount_slashes(const char*cp) 754{ 755int cnt =0; 756char ch; 757 758while((ch = *cp++)) 759if(ch =='/') 760 cnt++; 761return cnt; 762} 763 764/* 765 * Given the string after "--- " or "+++ ", guess the appropriate 766 * p_value for the given patch. 767 */ 768static intguess_p_value(struct apply_state *state,const char*nameline) 769{ 770char*name, *cp; 771int val = -1; 772 773if(is_dev_null(nameline)) 774return-1; 775 name =find_name_traditional(state, nameline, NULL,0); 776if(!name) 777return-1; 778 cp =strchr(name,'/'); 779if(!cp) 780 val =0; 781else if(state->prefix) { 782/* 783 * Does it begin with "a/$our-prefix" and such? Then this is 784 * very likely to apply to our directory. 785 */ 786if(!strncmp(name, state->prefix, state->prefix_length)) 787 val =count_slashes(state->prefix); 788else{ 789 cp++; 790if(!strncmp(cp, state->prefix, state->prefix_length)) 791 val =count_slashes(state->prefix) +1; 792} 793} 794free(name); 795return val; 796} 797 798/* 799 * Does the ---/+++ line have the POSIX timestamp after the last HT? 800 * GNU diff puts epoch there to signal a creation/deletion event. Is 801 * this such a timestamp? 802 */ 803static inthas_epoch_timestamp(const char*nameline) 804{ 805/* 806 * We are only interested in epoch timestamp; any non-zero 807 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 808 * For the same reason, the date must be either 1969-12-31 or 809 * 1970-01-01, and the seconds part must be "00". 810 */ 811const char stamp_regexp[] = 812"^(1969-12-31|1970-01-01)" 813" " 814"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 815" " 816"([-+][0-2][0-9]:?[0-5][0-9])\n"; 817const char*timestamp = NULL, *cp, *colon; 818static regex_t *stamp; 819 regmatch_t m[10]; 820int zoneoffset; 821int hourminute; 822int status; 823 824for(cp = nameline; *cp !='\n'; cp++) { 825if(*cp =='\t') 826 timestamp = cp +1; 827} 828if(!timestamp) 829return0; 830if(!stamp) { 831 stamp =xmalloc(sizeof(*stamp)); 832if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 833warning(_("Cannot prepare timestamp regexp%s"), 834 stamp_regexp); 835return0; 836} 837} 838 839 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 840if(status) { 841if(status != REG_NOMATCH) 842warning(_("regexec returned%dfor input:%s"), 843 status, timestamp); 844return0; 845} 846 847 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 848if(*colon ==':') 849 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 850else 851 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 852if(timestamp[m[3].rm_so] =='-') 853 zoneoffset = -zoneoffset; 854 855/* 856 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 857 * (west of GMT) or 1970-01-01 (east of GMT) 858 */ 859if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 860(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 861return0; 862 863 hourminute = (strtol(timestamp +11, NULL,10) *60+ 864strtol(timestamp +14, NULL,10) - 865 zoneoffset); 866 867return((zoneoffset <0&& hourminute ==1440) || 868(0<= zoneoffset && !hourminute)); 869} 870 871/* 872 * Get the name etc info from the ---/+++ lines of a traditional patch header 873 * 874 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 875 * files, we can happily check the index for a match, but for creating a 876 * new file we should try to match whatever "patch" does. I have no idea. 877 */ 878static intparse_traditional_patch(struct apply_state *state, 879const char*first, 880const char*second, 881struct patch *patch) 882{ 883char*name; 884 885 first +=4;/* skip "--- " */ 886 second +=4;/* skip "+++ " */ 887if(!state->p_value_known) { 888int p, q; 889 p =guess_p_value(state, first); 890 q =guess_p_value(state, second); 891if(p <0) p = q; 892if(0<= p && p == q) { 893 state->p_value = p; 894 state->p_value_known =1; 895} 896} 897if(is_dev_null(first)) { 898 patch->is_new =1; 899 patch->is_delete =0; 900 name =find_name_traditional(state, second, NULL, state->p_value); 901 patch->new_name = name; 902}else if(is_dev_null(second)) { 903 patch->is_new =0; 904 patch->is_delete =1; 905 name =find_name_traditional(state, first, NULL, state->p_value); 906 patch->old_name = name; 907}else{ 908char*first_name; 909 first_name =find_name_traditional(state, first, NULL, state->p_value); 910 name =find_name_traditional(state, second, first_name, state->p_value); 911free(first_name); 912if(has_epoch_timestamp(first)) { 913 patch->is_new =1; 914 patch->is_delete =0; 915 patch->new_name = name; 916}else if(has_epoch_timestamp(second)) { 917 patch->is_new =0; 918 patch->is_delete =1; 919 patch->old_name = name; 920}else{ 921 patch->old_name = name; 922 patch->new_name =xstrdup_or_null(name); 923} 924} 925if(!name) 926returnerror(_("unable to find filename in patch at line%d"), state->linenr); 927 928return0; 929} 930 931static intgitdiff_hdrend(struct apply_state *state, 932const char*line, 933struct patch *patch) 934{ 935return1; 936} 937 938/* 939 * We're anal about diff header consistency, to make 940 * sure that we don't end up having strange ambiguous 941 * patches floating around. 942 * 943 * As a result, gitdiff_{old|new}name() will check 944 * their names against any previous information, just 945 * to make sure.. 946 */ 947#define DIFF_OLD_NAME 0 948#define DIFF_NEW_NAME 1 949 950static intgitdiff_verify_name(struct apply_state *state, 951const char*line, 952int isnull, 953char**name, 954int side) 955{ 956if(!*name && !isnull) { 957*name =find_name(state, line, NULL, state->p_value, TERM_TAB); 958return0; 959} 960 961if(*name) { 962int len =strlen(*name); 963char*another; 964if(isnull) 965returnerror(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 966*name, state->linenr); 967 another =find_name(state, line, NULL, state->p_value, TERM_TAB); 968if(!another ||memcmp(another, *name, len +1)) { 969free(another); 970returnerror((side == DIFF_NEW_NAME) ? 971_("git apply: bad git-diff - inconsistent new filename on line%d") : 972_("git apply: bad git-diff - inconsistent old filename on line%d"), state->linenr); 973} 974free(another); 975}else{ 976/* expect "/dev/null" */ 977if(memcmp("/dev/null", line,9) || line[9] !='\n') 978returnerror(_("git apply: bad git-diff - expected /dev/null on line%d"), state->linenr); 979} 980 981return0; 982} 983 984static intgitdiff_oldname(struct apply_state *state, 985const char*line, 986struct patch *patch) 987{ 988returngitdiff_verify_name(state, line, 989 patch->is_new, &patch->old_name, 990 DIFF_OLD_NAME); 991} 992 993static intgitdiff_newname(struct apply_state *state, 994const char*line, 995struct patch *patch) 996{ 997returngitdiff_verify_name(state, line, 998 patch->is_delete, &patch->new_name, 999 DIFF_NEW_NAME);1000}10011002static intgitdiff_oldmode(struct apply_state *state,1003const char*line,1004struct patch *patch)1005{1006 patch->old_mode =strtoul(line, NULL,8);1007return0;1008}10091010static intgitdiff_newmode(struct apply_state *state,1011const char*line,1012struct patch *patch)1013{1014 patch->new_mode =strtoul(line, NULL,8);1015return0;1016}10171018static intgitdiff_delete(struct apply_state *state,1019const char*line,1020struct patch *patch)1021{1022 patch->is_delete =1;1023free(patch->old_name);1024 patch->old_name =xstrdup_or_null(patch->def_name);1025returngitdiff_oldmode(state, line, patch);1026}10271028static intgitdiff_newfile(struct apply_state *state,1029const char*line,1030struct patch *patch)1031{1032 patch->is_new =1;1033free(patch->new_name);1034 patch->new_name =xstrdup_or_null(patch->def_name);1035returngitdiff_newmode(state, line, patch);1036}10371038static intgitdiff_copysrc(struct apply_state *state,1039const char*line,1040struct patch *patch)1041{1042 patch->is_copy =1;1043free(patch->old_name);1044 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1045return0;1046}10471048static intgitdiff_copydst(struct apply_state *state,1049const char*line,1050struct patch *patch)1051{1052 patch->is_copy =1;1053free(patch->new_name);1054 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1055return0;1056}10571058static intgitdiff_renamesrc(struct apply_state *state,1059const char*line,1060struct patch *patch)1061{1062 patch->is_rename =1;1063free(patch->old_name);1064 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1065return0;1066}10671068static intgitdiff_renamedst(struct apply_state *state,1069const char*line,1070struct patch *patch)1071{1072 patch->is_rename =1;1073free(patch->new_name);1074 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1075return0;1076}10771078static intgitdiff_similarity(struct apply_state *state,1079const char*line,1080struct patch *patch)1081{1082unsigned long val =strtoul(line, NULL,10);1083if(val <=100)1084 patch->score = val;1085return0;1086}10871088static intgitdiff_dissimilarity(struct apply_state *state,1089const char*line,1090struct patch *patch)1091{1092unsigned long val =strtoul(line, NULL,10);1093if(val <=100)1094 patch->score = val;1095return0;1096}10971098static intgitdiff_index(struct apply_state *state,1099const char*line,1100struct patch *patch)1101{1102/*1103 * index line is N hexadecimal, "..", N hexadecimal,1104 * and optional space with octal mode.1105 */1106const char*ptr, *eol;1107int len;11081109 ptr =strchr(line,'.');1110if(!ptr || ptr[1] !='.'||40< ptr - line)1111return0;1112 len = ptr - line;1113memcpy(patch->old_sha1_prefix, line, len);1114 patch->old_sha1_prefix[len] =0;11151116 line = ptr +2;1117 ptr =strchr(line,' ');1118 eol =strchrnul(line,'\n');11191120if(!ptr || eol < ptr)1121 ptr = eol;1122 len = ptr - line;11231124if(40< len)1125return0;1126memcpy(patch->new_sha1_prefix, line, len);1127 patch->new_sha1_prefix[len] =0;1128if(*ptr ==' ')1129 patch->old_mode =strtoul(ptr+1, NULL,8);1130return0;1131}11321133/*1134 * This is normal for a diff that doesn't change anything: we'll fall through1135 * into the next diff. Tell the parser to break out.1136 */1137static intgitdiff_unrecognized(struct apply_state *state,1138const char*line,1139struct patch *patch)1140{1141return1;1142}11431144/*1145 * Skip p_value leading components from "line"; as we do not accept1146 * absolute paths, return NULL in that case.1147 */1148static const char*skip_tree_prefix(struct apply_state *state,1149const char*line,1150int llen)1151{1152int nslash;1153int i;11541155if(!state->p_value)1156return(llen && line[0] =='/') ? NULL : line;11571158 nslash = state->p_value;1159for(i =0; i < llen; i++) {1160int ch = line[i];1161if(ch =='/'&& --nslash <=0)1162return(i ==0) ? NULL : &line[i +1];1163}1164return NULL;1165}11661167/*1168 * This is to extract the same name that appears on "diff --git"1169 * line. We do not find and return anything if it is a rename1170 * patch, and it is OK because we will find the name elsewhere.1171 * We need to reliably find name only when it is mode-change only,1172 * creation or deletion of an empty file. In any of these cases,1173 * both sides are the same name under a/ and b/ respectively.1174 */1175static char*git_header_name(struct apply_state *state,1176const char*line,1177int llen)1178{1179const char*name;1180const char*second = NULL;1181size_t len, line_len;11821183 line +=strlen("diff --git ");1184 llen -=strlen("diff --git ");11851186if(*line =='"') {1187const char*cp;1188struct strbuf first = STRBUF_INIT;1189struct strbuf sp = STRBUF_INIT;11901191if(unquote_c_style(&first, line, &second))1192goto free_and_fail1;11931194/* strip the a/b prefix including trailing slash */1195 cp =skip_tree_prefix(state, first.buf, first.len);1196if(!cp)1197goto free_and_fail1;1198strbuf_remove(&first,0, cp - first.buf);11991200/*1201 * second points at one past closing dq of name.1202 * find the second name.1203 */1204while((second < line + llen) &&isspace(*second))1205 second++;12061207if(line + llen <= second)1208goto free_and_fail1;1209if(*second =='"') {1210if(unquote_c_style(&sp, second, NULL))1211goto free_and_fail1;1212 cp =skip_tree_prefix(state, sp.buf, sp.len);1213if(!cp)1214goto free_and_fail1;1215/* They must match, otherwise ignore */1216if(strcmp(cp, first.buf))1217goto free_and_fail1;1218strbuf_release(&sp);1219returnstrbuf_detach(&first, NULL);1220}12211222/* unquoted second */1223 cp =skip_tree_prefix(state, second, line + llen - second);1224if(!cp)1225goto free_and_fail1;1226if(line + llen - cp != first.len ||1227memcmp(first.buf, cp, first.len))1228goto free_and_fail1;1229returnstrbuf_detach(&first, NULL);12301231 free_and_fail1:1232strbuf_release(&first);1233strbuf_release(&sp);1234return NULL;1235}12361237/* unquoted first name */1238 name =skip_tree_prefix(state, line, llen);1239if(!name)1240return NULL;12411242/*1243 * since the first name is unquoted, a dq if exists must be1244 * the beginning of the second name.1245 */1246for(second = name; second < line + llen; second++) {1247if(*second =='"') {1248struct strbuf sp = STRBUF_INIT;1249const char*np;12501251if(unquote_c_style(&sp, second, NULL))1252goto free_and_fail2;12531254 np =skip_tree_prefix(state, sp.buf, sp.len);1255if(!np)1256goto free_and_fail2;12571258 len = sp.buf + sp.len - np;1259if(len < second - name &&1260!strncmp(np, name, len) &&1261isspace(name[len])) {1262/* Good */1263strbuf_remove(&sp,0, np - sp.buf);1264returnstrbuf_detach(&sp, NULL);1265}12661267 free_and_fail2:1268strbuf_release(&sp);1269return NULL;1270}1271}12721273/*1274 * Accept a name only if it shows up twice, exactly the same1275 * form.1276 */1277 second =strchr(name,'\n');1278if(!second)1279return NULL;1280 line_len = second - name;1281for(len =0; ; len++) {1282switch(name[len]) {1283default:1284continue;1285case'\n':1286return NULL;1287case'\t':case' ':1288/*1289 * Is this the separator between the preimage1290 * and the postimage pathname? Again, we are1291 * only interested in the case where there is1292 * no rename, as this is only to set def_name1293 * and a rename patch has the names elsewhere1294 * in an unambiguous form.1295 */1296if(!name[len +1])1297return NULL;/* no postimage name */1298 second =skip_tree_prefix(state, name + len +1,1299 line_len - (len +1));1300if(!second)1301return NULL;1302/*1303 * Does len bytes starting at "name" and "second"1304 * (that are separated by one HT or SP we just1305 * found) exactly match?1306 */1307if(second[len] =='\n'&& !strncmp(name, second, len))1308returnxmemdupz(name, len);1309}1310}1311}13121313/* Verify that we recognize the lines following a git header */1314static intparse_git_header(struct apply_state *state,1315const char*line,1316int len,1317unsigned int size,1318struct patch *patch)1319{1320unsigned long offset;13211322/* A git diff has explicit new/delete information, so we don't guess */1323 patch->is_new =0;1324 patch->is_delete =0;13251326/*1327 * Some things may not have the old name in the1328 * rest of the headers anywhere (pure mode changes,1329 * or removing or adding empty files), so we get1330 * the default name from the header.1331 */1332 patch->def_name =git_header_name(state, line, len);1333if(patch->def_name && state->root.len) {1334char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1335free(patch->def_name);1336 patch->def_name = s;1337}13381339 line += len;1340 size -= len;1341 state->linenr++;1342for(offset = len ; size >0; offset += len, size -= len, line += len, state->linenr++) {1343static const struct opentry {1344const char*str;1345int(*fn)(struct apply_state *,const char*,struct patch *);1346} optable[] = {1347{"@@ -", gitdiff_hdrend },1348{"--- ", gitdiff_oldname },1349{"+++ ", gitdiff_newname },1350{"old mode ", gitdiff_oldmode },1351{"new mode ", gitdiff_newmode },1352{"deleted file mode ", gitdiff_delete },1353{"new file mode ", gitdiff_newfile },1354{"copy from ", gitdiff_copysrc },1355{"copy to ", gitdiff_copydst },1356{"rename old ", gitdiff_renamesrc },1357{"rename new ", gitdiff_renamedst },1358{"rename from ", gitdiff_renamesrc },1359{"rename to ", gitdiff_renamedst },1360{"similarity index ", gitdiff_similarity },1361{"dissimilarity index ", gitdiff_dissimilarity },1362{"index ", gitdiff_index },1363{"", gitdiff_unrecognized },1364};1365int i;13661367 len =linelen(line, size);1368if(!len || line[len-1] !='\n')1369break;1370for(i =0; i <ARRAY_SIZE(optable); i++) {1371const struct opentry *p = optable + i;1372int oplen =strlen(p->str);1373int res;1374if(len < oplen ||memcmp(p->str, line, oplen))1375continue;1376 res = p->fn(state, line + oplen, patch);1377if(res <0)1378return-1;1379if(res >0)1380return offset;1381break;1382}1383}13841385return offset;1386}13871388static intparse_num(const char*line,unsigned long*p)1389{1390char*ptr;13911392if(!isdigit(*line))1393return0;1394*p =strtoul(line, &ptr,10);1395return ptr - line;1396}13971398static intparse_range(const char*line,int len,int offset,const char*expect,1399unsigned long*p1,unsigned long*p2)1400{1401int digits, ex;14021403if(offset <0|| offset >= len)1404return-1;1405 line += offset;1406 len -= offset;14071408 digits =parse_num(line, p1);1409if(!digits)1410return-1;14111412 offset += digits;1413 line += digits;1414 len -= digits;14151416*p2 =1;1417if(*line ==',') {1418 digits =parse_num(line+1, p2);1419if(!digits)1420return-1;14211422 offset += digits+1;1423 line += digits+1;1424 len -= digits+1;1425}14261427 ex =strlen(expect);1428if(ex > len)1429return-1;1430if(memcmp(line, expect, ex))1431return-1;14321433return offset + ex;1434}14351436static voidrecount_diff(const char*line,int size,struct fragment *fragment)1437{1438int oldlines =0, newlines =0, ret =0;14391440if(size <1) {1441warning("recount: ignore empty hunk");1442return;1443}14441445for(;;) {1446int len =linelen(line, size);1447 size -= len;1448 line += len;14491450if(size <1)1451break;14521453switch(*line) {1454case' ':case'\n':1455 newlines++;1456/* fall through */1457case'-':1458 oldlines++;1459continue;1460case'+':1461 newlines++;1462continue;1463case'\\':1464continue;1465case'@':1466 ret = size <3|| !starts_with(line,"@@ ");1467break;1468case'd':1469 ret = size <5|| !starts_with(line,"diff ");1470break;1471default:1472 ret = -1;1473break;1474}1475if(ret) {1476warning(_("recount: unexpected line: %.*s"),1477(int)linelen(line, size), line);1478return;1479}1480break;1481}1482 fragment->oldlines = oldlines;1483 fragment->newlines = newlines;1484}14851486/*1487 * Parse a unified diff fragment header of the1488 * form "@@ -a,b +c,d @@"1489 */1490static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1491{1492int offset;14931494if(!len || line[len-1] !='\n')1495return-1;14961497/* Figure out the number of lines in a fragment */1498 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1499 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);15001501return offset;1502}15031504/*1505 * Find file diff header1506 *1507 * Returns:1508 * -1 if no header was found1509 * -128 in case of error1510 * the size of the header in bytes (called "offset") otherwise1511 */1512static intfind_header(struct apply_state *state,1513const char*line,1514unsigned long size,1515int*hdrsize,1516struct patch *patch)1517{1518unsigned long offset, len;15191520 patch->is_toplevel_relative =0;1521 patch->is_rename = patch->is_copy =0;1522 patch->is_new = patch->is_delete = -1;1523 patch->old_mode = patch->new_mode =0;1524 patch->old_name = patch->new_name = NULL;1525for(offset =0; size >0; offset += len, size -= len, line += len, state->linenr++) {1526unsigned long nextlen;15271528 len =linelen(line, size);1529if(!len)1530break;15311532/* Testing this early allows us to take a few shortcuts.. */1533if(len <6)1534continue;15351536/*1537 * Make sure we don't find any unconnected patch fragments.1538 * That's a sign that we didn't find a header, and that a1539 * patch has become corrupted/broken up.1540 */1541if(!memcmp("@@ -", line,4)) {1542struct fragment dummy;1543if(parse_fragment_header(line, len, &dummy) <0)1544continue;1545error(_("patch fragment without header at line%d: %.*s"),1546 state->linenr, (int)len-1, line);1547return-128;1548}15491550if(size < len +6)1551break;15521553/*1554 * Git patch? It might not have a real patch, just a rename1555 * or mode change, so we handle that specially1556 */1557if(!memcmp("diff --git ", line,11)) {1558int git_hdr_len =parse_git_header(state, line, len, size, patch);1559if(git_hdr_len <0)1560return-128;1561if(git_hdr_len <= len)1562continue;1563if(!patch->old_name && !patch->new_name) {1564if(!patch->def_name) {1565error(Q_("git diff header lacks filename information when removing "1566"%dleading pathname component (line%d)",1567"git diff header lacks filename information when removing "1568"%dleading pathname components (line%d)",1569 state->p_value),1570 state->p_value, state->linenr);1571return-128;1572}1573 patch->old_name =xstrdup(patch->def_name);1574 patch->new_name =xstrdup(patch->def_name);1575}1576if(!patch->is_delete && !patch->new_name) {1577error("git diff header lacks filename information "1578"(line%d)", state->linenr);1579return-128;1580}1581 patch->is_toplevel_relative =1;1582*hdrsize = git_hdr_len;1583return offset;1584}15851586/* --- followed by +++ ? */1587if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1588continue;15891590/*1591 * We only accept unified patches, so we want it to1592 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1593 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1594 */1595 nextlen =linelen(line + len, size - len);1596if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1597continue;15981599/* Ok, we'll consider it a patch */1600if(parse_traditional_patch(state, line, line+len, patch))1601return-128;1602*hdrsize = len + nextlen;1603 state->linenr +=2;1604return offset;1605}1606return-1;1607}16081609static voidrecord_ws_error(struct apply_state *state,1610unsigned result,1611const char*line,1612int len,1613int linenr)1614{1615char*err;16161617if(!result)1618return;16191620 state->whitespace_error++;1621if(state->squelch_whitespace_errors &&1622 state->squelch_whitespace_errors < state->whitespace_error)1623return;16241625 err =whitespace_error_string(result);1626if(state->apply_verbosity > verbosity_silent)1627fprintf(stderr,"%s:%d:%s.\n%.*s\n",1628 state->patch_input_file, linenr, err, len, line);1629free(err);1630}16311632static voidcheck_whitespace(struct apply_state *state,1633const char*line,1634int len,1635unsigned ws_rule)1636{1637unsigned result =ws_check(line +1, len -1, ws_rule);16381639record_ws_error(state, result, line +1, len -2, state->linenr);1640}16411642/*1643 * Parse a unified diff. Note that this really needs to parse each1644 * fragment separately, since the only way to know the difference1645 * between a "---" that is part of a patch, and a "---" that starts1646 * the next patch is to look at the line counts..1647 */1648static intparse_fragment(struct apply_state *state,1649const char*line,1650unsigned long size,1651struct patch *patch,1652struct fragment *fragment)1653{1654int added, deleted;1655int len =linelen(line, size), offset;1656unsigned long oldlines, newlines;1657unsigned long leading, trailing;16581659 offset =parse_fragment_header(line, len, fragment);1660if(offset <0)1661return-1;1662if(offset >0&& patch->recount)1663recount_diff(line + offset, size - offset, fragment);1664 oldlines = fragment->oldlines;1665 newlines = fragment->newlines;1666 leading =0;1667 trailing =0;16681669/* Parse the thing.. */1670 line += len;1671 size -= len;1672 state->linenr++;1673 added = deleted =0;1674for(offset = len;16750< size;1676 offset += len, size -= len, line += len, state->linenr++) {1677if(!oldlines && !newlines)1678break;1679 len =linelen(line, size);1680if(!len || line[len-1] !='\n')1681return-1;1682switch(*line) {1683default:1684return-1;1685case'\n':/* newer GNU diff, an empty context line */1686case' ':1687 oldlines--;1688 newlines--;1689if(!deleted && !added)1690 leading++;1691 trailing++;1692if(!state->apply_in_reverse &&1693 state->ws_error_action == correct_ws_error)1694check_whitespace(state, line, len, patch->ws_rule);1695break;1696case'-':1697if(state->apply_in_reverse &&1698 state->ws_error_action != nowarn_ws_error)1699check_whitespace(state, line, len, patch->ws_rule);1700 deleted++;1701 oldlines--;1702 trailing =0;1703break;1704case'+':1705if(!state->apply_in_reverse &&1706 state->ws_error_action != nowarn_ws_error)1707check_whitespace(state, line, len, patch->ws_rule);1708 added++;1709 newlines--;1710 trailing =0;1711break;17121713/*1714 * We allow "\ No newline at end of file". Depending1715 * on locale settings when the patch was produced we1716 * don't know what this line looks like. The only1717 * thing we do know is that it begins with "\ ".1718 * Checking for 12 is just for sanity check -- any1719 * l10n of "\ No newline..." is at least that long.1720 */1721case'\\':1722if(len <12||memcmp(line,"\\",2))1723return-1;1724break;1725}1726}1727if(oldlines || newlines)1728return-1;1729if(!deleted && !added)1730return-1;17311732 fragment->leading = leading;1733 fragment->trailing = trailing;17341735/*1736 * If a fragment ends with an incomplete line, we failed to include1737 * it in the above loop because we hit oldlines == newlines == 01738 * before seeing it.1739 */1740if(12< size && !memcmp(line,"\\",2))1741 offset +=linelen(line, size);17421743 patch->lines_added += added;1744 patch->lines_deleted += deleted;17451746if(0< patch->is_new && oldlines)1747returnerror(_("new file depends on old contents"));1748if(0< patch->is_delete && newlines)1749returnerror(_("deleted file still has contents"));1750return offset;1751}17521753/*1754 * We have seen "diff --git a/... b/..." header (or a traditional patch1755 * header). Read hunks that belong to this patch into fragments and hang1756 * them to the given patch structure.1757 *1758 * The (fragment->patch, fragment->size) pair points into the memory given1759 * by the caller, not a copy, when we return.1760 *1761 * Returns:1762 * -1 in case of error,1763 * the number of bytes in the patch otherwise.1764 */1765static intparse_single_patch(struct apply_state *state,1766const char*line,1767unsigned long size,1768struct patch *patch)1769{1770unsigned long offset =0;1771unsigned long oldlines =0, newlines =0, context =0;1772struct fragment **fragp = &patch->fragments;17731774while(size >4&& !memcmp(line,"@@ -",4)) {1775struct fragment *fragment;1776int len;17771778 fragment =xcalloc(1,sizeof(*fragment));1779 fragment->linenr = state->linenr;1780 len =parse_fragment(state, line, size, patch, fragment);1781if(len <=0) {1782free(fragment);1783returnerror(_("corrupt patch at line%d"), state->linenr);1784}1785 fragment->patch = line;1786 fragment->size = len;1787 oldlines += fragment->oldlines;1788 newlines += fragment->newlines;1789 context += fragment->leading + fragment->trailing;17901791*fragp = fragment;1792 fragp = &fragment->next;17931794 offset += len;1795 line += len;1796 size -= len;1797}17981799/*1800 * If something was removed (i.e. we have old-lines) it cannot1801 * be creation, and if something was added it cannot be1802 * deletion. However, the reverse is not true; --unified=01803 * patches that only add are not necessarily creation even1804 * though they do not have any old lines, and ones that only1805 * delete are not necessarily deletion.1806 *1807 * Unfortunately, a real creation/deletion patch do _not_ have1808 * any context line by definition, so we cannot safely tell it1809 * apart with --unified=0 insanity. At least if the patch has1810 * more than one hunk it is not creation or deletion.1811 */1812if(patch->is_new <0&&1813(oldlines || (patch->fragments && patch->fragments->next)))1814 patch->is_new =0;1815if(patch->is_delete <0&&1816(newlines || (patch->fragments && patch->fragments->next)))1817 patch->is_delete =0;18181819if(0< patch->is_new && oldlines)1820returnerror(_("new file%sdepends on old contents"), patch->new_name);1821if(0< patch->is_delete && newlines)1822returnerror(_("deleted file%sstill has contents"), patch->old_name);1823if(!patch->is_delete && !newlines && context && state->apply_verbosity > verbosity_silent)1824fprintf_ln(stderr,1825_("** warning: "1826"file%sbecomes empty but is not deleted"),1827 patch->new_name);18281829return offset;1830}18311832staticinlineintmetadata_changes(struct patch *patch)1833{1834return patch->is_rename >0||1835 patch->is_copy >0||1836 patch->is_new >0||1837 patch->is_delete ||1838(patch->old_mode && patch->new_mode &&1839 patch->old_mode != patch->new_mode);1840}18411842static char*inflate_it(const void*data,unsigned long size,1843unsigned long inflated_size)1844{1845 git_zstream stream;1846void*out;1847int st;18481849memset(&stream,0,sizeof(stream));18501851 stream.next_in = (unsigned char*)data;1852 stream.avail_in = size;1853 stream.next_out = out =xmalloc(inflated_size);1854 stream.avail_out = inflated_size;1855git_inflate_init(&stream);1856 st =git_inflate(&stream, Z_FINISH);1857git_inflate_end(&stream);1858if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1859free(out);1860return NULL;1861}1862return out;1863}18641865/*1866 * Read a binary hunk and return a new fragment; fragment->patch1867 * points at an allocated memory that the caller must free, so1868 * it is marked as "->free_patch = 1".1869 */1870static struct fragment *parse_binary_hunk(struct apply_state *state,1871char**buf_p,1872unsigned long*sz_p,1873int*status_p,1874int*used_p)1875{1876/*1877 * Expect a line that begins with binary patch method ("literal"1878 * or "delta"), followed by the length of data before deflating.1879 * a sequence of 'length-byte' followed by base-85 encoded data1880 * should follow, terminated by a newline.1881 *1882 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1883 * and we would limit the patch line to 66 characters,1884 * so one line can fit up to 13 groups that would decode1885 * to 52 bytes max. The length byte 'A'-'Z' corresponds1886 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1887 */1888int llen, used;1889unsigned long size = *sz_p;1890char*buffer = *buf_p;1891int patch_method;1892unsigned long origlen;1893char*data = NULL;1894int hunk_size =0;1895struct fragment *frag;18961897 llen =linelen(buffer, size);1898 used = llen;18991900*status_p =0;19011902if(starts_with(buffer,"delta ")) {1903 patch_method = BINARY_DELTA_DEFLATED;1904 origlen =strtoul(buffer +6, NULL,10);1905}1906else if(starts_with(buffer,"literal ")) {1907 patch_method = BINARY_LITERAL_DEFLATED;1908 origlen =strtoul(buffer +8, NULL,10);1909}1910else1911return NULL;19121913 state->linenr++;1914 buffer += llen;1915while(1) {1916int byte_length, max_byte_length, newsize;1917 llen =linelen(buffer, size);1918 used += llen;1919 state->linenr++;1920if(llen ==1) {1921/* consume the blank line */1922 buffer++;1923 size--;1924break;1925}1926/*1927 * Minimum line is "A00000\n" which is 7-byte long,1928 * and the line length must be multiple of 5 plus 2.1929 */1930if((llen <7) || (llen-2) %5)1931goto corrupt;1932 max_byte_length = (llen -2) /5*4;1933 byte_length = *buffer;1934if('A'<= byte_length && byte_length <='Z')1935 byte_length = byte_length -'A'+1;1936else if('a'<= byte_length && byte_length <='z')1937 byte_length = byte_length -'a'+27;1938else1939goto corrupt;1940/* if the input length was not multiple of 4, we would1941 * have filler at the end but the filler should never1942 * exceed 3 bytes1943 */1944if(max_byte_length < byte_length ||1945 byte_length <= max_byte_length -4)1946goto corrupt;1947 newsize = hunk_size + byte_length;1948 data =xrealloc(data, newsize);1949if(decode_85(data + hunk_size, buffer +1, byte_length))1950goto corrupt;1951 hunk_size = newsize;1952 buffer += llen;1953 size -= llen;1954}19551956 frag =xcalloc(1,sizeof(*frag));1957 frag->patch =inflate_it(data, hunk_size, origlen);1958 frag->free_patch =1;1959if(!frag->patch)1960goto corrupt;1961free(data);1962 frag->size = origlen;1963*buf_p = buffer;1964*sz_p = size;1965*used_p = used;1966 frag->binary_patch_method = patch_method;1967return frag;19681969 corrupt:1970free(data);1971*status_p = -1;1972error(_("corrupt binary patch at line%d: %.*s"),1973 state->linenr-1, llen-1, buffer);1974return NULL;1975}19761977/*1978 * Returns:1979 * -1 in case of error,1980 * the length of the parsed binary patch otherwise1981 */1982static intparse_binary(struct apply_state *state,1983char*buffer,1984unsigned long size,1985struct patch *patch)1986{1987/*1988 * We have read "GIT binary patch\n"; what follows is a line1989 * that says the patch method (currently, either "literal" or1990 * "delta") and the length of data before deflating; a1991 * sequence of 'length-byte' followed by base-85 encoded data1992 * follows.1993 *1994 * When a binary patch is reversible, there is another binary1995 * hunk in the same format, starting with patch method (either1996 * "literal" or "delta") with the length of data, and a sequence1997 * of length-byte + base-85 encoded data, terminated with another1998 * empty line. This data, when applied to the postimage, produces1999 * the preimage.2000 */2001struct fragment *forward;2002struct fragment *reverse;2003int status;2004int used, used_1;20052006 forward =parse_binary_hunk(state, &buffer, &size, &status, &used);2007if(!forward && !status)2008/* there has to be one hunk (forward hunk) */2009returnerror(_("unrecognized binary patch at line%d"), state->linenr-1);2010if(status)2011/* otherwise we already gave an error message */2012return status;20132014 reverse =parse_binary_hunk(state, &buffer, &size, &status, &used_1);2015if(reverse)2016 used += used_1;2017else if(status) {2018/*2019 * Not having reverse hunk is not an error, but having2020 * a corrupt reverse hunk is.2021 */2022free((void*) forward->patch);2023free(forward);2024return status;2025}2026 forward->next = reverse;2027 patch->fragments = forward;2028 patch->is_binary =1;2029return used;2030}20312032static voidprefix_one(struct apply_state *state,char**name)2033{2034char*old_name = *name;2035if(!old_name)2036return;2037*name =xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));2038free(old_name);2039}20402041static voidprefix_patch(struct apply_state *state,struct patch *p)2042{2043if(!state->prefix || p->is_toplevel_relative)2044return;2045prefix_one(state, &p->new_name);2046prefix_one(state, &p->old_name);2047}20482049/*2050 * include/exclude2051 */20522053static voidadd_name_limit(struct apply_state *state,2054const char*name,2055int exclude)2056{2057struct string_list_item *it;20582059 it =string_list_append(&state->limit_by_name, name);2060 it->util = exclude ? NULL : (void*)1;2061}20622063static intuse_patch(struct apply_state *state,struct patch *p)2064{2065const char*pathname = p->new_name ? p->new_name : p->old_name;2066int i;20672068/* Paths outside are not touched regardless of "--include" */2069if(0< state->prefix_length) {2070int pathlen =strlen(pathname);2071if(pathlen <= state->prefix_length ||2072memcmp(state->prefix, pathname, state->prefix_length))2073return0;2074}20752076/* See if it matches any of exclude/include rule */2077for(i =0; i < state->limit_by_name.nr; i++) {2078struct string_list_item *it = &state->limit_by_name.items[i];2079if(!wildmatch(it->string, pathname,0, NULL))2080return(it->util != NULL);2081}20822083/*2084 * If we had any include, a path that does not match any rule is2085 * not used. Otherwise, we saw bunch of exclude rules (or none)2086 * and such a path is used.2087 */2088return!state->has_include;2089}20902091/*2092 * Read the patch text in "buffer" that extends for "size" bytes; stop2093 * reading after seeing a single patch (i.e. changes to a single file).2094 * Create fragments (i.e. patch hunks) and hang them to the given patch.2095 *2096 * Returns:2097 * -1 if no header was found or parse_binary() failed,2098 * -128 on another error,2099 * the number of bytes consumed otherwise,2100 * so that the caller can call us again for the next patch.2101 */2102static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2103{2104int hdrsize, patchsize;2105int offset =find_header(state, buffer, size, &hdrsize, patch);21062107if(offset <0)2108return offset;21092110prefix_patch(state, patch);21112112if(!use_patch(state, patch))2113 patch->ws_rule =0;2114else2115 patch->ws_rule =whitespace_rule(patch->new_name2116? patch->new_name2117: patch->old_name);21182119 patchsize =parse_single_patch(state,2120 buffer + offset + hdrsize,2121 size - offset - hdrsize,2122 patch);21232124if(patchsize <0)2125return-128;21262127if(!patchsize) {2128static const char git_binary[] ="GIT binary patch\n";2129int hd = hdrsize + offset;2130unsigned long llen =linelen(buffer + hd, size - hd);21312132if(llen ==sizeof(git_binary) -1&&2133!memcmp(git_binary, buffer + hd, llen)) {2134int used;2135 state->linenr++;2136 used =parse_binary(state, buffer + hd + llen,2137 size - hd - llen, patch);2138if(used <0)2139return-1;2140if(used)2141 patchsize = used + llen;2142else2143 patchsize =0;2144}2145else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2146static const char*binhdr[] = {2147"Binary files ",2148"Files ",2149 NULL,2150};2151int i;2152for(i =0; binhdr[i]; i++) {2153int len =strlen(binhdr[i]);2154if(len < size - hd &&2155!memcmp(binhdr[i], buffer + hd, len)) {2156 state->linenr++;2157 patch->is_binary =1;2158 patchsize = llen;2159break;2160}2161}2162}21632164/* Empty patch cannot be applied if it is a text patch2165 * without metadata change. A binary patch appears2166 * empty to us here.2167 */2168if((state->apply || state->check) &&2169(!patch->is_binary && !metadata_changes(patch))) {2170error(_("patch with only garbage at line%d"), state->linenr);2171return-128;2172}2173}21742175return offset + hdrsize + patchsize;2176}21772178#define swap(a,b) myswap((a),(b),sizeof(a))21792180#define myswap(a, b, size) do { \2181 unsigned char mytmp[size]; \2182 memcpy(mytmp, &a, size); \2183 memcpy(&a, &b, size); \2184 memcpy(&b, mytmp, size); \2185} while (0)21862187static voidreverse_patches(struct patch *p)2188{2189for(; p; p = p->next) {2190struct fragment *frag = p->fragments;21912192swap(p->new_name, p->old_name);2193swap(p->new_mode, p->old_mode);2194swap(p->is_new, p->is_delete);2195swap(p->lines_added, p->lines_deleted);2196swap(p->old_sha1_prefix, p->new_sha1_prefix);21972198for(; frag; frag = frag->next) {2199swap(frag->newpos, frag->oldpos);2200swap(frag->newlines, frag->oldlines);2201}2202}2203}22042205static const char pluses[] =2206"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2207static const char minuses[]=2208"----------------------------------------------------------------------";22092210static voidshow_stats(struct apply_state *state,struct patch *patch)2211{2212struct strbuf qname = STRBUF_INIT;2213char*cp = patch->new_name ? patch->new_name : patch->old_name;2214int max, add, del;22152216quote_c_style(cp, &qname, NULL,0);22172218/*2219 * "scale" the filename2220 */2221 max = state->max_len;2222if(max >50)2223 max =50;22242225if(qname.len > max) {2226 cp =strchr(qname.buf + qname.len +3- max,'/');2227if(!cp)2228 cp = qname.buf + qname.len +3- max;2229strbuf_splice(&qname,0, cp - qname.buf,"...",3);2230}22312232if(patch->is_binary) {2233printf(" %-*s | Bin\n", max, qname.buf);2234strbuf_release(&qname);2235return;2236}22372238printf(" %-*s |", max, qname.buf);2239strbuf_release(&qname);22402241/*2242 * scale the add/delete2243 */2244 max = max + state->max_change >70?70- max : state->max_change;2245 add = patch->lines_added;2246 del = patch->lines_deleted;22472248if(state->max_change >0) {2249int total = ((add + del) * max + state->max_change /2) / state->max_change;2250 add = (add * max + state->max_change /2) / state->max_change;2251 del = total - add;2252}2253printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2254 add, pluses, del, minuses);2255}22562257static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2258{2259switch(st->st_mode & S_IFMT) {2260case S_IFLNK:2261if(strbuf_readlink(buf, path, st->st_size) <0)2262returnerror(_("unable to read symlink%s"), path);2263return0;2264case S_IFREG:2265if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2266returnerror(_("unable to open or read%s"), path);2267convert_to_git(path, buf->buf, buf->len, buf,0);2268return0;2269default:2270return-1;2271}2272}22732274/*2275 * Update the preimage, and the common lines in postimage,2276 * from buffer buf of length len. If postlen is 0 the postimage2277 * is updated in place, otherwise it's updated on a new buffer2278 * of length postlen2279 */22802281static voidupdate_pre_post_images(struct image *preimage,2282struct image *postimage,2283char*buf,2284size_t len,size_t postlen)2285{2286int i, ctx, reduced;2287char*new, *old, *fixed;2288struct image fixed_preimage;22892290/*2291 * Update the preimage with whitespace fixes. Note that we2292 * are not losing preimage->buf -- apply_one_fragment() will2293 * free "oldlines".2294 */2295prepare_image(&fixed_preimage, buf, len,1);2296assert(postlen2297? fixed_preimage.nr == preimage->nr2298: fixed_preimage.nr <= preimage->nr);2299for(i =0; i < fixed_preimage.nr; i++)2300 fixed_preimage.line[i].flag = preimage->line[i].flag;2301free(preimage->line_allocated);2302*preimage = fixed_preimage;23032304/*2305 * Adjust the common context lines in postimage. This can be2306 * done in-place when we are shrinking it with whitespace2307 * fixing, but needs a new buffer when ignoring whitespace or2308 * expanding leading tabs to spaces.2309 *2310 * We trust the caller to tell us if the update can be done2311 * in place (postlen==0) or not.2312 */2313 old = postimage->buf;2314if(postlen)2315new= postimage->buf =xmalloc(postlen);2316else2317new= old;2318 fixed = preimage->buf;23192320for(i = reduced = ctx =0; i < postimage->nr; i++) {2321size_t l_len = postimage->line[i].len;2322if(!(postimage->line[i].flag & LINE_COMMON)) {2323/* an added line -- no counterparts in preimage */2324memmove(new, old, l_len);2325 old += l_len;2326new+= l_len;2327continue;2328}23292330/* a common context -- skip it in the original postimage */2331 old += l_len;23322333/* and find the corresponding one in the fixed preimage */2334while(ctx < preimage->nr &&2335!(preimage->line[ctx].flag & LINE_COMMON)) {2336 fixed += preimage->line[ctx].len;2337 ctx++;2338}23392340/*2341 * preimage is expected to run out, if the caller2342 * fixed addition of trailing blank lines.2343 */2344if(preimage->nr <= ctx) {2345 reduced++;2346continue;2347}23482349/* and copy it in, while fixing the line length */2350 l_len = preimage->line[ctx].len;2351memcpy(new, fixed, l_len);2352new+= l_len;2353 fixed += l_len;2354 postimage->line[i].len = l_len;2355 ctx++;2356}23572358if(postlen2359? postlen <new- postimage->buf2360: postimage->len <new- postimage->buf)2361die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2362(int)postlen, (int) postimage->len, (int)(new- postimage->buf));23632364/* Fix the length of the whole thing */2365 postimage->len =new- postimage->buf;2366 postimage->nr -= reduced;2367}23682369static intline_by_line_fuzzy_match(struct image *img,2370struct image *preimage,2371struct image *postimage,2372unsigned longtry,2373int try_lno,2374int preimage_limit)2375{2376int i;2377size_t imgoff =0;2378size_t preoff =0;2379size_t postlen = postimage->len;2380size_t extra_chars;2381char*buf;2382char*preimage_eof;2383char*preimage_end;2384struct strbuf fixed;2385char*fixed_buf;2386size_t fixed_len;23872388for(i =0; i < preimage_limit; i++) {2389size_t prelen = preimage->line[i].len;2390size_t imglen = img->line[try_lno+i].len;23912392if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2393 preimage->buf + preoff, prelen))2394return0;2395if(preimage->line[i].flag & LINE_COMMON)2396 postlen += imglen - prelen;2397 imgoff += imglen;2398 preoff += prelen;2399}24002401/*2402 * Ok, the preimage matches with whitespace fuzz.2403 *2404 * imgoff now holds the true length of the target that2405 * matches the preimage before the end of the file.2406 *2407 * Count the number of characters in the preimage that fall2408 * beyond the end of the file and make sure that all of them2409 * are whitespace characters. (This can only happen if2410 * we are removing blank lines at the end of the file.)2411 */2412 buf = preimage_eof = preimage->buf + preoff;2413for( ; i < preimage->nr; i++)2414 preoff += preimage->line[i].len;2415 preimage_end = preimage->buf + preoff;2416for( ; buf < preimage_end; buf++)2417if(!isspace(*buf))2418return0;24192420/*2421 * Update the preimage and the common postimage context2422 * lines to use the same whitespace as the target.2423 * If whitespace is missing in the target (i.e.2424 * if the preimage extends beyond the end of the file),2425 * use the whitespace from the preimage.2426 */2427 extra_chars = preimage_end - preimage_eof;2428strbuf_init(&fixed, imgoff + extra_chars);2429strbuf_add(&fixed, img->buf +try, imgoff);2430strbuf_add(&fixed, preimage_eof, extra_chars);2431 fixed_buf =strbuf_detach(&fixed, &fixed_len);2432update_pre_post_images(preimage, postimage,2433 fixed_buf, fixed_len, postlen);2434return1;2435}24362437static intmatch_fragment(struct apply_state *state,2438struct image *img,2439struct image *preimage,2440struct image *postimage,2441unsigned longtry,2442int try_lno,2443unsigned ws_rule,2444int match_beginning,int match_end)2445{2446int i;2447char*fixed_buf, *buf, *orig, *target;2448struct strbuf fixed;2449size_t fixed_len, postlen;2450int preimage_limit;24512452if(preimage->nr + try_lno <= img->nr) {2453/*2454 * The hunk falls within the boundaries of img.2455 */2456 preimage_limit = preimage->nr;2457if(match_end && (preimage->nr + try_lno != img->nr))2458return0;2459}else if(state->ws_error_action == correct_ws_error &&2460(ws_rule & WS_BLANK_AT_EOF)) {2461/*2462 * This hunk extends beyond the end of img, and we are2463 * removing blank lines at the end of the file. This2464 * many lines from the beginning of the preimage must2465 * match with img, and the remainder of the preimage2466 * must be blank.2467 */2468 preimage_limit = img->nr - try_lno;2469}else{2470/*2471 * The hunk extends beyond the end of the img and2472 * we are not removing blanks at the end, so we2473 * should reject the hunk at this position.2474 */2475return0;2476}24772478if(match_beginning && try_lno)2479return0;24802481/* Quick hash check */2482for(i =0; i < preimage_limit; i++)2483if((img->line[try_lno + i].flag & LINE_PATCHED) ||2484(preimage->line[i].hash != img->line[try_lno + i].hash))2485return0;24862487if(preimage_limit == preimage->nr) {2488/*2489 * Do we have an exact match? If we were told to match2490 * at the end, size must be exactly at try+fragsize,2491 * otherwise try+fragsize must be still within the preimage,2492 * and either case, the old piece should match the preimage2493 * exactly.2494 */2495if((match_end2496? (try+ preimage->len == img->len)2497: (try+ preimage->len <= img->len)) &&2498!memcmp(img->buf +try, preimage->buf, preimage->len))2499return1;2500}else{2501/*2502 * The preimage extends beyond the end of img, so2503 * there cannot be an exact match.2504 *2505 * There must be one non-blank context line that match2506 * a line before the end of img.2507 */2508char*buf_end;25092510 buf = preimage->buf;2511 buf_end = buf;2512for(i =0; i < preimage_limit; i++)2513 buf_end += preimage->line[i].len;25142515for( ; buf < buf_end; buf++)2516if(!isspace(*buf))2517break;2518if(buf == buf_end)2519return0;2520}25212522/*2523 * No exact match. If we are ignoring whitespace, run a line-by-line2524 * fuzzy matching. We collect all the line length information because2525 * we need it to adjust whitespace if we match.2526 */2527if(state->ws_ignore_action == ignore_ws_change)2528returnline_by_line_fuzzy_match(img, preimage, postimage,2529try, try_lno, preimage_limit);25302531if(state->ws_error_action != correct_ws_error)2532return0;25332534/*2535 * The hunk does not apply byte-by-byte, but the hash says2536 * it might with whitespace fuzz. We weren't asked to2537 * ignore whitespace, we were asked to correct whitespace2538 * errors, so let's try matching after whitespace correction.2539 *2540 * While checking the preimage against the target, whitespace2541 * errors in both fixed, we count how large the corresponding2542 * postimage needs to be. The postimage prepared by2543 * apply_one_fragment() has whitespace errors fixed on added2544 * lines already, but the common lines were propagated as-is,2545 * which may become longer when their whitespace errors are2546 * fixed.2547 */25482549/* First count added lines in postimage */2550 postlen =0;2551for(i =0; i < postimage->nr; i++) {2552if(!(postimage->line[i].flag & LINE_COMMON))2553 postlen += postimage->line[i].len;2554}25552556/*2557 * The preimage may extend beyond the end of the file,2558 * but in this loop we will only handle the part of the2559 * preimage that falls within the file.2560 */2561strbuf_init(&fixed, preimage->len +1);2562 orig = preimage->buf;2563 target = img->buf +try;2564for(i =0; i < preimage_limit; i++) {2565size_t oldlen = preimage->line[i].len;2566size_t tgtlen = img->line[try_lno + i].len;2567size_t fixstart = fixed.len;2568struct strbuf tgtfix;2569int match;25702571/* Try fixing the line in the preimage */2572ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25732574/* Try fixing the line in the target */2575strbuf_init(&tgtfix, tgtlen);2576ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);25772578/*2579 * If they match, either the preimage was based on2580 * a version before our tree fixed whitespace breakage,2581 * or we are lacking a whitespace-fix patch the tree2582 * the preimage was based on already had (i.e. target2583 * has whitespace breakage, the preimage doesn't).2584 * In either case, we are fixing the whitespace breakages2585 * so we might as well take the fix together with their2586 * real change.2587 */2588 match = (tgtfix.len == fixed.len - fixstart &&2589!memcmp(tgtfix.buf, fixed.buf + fixstart,2590 fixed.len - fixstart));25912592/* Add the length if this is common with the postimage */2593if(preimage->line[i].flag & LINE_COMMON)2594 postlen += tgtfix.len;25952596strbuf_release(&tgtfix);2597if(!match)2598goto unmatch_exit;25992600 orig += oldlen;2601 target += tgtlen;2602}260326042605/*2606 * Now handle the lines in the preimage that falls beyond the2607 * end of the file (if any). They will only match if they are2608 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2609 * false).2610 */2611for( ; i < preimage->nr; i++) {2612size_t fixstart = fixed.len;/* start of the fixed preimage */2613size_t oldlen = preimage->line[i].len;2614int j;26152616/* Try fixing the line in the preimage */2617ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);26182619for(j = fixstart; j < fixed.len; j++)2620if(!isspace(fixed.buf[j]))2621goto unmatch_exit;26222623 orig += oldlen;2624}26252626/*2627 * Yes, the preimage is based on an older version that still2628 * has whitespace breakages unfixed, and fixing them makes the2629 * hunk match. Update the context lines in the postimage.2630 */2631 fixed_buf =strbuf_detach(&fixed, &fixed_len);2632if(postlen < postimage->len)2633 postlen =0;2634update_pre_post_images(preimage, postimage,2635 fixed_buf, fixed_len, postlen);2636return1;26372638 unmatch_exit:2639strbuf_release(&fixed);2640return0;2641}26422643static intfind_pos(struct apply_state *state,2644struct image *img,2645struct image *preimage,2646struct image *postimage,2647int line,2648unsigned ws_rule,2649int match_beginning,int match_end)2650{2651int i;2652unsigned long backwards, forwards,try;2653int backwards_lno, forwards_lno, try_lno;26542655/*2656 * If match_beginning or match_end is specified, there is no2657 * point starting from a wrong line that will never match and2658 * wander around and wait for a match at the specified end.2659 */2660if(match_beginning)2661 line =0;2662else if(match_end)2663 line = img->nr - preimage->nr;26642665/*2666 * Because the comparison is unsigned, the following test2667 * will also take care of a negative line number that can2668 * result when match_end and preimage is larger than the target.2669 */2670if((size_t) line > img->nr)2671 line = img->nr;26722673try=0;2674for(i =0; i < line; i++)2675try+= img->line[i].len;26762677/*2678 * There's probably some smart way to do this, but I'll leave2679 * that to the smart and beautiful people. I'm simple and stupid.2680 */2681 backwards =try;2682 backwards_lno = line;2683 forwards =try;2684 forwards_lno = line;2685 try_lno = line;26862687for(i =0; ; i++) {2688if(match_fragment(state, img, preimage, postimage,2689try, try_lno, ws_rule,2690 match_beginning, match_end))2691return try_lno;26922693 again:2694if(backwards_lno ==0&& forwards_lno == img->nr)2695break;26962697if(i &1) {2698if(backwards_lno ==0) {2699 i++;2700goto again;2701}2702 backwards_lno--;2703 backwards -= img->line[backwards_lno].len;2704try= backwards;2705 try_lno = backwards_lno;2706}else{2707if(forwards_lno == img->nr) {2708 i++;2709goto again;2710}2711 forwards += img->line[forwards_lno].len;2712 forwards_lno++;2713try= forwards;2714 try_lno = forwards_lno;2715}27162717}2718return-1;2719}27202721static voidremove_first_line(struct image *img)2722{2723 img->buf += img->line[0].len;2724 img->len -= img->line[0].len;2725 img->line++;2726 img->nr--;2727}27282729static voidremove_last_line(struct image *img)2730{2731 img->len -= img->line[--img->nr].len;2732}27332734/*2735 * The change from "preimage" and "postimage" has been found to2736 * apply at applied_pos (counts in line numbers) in "img".2737 * Update "img" to remove "preimage" and replace it with "postimage".2738 */2739static voidupdate_image(struct apply_state *state,2740struct image *img,2741int applied_pos,2742struct image *preimage,2743struct image *postimage)2744{2745/*2746 * remove the copy of preimage at offset in img2747 * and replace it with postimage2748 */2749int i, nr;2750size_t remove_count, insert_count, applied_at =0;2751char*result;2752int preimage_limit;27532754/*2755 * If we are removing blank lines at the end of img,2756 * the preimage may extend beyond the end.2757 * If that is the case, we must be careful only to2758 * remove the part of the preimage that falls within2759 * the boundaries of img. Initialize preimage_limit2760 * to the number of lines in the preimage that falls2761 * within the boundaries.2762 */2763 preimage_limit = preimage->nr;2764if(preimage_limit > img->nr - applied_pos)2765 preimage_limit = img->nr - applied_pos;27662767for(i =0; i < applied_pos; i++)2768 applied_at += img->line[i].len;27692770 remove_count =0;2771for(i =0; i < preimage_limit; i++)2772 remove_count += img->line[applied_pos + i].len;2773 insert_count = postimage->len;27742775/* Adjust the contents */2776 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2777memcpy(result, img->buf, applied_at);2778memcpy(result + applied_at, postimage->buf, postimage->len);2779memcpy(result + applied_at + postimage->len,2780 img->buf + (applied_at + remove_count),2781 img->len - (applied_at + remove_count));2782free(img->buf);2783 img->buf = result;2784 img->len += insert_count - remove_count;2785 result[img->len] ='\0';27862787/* Adjust the line table */2788 nr = img->nr + postimage->nr - preimage_limit;2789if(preimage_limit < postimage->nr) {2790/*2791 * NOTE: this knows that we never call remove_first_line()2792 * on anything other than pre/post image.2793 */2794REALLOC_ARRAY(img->line, nr);2795 img->line_allocated = img->line;2796}2797if(preimage_limit != postimage->nr)2798memmove(img->line + applied_pos + postimage->nr,2799 img->line + applied_pos + preimage_limit,2800(img->nr - (applied_pos + preimage_limit)) *2801sizeof(*img->line));2802memcpy(img->line + applied_pos,2803 postimage->line,2804 postimage->nr *sizeof(*img->line));2805if(!state->allow_overlap)2806for(i =0; i < postimage->nr; i++)2807 img->line[applied_pos + i].flag |= LINE_PATCHED;2808 img->nr = nr;2809}28102811/*2812 * Use the patch-hunk text in "frag" to prepare two images (preimage and2813 * postimage) for the hunk. Find lines that match "preimage" in "img" and2814 * replace the part of "img" with "postimage" text.2815 */2816static intapply_one_fragment(struct apply_state *state,2817struct image *img,struct fragment *frag,2818int inaccurate_eof,unsigned ws_rule,2819int nth_fragment)2820{2821int match_beginning, match_end;2822const char*patch = frag->patch;2823int size = frag->size;2824char*old, *oldlines;2825struct strbuf newlines;2826int new_blank_lines_at_end =0;2827int found_new_blank_lines_at_end =0;2828int hunk_linenr = frag->linenr;2829unsigned long leading, trailing;2830int pos, applied_pos;2831struct image preimage;2832struct image postimage;28332834memset(&preimage,0,sizeof(preimage));2835memset(&postimage,0,sizeof(postimage));2836 oldlines =xmalloc(size);2837strbuf_init(&newlines, size);28382839 old = oldlines;2840while(size >0) {2841char first;2842int len =linelen(patch, size);2843int plen;2844int added_blank_line =0;2845int is_blank_context =0;2846size_t start;28472848if(!len)2849break;28502851/*2852 * "plen" is how much of the line we should use for2853 * the actual patch data. Normally we just remove the2854 * first character on the line, but if the line is2855 * followed by "\ No newline", then we also remove the2856 * last one (which is the newline, of course).2857 */2858 plen = len -1;2859if(len < size && patch[len] =='\\')2860 plen--;2861 first = *patch;2862if(state->apply_in_reverse) {2863if(first =='-')2864 first ='+';2865else if(first =='+')2866 first ='-';2867}28682869switch(first) {2870case'\n':2871/* Newer GNU diff, empty context line */2872if(plen <0)2873/* ... followed by '\No newline'; nothing */2874break;2875*old++ ='\n';2876strbuf_addch(&newlines,'\n');2877add_line_info(&preimage,"\n",1, LINE_COMMON);2878add_line_info(&postimage,"\n",1, LINE_COMMON);2879 is_blank_context =1;2880break;2881case' ':2882if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2883ws_blank_line(patch +1, plen, ws_rule))2884 is_blank_context =1;2885case'-':2886memcpy(old, patch +1, plen);2887add_line_info(&preimage, old, plen,2888(first ==' '? LINE_COMMON :0));2889 old += plen;2890if(first =='-')2891break;2892/* Fall-through for ' ' */2893case'+':2894/* --no-add does not add new lines */2895if(first =='+'&& state->no_add)2896break;28972898 start = newlines.len;2899if(first !='+'||2900!state->whitespace_error ||2901 state->ws_error_action != correct_ws_error) {2902strbuf_add(&newlines, patch +1, plen);2903}2904else{2905ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2906}2907add_line_info(&postimage, newlines.buf + start, newlines.len - start,2908(first =='+'?0: LINE_COMMON));2909if(first =='+'&&2910(ws_rule & WS_BLANK_AT_EOF) &&2911ws_blank_line(patch +1, plen, ws_rule))2912 added_blank_line =1;2913break;2914case'@':case'\\':2915/* Ignore it, we already handled it */2916break;2917default:2918if(state->apply_verbosity > verbosity_normal)2919error(_("invalid start of line: '%c'"), first);2920 applied_pos = -1;2921goto out;2922}2923if(added_blank_line) {2924if(!new_blank_lines_at_end)2925 found_new_blank_lines_at_end = hunk_linenr;2926 new_blank_lines_at_end++;2927}2928else if(is_blank_context)2929;2930else2931 new_blank_lines_at_end =0;2932 patch += len;2933 size -= len;2934 hunk_linenr++;2935}2936if(inaccurate_eof &&2937 old > oldlines && old[-1] =='\n'&&2938 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2939 old--;2940strbuf_setlen(&newlines, newlines.len -1);2941}29422943 leading = frag->leading;2944 trailing = frag->trailing;29452946/*2947 * A hunk to change lines at the beginning would begin with2948 * @@ -1,L +N,M @@2949 * but we need to be careful. -U0 that inserts before the second2950 * line also has this pattern.2951 *2952 * And a hunk to add to an empty file would begin with2953 * @@ -0,0 +N,M @@2954 *2955 * In other words, a hunk that is (frag->oldpos <= 1) with or2956 * without leading context must match at the beginning.2957 */2958 match_beginning = (!frag->oldpos ||2959(frag->oldpos ==1&& !state->unidiff_zero));29602961/*2962 * A hunk without trailing lines must match at the end.2963 * However, we simply cannot tell if a hunk must match end2964 * from the lack of trailing lines if the patch was generated2965 * with unidiff without any context.2966 */2967 match_end = !state->unidiff_zero && !trailing;29682969 pos = frag->newpos ? (frag->newpos -1) :0;2970 preimage.buf = oldlines;2971 preimage.len = old - oldlines;2972 postimage.buf = newlines.buf;2973 postimage.len = newlines.len;2974 preimage.line = preimage.line_allocated;2975 postimage.line = postimage.line_allocated;29762977for(;;) {29782979 applied_pos =find_pos(state, img, &preimage, &postimage, pos,2980 ws_rule, match_beginning, match_end);29812982if(applied_pos >=0)2983break;29842985/* Am I at my context limits? */2986if((leading <= state->p_context) && (trailing <= state->p_context))2987break;2988if(match_beginning || match_end) {2989 match_beginning = match_end =0;2990continue;2991}29922993/*2994 * Reduce the number of context lines; reduce both2995 * leading and trailing if they are equal otherwise2996 * just reduce the larger context.2997 */2998if(leading >= trailing) {2999remove_first_line(&preimage);3000remove_first_line(&postimage);3001 pos--;3002 leading--;3003}3004if(trailing > leading) {3005remove_last_line(&preimage);3006remove_last_line(&postimage);3007 trailing--;3008}3009}30103011if(applied_pos >=0) {3012if(new_blank_lines_at_end &&3013 preimage.nr + applied_pos >= img->nr &&3014(ws_rule & WS_BLANK_AT_EOF) &&3015 state->ws_error_action != nowarn_ws_error) {3016record_ws_error(state, WS_BLANK_AT_EOF,"+",1,3017 found_new_blank_lines_at_end);3018if(state->ws_error_action == correct_ws_error) {3019while(new_blank_lines_at_end--)3020remove_last_line(&postimage);3021}3022/*3023 * We would want to prevent write_out_results()3024 * from taking place in apply_patch() that follows3025 * the callchain led us here, which is:3026 * apply_patch->check_patch_list->check_patch->3027 * apply_data->apply_fragments->apply_one_fragment3028 */3029if(state->ws_error_action == die_on_ws_error)3030 state->apply =0;3031}30323033if(state->apply_verbosity > verbosity_normal && applied_pos != pos) {3034int offset = applied_pos - pos;3035if(state->apply_in_reverse)3036 offset =0- offset;3037fprintf_ln(stderr,3038Q_("Hunk #%dsucceeded at%d(offset%dline).",3039"Hunk #%dsucceeded at%d(offset%dlines).",3040 offset),3041 nth_fragment, applied_pos +1, offset);3042}30433044/*3045 * Warn if it was necessary to reduce the number3046 * of context lines.3047 */3048if((leading != frag->leading ||3049 trailing != frag->trailing) && state->apply_verbosity > verbosity_silent)3050fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"3051" to apply fragment at%d"),3052 leading, trailing, applied_pos+1);3053update_image(state, img, applied_pos, &preimage, &postimage);3054}else{3055if(state->apply_verbosity > verbosity_normal)3056error(_("while searching for:\n%.*s"),3057(int)(old - oldlines), oldlines);3058}30593060out:3061free(oldlines);3062strbuf_release(&newlines);3063free(preimage.line_allocated);3064free(postimage.line_allocated);30653066return(applied_pos <0);3067}30683069static intapply_binary_fragment(struct apply_state *state,3070struct image *img,3071struct patch *patch)3072{3073struct fragment *fragment = patch->fragments;3074unsigned long len;3075void*dst;30763077if(!fragment)3078returnerror(_("missing binary patch data for '%s'"),3079 patch->new_name ?3080 patch->new_name :3081 patch->old_name);30823083/* Binary patch is irreversible without the optional second hunk */3084if(state->apply_in_reverse) {3085if(!fragment->next)3086returnerror("cannot reverse-apply a binary patch "3087"without the reverse hunk to '%s'",3088 patch->new_name3089? patch->new_name : patch->old_name);3090 fragment = fragment->next;3091}3092switch(fragment->binary_patch_method) {3093case BINARY_DELTA_DEFLATED:3094 dst =patch_delta(img->buf, img->len, fragment->patch,3095 fragment->size, &len);3096if(!dst)3097return-1;3098clear_image(img);3099 img->buf = dst;3100 img->len = len;3101return0;3102case BINARY_LITERAL_DEFLATED:3103clear_image(img);3104 img->len = fragment->size;3105 img->buf =xmemdupz(fragment->patch, img->len);3106return0;3107}3108return-1;3109}31103111/*3112 * Replace "img" with the result of applying the binary patch.3113 * The binary patch data itself in patch->fragment is still kept3114 * but the preimage prepared by the caller in "img" is freed here3115 * or in the helper function apply_binary_fragment() this calls.3116 */3117static intapply_binary(struct apply_state *state,3118struct image *img,3119struct patch *patch)3120{3121const char*name = patch->old_name ? patch->old_name : patch->new_name;3122unsigned char sha1[20];31233124/*3125 * For safety, we require patch index line to contain3126 * full 40-byte textual SHA1 for old and new, at least for now.3127 */3128if(strlen(patch->old_sha1_prefix) !=40||3129strlen(patch->new_sha1_prefix) !=40||3130get_sha1_hex(patch->old_sha1_prefix, sha1) ||3131get_sha1_hex(patch->new_sha1_prefix, sha1))3132returnerror("cannot apply binary patch to '%s' "3133"without full index line", name);31343135if(patch->old_name) {3136/*3137 * See if the old one matches what the patch3138 * applies to.3139 */3140hash_sha1_file(img->buf, img->len, blob_type, sha1);3141if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3142returnerror("the patch applies to '%s' (%s), "3143"which does not match the "3144"current contents.",3145 name,sha1_to_hex(sha1));3146}3147else{3148/* Otherwise, the old one must be empty. */3149if(img->len)3150returnerror("the patch applies to an empty "3151"'%s' but it is not empty", name);3152}31533154get_sha1_hex(patch->new_sha1_prefix, sha1);3155if(is_null_sha1(sha1)) {3156clear_image(img);3157return0;/* deletion patch */3158}31593160if(has_sha1_file(sha1)) {3161/* We already have the postimage */3162enum object_type type;3163unsigned long size;3164char*result;31653166 result =read_sha1_file(sha1, &type, &size);3167if(!result)3168returnerror("the necessary postimage%sfor "3169"'%s' cannot be read",3170 patch->new_sha1_prefix, name);3171clear_image(img);3172 img->buf = result;3173 img->len = size;3174}else{3175/*3176 * We have verified buf matches the preimage;3177 * apply the patch data to it, which is stored3178 * in the patch->fragments->{patch,size}.3179 */3180if(apply_binary_fragment(state, img, patch))3181returnerror(_("binary patch does not apply to '%s'"),3182 name);31833184/* verify that the result matches */3185hash_sha1_file(img->buf, img->len, blob_type, sha1);3186if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3187returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3188 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3189}31903191return0;3192}31933194static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3195{3196struct fragment *frag = patch->fragments;3197const char*name = patch->old_name ? patch->old_name : patch->new_name;3198unsigned ws_rule = patch->ws_rule;3199unsigned inaccurate_eof = patch->inaccurate_eof;3200int nth =0;32013202if(patch->is_binary)3203returnapply_binary(state, img, patch);32043205while(frag) {3206 nth++;3207if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3208error(_("patch failed:%s:%ld"), name, frag->oldpos);3209if(!state->apply_with_reject)3210return-1;3211 frag->rejected =1;3212}3213 frag = frag->next;3214}3215return0;3216}32173218static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3219{3220if(S_ISGITLINK(mode)) {3221strbuf_grow(buf,100);3222strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3223}else{3224enum object_type type;3225unsigned long sz;3226char*result;32273228 result =read_sha1_file(sha1, &type, &sz);3229if(!result)3230return-1;3231/* XXX read_sha1_file NUL-terminates */3232strbuf_attach(buf, result, sz, sz +1);3233}3234return0;3235}32363237static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3238{3239if(!ce)3240return0;3241returnread_blob_object(buf, ce->sha1, ce->ce_mode);3242}32433244static struct patch *in_fn_table(struct apply_state *state,const char*name)3245{3246struct string_list_item *item;32473248if(name == NULL)3249return NULL;32503251 item =string_list_lookup(&state->fn_table, name);3252if(item != NULL)3253return(struct patch *)item->util;32543255return NULL;3256}32573258/*3259 * item->util in the filename table records the status of the path.3260 * Usually it points at a patch (whose result records the contents3261 * of it after applying it), but it could be PATH_WAS_DELETED for a3262 * path that a previously applied patch has already removed, or3263 * PATH_TO_BE_DELETED for a path that a later patch would remove.3264 *3265 * The latter is needed to deal with a case where two paths A and B3266 * are swapped by first renaming A to B and then renaming B to A;3267 * moving A to B should not be prevented due to presence of B as we3268 * will remove it in a later patch.3269 */3270#define PATH_TO_BE_DELETED ((struct patch *) -2)3271#define PATH_WAS_DELETED ((struct patch *) -1)32723273static intto_be_deleted(struct patch *patch)3274{3275return patch == PATH_TO_BE_DELETED;3276}32773278static intwas_deleted(struct patch *patch)3279{3280return patch == PATH_WAS_DELETED;3281}32823283static voidadd_to_fn_table(struct apply_state *state,struct patch *patch)3284{3285struct string_list_item *item;32863287/*3288 * Always add new_name unless patch is a deletion3289 * This should cover the cases for normal diffs,3290 * file creations and copies3291 */3292if(patch->new_name != NULL) {3293 item =string_list_insert(&state->fn_table, patch->new_name);3294 item->util = patch;3295}32963297/*3298 * store a failure on rename/deletion cases because3299 * later chunks shouldn't patch old names3300 */3301if((patch->new_name == NULL) || (patch->is_rename)) {3302 item =string_list_insert(&state->fn_table, patch->old_name);3303 item->util = PATH_WAS_DELETED;3304}3305}33063307static voidprepare_fn_table(struct apply_state *state,struct patch *patch)3308{3309/*3310 * store information about incoming file deletion3311 */3312while(patch) {3313if((patch->new_name == NULL) || (patch->is_rename)) {3314struct string_list_item *item;3315 item =string_list_insert(&state->fn_table, patch->old_name);3316 item->util = PATH_TO_BE_DELETED;3317}3318 patch = patch->next;3319}3320}33213322static intcheckout_target(struct index_state *istate,3323struct cache_entry *ce,struct stat *st)3324{3325struct checkout costate;33263327memset(&costate,0,sizeof(costate));3328 costate.base_dir ="";3329 costate.refresh_cache =1;3330 costate.istate = istate;3331if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3332returnerror(_("cannot checkout%s"), ce->name);3333return0;3334}33353336static struct patch *previous_patch(struct apply_state *state,3337struct patch *patch,3338int*gone)3339{3340struct patch *previous;33413342*gone =0;3343if(patch->is_copy || patch->is_rename)3344return NULL;/* "git" patches do not depend on the order */33453346 previous =in_fn_table(state, patch->old_name);3347if(!previous)3348return NULL;33493350if(to_be_deleted(previous))3351return NULL;/* the deletion hasn't happened yet */33523353if(was_deleted(previous))3354*gone =1;33553356return previous;3357}33583359static intverify_index_match(const struct cache_entry *ce,struct stat *st)3360{3361if(S_ISGITLINK(ce->ce_mode)) {3362if(!S_ISDIR(st->st_mode))3363return-1;3364return0;3365}3366returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3367}33683369#define SUBMODULE_PATCH_WITHOUT_INDEX 133703371static intload_patch_target(struct apply_state *state,3372struct strbuf *buf,3373const struct cache_entry *ce,3374struct stat *st,3375const char*name,3376unsigned expected_mode)3377{3378if(state->cached || state->check_index) {3379if(read_file_or_gitlink(ce, buf))3380returnerror(_("failed to read%s"), name);3381}else if(name) {3382if(S_ISGITLINK(expected_mode)) {3383if(ce)3384returnread_file_or_gitlink(ce, buf);3385else3386return SUBMODULE_PATCH_WITHOUT_INDEX;3387}else if(has_symlink_leading_path(name,strlen(name))) {3388returnerror(_("reading from '%s' beyond a symbolic link"), name);3389}else{3390if(read_old_data(st, name, buf))3391returnerror(_("failed to read%s"), name);3392}3393}3394return0;3395}33963397/*3398 * We are about to apply "patch"; populate the "image" with the3399 * current version we have, from the working tree or from the index,3400 * depending on the situation e.g. --cached/--index. If we are3401 * applying a non-git patch that incrementally updates the tree,3402 * we read from the result of a previous diff.3403 */3404static intload_preimage(struct apply_state *state,3405struct image *image,3406struct patch *patch,struct stat *st,3407const struct cache_entry *ce)3408{3409struct strbuf buf = STRBUF_INIT;3410size_t len;3411char*img;3412struct patch *previous;3413int status;34143415 previous =previous_patch(state, patch, &status);3416if(status)3417returnerror(_("path%shas been renamed/deleted"),3418 patch->old_name);3419if(previous) {3420/* We have a patched copy in memory; use that. */3421strbuf_add(&buf, previous->result, previous->resultsize);3422}else{3423 status =load_patch_target(state, &buf, ce, st,3424 patch->old_name, patch->old_mode);3425if(status <0)3426return status;3427else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3428/*3429 * There is no way to apply subproject3430 * patch without looking at the index.3431 * NEEDSWORK: shouldn't this be flagged3432 * as an error???3433 */3434free_fragment_list(patch->fragments);3435 patch->fragments = NULL;3436}else if(status) {3437returnerror(_("failed to read%s"), patch->old_name);3438}3439}34403441 img =strbuf_detach(&buf, &len);3442prepare_image(image, img, len, !patch->is_binary);3443return0;3444}34453446static intthree_way_merge(struct image *image,3447char*path,3448const unsigned char*base,3449const unsigned char*ours,3450const unsigned char*theirs)3451{3452 mmfile_t base_file, our_file, their_file;3453 mmbuffer_t result = { NULL };3454int status;34553456read_mmblob(&base_file, base);3457read_mmblob(&our_file, ours);3458read_mmblob(&their_file, theirs);3459 status =ll_merge(&result, path,3460&base_file,"base",3461&our_file,"ours",3462&their_file,"theirs", NULL);3463free(base_file.ptr);3464free(our_file.ptr);3465free(their_file.ptr);3466if(status <0|| !result.ptr) {3467free(result.ptr);3468return-1;3469}3470clear_image(image);3471 image->buf = result.ptr;3472 image->len = result.size;34733474return status;3475}34763477/*3478 * When directly falling back to add/add three-way merge, we read from3479 * the current contents of the new_name. In no cases other than that3480 * this function will be called.3481 */3482static intload_current(struct apply_state *state,3483struct image *image,3484struct patch *patch)3485{3486struct strbuf buf = STRBUF_INIT;3487int status, pos;3488size_t len;3489char*img;3490struct stat st;3491struct cache_entry *ce;3492char*name = patch->new_name;3493unsigned mode = patch->new_mode;34943495if(!patch->is_new)3496die("BUG: patch to%sis not a creation", patch->old_name);34973498 pos =cache_name_pos(name,strlen(name));3499if(pos <0)3500returnerror(_("%s: does not exist in index"), name);3501 ce = active_cache[pos];3502if(lstat(name, &st)) {3503if(errno != ENOENT)3504returnerror_errno("%s", name);3505if(checkout_target(&the_index, ce, &st))3506return-1;3507}3508if(verify_index_match(ce, &st))3509returnerror(_("%s: does not match index"), name);35103511 status =load_patch_target(state, &buf, ce, &st, name, mode);3512if(status <0)3513return status;3514else if(status)3515return-1;3516 img =strbuf_detach(&buf, &len);3517prepare_image(image, img, len, !patch->is_binary);3518return0;3519}35203521static inttry_threeway(struct apply_state *state,3522struct image *image,3523struct patch *patch,3524struct stat *st,3525const struct cache_entry *ce)3526{3527unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3528struct strbuf buf = STRBUF_INIT;3529size_t len;3530int status;3531char*img;3532struct image tmp_image;35333534/* No point falling back to 3-way merge in these cases */3535if(patch->is_delete ||3536S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3537return-1;35383539/* Preimage the patch was prepared for */3540if(patch->is_new)3541write_sha1_file("",0, blob_type, pre_sha1);3542else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3543read_blob_object(&buf, pre_sha1, patch->old_mode))3544returnerror("repository lacks the necessary blob to fall back on 3-way merge.");35453546if(state->apply_verbosity > verbosity_silent)3547fprintf(stderr,"Falling back to three-way merge...\n");35483549 img =strbuf_detach(&buf, &len);3550prepare_image(&tmp_image, img, len,1);3551/* Apply the patch to get the post image */3552if(apply_fragments(state, &tmp_image, patch) <0) {3553clear_image(&tmp_image);3554return-1;3555}3556/* post_sha1[] is theirs */3557write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3558clear_image(&tmp_image);35593560/* our_sha1[] is ours */3561if(patch->is_new) {3562if(load_current(state, &tmp_image, patch))3563returnerror("cannot read the current contents of '%s'",3564 patch->new_name);3565}else{3566if(load_preimage(state, &tmp_image, patch, st, ce))3567returnerror("cannot read the current contents of '%s'",3568 patch->old_name);3569}3570write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3571clear_image(&tmp_image);35723573/* in-core three-way merge between post and our using pre as base */3574 status =three_way_merge(image, patch->new_name,3575 pre_sha1, our_sha1, post_sha1);3576if(status <0) {3577if(state->apply_verbosity > verbosity_silent)3578fprintf(stderr,3579"Failed to fall back on three-way merge...\n");3580return status;3581}35823583if(status) {3584 patch->conflicted_threeway =1;3585if(patch->is_new)3586oidclr(&patch->threeway_stage[0]);3587else3588hashcpy(patch->threeway_stage[0].hash, pre_sha1);3589hashcpy(patch->threeway_stage[1].hash, our_sha1);3590hashcpy(patch->threeway_stage[2].hash, post_sha1);3591if(state->apply_verbosity > verbosity_silent)3592fprintf(stderr,3593"Applied patch to '%s' with conflicts.\n",3594 patch->new_name);3595}else{3596if(state->apply_verbosity > verbosity_silent)3597fprintf(stderr,3598"Applied patch to '%s' cleanly.\n",3599 patch->new_name);3600}3601return0;3602}36033604static intapply_data(struct apply_state *state,struct patch *patch,3605struct stat *st,const struct cache_entry *ce)3606{3607struct image image;36083609if(load_preimage(state, &image, patch, st, ce) <0)3610return-1;36113612if(patch->direct_to_threeway ||3613apply_fragments(state, &image, patch) <0) {3614/* Note: with --reject, apply_fragments() returns 0 */3615if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3616return-1;3617}3618 patch->result = image.buf;3619 patch->resultsize = image.len;3620add_to_fn_table(state, patch);3621free(image.line_allocated);36223623if(0< patch->is_delete && patch->resultsize)3624returnerror(_("removal patch leaves file contents"));36253626return0;3627}36283629/*3630 * If "patch" that we are looking at modifies or deletes what we have,3631 * we would want it not to lose any local modification we have, either3632 * in the working tree or in the index.3633 *3634 * This also decides if a non-git patch is a creation patch or a3635 * modification to an existing empty file. We do not check the state3636 * of the current tree for a creation patch in this function; the caller3637 * check_patch() separately makes sure (and errors out otherwise) that3638 * the path the patch creates does not exist in the current tree.3639 */3640static intcheck_preimage(struct apply_state *state,3641struct patch *patch,3642struct cache_entry **ce,3643struct stat *st)3644{3645const char*old_name = patch->old_name;3646struct patch *previous = NULL;3647int stat_ret =0, status;3648unsigned st_mode =0;36493650if(!old_name)3651return0;36523653assert(patch->is_new <=0);3654 previous =previous_patch(state, patch, &status);36553656if(status)3657returnerror(_("path%shas been renamed/deleted"), old_name);3658if(previous) {3659 st_mode = previous->new_mode;3660}else if(!state->cached) {3661 stat_ret =lstat(old_name, st);3662if(stat_ret && errno != ENOENT)3663returnerror_errno("%s", old_name);3664}36653666if(state->check_index && !previous) {3667int pos =cache_name_pos(old_name,strlen(old_name));3668if(pos <0) {3669if(patch->is_new <0)3670goto is_new;3671returnerror(_("%s: does not exist in index"), old_name);3672}3673*ce = active_cache[pos];3674if(stat_ret <0) {3675if(checkout_target(&the_index, *ce, st))3676return-1;3677}3678if(!state->cached &&verify_index_match(*ce, st))3679returnerror(_("%s: does not match index"), old_name);3680if(state->cached)3681 st_mode = (*ce)->ce_mode;3682}else if(stat_ret <0) {3683if(patch->is_new <0)3684goto is_new;3685returnerror_errno("%s", old_name);3686}36873688if(!state->cached && !previous)3689 st_mode =ce_mode_from_stat(*ce, st->st_mode);36903691if(patch->is_new <0)3692 patch->is_new =0;3693if(!patch->old_mode)3694 patch->old_mode = st_mode;3695if((st_mode ^ patch->old_mode) & S_IFMT)3696returnerror(_("%s: wrong type"), old_name);3697if(st_mode != patch->old_mode)3698warning(_("%shas type%o, expected%o"),3699 old_name, st_mode, patch->old_mode);3700if(!patch->new_mode && !patch->is_delete)3701 patch->new_mode = st_mode;3702return0;37033704 is_new:3705 patch->is_new =1;3706 patch->is_delete =0;3707free(patch->old_name);3708 patch->old_name = NULL;3709return0;3710}371137123713#define EXISTS_IN_INDEX 13714#define EXISTS_IN_WORKTREE 237153716static intcheck_to_create(struct apply_state *state,3717const char*new_name,3718int ok_if_exists)3719{3720struct stat nst;37213722if(state->check_index &&3723cache_name_pos(new_name,strlen(new_name)) >=0&&3724!ok_if_exists)3725return EXISTS_IN_INDEX;3726if(state->cached)3727return0;37283729if(!lstat(new_name, &nst)) {3730if(S_ISDIR(nst.st_mode) || ok_if_exists)3731return0;3732/*3733 * A leading component of new_name might be a symlink3734 * that is going to be removed with this patch, but3735 * still pointing at somewhere that has the path.3736 * In such a case, path "new_name" does not exist as3737 * far as git is concerned.3738 */3739if(has_symlink_leading_path(new_name,strlen(new_name)))3740return0;37413742return EXISTS_IN_WORKTREE;3743}else if((errno != ENOENT) && (errno != ENOTDIR)) {3744returnerror_errno("%s", new_name);3745}3746return0;3747}37483749static uintptr_tregister_symlink_changes(struct apply_state *state,3750const char*path,3751uintptr_t what)3752{3753struct string_list_item *ent;37543755 ent =string_list_lookup(&state->symlink_changes, path);3756if(!ent) {3757 ent =string_list_insert(&state->symlink_changes, path);3758 ent->util = (void*)0;3759}3760 ent->util = (void*)(what | ((uintptr_t)ent->util));3761return(uintptr_t)ent->util;3762}37633764static uintptr_tcheck_symlink_changes(struct apply_state *state,const char*path)3765{3766struct string_list_item *ent;37673768 ent =string_list_lookup(&state->symlink_changes, path);3769if(!ent)3770return0;3771return(uintptr_t)ent->util;3772}37733774static voidprepare_symlink_changes(struct apply_state *state,struct patch *patch)3775{3776for( ; patch; patch = patch->next) {3777if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3778(patch->is_rename || patch->is_delete))3779/* the symlink at patch->old_name is removed */3780register_symlink_changes(state, patch->old_name, APPLY_SYMLINK_GOES_AWAY);37813782if(patch->new_name &&S_ISLNK(patch->new_mode))3783/* the symlink at patch->new_name is created or remains */3784register_symlink_changes(state, patch->new_name, APPLY_SYMLINK_IN_RESULT);3785}3786}37873788static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3789{3790do{3791unsigned int change;37923793while(--name->len && name->buf[name->len] !='/')3794;/* scan backwards */3795if(!name->len)3796break;3797 name->buf[name->len] ='\0';3798 change =check_symlink_changes(state, name->buf);3799if(change & APPLY_SYMLINK_IN_RESULT)3800return1;3801if(change & APPLY_SYMLINK_GOES_AWAY)3802/*3803 * This cannot be "return 0", because we may3804 * see a new one created at a higher level.3805 */3806continue;38073808/* otherwise, check the preimage */3809if(state->check_index) {3810struct cache_entry *ce;38113812 ce =cache_file_exists(name->buf, name->len, ignore_case);3813if(ce &&S_ISLNK(ce->ce_mode))3814return1;3815}else{3816struct stat st;3817if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3818return1;3819}3820}while(1);3821return0;3822}38233824static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3825{3826int ret;3827struct strbuf name = STRBUF_INIT;38283829assert(*name_ !='\0');3830strbuf_addstr(&name, name_);3831 ret =path_is_beyond_symlink_1(state, &name);3832strbuf_release(&name);38333834return ret;3835}38363837static intcheck_unsafe_path(struct patch *patch)3838{3839const char*old_name = NULL;3840const char*new_name = NULL;3841if(patch->is_delete)3842 old_name = patch->old_name;3843else if(!patch->is_new && !patch->is_copy)3844 old_name = patch->old_name;3845if(!patch->is_delete)3846 new_name = patch->new_name;38473848if(old_name && !verify_path(old_name))3849returnerror(_("invalid path '%s'"), old_name);3850if(new_name && !verify_path(new_name))3851returnerror(_("invalid path '%s'"), new_name);3852return0;3853}38543855/*3856 * Check and apply the patch in-core; leave the result in patch->result3857 * for the caller to write it out to the final destination.3858 */3859static intcheck_patch(struct apply_state *state,struct patch *patch)3860{3861struct stat st;3862const char*old_name = patch->old_name;3863const char*new_name = patch->new_name;3864const char*name = old_name ? old_name : new_name;3865struct cache_entry *ce = NULL;3866struct patch *tpatch;3867int ok_if_exists;3868int status;38693870 patch->rejected =1;/* we will drop this after we succeed */38713872 status =check_preimage(state, patch, &ce, &st);3873if(status)3874return status;3875 old_name = patch->old_name;38763877/*3878 * A type-change diff is always split into a patch to delete3879 * old, immediately followed by a patch to create new (see3880 * diff.c::run_diff()); in such a case it is Ok that the entry3881 * to be deleted by the previous patch is still in the working3882 * tree and in the index.3883 *3884 * A patch to swap-rename between A and B would first rename A3885 * to B and then rename B to A. While applying the first one,3886 * the presence of B should not stop A from getting renamed to3887 * B; ask to_be_deleted() about the later rename. Removal of3888 * B and rename from A to B is handled the same way by asking3889 * was_deleted().3890 */3891if((tpatch =in_fn_table(state, new_name)) &&3892(was_deleted(tpatch) ||to_be_deleted(tpatch)))3893 ok_if_exists =1;3894else3895 ok_if_exists =0;38963897if(new_name &&3898((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3899int err =check_to_create(state, new_name, ok_if_exists);39003901if(err && state->threeway) {3902 patch->direct_to_threeway =1;3903}else switch(err) {3904case0:3905break;/* happy */3906case EXISTS_IN_INDEX:3907returnerror(_("%s: already exists in index"), new_name);3908break;3909case EXISTS_IN_WORKTREE:3910returnerror(_("%s: already exists in working directory"),3911 new_name);3912default:3913return err;3914}39153916if(!patch->new_mode) {3917if(0< patch->is_new)3918 patch->new_mode = S_IFREG |0644;3919else3920 patch->new_mode = patch->old_mode;3921}3922}39233924if(new_name && old_name) {3925int same = !strcmp(old_name, new_name);3926if(!patch->new_mode)3927 patch->new_mode = patch->old_mode;3928if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3929if(same)3930returnerror(_("new mode (%o) of%sdoes not "3931"match old mode (%o)"),3932 patch->new_mode, new_name,3933 patch->old_mode);3934else3935returnerror(_("new mode (%o) of%sdoes not "3936"match old mode (%o) of%s"),3937 patch->new_mode, new_name,3938 patch->old_mode, old_name);3939}3940}39413942if(!state->unsafe_paths &&check_unsafe_path(patch))3943return-128;39443945/*3946 * An attempt to read from or delete a path that is beyond a3947 * symbolic link will be prevented by load_patch_target() that3948 * is called at the beginning of apply_data() so we do not3949 * have to worry about a patch marked with "is_delete" bit3950 * here. We however need to make sure that the patch result3951 * is not deposited to a path that is beyond a symbolic link3952 * here.3953 */3954if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3955returnerror(_("affected file '%s' is beyond a symbolic link"),3956 patch->new_name);39573958if(apply_data(state, patch, &st, ce) <0)3959returnerror(_("%s: patch does not apply"), name);3960 patch->rejected =0;3961return0;3962}39633964static intcheck_patch_list(struct apply_state *state,struct patch *patch)3965{3966int err =0;39673968prepare_symlink_changes(state, patch);3969prepare_fn_table(state, patch);3970while(patch) {3971int res;3972if(state->apply_verbosity > verbosity_normal)3973say_patch_name(stderr,3974_("Checking patch%s..."), patch);3975 res =check_patch(state, patch);3976if(res == -128)3977return-128;3978 err |= res;3979 patch = patch->next;3980}3981return err;3982}39833984/* This function tries to read the sha1 from the current index */3985static intget_current_sha1(const char*path,unsigned char*sha1)3986{3987int pos;39883989if(read_cache() <0)3990return-1;3991 pos =cache_name_pos(path,strlen(path));3992if(pos <0)3993return-1;3994hashcpy(sha1, active_cache[pos]->sha1);3995return0;3996}39973998static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3999{4000/*4001 * A usable gitlink patch has only one fragment (hunk) that looks like:4002 * @@ -1 +1 @@4003 * -Subproject commit <old sha1>4004 * +Subproject commit <new sha1>4005 * or4006 * @@ -1 +0,0 @@4007 * -Subproject commit <old sha1>4008 * for a removal patch.4009 */4010struct fragment *hunk = p->fragments;4011static const char heading[] ="-Subproject commit ";4012char*preimage;40134014if(/* does the patch have only one hunk? */4015 hunk && !hunk->next &&4016/* is its preimage one line? */4017 hunk->oldpos ==1&& hunk->oldlines ==1&&4018/* does preimage begin with the heading? */4019(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&4020starts_with(++preimage, heading) &&4021/* does it record full SHA-1? */4022!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&4023 preimage[sizeof(heading) +40-1] =='\n'&&4024/* does the abbreviated name on the index line agree with it? */4025starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))4026return0;/* it all looks fine */40274028/* we may have full object name on the index line */4029returnget_sha1_hex(p->old_sha1_prefix, sha1);4030}40314032/* Build an index that contains the just the files needed for a 3way merge */4033static intbuild_fake_ancestor(struct patch *list,const char*filename)4034{4035struct patch *patch;4036struct index_state result = { NULL };4037static struct lock_file lock;4038int res;40394040/* Once we start supporting the reverse patch, it may be4041 * worth showing the new sha1 prefix, but until then...4042 */4043for(patch = list; patch; patch = patch->next) {4044unsigned char sha1[20];4045struct cache_entry *ce;4046const char*name;40474048 name = patch->old_name ? patch->old_name : patch->new_name;4049if(0< patch->is_new)4050continue;40514052if(S_ISGITLINK(patch->old_mode)) {4053if(!preimage_sha1_in_gitlink_patch(patch, sha1))4054;/* ok, the textual part looks sane */4055else4056returnerror("sha1 information is lacking or "4057"useless for submodule%s", name);4058}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {4059;/* ok */4060}else if(!patch->lines_added && !patch->lines_deleted) {4061/* mode-only change: update the current */4062if(get_current_sha1(patch->old_name, sha1))4063returnerror("mode change for%s, which is not "4064"in current HEAD", name);4065}else4066returnerror("sha1 information is lacking or useless "4067"(%s).", name);40684069 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);4070if(!ce)4071returnerror(_("make_cache_entry failed for path '%s'"),4072 name);4073if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) {4074free(ce);4075returnerror("Could not add%sto temporary index",4076 name);4077}4078}40794080hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);4081 res =write_locked_index(&result, &lock, COMMIT_LOCK);4082discard_index(&result);40834084if(res)4085returnerror("Could not write temporary index to%s", filename);40864087return0;4088}40894090static voidstat_patch_list(struct apply_state *state,struct patch *patch)4091{4092int files, adds, dels;40934094for(files = adds = dels =0; patch ; patch = patch->next) {4095 files++;4096 adds += patch->lines_added;4097 dels += patch->lines_deleted;4098show_stats(state, patch);4099}41004101print_stat_summary(stdout, files, adds, dels);4102}41034104static voidnumstat_patch_list(struct apply_state *state,4105struct patch *patch)4106{4107for( ; patch; patch = patch->next) {4108const char*name;4109 name = patch->new_name ? patch->new_name : patch->old_name;4110if(patch->is_binary)4111printf("-\t-\t");4112else4113printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4114write_name_quoted(name, stdout, state->line_termination);4115}4116}41174118static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4119{4120if(mode)4121printf("%smode%06o%s\n", newdelete, mode, name);4122else4123printf("%s %s\n", newdelete, name);4124}41254126static voidshow_mode_change(struct patch *p,int show_name)4127{4128if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4129if(show_name)4130printf(" mode change%06o =>%06o%s\n",4131 p->old_mode, p->new_mode, p->new_name);4132else4133printf(" mode change%06o =>%06o\n",4134 p->old_mode, p->new_mode);4135}4136}41374138static voidshow_rename_copy(struct patch *p)4139{4140const char*renamecopy = p->is_rename ?"rename":"copy";4141const char*old, *new;41424143/* Find common prefix */4144 old = p->old_name;4145new= p->new_name;4146while(1) {4147const char*slash_old, *slash_new;4148 slash_old =strchr(old,'/');4149 slash_new =strchr(new,'/');4150if(!slash_old ||4151!slash_new ||4152 slash_old - old != slash_new -new||4153memcmp(old,new, slash_new -new))4154break;4155 old = slash_old +1;4156new= slash_new +1;4157}4158/* p->old_name thru old is the common prefix, and old and new4159 * through the end of names are renames4160 */4161if(old != p->old_name)4162printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4163(int)(old - p->old_name), p->old_name,4164 old,new, p->score);4165else4166printf("%s %s=>%s(%d%%)\n", renamecopy,4167 p->old_name, p->new_name, p->score);4168show_mode_change(p,0);4169}41704171static voidsummary_patch_list(struct patch *patch)4172{4173struct patch *p;41744175for(p = patch; p; p = p->next) {4176if(p->is_new)4177show_file_mode_name("create", p->new_mode, p->new_name);4178else if(p->is_delete)4179show_file_mode_name("delete", p->old_mode, p->old_name);4180else{4181if(p->is_rename || p->is_copy)4182show_rename_copy(p);4183else{4184if(p->score) {4185printf(" rewrite%s(%d%%)\n",4186 p->new_name, p->score);4187show_mode_change(p,0);4188}4189else4190show_mode_change(p,1);4191}4192}4193}4194}41954196static voidpatch_stats(struct apply_state *state,struct patch *patch)4197{4198int lines = patch->lines_added + patch->lines_deleted;41994200if(lines > state->max_change)4201 state->max_change = lines;4202if(patch->old_name) {4203int len =quote_c_style(patch->old_name, NULL, NULL,0);4204if(!len)4205 len =strlen(patch->old_name);4206if(len > state->max_len)4207 state->max_len = len;4208}4209if(patch->new_name) {4210int len =quote_c_style(patch->new_name, NULL, NULL,0);4211if(!len)4212 len =strlen(patch->new_name);4213if(len > state->max_len)4214 state->max_len = len;4215}4216}42174218static intremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4219{4220if(state->update_index) {4221if(remove_file_from_cache(patch->old_name) <0)4222returnerror(_("unable to remove%sfrom index"), patch->old_name);4223}4224if(!state->cached) {4225if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4226remove_path(patch->old_name);4227}4228}4229return0;4230}42314232static intadd_index_file(struct apply_state *state,4233const char*path,4234unsigned mode,4235void*buf,4236unsigned long size)4237{4238struct stat st;4239struct cache_entry *ce;4240int namelen =strlen(path);4241unsigned ce_size =cache_entry_size(namelen);42424243if(!state->update_index)4244return0;42454246 ce =xcalloc(1, ce_size);4247memcpy(ce->name, path, namelen);4248 ce->ce_mode =create_ce_mode(mode);4249 ce->ce_flags =create_ce_flags(0);4250 ce->ce_namelen = namelen;4251if(S_ISGITLINK(mode)) {4252const char*s;42534254if(!skip_prefix(buf,"Subproject commit ", &s) ||4255get_sha1_hex(s, ce->sha1)) {4256free(ce);4257returnerror(_("corrupt patch for submodule%s"), path);4258}4259}else{4260if(!state->cached) {4261if(lstat(path, &st) <0) {4262free(ce);4263returnerror_errno(_("unable to stat newly "4264"created file '%s'"),4265 path);4266}4267fill_stat_cache_info(ce, &st);4268}4269if(write_sha1_file(buf, size, blob_type, ce->sha1) <0) {4270free(ce);4271returnerror(_("unable to create backing store "4272"for newly created file%s"), path);4273}4274}4275if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0) {4276free(ce);4277returnerror(_("unable to add cache entry for%s"), path);4278}42794280return0;4281}42824283/*4284 * Returns:4285 * -1 if an unrecoverable error happened4286 * 0 if everything went well4287 * 1 if a recoverable error happened4288 */4289static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4290{4291int fd, res;4292struct strbuf nbuf = STRBUF_INIT;42934294if(S_ISGITLINK(mode)) {4295struct stat st;4296if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4297return0;4298return!!mkdir(path,0777);4299}43004301if(has_symlinks &&S_ISLNK(mode))4302/* Although buf:size is counted string, it also is NUL4303 * terminated.4304 */4305return!!symlink(buf, path);43064307 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4308if(fd <0)4309return1;43104311if(convert_to_working_tree(path, buf, size, &nbuf)) {4312 size = nbuf.len;4313 buf = nbuf.buf;4314}43154316 res =write_in_full(fd, buf, size) <0;4317if(res)4318error_errno(_("failed to write to '%s'"), path);4319strbuf_release(&nbuf);43204321if(close(fd) <0&& !res)4322returnerror_errno(_("closing file '%s'"), path);43234324return res ? -1:0;4325}43264327/*4328 * We optimistically assume that the directories exist,4329 * which is true 99% of the time anyway. If they don't,4330 * we create them and try again.4331 *4332 * Returns:4333 * -1 on error4334 * 0 otherwise4335 */4336static intcreate_one_file(struct apply_state *state,4337char*path,4338unsigned mode,4339const char*buf,4340unsigned long size)4341{4342int res;43434344if(state->cached)4345return0;43464347 res =try_create_file(path, mode, buf, size);4348if(res <0)4349return-1;4350if(!res)4351return0;43524353if(errno == ENOENT) {4354if(safe_create_leading_directories(path))4355return0;4356 res =try_create_file(path, mode, buf, size);4357if(res <0)4358return-1;4359if(!res)4360return0;4361}43624363if(errno == EEXIST || errno == EACCES) {4364/* We may be trying to create a file where a directory4365 * used to be.4366 */4367struct stat st;4368if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4369 errno = EEXIST;4370}43714372if(errno == EEXIST) {4373unsigned int nr =getpid();43744375for(;;) {4376char newpath[PATH_MAX];4377mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4378 res =try_create_file(newpath, mode, buf, size);4379if(res <0)4380return-1;4381if(!res) {4382if(!rename(newpath, path))4383return0;4384unlink_or_warn(newpath);4385break;4386}4387if(errno != EEXIST)4388break;4389++nr;4390}4391}4392returnerror_errno(_("unable to write file '%s' mode%o"),4393 path, mode);4394}43954396static intadd_conflicted_stages_file(struct apply_state *state,4397struct patch *patch)4398{4399int stage, namelen;4400unsigned ce_size, mode;4401struct cache_entry *ce;44024403if(!state->update_index)4404return0;4405 namelen =strlen(patch->new_name);4406 ce_size =cache_entry_size(namelen);4407 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);44084409remove_file_from_cache(patch->new_name);4410for(stage =1; stage <4; stage++) {4411if(is_null_oid(&patch->threeway_stage[stage -1]))4412continue;4413 ce =xcalloc(1, ce_size);4414memcpy(ce->name, patch->new_name, namelen);4415 ce->ce_mode =create_ce_mode(mode);4416 ce->ce_flags =create_ce_flags(stage);4417 ce->ce_namelen = namelen;4418hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4419if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0) {4420free(ce);4421returnerror(_("unable to add cache entry for%s"),4422 patch->new_name);4423}4424}44254426return0;4427}44284429static intcreate_file(struct apply_state *state,struct patch *patch)4430{4431char*path = patch->new_name;4432unsigned mode = patch->new_mode;4433unsigned long size = patch->resultsize;4434char*buf = patch->result;44354436if(!mode)4437 mode = S_IFREG |0644;4438if(create_one_file(state, path, mode, buf, size))4439return-1;44404441if(patch->conflicted_threeway)4442returnadd_conflicted_stages_file(state, patch);4443else4444returnadd_index_file(state, path, mode, buf, size);4445}44464447/* phase zero is to remove, phase one is to create */4448static intwrite_out_one_result(struct apply_state *state,4449struct patch *patch,4450int phase)4451{4452if(patch->is_delete >0) {4453if(phase ==0)4454returnremove_file(state, patch,1);4455return0;4456}4457if(patch->is_new >0|| patch->is_copy) {4458if(phase ==1)4459returncreate_file(state, patch);4460return0;4461}4462/*4463 * Rename or modification boils down to the same4464 * thing: remove the old, write the new4465 */4466if(phase ==0)4467returnremove_file(state, patch, patch->is_rename);4468if(phase ==1)4469returncreate_file(state, patch);4470return0;4471}44724473static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4474{4475FILE*rej;4476char namebuf[PATH_MAX];4477struct fragment *frag;4478int cnt =0;4479struct strbuf sb = STRBUF_INIT;44804481for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4482if(!frag->rejected)4483continue;4484 cnt++;4485}44864487if(!cnt) {4488if(state->apply_verbosity > verbosity_normal)4489say_patch_name(stderr,4490_("Applied patch%scleanly."), patch);4491return0;4492}44934494/* This should not happen, because a removal patch that leaves4495 * contents are marked "rejected" at the patch level.4496 */4497if(!patch->new_name)4498die(_("internal error"));44994500/* Say this even without --verbose */4501strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4502"Applying patch %%swith%drejects...",4503 cnt),4504 cnt);4505if(state->apply_verbosity > verbosity_silent)4506say_patch_name(stderr, sb.buf, patch);4507strbuf_release(&sb);45084509 cnt =strlen(patch->new_name);4510if(ARRAY_SIZE(namebuf) <= cnt +5) {4511 cnt =ARRAY_SIZE(namebuf) -5;4512warning(_("truncating .rej filename to %.*s.rej"),4513 cnt -1, patch->new_name);4514}4515memcpy(namebuf, patch->new_name, cnt);4516memcpy(namebuf + cnt,".rej",5);45174518 rej =fopen(namebuf,"w");4519if(!rej)4520returnerror_errno(_("cannot open%s"), namebuf);45214522/* Normal git tools never deal with .rej, so do not pretend4523 * this is a git patch by saying --git or giving extended4524 * headers. While at it, maybe please "kompare" that wants4525 * the trailing TAB and some garbage at the end of line ;-).4526 */4527fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4528 patch->new_name, patch->new_name);4529for(cnt =1, frag = patch->fragments;4530 frag;4531 cnt++, frag = frag->next) {4532if(!frag->rejected) {4533if(state->apply_verbosity > verbosity_silent)4534fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4535continue;4536}4537if(state->apply_verbosity > verbosity_silent)4538fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4539fprintf(rej,"%.*s", frag->size, frag->patch);4540if(frag->patch[frag->size-1] !='\n')4541fputc('\n', rej);4542}4543fclose(rej);4544return-1;4545}45464547/*4548 * Returns:4549 * -1 if an error happened4550 * 0 if the patch applied cleanly4551 * 1 if the patch did not apply cleanly4552 */4553static intwrite_out_results(struct apply_state *state,struct patch *list)4554{4555int phase;4556int errs =0;4557struct patch *l;4558struct string_list cpath = STRING_LIST_INIT_DUP;45594560for(phase =0; phase <2; phase++) {4561 l = list;4562while(l) {4563if(l->rejected)4564 errs =1;4565else{4566if(write_out_one_result(state, l, phase)) {4567string_list_clear(&cpath,0);4568return-1;4569}4570if(phase ==1) {4571if(write_out_one_reject(state, l))4572 errs =1;4573if(l->conflicted_threeway) {4574string_list_append(&cpath, l->new_name);4575 errs =1;4576}4577}4578}4579 l = l->next;4580}4581}45824583if(cpath.nr) {4584struct string_list_item *item;45854586string_list_sort(&cpath);4587if(state->apply_verbosity > verbosity_silent) {4588for_each_string_list_item(item, &cpath)4589fprintf(stderr,"U%s\n", item->string);4590}4591string_list_clear(&cpath,0);45924593rerere(0);4594}45954596return errs;4597}45984599/*4600 * Try to apply a patch.4601 *4602 * Returns:4603 * -128 if a bad error happened (like patch unreadable)4604 * -1 if patch did not apply and user cannot deal with it4605 * 0 if the patch applied4606 * 1 if the patch did not apply but user might fix it4607 */4608static intapply_patch(struct apply_state *state,4609int fd,4610const char*filename,4611int options)4612{4613size_t offset;4614struct strbuf buf = STRBUF_INIT;/* owns the patch text */4615struct patch *list = NULL, **listp = &list;4616int skipped_patch =0;4617int res =0;46184619 state->patch_input_file = filename;4620if(read_patch_file(&buf, fd) <0)4621return-128;4622 offset =0;4623while(offset < buf.len) {4624struct patch *patch;4625int nr;46264627 patch =xcalloc(1,sizeof(*patch));4628 patch->inaccurate_eof = !!(options & APPLY_OPT_INACCURATE_EOF);4629 patch->recount = !!(options & APPLY_OPT_RECOUNT);4630 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4631if(nr <0) {4632free_patch(patch);4633if(nr == -128) {4634 res = -128;4635goto end;4636}4637break;4638}4639if(state->apply_in_reverse)4640reverse_patches(patch);4641if(use_patch(state, patch)) {4642patch_stats(state, patch);4643*listp = patch;4644 listp = &patch->next;4645}4646else{4647if(state->apply_verbosity > verbosity_normal)4648say_patch_name(stderr,_("Skipped patch '%s'."), patch);4649free_patch(patch);4650 skipped_patch++;4651}4652 offset += nr;4653}46544655if(!list && !skipped_patch) {4656error(_("unrecognized input"));4657 res = -128;4658goto end;4659}46604661if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4662 state->apply =0;46634664 state->update_index = state->check_index && state->apply;4665if(state->update_index && state->newfd <0)4666 state->newfd =hold_locked_index(state->lock_file,1);46674668if(state->check_index &&read_cache() <0) {4669error(_("unable to read index file"));4670 res = -128;4671goto end;4672}46734674if(state->check || state->apply) {4675int r =check_patch_list(state, list);4676if(r == -128) {4677 res = -128;4678goto end;4679}4680if(r <0&& !state->apply_with_reject) {4681 res = -1;4682goto end;4683}4684}46854686if(state->apply) {4687int write_res =write_out_results(state, list);4688if(write_res <0) {4689 res = -128;4690goto end;4691}4692if(write_res >0) {4693/* with --3way, we still need to write the index out */4694 res = state->apply_with_reject ? -1:1;4695goto end;4696}4697}46984699if(state->fake_ancestor &&4700build_fake_ancestor(list, state->fake_ancestor)) {4701 res = -128;4702goto end;4703}47044705if(state->diffstat && state->apply_verbosity > verbosity_silent)4706stat_patch_list(state, list);47074708if(state->numstat && state->apply_verbosity > verbosity_silent)4709numstat_patch_list(state, list);47104711if(state->summary && state->apply_verbosity > verbosity_silent)4712summary_patch_list(list);47134714end:4715free_patch_list(list);4716strbuf_release(&buf);4717string_list_clear(&state->fn_table,0);4718return res;4719}47204721intapply_option_parse_exclude(const struct option *opt,4722const char*arg,int unset)4723{4724struct apply_state *state = opt->value;4725add_name_limit(state, arg,1);4726return0;4727}47284729intapply_option_parse_include(const struct option *opt,4730const char*arg,int unset)4731{4732struct apply_state *state = opt->value;4733add_name_limit(state, arg,0);4734 state->has_include =1;4735return0;4736}47374738intapply_option_parse_p(const struct option *opt,4739const char*arg,4740int unset)4741{4742struct apply_state *state = opt->value;4743 state->p_value =atoi(arg);4744 state->p_value_known =1;4745return0;4746}47474748intapply_option_parse_space_change(const struct option *opt,4749const char*arg,int unset)4750{4751struct apply_state *state = opt->value;4752if(unset)4753 state->ws_ignore_action = ignore_ws_none;4754else4755 state->ws_ignore_action = ignore_ws_change;4756return0;4757}47584759intapply_option_parse_whitespace(const struct option *opt,4760const char*arg,int unset)4761{4762struct apply_state *state = opt->value;4763 state->whitespace_option = arg;4764if(parse_whitespace_option(state, arg))4765exit(1);4766return0;4767}47684769intapply_option_parse_directory(const struct option *opt,4770const char*arg,int unset)4771{4772struct apply_state *state = opt->value;4773strbuf_reset(&state->root);4774strbuf_addstr(&state->root, arg);4775strbuf_complete(&state->root,'/');4776return0;4777}47784779intapply_all_patches(struct apply_state *state,4780int argc,4781const char**argv,4782int options)4783{4784int i;4785int res;4786int errs =0;4787int read_stdin =1;47884789for(i =0; i < argc; i++) {4790const char*arg = argv[i];4791int fd;47924793if(!strcmp(arg,"-")) {4794 res =apply_patch(state,0,"<stdin>", options);4795if(res <0)4796goto end;4797 errs |= res;4798 read_stdin =0;4799continue;4800}else if(0< state->prefix_length)4801 arg =prefix_filename(state->prefix,4802 state->prefix_length,4803 arg);48044805 fd =open(arg, O_RDONLY);4806if(fd <0) {4807error(_("can't open patch '%s':%s"), arg,strerror(errno));4808 res = -128;4809goto end;4810}4811 read_stdin =0;4812set_default_whitespace_mode(state);4813 res =apply_patch(state, fd, arg, options);4814close(fd);4815if(res <0)4816goto end;4817 errs |= res;4818}4819set_default_whitespace_mode(state);4820if(read_stdin) {4821 res =apply_patch(state,0,"<stdin>", options);4822if(res <0)4823goto end;4824 errs |= res;4825}48264827if(state->whitespace_error) {4828if(state->squelch_whitespace_errors &&4829 state->squelch_whitespace_errors < state->whitespace_error) {4830int squelched =4831 state->whitespace_error - state->squelch_whitespace_errors;4832warning(Q_("squelched%dwhitespace error",4833"squelched%dwhitespace errors",4834 squelched),4835 squelched);4836}4837if(state->ws_error_action == die_on_ws_error) {4838error(Q_("%dline adds whitespace errors.",4839"%dlines add whitespace errors.",4840 state->whitespace_error),4841 state->whitespace_error);4842 res = -128;4843goto end;4844}4845if(state->applied_after_fixing_ws && state->apply)4846warning("%dline%sapplied after"4847" fixing whitespace errors.",4848 state->applied_after_fixing_ws,4849 state->applied_after_fixing_ws ==1?"":"s");4850else if(state->whitespace_error)4851warning(Q_("%dline adds whitespace errors.",4852"%dlines add whitespace errors.",4853 state->whitespace_error),4854 state->whitespace_error);4855}48564857if(state->update_index) {4858 res =write_locked_index(&the_index, state->lock_file, COMMIT_LOCK);4859if(res) {4860error(_("Unable to write new index file"));4861 res = -128;4862goto end;4863}4864 state->newfd = -1;4865}48664867return!!errs;48684869end:4870if(state->newfd >=0) {4871rollback_lock_file(state->lock_file);4872 state->newfd = -1;4873}48744875return(res == -1?1:128);4876}