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"config.h" 12#include"blob.h" 13#include"delta.h" 14#include"diff.h" 15#include"dir.h" 16#include"xdiff-interface.h" 17#include"ll-merge.h" 18#include"lockfile.h" 19#include"parse-options.h" 20#include"quote.h" 21#include"rerere.h" 22#include"apply.h" 23 24static voidgit_apply_config(void) 25{ 26git_config_get_string_const("apply.whitespace", &apply_default_whitespace); 27git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace); 28git_config(git_default_config, NULL); 29} 30 31static intparse_whitespace_option(struct apply_state *state,const char*option) 32{ 33if(!option) { 34 state->ws_error_action = warn_on_ws_error; 35return0; 36} 37if(!strcmp(option,"warn")) { 38 state->ws_error_action = warn_on_ws_error; 39return0; 40} 41if(!strcmp(option,"nowarn")) { 42 state->ws_error_action = nowarn_ws_error; 43return0; 44} 45if(!strcmp(option,"error")) { 46 state->ws_error_action = die_on_ws_error; 47return0; 48} 49if(!strcmp(option,"error-all")) { 50 state->ws_error_action = die_on_ws_error; 51 state->squelch_whitespace_errors =0; 52return0; 53} 54if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 55 state->ws_error_action = correct_ws_error; 56return0; 57} 58returnerror(_("unrecognized whitespace option '%s'"), option); 59} 60 61static intparse_ignorewhitespace_option(struct apply_state *state, 62const char*option) 63{ 64if(!option || !strcmp(option,"no") || 65!strcmp(option,"false") || !strcmp(option,"never") || 66!strcmp(option,"none")) { 67 state->ws_ignore_action = ignore_ws_none; 68return0; 69} 70if(!strcmp(option,"change")) { 71 state->ws_ignore_action = ignore_ws_change; 72return0; 73} 74returnerror(_("unrecognized whitespace ignore option '%s'"), option); 75} 76 77intinit_apply_state(struct apply_state *state, 78const char*prefix, 79struct lock_file *lock_file) 80{ 81memset(state,0,sizeof(*state)); 82 state->prefix = prefix; 83 state->prefix_length = state->prefix ?strlen(state->prefix) :0; 84 state->lock_file = lock_file; 85 state->newfd = -1; 86 state->apply =1; 87 state->line_termination ='\n'; 88 state->p_value =1; 89 state->p_context = UINT_MAX; 90 state->squelch_whitespace_errors =5; 91 state->ws_error_action = warn_on_ws_error; 92 state->ws_ignore_action = ignore_ws_none; 93 state->linenr =1; 94string_list_init(&state->fn_table,0); 95string_list_init(&state->limit_by_name,0); 96string_list_init(&state->symlink_changes,0); 97strbuf_init(&state->root,0); 98 99git_apply_config(); 100if(apply_default_whitespace &&parse_whitespace_option(state, apply_default_whitespace)) 101return-1; 102if(apply_default_ignorewhitespace &&parse_ignorewhitespace_option(state, apply_default_ignorewhitespace)) 103return-1; 104return0; 105} 106 107voidclear_apply_state(struct apply_state *state) 108{ 109string_list_clear(&state->limit_by_name,0); 110string_list_clear(&state->symlink_changes,0); 111strbuf_release(&state->root); 112 113/* &state->fn_table is cleared at the end of apply_patch() */ 114} 115 116static voidmute_routine(const char*msg,va_list params) 117{ 118/* do nothing */ 119} 120 121intcheck_apply_state(struct apply_state *state,int force_apply) 122{ 123int is_not_gitdir = !startup_info->have_repository; 124 125if(state->apply_with_reject && state->threeway) 126returnerror(_("--reject and --3way cannot be used together.")); 127if(state->cached && state->threeway) 128returnerror(_("--cached and --3way cannot be used together.")); 129if(state->threeway) { 130if(is_not_gitdir) 131returnerror(_("--3way outside a repository")); 132 state->check_index =1; 133} 134if(state->apply_with_reject) { 135 state->apply =1; 136if(state->apply_verbosity == verbosity_normal) 137 state->apply_verbosity = verbosity_verbose; 138} 139if(!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor)) 140 state->apply =0; 141if(state->check_index && is_not_gitdir) 142returnerror(_("--index outside a repository")); 143if(state->cached) { 144if(is_not_gitdir) 145returnerror(_("--cached outside a repository")); 146 state->check_index =1; 147} 148if(state->check_index) 149 state->unsafe_paths =0; 150if(!state->lock_file) 151returnerror("BUG: state->lock_file should not be NULL"); 152 153if(state->apply_verbosity <= verbosity_silent) { 154 state->saved_error_routine =get_error_routine(); 155 state->saved_warn_routine =get_warn_routine(); 156set_error_routine(mute_routine); 157set_warn_routine(mute_routine); 158} 159 160return0; 161} 162 163static voidset_default_whitespace_mode(struct apply_state *state) 164{ 165if(!state->whitespace_option && !apply_default_whitespace) 166 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 167} 168 169/* 170 * This represents one "hunk" from a patch, starting with 171 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 172 * patch text is pointed at by patch, and its byte length 173 * is stored in size. leading and trailing are the number 174 * of context lines. 175 */ 176struct fragment { 177unsigned long leading, trailing; 178unsigned long oldpos, oldlines; 179unsigned long newpos, newlines; 180/* 181 * 'patch' is usually borrowed from buf in apply_patch(), 182 * but some codepaths store an allocated buffer. 183 */ 184const char*patch; 185unsigned free_patch:1, 186 rejected:1; 187int size; 188int linenr; 189struct fragment *next; 190}; 191 192/* 193 * When dealing with a binary patch, we reuse "leading" field 194 * to store the type of the binary hunk, either deflated "delta" 195 * or deflated "literal". 196 */ 197#define binary_patch_method leading 198#define BINARY_DELTA_DEFLATED 1 199#define BINARY_LITERAL_DEFLATED 2 200 201/* 202 * This represents a "patch" to a file, both metainfo changes 203 * such as creation/deletion, filemode and content changes represented 204 * as a series of fragments. 205 */ 206struct patch { 207char*new_name, *old_name, *def_name; 208unsigned int old_mode, new_mode; 209int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 210int rejected; 211unsigned ws_rule; 212int lines_added, lines_deleted; 213int score; 214int extension_linenr;/* first line specifying delete/new/rename/copy */ 215unsigned int is_toplevel_relative:1; 216unsigned int inaccurate_eof:1; 217unsigned int is_binary:1; 218unsigned int is_copy:1; 219unsigned int is_rename:1; 220unsigned int recount:1; 221unsigned int conflicted_threeway:1; 222unsigned int direct_to_threeway:1; 223struct fragment *fragments; 224char*result; 225size_t resultsize; 226char old_sha1_prefix[41]; 227char new_sha1_prefix[41]; 228struct patch *next; 229 230/* three-way fallback result */ 231struct object_id threeway_stage[3]; 232}; 233 234static voidfree_fragment_list(struct fragment *list) 235{ 236while(list) { 237struct fragment *next = list->next; 238if(list->free_patch) 239free((char*)list->patch); 240free(list); 241 list = next; 242} 243} 244 245static voidfree_patch(struct patch *patch) 246{ 247free_fragment_list(patch->fragments); 248free(patch->def_name); 249free(patch->old_name); 250free(patch->new_name); 251free(patch->result); 252free(patch); 253} 254 255static voidfree_patch_list(struct patch *list) 256{ 257while(list) { 258struct patch *next = list->next; 259free_patch(list); 260 list = next; 261} 262} 263 264/* 265 * A line in a file, len-bytes long (includes the terminating LF, 266 * except for an incomplete line at the end if the file ends with 267 * one), and its contents hashes to 'hash'. 268 */ 269struct line { 270size_t len; 271unsigned hash :24; 272unsigned flag :8; 273#define LINE_COMMON 1 274#define LINE_PATCHED 2 275}; 276 277/* 278 * This represents a "file", which is an array of "lines". 279 */ 280struct image { 281char*buf; 282size_t len; 283size_t nr; 284size_t alloc; 285struct line *line_allocated; 286struct line *line; 287}; 288 289static uint32_thash_line(const char*cp,size_t len) 290{ 291size_t i; 292uint32_t h; 293for(i =0, h =0; i < len; i++) { 294if(!isspace(cp[i])) { 295 h = h *3+ (cp[i] &0xff); 296} 297} 298return h; 299} 300 301/* 302 * Compare lines s1 of length n1 and s2 of length n2, ignoring 303 * whitespace difference. Returns 1 if they match, 0 otherwise 304 */ 305static intfuzzy_matchlines(const char*s1,size_t n1, 306const char*s2,size_t n2) 307{ 308const char*last1 = s1 + n1 -1; 309const char*last2 = s2 + n2 -1; 310int result =0; 311 312/* ignore line endings */ 313while((*last1 =='\r') || (*last1 =='\n')) 314 last1--; 315while((*last2 =='\r') || (*last2 =='\n')) 316 last2--; 317 318/* skip leading whitespaces, if both begin with whitespace */ 319if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 320while(isspace(*s1) && (s1 <= last1)) 321 s1++; 322while(isspace(*s2) && (s2 <= last2)) 323 s2++; 324} 325/* early return if both lines are empty */ 326if((s1 > last1) && (s2 > last2)) 327return1; 328while(!result) { 329 result = *s1++ - *s2++; 330/* 331 * Skip whitespace inside. We check for whitespace on 332 * both buffers because we don't want "a b" to match 333 * "ab" 334 */ 335if(isspace(*s1) &&isspace(*s2)) { 336while(isspace(*s1) && s1 <= last1) 337 s1++; 338while(isspace(*s2) && s2 <= last2) 339 s2++; 340} 341/* 342 * If we reached the end on one side only, 343 * lines don't match 344 */ 345if( 346((s2 > last2) && (s1 <= last1)) || 347((s1 > last1) && (s2 <= last2))) 348return0; 349if((s1 > last1) && (s2 > last2)) 350break; 351} 352 353return!result; 354} 355 356static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 357{ 358ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 359 img->line_allocated[img->nr].len = len; 360 img->line_allocated[img->nr].hash =hash_line(bol, len); 361 img->line_allocated[img->nr].flag = flag; 362 img->nr++; 363} 364 365/* 366 * "buf" has the file contents to be patched (read from various sources). 367 * attach it to "image" and add line-based index to it. 368 * "image" now owns the "buf". 369 */ 370static voidprepare_image(struct image *image,char*buf,size_t len, 371int prepare_linetable) 372{ 373const char*cp, *ep; 374 375memset(image,0,sizeof(*image)); 376 image->buf = buf; 377 image->len = len; 378 379if(!prepare_linetable) 380return; 381 382 ep = image->buf + image->len; 383 cp = image->buf; 384while(cp < ep) { 385const char*next; 386for(next = cp; next < ep && *next !='\n'; next++) 387; 388if(next < ep) 389 next++; 390add_line_info(image, cp, next - cp,0); 391 cp = next; 392} 393 image->line = image->line_allocated; 394} 395 396static voidclear_image(struct image *image) 397{ 398free(image->buf); 399free(image->line_allocated); 400memset(image,0,sizeof(*image)); 401} 402 403/* fmt must contain _one_ %s and no other substitution */ 404static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 405{ 406struct strbuf sb = STRBUF_INIT; 407 408if(patch->old_name && patch->new_name && 409strcmp(patch->old_name, patch->new_name)) { 410quote_c_style(patch->old_name, &sb, NULL,0); 411strbuf_addstr(&sb," => "); 412quote_c_style(patch->new_name, &sb, NULL,0); 413}else{ 414const char*n = patch->new_name; 415if(!n) 416 n = patch->old_name; 417quote_c_style(n, &sb, NULL,0); 418} 419fprintf(output, fmt, sb.buf); 420fputc('\n', output); 421strbuf_release(&sb); 422} 423 424#define SLOP (16) 425 426static intread_patch_file(struct strbuf *sb,int fd) 427{ 428if(strbuf_read(sb, fd,0) <0) 429returnerror_errno("git apply: failed to read"); 430 431/* 432 * Make sure that we have some slop in the buffer 433 * so that we can do speculative "memcmp" etc, and 434 * see to it that it is NUL-filled. 435 */ 436strbuf_grow(sb, SLOP); 437memset(sb->buf + sb->len,0, SLOP); 438return0; 439} 440 441static unsigned longlinelen(const char*buffer,unsigned long size) 442{ 443unsigned long len =0; 444while(size--) { 445 len++; 446if(*buffer++ =='\n') 447break; 448} 449return len; 450} 451 452static intis_dev_null(const char*str) 453{ 454returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 455} 456 457#define TERM_SPACE 1 458#define TERM_TAB 2 459 460static intname_terminate(int c,int terminate) 461{ 462if(c ==' '&& !(terminate & TERM_SPACE)) 463return0; 464if(c =='\t'&& !(terminate & TERM_TAB)) 465return0; 466 467return1; 468} 469 470/* remove double slashes to make --index work with such filenames */ 471static char*squash_slash(char*name) 472{ 473int i =0, j =0; 474 475if(!name) 476return NULL; 477 478while(name[i]) { 479if((name[j++] = name[i++]) =='/') 480while(name[i] =='/') 481 i++; 482} 483 name[j] ='\0'; 484return name; 485} 486 487static char*find_name_gnu(struct apply_state *state, 488const char*line, 489const char*def, 490int p_value) 491{ 492struct strbuf name = STRBUF_INIT; 493char*cp; 494 495/* 496 * Proposed "new-style" GNU patch/diff format; see 497 * http://marc.info/?l=git&m=112927316408690&w=2 498 */ 499if(unquote_c_style(&name, line, NULL)) { 500strbuf_release(&name); 501return NULL; 502} 503 504for(cp = name.buf; p_value; p_value--) { 505 cp =strchr(cp,'/'); 506if(!cp) { 507strbuf_release(&name); 508return NULL; 509} 510 cp++; 511} 512 513strbuf_remove(&name,0, cp - name.buf); 514if(state->root.len) 515strbuf_insert(&name,0, state->root.buf, state->root.len); 516returnsquash_slash(strbuf_detach(&name, NULL)); 517} 518 519static size_tsane_tz_len(const char*line,size_t len) 520{ 521const char*tz, *p; 522 523if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 524return0; 525 tz = line + len -strlen(" +0500"); 526 527if(tz[1] !='+'&& tz[1] !='-') 528return0; 529 530for(p = tz +2; p != line + len; p++) 531if(!isdigit(*p)) 532return0; 533 534return line + len - tz; 535} 536 537static size_ttz_with_colon_len(const char*line,size_t len) 538{ 539const char*tz, *p; 540 541if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 542return0; 543 tz = line + len -strlen(" +08:00"); 544 545if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 546return0; 547 p = tz +2; 548if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 549!isdigit(*p++) || !isdigit(*p++)) 550return0; 551 552return line + len - tz; 553} 554 555static size_tdate_len(const char*line,size_t len) 556{ 557const char*date, *p; 558 559if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 560return0; 561 p = date = line + len -strlen("72-02-05"); 562 563if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 564!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 565!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 566return0; 567 568if(date - line >=strlen("19") && 569isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 570 date -=strlen("19"); 571 572return line + len - date; 573} 574 575static size_tshort_time_len(const char*line,size_t len) 576{ 577const char*time, *p; 578 579if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 580return0; 581 p = time = line + len -strlen(" 07:01:32"); 582 583/* Permit 1-digit hours? */ 584if(*p++ !=' '|| 585!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 586!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 587!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 588return0; 589 590return line + len - time; 591} 592 593static size_tfractional_time_len(const char*line,size_t len) 594{ 595const char*p; 596size_t n; 597 598/* Expected format: 19:41:17.620000023 */ 599if(!len || !isdigit(line[len -1])) 600return0; 601 p = line + len -1; 602 603/* Fractional seconds. */ 604while(p > line &&isdigit(*p)) 605 p--; 606if(*p !='.') 607return0; 608 609/* Hours, minutes, and whole seconds. */ 610 n =short_time_len(line, p - line); 611if(!n) 612return0; 613 614return line + len - p + n; 615} 616 617static size_ttrailing_spaces_len(const char*line,size_t len) 618{ 619const char*p; 620 621/* Expected format: ' ' x (1 or more) */ 622if(!len || line[len -1] !=' ') 623return0; 624 625 p = line + len; 626while(p != line) { 627 p--; 628if(*p !=' ') 629return line + len - (p +1); 630} 631 632/* All spaces! */ 633return len; 634} 635 636static size_tdiff_timestamp_len(const char*line,size_t len) 637{ 638const char*end = line + len; 639size_t n; 640 641/* 642 * Posix: 2010-07-05 19:41:17 643 * GNU: 2010-07-05 19:41:17.620000023 -0500 644 */ 645 646if(!isdigit(end[-1])) 647return0; 648 649 n =sane_tz_len(line, end - line); 650if(!n) 651 n =tz_with_colon_len(line, end - line); 652 end -= n; 653 654 n =short_time_len(line, end - line); 655if(!n) 656 n =fractional_time_len(line, end - line); 657 end -= n; 658 659 n =date_len(line, end - line); 660if(!n)/* No date. Too bad. */ 661return0; 662 end -= n; 663 664if(end == line)/* No space before date. */ 665return0; 666if(end[-1] =='\t') {/* Success! */ 667 end--; 668return line + len - end; 669} 670if(end[-1] !=' ')/* No space before date. */ 671return0; 672 673/* Whitespace damage. */ 674 end -=trailing_spaces_len(line, end - line); 675return line + len - end; 676} 677 678static char*find_name_common(struct apply_state *state, 679const char*line, 680const char*def, 681int p_value, 682const char*end, 683int terminate) 684{ 685int len; 686const char*start = NULL; 687 688if(p_value ==0) 689 start = line; 690while(line != end) { 691char c = *line; 692 693if(!end &&isspace(c)) { 694if(c =='\n') 695break; 696if(name_terminate(c, terminate)) 697break; 698} 699 line++; 700if(c =='/'&& !--p_value) 701 start = line; 702} 703if(!start) 704returnsquash_slash(xstrdup_or_null(def)); 705 len = line - start; 706if(!len) 707returnsquash_slash(xstrdup_or_null(def)); 708 709/* 710 * Generally we prefer the shorter name, especially 711 * if the other one is just a variation of that with 712 * something else tacked on to the end (ie "file.orig" 713 * or "file~"). 714 */ 715if(def) { 716int deflen =strlen(def); 717if(deflen < len && !strncmp(start, def, deflen)) 718returnsquash_slash(xstrdup(def)); 719} 720 721if(state->root.len) { 722char*ret =xstrfmt("%s%.*s", state->root.buf, len, start); 723returnsquash_slash(ret); 724} 725 726returnsquash_slash(xmemdupz(start, len)); 727} 728 729static char*find_name(struct apply_state *state, 730const char*line, 731char*def, 732int p_value, 733int terminate) 734{ 735if(*line =='"') { 736char*name =find_name_gnu(state, line, def, p_value); 737if(name) 738return name; 739} 740 741returnfind_name_common(state, line, def, p_value, NULL, terminate); 742} 743 744static char*find_name_traditional(struct apply_state *state, 745const char*line, 746char*def, 747int p_value) 748{ 749size_t len; 750size_t date_len; 751 752if(*line =='"') { 753char*name =find_name_gnu(state, line, def, p_value); 754if(name) 755return name; 756} 757 758 len =strchrnul(line,'\n') - line; 759 date_len =diff_timestamp_len(line, len); 760if(!date_len) 761returnfind_name_common(state, line, def, p_value, NULL, TERM_TAB); 762 len -= date_len; 763 764returnfind_name_common(state, line, def, p_value, line + len,0); 765} 766 767/* 768 * Given the string after "--- " or "+++ ", guess the appropriate 769 * p_value for the given patch. 770 */ 771static intguess_p_value(struct apply_state *state,const char*nameline) 772{ 773char*name, *cp; 774int val = -1; 775 776if(is_dev_null(nameline)) 777return-1; 778 name =find_name_traditional(state, nameline, NULL,0); 779if(!name) 780return-1; 781 cp =strchr(name,'/'); 782if(!cp) 783 val =0; 784else if(state->prefix) { 785/* 786 * Does it begin with "a/$our-prefix" and such? Then this is 787 * very likely to apply to our directory. 788 */ 789if(!strncmp(name, state->prefix, state->prefix_length)) 790 val =count_slashes(state->prefix); 791else{ 792 cp++; 793if(!strncmp(cp, state->prefix, state->prefix_length)) 794 val =count_slashes(state->prefix) +1; 795} 796} 797free(name); 798return val; 799} 800 801/* 802 * Does the ---/+++ line have the POSIX timestamp after the last HT? 803 * GNU diff puts epoch there to signal a creation/deletion event. Is 804 * this such a timestamp? 805 */ 806static inthas_epoch_timestamp(const char*nameline) 807{ 808/* 809 * We are only interested in epoch timestamp; any non-zero 810 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 811 * For the same reason, the date must be either 1969-12-31 or 812 * 1970-01-01, and the seconds part must be "00". 813 */ 814const char stamp_regexp[] = 815"^(1969-12-31|1970-01-01)" 816" " 817"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 818" " 819"([-+][0-2][0-9]:?[0-5][0-9])\n"; 820const char*timestamp = NULL, *cp, *colon; 821static regex_t *stamp; 822 regmatch_t m[10]; 823int zoneoffset, epoch_hour, hour, minute; 824int status; 825 826for(cp = nameline; *cp !='\n'; cp++) { 827if(*cp =='\t') 828 timestamp = cp +1; 829} 830if(!timestamp) 831return0; 832 833/* 834 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 835 * (west of GMT) or 1970-01-01 (east of GMT) 836 */ 837if(starts_with(timestamp,"1969-12-31")) 838 epoch_hour =24; 839else if(starts_with(timestamp,"1970-01-01")) 840 epoch_hour =0; 841else 842return0; 843 844if(!stamp) { 845 stamp =xmalloc(sizeof(*stamp)); 846if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 847warning(_("Cannot prepare timestamp regexp%s"), 848 stamp_regexp); 849return0; 850} 851} 852 853 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 854if(status) { 855if(status != REG_NOMATCH) 856warning(_("regexec returned%dfor input:%s"), 857 status, timestamp); 858return0; 859} 860 861 hour =strtol(timestamp +11, NULL,10); 862 minute =strtol(timestamp +14, NULL,10); 863 864 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 865if(*colon ==':') 866 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 867else 868 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 869if(timestamp[m[3].rm_so] =='-') 870 zoneoffset = -zoneoffset; 871 872return hour *60+ minute - zoneoffset == epoch_hour *60; 873} 874 875/* 876 * Get the name etc info from the ---/+++ lines of a traditional patch header 877 * 878 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 879 * files, we can happily check the index for a match, but for creating a 880 * new file we should try to match whatever "patch" does. I have no idea. 881 */ 882static intparse_traditional_patch(struct apply_state *state, 883const char*first, 884const char*second, 885struct patch *patch) 886{ 887char*name; 888 889 first +=4;/* skip "--- " */ 890 second +=4;/* skip "+++ " */ 891if(!state->p_value_known) { 892int p, q; 893 p =guess_p_value(state, first); 894 q =guess_p_value(state, second); 895if(p <0) p = q; 896if(0<= p && p == q) { 897 state->p_value = p; 898 state->p_value_known =1; 899} 900} 901if(is_dev_null(first)) { 902 patch->is_new =1; 903 patch->is_delete =0; 904 name =find_name_traditional(state, second, NULL, state->p_value); 905 patch->new_name = name; 906}else if(is_dev_null(second)) { 907 patch->is_new =0; 908 patch->is_delete =1; 909 name =find_name_traditional(state, first, NULL, state->p_value); 910 patch->old_name = name; 911}else{ 912char*first_name; 913 first_name =find_name_traditional(state, first, NULL, state->p_value); 914 name =find_name_traditional(state, second, first_name, state->p_value); 915free(first_name); 916if(has_epoch_timestamp(first)) { 917 patch->is_new =1; 918 patch->is_delete =0; 919 patch->new_name = name; 920}else if(has_epoch_timestamp(second)) { 921 patch->is_new =0; 922 patch->is_delete =1; 923 patch->old_name = name; 924}else{ 925 patch->old_name = name; 926 patch->new_name =xstrdup_or_null(name); 927} 928} 929if(!name) 930returnerror(_("unable to find filename in patch at line%d"), state->linenr); 931 932return0; 933} 934 935static intgitdiff_hdrend(struct apply_state *state, 936const char*line, 937struct patch *patch) 938{ 939return1; 940} 941 942/* 943 * We're anal about diff header consistency, to make 944 * sure that we don't end up having strange ambiguous 945 * patches floating around. 946 * 947 * As a result, gitdiff_{old|new}name() will check 948 * their names against any previous information, just 949 * to make sure.. 950 */ 951#define DIFF_OLD_NAME 0 952#define DIFF_NEW_NAME 1 953 954static intgitdiff_verify_name(struct apply_state *state, 955const char*line, 956int isnull, 957char**name, 958int side) 959{ 960if(!*name && !isnull) { 961*name =find_name(state, line, NULL, state->p_value, TERM_TAB); 962return0; 963} 964 965if(*name) { 966char*another; 967if(isnull) 968returnerror(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 969*name, state->linenr); 970 another =find_name(state, line, NULL, state->p_value, TERM_TAB); 971if(!another ||strcmp(another, *name)) { 972free(another); 973returnerror((side == DIFF_NEW_NAME) ? 974_("git apply: bad git-diff - inconsistent new filename on line%d") : 975_("git apply: bad git-diff - inconsistent old filename on line%d"), state->linenr); 976} 977free(another); 978}else{ 979if(!starts_with(line,"/dev/null\n")) 980returnerror(_("git apply: bad git-diff - expected /dev/null on line%d"), state->linenr); 981} 982 983return0; 984} 985 986static intgitdiff_oldname(struct apply_state *state, 987const char*line, 988struct patch *patch) 989{ 990returngitdiff_verify_name(state, line, 991 patch->is_new, &patch->old_name, 992 DIFF_OLD_NAME); 993} 994 995static intgitdiff_newname(struct apply_state *state, 996const char*line, 997struct patch *patch) 998{ 999returngitdiff_verify_name(state, line,1000 patch->is_delete, &patch->new_name,1001 DIFF_NEW_NAME);1002}10031004static intparse_mode_line(const char*line,int linenr,unsigned int*mode)1005{1006char*end;1007*mode =strtoul(line, &end,8);1008if(end == line || !isspace(*end))1009returnerror(_("invalid mode on line%d:%s"), linenr, line);1010return0;1011}10121013static intgitdiff_oldmode(struct apply_state *state,1014const char*line,1015struct patch *patch)1016{1017returnparse_mode_line(line, state->linenr, &patch->old_mode);1018}10191020static intgitdiff_newmode(struct apply_state *state,1021const char*line,1022struct patch *patch)1023{1024returnparse_mode_line(line, state->linenr, &patch->new_mode);1025}10261027static intgitdiff_delete(struct apply_state *state,1028const char*line,1029struct patch *patch)1030{1031 patch->is_delete =1;1032free(patch->old_name);1033 patch->old_name =xstrdup_or_null(patch->def_name);1034returngitdiff_oldmode(state, line, patch);1035}10361037static intgitdiff_newfile(struct apply_state *state,1038const char*line,1039struct patch *patch)1040{1041 patch->is_new =1;1042free(patch->new_name);1043 patch->new_name =xstrdup_or_null(patch->def_name);1044returngitdiff_newmode(state, line, patch);1045}10461047static intgitdiff_copysrc(struct apply_state *state,1048const char*line,1049struct patch *patch)1050{1051 patch->is_copy =1;1052free(patch->old_name);1053 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1054return0;1055}10561057static intgitdiff_copydst(struct apply_state *state,1058const char*line,1059struct patch *patch)1060{1061 patch->is_copy =1;1062free(patch->new_name);1063 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1064return0;1065}10661067static intgitdiff_renamesrc(struct apply_state *state,1068const char*line,1069struct patch *patch)1070{1071 patch->is_rename =1;1072free(patch->old_name);1073 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1074return0;1075}10761077static intgitdiff_renamedst(struct apply_state *state,1078const char*line,1079struct patch *patch)1080{1081 patch->is_rename =1;1082free(patch->new_name);1083 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1084return0;1085}10861087static intgitdiff_similarity(struct apply_state *state,1088const char*line,1089struct patch *patch)1090{1091unsigned long val =strtoul(line, NULL,10);1092if(val <=100)1093 patch->score = val;1094return0;1095}10961097static intgitdiff_dissimilarity(struct apply_state *state,1098const char*line,1099struct patch *patch)1100{1101unsigned long val =strtoul(line, NULL,10);1102if(val <=100)1103 patch->score = val;1104return0;1105}11061107static intgitdiff_index(struct apply_state *state,1108const char*line,1109struct patch *patch)1110{1111/*1112 * index line is N hexadecimal, "..", N hexadecimal,1113 * and optional space with octal mode.1114 */1115const char*ptr, *eol;1116int len;11171118 ptr =strchr(line,'.');1119if(!ptr || ptr[1] !='.'||40< ptr - line)1120return0;1121 len = ptr - line;1122memcpy(patch->old_sha1_prefix, line, len);1123 patch->old_sha1_prefix[len] =0;11241125 line = ptr +2;1126 ptr =strchr(line,' ');1127 eol =strchrnul(line,'\n');11281129if(!ptr || eol < ptr)1130 ptr = eol;1131 len = ptr - line;11321133if(40< len)1134return0;1135memcpy(patch->new_sha1_prefix, line, len);1136 patch->new_sha1_prefix[len] =0;1137if(*ptr ==' ')1138returngitdiff_oldmode(state, ptr +1, patch);1139return0;1140}11411142/*1143 * This is normal for a diff that doesn't change anything: we'll fall through1144 * into the next diff. Tell the parser to break out.1145 */1146static intgitdiff_unrecognized(struct apply_state *state,1147const char*line,1148struct patch *patch)1149{1150return1;1151}11521153/*1154 * Skip p_value leading components from "line"; as we do not accept1155 * absolute paths, return NULL in that case.1156 */1157static const char*skip_tree_prefix(struct apply_state *state,1158const char*line,1159int llen)1160{1161int nslash;1162int i;11631164if(!state->p_value)1165return(llen && line[0] =='/') ? NULL : line;11661167 nslash = state->p_value;1168for(i =0; i < llen; i++) {1169int ch = line[i];1170if(ch =='/'&& --nslash <=0)1171return(i ==0) ? NULL : &line[i +1];1172}1173return NULL;1174}11751176/*1177 * This is to extract the same name that appears on "diff --git"1178 * line. We do not find and return anything if it is a rename1179 * patch, and it is OK because we will find the name elsewhere.1180 * We need to reliably find name only when it is mode-change only,1181 * creation or deletion of an empty file. In any of these cases,1182 * both sides are the same name under a/ and b/ respectively.1183 */1184static char*git_header_name(struct apply_state *state,1185const char*line,1186int llen)1187{1188const char*name;1189const char*second = NULL;1190size_t len, line_len;11911192 line +=strlen("diff --git ");1193 llen -=strlen("diff --git ");11941195if(*line =='"') {1196const char*cp;1197struct strbuf first = STRBUF_INIT;1198struct strbuf sp = STRBUF_INIT;11991200if(unquote_c_style(&first, line, &second))1201goto free_and_fail1;12021203/* strip the a/b prefix including trailing slash */1204 cp =skip_tree_prefix(state, first.buf, first.len);1205if(!cp)1206goto free_and_fail1;1207strbuf_remove(&first,0, cp - first.buf);12081209/*1210 * second points at one past closing dq of name.1211 * find the second name.1212 */1213while((second < line + llen) &&isspace(*second))1214 second++;12151216if(line + llen <= second)1217goto free_and_fail1;1218if(*second =='"') {1219if(unquote_c_style(&sp, second, NULL))1220goto free_and_fail1;1221 cp =skip_tree_prefix(state, sp.buf, sp.len);1222if(!cp)1223goto free_and_fail1;1224/* They must match, otherwise ignore */1225if(strcmp(cp, first.buf))1226goto free_and_fail1;1227strbuf_release(&sp);1228returnstrbuf_detach(&first, NULL);1229}12301231/* unquoted second */1232 cp =skip_tree_prefix(state, second, line + llen - second);1233if(!cp)1234goto free_and_fail1;1235if(line + llen - cp != first.len ||1236memcmp(first.buf, cp, first.len))1237goto free_and_fail1;1238returnstrbuf_detach(&first, NULL);12391240 free_and_fail1:1241strbuf_release(&first);1242strbuf_release(&sp);1243return NULL;1244}12451246/* unquoted first name */1247 name =skip_tree_prefix(state, line, llen);1248if(!name)1249return NULL;12501251/*1252 * since the first name is unquoted, a dq if exists must be1253 * the beginning of the second name.1254 */1255for(second = name; second < line + llen; second++) {1256if(*second =='"') {1257struct strbuf sp = STRBUF_INIT;1258const char*np;12591260if(unquote_c_style(&sp, second, NULL))1261goto free_and_fail2;12621263 np =skip_tree_prefix(state, sp.buf, sp.len);1264if(!np)1265goto free_and_fail2;12661267 len = sp.buf + sp.len - np;1268if(len < second - name &&1269!strncmp(np, name, len) &&1270isspace(name[len])) {1271/* Good */1272strbuf_remove(&sp,0, np - sp.buf);1273returnstrbuf_detach(&sp, NULL);1274}12751276 free_and_fail2:1277strbuf_release(&sp);1278return NULL;1279}1280}12811282/*1283 * Accept a name only if it shows up twice, exactly the same1284 * form.1285 */1286 second =strchr(name,'\n');1287if(!second)1288return NULL;1289 line_len = second - name;1290for(len =0; ; len++) {1291switch(name[len]) {1292default:1293continue;1294case'\n':1295return NULL;1296case'\t':case' ':1297/*1298 * Is this the separator between the preimage1299 * and the postimage pathname? Again, we are1300 * only interested in the case where there is1301 * no rename, as this is only to set def_name1302 * and a rename patch has the names elsewhere1303 * in an unambiguous form.1304 */1305if(!name[len +1])1306return NULL;/* no postimage name */1307 second =skip_tree_prefix(state, name + len +1,1308 line_len - (len +1));1309if(!second)1310return NULL;1311/*1312 * Does len bytes starting at "name" and "second"1313 * (that are separated by one HT or SP we just1314 * found) exactly match?1315 */1316if(second[len] =='\n'&& !strncmp(name, second, len))1317returnxmemdupz(name, len);1318}1319}1320}13211322static intcheck_header_line(struct apply_state *state,struct patch *patch)1323{1324int extensions = (patch->is_delete ==1) + (patch->is_new ==1) +1325(patch->is_rename ==1) + (patch->is_copy ==1);1326if(extensions >1)1327returnerror(_("inconsistent header lines%dand%d"),1328 patch->extension_linenr, state->linenr);1329if(extensions && !patch->extension_linenr)1330 patch->extension_linenr = state->linenr;1331return0;1332}13331334/* Verify that we recognize the lines following a git header */1335static intparse_git_header(struct apply_state *state,1336const char*line,1337int len,1338unsigned int size,1339struct patch *patch)1340{1341unsigned long offset;13421343/* A git diff has explicit new/delete information, so we don't guess */1344 patch->is_new =0;1345 patch->is_delete =0;13461347/*1348 * Some things may not have the old name in the1349 * rest of the headers anywhere (pure mode changes,1350 * or removing or adding empty files), so we get1351 * the default name from the header.1352 */1353 patch->def_name =git_header_name(state, line, len);1354if(patch->def_name && state->root.len) {1355char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1356free(patch->def_name);1357 patch->def_name = s;1358}13591360 line += len;1361 size -= len;1362 state->linenr++;1363for(offset = len ; size >0; offset += len, size -= len, line += len, state->linenr++) {1364static const struct opentry {1365const char*str;1366int(*fn)(struct apply_state *,const char*,struct patch *);1367} optable[] = {1368{"@@ -", gitdiff_hdrend },1369{"--- ", gitdiff_oldname },1370{"+++ ", gitdiff_newname },1371{"old mode ", gitdiff_oldmode },1372{"new mode ", gitdiff_newmode },1373{"deleted file mode ", gitdiff_delete },1374{"new file mode ", gitdiff_newfile },1375{"copy from ", gitdiff_copysrc },1376{"copy to ", gitdiff_copydst },1377{"rename old ", gitdiff_renamesrc },1378{"rename new ", gitdiff_renamedst },1379{"rename from ", gitdiff_renamesrc },1380{"rename to ", gitdiff_renamedst },1381{"similarity index ", gitdiff_similarity },1382{"dissimilarity index ", gitdiff_dissimilarity },1383{"index ", gitdiff_index },1384{"", gitdiff_unrecognized },1385};1386int i;13871388 len =linelen(line, size);1389if(!len || line[len-1] !='\n')1390break;1391for(i =0; i <ARRAY_SIZE(optable); i++) {1392const struct opentry *p = optable + i;1393int oplen =strlen(p->str);1394int res;1395if(len < oplen ||memcmp(p->str, line, oplen))1396continue;1397 res = p->fn(state, line + oplen, patch);1398if(res <0)1399return-1;1400if(check_header_line(state, patch))1401return-1;1402if(res >0)1403return offset;1404break;1405}1406}14071408return offset;1409}14101411static intparse_num(const char*line,unsigned long*p)1412{1413char*ptr;14141415if(!isdigit(*line))1416return0;1417*p =strtoul(line, &ptr,10);1418return ptr - line;1419}14201421static intparse_range(const char*line,int len,int offset,const char*expect,1422unsigned long*p1,unsigned long*p2)1423{1424int digits, ex;14251426if(offset <0|| offset >= len)1427return-1;1428 line += offset;1429 len -= offset;14301431 digits =parse_num(line, p1);1432if(!digits)1433return-1;14341435 offset += digits;1436 line += digits;1437 len -= digits;14381439*p2 =1;1440if(*line ==',') {1441 digits =parse_num(line+1, p2);1442if(!digits)1443return-1;14441445 offset += digits+1;1446 line += digits+1;1447 len -= digits+1;1448}14491450 ex =strlen(expect);1451if(ex > len)1452return-1;1453if(memcmp(line, expect, ex))1454return-1;14551456return offset + ex;1457}14581459static voidrecount_diff(const char*line,int size,struct fragment *fragment)1460{1461int oldlines =0, newlines =0, ret =0;14621463if(size <1) {1464warning("recount: ignore empty hunk");1465return;1466}14671468for(;;) {1469int len =linelen(line, size);1470 size -= len;1471 line += len;14721473if(size <1)1474break;14751476switch(*line) {1477case' ':case'\n':1478 newlines++;1479/* fall through */1480case'-':1481 oldlines++;1482continue;1483case'+':1484 newlines++;1485continue;1486case'\\':1487continue;1488case'@':1489 ret = size <3|| !starts_with(line,"@@ ");1490break;1491case'd':1492 ret = size <5|| !starts_with(line,"diff ");1493break;1494default:1495 ret = -1;1496break;1497}1498if(ret) {1499warning(_("recount: unexpected line: %.*s"),1500(int)linelen(line, size), line);1501return;1502}1503break;1504}1505 fragment->oldlines = oldlines;1506 fragment->newlines = newlines;1507}15081509/*1510 * Parse a unified diff fragment header of the1511 * form "@@ -a,b +c,d @@"1512 */1513static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1514{1515int offset;15161517if(!len || line[len-1] !='\n')1518return-1;15191520/* Figure out the number of lines in a fragment */1521 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1522 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);15231524return offset;1525}15261527/*1528 * Find file diff header1529 *1530 * Returns:1531 * -1 if no header was found1532 * -128 in case of error1533 * the size of the header in bytes (called "offset") otherwise1534 */1535static intfind_header(struct apply_state *state,1536const char*line,1537unsigned long size,1538int*hdrsize,1539struct patch *patch)1540{1541unsigned long offset, len;15421543 patch->is_toplevel_relative =0;1544 patch->is_rename = patch->is_copy =0;1545 patch->is_new = patch->is_delete = -1;1546 patch->old_mode = patch->new_mode =0;1547 patch->old_name = patch->new_name = NULL;1548for(offset =0; size >0; offset += len, size -= len, line += len, state->linenr++) {1549unsigned long nextlen;15501551 len =linelen(line, size);1552if(!len)1553break;15541555/* Testing this early allows us to take a few shortcuts.. */1556if(len <6)1557continue;15581559/*1560 * Make sure we don't find any unconnected patch fragments.1561 * That's a sign that we didn't find a header, and that a1562 * patch has become corrupted/broken up.1563 */1564if(!memcmp("@@ -", line,4)) {1565struct fragment dummy;1566if(parse_fragment_header(line, len, &dummy) <0)1567continue;1568error(_("patch fragment without header at line%d: %.*s"),1569 state->linenr, (int)len-1, line);1570return-128;1571}15721573if(size < len +6)1574break;15751576/*1577 * Git patch? It might not have a real patch, just a rename1578 * or mode change, so we handle that specially1579 */1580if(!memcmp("diff --git ", line,11)) {1581int git_hdr_len =parse_git_header(state, line, len, size, patch);1582if(git_hdr_len <0)1583return-128;1584if(git_hdr_len <= len)1585continue;1586if(!patch->old_name && !patch->new_name) {1587if(!patch->def_name) {1588error(Q_("git diff header lacks filename information when removing "1589"%dleading pathname component (line%d)",1590"git diff header lacks filename information when removing "1591"%dleading pathname components (line%d)",1592 state->p_value),1593 state->p_value, state->linenr);1594return-128;1595}1596 patch->old_name =xstrdup(patch->def_name);1597 patch->new_name =xstrdup(patch->def_name);1598}1599if((!patch->new_name && !patch->is_delete) ||1600(!patch->old_name && !patch->is_new)) {1601error(_("git diff header lacks filename information "1602"(line%d)"), state->linenr);1603return-128;1604}1605 patch->is_toplevel_relative =1;1606*hdrsize = git_hdr_len;1607return offset;1608}16091610/* --- followed by +++ ? */1611if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1612continue;16131614/*1615 * We only accept unified patches, so we want it to1616 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1617 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1618 */1619 nextlen =linelen(line + len, size - len);1620if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1621continue;16221623/* Ok, we'll consider it a patch */1624if(parse_traditional_patch(state, line, line+len, patch))1625return-128;1626*hdrsize = len + nextlen;1627 state->linenr +=2;1628return offset;1629}1630return-1;1631}16321633static voidrecord_ws_error(struct apply_state *state,1634unsigned result,1635const char*line,1636int len,1637int linenr)1638{1639char*err;16401641if(!result)1642return;16431644 state->whitespace_error++;1645if(state->squelch_whitespace_errors &&1646 state->squelch_whitespace_errors < state->whitespace_error)1647return;16481649 err =whitespace_error_string(result);1650if(state->apply_verbosity > verbosity_silent)1651fprintf(stderr,"%s:%d:%s.\n%.*s\n",1652 state->patch_input_file, linenr, err, len, line);1653free(err);1654}16551656static voidcheck_whitespace(struct apply_state *state,1657const char*line,1658int len,1659unsigned ws_rule)1660{1661unsigned result =ws_check(line +1, len -1, ws_rule);16621663record_ws_error(state, result, line +1, len -2, state->linenr);1664}16651666/*1667 * Parse a unified diff. Note that this really needs to parse each1668 * fragment separately, since the only way to know the difference1669 * between a "---" that is part of a patch, and a "---" that starts1670 * the next patch is to look at the line counts..1671 */1672static intparse_fragment(struct apply_state *state,1673const char*line,1674unsigned long size,1675struct patch *patch,1676struct fragment *fragment)1677{1678int added, deleted;1679int len =linelen(line, size), offset;1680unsigned long oldlines, newlines;1681unsigned long leading, trailing;16821683 offset =parse_fragment_header(line, len, fragment);1684if(offset <0)1685return-1;1686if(offset >0&& patch->recount)1687recount_diff(line + offset, size - offset, fragment);1688 oldlines = fragment->oldlines;1689 newlines = fragment->newlines;1690 leading =0;1691 trailing =0;16921693/* Parse the thing.. */1694 line += len;1695 size -= len;1696 state->linenr++;1697 added = deleted =0;1698for(offset = len;16990< size;1700 offset += len, size -= len, line += len, state->linenr++) {1701if(!oldlines && !newlines)1702break;1703 len =linelen(line, size);1704if(!len || line[len-1] !='\n')1705return-1;1706switch(*line) {1707default:1708return-1;1709case'\n':/* newer GNU diff, an empty context line */1710case' ':1711 oldlines--;1712 newlines--;1713if(!deleted && !added)1714 leading++;1715 trailing++;1716if(!state->apply_in_reverse &&1717 state->ws_error_action == correct_ws_error)1718check_whitespace(state, line, len, patch->ws_rule);1719break;1720case'-':1721if(state->apply_in_reverse &&1722 state->ws_error_action != nowarn_ws_error)1723check_whitespace(state, line, len, patch->ws_rule);1724 deleted++;1725 oldlines--;1726 trailing =0;1727break;1728case'+':1729if(!state->apply_in_reverse &&1730 state->ws_error_action != nowarn_ws_error)1731check_whitespace(state, line, len, patch->ws_rule);1732 added++;1733 newlines--;1734 trailing =0;1735break;17361737/*1738 * We allow "\ No newline at end of file". Depending1739 * on locale settings when the patch was produced we1740 * don't know what this line looks like. The only1741 * thing we do know is that it begins with "\ ".1742 * Checking for 12 is just for sanity check -- any1743 * l10n of "\ No newline..." is at least that long.1744 */1745case'\\':1746if(len <12||memcmp(line,"\\",2))1747return-1;1748break;1749}1750}1751if(oldlines || newlines)1752return-1;1753if(!deleted && !added)1754return-1;17551756 fragment->leading = leading;1757 fragment->trailing = trailing;17581759/*1760 * If a fragment ends with an incomplete line, we failed to include1761 * it in the above loop because we hit oldlines == newlines == 01762 * before seeing it.1763 */1764if(12< size && !memcmp(line,"\\",2))1765 offset +=linelen(line, size);17661767 patch->lines_added += added;1768 patch->lines_deleted += deleted;17691770if(0< patch->is_new && oldlines)1771returnerror(_("new file depends on old contents"));1772if(0< patch->is_delete && newlines)1773returnerror(_("deleted file still has contents"));1774return offset;1775}17761777/*1778 * We have seen "diff --git a/... b/..." header (or a traditional patch1779 * header). Read hunks that belong to this patch into fragments and hang1780 * them to the given patch structure.1781 *1782 * The (fragment->patch, fragment->size) pair points into the memory given1783 * by the caller, not a copy, when we return.1784 *1785 * Returns:1786 * -1 in case of error,1787 * the number of bytes in the patch otherwise.1788 */1789static intparse_single_patch(struct apply_state *state,1790const char*line,1791unsigned long size,1792struct patch *patch)1793{1794unsigned long offset =0;1795unsigned long oldlines =0, newlines =0, context =0;1796struct fragment **fragp = &patch->fragments;17971798while(size >4&& !memcmp(line,"@@ -",4)) {1799struct fragment *fragment;1800int len;18011802 fragment =xcalloc(1,sizeof(*fragment));1803 fragment->linenr = state->linenr;1804 len =parse_fragment(state, line, size, patch, fragment);1805if(len <=0) {1806free(fragment);1807returnerror(_("corrupt patch at line%d"), state->linenr);1808}1809 fragment->patch = line;1810 fragment->size = len;1811 oldlines += fragment->oldlines;1812 newlines += fragment->newlines;1813 context += fragment->leading + fragment->trailing;18141815*fragp = fragment;1816 fragp = &fragment->next;18171818 offset += len;1819 line += len;1820 size -= len;1821}18221823/*1824 * If something was removed (i.e. we have old-lines) it cannot1825 * be creation, and if something was added it cannot be1826 * deletion. However, the reverse is not true; --unified=01827 * patches that only add are not necessarily creation even1828 * though they do not have any old lines, and ones that only1829 * delete are not necessarily deletion.1830 *1831 * Unfortunately, a real creation/deletion patch do _not_ have1832 * any context line by definition, so we cannot safely tell it1833 * apart with --unified=0 insanity. At least if the patch has1834 * more than one hunk it is not creation or deletion.1835 */1836if(patch->is_new <0&&1837(oldlines || (patch->fragments && patch->fragments->next)))1838 patch->is_new =0;1839if(patch->is_delete <0&&1840(newlines || (patch->fragments && patch->fragments->next)))1841 patch->is_delete =0;18421843if(0< patch->is_new && oldlines)1844returnerror(_("new file%sdepends on old contents"), patch->new_name);1845if(0< patch->is_delete && newlines)1846returnerror(_("deleted file%sstill has contents"), patch->old_name);1847if(!patch->is_delete && !newlines && context && state->apply_verbosity > verbosity_silent)1848fprintf_ln(stderr,1849_("** warning: "1850"file%sbecomes empty but is not deleted"),1851 patch->new_name);18521853return offset;1854}18551856staticinlineintmetadata_changes(struct patch *patch)1857{1858return patch->is_rename >0||1859 patch->is_copy >0||1860 patch->is_new >0||1861 patch->is_delete ||1862(patch->old_mode && patch->new_mode &&1863 patch->old_mode != patch->new_mode);1864}18651866static char*inflate_it(const void*data,unsigned long size,1867unsigned long inflated_size)1868{1869 git_zstream stream;1870void*out;1871int st;18721873memset(&stream,0,sizeof(stream));18741875 stream.next_in = (unsigned char*)data;1876 stream.avail_in = size;1877 stream.next_out = out =xmalloc(inflated_size);1878 stream.avail_out = inflated_size;1879git_inflate_init(&stream);1880 st =git_inflate(&stream, Z_FINISH);1881git_inflate_end(&stream);1882if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1883free(out);1884return NULL;1885}1886return out;1887}18881889/*1890 * Read a binary hunk and return a new fragment; fragment->patch1891 * points at an allocated memory that the caller must free, so1892 * it is marked as "->free_patch = 1".1893 */1894static struct fragment *parse_binary_hunk(struct apply_state *state,1895char**buf_p,1896unsigned long*sz_p,1897int*status_p,1898int*used_p)1899{1900/*1901 * Expect a line that begins with binary patch method ("literal"1902 * or "delta"), followed by the length of data before deflating.1903 * a sequence of 'length-byte' followed by base-85 encoded data1904 * should follow, terminated by a newline.1905 *1906 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1907 * and we would limit the patch line to 66 characters,1908 * so one line can fit up to 13 groups that would decode1909 * to 52 bytes max. The length byte 'A'-'Z' corresponds1910 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1911 */1912int llen, used;1913unsigned long size = *sz_p;1914char*buffer = *buf_p;1915int patch_method;1916unsigned long origlen;1917char*data = NULL;1918int hunk_size =0;1919struct fragment *frag;19201921 llen =linelen(buffer, size);1922 used = llen;19231924*status_p =0;19251926if(starts_with(buffer,"delta ")) {1927 patch_method = BINARY_DELTA_DEFLATED;1928 origlen =strtoul(buffer +6, NULL,10);1929}1930else if(starts_with(buffer,"literal ")) {1931 patch_method = BINARY_LITERAL_DEFLATED;1932 origlen =strtoul(buffer +8, NULL,10);1933}1934else1935return NULL;19361937 state->linenr++;1938 buffer += llen;1939while(1) {1940int byte_length, max_byte_length, newsize;1941 llen =linelen(buffer, size);1942 used += llen;1943 state->linenr++;1944if(llen ==1) {1945/* consume the blank line */1946 buffer++;1947 size--;1948break;1949}1950/*1951 * Minimum line is "A00000\n" which is 7-byte long,1952 * and the line length must be multiple of 5 plus 2.1953 */1954if((llen <7) || (llen-2) %5)1955goto corrupt;1956 max_byte_length = (llen -2) /5*4;1957 byte_length = *buffer;1958if('A'<= byte_length && byte_length <='Z')1959 byte_length = byte_length -'A'+1;1960else if('a'<= byte_length && byte_length <='z')1961 byte_length = byte_length -'a'+27;1962else1963goto corrupt;1964/* if the input length was not multiple of 4, we would1965 * have filler at the end but the filler should never1966 * exceed 3 bytes1967 */1968if(max_byte_length < byte_length ||1969 byte_length <= max_byte_length -4)1970goto corrupt;1971 newsize = hunk_size + byte_length;1972 data =xrealloc(data, newsize);1973if(decode_85(data + hunk_size, buffer +1, byte_length))1974goto corrupt;1975 hunk_size = newsize;1976 buffer += llen;1977 size -= llen;1978}19791980 frag =xcalloc(1,sizeof(*frag));1981 frag->patch =inflate_it(data, hunk_size, origlen);1982 frag->free_patch =1;1983if(!frag->patch)1984goto corrupt;1985free(data);1986 frag->size = origlen;1987*buf_p = buffer;1988*sz_p = size;1989*used_p = used;1990 frag->binary_patch_method = patch_method;1991return frag;19921993 corrupt:1994free(data);1995*status_p = -1;1996error(_("corrupt binary patch at line%d: %.*s"),1997 state->linenr-1, llen-1, buffer);1998return NULL;1999}20002001/*2002 * Returns:2003 * -1 in case of error,2004 * the length of the parsed binary patch otherwise2005 */2006static intparse_binary(struct apply_state *state,2007char*buffer,2008unsigned long size,2009struct patch *patch)2010{2011/*2012 * We have read "GIT binary patch\n"; what follows is a line2013 * that says the patch method (currently, either "literal" or2014 * "delta") and the length of data before deflating; a2015 * sequence of 'length-byte' followed by base-85 encoded data2016 * follows.2017 *2018 * When a binary patch is reversible, there is another binary2019 * hunk in the same format, starting with patch method (either2020 * "literal" or "delta") with the length of data, and a sequence2021 * of length-byte + base-85 encoded data, terminated with another2022 * empty line. This data, when applied to the postimage, produces2023 * the preimage.2024 */2025struct fragment *forward;2026struct fragment *reverse;2027int status;2028int used, used_1;20292030 forward =parse_binary_hunk(state, &buffer, &size, &status, &used);2031if(!forward && !status)2032/* there has to be one hunk (forward hunk) */2033returnerror(_("unrecognized binary patch at line%d"), state->linenr-1);2034if(status)2035/* otherwise we already gave an error message */2036return status;20372038 reverse =parse_binary_hunk(state, &buffer, &size, &status, &used_1);2039if(reverse)2040 used += used_1;2041else if(status) {2042/*2043 * Not having reverse hunk is not an error, but having2044 * a corrupt reverse hunk is.2045 */2046free((void*) forward->patch);2047free(forward);2048return status;2049}2050 forward->next = reverse;2051 patch->fragments = forward;2052 patch->is_binary =1;2053return used;2054}20552056static voidprefix_one(struct apply_state *state,char**name)2057{2058char*old_name = *name;2059if(!old_name)2060return;2061*name =prefix_filename(state->prefix, *name);2062free(old_name);2063}20642065static voidprefix_patch(struct apply_state *state,struct patch *p)2066{2067if(!state->prefix || p->is_toplevel_relative)2068return;2069prefix_one(state, &p->new_name);2070prefix_one(state, &p->old_name);2071}20722073/*2074 * include/exclude2075 */20762077static voidadd_name_limit(struct apply_state *state,2078const char*name,2079int exclude)2080{2081struct string_list_item *it;20822083 it =string_list_append(&state->limit_by_name, name);2084 it->util = exclude ? NULL : (void*)1;2085}20862087static intuse_patch(struct apply_state *state,struct patch *p)2088{2089const char*pathname = p->new_name ? p->new_name : p->old_name;2090int i;20912092/* Paths outside are not touched regardless of "--include" */2093if(0< state->prefix_length) {2094int pathlen =strlen(pathname);2095if(pathlen <= state->prefix_length ||2096memcmp(state->prefix, pathname, state->prefix_length))2097return0;2098}20992100/* See if it matches any of exclude/include rule */2101for(i =0; i < state->limit_by_name.nr; i++) {2102struct string_list_item *it = &state->limit_by_name.items[i];2103if(!wildmatch(it->string, pathname,0))2104return(it->util != NULL);2105}21062107/*2108 * If we had any include, a path that does not match any rule is2109 * not used. Otherwise, we saw bunch of exclude rules (or none)2110 * and such a path is used.2111 */2112return!state->has_include;2113}21142115/*2116 * Read the patch text in "buffer" that extends for "size" bytes; stop2117 * reading after seeing a single patch (i.e. changes to a single file).2118 * Create fragments (i.e. patch hunks) and hang them to the given patch.2119 *2120 * Returns:2121 * -1 if no header was found or parse_binary() failed,2122 * -128 on another error,2123 * the number of bytes consumed otherwise,2124 * so that the caller can call us again for the next patch.2125 */2126static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2127{2128int hdrsize, patchsize;2129int offset =find_header(state, buffer, size, &hdrsize, patch);21302131if(offset <0)2132return offset;21332134prefix_patch(state, patch);21352136if(!use_patch(state, patch))2137 patch->ws_rule =0;2138else2139 patch->ws_rule =whitespace_rule(patch->new_name2140? patch->new_name2141: patch->old_name);21422143 patchsize =parse_single_patch(state,2144 buffer + offset + hdrsize,2145 size - offset - hdrsize,2146 patch);21472148if(patchsize <0)2149return-128;21502151if(!patchsize) {2152static const char git_binary[] ="GIT binary patch\n";2153int hd = hdrsize + offset;2154unsigned long llen =linelen(buffer + hd, size - hd);21552156if(llen ==sizeof(git_binary) -1&&2157!memcmp(git_binary, buffer + hd, llen)) {2158int used;2159 state->linenr++;2160 used =parse_binary(state, buffer + hd + llen,2161 size - hd - llen, patch);2162if(used <0)2163return-1;2164if(used)2165 patchsize = used + llen;2166else2167 patchsize =0;2168}2169else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2170static const char*binhdr[] = {2171"Binary files ",2172"Files ",2173 NULL,2174};2175int i;2176for(i =0; binhdr[i]; i++) {2177int len =strlen(binhdr[i]);2178if(len < size - hd &&2179!memcmp(binhdr[i], buffer + hd, len)) {2180 state->linenr++;2181 patch->is_binary =1;2182 patchsize = llen;2183break;2184}2185}2186}21872188/* Empty patch cannot be applied if it is a text patch2189 * without metadata change. A binary patch appears2190 * empty to us here.2191 */2192if((state->apply || state->check) &&2193(!patch->is_binary && !metadata_changes(patch))) {2194error(_("patch with only garbage at line%d"), state->linenr);2195return-128;2196}2197}21982199return offset + hdrsize + patchsize;2200}22012202static voidreverse_patches(struct patch *p)2203{2204for(; p; p = p->next) {2205struct fragment *frag = p->fragments;22062207SWAP(p->new_name, p->old_name);2208SWAP(p->new_mode, p->old_mode);2209SWAP(p->is_new, p->is_delete);2210SWAP(p->lines_added, p->lines_deleted);2211SWAP(p->old_sha1_prefix, p->new_sha1_prefix);22122213for(; frag; frag = frag->next) {2214SWAP(frag->newpos, frag->oldpos);2215SWAP(frag->newlines, frag->oldlines);2216}2217}2218}22192220static const char pluses[] =2221"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2222static const char minuses[]=2223"----------------------------------------------------------------------";22242225static voidshow_stats(struct apply_state *state,struct patch *patch)2226{2227struct strbuf qname = STRBUF_INIT;2228char*cp = patch->new_name ? patch->new_name : patch->old_name;2229int max, add, del;22302231quote_c_style(cp, &qname, NULL,0);22322233/*2234 * "scale" the filename2235 */2236 max = state->max_len;2237if(max >50)2238 max =50;22392240if(qname.len > max) {2241 cp =strchr(qname.buf + qname.len +3- max,'/');2242if(!cp)2243 cp = qname.buf + qname.len +3- max;2244strbuf_splice(&qname,0, cp - qname.buf,"...",3);2245}22462247if(patch->is_binary) {2248printf(" %-*s | Bin\n", max, qname.buf);2249strbuf_release(&qname);2250return;2251}22522253printf(" %-*s |", max, qname.buf);2254strbuf_release(&qname);22552256/*2257 * scale the add/delete2258 */2259 max = max + state->max_change >70?70- max : state->max_change;2260 add = patch->lines_added;2261 del = patch->lines_deleted;22622263if(state->max_change >0) {2264int total = ((add + del) * max + state->max_change /2) / state->max_change;2265 add = (add * max + state->max_change /2) / state->max_change;2266 del = total - add;2267}2268printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2269 add, pluses, del, minuses);2270}22712272static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2273{2274switch(st->st_mode & S_IFMT) {2275case S_IFLNK:2276if(strbuf_readlink(buf, path, st->st_size) <0)2277returnerror(_("unable to read symlink%s"), path);2278return0;2279case S_IFREG:2280if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2281returnerror(_("unable to open or read%s"), path);2282convert_to_git(&the_index, path, buf->buf, buf->len, buf,0);2283return0;2284default:2285return-1;2286}2287}22882289/*2290 * Update the preimage, and the common lines in postimage,2291 * from buffer buf of length len. If postlen is 0 the postimage2292 * is updated in place, otherwise it's updated on a new buffer2293 * of length postlen2294 */22952296static voidupdate_pre_post_images(struct image *preimage,2297struct image *postimage,2298char*buf,2299size_t len,size_t postlen)2300{2301int i, ctx, reduced;2302char*new, *old, *fixed;2303struct image fixed_preimage;23042305/*2306 * Update the preimage with whitespace fixes. Note that we2307 * are not losing preimage->buf -- apply_one_fragment() will2308 * free "oldlines".2309 */2310prepare_image(&fixed_preimage, buf, len,1);2311assert(postlen2312? fixed_preimage.nr == preimage->nr2313: fixed_preimage.nr <= preimage->nr);2314for(i =0; i < fixed_preimage.nr; i++)2315 fixed_preimage.line[i].flag = preimage->line[i].flag;2316free(preimage->line_allocated);2317*preimage = fixed_preimage;23182319/*2320 * Adjust the common context lines in postimage. This can be2321 * done in-place when we are shrinking it with whitespace2322 * fixing, but needs a new buffer when ignoring whitespace or2323 * expanding leading tabs to spaces.2324 *2325 * We trust the caller to tell us if the update can be done2326 * in place (postlen==0) or not.2327 */2328 old = postimage->buf;2329if(postlen)2330new= postimage->buf =xmalloc(postlen);2331else2332new= old;2333 fixed = preimage->buf;23342335for(i = reduced = ctx =0; i < postimage->nr; i++) {2336size_t l_len = postimage->line[i].len;2337if(!(postimage->line[i].flag & LINE_COMMON)) {2338/* an added line -- no counterparts in preimage */2339memmove(new, old, l_len);2340 old += l_len;2341new+= l_len;2342continue;2343}23442345/* a common context -- skip it in the original postimage */2346 old += l_len;23472348/* and find the corresponding one in the fixed preimage */2349while(ctx < preimage->nr &&2350!(preimage->line[ctx].flag & LINE_COMMON)) {2351 fixed += preimage->line[ctx].len;2352 ctx++;2353}23542355/*2356 * preimage is expected to run out, if the caller2357 * fixed addition of trailing blank lines.2358 */2359if(preimage->nr <= ctx) {2360 reduced++;2361continue;2362}23632364/* and copy it in, while fixing the line length */2365 l_len = preimage->line[ctx].len;2366memcpy(new, fixed, l_len);2367new+= l_len;2368 fixed += l_len;2369 postimage->line[i].len = l_len;2370 ctx++;2371}23722373if(postlen2374? postlen <new- postimage->buf2375: postimage->len <new- postimage->buf)2376die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2377(int)postlen, (int) postimage->len, (int)(new- postimage->buf));23782379/* Fix the length of the whole thing */2380 postimage->len =new- postimage->buf;2381 postimage->nr -= reduced;2382}23832384static intline_by_line_fuzzy_match(struct image *img,2385struct image *preimage,2386struct image *postimage,2387unsigned longtry,2388int try_lno,2389int preimage_limit)2390{2391int i;2392size_t imgoff =0;2393size_t preoff =0;2394size_t postlen = postimage->len;2395size_t extra_chars;2396char*buf;2397char*preimage_eof;2398char*preimage_end;2399struct strbuf fixed;2400char*fixed_buf;2401size_t fixed_len;24022403for(i =0; i < preimage_limit; i++) {2404size_t prelen = preimage->line[i].len;2405size_t imglen = img->line[try_lno+i].len;24062407if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2408 preimage->buf + preoff, prelen))2409return0;2410if(preimage->line[i].flag & LINE_COMMON)2411 postlen += imglen - prelen;2412 imgoff += imglen;2413 preoff += prelen;2414}24152416/*2417 * Ok, the preimage matches with whitespace fuzz.2418 *2419 * imgoff now holds the true length of the target that2420 * matches the preimage before the end of the file.2421 *2422 * Count the number of characters in the preimage that fall2423 * beyond the end of the file and make sure that all of them2424 * are whitespace characters. (This can only happen if2425 * we are removing blank lines at the end of the file.)2426 */2427 buf = preimage_eof = preimage->buf + preoff;2428for( ; i < preimage->nr; i++)2429 preoff += preimage->line[i].len;2430 preimage_end = preimage->buf + preoff;2431for( ; buf < preimage_end; buf++)2432if(!isspace(*buf))2433return0;24342435/*2436 * Update the preimage and the common postimage context2437 * lines to use the same whitespace as the target.2438 * If whitespace is missing in the target (i.e.2439 * if the preimage extends beyond the end of the file),2440 * use the whitespace from the preimage.2441 */2442 extra_chars = preimage_end - preimage_eof;2443strbuf_init(&fixed, imgoff + extra_chars);2444strbuf_add(&fixed, img->buf +try, imgoff);2445strbuf_add(&fixed, preimage_eof, extra_chars);2446 fixed_buf =strbuf_detach(&fixed, &fixed_len);2447update_pre_post_images(preimage, postimage,2448 fixed_buf, fixed_len, postlen);2449return1;2450}24512452static intmatch_fragment(struct apply_state *state,2453struct image *img,2454struct image *preimage,2455struct image *postimage,2456unsigned longtry,2457int try_lno,2458unsigned ws_rule,2459int match_beginning,int match_end)2460{2461int i;2462char*fixed_buf, *buf, *orig, *target;2463struct strbuf fixed;2464size_t fixed_len, postlen;2465int preimage_limit;24662467if(preimage->nr + try_lno <= img->nr) {2468/*2469 * The hunk falls within the boundaries of img.2470 */2471 preimage_limit = preimage->nr;2472if(match_end && (preimage->nr + try_lno != img->nr))2473return0;2474}else if(state->ws_error_action == correct_ws_error &&2475(ws_rule & WS_BLANK_AT_EOF)) {2476/*2477 * This hunk extends beyond the end of img, and we are2478 * removing blank lines at the end of the file. This2479 * many lines from the beginning of the preimage must2480 * match with img, and the remainder of the preimage2481 * must be blank.2482 */2483 preimage_limit = img->nr - try_lno;2484}else{2485/*2486 * The hunk extends beyond the end of the img and2487 * we are not removing blanks at the end, so we2488 * should reject the hunk at this position.2489 */2490return0;2491}24922493if(match_beginning && try_lno)2494return0;24952496/* Quick hash check */2497for(i =0; i < preimage_limit; i++)2498if((img->line[try_lno + i].flag & LINE_PATCHED) ||2499(preimage->line[i].hash != img->line[try_lno + i].hash))2500return0;25012502if(preimage_limit == preimage->nr) {2503/*2504 * Do we have an exact match? If we were told to match2505 * at the end, size must be exactly at try+fragsize,2506 * otherwise try+fragsize must be still within the preimage,2507 * and either case, the old piece should match the preimage2508 * exactly.2509 */2510if((match_end2511? (try+ preimage->len == img->len)2512: (try+ preimage->len <= img->len)) &&2513!memcmp(img->buf +try, preimage->buf, preimage->len))2514return1;2515}else{2516/*2517 * The preimage extends beyond the end of img, so2518 * there cannot be an exact match.2519 *2520 * There must be one non-blank context line that match2521 * a line before the end of img.2522 */2523char*buf_end;25242525 buf = preimage->buf;2526 buf_end = buf;2527for(i =0; i < preimage_limit; i++)2528 buf_end += preimage->line[i].len;25292530for( ; buf < buf_end; buf++)2531if(!isspace(*buf))2532break;2533if(buf == buf_end)2534return0;2535}25362537/*2538 * No exact match. If we are ignoring whitespace, run a line-by-line2539 * fuzzy matching. We collect all the line length information because2540 * we need it to adjust whitespace if we match.2541 */2542if(state->ws_ignore_action == ignore_ws_change)2543returnline_by_line_fuzzy_match(img, preimage, postimage,2544try, try_lno, preimage_limit);25452546if(state->ws_error_action != correct_ws_error)2547return0;25482549/*2550 * The hunk does not apply byte-by-byte, but the hash says2551 * it might with whitespace fuzz. We weren't asked to2552 * ignore whitespace, we were asked to correct whitespace2553 * errors, so let's try matching after whitespace correction.2554 *2555 * While checking the preimage against the target, whitespace2556 * errors in both fixed, we count how large the corresponding2557 * postimage needs to be. The postimage prepared by2558 * apply_one_fragment() has whitespace errors fixed on added2559 * lines already, but the common lines were propagated as-is,2560 * which may become longer when their whitespace errors are2561 * fixed.2562 */25632564/* First count added lines in postimage */2565 postlen =0;2566for(i =0; i < postimage->nr; i++) {2567if(!(postimage->line[i].flag & LINE_COMMON))2568 postlen += postimage->line[i].len;2569}25702571/*2572 * The preimage may extend beyond the end of the file,2573 * but in this loop we will only handle the part of the2574 * preimage that falls within the file.2575 */2576strbuf_init(&fixed, preimage->len +1);2577 orig = preimage->buf;2578 target = img->buf +try;2579for(i =0; i < preimage_limit; i++) {2580size_t oldlen = preimage->line[i].len;2581size_t tgtlen = img->line[try_lno + i].len;2582size_t fixstart = fixed.len;2583struct strbuf tgtfix;2584int match;25852586/* Try fixing the line in the preimage */2587ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25882589/* Try fixing the line in the target */2590strbuf_init(&tgtfix, tgtlen);2591ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);25922593/*2594 * If they match, either the preimage was based on2595 * a version before our tree fixed whitespace breakage,2596 * or we are lacking a whitespace-fix patch the tree2597 * the preimage was based on already had (i.e. target2598 * has whitespace breakage, the preimage doesn't).2599 * In either case, we are fixing the whitespace breakages2600 * so we might as well take the fix together with their2601 * real change.2602 */2603 match = (tgtfix.len == fixed.len - fixstart &&2604!memcmp(tgtfix.buf, fixed.buf + fixstart,2605 fixed.len - fixstart));26062607/* Add the length if this is common with the postimage */2608if(preimage->line[i].flag & LINE_COMMON)2609 postlen += tgtfix.len;26102611strbuf_release(&tgtfix);2612if(!match)2613goto unmatch_exit;26142615 orig += oldlen;2616 target += tgtlen;2617}261826192620/*2621 * Now handle the lines in the preimage that falls beyond the2622 * end of the file (if any). They will only match if they are2623 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2624 * false).2625 */2626for( ; i < preimage->nr; i++) {2627size_t fixstart = fixed.len;/* start of the fixed preimage */2628size_t oldlen = preimage->line[i].len;2629int j;26302631/* Try fixing the line in the preimage */2632ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);26332634for(j = fixstart; j < fixed.len; j++)2635if(!isspace(fixed.buf[j]))2636goto unmatch_exit;26372638 orig += oldlen;2639}26402641/*2642 * Yes, the preimage is based on an older version that still2643 * has whitespace breakages unfixed, and fixing them makes the2644 * hunk match. Update the context lines in the postimage.2645 */2646 fixed_buf =strbuf_detach(&fixed, &fixed_len);2647if(postlen < postimage->len)2648 postlen =0;2649update_pre_post_images(preimage, postimage,2650 fixed_buf, fixed_len, postlen);2651return1;26522653 unmatch_exit:2654strbuf_release(&fixed);2655return0;2656}26572658static intfind_pos(struct apply_state *state,2659struct image *img,2660struct image *preimage,2661struct image *postimage,2662int line,2663unsigned ws_rule,2664int match_beginning,int match_end)2665{2666int i;2667unsigned long backwards, forwards,try;2668int backwards_lno, forwards_lno, try_lno;26692670/*2671 * If match_beginning or match_end is specified, there is no2672 * point starting from a wrong line that will never match and2673 * wander around and wait for a match at the specified end.2674 */2675if(match_beginning)2676 line =0;2677else if(match_end)2678 line = img->nr - preimage->nr;26792680/*2681 * Because the comparison is unsigned, the following test2682 * will also take care of a negative line number that can2683 * result when match_end and preimage is larger than the target.2684 */2685if((size_t) line > img->nr)2686 line = img->nr;26872688try=0;2689for(i =0; i < line; i++)2690try+= img->line[i].len;26912692/*2693 * There's probably some smart way to do this, but I'll leave2694 * that to the smart and beautiful people. I'm simple and stupid.2695 */2696 backwards =try;2697 backwards_lno = line;2698 forwards =try;2699 forwards_lno = line;2700 try_lno = line;27012702for(i =0; ; i++) {2703if(match_fragment(state, img, preimage, postimage,2704try, try_lno, ws_rule,2705 match_beginning, match_end))2706return try_lno;27072708 again:2709if(backwards_lno ==0&& forwards_lno == img->nr)2710break;27112712if(i &1) {2713if(backwards_lno ==0) {2714 i++;2715goto again;2716}2717 backwards_lno--;2718 backwards -= img->line[backwards_lno].len;2719try= backwards;2720 try_lno = backwards_lno;2721}else{2722if(forwards_lno == img->nr) {2723 i++;2724goto again;2725}2726 forwards += img->line[forwards_lno].len;2727 forwards_lno++;2728try= forwards;2729 try_lno = forwards_lno;2730}27312732}2733return-1;2734}27352736static voidremove_first_line(struct image *img)2737{2738 img->buf += img->line[0].len;2739 img->len -= img->line[0].len;2740 img->line++;2741 img->nr--;2742}27432744static voidremove_last_line(struct image *img)2745{2746 img->len -= img->line[--img->nr].len;2747}27482749/*2750 * The change from "preimage" and "postimage" has been found to2751 * apply at applied_pos (counts in line numbers) in "img".2752 * Update "img" to remove "preimage" and replace it with "postimage".2753 */2754static voidupdate_image(struct apply_state *state,2755struct image *img,2756int applied_pos,2757struct image *preimage,2758struct image *postimage)2759{2760/*2761 * remove the copy of preimage at offset in img2762 * and replace it with postimage2763 */2764int i, nr;2765size_t remove_count, insert_count, applied_at =0;2766char*result;2767int preimage_limit;27682769/*2770 * If we are removing blank lines at the end of img,2771 * the preimage may extend beyond the end.2772 * If that is the case, we must be careful only to2773 * remove the part of the preimage that falls within2774 * the boundaries of img. Initialize preimage_limit2775 * to the number of lines in the preimage that falls2776 * within the boundaries.2777 */2778 preimage_limit = preimage->nr;2779if(preimage_limit > img->nr - applied_pos)2780 preimage_limit = img->nr - applied_pos;27812782for(i =0; i < applied_pos; i++)2783 applied_at += img->line[i].len;27842785 remove_count =0;2786for(i =0; i < preimage_limit; i++)2787 remove_count += img->line[applied_pos + i].len;2788 insert_count = postimage->len;27892790/* Adjust the contents */2791 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2792memcpy(result, img->buf, applied_at);2793memcpy(result + applied_at, postimage->buf, postimage->len);2794memcpy(result + applied_at + postimage->len,2795 img->buf + (applied_at + remove_count),2796 img->len - (applied_at + remove_count));2797free(img->buf);2798 img->buf = result;2799 img->len += insert_count - remove_count;2800 result[img->len] ='\0';28012802/* Adjust the line table */2803 nr = img->nr + postimage->nr - preimage_limit;2804if(preimage_limit < postimage->nr) {2805/*2806 * NOTE: this knows that we never call remove_first_line()2807 * on anything other than pre/post image.2808 */2809REALLOC_ARRAY(img->line, nr);2810 img->line_allocated = img->line;2811}2812if(preimage_limit != postimage->nr)2813MOVE_ARRAY(img->line + applied_pos + postimage->nr,2814 img->line + applied_pos + preimage_limit,2815 img->nr - (applied_pos + preimage_limit));2816COPY_ARRAY(img->line + applied_pos, postimage->line, postimage->nr);2817if(!state->allow_overlap)2818for(i =0; i < postimage->nr; i++)2819 img->line[applied_pos + i].flag |= LINE_PATCHED;2820 img->nr = nr;2821}28222823/*2824 * Use the patch-hunk text in "frag" to prepare two images (preimage and2825 * postimage) for the hunk. Find lines that match "preimage" in "img" and2826 * replace the part of "img" with "postimage" text.2827 */2828static intapply_one_fragment(struct apply_state *state,2829struct image *img,struct fragment *frag,2830int inaccurate_eof,unsigned ws_rule,2831int nth_fragment)2832{2833int match_beginning, match_end;2834const char*patch = frag->patch;2835int size = frag->size;2836char*old, *oldlines;2837struct strbuf newlines;2838int new_blank_lines_at_end =0;2839int found_new_blank_lines_at_end =0;2840int hunk_linenr = frag->linenr;2841unsigned long leading, trailing;2842int pos, applied_pos;2843struct image preimage;2844struct image postimage;28452846memset(&preimage,0,sizeof(preimage));2847memset(&postimage,0,sizeof(postimage));2848 oldlines =xmalloc(size);2849strbuf_init(&newlines, size);28502851 old = oldlines;2852while(size >0) {2853char first;2854int len =linelen(patch, size);2855int plen;2856int added_blank_line =0;2857int is_blank_context =0;2858size_t start;28592860if(!len)2861break;28622863/*2864 * "plen" is how much of the line we should use for2865 * the actual patch data. Normally we just remove the2866 * first character on the line, but if the line is2867 * followed by "\ No newline", then we also remove the2868 * last one (which is the newline, of course).2869 */2870 plen = len -1;2871if(len < size && patch[len] =='\\')2872 plen--;2873 first = *patch;2874if(state->apply_in_reverse) {2875if(first =='-')2876 first ='+';2877else if(first =='+')2878 first ='-';2879}28802881switch(first) {2882case'\n':2883/* Newer GNU diff, empty context line */2884if(plen <0)2885/* ... followed by '\No newline'; nothing */2886break;2887*old++ ='\n';2888strbuf_addch(&newlines,'\n');2889add_line_info(&preimage,"\n",1, LINE_COMMON);2890add_line_info(&postimage,"\n",1, LINE_COMMON);2891 is_blank_context =1;2892break;2893case' ':2894if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2895ws_blank_line(patch +1, plen, ws_rule))2896 is_blank_context =1;2897case'-':2898memcpy(old, patch +1, plen);2899add_line_info(&preimage, old, plen,2900(first ==' '? LINE_COMMON :0));2901 old += plen;2902if(first =='-')2903break;2904/* Fall-through for ' ' */2905case'+':2906/* --no-add does not add new lines */2907if(first =='+'&& state->no_add)2908break;29092910 start = newlines.len;2911if(first !='+'||2912!state->whitespace_error ||2913 state->ws_error_action != correct_ws_error) {2914strbuf_add(&newlines, patch +1, plen);2915}2916else{2917ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2918}2919add_line_info(&postimage, newlines.buf + start, newlines.len - start,2920(first =='+'?0: LINE_COMMON));2921if(first =='+'&&2922(ws_rule & WS_BLANK_AT_EOF) &&2923ws_blank_line(patch +1, plen, ws_rule))2924 added_blank_line =1;2925break;2926case'@':case'\\':2927/* Ignore it, we already handled it */2928break;2929default:2930if(state->apply_verbosity > verbosity_normal)2931error(_("invalid start of line: '%c'"), first);2932 applied_pos = -1;2933goto out;2934}2935if(added_blank_line) {2936if(!new_blank_lines_at_end)2937 found_new_blank_lines_at_end = hunk_linenr;2938 new_blank_lines_at_end++;2939}2940else if(is_blank_context)2941;2942else2943 new_blank_lines_at_end =0;2944 patch += len;2945 size -= len;2946 hunk_linenr++;2947}2948if(inaccurate_eof &&2949 old > oldlines && old[-1] =='\n'&&2950 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2951 old--;2952strbuf_setlen(&newlines, newlines.len -1);2953}29542955 leading = frag->leading;2956 trailing = frag->trailing;29572958/*2959 * A hunk to change lines at the beginning would begin with2960 * @@ -1,L +N,M @@2961 * but we need to be careful. -U0 that inserts before the second2962 * line also has this pattern.2963 *2964 * And a hunk to add to an empty file would begin with2965 * @@ -0,0 +N,M @@2966 *2967 * In other words, a hunk that is (frag->oldpos <= 1) with or2968 * without leading context must match at the beginning.2969 */2970 match_beginning = (!frag->oldpos ||2971(frag->oldpos ==1&& !state->unidiff_zero));29722973/*2974 * A hunk without trailing lines must match at the end.2975 * However, we simply cannot tell if a hunk must match end2976 * from the lack of trailing lines if the patch was generated2977 * with unidiff without any context.2978 */2979 match_end = !state->unidiff_zero && !trailing;29802981 pos = frag->newpos ? (frag->newpos -1) :0;2982 preimage.buf = oldlines;2983 preimage.len = old - oldlines;2984 postimage.buf = newlines.buf;2985 postimage.len = newlines.len;2986 preimage.line = preimage.line_allocated;2987 postimage.line = postimage.line_allocated;29882989for(;;) {29902991 applied_pos =find_pos(state, img, &preimage, &postimage, pos,2992 ws_rule, match_beginning, match_end);29932994if(applied_pos >=0)2995break;29962997/* Am I at my context limits? */2998if((leading <= state->p_context) && (trailing <= state->p_context))2999break;3000if(match_beginning || match_end) {3001 match_beginning = match_end =0;3002continue;3003}30043005/*3006 * Reduce the number of context lines; reduce both3007 * leading and trailing if they are equal otherwise3008 * just reduce the larger context.3009 */3010if(leading >= trailing) {3011remove_first_line(&preimage);3012remove_first_line(&postimage);3013 pos--;3014 leading--;3015}3016if(trailing > leading) {3017remove_last_line(&preimage);3018remove_last_line(&postimage);3019 trailing--;3020}3021}30223023if(applied_pos >=0) {3024if(new_blank_lines_at_end &&3025 preimage.nr + applied_pos >= img->nr &&3026(ws_rule & WS_BLANK_AT_EOF) &&3027 state->ws_error_action != nowarn_ws_error) {3028record_ws_error(state, WS_BLANK_AT_EOF,"+",1,3029 found_new_blank_lines_at_end);3030if(state->ws_error_action == correct_ws_error) {3031while(new_blank_lines_at_end--)3032remove_last_line(&postimage);3033}3034/*3035 * We would want to prevent write_out_results()3036 * from taking place in apply_patch() that follows3037 * the callchain led us here, which is:3038 * apply_patch->check_patch_list->check_patch->3039 * apply_data->apply_fragments->apply_one_fragment3040 */3041if(state->ws_error_action == die_on_ws_error)3042 state->apply =0;3043}30443045if(state->apply_verbosity > verbosity_normal && applied_pos != pos) {3046int offset = applied_pos - pos;3047if(state->apply_in_reverse)3048 offset =0- offset;3049fprintf_ln(stderr,3050Q_("Hunk #%dsucceeded at%d(offset%dline).",3051"Hunk #%dsucceeded at%d(offset%dlines).",3052 offset),3053 nth_fragment, applied_pos +1, offset);3054}30553056/*3057 * Warn if it was necessary to reduce the number3058 * of context lines.3059 */3060if((leading != frag->leading ||3061 trailing != frag->trailing) && state->apply_verbosity > verbosity_silent)3062fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"3063" to apply fragment at%d"),3064 leading, trailing, applied_pos+1);3065update_image(state, img, applied_pos, &preimage, &postimage);3066}else{3067if(state->apply_verbosity > verbosity_normal)3068error(_("while searching for:\n%.*s"),3069(int)(old - oldlines), oldlines);3070}30713072out:3073free(oldlines);3074strbuf_release(&newlines);3075free(preimage.line_allocated);3076free(postimage.line_allocated);30773078return(applied_pos <0);3079}30803081static intapply_binary_fragment(struct apply_state *state,3082struct image *img,3083struct patch *patch)3084{3085struct fragment *fragment = patch->fragments;3086unsigned long len;3087void*dst;30883089if(!fragment)3090returnerror(_("missing binary patch data for '%s'"),3091 patch->new_name ?3092 patch->new_name :3093 patch->old_name);30943095/* Binary patch is irreversible without the optional second hunk */3096if(state->apply_in_reverse) {3097if(!fragment->next)3098returnerror(_("cannot reverse-apply a binary patch "3099"without the reverse hunk to '%s'"),3100 patch->new_name3101? patch->new_name : patch->old_name);3102 fragment = fragment->next;3103}3104switch(fragment->binary_patch_method) {3105case BINARY_DELTA_DEFLATED:3106 dst =patch_delta(img->buf, img->len, fragment->patch,3107 fragment->size, &len);3108if(!dst)3109return-1;3110clear_image(img);3111 img->buf = dst;3112 img->len = len;3113return0;3114case BINARY_LITERAL_DEFLATED:3115clear_image(img);3116 img->len = fragment->size;3117 img->buf =xmemdupz(fragment->patch, img->len);3118return0;3119}3120return-1;3121}31223123/*3124 * Replace "img" with the result of applying the binary patch.3125 * The binary patch data itself in patch->fragment is still kept3126 * but the preimage prepared by the caller in "img" is freed here3127 * or in the helper function apply_binary_fragment() this calls.3128 */3129static intapply_binary(struct apply_state *state,3130struct image *img,3131struct patch *patch)3132{3133const char*name = patch->old_name ? patch->old_name : patch->new_name;3134struct object_id oid;31353136/*3137 * For safety, we require patch index line to contain3138 * full 40-byte textual SHA1 for old and new, at least for now.3139 */3140if(strlen(patch->old_sha1_prefix) !=40||3141strlen(patch->new_sha1_prefix) !=40||3142get_oid_hex(patch->old_sha1_prefix, &oid) ||3143get_oid_hex(patch->new_sha1_prefix, &oid))3144returnerror(_("cannot apply binary patch to '%s' "3145"without full index line"), name);31463147if(patch->old_name) {3148/*3149 * See if the old one matches what the patch3150 * applies to.3151 */3152hash_sha1_file(img->buf, img->len, blob_type, oid.hash);3153if(strcmp(oid_to_hex(&oid), patch->old_sha1_prefix))3154returnerror(_("the patch applies to '%s' (%s), "3155"which does not match the "3156"current contents."),3157 name,oid_to_hex(&oid));3158}3159else{3160/* Otherwise, the old one must be empty. */3161if(img->len)3162returnerror(_("the patch applies to an empty "3163"'%s' but it is not empty"), name);3164}31653166get_oid_hex(patch->new_sha1_prefix, &oid);3167if(is_null_oid(&oid)) {3168clear_image(img);3169return0;/* deletion patch */3170}31713172if(has_sha1_file(oid.hash)) {3173/* We already have the postimage */3174enum object_type type;3175unsigned long size;3176char*result;31773178 result =read_sha1_file(oid.hash, &type, &size);3179if(!result)3180returnerror(_("the necessary postimage%sfor "3181"'%s' cannot be read"),3182 patch->new_sha1_prefix, name);3183clear_image(img);3184 img->buf = result;3185 img->len = size;3186}else{3187/*3188 * We have verified buf matches the preimage;3189 * apply the patch data to it, which is stored3190 * in the patch->fragments->{patch,size}.3191 */3192if(apply_binary_fragment(state, img, patch))3193returnerror(_("binary patch does not apply to '%s'"),3194 name);31953196/* verify that the result matches */3197hash_sha1_file(img->buf, img->len, blob_type, oid.hash);3198if(strcmp(oid_to_hex(&oid), patch->new_sha1_prefix))3199returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3200 name, patch->new_sha1_prefix,oid_to_hex(&oid));3201}32023203return0;3204}32053206static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3207{3208struct fragment *frag = patch->fragments;3209const char*name = patch->old_name ? patch->old_name : patch->new_name;3210unsigned ws_rule = patch->ws_rule;3211unsigned inaccurate_eof = patch->inaccurate_eof;3212int nth =0;32133214if(patch->is_binary)3215returnapply_binary(state, img, patch);32163217while(frag) {3218 nth++;3219if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3220error(_("patch failed:%s:%ld"), name, frag->oldpos);3221if(!state->apply_with_reject)3222return-1;3223 frag->rejected =1;3224}3225 frag = frag->next;3226}3227return0;3228}32293230static intread_blob_object(struct strbuf *buf,const struct object_id *oid,unsigned mode)3231{3232if(S_ISGITLINK(mode)) {3233strbuf_grow(buf,100);3234strbuf_addf(buf,"Subproject commit%s\n",oid_to_hex(oid));3235}else{3236enum object_type type;3237unsigned long sz;3238char*result;32393240 result =read_sha1_file(oid->hash, &type, &sz);3241if(!result)3242return-1;3243/* XXX read_sha1_file NUL-terminates */3244strbuf_attach(buf, result, sz, sz +1);3245}3246return0;3247}32483249static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3250{3251if(!ce)3252return0;3253returnread_blob_object(buf, &ce->oid, ce->ce_mode);3254}32553256static struct patch *in_fn_table(struct apply_state *state,const char*name)3257{3258struct string_list_item *item;32593260if(name == NULL)3261return NULL;32623263 item =string_list_lookup(&state->fn_table, name);3264if(item != NULL)3265return(struct patch *)item->util;32663267return NULL;3268}32693270/*3271 * item->util in the filename table records the status of the path.3272 * Usually it points at a patch (whose result records the contents3273 * of it after applying it), but it could be PATH_WAS_DELETED for a3274 * path that a previously applied patch has already removed, or3275 * PATH_TO_BE_DELETED for a path that a later patch would remove.3276 *3277 * The latter is needed to deal with a case where two paths A and B3278 * are swapped by first renaming A to B and then renaming B to A;3279 * moving A to B should not be prevented due to presence of B as we3280 * will remove it in a later patch.3281 */3282#define PATH_TO_BE_DELETED ((struct patch *) -2)3283#define PATH_WAS_DELETED ((struct patch *) -1)32843285static intto_be_deleted(struct patch *patch)3286{3287return patch == PATH_TO_BE_DELETED;3288}32893290static intwas_deleted(struct patch *patch)3291{3292return patch == PATH_WAS_DELETED;3293}32943295static voidadd_to_fn_table(struct apply_state *state,struct patch *patch)3296{3297struct string_list_item *item;32983299/*3300 * Always add new_name unless patch is a deletion3301 * This should cover the cases for normal diffs,3302 * file creations and copies3303 */3304if(patch->new_name != NULL) {3305 item =string_list_insert(&state->fn_table, patch->new_name);3306 item->util = patch;3307}33083309/*3310 * store a failure on rename/deletion cases because3311 * later chunks shouldn't patch old names3312 */3313if((patch->new_name == NULL) || (patch->is_rename)) {3314 item =string_list_insert(&state->fn_table, patch->old_name);3315 item->util = PATH_WAS_DELETED;3316}3317}33183319static voidprepare_fn_table(struct apply_state *state,struct patch *patch)3320{3321/*3322 * store information about incoming file deletion3323 */3324while(patch) {3325if((patch->new_name == NULL) || (patch->is_rename)) {3326struct string_list_item *item;3327 item =string_list_insert(&state->fn_table, patch->old_name);3328 item->util = PATH_TO_BE_DELETED;3329}3330 patch = patch->next;3331}3332}33333334static intcheckout_target(struct index_state *istate,3335struct cache_entry *ce,struct stat *st)3336{3337struct checkout costate = CHECKOUT_INIT;33383339 costate.refresh_cache =1;3340 costate.istate = istate;3341if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3342returnerror(_("cannot checkout%s"), ce->name);3343return0;3344}33453346static struct patch *previous_patch(struct apply_state *state,3347struct patch *patch,3348int*gone)3349{3350struct patch *previous;33513352*gone =0;3353if(patch->is_copy || patch->is_rename)3354return NULL;/* "git" patches do not depend on the order */33553356 previous =in_fn_table(state, patch->old_name);3357if(!previous)3358return NULL;33593360if(to_be_deleted(previous))3361return NULL;/* the deletion hasn't happened yet */33623363if(was_deleted(previous))3364*gone =1;33653366return previous;3367}33683369static intverify_index_match(const struct cache_entry *ce,struct stat *st)3370{3371if(S_ISGITLINK(ce->ce_mode)) {3372if(!S_ISDIR(st->st_mode))3373return-1;3374return0;3375}3376returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3377}33783379#define SUBMODULE_PATCH_WITHOUT_INDEX 133803381static intload_patch_target(struct apply_state *state,3382struct strbuf *buf,3383const struct cache_entry *ce,3384struct stat *st,3385const char*name,3386unsigned expected_mode)3387{3388if(state->cached || state->check_index) {3389if(read_file_or_gitlink(ce, buf))3390returnerror(_("failed to read%s"), name);3391}else if(name) {3392if(S_ISGITLINK(expected_mode)) {3393if(ce)3394returnread_file_or_gitlink(ce, buf);3395else3396return SUBMODULE_PATCH_WITHOUT_INDEX;3397}else if(has_symlink_leading_path(name,strlen(name))) {3398returnerror(_("reading from '%s' beyond a symbolic link"), name);3399}else{3400if(read_old_data(st, name, buf))3401returnerror(_("failed to read%s"), name);3402}3403}3404return0;3405}34063407/*3408 * We are about to apply "patch"; populate the "image" with the3409 * current version we have, from the working tree or from the index,3410 * depending on the situation e.g. --cached/--index. If we are3411 * applying a non-git patch that incrementally updates the tree,3412 * we read from the result of a previous diff.3413 */3414static intload_preimage(struct apply_state *state,3415struct image *image,3416struct patch *patch,struct stat *st,3417const struct cache_entry *ce)3418{3419struct strbuf buf = STRBUF_INIT;3420size_t len;3421char*img;3422struct patch *previous;3423int status;34243425 previous =previous_patch(state, patch, &status);3426if(status)3427returnerror(_("path%shas been renamed/deleted"),3428 patch->old_name);3429if(previous) {3430/* We have a patched copy in memory; use that. */3431strbuf_add(&buf, previous->result, previous->resultsize);3432}else{3433 status =load_patch_target(state, &buf, ce, st,3434 patch->old_name, patch->old_mode);3435if(status <0)3436return status;3437else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3438/*3439 * There is no way to apply subproject3440 * patch without looking at the index.3441 * NEEDSWORK: shouldn't this be flagged3442 * as an error???3443 */3444free_fragment_list(patch->fragments);3445 patch->fragments = NULL;3446}else if(status) {3447returnerror(_("failed to read%s"), patch->old_name);3448}3449}34503451 img =strbuf_detach(&buf, &len);3452prepare_image(image, img, len, !patch->is_binary);3453return0;3454}34553456static intthree_way_merge(struct image *image,3457char*path,3458const struct object_id *base,3459const struct object_id *ours,3460const struct object_id *theirs)3461{3462 mmfile_t base_file, our_file, their_file;3463 mmbuffer_t result = { NULL };3464int status;34653466read_mmblob(&base_file, base);3467read_mmblob(&our_file, ours);3468read_mmblob(&their_file, theirs);3469 status =ll_merge(&result, path,3470&base_file,"base",3471&our_file,"ours",3472&their_file,"theirs", NULL);3473free(base_file.ptr);3474free(our_file.ptr);3475free(their_file.ptr);3476if(status <0|| !result.ptr) {3477free(result.ptr);3478return-1;3479}3480clear_image(image);3481 image->buf = result.ptr;3482 image->len = result.size;34833484return status;3485}34863487/*3488 * When directly falling back to add/add three-way merge, we read from3489 * the current contents of the new_name. In no cases other than that3490 * this function will be called.3491 */3492static intload_current(struct apply_state *state,3493struct image *image,3494struct patch *patch)3495{3496struct strbuf buf = STRBUF_INIT;3497int status, pos;3498size_t len;3499char*img;3500struct stat st;3501struct cache_entry *ce;3502char*name = patch->new_name;3503unsigned mode = patch->new_mode;35043505if(!patch->is_new)3506die("BUG: patch to%sis not a creation", patch->old_name);35073508 pos =cache_name_pos(name,strlen(name));3509if(pos <0)3510returnerror(_("%s: does not exist in index"), name);3511 ce = active_cache[pos];3512if(lstat(name, &st)) {3513if(errno != ENOENT)3514returnerror_errno("%s", name);3515if(checkout_target(&the_index, ce, &st))3516return-1;3517}3518if(verify_index_match(ce, &st))3519returnerror(_("%s: does not match index"), name);35203521 status =load_patch_target(state, &buf, ce, &st, name, mode);3522if(status <0)3523return status;3524else if(status)3525return-1;3526 img =strbuf_detach(&buf, &len);3527prepare_image(image, img, len, !patch->is_binary);3528return0;3529}35303531static inttry_threeway(struct apply_state *state,3532struct image *image,3533struct patch *patch,3534struct stat *st,3535const struct cache_entry *ce)3536{3537struct object_id pre_oid, post_oid, our_oid;3538struct strbuf buf = STRBUF_INIT;3539size_t len;3540int status;3541char*img;3542struct image tmp_image;35433544/* No point falling back to 3-way merge in these cases */3545if(patch->is_delete ||3546S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3547return-1;35483549/* Preimage the patch was prepared for */3550if(patch->is_new)3551write_sha1_file("",0, blob_type, pre_oid.hash);3552else if(get_sha1(patch->old_sha1_prefix, pre_oid.hash) ||3553read_blob_object(&buf, &pre_oid, patch->old_mode))3554returnerror(_("repository lacks the necessary blob to fall back on 3-way merge."));35553556if(state->apply_verbosity > verbosity_silent)3557fprintf(stderr,_("Falling back to three-way merge...\n"));35583559 img =strbuf_detach(&buf, &len);3560prepare_image(&tmp_image, img, len,1);3561/* Apply the patch to get the post image */3562if(apply_fragments(state, &tmp_image, patch) <0) {3563clear_image(&tmp_image);3564return-1;3565}3566/* post_oid is theirs */3567write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_oid.hash);3568clear_image(&tmp_image);35693570/* our_oid is ours */3571if(patch->is_new) {3572if(load_current(state, &tmp_image, patch))3573returnerror(_("cannot read the current contents of '%s'"),3574 patch->new_name);3575}else{3576if(load_preimage(state, &tmp_image, patch, st, ce))3577returnerror(_("cannot read the current contents of '%s'"),3578 patch->old_name);3579}3580write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_oid.hash);3581clear_image(&tmp_image);35823583/* in-core three-way merge between post and our using pre as base */3584 status =three_way_merge(image, patch->new_name,3585&pre_oid, &our_oid, &post_oid);3586if(status <0) {3587if(state->apply_verbosity > verbosity_silent)3588fprintf(stderr,3589_("Failed to fall back on three-way merge...\n"));3590return status;3591}35923593if(status) {3594 patch->conflicted_threeway =1;3595if(patch->is_new)3596oidclr(&patch->threeway_stage[0]);3597else3598oidcpy(&patch->threeway_stage[0], &pre_oid);3599oidcpy(&patch->threeway_stage[1], &our_oid);3600oidcpy(&patch->threeway_stage[2], &post_oid);3601if(state->apply_verbosity > verbosity_silent)3602fprintf(stderr,3603_("Applied patch to '%s' with conflicts.\n"),3604 patch->new_name);3605}else{3606if(state->apply_verbosity > verbosity_silent)3607fprintf(stderr,3608_("Applied patch to '%s' cleanly.\n"),3609 patch->new_name);3610}3611return0;3612}36133614static intapply_data(struct apply_state *state,struct patch *patch,3615struct stat *st,const struct cache_entry *ce)3616{3617struct image image;36183619if(load_preimage(state, &image, patch, st, ce) <0)3620return-1;36213622if(patch->direct_to_threeway ||3623apply_fragments(state, &image, patch) <0) {3624/* Note: with --reject, apply_fragments() returns 0 */3625if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3626return-1;3627}3628 patch->result = image.buf;3629 patch->resultsize = image.len;3630add_to_fn_table(state, patch);3631free(image.line_allocated);36323633if(0< patch->is_delete && patch->resultsize)3634returnerror(_("removal patch leaves file contents"));36353636return0;3637}36383639/*3640 * If "patch" that we are looking at modifies or deletes what we have,3641 * we would want it not to lose any local modification we have, either3642 * in the working tree or in the index.3643 *3644 * This also decides if a non-git patch is a creation patch or a3645 * modification to an existing empty file. We do not check the state3646 * of the current tree for a creation patch in this function; the caller3647 * check_patch() separately makes sure (and errors out otherwise) that3648 * the path the patch creates does not exist in the current tree.3649 */3650static intcheck_preimage(struct apply_state *state,3651struct patch *patch,3652struct cache_entry **ce,3653struct stat *st)3654{3655const char*old_name = patch->old_name;3656struct patch *previous = NULL;3657int stat_ret =0, status;3658unsigned st_mode =0;36593660if(!old_name)3661return0;36623663assert(patch->is_new <=0);3664 previous =previous_patch(state, patch, &status);36653666if(status)3667returnerror(_("path%shas been renamed/deleted"), old_name);3668if(previous) {3669 st_mode = previous->new_mode;3670}else if(!state->cached) {3671 stat_ret =lstat(old_name, st);3672if(stat_ret && errno != ENOENT)3673returnerror_errno("%s", old_name);3674}36753676if(state->check_index && !previous) {3677int pos =cache_name_pos(old_name,strlen(old_name));3678if(pos <0) {3679if(patch->is_new <0)3680goto is_new;3681returnerror(_("%s: does not exist in index"), old_name);3682}3683*ce = active_cache[pos];3684if(stat_ret <0) {3685if(checkout_target(&the_index, *ce, st))3686return-1;3687}3688if(!state->cached &&verify_index_match(*ce, st))3689returnerror(_("%s: does not match index"), old_name);3690if(state->cached)3691 st_mode = (*ce)->ce_mode;3692}else if(stat_ret <0) {3693if(patch->is_new <0)3694goto is_new;3695returnerror_errno("%s", old_name);3696}36973698if(!state->cached && !previous)3699 st_mode =ce_mode_from_stat(*ce, st->st_mode);37003701if(patch->is_new <0)3702 patch->is_new =0;3703if(!patch->old_mode)3704 patch->old_mode = st_mode;3705if((st_mode ^ patch->old_mode) & S_IFMT)3706returnerror(_("%s: wrong type"), old_name);3707if(st_mode != patch->old_mode)3708warning(_("%shas type%o, expected%o"),3709 old_name, st_mode, patch->old_mode);3710if(!patch->new_mode && !patch->is_delete)3711 patch->new_mode = st_mode;3712return0;37133714 is_new:3715 patch->is_new =1;3716 patch->is_delete =0;3717FREE_AND_NULL(patch->old_name);3718return0;3719}372037213722#define EXISTS_IN_INDEX 13723#define EXISTS_IN_WORKTREE 237243725static intcheck_to_create(struct apply_state *state,3726const char*new_name,3727int ok_if_exists)3728{3729struct stat nst;37303731if(state->check_index &&3732cache_name_pos(new_name,strlen(new_name)) >=0&&3733!ok_if_exists)3734return EXISTS_IN_INDEX;3735if(state->cached)3736return0;37373738if(!lstat(new_name, &nst)) {3739if(S_ISDIR(nst.st_mode) || ok_if_exists)3740return0;3741/*3742 * A leading component of new_name might be a symlink3743 * that is going to be removed with this patch, but3744 * still pointing at somewhere that has the path.3745 * In such a case, path "new_name" does not exist as3746 * far as git is concerned.3747 */3748if(has_symlink_leading_path(new_name,strlen(new_name)))3749return0;37503751return EXISTS_IN_WORKTREE;3752}else if(!is_missing_file_error(errno)) {3753returnerror_errno("%s", new_name);3754}3755return0;3756}37573758static uintptr_tregister_symlink_changes(struct apply_state *state,3759const char*path,3760uintptr_t what)3761{3762struct string_list_item *ent;37633764 ent =string_list_lookup(&state->symlink_changes, path);3765if(!ent) {3766 ent =string_list_insert(&state->symlink_changes, path);3767 ent->util = (void*)0;3768}3769 ent->util = (void*)(what | ((uintptr_t)ent->util));3770return(uintptr_t)ent->util;3771}37723773static uintptr_tcheck_symlink_changes(struct apply_state *state,const char*path)3774{3775struct string_list_item *ent;37763777 ent =string_list_lookup(&state->symlink_changes, path);3778if(!ent)3779return0;3780return(uintptr_t)ent->util;3781}37823783static voidprepare_symlink_changes(struct apply_state *state,struct patch *patch)3784{3785for( ; patch; patch = patch->next) {3786if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3787(patch->is_rename || patch->is_delete))3788/* the symlink at patch->old_name is removed */3789register_symlink_changes(state, patch->old_name, APPLY_SYMLINK_GOES_AWAY);37903791if(patch->new_name &&S_ISLNK(patch->new_mode))3792/* the symlink at patch->new_name is created or remains */3793register_symlink_changes(state, patch->new_name, APPLY_SYMLINK_IN_RESULT);3794}3795}37963797static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3798{3799do{3800unsigned int change;38013802while(--name->len && name->buf[name->len] !='/')3803;/* scan backwards */3804if(!name->len)3805break;3806 name->buf[name->len] ='\0';3807 change =check_symlink_changes(state, name->buf);3808if(change & APPLY_SYMLINK_IN_RESULT)3809return1;3810if(change & APPLY_SYMLINK_GOES_AWAY)3811/*3812 * This cannot be "return 0", because we may3813 * see a new one created at a higher level.3814 */3815continue;38163817/* otherwise, check the preimage */3818if(state->check_index) {3819struct cache_entry *ce;38203821 ce =cache_file_exists(name->buf, name->len, ignore_case);3822if(ce &&S_ISLNK(ce->ce_mode))3823return1;3824}else{3825struct stat st;3826if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3827return1;3828}3829}while(1);3830return0;3831}38323833static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3834{3835int ret;3836struct strbuf name = STRBUF_INIT;38373838assert(*name_ !='\0');3839strbuf_addstr(&name, name_);3840 ret =path_is_beyond_symlink_1(state, &name);3841strbuf_release(&name);38423843return ret;3844}38453846static intcheck_unsafe_path(struct patch *patch)3847{3848const char*old_name = NULL;3849const char*new_name = NULL;3850if(patch->is_delete)3851 old_name = patch->old_name;3852else if(!patch->is_new && !patch->is_copy)3853 old_name = patch->old_name;3854if(!patch->is_delete)3855 new_name = patch->new_name;38563857if(old_name && !verify_path(old_name))3858returnerror(_("invalid path '%s'"), old_name);3859if(new_name && !verify_path(new_name))3860returnerror(_("invalid path '%s'"), new_name);3861return0;3862}38633864/*3865 * Check and apply the patch in-core; leave the result in patch->result3866 * for the caller to write it out to the final destination.3867 */3868static intcheck_patch(struct apply_state *state,struct patch *patch)3869{3870struct stat st;3871const char*old_name = patch->old_name;3872const char*new_name = patch->new_name;3873const char*name = old_name ? old_name : new_name;3874struct cache_entry *ce = NULL;3875struct patch *tpatch;3876int ok_if_exists;3877int status;38783879 patch->rejected =1;/* we will drop this after we succeed */38803881 status =check_preimage(state, patch, &ce, &st);3882if(status)3883return status;3884 old_name = patch->old_name;38853886/*3887 * A type-change diff is always split into a patch to delete3888 * old, immediately followed by a patch to create new (see3889 * diff.c::run_diff()); in such a case it is Ok that the entry3890 * to be deleted by the previous patch is still in the working3891 * tree and in the index.3892 *3893 * A patch to swap-rename between A and B would first rename A3894 * to B and then rename B to A. While applying the first one,3895 * the presence of B should not stop A from getting renamed to3896 * B; ask to_be_deleted() about the later rename. Removal of3897 * B and rename from A to B is handled the same way by asking3898 * was_deleted().3899 */3900if((tpatch =in_fn_table(state, new_name)) &&3901(was_deleted(tpatch) ||to_be_deleted(tpatch)))3902 ok_if_exists =1;3903else3904 ok_if_exists =0;39053906if(new_name &&3907((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3908int err =check_to_create(state, new_name, ok_if_exists);39093910if(err && state->threeway) {3911 patch->direct_to_threeway =1;3912}else switch(err) {3913case0:3914break;/* happy */3915case EXISTS_IN_INDEX:3916returnerror(_("%s: already exists in index"), new_name);3917break;3918case EXISTS_IN_WORKTREE:3919returnerror(_("%s: already exists in working directory"),3920 new_name);3921default:3922return err;3923}39243925if(!patch->new_mode) {3926if(0< patch->is_new)3927 patch->new_mode = S_IFREG |0644;3928else3929 patch->new_mode = patch->old_mode;3930}3931}39323933if(new_name && old_name) {3934int same = !strcmp(old_name, new_name);3935if(!patch->new_mode)3936 patch->new_mode = patch->old_mode;3937if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3938if(same)3939returnerror(_("new mode (%o) of%sdoes not "3940"match old mode (%o)"),3941 patch->new_mode, new_name,3942 patch->old_mode);3943else3944returnerror(_("new mode (%o) of%sdoes not "3945"match old mode (%o) of%s"),3946 patch->new_mode, new_name,3947 patch->old_mode, old_name);3948}3949}39503951if(!state->unsafe_paths &&check_unsafe_path(patch))3952return-128;39533954/*3955 * An attempt to read from or delete a path that is beyond a3956 * symbolic link will be prevented by load_patch_target() that3957 * is called at the beginning of apply_data() so we do not3958 * have to worry about a patch marked with "is_delete" bit3959 * here. We however need to make sure that the patch result3960 * is not deposited to a path that is beyond a symbolic link3961 * here.3962 */3963if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3964returnerror(_("affected file '%s' is beyond a symbolic link"),3965 patch->new_name);39663967if(apply_data(state, patch, &st, ce) <0)3968returnerror(_("%s: patch does not apply"), name);3969 patch->rejected =0;3970return0;3971}39723973static intcheck_patch_list(struct apply_state *state,struct patch *patch)3974{3975int err =0;39763977prepare_symlink_changes(state, patch);3978prepare_fn_table(state, patch);3979while(patch) {3980int res;3981if(state->apply_verbosity > verbosity_normal)3982say_patch_name(stderr,3983_("Checking patch%s..."), patch);3984 res =check_patch(state, patch);3985if(res == -128)3986return-128;3987 err |= res;3988 patch = patch->next;3989}3990return err;3991}39923993static intread_apply_cache(struct apply_state *state)3994{3995if(state->index_file)3996returnread_cache_from(state->index_file);3997else3998returnread_cache();3999}40004001/* This function tries to read the object name from the current index */4002static intget_current_oid(struct apply_state *state,const char*path,4003struct object_id *oid)4004{4005int pos;40064007if(read_apply_cache(state) <0)4008return-1;4009 pos =cache_name_pos(path,strlen(path));4010if(pos <0)4011return-1;4012oidcpy(oid, &active_cache[pos]->oid);4013return0;4014}40154016static intpreimage_oid_in_gitlink_patch(struct patch *p,struct object_id *oid)4017{4018/*4019 * A usable gitlink patch has only one fragment (hunk) that looks like:4020 * @@ -1 +1 @@4021 * -Subproject commit <old sha1>4022 * +Subproject commit <new sha1>4023 * or4024 * @@ -1 +0,0 @@4025 * -Subproject commit <old sha1>4026 * for a removal patch.4027 */4028struct fragment *hunk = p->fragments;4029static const char heading[] ="-Subproject commit ";4030char*preimage;40314032if(/* does the patch have only one hunk? */4033 hunk && !hunk->next &&4034/* is its preimage one line? */4035 hunk->oldpos ==1&& hunk->oldlines ==1&&4036/* does preimage begin with the heading? */4037(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&4038starts_with(++preimage, heading) &&4039/* does it record full SHA-1? */4040!get_oid_hex(preimage +sizeof(heading) -1, oid) &&4041 preimage[sizeof(heading) + GIT_SHA1_HEXSZ -1] =='\n'&&4042/* does the abbreviated name on the index line agree with it? */4043starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))4044return0;/* it all looks fine */40454046/* we may have full object name on the index line */4047returnget_oid_hex(p->old_sha1_prefix, oid);4048}40494050/* Build an index that contains the just the files needed for a 3way merge */4051static intbuild_fake_ancestor(struct apply_state *state,struct patch *list)4052{4053struct patch *patch;4054struct index_state result = { NULL };4055static struct lock_file lock;4056int res;40574058/* Once we start supporting the reverse patch, it may be4059 * worth showing the new sha1 prefix, but until then...4060 */4061for(patch = list; patch; patch = patch->next) {4062struct object_id oid;4063struct cache_entry *ce;4064const char*name;40654066 name = patch->old_name ? patch->old_name : patch->new_name;4067if(0< patch->is_new)4068continue;40694070if(S_ISGITLINK(patch->old_mode)) {4071if(!preimage_oid_in_gitlink_patch(patch, &oid))4072;/* ok, the textual part looks sane */4073else4074returnerror(_("sha1 information is lacking or "4075"useless for submodule%s"), name);4076}else if(!get_sha1_blob(patch->old_sha1_prefix, oid.hash)) {4077;/* ok */4078}else if(!patch->lines_added && !patch->lines_deleted) {4079/* mode-only change: update the current */4080if(get_current_oid(state, patch->old_name, &oid))4081returnerror(_("mode change for%s, which is not "4082"in current HEAD"), name);4083}else4084returnerror(_("sha1 information is lacking or useless "4085"(%s)."), name);40864087 ce =make_cache_entry(patch->old_mode, oid.hash, name,0,0);4088if(!ce)4089returnerror(_("make_cache_entry failed for path '%s'"),4090 name);4091if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) {4092free(ce);4093returnerror(_("could not add%sto temporary index"),4094 name);4095}4096}40974098hold_lock_file_for_update(&lock, state->fake_ancestor, LOCK_DIE_ON_ERROR);4099 res =write_locked_index(&result, &lock, COMMIT_LOCK);4100discard_index(&result);41014102if(res)4103returnerror(_("could not write temporary index to%s"),4104 state->fake_ancestor);41054106return0;4107}41084109static voidstat_patch_list(struct apply_state *state,struct patch *patch)4110{4111int files, adds, dels;41124113for(files = adds = dels =0; patch ; patch = patch->next) {4114 files++;4115 adds += patch->lines_added;4116 dels += patch->lines_deleted;4117show_stats(state, patch);4118}41194120print_stat_summary(stdout, files, adds, dels);4121}41224123static voidnumstat_patch_list(struct apply_state *state,4124struct patch *patch)4125{4126for( ; patch; patch = patch->next) {4127const char*name;4128 name = patch->new_name ? patch->new_name : patch->old_name;4129if(patch->is_binary)4130printf("-\t-\t");4131else4132printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4133write_name_quoted(name, stdout, state->line_termination);4134}4135}41364137static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4138{4139if(mode)4140printf("%smode%06o%s\n", newdelete, mode, name);4141else4142printf("%s %s\n", newdelete, name);4143}41444145static voidshow_mode_change(struct patch *p,int show_name)4146{4147if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4148if(show_name)4149printf(" mode change%06o =>%06o%s\n",4150 p->old_mode, p->new_mode, p->new_name);4151else4152printf(" mode change%06o =>%06o\n",4153 p->old_mode, p->new_mode);4154}4155}41564157static voidshow_rename_copy(struct patch *p)4158{4159const char*renamecopy = p->is_rename ?"rename":"copy";4160const char*old, *new;41614162/* Find common prefix */4163 old = p->old_name;4164new= p->new_name;4165while(1) {4166const char*slash_old, *slash_new;4167 slash_old =strchr(old,'/');4168 slash_new =strchr(new,'/');4169if(!slash_old ||4170!slash_new ||4171 slash_old - old != slash_new -new||4172memcmp(old,new, slash_new -new))4173break;4174 old = slash_old +1;4175new= slash_new +1;4176}4177/* p->old_name thru old is the common prefix, and old and new4178 * through the end of names are renames4179 */4180if(old != p->old_name)4181printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4182(int)(old - p->old_name), p->old_name,4183 old,new, p->score);4184else4185printf("%s %s=>%s(%d%%)\n", renamecopy,4186 p->old_name, p->new_name, p->score);4187show_mode_change(p,0);4188}41894190static voidsummary_patch_list(struct patch *patch)4191{4192struct patch *p;41934194for(p = patch; p; p = p->next) {4195if(p->is_new)4196show_file_mode_name("create", p->new_mode, p->new_name);4197else if(p->is_delete)4198show_file_mode_name("delete", p->old_mode, p->old_name);4199else{4200if(p->is_rename || p->is_copy)4201show_rename_copy(p);4202else{4203if(p->score) {4204printf(" rewrite%s(%d%%)\n",4205 p->new_name, p->score);4206show_mode_change(p,0);4207}4208else4209show_mode_change(p,1);4210}4211}4212}4213}42144215static voidpatch_stats(struct apply_state *state,struct patch *patch)4216{4217int lines = patch->lines_added + patch->lines_deleted;42184219if(lines > state->max_change)4220 state->max_change = lines;4221if(patch->old_name) {4222int len =quote_c_style(patch->old_name, NULL, NULL,0);4223if(!len)4224 len =strlen(patch->old_name);4225if(len > state->max_len)4226 state->max_len = len;4227}4228if(patch->new_name) {4229int len =quote_c_style(patch->new_name, NULL, NULL,0);4230if(!len)4231 len =strlen(patch->new_name);4232if(len > state->max_len)4233 state->max_len = len;4234}4235}42364237static intremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4238{4239if(state->update_index) {4240if(remove_file_from_cache(patch->old_name) <0)4241returnerror(_("unable to remove%sfrom index"), patch->old_name);4242}4243if(!state->cached) {4244if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4245remove_path(patch->old_name);4246}4247}4248return0;4249}42504251static intadd_index_file(struct apply_state *state,4252const char*path,4253unsigned mode,4254void*buf,4255unsigned long size)4256{4257struct stat st;4258struct cache_entry *ce;4259int namelen =strlen(path);4260unsigned ce_size =cache_entry_size(namelen);42614262if(!state->update_index)4263return0;42644265 ce =xcalloc(1, ce_size);4266memcpy(ce->name, path, namelen);4267 ce->ce_mode =create_ce_mode(mode);4268 ce->ce_flags =create_ce_flags(0);4269 ce->ce_namelen = namelen;4270if(S_ISGITLINK(mode)) {4271const char*s;42724273if(!skip_prefix(buf,"Subproject commit ", &s) ||4274get_oid_hex(s, &ce->oid)) {4275free(ce);4276returnerror(_("corrupt patch for submodule%s"), path);4277}4278}else{4279if(!state->cached) {4280if(lstat(path, &st) <0) {4281free(ce);4282returnerror_errno(_("unable to stat newly "4283"created file '%s'"),4284 path);4285}4286fill_stat_cache_info(ce, &st);4287}4288if(write_sha1_file(buf, size, blob_type, ce->oid.hash) <0) {4289free(ce);4290returnerror(_("unable to create backing store "4291"for newly created file%s"), path);4292}4293}4294if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0) {4295free(ce);4296returnerror(_("unable to add cache entry for%s"), path);4297}42984299return0;4300}43014302/*4303 * Returns:4304 * -1 if an unrecoverable error happened4305 * 0 if everything went well4306 * 1 if a recoverable error happened4307 */4308static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4309{4310int fd, res;4311struct strbuf nbuf = STRBUF_INIT;43124313if(S_ISGITLINK(mode)) {4314struct stat st;4315if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4316return0;4317return!!mkdir(path,0777);4318}43194320if(has_symlinks &&S_ISLNK(mode))4321/* Although buf:size is counted string, it also is NUL4322 * terminated.4323 */4324return!!symlink(buf, path);43254326 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4327if(fd <0)4328return1;43294330if(convert_to_working_tree(path, buf, size, &nbuf)) {4331 size = nbuf.len;4332 buf = nbuf.buf;4333}43344335 res =write_in_full(fd, buf, size) <0;4336if(res)4337error_errno(_("failed to write to '%s'"), path);4338strbuf_release(&nbuf);43394340if(close(fd) <0&& !res)4341returnerror_errno(_("closing file '%s'"), path);43424343return res ? -1:0;4344}43454346/*4347 * We optimistically assume that the directories exist,4348 * which is true 99% of the time anyway. If they don't,4349 * we create them and try again.4350 *4351 * Returns:4352 * -1 on error4353 * 0 otherwise4354 */4355static intcreate_one_file(struct apply_state *state,4356char*path,4357unsigned mode,4358const char*buf,4359unsigned long size)4360{4361int res;43624363if(state->cached)4364return0;43654366 res =try_create_file(path, mode, buf, size);4367if(res <0)4368return-1;4369if(!res)4370return0;43714372if(errno == ENOENT) {4373if(safe_create_leading_directories(path))4374return0;4375 res =try_create_file(path, mode, buf, size);4376if(res <0)4377return-1;4378if(!res)4379return0;4380}43814382if(errno == EEXIST || errno == EACCES) {4383/* We may be trying to create a file where a directory4384 * used to be.4385 */4386struct stat st;4387if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4388 errno = EEXIST;4389}43904391if(errno == EEXIST) {4392unsigned int nr =getpid();43934394for(;;) {4395char newpath[PATH_MAX];4396mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4397 res =try_create_file(newpath, mode, buf, size);4398if(res <0)4399return-1;4400if(!res) {4401if(!rename(newpath, path))4402return0;4403unlink_or_warn(newpath);4404break;4405}4406if(errno != EEXIST)4407break;4408++nr;4409}4410}4411returnerror_errno(_("unable to write file '%s' mode%o"),4412 path, mode);4413}44144415static intadd_conflicted_stages_file(struct apply_state *state,4416struct patch *patch)4417{4418int stage, namelen;4419unsigned ce_size, mode;4420struct cache_entry *ce;44214422if(!state->update_index)4423return0;4424 namelen =strlen(patch->new_name);4425 ce_size =cache_entry_size(namelen);4426 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);44274428remove_file_from_cache(patch->new_name);4429for(stage =1; stage <4; stage++) {4430if(is_null_oid(&patch->threeway_stage[stage -1]))4431continue;4432 ce =xcalloc(1, ce_size);4433memcpy(ce->name, patch->new_name, namelen);4434 ce->ce_mode =create_ce_mode(mode);4435 ce->ce_flags =create_ce_flags(stage);4436 ce->ce_namelen = namelen;4437oidcpy(&ce->oid, &patch->threeway_stage[stage -1]);4438if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0) {4439free(ce);4440returnerror(_("unable to add cache entry for%s"),4441 patch->new_name);4442}4443}44444445return0;4446}44474448static intcreate_file(struct apply_state *state,struct patch *patch)4449{4450char*path = patch->new_name;4451unsigned mode = patch->new_mode;4452unsigned long size = patch->resultsize;4453char*buf = patch->result;44544455if(!mode)4456 mode = S_IFREG |0644;4457if(create_one_file(state, path, mode, buf, size))4458return-1;44594460if(patch->conflicted_threeway)4461returnadd_conflicted_stages_file(state, patch);4462else4463returnadd_index_file(state, path, mode, buf, size);4464}44654466/* phase zero is to remove, phase one is to create */4467static intwrite_out_one_result(struct apply_state *state,4468struct patch *patch,4469int phase)4470{4471if(patch->is_delete >0) {4472if(phase ==0)4473returnremove_file(state, patch,1);4474return0;4475}4476if(patch->is_new >0|| patch->is_copy) {4477if(phase ==1)4478returncreate_file(state, patch);4479return0;4480}4481/*4482 * Rename or modification boils down to the same4483 * thing: remove the old, write the new4484 */4485if(phase ==0)4486returnremove_file(state, patch, patch->is_rename);4487if(phase ==1)4488returncreate_file(state, patch);4489return0;4490}44914492static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4493{4494FILE*rej;4495char namebuf[PATH_MAX];4496struct fragment *frag;4497int cnt =0;4498struct strbuf sb = STRBUF_INIT;44994500for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4501if(!frag->rejected)4502continue;4503 cnt++;4504}45054506if(!cnt) {4507if(state->apply_verbosity > verbosity_normal)4508say_patch_name(stderr,4509_("Applied patch%scleanly."), patch);4510return0;4511}45124513/* This should not happen, because a removal patch that leaves4514 * contents are marked "rejected" at the patch level.4515 */4516if(!patch->new_name)4517die(_("internal error"));45184519/* Say this even without --verbose */4520strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4521"Applying patch %%swith%drejects...",4522 cnt),4523 cnt);4524if(state->apply_verbosity > verbosity_silent)4525say_patch_name(stderr, sb.buf, patch);4526strbuf_release(&sb);45274528 cnt =strlen(patch->new_name);4529if(ARRAY_SIZE(namebuf) <= cnt +5) {4530 cnt =ARRAY_SIZE(namebuf) -5;4531warning(_("truncating .rej filename to %.*s.rej"),4532 cnt -1, patch->new_name);4533}4534memcpy(namebuf, patch->new_name, cnt);4535memcpy(namebuf + cnt,".rej",5);45364537 rej =fopen(namebuf,"w");4538if(!rej)4539returnerror_errno(_("cannot open%s"), namebuf);45404541/* Normal git tools never deal with .rej, so do not pretend4542 * this is a git patch by saying --git or giving extended4543 * headers. While at it, maybe please "kompare" that wants4544 * the trailing TAB and some garbage at the end of line ;-).4545 */4546fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4547 patch->new_name, patch->new_name);4548for(cnt =1, frag = patch->fragments;4549 frag;4550 cnt++, frag = frag->next) {4551if(!frag->rejected) {4552if(state->apply_verbosity > verbosity_silent)4553fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4554continue;4555}4556if(state->apply_verbosity > verbosity_silent)4557fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4558fprintf(rej,"%.*s", frag->size, frag->patch);4559if(frag->patch[frag->size-1] !='\n')4560fputc('\n', rej);4561}4562fclose(rej);4563return-1;4564}45654566/*4567 * Returns:4568 * -1 if an error happened4569 * 0 if the patch applied cleanly4570 * 1 if the patch did not apply cleanly4571 */4572static intwrite_out_results(struct apply_state *state,struct patch *list)4573{4574int phase;4575int errs =0;4576struct patch *l;4577struct string_list cpath = STRING_LIST_INIT_DUP;45784579for(phase =0; phase <2; phase++) {4580 l = list;4581while(l) {4582if(l->rejected)4583 errs =1;4584else{4585if(write_out_one_result(state, l, phase)) {4586string_list_clear(&cpath,0);4587return-1;4588}4589if(phase ==1) {4590if(write_out_one_reject(state, l))4591 errs =1;4592if(l->conflicted_threeway) {4593string_list_append(&cpath, l->new_name);4594 errs =1;4595}4596}4597}4598 l = l->next;4599}4600}46014602if(cpath.nr) {4603struct string_list_item *item;46044605string_list_sort(&cpath);4606if(state->apply_verbosity > verbosity_silent) {4607for_each_string_list_item(item, &cpath)4608fprintf(stderr,"U%s\n", item->string);4609}4610string_list_clear(&cpath,0);46114612rerere(0);4613}46144615return errs;4616}46174618/*4619 * Try to apply a patch.4620 *4621 * Returns:4622 * -128 if a bad error happened (like patch unreadable)4623 * -1 if patch did not apply and user cannot deal with it4624 * 0 if the patch applied4625 * 1 if the patch did not apply but user might fix it4626 */4627static intapply_patch(struct apply_state *state,4628int fd,4629const char*filename,4630int options)4631{4632size_t offset;4633struct strbuf buf = STRBUF_INIT;/* owns the patch text */4634struct patch *list = NULL, **listp = &list;4635int skipped_patch =0;4636int res =0;46374638 state->patch_input_file = filename;4639if(read_patch_file(&buf, fd) <0)4640return-128;4641 offset =0;4642while(offset < buf.len) {4643struct patch *patch;4644int nr;46454646 patch =xcalloc(1,sizeof(*patch));4647 patch->inaccurate_eof = !!(options & APPLY_OPT_INACCURATE_EOF);4648 patch->recount = !!(options & APPLY_OPT_RECOUNT);4649 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4650if(nr <0) {4651free_patch(patch);4652if(nr == -128) {4653 res = -128;4654goto end;4655}4656break;4657}4658if(state->apply_in_reverse)4659reverse_patches(patch);4660if(use_patch(state, patch)) {4661patch_stats(state, patch);4662*listp = patch;4663 listp = &patch->next;4664}4665else{4666if(state->apply_verbosity > verbosity_normal)4667say_patch_name(stderr,_("Skipped patch '%s'."), patch);4668free_patch(patch);4669 skipped_patch++;4670}4671 offset += nr;4672}46734674if(!list && !skipped_patch) {4675error(_("unrecognized input"));4676 res = -128;4677goto end;4678}46794680if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4681 state->apply =0;46824683 state->update_index = state->check_index && state->apply;4684if(state->update_index && state->newfd <0) {4685if(state->index_file)4686 state->newfd =hold_lock_file_for_update(state->lock_file,4687 state->index_file,4688 LOCK_DIE_ON_ERROR);4689else4690 state->newfd =hold_locked_index(state->lock_file, LOCK_DIE_ON_ERROR);4691}46924693if(state->check_index &&read_apply_cache(state) <0) {4694error(_("unable to read index file"));4695 res = -128;4696goto end;4697}46984699if(state->check || state->apply) {4700int r =check_patch_list(state, list);4701if(r == -128) {4702 res = -128;4703goto end;4704}4705if(r <0&& !state->apply_with_reject) {4706 res = -1;4707goto end;4708}4709}47104711if(state->apply) {4712int write_res =write_out_results(state, list);4713if(write_res <0) {4714 res = -128;4715goto end;4716}4717if(write_res >0) {4718/* with --3way, we still need to write the index out */4719 res = state->apply_with_reject ? -1:1;4720goto end;4721}4722}47234724if(state->fake_ancestor &&4725build_fake_ancestor(state, list)) {4726 res = -128;4727goto end;4728}47294730if(state->diffstat && state->apply_verbosity > verbosity_silent)4731stat_patch_list(state, list);47324733if(state->numstat && state->apply_verbosity > verbosity_silent)4734numstat_patch_list(state, list);47354736if(state->summary && state->apply_verbosity > verbosity_silent)4737summary_patch_list(list);47384739end:4740free_patch_list(list);4741strbuf_release(&buf);4742string_list_clear(&state->fn_table,0);4743return res;4744}47454746static intapply_option_parse_exclude(const struct option *opt,4747const char*arg,int unset)4748{4749struct apply_state *state = opt->value;4750add_name_limit(state, arg,1);4751return0;4752}47534754static intapply_option_parse_include(const struct option *opt,4755const char*arg,int unset)4756{4757struct apply_state *state = opt->value;4758add_name_limit(state, arg,0);4759 state->has_include =1;4760return0;4761}47624763static intapply_option_parse_p(const struct option *opt,4764const char*arg,4765int unset)4766{4767struct apply_state *state = opt->value;4768 state->p_value =atoi(arg);4769 state->p_value_known =1;4770return0;4771}47724773static intapply_option_parse_space_change(const struct option *opt,4774const char*arg,int unset)4775{4776struct apply_state *state = opt->value;4777if(unset)4778 state->ws_ignore_action = ignore_ws_none;4779else4780 state->ws_ignore_action = ignore_ws_change;4781return0;4782}47834784static intapply_option_parse_whitespace(const struct option *opt,4785const char*arg,int unset)4786{4787struct apply_state *state = opt->value;4788 state->whitespace_option = arg;4789if(parse_whitespace_option(state, arg))4790exit(1);4791return0;4792}47934794static intapply_option_parse_directory(const struct option *opt,4795const char*arg,int unset)4796{4797struct apply_state *state = opt->value;4798strbuf_reset(&state->root);4799strbuf_addstr(&state->root, arg);4800strbuf_complete(&state->root,'/');4801return0;4802}48034804intapply_all_patches(struct apply_state *state,4805int argc,4806const char**argv,4807int options)4808{4809int i;4810int res;4811int errs =0;4812int read_stdin =1;48134814for(i =0; i < argc; i++) {4815const char*arg = argv[i];4816char*to_free = NULL;4817int fd;48184819if(!strcmp(arg,"-")) {4820 res =apply_patch(state,0,"<stdin>", options);4821if(res <0)4822goto end;4823 errs |= res;4824 read_stdin =0;4825continue;4826}else4827 arg = to_free =prefix_filename(state->prefix, arg);48284829 fd =open(arg, O_RDONLY);4830if(fd <0) {4831error(_("can't open patch '%s':%s"), arg,strerror(errno));4832 res = -128;4833free(to_free);4834goto end;4835}4836 read_stdin =0;4837set_default_whitespace_mode(state);4838 res =apply_patch(state, fd, arg, options);4839close(fd);4840free(to_free);4841if(res <0)4842goto end;4843 errs |= res;4844}4845set_default_whitespace_mode(state);4846if(read_stdin) {4847 res =apply_patch(state,0,"<stdin>", options);4848if(res <0)4849goto end;4850 errs |= res;4851}48524853if(state->whitespace_error) {4854if(state->squelch_whitespace_errors &&4855 state->squelch_whitespace_errors < state->whitespace_error) {4856int squelched =4857 state->whitespace_error - state->squelch_whitespace_errors;4858warning(Q_("squelched%dwhitespace error",4859"squelched%dwhitespace errors",4860 squelched),4861 squelched);4862}4863if(state->ws_error_action == die_on_ws_error) {4864error(Q_("%dline adds whitespace errors.",4865"%dlines add whitespace errors.",4866 state->whitespace_error),4867 state->whitespace_error);4868 res = -128;4869goto end;4870}4871if(state->applied_after_fixing_ws && state->apply)4872warning(Q_("%dline applied after"4873" fixing whitespace errors.",4874"%dlines applied after"4875" fixing whitespace errors.",4876 state->applied_after_fixing_ws),4877 state->applied_after_fixing_ws);4878else if(state->whitespace_error)4879warning(Q_("%dline adds whitespace errors.",4880"%dlines add whitespace errors.",4881 state->whitespace_error),4882 state->whitespace_error);4883}48844885if(state->update_index) {4886 res =write_locked_index(&the_index, state->lock_file, COMMIT_LOCK);4887if(res) {4888error(_("Unable to write new index file"));4889 res = -128;4890goto end;4891}4892 state->newfd = -1;4893}48944895 res = !!errs;48964897end:4898if(state->newfd >=0) {4899rollback_lock_file(state->lock_file);4900 state->newfd = -1;4901}49024903if(state->apply_verbosity <= verbosity_silent) {4904set_error_routine(state->saved_error_routine);4905set_warn_routine(state->saved_warn_routine);4906}49074908if(res > -1)4909return res;4910return(res == -1?1:128);4911}49124913intapply_parse_options(int argc,const char**argv,4914struct apply_state *state,4915int*force_apply,int*options,4916const char*const*apply_usage)4917{4918struct option builtin_apply_options[] = {4919{ OPTION_CALLBACK,0,"exclude", state,N_("path"),4920N_("don't apply changes matching the given path"),49210, apply_option_parse_exclude },4922{ OPTION_CALLBACK,0,"include", state,N_("path"),4923N_("apply changes matching the given path"),49240, apply_option_parse_include },4925{ OPTION_CALLBACK,'p', NULL, state,N_("num"),4926N_("remove <num> leading slashes from traditional diff paths"),49270, apply_option_parse_p },4928OPT_BOOL(0,"no-add", &state->no_add,4929N_("ignore additions made by the patch")),4930OPT_BOOL(0,"stat", &state->diffstat,4931N_("instead of applying the patch, output diffstat for the input")),4932OPT_NOOP_NOARG(0,"allow-binary-replacement"),4933OPT_NOOP_NOARG(0,"binary"),4934OPT_BOOL(0,"numstat", &state->numstat,4935N_("show number of added and deleted lines in decimal notation")),4936OPT_BOOL(0,"summary", &state->summary,4937N_("instead of applying the patch, output a summary for the input")),4938OPT_BOOL(0,"check", &state->check,4939N_("instead of applying the patch, see if the patch is applicable")),4940OPT_BOOL(0,"index", &state->check_index,4941N_("make sure the patch is applicable to the current index")),4942OPT_BOOL(0,"cached", &state->cached,4943N_("apply a patch without touching the working tree")),4944OPT_BOOL(0,"unsafe-paths", &state->unsafe_paths,4945N_("accept a patch that touches outside the working area")),4946OPT_BOOL(0,"apply", force_apply,4947N_("also apply the patch (use with --stat/--summary/--check)")),4948OPT_BOOL('3',"3way", &state->threeway,4949N_("attempt three-way merge if a patch does not apply")),4950OPT_FILENAME(0,"build-fake-ancestor", &state->fake_ancestor,4951N_("build a temporary index based on embedded index information")),4952/* Think twice before adding "--nul" synonym to this */4953OPT_SET_INT('z', NULL, &state->line_termination,4954N_("paths are separated with NUL character"),'\0'),4955OPT_INTEGER('C', NULL, &state->p_context,4956N_("ensure at least <n> lines of context match")),4957{ OPTION_CALLBACK,0,"whitespace", state,N_("action"),4958N_("detect new or modified lines that have whitespace errors"),49590, apply_option_parse_whitespace },4960{ OPTION_CALLBACK,0,"ignore-space-change", state, NULL,4961N_("ignore changes in whitespace when finding context"),4962 PARSE_OPT_NOARG, apply_option_parse_space_change },4963{ OPTION_CALLBACK,0,"ignore-whitespace", state, NULL,4964N_("ignore changes in whitespace when finding context"),4965 PARSE_OPT_NOARG, apply_option_parse_space_change },4966OPT_BOOL('R',"reverse", &state->apply_in_reverse,4967N_("apply the patch in reverse")),4968OPT_BOOL(0,"unidiff-zero", &state->unidiff_zero,4969N_("don't expect at least one line of context")),4970OPT_BOOL(0,"reject", &state->apply_with_reject,4971N_("leave the rejected hunks in corresponding *.rej files")),4972OPT_BOOL(0,"allow-overlap", &state->allow_overlap,4973N_("allow overlapping hunks")),4974OPT__VERBOSE(&state->apply_verbosity,N_("be verbose")),4975OPT_BIT(0,"inaccurate-eof", options,4976N_("tolerate incorrectly detected missing new-line at the end of file"),4977 APPLY_OPT_INACCURATE_EOF),4978OPT_BIT(0,"recount", options,4979N_("do not trust the line counts in the hunk headers"),4980 APPLY_OPT_RECOUNT),4981{ OPTION_CALLBACK,0,"directory", state,N_("root"),4982N_("prepend <root> to all filenames"),49830, apply_option_parse_directory },4984OPT_END()4985};49864987returnparse_options(argc, argv, state->prefix, builtin_apply_options, apply_usage,0);4988}