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; 214unsigned int is_toplevel_relative:1; 215unsigned int inaccurate_eof:1; 216unsigned int is_binary:1; 217unsigned int is_copy:1; 218unsigned int is_rename:1; 219unsigned int recount:1; 220unsigned int conflicted_threeway:1; 221unsigned int direct_to_threeway:1; 222struct fragment *fragments; 223char*result; 224size_t resultsize; 225char old_sha1_prefix[41]; 226char new_sha1_prefix[41]; 227struct patch *next; 228 229/* three-way fallback result */ 230struct object_id threeway_stage[3]; 231}; 232 233static voidfree_fragment_list(struct fragment *list) 234{ 235while(list) { 236struct fragment *next = list->next; 237if(list->free_patch) 238free((char*)list->patch); 239free(list); 240 list = next; 241} 242} 243 244static voidfree_patch(struct patch *patch) 245{ 246free_fragment_list(patch->fragments); 247free(patch->def_name); 248free(patch->old_name); 249free(patch->new_name); 250free(patch->result); 251free(patch); 252} 253 254static voidfree_patch_list(struct patch *list) 255{ 256while(list) { 257struct patch *next = list->next; 258free_patch(list); 259 list = next; 260} 261} 262 263/* 264 * A line in a file, len-bytes long (includes the terminating LF, 265 * except for an incomplete line at the end if the file ends with 266 * one), and its contents hashes to 'hash'. 267 */ 268struct line { 269size_t len; 270unsigned hash :24; 271unsigned flag :8; 272#define LINE_COMMON 1 273#define LINE_PATCHED 2 274}; 275 276/* 277 * This represents a "file", which is an array of "lines". 278 */ 279struct image { 280char*buf; 281size_t len; 282size_t nr; 283size_t alloc; 284struct line *line_allocated; 285struct line *line; 286}; 287 288static uint32_thash_line(const char*cp,size_t len) 289{ 290size_t i; 291uint32_t h; 292for(i =0, h =0; i < len; i++) { 293if(!isspace(cp[i])) { 294 h = h *3+ (cp[i] &0xff); 295} 296} 297return h; 298} 299 300/* 301 * Compare lines s1 of length n1 and s2 of length n2, ignoring 302 * whitespace difference. Returns 1 if they match, 0 otherwise 303 */ 304static intfuzzy_matchlines(const char*s1,size_t n1, 305const char*s2,size_t n2) 306{ 307const char*last1 = s1 + n1 -1; 308const char*last2 = s2 + n2 -1; 309int result =0; 310 311/* ignore line endings */ 312while((*last1 =='\r') || (*last1 =='\n')) 313 last1--; 314while((*last2 =='\r') || (*last2 =='\n')) 315 last2--; 316 317/* skip leading whitespaces, if both begin with whitespace */ 318if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 319while(isspace(*s1) && (s1 <= last1)) 320 s1++; 321while(isspace(*s2) && (s2 <= last2)) 322 s2++; 323} 324/* early return if both lines are empty */ 325if((s1 > last1) && (s2 > last2)) 326return1; 327while(!result) { 328 result = *s1++ - *s2++; 329/* 330 * Skip whitespace inside. We check for whitespace on 331 * both buffers because we don't want "a b" to match 332 * "ab" 333 */ 334if(isspace(*s1) &&isspace(*s2)) { 335while(isspace(*s1) && s1 <= last1) 336 s1++; 337while(isspace(*s2) && s2 <= last2) 338 s2++; 339} 340/* 341 * If we reached the end on one side only, 342 * lines don't match 343 */ 344if( 345((s2 > last2) && (s1 <= last1)) || 346((s1 > last1) && (s2 <= last2))) 347return0; 348if((s1 > last1) && (s2 > last2)) 349break; 350} 351 352return!result; 353} 354 355static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 356{ 357ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 358 img->line_allocated[img->nr].len = len; 359 img->line_allocated[img->nr].hash =hash_line(bol, len); 360 img->line_allocated[img->nr].flag = flag; 361 img->nr++; 362} 363 364/* 365 * "buf" has the file contents to be patched (read from various sources). 366 * attach it to "image" and add line-based index to it. 367 * "image" now owns the "buf". 368 */ 369static voidprepare_image(struct image *image,char*buf,size_t len, 370int prepare_linetable) 371{ 372const char*cp, *ep; 373 374memset(image,0,sizeof(*image)); 375 image->buf = buf; 376 image->len = len; 377 378if(!prepare_linetable) 379return; 380 381 ep = image->buf + image->len; 382 cp = image->buf; 383while(cp < ep) { 384const char*next; 385for(next = cp; next < ep && *next !='\n'; next++) 386; 387if(next < ep) 388 next++; 389add_line_info(image, cp, next - cp,0); 390 cp = next; 391} 392 image->line = image->line_allocated; 393} 394 395static voidclear_image(struct image *image) 396{ 397free(image->buf); 398free(image->line_allocated); 399memset(image,0,sizeof(*image)); 400} 401 402/* fmt must contain _one_ %s and no other substitution */ 403static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 404{ 405struct strbuf sb = STRBUF_INIT; 406 407if(patch->old_name && patch->new_name && 408strcmp(patch->old_name, patch->new_name)) { 409quote_c_style(patch->old_name, &sb, NULL,0); 410strbuf_addstr(&sb," => "); 411quote_c_style(patch->new_name, &sb, NULL,0); 412}else{ 413const char*n = patch->new_name; 414if(!n) 415 n = patch->old_name; 416quote_c_style(n, &sb, NULL,0); 417} 418fprintf(output, fmt, sb.buf); 419fputc('\n', output); 420strbuf_release(&sb); 421} 422 423#define SLOP (16) 424 425static intread_patch_file(struct strbuf *sb,int fd) 426{ 427if(strbuf_read(sb, fd,0) <0) 428returnerror_errno("git apply: failed to read"); 429 430/* 431 * Make sure that we have some slop in the buffer 432 * so that we can do speculative "memcmp" etc, and 433 * see to it that it is NUL-filled. 434 */ 435strbuf_grow(sb, SLOP); 436memset(sb->buf + sb->len,0, SLOP); 437return0; 438} 439 440static unsigned longlinelen(const char*buffer,unsigned long size) 441{ 442unsigned long len =0; 443while(size--) { 444 len++; 445if(*buffer++ =='\n') 446break; 447} 448return len; 449} 450 451static intis_dev_null(const char*str) 452{ 453returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 454} 455 456#define TERM_SPACE 1 457#define TERM_TAB 2 458 459static intname_terminate(int c,int terminate) 460{ 461if(c ==' '&& !(terminate & TERM_SPACE)) 462return0; 463if(c =='\t'&& !(terminate & TERM_TAB)) 464return0; 465 466return1; 467} 468 469/* remove double slashes to make --index work with such filenames */ 470static char*squash_slash(char*name) 471{ 472int i =0, j =0; 473 474if(!name) 475return NULL; 476 477while(name[i]) { 478if((name[j++] = name[i++]) =='/') 479while(name[i] =='/') 480 i++; 481} 482 name[j] ='\0'; 483return name; 484} 485 486static char*find_name_gnu(struct apply_state *state, 487const char*line, 488const char*def, 489int p_value) 490{ 491struct strbuf name = STRBUF_INIT; 492char*cp; 493 494/* 495 * Proposed "new-style" GNU patch/diff format; see 496 * http://marc.info/?l=git&m=112927316408690&w=2 497 */ 498if(unquote_c_style(&name, line, NULL)) { 499strbuf_release(&name); 500return NULL; 501} 502 503for(cp = name.buf; p_value; p_value--) { 504 cp =strchr(cp,'/'); 505if(!cp) { 506strbuf_release(&name); 507return NULL; 508} 509 cp++; 510} 511 512strbuf_remove(&name,0, cp - name.buf); 513if(state->root.len) 514strbuf_insert(&name,0, state->root.buf, state->root.len); 515returnsquash_slash(strbuf_detach(&name, NULL)); 516} 517 518static size_tsane_tz_len(const char*line,size_t len) 519{ 520const char*tz, *p; 521 522if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 523return0; 524 tz = line + len -strlen(" +0500"); 525 526if(tz[1] !='+'&& tz[1] !='-') 527return0; 528 529for(p = tz +2; p != line + len; p++) 530if(!isdigit(*p)) 531return0; 532 533return line + len - tz; 534} 535 536static size_ttz_with_colon_len(const char*line,size_t len) 537{ 538const char*tz, *p; 539 540if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 541return0; 542 tz = line + len -strlen(" +08:00"); 543 544if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 545return0; 546 p = tz +2; 547if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 548!isdigit(*p++) || !isdigit(*p++)) 549return0; 550 551return line + len - tz; 552} 553 554static size_tdate_len(const char*line,size_t len) 555{ 556const char*date, *p; 557 558if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 559return0; 560 p = date = line + len -strlen("72-02-05"); 561 562if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 563!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 564!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 565return0; 566 567if(date - line >=strlen("19") && 568isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 569 date -=strlen("19"); 570 571return line + len - date; 572} 573 574static size_tshort_time_len(const char*line,size_t len) 575{ 576const char*time, *p; 577 578if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 579return0; 580 p = time = line + len -strlen(" 07:01:32"); 581 582/* Permit 1-digit hours? */ 583if(*p++ !=' '|| 584!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 585!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 586!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 587return0; 588 589return line + len - time; 590} 591 592static size_tfractional_time_len(const char*line,size_t len) 593{ 594const char*p; 595size_t n; 596 597/* Expected format: 19:41:17.620000023 */ 598if(!len || !isdigit(line[len -1])) 599return0; 600 p = line + len -1; 601 602/* Fractional seconds. */ 603while(p > line &&isdigit(*p)) 604 p--; 605if(*p !='.') 606return0; 607 608/* Hours, minutes, and whole seconds. */ 609 n =short_time_len(line, p - line); 610if(!n) 611return0; 612 613return line + len - p + n; 614} 615 616static size_ttrailing_spaces_len(const char*line,size_t len) 617{ 618const char*p; 619 620/* Expected format: ' ' x (1 or more) */ 621if(!len || line[len -1] !=' ') 622return0; 623 624 p = line + len; 625while(p != line) { 626 p--; 627if(*p !=' ') 628return line + len - (p +1); 629} 630 631/* All spaces! */ 632return len; 633} 634 635static size_tdiff_timestamp_len(const char*line,size_t len) 636{ 637const char*end = line + len; 638size_t n; 639 640/* 641 * Posix: 2010-07-05 19:41:17 642 * GNU: 2010-07-05 19:41:17.620000023 -0500 643 */ 644 645if(!isdigit(end[-1])) 646return0; 647 648 n =sane_tz_len(line, end - line); 649if(!n) 650 n =tz_with_colon_len(line, end - line); 651 end -= n; 652 653 n =short_time_len(line, end - line); 654if(!n) 655 n =fractional_time_len(line, end - line); 656 end -= n; 657 658 n =date_len(line, end - line); 659if(!n)/* No date. Too bad. */ 660return0; 661 end -= n; 662 663if(end == line)/* No space before date. */ 664return0; 665if(end[-1] =='\t') {/* Success! */ 666 end--; 667return line + len - end; 668} 669if(end[-1] !=' ')/* No space before date. */ 670return0; 671 672/* Whitespace damage. */ 673 end -=trailing_spaces_len(line, end - line); 674return line + len - end; 675} 676 677static char*find_name_common(struct apply_state *state, 678const char*line, 679const char*def, 680int p_value, 681const char*end, 682int terminate) 683{ 684int len; 685const char*start = NULL; 686 687if(p_value ==0) 688 start = line; 689while(line != end) { 690char c = *line; 691 692if(!end &&isspace(c)) { 693if(c =='\n') 694break; 695if(name_terminate(c, terminate)) 696break; 697} 698 line++; 699if(c =='/'&& !--p_value) 700 start = line; 701} 702if(!start) 703returnsquash_slash(xstrdup_or_null(def)); 704 len = line - start; 705if(!len) 706returnsquash_slash(xstrdup_or_null(def)); 707 708/* 709 * Generally we prefer the shorter name, especially 710 * if the other one is just a variation of that with 711 * something else tacked on to the end (ie "file.orig" 712 * or "file~"). 713 */ 714if(def) { 715int deflen =strlen(def); 716if(deflen < len && !strncmp(start, def, deflen)) 717returnsquash_slash(xstrdup(def)); 718} 719 720if(state->root.len) { 721char*ret =xstrfmt("%s%.*s", state->root.buf, len, start); 722returnsquash_slash(ret); 723} 724 725returnsquash_slash(xmemdupz(start, len)); 726} 727 728static char*find_name(struct apply_state *state, 729const char*line, 730char*def, 731int p_value, 732int terminate) 733{ 734if(*line =='"') { 735char*name =find_name_gnu(state, line, def, p_value); 736if(name) 737return name; 738} 739 740returnfind_name_common(state, line, def, p_value, NULL, terminate); 741} 742 743static char*find_name_traditional(struct apply_state *state, 744const char*line, 745char*def, 746int p_value) 747{ 748size_t len; 749size_t date_len; 750 751if(*line =='"') { 752char*name =find_name_gnu(state, line, def, p_value); 753if(name) 754return name; 755} 756 757 len =strchrnul(line,'\n') - line; 758 date_len =diff_timestamp_len(line, len); 759if(!date_len) 760returnfind_name_common(state, line, def, p_value, NULL, TERM_TAB); 761 len -= date_len; 762 763returnfind_name_common(state, line, def, p_value, line + len,0); 764} 765 766static intcount_slashes(const char*cp) 767{ 768int cnt =0; 769char ch; 770 771while((ch = *cp++)) 772if(ch =='/') 773 cnt++; 774return cnt; 775} 776 777/* 778 * Given the string after "--- " or "+++ ", guess the appropriate 779 * p_value for the given patch. 780 */ 781static intguess_p_value(struct apply_state *state,const char*nameline) 782{ 783char*name, *cp; 784int val = -1; 785 786if(is_dev_null(nameline)) 787return-1; 788 name =find_name_traditional(state, nameline, NULL,0); 789if(!name) 790return-1; 791 cp =strchr(name,'/'); 792if(!cp) 793 val =0; 794else if(state->prefix) { 795/* 796 * Does it begin with "a/$our-prefix" and such? Then this is 797 * very likely to apply to our directory. 798 */ 799if(!strncmp(name, state->prefix, state->prefix_length)) 800 val =count_slashes(state->prefix); 801else{ 802 cp++; 803if(!strncmp(cp, state->prefix, state->prefix_length)) 804 val =count_slashes(state->prefix) +1; 805} 806} 807free(name); 808return val; 809} 810 811/* 812 * Does the ---/+++ line have the POSIX timestamp after the last HT? 813 * GNU diff puts epoch there to signal a creation/deletion event. Is 814 * this such a timestamp? 815 */ 816static inthas_epoch_timestamp(const char*nameline) 817{ 818/* 819 * We are only interested in epoch timestamp; any non-zero 820 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 821 * For the same reason, the date must be either 1969-12-31 or 822 * 1970-01-01, and the seconds part must be "00". 823 */ 824const char stamp_regexp[] = 825"^(1969-12-31|1970-01-01)" 826" " 827"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 828" " 829"([-+][0-2][0-9]:?[0-5][0-9])\n"; 830const char*timestamp = NULL, *cp, *colon; 831static regex_t *stamp; 832 regmatch_t m[10]; 833int zoneoffset; 834int hourminute; 835int status; 836 837for(cp = nameline; *cp !='\n'; cp++) { 838if(*cp =='\t') 839 timestamp = cp +1; 840} 841if(!timestamp) 842return0; 843if(!stamp) { 844 stamp =xmalloc(sizeof(*stamp)); 845if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 846warning(_("Cannot prepare timestamp regexp%s"), 847 stamp_regexp); 848return0; 849} 850} 851 852 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 853if(status) { 854if(status != REG_NOMATCH) 855warning(_("regexec returned%dfor input:%s"), 856 status, timestamp); 857return0; 858} 859 860 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 861if(*colon ==':') 862 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 863else 864 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 865if(timestamp[m[3].rm_so] =='-') 866 zoneoffset = -zoneoffset; 867 868/* 869 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 870 * (west of GMT) or 1970-01-01 (east of GMT) 871 */ 872if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 873(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 874return0; 875 876 hourminute = (strtol(timestamp +11, NULL,10) *60+ 877strtol(timestamp +14, NULL,10) - 878 zoneoffset); 879 880return((zoneoffset <0&& hourminute ==1440) || 881(0<= zoneoffset && !hourminute)); 882} 883 884/* 885 * Get the name etc info from the ---/+++ lines of a traditional patch header 886 * 887 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 888 * files, we can happily check the index for a match, but for creating a 889 * new file we should try to match whatever "patch" does. I have no idea. 890 */ 891static intparse_traditional_patch(struct apply_state *state, 892const char*first, 893const char*second, 894struct patch *patch) 895{ 896char*name; 897 898 first +=4;/* skip "--- " */ 899 second +=4;/* skip "+++ " */ 900if(!state->p_value_known) { 901int p, q; 902 p =guess_p_value(state, first); 903 q =guess_p_value(state, second); 904if(p <0) p = q; 905if(0<= p && p == q) { 906 state->p_value = p; 907 state->p_value_known =1; 908} 909} 910if(is_dev_null(first)) { 911 patch->is_new =1; 912 patch->is_delete =0; 913 name =find_name_traditional(state, second, NULL, state->p_value); 914 patch->new_name = name; 915}else if(is_dev_null(second)) { 916 patch->is_new =0; 917 patch->is_delete =1; 918 name =find_name_traditional(state, first, NULL, state->p_value); 919 patch->old_name = name; 920}else{ 921char*first_name; 922 first_name =find_name_traditional(state, first, NULL, state->p_value); 923 name =find_name_traditional(state, second, first_name, state->p_value); 924free(first_name); 925if(has_epoch_timestamp(first)) { 926 patch->is_new =1; 927 patch->is_delete =0; 928 patch->new_name = name; 929}else if(has_epoch_timestamp(second)) { 930 patch->is_new =0; 931 patch->is_delete =1; 932 patch->old_name = name; 933}else{ 934 patch->old_name = name; 935 patch->new_name =xstrdup_or_null(name); 936} 937} 938if(!name) 939returnerror(_("unable to find filename in patch at line%d"), state->linenr); 940 941return0; 942} 943 944static intgitdiff_hdrend(struct apply_state *state, 945const char*line, 946struct patch *patch) 947{ 948return1; 949} 950 951/* 952 * We're anal about diff header consistency, to make 953 * sure that we don't end up having strange ambiguous 954 * patches floating around. 955 * 956 * As a result, gitdiff_{old|new}name() will check 957 * their names against any previous information, just 958 * to make sure.. 959 */ 960#define DIFF_OLD_NAME 0 961#define DIFF_NEW_NAME 1 962 963static intgitdiff_verify_name(struct apply_state *state, 964const char*line, 965int isnull, 966char**name, 967int side) 968{ 969if(!*name && !isnull) { 970*name =find_name(state, line, NULL, state->p_value, TERM_TAB); 971return0; 972} 973 974if(*name) { 975int len =strlen(*name); 976char*another; 977if(isnull) 978returnerror(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 979*name, state->linenr); 980 another =find_name(state, line, NULL, state->p_value, TERM_TAB); 981if(!another ||memcmp(another, *name, len +1)) { 982free(another); 983returnerror((side == DIFF_NEW_NAME) ? 984_("git apply: bad git-diff - inconsistent new filename on line%d") : 985_("git apply: bad git-diff - inconsistent old filename on line%d"), state->linenr); 986} 987free(another); 988}else{ 989/* expect "/dev/null" */ 990if(memcmp("/dev/null", line,9) || line[9] !='\n') 991returnerror(_("git apply: bad git-diff - expected /dev/null on line%d"), state->linenr); 992} 993 994return0; 995} 996 997static intgitdiff_oldname(struct apply_state *state, 998const char*line, 999struct patch *patch)1000{1001returngitdiff_verify_name(state, line,1002 patch->is_new, &patch->old_name,1003 DIFF_OLD_NAME);1004}10051006static intgitdiff_newname(struct apply_state *state,1007const char*line,1008struct patch *patch)1009{1010returngitdiff_verify_name(state, line,1011 patch->is_delete, &patch->new_name,1012 DIFF_NEW_NAME);1013}10141015static intgitdiff_oldmode(struct apply_state *state,1016const char*line,1017struct patch *patch)1018{1019 patch->old_mode =strtoul(line, NULL,8);1020return0;1021}10221023static intgitdiff_newmode(struct apply_state *state,1024const char*line,1025struct patch *patch)1026{1027 patch->new_mode =strtoul(line, NULL,8);1028return0;1029}10301031static intgitdiff_delete(struct apply_state *state,1032const char*line,1033struct patch *patch)1034{1035 patch->is_delete =1;1036free(patch->old_name);1037 patch->old_name =xstrdup_or_null(patch->def_name);1038returngitdiff_oldmode(state, line, patch);1039}10401041static intgitdiff_newfile(struct apply_state *state,1042const char*line,1043struct patch *patch)1044{1045 patch->is_new =1;1046free(patch->new_name);1047 patch->new_name =xstrdup_or_null(patch->def_name);1048returngitdiff_newmode(state, line, patch);1049}10501051static intgitdiff_copysrc(struct apply_state *state,1052const char*line,1053struct patch *patch)1054{1055 patch->is_copy =1;1056free(patch->old_name);1057 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1058return0;1059}10601061static intgitdiff_copydst(struct apply_state *state,1062const char*line,1063struct patch *patch)1064{1065 patch->is_copy =1;1066free(patch->new_name);1067 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1068return0;1069}10701071static intgitdiff_renamesrc(struct apply_state *state,1072const char*line,1073struct patch *patch)1074{1075 patch->is_rename =1;1076free(patch->old_name);1077 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1078return0;1079}10801081static intgitdiff_renamedst(struct apply_state *state,1082const char*line,1083struct patch *patch)1084{1085 patch->is_rename =1;1086free(patch->new_name);1087 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1088return0;1089}10901091static intgitdiff_similarity(struct apply_state *state,1092const char*line,1093struct patch *patch)1094{1095unsigned long val =strtoul(line, NULL,10);1096if(val <=100)1097 patch->score = val;1098return0;1099}11001101static intgitdiff_dissimilarity(struct apply_state *state,1102const char*line,1103struct patch *patch)1104{1105unsigned long val =strtoul(line, NULL,10);1106if(val <=100)1107 patch->score = val;1108return0;1109}11101111static intgitdiff_index(struct apply_state *state,1112const char*line,1113struct patch *patch)1114{1115/*1116 * index line is N hexadecimal, "..", N hexadecimal,1117 * and optional space with octal mode.1118 */1119const char*ptr, *eol;1120int len;11211122 ptr =strchr(line,'.');1123if(!ptr || ptr[1] !='.'||40< ptr - line)1124return0;1125 len = ptr - line;1126memcpy(patch->old_sha1_prefix, line, len);1127 patch->old_sha1_prefix[len] =0;11281129 line = ptr +2;1130 ptr =strchr(line,' ');1131 eol =strchrnul(line,'\n');11321133if(!ptr || eol < ptr)1134 ptr = eol;1135 len = ptr - line;11361137if(40< len)1138return0;1139memcpy(patch->new_sha1_prefix, line, len);1140 patch->new_sha1_prefix[len] =0;1141if(*ptr ==' ')1142 patch->old_mode =strtoul(ptr+1, NULL,8);1143return0;1144}11451146/*1147 * This is normal for a diff that doesn't change anything: we'll fall through1148 * into the next diff. Tell the parser to break out.1149 */1150static intgitdiff_unrecognized(struct apply_state *state,1151const char*line,1152struct patch *patch)1153{1154return1;1155}11561157/*1158 * Skip p_value leading components from "line"; as we do not accept1159 * absolute paths, return NULL in that case.1160 */1161static const char*skip_tree_prefix(struct apply_state *state,1162const char*line,1163int llen)1164{1165int nslash;1166int i;11671168if(!state->p_value)1169return(llen && line[0] =='/') ? NULL : line;11701171 nslash = state->p_value;1172for(i =0; i < llen; i++) {1173int ch = line[i];1174if(ch =='/'&& --nslash <=0)1175return(i ==0) ? NULL : &line[i +1];1176}1177return NULL;1178}11791180/*1181 * This is to extract the same name that appears on "diff --git"1182 * line. We do not find and return anything if it is a rename1183 * patch, and it is OK because we will find the name elsewhere.1184 * We need to reliably find name only when it is mode-change only,1185 * creation or deletion of an empty file. In any of these cases,1186 * both sides are the same name under a/ and b/ respectively.1187 */1188static char*git_header_name(struct apply_state *state,1189const char*line,1190int llen)1191{1192const char*name;1193const char*second = NULL;1194size_t len, line_len;11951196 line +=strlen("diff --git ");1197 llen -=strlen("diff --git ");11981199if(*line =='"') {1200const char*cp;1201struct strbuf first = STRBUF_INIT;1202struct strbuf sp = STRBUF_INIT;12031204if(unquote_c_style(&first, line, &second))1205goto free_and_fail1;12061207/* strip the a/b prefix including trailing slash */1208 cp =skip_tree_prefix(state, first.buf, first.len);1209if(!cp)1210goto free_and_fail1;1211strbuf_remove(&first,0, cp - first.buf);12121213/*1214 * second points at one past closing dq of name.1215 * find the second name.1216 */1217while((second < line + llen) &&isspace(*second))1218 second++;12191220if(line + llen <= second)1221goto free_and_fail1;1222if(*second =='"') {1223if(unquote_c_style(&sp, second, NULL))1224goto free_and_fail1;1225 cp =skip_tree_prefix(state, sp.buf, sp.len);1226if(!cp)1227goto free_and_fail1;1228/* They must match, otherwise ignore */1229if(strcmp(cp, first.buf))1230goto free_and_fail1;1231strbuf_release(&sp);1232returnstrbuf_detach(&first, NULL);1233}12341235/* unquoted second */1236 cp =skip_tree_prefix(state, second, line + llen - second);1237if(!cp)1238goto free_and_fail1;1239if(line + llen - cp != first.len ||1240memcmp(first.buf, cp, first.len))1241goto free_and_fail1;1242returnstrbuf_detach(&first, NULL);12431244 free_and_fail1:1245strbuf_release(&first);1246strbuf_release(&sp);1247return NULL;1248}12491250/* unquoted first name */1251 name =skip_tree_prefix(state, line, llen);1252if(!name)1253return NULL;12541255/*1256 * since the first name is unquoted, a dq if exists must be1257 * the beginning of the second name.1258 */1259for(second = name; second < line + llen; second++) {1260if(*second =='"') {1261struct strbuf sp = STRBUF_INIT;1262const char*np;12631264if(unquote_c_style(&sp, second, NULL))1265goto free_and_fail2;12661267 np =skip_tree_prefix(state, sp.buf, sp.len);1268if(!np)1269goto free_and_fail2;12701271 len = sp.buf + sp.len - np;1272if(len < second - name &&1273!strncmp(np, name, len) &&1274isspace(name[len])) {1275/* Good */1276strbuf_remove(&sp,0, np - sp.buf);1277returnstrbuf_detach(&sp, NULL);1278}12791280 free_and_fail2:1281strbuf_release(&sp);1282return NULL;1283}1284}12851286/*1287 * Accept a name only if it shows up twice, exactly the same1288 * form.1289 */1290 second =strchr(name,'\n');1291if(!second)1292return NULL;1293 line_len = second - name;1294for(len =0; ; len++) {1295switch(name[len]) {1296default:1297continue;1298case'\n':1299return NULL;1300case'\t':case' ':1301/*1302 * Is this the separator between the preimage1303 * and the postimage pathname? Again, we are1304 * only interested in the case where there is1305 * no rename, as this is only to set def_name1306 * and a rename patch has the names elsewhere1307 * in an unambiguous form.1308 */1309if(!name[len +1])1310return NULL;/* no postimage name */1311 second =skip_tree_prefix(state, name + len +1,1312 line_len - (len +1));1313if(!second)1314return NULL;1315/*1316 * Does len bytes starting at "name" and "second"1317 * (that are separated by one HT or SP we just1318 * found) exactly match?1319 */1320if(second[len] =='\n'&& !strncmp(name, second, len))1321returnxmemdupz(name, len);1322}1323}1324}13251326/* Verify that we recognize the lines following a git header */1327static intparse_git_header(struct apply_state *state,1328const char*line,1329int len,1330unsigned int size,1331struct patch *patch)1332{1333unsigned long offset;13341335/* A git diff has explicit new/delete information, so we don't guess */1336 patch->is_new =0;1337 patch->is_delete =0;13381339/*1340 * Some things may not have the old name in the1341 * rest of the headers anywhere (pure mode changes,1342 * or removing or adding empty files), so we get1343 * the default name from the header.1344 */1345 patch->def_name =git_header_name(state, line, len);1346if(patch->def_name && state->root.len) {1347char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1348free(patch->def_name);1349 patch->def_name = s;1350}13511352 line += len;1353 size -= len;1354 state->linenr++;1355for(offset = len ; size >0; offset += len, size -= len, line += len, state->linenr++) {1356static const struct opentry {1357const char*str;1358int(*fn)(struct apply_state *,const char*,struct patch *);1359} optable[] = {1360{"@@ -", gitdiff_hdrend },1361{"--- ", gitdiff_oldname },1362{"+++ ", gitdiff_newname },1363{"old mode ", gitdiff_oldmode },1364{"new mode ", gitdiff_newmode },1365{"deleted file mode ", gitdiff_delete },1366{"new file mode ", gitdiff_newfile },1367{"copy from ", gitdiff_copysrc },1368{"copy to ", gitdiff_copydst },1369{"rename old ", gitdiff_renamesrc },1370{"rename new ", gitdiff_renamedst },1371{"rename from ", gitdiff_renamesrc },1372{"rename to ", gitdiff_renamedst },1373{"similarity index ", gitdiff_similarity },1374{"dissimilarity index ", gitdiff_dissimilarity },1375{"index ", gitdiff_index },1376{"", gitdiff_unrecognized },1377};1378int i;13791380 len =linelen(line, size);1381if(!len || line[len-1] !='\n')1382break;1383for(i =0; i <ARRAY_SIZE(optable); i++) {1384const struct opentry *p = optable + i;1385int oplen =strlen(p->str);1386int res;1387if(len < oplen ||memcmp(p->str, line, oplen))1388continue;1389 res = p->fn(state, line + oplen, patch);1390if(res <0)1391return-1;1392if(res >0)1393return offset;1394break;1395}1396}13971398return offset;1399}14001401static intparse_num(const char*line,unsigned long*p)1402{1403char*ptr;14041405if(!isdigit(*line))1406return0;1407*p =strtoul(line, &ptr,10);1408return ptr - line;1409}14101411static intparse_range(const char*line,int len,int offset,const char*expect,1412unsigned long*p1,unsigned long*p2)1413{1414int digits, ex;14151416if(offset <0|| offset >= len)1417return-1;1418 line += offset;1419 len -= offset;14201421 digits =parse_num(line, p1);1422if(!digits)1423return-1;14241425 offset += digits;1426 line += digits;1427 len -= digits;14281429*p2 =1;1430if(*line ==',') {1431 digits =parse_num(line+1, p2);1432if(!digits)1433return-1;14341435 offset += digits+1;1436 line += digits+1;1437 len -= digits+1;1438}14391440 ex =strlen(expect);1441if(ex > len)1442return-1;1443if(memcmp(line, expect, ex))1444return-1;14451446return offset + ex;1447}14481449static voidrecount_diff(const char*line,int size,struct fragment *fragment)1450{1451int oldlines =0, newlines =0, ret =0;14521453if(size <1) {1454warning("recount: ignore empty hunk");1455return;1456}14571458for(;;) {1459int len =linelen(line, size);1460 size -= len;1461 line += len;14621463if(size <1)1464break;14651466switch(*line) {1467case' ':case'\n':1468 newlines++;1469/* fall through */1470case'-':1471 oldlines++;1472continue;1473case'+':1474 newlines++;1475continue;1476case'\\':1477continue;1478case'@':1479 ret = size <3|| !starts_with(line,"@@ ");1480break;1481case'd':1482 ret = size <5|| !starts_with(line,"diff ");1483break;1484default:1485 ret = -1;1486break;1487}1488if(ret) {1489warning(_("recount: unexpected line: %.*s"),1490(int)linelen(line, size), line);1491return;1492}1493break;1494}1495 fragment->oldlines = oldlines;1496 fragment->newlines = newlines;1497}14981499/*1500 * Parse a unified diff fragment header of the1501 * form "@@ -a,b +c,d @@"1502 */1503static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1504{1505int offset;15061507if(!len || line[len-1] !='\n')1508return-1;15091510/* Figure out the number of lines in a fragment */1511 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1512 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);15131514return offset;1515}15161517/*1518 * Find file diff header1519 *1520 * Returns:1521 * -1 if no header was found1522 * -128 in case of error1523 * the size of the header in bytes (called "offset") otherwise1524 */1525static intfind_header(struct apply_state *state,1526const char*line,1527unsigned long size,1528int*hdrsize,1529struct patch *patch)1530{1531unsigned long offset, len;15321533 patch->is_toplevel_relative =0;1534 patch->is_rename = patch->is_copy =0;1535 patch->is_new = patch->is_delete = -1;1536 patch->old_mode = patch->new_mode =0;1537 patch->old_name = patch->new_name = NULL;1538for(offset =0; size >0; offset += len, size -= len, line += len, state->linenr++) {1539unsigned long nextlen;15401541 len =linelen(line, size);1542if(!len)1543break;15441545/* Testing this early allows us to take a few shortcuts.. */1546if(len <6)1547continue;15481549/*1550 * Make sure we don't find any unconnected patch fragments.1551 * That's a sign that we didn't find a header, and that a1552 * patch has become corrupted/broken up.1553 */1554if(!memcmp("@@ -", line,4)) {1555struct fragment dummy;1556if(parse_fragment_header(line, len, &dummy) <0)1557continue;1558error(_("patch fragment without header at line%d: %.*s"),1559 state->linenr, (int)len-1, line);1560return-128;1561}15621563if(size < len +6)1564break;15651566/*1567 * Git patch? It might not have a real patch, just a rename1568 * or mode change, so we handle that specially1569 */1570if(!memcmp("diff --git ", line,11)) {1571int git_hdr_len =parse_git_header(state, line, len, size, patch);1572if(git_hdr_len <0)1573return-128;1574if(git_hdr_len <= len)1575continue;1576if(!patch->old_name && !patch->new_name) {1577if(!patch->def_name) {1578error(Q_("git diff header lacks filename information when removing "1579"%dleading pathname component (line%d)",1580"git diff header lacks filename information when removing "1581"%dleading pathname components (line%d)",1582 state->p_value),1583 state->p_value, state->linenr);1584return-128;1585}1586 patch->old_name =xstrdup(patch->def_name);1587 patch->new_name =xstrdup(patch->def_name);1588}1589if(!patch->is_delete && !patch->new_name) {1590error(_("git diff header lacks filename information "1591"(line%d)"), state->linenr);1592return-128;1593}1594 patch->is_toplevel_relative =1;1595*hdrsize = git_hdr_len;1596return offset;1597}15981599/* --- followed by +++ ? */1600if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1601continue;16021603/*1604 * We only accept unified patches, so we want it to1605 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1606 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1607 */1608 nextlen =linelen(line + len, size - len);1609if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1610continue;16111612/* Ok, we'll consider it a patch */1613if(parse_traditional_patch(state, line, line+len, patch))1614return-128;1615*hdrsize = len + nextlen;1616 state->linenr +=2;1617return offset;1618}1619return-1;1620}16211622static voidrecord_ws_error(struct apply_state *state,1623unsigned result,1624const char*line,1625int len,1626int linenr)1627{1628char*err;16291630if(!result)1631return;16321633 state->whitespace_error++;1634if(state->squelch_whitespace_errors &&1635 state->squelch_whitespace_errors < state->whitespace_error)1636return;16371638 err =whitespace_error_string(result);1639if(state->apply_verbosity > verbosity_silent)1640fprintf(stderr,"%s:%d:%s.\n%.*s\n",1641 state->patch_input_file, linenr, err, len, line);1642free(err);1643}16441645static voidcheck_whitespace(struct apply_state *state,1646const char*line,1647int len,1648unsigned ws_rule)1649{1650unsigned result =ws_check(line +1, len -1, ws_rule);16511652record_ws_error(state, result, line +1, len -2, state->linenr);1653}16541655/*1656 * Parse a unified diff. Note that this really needs to parse each1657 * fragment separately, since the only way to know the difference1658 * between a "---" that is part of a patch, and a "---" that starts1659 * the next patch is to look at the line counts..1660 */1661static intparse_fragment(struct apply_state *state,1662const char*line,1663unsigned long size,1664struct patch *patch,1665struct fragment *fragment)1666{1667int added, deleted;1668int len =linelen(line, size), offset;1669unsigned long oldlines, newlines;1670unsigned long leading, trailing;16711672 offset =parse_fragment_header(line, len, fragment);1673if(offset <0)1674return-1;1675if(offset >0&& patch->recount)1676recount_diff(line + offset, size - offset, fragment);1677 oldlines = fragment->oldlines;1678 newlines = fragment->newlines;1679 leading =0;1680 trailing =0;16811682/* Parse the thing.. */1683 line += len;1684 size -= len;1685 state->linenr++;1686 added = deleted =0;1687for(offset = len;16880< size;1689 offset += len, size -= len, line += len, state->linenr++) {1690if(!oldlines && !newlines)1691break;1692 len =linelen(line, size);1693if(!len || line[len-1] !='\n')1694return-1;1695switch(*line) {1696default:1697return-1;1698case'\n':/* newer GNU diff, an empty context line */1699case' ':1700 oldlines--;1701 newlines--;1702if(!deleted && !added)1703 leading++;1704 trailing++;1705if(!state->apply_in_reverse &&1706 state->ws_error_action == correct_ws_error)1707check_whitespace(state, line, len, patch->ws_rule);1708break;1709case'-':1710if(state->apply_in_reverse &&1711 state->ws_error_action != nowarn_ws_error)1712check_whitespace(state, line, len, patch->ws_rule);1713 deleted++;1714 oldlines--;1715 trailing =0;1716break;1717case'+':1718if(!state->apply_in_reverse &&1719 state->ws_error_action != nowarn_ws_error)1720check_whitespace(state, line, len, patch->ws_rule);1721 added++;1722 newlines--;1723 trailing =0;1724break;17251726/*1727 * We allow "\ No newline at end of file". Depending1728 * on locale settings when the patch was produced we1729 * don't know what this line looks like. The only1730 * thing we do know is that it begins with "\ ".1731 * Checking for 12 is just for sanity check -- any1732 * l10n of "\ No newline..." is at least that long.1733 */1734case'\\':1735if(len <12||memcmp(line,"\\",2))1736return-1;1737break;1738}1739}1740if(oldlines || newlines)1741return-1;1742if(!deleted && !added)1743return-1;17441745 fragment->leading = leading;1746 fragment->trailing = trailing;17471748/*1749 * If a fragment ends with an incomplete line, we failed to include1750 * it in the above loop because we hit oldlines == newlines == 01751 * before seeing it.1752 */1753if(12< size && !memcmp(line,"\\",2))1754 offset +=linelen(line, size);17551756 patch->lines_added += added;1757 patch->lines_deleted += deleted;17581759if(0< patch->is_new && oldlines)1760returnerror(_("new file depends on old contents"));1761if(0< patch->is_delete && newlines)1762returnerror(_("deleted file still has contents"));1763return offset;1764}17651766/*1767 * We have seen "diff --git a/... b/..." header (or a traditional patch1768 * header). Read hunks that belong to this patch into fragments and hang1769 * them to the given patch structure.1770 *1771 * The (fragment->patch, fragment->size) pair points into the memory given1772 * by the caller, not a copy, when we return.1773 *1774 * Returns:1775 * -1 in case of error,1776 * the number of bytes in the patch otherwise.1777 */1778static intparse_single_patch(struct apply_state *state,1779const char*line,1780unsigned long size,1781struct patch *patch)1782{1783unsigned long offset =0;1784unsigned long oldlines =0, newlines =0, context =0;1785struct fragment **fragp = &patch->fragments;17861787while(size >4&& !memcmp(line,"@@ -",4)) {1788struct fragment *fragment;1789int len;17901791 fragment =xcalloc(1,sizeof(*fragment));1792 fragment->linenr = state->linenr;1793 len =parse_fragment(state, line, size, patch, fragment);1794if(len <=0) {1795free(fragment);1796returnerror(_("corrupt patch at line%d"), state->linenr);1797}1798 fragment->patch = line;1799 fragment->size = len;1800 oldlines += fragment->oldlines;1801 newlines += fragment->newlines;1802 context += fragment->leading + fragment->trailing;18031804*fragp = fragment;1805 fragp = &fragment->next;18061807 offset += len;1808 line += len;1809 size -= len;1810}18111812/*1813 * If something was removed (i.e. we have old-lines) it cannot1814 * be creation, and if something was added it cannot be1815 * deletion. However, the reverse is not true; --unified=01816 * patches that only add are not necessarily creation even1817 * though they do not have any old lines, and ones that only1818 * delete are not necessarily deletion.1819 *1820 * Unfortunately, a real creation/deletion patch do _not_ have1821 * any context line by definition, so we cannot safely tell it1822 * apart with --unified=0 insanity. At least if the patch has1823 * more than one hunk it is not creation or deletion.1824 */1825if(patch->is_new <0&&1826(oldlines || (patch->fragments && patch->fragments->next)))1827 patch->is_new =0;1828if(patch->is_delete <0&&1829(newlines || (patch->fragments && patch->fragments->next)))1830 patch->is_delete =0;18311832if(0< patch->is_new && oldlines)1833returnerror(_("new file%sdepends on old contents"), patch->new_name);1834if(0< patch->is_delete && newlines)1835returnerror(_("deleted file%sstill has contents"), patch->old_name);1836if(!patch->is_delete && !newlines && context && state->apply_verbosity > verbosity_silent)1837fprintf_ln(stderr,1838_("** warning: "1839"file%sbecomes empty but is not deleted"),1840 patch->new_name);18411842return offset;1843}18441845staticinlineintmetadata_changes(struct patch *patch)1846{1847return patch->is_rename >0||1848 patch->is_copy >0||1849 patch->is_new >0||1850 patch->is_delete ||1851(patch->old_mode && patch->new_mode &&1852 patch->old_mode != patch->new_mode);1853}18541855static char*inflate_it(const void*data,unsigned long size,1856unsigned long inflated_size)1857{1858 git_zstream stream;1859void*out;1860int st;18611862memset(&stream,0,sizeof(stream));18631864 stream.next_in = (unsigned char*)data;1865 stream.avail_in = size;1866 stream.next_out = out =xmalloc(inflated_size);1867 stream.avail_out = inflated_size;1868git_inflate_init(&stream);1869 st =git_inflate(&stream, Z_FINISH);1870git_inflate_end(&stream);1871if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1872free(out);1873return NULL;1874}1875return out;1876}18771878/*1879 * Read a binary hunk and return a new fragment; fragment->patch1880 * points at an allocated memory that the caller must free, so1881 * it is marked as "->free_patch = 1".1882 */1883static struct fragment *parse_binary_hunk(struct apply_state *state,1884char**buf_p,1885unsigned long*sz_p,1886int*status_p,1887int*used_p)1888{1889/*1890 * Expect a line that begins with binary patch method ("literal"1891 * or "delta"), followed by the length of data before deflating.1892 * a sequence of 'length-byte' followed by base-85 encoded data1893 * should follow, terminated by a newline.1894 *1895 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1896 * and we would limit the patch line to 66 characters,1897 * so one line can fit up to 13 groups that would decode1898 * to 52 bytes max. The length byte 'A'-'Z' corresponds1899 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1900 */1901int llen, used;1902unsigned long size = *sz_p;1903char*buffer = *buf_p;1904int patch_method;1905unsigned long origlen;1906char*data = NULL;1907int hunk_size =0;1908struct fragment *frag;19091910 llen =linelen(buffer, size);1911 used = llen;19121913*status_p =0;19141915if(starts_with(buffer,"delta ")) {1916 patch_method = BINARY_DELTA_DEFLATED;1917 origlen =strtoul(buffer +6, NULL,10);1918}1919else if(starts_with(buffer,"literal ")) {1920 patch_method = BINARY_LITERAL_DEFLATED;1921 origlen =strtoul(buffer +8, NULL,10);1922}1923else1924return NULL;19251926 state->linenr++;1927 buffer += llen;1928while(1) {1929int byte_length, max_byte_length, newsize;1930 llen =linelen(buffer, size);1931 used += llen;1932 state->linenr++;1933if(llen ==1) {1934/* consume the blank line */1935 buffer++;1936 size--;1937break;1938}1939/*1940 * Minimum line is "A00000\n" which is 7-byte long,1941 * and the line length must be multiple of 5 plus 2.1942 */1943if((llen <7) || (llen-2) %5)1944goto corrupt;1945 max_byte_length = (llen -2) /5*4;1946 byte_length = *buffer;1947if('A'<= byte_length && byte_length <='Z')1948 byte_length = byte_length -'A'+1;1949else if('a'<= byte_length && byte_length <='z')1950 byte_length = byte_length -'a'+27;1951else1952goto corrupt;1953/* if the input length was not multiple of 4, we would1954 * have filler at the end but the filler should never1955 * exceed 3 bytes1956 */1957if(max_byte_length < byte_length ||1958 byte_length <= max_byte_length -4)1959goto corrupt;1960 newsize = hunk_size + byte_length;1961 data =xrealloc(data, newsize);1962if(decode_85(data + hunk_size, buffer +1, byte_length))1963goto corrupt;1964 hunk_size = newsize;1965 buffer += llen;1966 size -= llen;1967}19681969 frag =xcalloc(1,sizeof(*frag));1970 frag->patch =inflate_it(data, hunk_size, origlen);1971 frag->free_patch =1;1972if(!frag->patch)1973goto corrupt;1974free(data);1975 frag->size = origlen;1976*buf_p = buffer;1977*sz_p = size;1978*used_p = used;1979 frag->binary_patch_method = patch_method;1980return frag;19811982 corrupt:1983free(data);1984*status_p = -1;1985error(_("corrupt binary patch at line%d: %.*s"),1986 state->linenr-1, llen-1, buffer);1987return NULL;1988}19891990/*1991 * Returns:1992 * -1 in case of error,1993 * the length of the parsed binary patch otherwise1994 */1995static intparse_binary(struct apply_state *state,1996char*buffer,1997unsigned long size,1998struct patch *patch)1999{2000/*2001 * We have read "GIT binary patch\n"; what follows is a line2002 * that says the patch method (currently, either "literal" or2003 * "delta") and the length of data before deflating; a2004 * sequence of 'length-byte' followed by base-85 encoded data2005 * follows.2006 *2007 * When a binary patch is reversible, there is another binary2008 * hunk in the same format, starting with patch method (either2009 * "literal" or "delta") with the length of data, and a sequence2010 * of length-byte + base-85 encoded data, terminated with another2011 * empty line. This data, when applied to the postimage, produces2012 * the preimage.2013 */2014struct fragment *forward;2015struct fragment *reverse;2016int status;2017int used, used_1;20182019 forward =parse_binary_hunk(state, &buffer, &size, &status, &used);2020if(!forward && !status)2021/* there has to be one hunk (forward hunk) */2022returnerror(_("unrecognized binary patch at line%d"), state->linenr-1);2023if(status)2024/* otherwise we already gave an error message */2025return status;20262027 reverse =parse_binary_hunk(state, &buffer, &size, &status, &used_1);2028if(reverse)2029 used += used_1;2030else if(status) {2031/*2032 * Not having reverse hunk is not an error, but having2033 * a corrupt reverse hunk is.2034 */2035free((void*) forward->patch);2036free(forward);2037return status;2038}2039 forward->next = reverse;2040 patch->fragments = forward;2041 patch->is_binary =1;2042return used;2043}20442045static voidprefix_one(struct apply_state *state,char**name)2046{2047char*old_name = *name;2048if(!old_name)2049return;2050*name =prefix_filename(state->prefix, *name);2051free(old_name);2052}20532054static voidprefix_patch(struct apply_state *state,struct patch *p)2055{2056if(!state->prefix || p->is_toplevel_relative)2057return;2058prefix_one(state, &p->new_name);2059prefix_one(state, &p->old_name);2060}20612062/*2063 * include/exclude2064 */20652066static voidadd_name_limit(struct apply_state *state,2067const char*name,2068int exclude)2069{2070struct string_list_item *it;20712072 it =string_list_append(&state->limit_by_name, name);2073 it->util = exclude ? NULL : (void*)1;2074}20752076static intuse_patch(struct apply_state *state,struct patch *p)2077{2078const char*pathname = p->new_name ? p->new_name : p->old_name;2079int i;20802081/* Paths outside are not touched regardless of "--include" */2082if(0< state->prefix_length) {2083int pathlen =strlen(pathname);2084if(pathlen <= state->prefix_length ||2085memcmp(state->prefix, pathname, state->prefix_length))2086return0;2087}20882089/* See if it matches any of exclude/include rule */2090for(i =0; i < state->limit_by_name.nr; i++) {2091struct string_list_item *it = &state->limit_by_name.items[i];2092if(!wildmatch(it->string, pathname,0, NULL))2093return(it->util != NULL);2094}20952096/*2097 * If we had any include, a path that does not match any rule is2098 * not used. Otherwise, we saw bunch of exclude rules (or none)2099 * and such a path is used.2100 */2101return!state->has_include;2102}21032104/*2105 * Read the patch text in "buffer" that extends for "size" bytes; stop2106 * reading after seeing a single patch (i.e. changes to a single file).2107 * Create fragments (i.e. patch hunks) and hang them to the given patch.2108 *2109 * Returns:2110 * -1 if no header was found or parse_binary() failed,2111 * -128 on another error,2112 * the number of bytes consumed otherwise,2113 * so that the caller can call us again for the next patch.2114 */2115static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2116{2117int hdrsize, patchsize;2118int offset =find_header(state, buffer, size, &hdrsize, patch);21192120if(offset <0)2121return offset;21222123prefix_patch(state, patch);21242125if(!use_patch(state, patch))2126 patch->ws_rule =0;2127else2128 patch->ws_rule =whitespace_rule(patch->new_name2129? patch->new_name2130: patch->old_name);21312132 patchsize =parse_single_patch(state,2133 buffer + offset + hdrsize,2134 size - offset - hdrsize,2135 patch);21362137if(patchsize <0)2138return-128;21392140if(!patchsize) {2141static const char git_binary[] ="GIT binary patch\n";2142int hd = hdrsize + offset;2143unsigned long llen =linelen(buffer + hd, size - hd);21442145if(llen ==sizeof(git_binary) -1&&2146!memcmp(git_binary, buffer + hd, llen)) {2147int used;2148 state->linenr++;2149 used =parse_binary(state, buffer + hd + llen,2150 size - hd - llen, patch);2151if(used <0)2152return-1;2153if(used)2154 patchsize = used + llen;2155else2156 patchsize =0;2157}2158else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2159static const char*binhdr[] = {2160"Binary files ",2161"Files ",2162 NULL,2163};2164int i;2165for(i =0; binhdr[i]; i++) {2166int len =strlen(binhdr[i]);2167if(len < size - hd &&2168!memcmp(binhdr[i], buffer + hd, len)) {2169 state->linenr++;2170 patch->is_binary =1;2171 patchsize = llen;2172break;2173}2174}2175}21762177/* Empty patch cannot be applied if it is a text patch2178 * without metadata change. A binary patch appears2179 * empty to us here.2180 */2181if((state->apply || state->check) &&2182(!patch->is_binary && !metadata_changes(patch))) {2183error(_("patch with only garbage at line%d"), state->linenr);2184return-128;2185}2186}21872188return offset + hdrsize + patchsize;2189}21902191static voidreverse_patches(struct patch *p)2192{2193for(; p; p = p->next) {2194struct fragment *frag = p->fragments;21952196SWAP(p->new_name, p->old_name);2197SWAP(p->new_mode, p->old_mode);2198SWAP(p->is_new, p->is_delete);2199SWAP(p->lines_added, p->lines_deleted);2200SWAP(p->old_sha1_prefix, p->new_sha1_prefix);22012202for(; frag; frag = frag->next) {2203SWAP(frag->newpos, frag->oldpos);2204SWAP(frag->newlines, frag->oldlines);2205}2206}2207}22082209static const char pluses[] =2210"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2211static const char minuses[]=2212"----------------------------------------------------------------------";22132214static voidshow_stats(struct apply_state *state,struct patch *patch)2215{2216struct strbuf qname = STRBUF_INIT;2217char*cp = patch->new_name ? patch->new_name : patch->old_name;2218int max, add, del;22192220quote_c_style(cp, &qname, NULL,0);22212222/*2223 * "scale" the filename2224 */2225 max = state->max_len;2226if(max >50)2227 max =50;22282229if(qname.len > max) {2230 cp =strchr(qname.buf + qname.len +3- max,'/');2231if(!cp)2232 cp = qname.buf + qname.len +3- max;2233strbuf_splice(&qname,0, cp - qname.buf,"...",3);2234}22352236if(patch->is_binary) {2237printf(" %-*s | Bin\n", max, qname.buf);2238strbuf_release(&qname);2239return;2240}22412242printf(" %-*s |", max, qname.buf);2243strbuf_release(&qname);22442245/*2246 * scale the add/delete2247 */2248 max = max + state->max_change >70?70- max : state->max_change;2249 add = patch->lines_added;2250 del = patch->lines_deleted;22512252if(state->max_change >0) {2253int total = ((add + del) * max + state->max_change /2) / state->max_change;2254 add = (add * max + state->max_change /2) / state->max_change;2255 del = total - add;2256}2257printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2258 add, pluses, del, minuses);2259}22602261static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2262{2263switch(st->st_mode & S_IFMT) {2264case S_IFLNK:2265if(strbuf_readlink(buf, path, st->st_size) <0)2266returnerror(_("unable to read symlink%s"), path);2267return0;2268case S_IFREG:2269if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2270returnerror(_("unable to open or read%s"), path);2271convert_to_git(&the_index, path, buf->buf, buf->len, buf,0);2272return0;2273default:2274return-1;2275}2276}22772278/*2279 * Update the preimage, and the common lines in postimage,2280 * from buffer buf of length len. If postlen is 0 the postimage2281 * is updated in place, otherwise it's updated on a new buffer2282 * of length postlen2283 */22842285static voidupdate_pre_post_images(struct image *preimage,2286struct image *postimage,2287char*buf,2288size_t len,size_t postlen)2289{2290int i, ctx, reduced;2291char*new, *old, *fixed;2292struct image fixed_preimage;22932294/*2295 * Update the preimage with whitespace fixes. Note that we2296 * are not losing preimage->buf -- apply_one_fragment() will2297 * free "oldlines".2298 */2299prepare_image(&fixed_preimage, buf, len,1);2300assert(postlen2301? fixed_preimage.nr == preimage->nr2302: fixed_preimage.nr <= preimage->nr);2303for(i =0; i < fixed_preimage.nr; i++)2304 fixed_preimage.line[i].flag = preimage->line[i].flag;2305free(preimage->line_allocated);2306*preimage = fixed_preimage;23072308/*2309 * Adjust the common context lines in postimage. This can be2310 * done in-place when we are shrinking it with whitespace2311 * fixing, but needs a new buffer when ignoring whitespace or2312 * expanding leading tabs to spaces.2313 *2314 * We trust the caller to tell us if the update can be done2315 * in place (postlen==0) or not.2316 */2317 old = postimage->buf;2318if(postlen)2319new= postimage->buf =xmalloc(postlen);2320else2321new= old;2322 fixed = preimage->buf;23232324for(i = reduced = ctx =0; i < postimage->nr; i++) {2325size_t l_len = postimage->line[i].len;2326if(!(postimage->line[i].flag & LINE_COMMON)) {2327/* an added line -- no counterparts in preimage */2328memmove(new, old, l_len);2329 old += l_len;2330new+= l_len;2331continue;2332}23332334/* a common context -- skip it in the original postimage */2335 old += l_len;23362337/* and find the corresponding one in the fixed preimage */2338while(ctx < preimage->nr &&2339!(preimage->line[ctx].flag & LINE_COMMON)) {2340 fixed += preimage->line[ctx].len;2341 ctx++;2342}23432344/*2345 * preimage is expected to run out, if the caller2346 * fixed addition of trailing blank lines.2347 */2348if(preimage->nr <= ctx) {2349 reduced++;2350continue;2351}23522353/* and copy it in, while fixing the line length */2354 l_len = preimage->line[ctx].len;2355memcpy(new, fixed, l_len);2356new+= l_len;2357 fixed += l_len;2358 postimage->line[i].len = l_len;2359 ctx++;2360}23612362if(postlen2363? postlen <new- postimage->buf2364: postimage->len <new- postimage->buf)2365die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2366(int)postlen, (int) postimage->len, (int)(new- postimage->buf));23672368/* Fix the length of the whole thing */2369 postimage->len =new- postimage->buf;2370 postimage->nr -= reduced;2371}23722373static intline_by_line_fuzzy_match(struct image *img,2374struct image *preimage,2375struct image *postimage,2376unsigned longtry,2377int try_lno,2378int preimage_limit)2379{2380int i;2381size_t imgoff =0;2382size_t preoff =0;2383size_t postlen = postimage->len;2384size_t extra_chars;2385char*buf;2386char*preimage_eof;2387char*preimage_end;2388struct strbuf fixed;2389char*fixed_buf;2390size_t fixed_len;23912392for(i =0; i < preimage_limit; i++) {2393size_t prelen = preimage->line[i].len;2394size_t imglen = img->line[try_lno+i].len;23952396if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2397 preimage->buf + preoff, prelen))2398return0;2399if(preimage->line[i].flag & LINE_COMMON)2400 postlen += imglen - prelen;2401 imgoff += imglen;2402 preoff += prelen;2403}24042405/*2406 * Ok, the preimage matches with whitespace fuzz.2407 *2408 * imgoff now holds the true length of the target that2409 * matches the preimage before the end of the file.2410 *2411 * Count the number of characters in the preimage that fall2412 * beyond the end of the file and make sure that all of them2413 * are whitespace characters. (This can only happen if2414 * we are removing blank lines at the end of the file.)2415 */2416 buf = preimage_eof = preimage->buf + preoff;2417for( ; i < preimage->nr; i++)2418 preoff += preimage->line[i].len;2419 preimage_end = preimage->buf + preoff;2420for( ; buf < preimage_end; buf++)2421if(!isspace(*buf))2422return0;24232424/*2425 * Update the preimage and the common postimage context2426 * lines to use the same whitespace as the target.2427 * If whitespace is missing in the target (i.e.2428 * if the preimage extends beyond the end of the file),2429 * use the whitespace from the preimage.2430 */2431 extra_chars = preimage_end - preimage_eof;2432strbuf_init(&fixed, imgoff + extra_chars);2433strbuf_add(&fixed, img->buf +try, imgoff);2434strbuf_add(&fixed, preimage_eof, extra_chars);2435 fixed_buf =strbuf_detach(&fixed, &fixed_len);2436update_pre_post_images(preimage, postimage,2437 fixed_buf, fixed_len, postlen);2438return1;2439}24402441static intmatch_fragment(struct apply_state *state,2442struct image *img,2443struct image *preimage,2444struct image *postimage,2445unsigned longtry,2446int try_lno,2447unsigned ws_rule,2448int match_beginning,int match_end)2449{2450int i;2451char*fixed_buf, *buf, *orig, *target;2452struct strbuf fixed;2453size_t fixed_len, postlen;2454int preimage_limit;24552456if(preimage->nr + try_lno <= img->nr) {2457/*2458 * The hunk falls within the boundaries of img.2459 */2460 preimage_limit = preimage->nr;2461if(match_end && (preimage->nr + try_lno != img->nr))2462return0;2463}else if(state->ws_error_action == correct_ws_error &&2464(ws_rule & WS_BLANK_AT_EOF)) {2465/*2466 * This hunk extends beyond the end of img, and we are2467 * removing blank lines at the end of the file. This2468 * many lines from the beginning of the preimage must2469 * match with img, and the remainder of the preimage2470 * must be blank.2471 */2472 preimage_limit = img->nr - try_lno;2473}else{2474/*2475 * The hunk extends beyond the end of the img and2476 * we are not removing blanks at the end, so we2477 * should reject the hunk at this position.2478 */2479return0;2480}24812482if(match_beginning && try_lno)2483return0;24842485/* Quick hash check */2486for(i =0; i < preimage_limit; i++)2487if((img->line[try_lno + i].flag & LINE_PATCHED) ||2488(preimage->line[i].hash != img->line[try_lno + i].hash))2489return0;24902491if(preimage_limit == preimage->nr) {2492/*2493 * Do we have an exact match? If we were told to match2494 * at the end, size must be exactly at try+fragsize,2495 * otherwise try+fragsize must be still within the preimage,2496 * and either case, the old piece should match the preimage2497 * exactly.2498 */2499if((match_end2500? (try+ preimage->len == img->len)2501: (try+ preimage->len <= img->len)) &&2502!memcmp(img->buf +try, preimage->buf, preimage->len))2503return1;2504}else{2505/*2506 * The preimage extends beyond the end of img, so2507 * there cannot be an exact match.2508 *2509 * There must be one non-blank context line that match2510 * a line before the end of img.2511 */2512char*buf_end;25132514 buf = preimage->buf;2515 buf_end = buf;2516for(i =0; i < preimage_limit; i++)2517 buf_end += preimage->line[i].len;25182519for( ; buf < buf_end; buf++)2520if(!isspace(*buf))2521break;2522if(buf == buf_end)2523return0;2524}25252526/*2527 * No exact match. If we are ignoring whitespace, run a line-by-line2528 * fuzzy matching. We collect all the line length information because2529 * we need it to adjust whitespace if we match.2530 */2531if(state->ws_ignore_action == ignore_ws_change)2532returnline_by_line_fuzzy_match(img, preimage, postimage,2533try, try_lno, preimage_limit);25342535if(state->ws_error_action != correct_ws_error)2536return0;25372538/*2539 * The hunk does not apply byte-by-byte, but the hash says2540 * it might with whitespace fuzz. We weren't asked to2541 * ignore whitespace, we were asked to correct whitespace2542 * errors, so let's try matching after whitespace correction.2543 *2544 * While checking the preimage against the target, whitespace2545 * errors in both fixed, we count how large the corresponding2546 * postimage needs to be. The postimage prepared by2547 * apply_one_fragment() has whitespace errors fixed on added2548 * lines already, but the common lines were propagated as-is,2549 * which may become longer when their whitespace errors are2550 * fixed.2551 */25522553/* First count added lines in postimage */2554 postlen =0;2555for(i =0; i < postimage->nr; i++) {2556if(!(postimage->line[i].flag & LINE_COMMON))2557 postlen += postimage->line[i].len;2558}25592560/*2561 * The preimage may extend beyond the end of the file,2562 * but in this loop we will only handle the part of the2563 * preimage that falls within the file.2564 */2565strbuf_init(&fixed, preimage->len +1);2566 orig = preimage->buf;2567 target = img->buf +try;2568for(i =0; i < preimage_limit; i++) {2569size_t oldlen = preimage->line[i].len;2570size_t tgtlen = img->line[try_lno + i].len;2571size_t fixstart = fixed.len;2572struct strbuf tgtfix;2573int match;25742575/* Try fixing the line in the preimage */2576ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25772578/* Try fixing the line in the target */2579strbuf_init(&tgtfix, tgtlen);2580ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);25812582/*2583 * If they match, either the preimage was based on2584 * a version before our tree fixed whitespace breakage,2585 * or we are lacking a whitespace-fix patch the tree2586 * the preimage was based on already had (i.e. target2587 * has whitespace breakage, the preimage doesn't).2588 * In either case, we are fixing the whitespace breakages2589 * so we might as well take the fix together with their2590 * real change.2591 */2592 match = (tgtfix.len == fixed.len - fixstart &&2593!memcmp(tgtfix.buf, fixed.buf + fixstart,2594 fixed.len - fixstart));25952596/* Add the length if this is common with the postimage */2597if(preimage->line[i].flag & LINE_COMMON)2598 postlen += tgtfix.len;25992600strbuf_release(&tgtfix);2601if(!match)2602goto unmatch_exit;26032604 orig += oldlen;2605 target += tgtlen;2606}260726082609/*2610 * Now handle the lines in the preimage that falls beyond the2611 * end of the file (if any). They will only match if they are2612 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2613 * false).2614 */2615for( ; i < preimage->nr; i++) {2616size_t fixstart = fixed.len;/* start of the fixed preimage */2617size_t oldlen = preimage->line[i].len;2618int j;26192620/* Try fixing the line in the preimage */2621ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);26222623for(j = fixstart; j < fixed.len; j++)2624if(!isspace(fixed.buf[j]))2625goto unmatch_exit;26262627 orig += oldlen;2628}26292630/*2631 * Yes, the preimage is based on an older version that still2632 * has whitespace breakages unfixed, and fixing them makes the2633 * hunk match. Update the context lines in the postimage.2634 */2635 fixed_buf =strbuf_detach(&fixed, &fixed_len);2636if(postlen < postimage->len)2637 postlen =0;2638update_pre_post_images(preimage, postimage,2639 fixed_buf, fixed_len, postlen);2640return1;26412642 unmatch_exit:2643strbuf_release(&fixed);2644return0;2645}26462647static intfind_pos(struct apply_state *state,2648struct image *img,2649struct image *preimage,2650struct image *postimage,2651int line,2652unsigned ws_rule,2653int match_beginning,int match_end)2654{2655int i;2656unsigned long backwards, forwards,try;2657int backwards_lno, forwards_lno, try_lno;26582659/*2660 * If match_beginning or match_end is specified, there is no2661 * point starting from a wrong line that will never match and2662 * wander around and wait for a match at the specified end.2663 */2664if(match_beginning)2665 line =0;2666else if(match_end)2667 line = img->nr - preimage->nr;26682669/*2670 * Because the comparison is unsigned, the following test2671 * will also take care of a negative line number that can2672 * result when match_end and preimage is larger than the target.2673 */2674if((size_t) line > img->nr)2675 line = img->nr;26762677try=0;2678for(i =0; i < line; i++)2679try+= img->line[i].len;26802681/*2682 * There's probably some smart way to do this, but I'll leave2683 * that to the smart and beautiful people. I'm simple and stupid.2684 */2685 backwards =try;2686 backwards_lno = line;2687 forwards =try;2688 forwards_lno = line;2689 try_lno = line;26902691for(i =0; ; i++) {2692if(match_fragment(state, img, preimage, postimage,2693try, try_lno, ws_rule,2694 match_beginning, match_end))2695return try_lno;26962697 again:2698if(backwards_lno ==0&& forwards_lno == img->nr)2699break;27002701if(i &1) {2702if(backwards_lno ==0) {2703 i++;2704goto again;2705}2706 backwards_lno--;2707 backwards -= img->line[backwards_lno].len;2708try= backwards;2709 try_lno = backwards_lno;2710}else{2711if(forwards_lno == img->nr) {2712 i++;2713goto again;2714}2715 forwards += img->line[forwards_lno].len;2716 forwards_lno++;2717try= forwards;2718 try_lno = forwards_lno;2719}27202721}2722return-1;2723}27242725static voidremove_first_line(struct image *img)2726{2727 img->buf += img->line[0].len;2728 img->len -= img->line[0].len;2729 img->line++;2730 img->nr--;2731}27322733static voidremove_last_line(struct image *img)2734{2735 img->len -= img->line[--img->nr].len;2736}27372738/*2739 * The change from "preimage" and "postimage" has been found to2740 * apply at applied_pos (counts in line numbers) in "img".2741 * Update "img" to remove "preimage" and replace it with "postimage".2742 */2743static voidupdate_image(struct apply_state *state,2744struct image *img,2745int applied_pos,2746struct image *preimage,2747struct image *postimage)2748{2749/*2750 * remove the copy of preimage at offset in img2751 * and replace it with postimage2752 */2753int i, nr;2754size_t remove_count, insert_count, applied_at =0;2755char*result;2756int preimage_limit;27572758/*2759 * If we are removing blank lines at the end of img,2760 * the preimage may extend beyond the end.2761 * If that is the case, we must be careful only to2762 * remove the part of the preimage that falls within2763 * the boundaries of img. Initialize preimage_limit2764 * to the number of lines in the preimage that falls2765 * within the boundaries.2766 */2767 preimage_limit = preimage->nr;2768if(preimage_limit > img->nr - applied_pos)2769 preimage_limit = img->nr - applied_pos;27702771for(i =0; i < applied_pos; i++)2772 applied_at += img->line[i].len;27732774 remove_count =0;2775for(i =0; i < preimage_limit; i++)2776 remove_count += img->line[applied_pos + i].len;2777 insert_count = postimage->len;27782779/* Adjust the contents */2780 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2781memcpy(result, img->buf, applied_at);2782memcpy(result + applied_at, postimage->buf, postimage->len);2783memcpy(result + applied_at + postimage->len,2784 img->buf + (applied_at + remove_count),2785 img->len - (applied_at + remove_count));2786free(img->buf);2787 img->buf = result;2788 img->len += insert_count - remove_count;2789 result[img->len] ='\0';27902791/* Adjust the line table */2792 nr = img->nr + postimage->nr - preimage_limit;2793if(preimage_limit < postimage->nr) {2794/*2795 * NOTE: this knows that we never call remove_first_line()2796 * on anything other than pre/post image.2797 */2798REALLOC_ARRAY(img->line, nr);2799 img->line_allocated = img->line;2800}2801if(preimage_limit != postimage->nr)2802memmove(img->line + applied_pos + postimage->nr,2803 img->line + applied_pos + preimage_limit,2804(img->nr - (applied_pos + preimage_limit)) *2805sizeof(*img->line));2806memcpy(img->line + applied_pos,2807 postimage->line,2808 postimage->nr *sizeof(*img->line));2809if(!state->allow_overlap)2810for(i =0; i < postimage->nr; i++)2811 img->line[applied_pos + i].flag |= LINE_PATCHED;2812 img->nr = nr;2813}28142815/*2816 * Use the patch-hunk text in "frag" to prepare two images (preimage and2817 * postimage) for the hunk. Find lines that match "preimage" in "img" and2818 * replace the part of "img" with "postimage" text.2819 */2820static intapply_one_fragment(struct apply_state *state,2821struct image *img,struct fragment *frag,2822int inaccurate_eof,unsigned ws_rule,2823int nth_fragment)2824{2825int match_beginning, match_end;2826const char*patch = frag->patch;2827int size = frag->size;2828char*old, *oldlines;2829struct strbuf newlines;2830int new_blank_lines_at_end =0;2831int found_new_blank_lines_at_end =0;2832int hunk_linenr = frag->linenr;2833unsigned long leading, trailing;2834int pos, applied_pos;2835struct image preimage;2836struct image postimage;28372838memset(&preimage,0,sizeof(preimage));2839memset(&postimage,0,sizeof(postimage));2840 oldlines =xmalloc(size);2841strbuf_init(&newlines, size);28422843 old = oldlines;2844while(size >0) {2845char first;2846int len =linelen(patch, size);2847int plen;2848int added_blank_line =0;2849int is_blank_context =0;2850size_t start;28512852if(!len)2853break;28542855/*2856 * "plen" is how much of the line we should use for2857 * the actual patch data. Normally we just remove the2858 * first character on the line, but if the line is2859 * followed by "\ No newline", then we also remove the2860 * last one (which is the newline, of course).2861 */2862 plen = len -1;2863if(len < size && patch[len] =='\\')2864 plen--;2865 first = *patch;2866if(state->apply_in_reverse) {2867if(first =='-')2868 first ='+';2869else if(first =='+')2870 first ='-';2871}28722873switch(first) {2874case'\n':2875/* Newer GNU diff, empty context line */2876if(plen <0)2877/* ... followed by '\No newline'; nothing */2878break;2879*old++ ='\n';2880strbuf_addch(&newlines,'\n');2881add_line_info(&preimage,"\n",1, LINE_COMMON);2882add_line_info(&postimage,"\n",1, LINE_COMMON);2883 is_blank_context =1;2884break;2885case' ':2886if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2887ws_blank_line(patch +1, plen, ws_rule))2888 is_blank_context =1;2889case'-':2890memcpy(old, patch +1, plen);2891add_line_info(&preimage, old, plen,2892(first ==' '? LINE_COMMON :0));2893 old += plen;2894if(first =='-')2895break;2896/* Fall-through for ' ' */2897case'+':2898/* --no-add does not add new lines */2899if(first =='+'&& state->no_add)2900break;29012902 start = newlines.len;2903if(first !='+'||2904!state->whitespace_error ||2905 state->ws_error_action != correct_ws_error) {2906strbuf_add(&newlines, patch +1, plen);2907}2908else{2909ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2910}2911add_line_info(&postimage, newlines.buf + start, newlines.len - start,2912(first =='+'?0: LINE_COMMON));2913if(first =='+'&&2914(ws_rule & WS_BLANK_AT_EOF) &&2915ws_blank_line(patch +1, plen, ws_rule))2916 added_blank_line =1;2917break;2918case'@':case'\\':2919/* Ignore it, we already handled it */2920break;2921default:2922if(state->apply_verbosity > verbosity_normal)2923error(_("invalid start of line: '%c'"), first);2924 applied_pos = -1;2925goto out;2926}2927if(added_blank_line) {2928if(!new_blank_lines_at_end)2929 found_new_blank_lines_at_end = hunk_linenr;2930 new_blank_lines_at_end++;2931}2932else if(is_blank_context)2933;2934else2935 new_blank_lines_at_end =0;2936 patch += len;2937 size -= len;2938 hunk_linenr++;2939}2940if(inaccurate_eof &&2941 old > oldlines && old[-1] =='\n'&&2942 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2943 old--;2944strbuf_setlen(&newlines, newlines.len -1);2945}29462947 leading = frag->leading;2948 trailing = frag->trailing;29492950/*2951 * A hunk to change lines at the beginning would begin with2952 * @@ -1,L +N,M @@2953 * but we need to be careful. -U0 that inserts before the second2954 * line also has this pattern.2955 *2956 * And a hunk to add to an empty file would begin with2957 * @@ -0,0 +N,M @@2958 *2959 * In other words, a hunk that is (frag->oldpos <= 1) with or2960 * without leading context must match at the beginning.2961 */2962 match_beginning = (!frag->oldpos ||2963(frag->oldpos ==1&& !state->unidiff_zero));29642965/*2966 * A hunk without trailing lines must match at the end.2967 * However, we simply cannot tell if a hunk must match end2968 * from the lack of trailing lines if the patch was generated2969 * with unidiff without any context.2970 */2971 match_end = !state->unidiff_zero && !trailing;29722973 pos = frag->newpos ? (frag->newpos -1) :0;2974 preimage.buf = oldlines;2975 preimage.len = old - oldlines;2976 postimage.buf = newlines.buf;2977 postimage.len = newlines.len;2978 preimage.line = preimage.line_allocated;2979 postimage.line = postimage.line_allocated;29802981for(;;) {29822983 applied_pos =find_pos(state, img, &preimage, &postimage, pos,2984 ws_rule, match_beginning, match_end);29852986if(applied_pos >=0)2987break;29882989/* Am I at my context limits? */2990if((leading <= state->p_context) && (trailing <= state->p_context))2991break;2992if(match_beginning || match_end) {2993 match_beginning = match_end =0;2994continue;2995}29962997/*2998 * Reduce the number of context lines; reduce both2999 * leading and trailing if they are equal otherwise3000 * just reduce the larger context.3001 */3002if(leading >= trailing) {3003remove_first_line(&preimage);3004remove_first_line(&postimage);3005 pos--;3006 leading--;3007}3008if(trailing > leading) {3009remove_last_line(&preimage);3010remove_last_line(&postimage);3011 trailing--;3012}3013}30143015if(applied_pos >=0) {3016if(new_blank_lines_at_end &&3017 preimage.nr + applied_pos >= img->nr &&3018(ws_rule & WS_BLANK_AT_EOF) &&3019 state->ws_error_action != nowarn_ws_error) {3020record_ws_error(state, WS_BLANK_AT_EOF,"+",1,3021 found_new_blank_lines_at_end);3022if(state->ws_error_action == correct_ws_error) {3023while(new_blank_lines_at_end--)3024remove_last_line(&postimage);3025}3026/*3027 * We would want to prevent write_out_results()3028 * from taking place in apply_patch() that follows3029 * the callchain led us here, which is:3030 * apply_patch->check_patch_list->check_patch->3031 * apply_data->apply_fragments->apply_one_fragment3032 */3033if(state->ws_error_action == die_on_ws_error)3034 state->apply =0;3035}30363037if(state->apply_verbosity > verbosity_normal && applied_pos != pos) {3038int offset = applied_pos - pos;3039if(state->apply_in_reverse)3040 offset =0- offset;3041fprintf_ln(stderr,3042Q_("Hunk #%dsucceeded at%d(offset%dline).",3043"Hunk #%dsucceeded at%d(offset%dlines).",3044 offset),3045 nth_fragment, applied_pos +1, offset);3046}30473048/*3049 * Warn if it was necessary to reduce the number3050 * of context lines.3051 */3052if((leading != frag->leading ||3053 trailing != frag->trailing) && state->apply_verbosity > verbosity_silent)3054fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"3055" to apply fragment at%d"),3056 leading, trailing, applied_pos+1);3057update_image(state, img, applied_pos, &preimage, &postimage);3058}else{3059if(state->apply_verbosity > verbosity_normal)3060error(_("while searching for:\n%.*s"),3061(int)(old - oldlines), oldlines);3062}30633064out:3065free(oldlines);3066strbuf_release(&newlines);3067free(preimage.line_allocated);3068free(postimage.line_allocated);30693070return(applied_pos <0);3071}30723073static intapply_binary_fragment(struct apply_state *state,3074struct image *img,3075struct patch *patch)3076{3077struct fragment *fragment = patch->fragments;3078unsigned long len;3079void*dst;30803081if(!fragment)3082returnerror(_("missing binary patch data for '%s'"),3083 patch->new_name ?3084 patch->new_name :3085 patch->old_name);30863087/* Binary patch is irreversible without the optional second hunk */3088if(state->apply_in_reverse) {3089if(!fragment->next)3090returnerror(_("cannot reverse-apply a binary patch "3091"without the reverse hunk to '%s'"),3092 patch->new_name3093? patch->new_name : patch->old_name);3094 fragment = fragment->next;3095}3096switch(fragment->binary_patch_method) {3097case BINARY_DELTA_DEFLATED:3098 dst =patch_delta(img->buf, img->len, fragment->patch,3099 fragment->size, &len);3100if(!dst)3101return-1;3102clear_image(img);3103 img->buf = dst;3104 img->len = len;3105return0;3106case BINARY_LITERAL_DEFLATED:3107clear_image(img);3108 img->len = fragment->size;3109 img->buf =xmemdupz(fragment->patch, img->len);3110return0;3111}3112return-1;3113}31143115/*3116 * Replace "img" with the result of applying the binary patch.3117 * The binary patch data itself in patch->fragment is still kept3118 * but the preimage prepared by the caller in "img" is freed here3119 * or in the helper function apply_binary_fragment() this calls.3120 */3121static intapply_binary(struct apply_state *state,3122struct image *img,3123struct patch *patch)3124{3125const char*name = patch->old_name ? patch->old_name : patch->new_name;3126struct object_id oid;31273128/*3129 * For safety, we require patch index line to contain3130 * full 40-byte textual SHA1 for old and new, at least for now.3131 */3132if(strlen(patch->old_sha1_prefix) !=40||3133strlen(patch->new_sha1_prefix) !=40||3134get_oid_hex(patch->old_sha1_prefix, &oid) ||3135get_oid_hex(patch->new_sha1_prefix, &oid))3136returnerror(_("cannot apply binary patch to '%s' "3137"without full index line"), name);31383139if(patch->old_name) {3140/*3141 * See if the old one matches what the patch3142 * applies to.3143 */3144hash_sha1_file(img->buf, img->len, blob_type, oid.hash);3145if(strcmp(oid_to_hex(&oid), patch->old_sha1_prefix))3146returnerror(_("the patch applies to '%s' (%s), "3147"which does not match the "3148"current contents."),3149 name,oid_to_hex(&oid));3150}3151else{3152/* Otherwise, the old one must be empty. */3153if(img->len)3154returnerror(_("the patch applies to an empty "3155"'%s' but it is not empty"), name);3156}31573158get_oid_hex(patch->new_sha1_prefix, &oid);3159if(is_null_oid(&oid)) {3160clear_image(img);3161return0;/* deletion patch */3162}31633164if(has_sha1_file(oid.hash)) {3165/* We already have the postimage */3166enum object_type type;3167unsigned long size;3168char*result;31693170 result =read_sha1_file(oid.hash, &type, &size);3171if(!result)3172returnerror(_("the necessary postimage%sfor "3173"'%s' cannot be read"),3174 patch->new_sha1_prefix, name);3175clear_image(img);3176 img->buf = result;3177 img->len = size;3178}else{3179/*3180 * We have verified buf matches the preimage;3181 * apply the patch data to it, which is stored3182 * in the patch->fragments->{patch,size}.3183 */3184if(apply_binary_fragment(state, img, patch))3185returnerror(_("binary patch does not apply to '%s'"),3186 name);31873188/* verify that the result matches */3189hash_sha1_file(img->buf, img->len, blob_type, oid.hash);3190if(strcmp(oid_to_hex(&oid), patch->new_sha1_prefix))3191returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3192 name, patch->new_sha1_prefix,oid_to_hex(&oid));3193}31943195return0;3196}31973198static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3199{3200struct fragment *frag = patch->fragments;3201const char*name = patch->old_name ? patch->old_name : patch->new_name;3202unsigned ws_rule = patch->ws_rule;3203unsigned inaccurate_eof = patch->inaccurate_eof;3204int nth =0;32053206if(patch->is_binary)3207returnapply_binary(state, img, patch);32083209while(frag) {3210 nth++;3211if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3212error(_("patch failed:%s:%ld"), name, frag->oldpos);3213if(!state->apply_with_reject)3214return-1;3215 frag->rejected =1;3216}3217 frag = frag->next;3218}3219return0;3220}32213222static intread_blob_object(struct strbuf *buf,const struct object_id *oid,unsigned mode)3223{3224if(S_ISGITLINK(mode)) {3225strbuf_grow(buf,100);3226strbuf_addf(buf,"Subproject commit%s\n",oid_to_hex(oid));3227}else{3228enum object_type type;3229unsigned long sz;3230char*result;32313232 result =read_sha1_file(oid->hash, &type, &sz);3233if(!result)3234return-1;3235/* XXX read_sha1_file NUL-terminates */3236strbuf_attach(buf, result, sz, sz +1);3237}3238return0;3239}32403241static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3242{3243if(!ce)3244return0;3245returnread_blob_object(buf, &ce->oid, ce->ce_mode);3246}32473248static struct patch *in_fn_table(struct apply_state *state,const char*name)3249{3250struct string_list_item *item;32513252if(name == NULL)3253return NULL;32543255 item =string_list_lookup(&state->fn_table, name);3256if(item != NULL)3257return(struct patch *)item->util;32583259return NULL;3260}32613262/*3263 * item->util in the filename table records the status of the path.3264 * Usually it points at a patch (whose result records the contents3265 * of it after applying it), but it could be PATH_WAS_DELETED for a3266 * path that a previously applied patch has already removed, or3267 * PATH_TO_BE_DELETED for a path that a later patch would remove.3268 *3269 * The latter is needed to deal with a case where two paths A and B3270 * are swapped by first renaming A to B and then renaming B to A;3271 * moving A to B should not be prevented due to presence of B as we3272 * will remove it in a later patch.3273 */3274#define PATH_TO_BE_DELETED ((struct patch *) -2)3275#define PATH_WAS_DELETED ((struct patch *) -1)32763277static intto_be_deleted(struct patch *patch)3278{3279return patch == PATH_TO_BE_DELETED;3280}32813282static intwas_deleted(struct patch *patch)3283{3284return patch == PATH_WAS_DELETED;3285}32863287static voidadd_to_fn_table(struct apply_state *state,struct patch *patch)3288{3289struct string_list_item *item;32903291/*3292 * Always add new_name unless patch is a deletion3293 * This should cover the cases for normal diffs,3294 * file creations and copies3295 */3296if(patch->new_name != NULL) {3297 item =string_list_insert(&state->fn_table, patch->new_name);3298 item->util = patch;3299}33003301/*3302 * store a failure on rename/deletion cases because3303 * later chunks shouldn't patch old names3304 */3305if((patch->new_name == NULL) || (patch->is_rename)) {3306 item =string_list_insert(&state->fn_table, patch->old_name);3307 item->util = PATH_WAS_DELETED;3308}3309}33103311static voidprepare_fn_table(struct apply_state *state,struct patch *patch)3312{3313/*3314 * store information about incoming file deletion3315 */3316while(patch) {3317if((patch->new_name == NULL) || (patch->is_rename)) {3318struct string_list_item *item;3319 item =string_list_insert(&state->fn_table, patch->old_name);3320 item->util = PATH_TO_BE_DELETED;3321}3322 patch = patch->next;3323}3324}33253326static intcheckout_target(struct index_state *istate,3327struct cache_entry *ce,struct stat *st)3328{3329struct checkout costate = CHECKOUT_INIT;33303331 costate.refresh_cache =1;3332 costate.istate = istate;3333if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3334returnerror(_("cannot checkout%s"), ce->name);3335return0;3336}33373338static struct patch *previous_patch(struct apply_state *state,3339struct patch *patch,3340int*gone)3341{3342struct patch *previous;33433344*gone =0;3345if(patch->is_copy || patch->is_rename)3346return NULL;/* "git" patches do not depend on the order */33473348 previous =in_fn_table(state, patch->old_name);3349if(!previous)3350return NULL;33513352if(to_be_deleted(previous))3353return NULL;/* the deletion hasn't happened yet */33543355if(was_deleted(previous))3356*gone =1;33573358return previous;3359}33603361static intverify_index_match(const struct cache_entry *ce,struct stat *st)3362{3363if(S_ISGITLINK(ce->ce_mode)) {3364if(!S_ISDIR(st->st_mode))3365return-1;3366return0;3367}3368returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3369}33703371#define SUBMODULE_PATCH_WITHOUT_INDEX 133723373static intload_patch_target(struct apply_state *state,3374struct strbuf *buf,3375const struct cache_entry *ce,3376struct stat *st,3377const char*name,3378unsigned expected_mode)3379{3380if(state->cached || state->check_index) {3381if(read_file_or_gitlink(ce, buf))3382returnerror(_("failed to read%s"), name);3383}else if(name) {3384if(S_ISGITLINK(expected_mode)) {3385if(ce)3386returnread_file_or_gitlink(ce, buf);3387else3388return SUBMODULE_PATCH_WITHOUT_INDEX;3389}else if(has_symlink_leading_path(name,strlen(name))) {3390returnerror(_("reading from '%s' beyond a symbolic link"), name);3391}else{3392if(read_old_data(st, name, buf))3393returnerror(_("failed to read%s"), name);3394}3395}3396return0;3397}33983399/*3400 * We are about to apply "patch"; populate the "image" with the3401 * current version we have, from the working tree or from the index,3402 * depending on the situation e.g. --cached/--index. If we are3403 * applying a non-git patch that incrementally updates the tree,3404 * we read from the result of a previous diff.3405 */3406static intload_preimage(struct apply_state *state,3407struct image *image,3408struct patch *patch,struct stat *st,3409const struct cache_entry *ce)3410{3411struct strbuf buf = STRBUF_INIT;3412size_t len;3413char*img;3414struct patch *previous;3415int status;34163417 previous =previous_patch(state, patch, &status);3418if(status)3419returnerror(_("path%shas been renamed/deleted"),3420 patch->old_name);3421if(previous) {3422/* We have a patched copy in memory; use that. */3423strbuf_add(&buf, previous->result, previous->resultsize);3424}else{3425 status =load_patch_target(state, &buf, ce, st,3426 patch->old_name, patch->old_mode);3427if(status <0)3428return status;3429else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3430/*3431 * There is no way to apply subproject3432 * patch without looking at the index.3433 * NEEDSWORK: shouldn't this be flagged3434 * as an error???3435 */3436free_fragment_list(patch->fragments);3437 patch->fragments = NULL;3438}else if(status) {3439returnerror(_("failed to read%s"), patch->old_name);3440}3441}34423443 img =strbuf_detach(&buf, &len);3444prepare_image(image, img, len, !patch->is_binary);3445return0;3446}34473448static intthree_way_merge(struct image *image,3449char*path,3450const struct object_id *base,3451const struct object_id *ours,3452const struct object_id *theirs)3453{3454 mmfile_t base_file, our_file, their_file;3455 mmbuffer_t result = { NULL };3456int status;34573458read_mmblob(&base_file, base);3459read_mmblob(&our_file, ours);3460read_mmblob(&their_file, theirs);3461 status =ll_merge(&result, path,3462&base_file,"base",3463&our_file,"ours",3464&their_file,"theirs", NULL);3465free(base_file.ptr);3466free(our_file.ptr);3467free(their_file.ptr);3468if(status <0|| !result.ptr) {3469free(result.ptr);3470return-1;3471}3472clear_image(image);3473 image->buf = result.ptr;3474 image->len = result.size;34753476return status;3477}34783479/*3480 * When directly falling back to add/add three-way merge, we read from3481 * the current contents of the new_name. In no cases other than that3482 * this function will be called.3483 */3484static intload_current(struct apply_state *state,3485struct image *image,3486struct patch *patch)3487{3488struct strbuf buf = STRBUF_INIT;3489int status, pos;3490size_t len;3491char*img;3492struct stat st;3493struct cache_entry *ce;3494char*name = patch->new_name;3495unsigned mode = patch->new_mode;34963497if(!patch->is_new)3498die("BUG: patch to%sis not a creation", patch->old_name);34993500 pos =cache_name_pos(name,strlen(name));3501if(pos <0)3502returnerror(_("%s: does not exist in index"), name);3503 ce = active_cache[pos];3504if(lstat(name, &st)) {3505if(errno != ENOENT)3506returnerror_errno("%s", name);3507if(checkout_target(&the_index, ce, &st))3508return-1;3509}3510if(verify_index_match(ce, &st))3511returnerror(_("%s: does not match index"), name);35123513 status =load_patch_target(state, &buf, ce, &st, name, mode);3514if(status <0)3515return status;3516else if(status)3517return-1;3518 img =strbuf_detach(&buf, &len);3519prepare_image(image, img, len, !patch->is_binary);3520return0;3521}35223523static inttry_threeway(struct apply_state *state,3524struct image *image,3525struct patch *patch,3526struct stat *st,3527const struct cache_entry *ce)3528{3529struct object_id pre_oid, post_oid, our_oid;3530struct strbuf buf = STRBUF_INIT;3531size_t len;3532int status;3533char*img;3534struct image tmp_image;35353536/* No point falling back to 3-way merge in these cases */3537if(patch->is_delete ||3538S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3539return-1;35403541/* Preimage the patch was prepared for */3542if(patch->is_new)3543write_sha1_file("",0, blob_type, pre_oid.hash);3544else if(get_sha1(patch->old_sha1_prefix, pre_oid.hash) ||3545read_blob_object(&buf, &pre_oid, patch->old_mode))3546returnerror(_("repository lacks the necessary blob to fall back on 3-way merge."));35473548if(state->apply_verbosity > verbosity_silent)3549fprintf(stderr,_("Falling back to three-way merge...\n"));35503551 img =strbuf_detach(&buf, &len);3552prepare_image(&tmp_image, img, len,1);3553/* Apply the patch to get the post image */3554if(apply_fragments(state, &tmp_image, patch) <0) {3555clear_image(&tmp_image);3556return-1;3557}3558/* post_oid is theirs */3559write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_oid.hash);3560clear_image(&tmp_image);35613562/* our_oid is ours */3563if(patch->is_new) {3564if(load_current(state, &tmp_image, patch))3565returnerror(_("cannot read the current contents of '%s'"),3566 patch->new_name);3567}else{3568if(load_preimage(state, &tmp_image, patch, st, ce))3569returnerror(_("cannot read the current contents of '%s'"),3570 patch->old_name);3571}3572write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_oid.hash);3573clear_image(&tmp_image);35743575/* in-core three-way merge between post and our using pre as base */3576 status =three_way_merge(image, patch->new_name,3577&pre_oid, &our_oid, &post_oid);3578if(status <0) {3579if(state->apply_verbosity > verbosity_silent)3580fprintf(stderr,3581_("Failed to fall back on three-way merge...\n"));3582return status;3583}35843585if(status) {3586 patch->conflicted_threeway =1;3587if(patch->is_new)3588oidclr(&patch->threeway_stage[0]);3589else3590oidcpy(&patch->threeway_stage[0], &pre_oid);3591oidcpy(&patch->threeway_stage[1], &our_oid);3592oidcpy(&patch->threeway_stage[2], &post_oid);3593if(state->apply_verbosity > verbosity_silent)3594fprintf(stderr,3595_("Applied patch to '%s' with conflicts.\n"),3596 patch->new_name);3597}else{3598if(state->apply_verbosity > verbosity_silent)3599fprintf(stderr,3600_("Applied patch to '%s' cleanly.\n"),3601 patch->new_name);3602}3603return0;3604}36053606static intapply_data(struct apply_state *state,struct patch *patch,3607struct stat *st,const struct cache_entry *ce)3608{3609struct image image;36103611if(load_preimage(state, &image, patch, st, ce) <0)3612return-1;36133614if(patch->direct_to_threeway ||3615apply_fragments(state, &image, patch) <0) {3616/* Note: with --reject, apply_fragments() returns 0 */3617if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3618return-1;3619}3620 patch->result = image.buf;3621 patch->resultsize = image.len;3622add_to_fn_table(state, patch);3623free(image.line_allocated);36243625if(0< patch->is_delete && patch->resultsize)3626returnerror(_("removal patch leaves file contents"));36273628return0;3629}36303631/*3632 * If "patch" that we are looking at modifies or deletes what we have,3633 * we would want it not to lose any local modification we have, either3634 * in the working tree or in the index.3635 *3636 * This also decides if a non-git patch is a creation patch or a3637 * modification to an existing empty file. We do not check the state3638 * of the current tree for a creation patch in this function; the caller3639 * check_patch() separately makes sure (and errors out otherwise) that3640 * the path the patch creates does not exist in the current tree.3641 */3642static intcheck_preimage(struct apply_state *state,3643struct patch *patch,3644struct cache_entry **ce,3645struct stat *st)3646{3647const char*old_name = patch->old_name;3648struct patch *previous = NULL;3649int stat_ret =0, status;3650unsigned st_mode =0;36513652if(!old_name)3653return0;36543655assert(patch->is_new <=0);3656 previous =previous_patch(state, patch, &status);36573658if(status)3659returnerror(_("path%shas been renamed/deleted"), old_name);3660if(previous) {3661 st_mode = previous->new_mode;3662}else if(!state->cached) {3663 stat_ret =lstat(old_name, st);3664if(stat_ret && errno != ENOENT)3665returnerror_errno("%s", old_name);3666}36673668if(state->check_index && !previous) {3669int pos =cache_name_pos(old_name,strlen(old_name));3670if(pos <0) {3671if(patch->is_new <0)3672goto is_new;3673returnerror(_("%s: does not exist in index"), old_name);3674}3675*ce = active_cache[pos];3676if(stat_ret <0) {3677if(checkout_target(&the_index, *ce, st))3678return-1;3679}3680if(!state->cached &&verify_index_match(*ce, st))3681returnerror(_("%s: does not match index"), old_name);3682if(state->cached)3683 st_mode = (*ce)->ce_mode;3684}else if(stat_ret <0) {3685if(patch->is_new <0)3686goto is_new;3687returnerror_errno("%s", old_name);3688}36893690if(!state->cached && !previous)3691 st_mode =ce_mode_from_stat(*ce, st->st_mode);36923693if(patch->is_new <0)3694 patch->is_new =0;3695if(!patch->old_mode)3696 patch->old_mode = st_mode;3697if((st_mode ^ patch->old_mode) & S_IFMT)3698returnerror(_("%s: wrong type"), old_name);3699if(st_mode != patch->old_mode)3700warning(_("%shas type%o, expected%o"),3701 old_name, st_mode, patch->old_mode);3702if(!patch->new_mode && !patch->is_delete)3703 patch->new_mode = st_mode;3704return0;37053706 is_new:3707 patch->is_new =1;3708 patch->is_delete =0;3709free(patch->old_name);3710 patch->old_name = NULL;3711return0;3712}371337143715#define EXISTS_IN_INDEX 13716#define EXISTS_IN_WORKTREE 237173718static intcheck_to_create(struct apply_state *state,3719const char*new_name,3720int ok_if_exists)3721{3722struct stat nst;37233724if(state->check_index &&3725cache_name_pos(new_name,strlen(new_name)) >=0&&3726!ok_if_exists)3727return EXISTS_IN_INDEX;3728if(state->cached)3729return0;37303731if(!lstat(new_name, &nst)) {3732if(S_ISDIR(nst.st_mode) || ok_if_exists)3733return0;3734/*3735 * A leading component of new_name might be a symlink3736 * that is going to be removed with this patch, but3737 * still pointing at somewhere that has the path.3738 * In such a case, path "new_name" does not exist as3739 * far as git is concerned.3740 */3741if(has_symlink_leading_path(new_name,strlen(new_name)))3742return0;37433744return EXISTS_IN_WORKTREE;3745}else if(!is_missing_file_error(errno)) {3746returnerror_errno("%s", new_name);3747}3748return0;3749}37503751static uintptr_tregister_symlink_changes(struct apply_state *state,3752const char*path,3753uintptr_t what)3754{3755struct string_list_item *ent;37563757 ent =string_list_lookup(&state->symlink_changes, path);3758if(!ent) {3759 ent =string_list_insert(&state->symlink_changes, path);3760 ent->util = (void*)0;3761}3762 ent->util = (void*)(what | ((uintptr_t)ent->util));3763return(uintptr_t)ent->util;3764}37653766static uintptr_tcheck_symlink_changes(struct apply_state *state,const char*path)3767{3768struct string_list_item *ent;37693770 ent =string_list_lookup(&state->symlink_changes, path);3771if(!ent)3772return0;3773return(uintptr_t)ent->util;3774}37753776static voidprepare_symlink_changes(struct apply_state *state,struct patch *patch)3777{3778for( ; patch; patch = patch->next) {3779if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3780(patch->is_rename || patch->is_delete))3781/* the symlink at patch->old_name is removed */3782register_symlink_changes(state, patch->old_name, APPLY_SYMLINK_GOES_AWAY);37833784if(patch->new_name &&S_ISLNK(patch->new_mode))3785/* the symlink at patch->new_name is created or remains */3786register_symlink_changes(state, patch->new_name, APPLY_SYMLINK_IN_RESULT);3787}3788}37893790static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3791{3792do{3793unsigned int change;37943795while(--name->len && name->buf[name->len] !='/')3796;/* scan backwards */3797if(!name->len)3798break;3799 name->buf[name->len] ='\0';3800 change =check_symlink_changes(state, name->buf);3801if(change & APPLY_SYMLINK_IN_RESULT)3802return1;3803if(change & APPLY_SYMLINK_GOES_AWAY)3804/*3805 * This cannot be "return 0", because we may3806 * see a new one created at a higher level.3807 */3808continue;38093810/* otherwise, check the preimage */3811if(state->check_index) {3812struct cache_entry *ce;38133814 ce =cache_file_exists(name->buf, name->len, ignore_case);3815if(ce &&S_ISLNK(ce->ce_mode))3816return1;3817}else{3818struct stat st;3819if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3820return1;3821}3822}while(1);3823return0;3824}38253826static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3827{3828int ret;3829struct strbuf name = STRBUF_INIT;38303831assert(*name_ !='\0');3832strbuf_addstr(&name, name_);3833 ret =path_is_beyond_symlink_1(state, &name);3834strbuf_release(&name);38353836return ret;3837}38383839static intcheck_unsafe_path(struct patch *patch)3840{3841const char*old_name = NULL;3842const char*new_name = NULL;3843if(patch->is_delete)3844 old_name = patch->old_name;3845else if(!patch->is_new && !patch->is_copy)3846 old_name = patch->old_name;3847if(!patch->is_delete)3848 new_name = patch->new_name;38493850if(old_name && !verify_path(old_name))3851returnerror(_("invalid path '%s'"), old_name);3852if(new_name && !verify_path(new_name))3853returnerror(_("invalid path '%s'"), new_name);3854return0;3855}38563857/*3858 * Check and apply the patch in-core; leave the result in patch->result3859 * for the caller to write it out to the final destination.3860 */3861static intcheck_patch(struct apply_state *state,struct patch *patch)3862{3863struct stat st;3864const char*old_name = patch->old_name;3865const char*new_name = patch->new_name;3866const char*name = old_name ? old_name : new_name;3867struct cache_entry *ce = NULL;3868struct patch *tpatch;3869int ok_if_exists;3870int status;38713872 patch->rejected =1;/* we will drop this after we succeed */38733874 status =check_preimage(state, patch, &ce, &st);3875if(status)3876return status;3877 old_name = patch->old_name;38783879/*3880 * A type-change diff is always split into a patch to delete3881 * old, immediately followed by a patch to create new (see3882 * diff.c::run_diff()); in such a case it is Ok that the entry3883 * to be deleted by the previous patch is still in the working3884 * tree and in the index.3885 *3886 * A patch to swap-rename between A and B would first rename A3887 * to B and then rename B to A. While applying the first one,3888 * the presence of B should not stop A from getting renamed to3889 * B; ask to_be_deleted() about the later rename. Removal of3890 * B and rename from A to B is handled the same way by asking3891 * was_deleted().3892 */3893if((tpatch =in_fn_table(state, new_name)) &&3894(was_deleted(tpatch) ||to_be_deleted(tpatch)))3895 ok_if_exists =1;3896else3897 ok_if_exists =0;38983899if(new_name &&3900((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3901int err =check_to_create(state, new_name, ok_if_exists);39023903if(err && state->threeway) {3904 patch->direct_to_threeway =1;3905}else switch(err) {3906case0:3907break;/* happy */3908case EXISTS_IN_INDEX:3909returnerror(_("%s: already exists in index"), new_name);3910break;3911case EXISTS_IN_WORKTREE:3912returnerror(_("%s: already exists in working directory"),3913 new_name);3914default:3915return err;3916}39173918if(!patch->new_mode) {3919if(0< patch->is_new)3920 patch->new_mode = S_IFREG |0644;3921else3922 patch->new_mode = patch->old_mode;3923}3924}39253926if(new_name && old_name) {3927int same = !strcmp(old_name, new_name);3928if(!patch->new_mode)3929 patch->new_mode = patch->old_mode;3930if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3931if(same)3932returnerror(_("new mode (%o) of%sdoes not "3933"match old mode (%o)"),3934 patch->new_mode, new_name,3935 patch->old_mode);3936else3937returnerror(_("new mode (%o) of%sdoes not "3938"match old mode (%o) of%s"),3939 patch->new_mode, new_name,3940 patch->old_mode, old_name);3941}3942}39433944if(!state->unsafe_paths &&check_unsafe_path(patch))3945return-128;39463947/*3948 * An attempt to read from or delete a path that is beyond a3949 * symbolic link will be prevented by load_patch_target() that3950 * is called at the beginning of apply_data() so we do not3951 * have to worry about a patch marked with "is_delete" bit3952 * here. We however need to make sure that the patch result3953 * is not deposited to a path that is beyond a symbolic link3954 * here.3955 */3956if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3957returnerror(_("affected file '%s' is beyond a symbolic link"),3958 patch->new_name);39593960if(apply_data(state, patch, &st, ce) <0)3961returnerror(_("%s: patch does not apply"), name);3962 patch->rejected =0;3963return0;3964}39653966static intcheck_patch_list(struct apply_state *state,struct patch *patch)3967{3968int err =0;39693970prepare_symlink_changes(state, patch);3971prepare_fn_table(state, patch);3972while(patch) {3973int res;3974if(state->apply_verbosity > verbosity_normal)3975say_patch_name(stderr,3976_("Checking patch%s..."), patch);3977 res =check_patch(state, patch);3978if(res == -128)3979return-128;3980 err |= res;3981 patch = patch->next;3982}3983return err;3984}39853986static intread_apply_cache(struct apply_state *state)3987{3988if(state->index_file)3989returnread_cache_from(state->index_file);3990else3991returnread_cache();3992}39933994/* This function tries to read the object name from the current index */3995static intget_current_oid(struct apply_state *state,const char*path,3996struct object_id *oid)3997{3998int pos;39994000if(read_apply_cache(state) <0)4001return-1;4002 pos =cache_name_pos(path,strlen(path));4003if(pos <0)4004return-1;4005oidcpy(oid, &active_cache[pos]->oid);4006return0;4007}40084009static intpreimage_oid_in_gitlink_patch(struct patch *p,struct object_id *oid)4010{4011/*4012 * A usable gitlink patch has only one fragment (hunk) that looks like:4013 * @@ -1 +1 @@4014 * -Subproject commit <old sha1>4015 * +Subproject commit <new sha1>4016 * or4017 * @@ -1 +0,0 @@4018 * -Subproject commit <old sha1>4019 * for a removal patch.4020 */4021struct fragment *hunk = p->fragments;4022static const char heading[] ="-Subproject commit ";4023char*preimage;40244025if(/* does the patch have only one hunk? */4026 hunk && !hunk->next &&4027/* is its preimage one line? */4028 hunk->oldpos ==1&& hunk->oldlines ==1&&4029/* does preimage begin with the heading? */4030(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&4031starts_with(++preimage, heading) &&4032/* does it record full SHA-1? */4033!get_oid_hex(preimage +sizeof(heading) -1, oid) &&4034 preimage[sizeof(heading) + GIT_SHA1_HEXSZ -1] =='\n'&&4035/* does the abbreviated name on the index line agree with it? */4036starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))4037return0;/* it all looks fine */40384039/* we may have full object name on the index line */4040returnget_oid_hex(p->old_sha1_prefix, oid);4041}40424043/* Build an index that contains the just the files needed for a 3way merge */4044static intbuild_fake_ancestor(struct apply_state *state,struct patch *list)4045{4046struct patch *patch;4047struct index_state result = { NULL };4048static struct lock_file lock;4049int res;40504051/* Once we start supporting the reverse patch, it may be4052 * worth showing the new sha1 prefix, but until then...4053 */4054for(patch = list; patch; patch = patch->next) {4055struct object_id oid;4056struct cache_entry *ce;4057const char*name;40584059 name = patch->old_name ? patch->old_name : patch->new_name;4060if(0< patch->is_new)4061continue;40624063if(S_ISGITLINK(patch->old_mode)) {4064if(!preimage_oid_in_gitlink_patch(patch, &oid))4065;/* ok, the textual part looks sane */4066else4067returnerror(_("sha1 information is lacking or "4068"useless for submodule%s"), name);4069}else if(!get_sha1_blob(patch->old_sha1_prefix, oid.hash)) {4070;/* ok */4071}else if(!patch->lines_added && !patch->lines_deleted) {4072/* mode-only change: update the current */4073if(get_current_oid(state, patch->old_name, &oid))4074returnerror(_("mode change for%s, which is not "4075"in current HEAD"), name);4076}else4077returnerror(_("sha1 information is lacking or useless "4078"(%s)."), name);40794080 ce =make_cache_entry(patch->old_mode, oid.hash, name,0,0);4081if(!ce)4082returnerror(_("make_cache_entry failed for path '%s'"),4083 name);4084if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) {4085free(ce);4086returnerror(_("could not add%sto temporary index"),4087 name);4088}4089}40904091hold_lock_file_for_update(&lock, state->fake_ancestor, LOCK_DIE_ON_ERROR);4092 res =write_locked_index(&result, &lock, COMMIT_LOCK);4093discard_index(&result);40944095if(res)4096returnerror(_("could not write temporary index to%s"),4097 state->fake_ancestor);40984099return0;4100}41014102static voidstat_patch_list(struct apply_state *state,struct patch *patch)4103{4104int files, adds, dels;41054106for(files = adds = dels =0; patch ; patch = patch->next) {4107 files++;4108 adds += patch->lines_added;4109 dels += patch->lines_deleted;4110show_stats(state, patch);4111}41124113print_stat_summary(stdout, files, adds, dels);4114}41154116static voidnumstat_patch_list(struct apply_state *state,4117struct patch *patch)4118{4119for( ; patch; patch = patch->next) {4120const char*name;4121 name = patch->new_name ? patch->new_name : patch->old_name;4122if(patch->is_binary)4123printf("-\t-\t");4124else4125printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4126write_name_quoted(name, stdout, state->line_termination);4127}4128}41294130static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4131{4132if(mode)4133printf("%smode%06o%s\n", newdelete, mode, name);4134else4135printf("%s %s\n", newdelete, name);4136}41374138static voidshow_mode_change(struct patch *p,int show_name)4139{4140if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4141if(show_name)4142printf(" mode change%06o =>%06o%s\n",4143 p->old_mode, p->new_mode, p->new_name);4144else4145printf(" mode change%06o =>%06o\n",4146 p->old_mode, p->new_mode);4147}4148}41494150static voidshow_rename_copy(struct patch *p)4151{4152const char*renamecopy = p->is_rename ?"rename":"copy";4153const char*old, *new;41544155/* Find common prefix */4156 old = p->old_name;4157new= p->new_name;4158while(1) {4159const char*slash_old, *slash_new;4160 slash_old =strchr(old,'/');4161 slash_new =strchr(new,'/');4162if(!slash_old ||4163!slash_new ||4164 slash_old - old != slash_new -new||4165memcmp(old,new, slash_new -new))4166break;4167 old = slash_old +1;4168new= slash_new +1;4169}4170/* p->old_name thru old is the common prefix, and old and new4171 * through the end of names are renames4172 */4173if(old != p->old_name)4174printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4175(int)(old - p->old_name), p->old_name,4176 old,new, p->score);4177else4178printf("%s %s=>%s(%d%%)\n", renamecopy,4179 p->old_name, p->new_name, p->score);4180show_mode_change(p,0);4181}41824183static voidsummary_patch_list(struct patch *patch)4184{4185struct patch *p;41864187for(p = patch; p; p = p->next) {4188if(p->is_new)4189show_file_mode_name("create", p->new_mode, p->new_name);4190else if(p->is_delete)4191show_file_mode_name("delete", p->old_mode, p->old_name);4192else{4193if(p->is_rename || p->is_copy)4194show_rename_copy(p);4195else{4196if(p->score) {4197printf(" rewrite%s(%d%%)\n",4198 p->new_name, p->score);4199show_mode_change(p,0);4200}4201else4202show_mode_change(p,1);4203}4204}4205}4206}42074208static voidpatch_stats(struct apply_state *state,struct patch *patch)4209{4210int lines = patch->lines_added + patch->lines_deleted;42114212if(lines > state->max_change)4213 state->max_change = lines;4214if(patch->old_name) {4215int len =quote_c_style(patch->old_name, NULL, NULL,0);4216if(!len)4217 len =strlen(patch->old_name);4218if(len > state->max_len)4219 state->max_len = len;4220}4221if(patch->new_name) {4222int len =quote_c_style(patch->new_name, NULL, NULL,0);4223if(!len)4224 len =strlen(patch->new_name);4225if(len > state->max_len)4226 state->max_len = len;4227}4228}42294230static intremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4231{4232if(state->update_index) {4233if(remove_file_from_cache(patch->old_name) <0)4234returnerror(_("unable to remove%sfrom index"), patch->old_name);4235}4236if(!state->cached) {4237if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4238remove_path(patch->old_name);4239}4240}4241return0;4242}42434244static intadd_index_file(struct apply_state *state,4245const char*path,4246unsigned mode,4247void*buf,4248unsigned long size)4249{4250struct stat st;4251struct cache_entry *ce;4252int namelen =strlen(path);4253unsigned ce_size =cache_entry_size(namelen);42544255if(!state->update_index)4256return0;42574258 ce =xcalloc(1, ce_size);4259memcpy(ce->name, path, namelen);4260 ce->ce_mode =create_ce_mode(mode);4261 ce->ce_flags =create_ce_flags(0);4262 ce->ce_namelen = namelen;4263if(S_ISGITLINK(mode)) {4264const char*s;42654266if(!skip_prefix(buf,"Subproject commit ", &s) ||4267get_oid_hex(s, &ce->oid)) {4268free(ce);4269returnerror(_("corrupt patch for submodule%s"), path);4270}4271}else{4272if(!state->cached) {4273if(lstat(path, &st) <0) {4274free(ce);4275returnerror_errno(_("unable to stat newly "4276"created file '%s'"),4277 path);4278}4279fill_stat_cache_info(ce, &st);4280}4281if(write_sha1_file(buf, size, blob_type, ce->oid.hash) <0) {4282free(ce);4283returnerror(_("unable to create backing store "4284"for newly created file%s"), path);4285}4286}4287if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0) {4288free(ce);4289returnerror(_("unable to add cache entry for%s"), path);4290}42914292return0;4293}42944295/*4296 * Returns:4297 * -1 if an unrecoverable error happened4298 * 0 if everything went well4299 * 1 if a recoverable error happened4300 */4301static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4302{4303int fd, res;4304struct strbuf nbuf = STRBUF_INIT;43054306if(S_ISGITLINK(mode)) {4307struct stat st;4308if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4309return0;4310return!!mkdir(path,0777);4311}43124313if(has_symlinks &&S_ISLNK(mode))4314/* Although buf:size is counted string, it also is NUL4315 * terminated.4316 */4317return!!symlink(buf, path);43184319 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4320if(fd <0)4321return1;43224323if(convert_to_working_tree(path, buf, size, &nbuf)) {4324 size = nbuf.len;4325 buf = nbuf.buf;4326}43274328 res =write_in_full(fd, buf, size) <0;4329if(res)4330error_errno(_("failed to write to '%s'"), path);4331strbuf_release(&nbuf);43324333if(close(fd) <0&& !res)4334returnerror_errno(_("closing file '%s'"), path);43354336return res ? -1:0;4337}43384339/*4340 * We optimistically assume that the directories exist,4341 * which is true 99% of the time anyway. If they don't,4342 * we create them and try again.4343 *4344 * Returns:4345 * -1 on error4346 * 0 otherwise4347 */4348static intcreate_one_file(struct apply_state *state,4349char*path,4350unsigned mode,4351const char*buf,4352unsigned long size)4353{4354int res;43554356if(state->cached)4357return0;43584359 res =try_create_file(path, mode, buf, size);4360if(res <0)4361return-1;4362if(!res)4363return0;43644365if(errno == ENOENT) {4366if(safe_create_leading_directories(path))4367return0;4368 res =try_create_file(path, mode, buf, size);4369if(res <0)4370return-1;4371if(!res)4372return0;4373}43744375if(errno == EEXIST || errno == EACCES) {4376/* We may be trying to create a file where a directory4377 * used to be.4378 */4379struct stat st;4380if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4381 errno = EEXIST;4382}43834384if(errno == EEXIST) {4385unsigned int nr =getpid();43864387for(;;) {4388char newpath[PATH_MAX];4389mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4390 res =try_create_file(newpath, mode, buf, size);4391if(res <0)4392return-1;4393if(!res) {4394if(!rename(newpath, path))4395return0;4396unlink_or_warn(newpath);4397break;4398}4399if(errno != EEXIST)4400break;4401++nr;4402}4403}4404returnerror_errno(_("unable to write file '%s' mode%o"),4405 path, mode);4406}44074408static intadd_conflicted_stages_file(struct apply_state *state,4409struct patch *patch)4410{4411int stage, namelen;4412unsigned ce_size, mode;4413struct cache_entry *ce;44144415if(!state->update_index)4416return0;4417 namelen =strlen(patch->new_name);4418 ce_size =cache_entry_size(namelen);4419 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);44204421remove_file_from_cache(patch->new_name);4422for(stage =1; stage <4; stage++) {4423if(is_null_oid(&patch->threeway_stage[stage -1]))4424continue;4425 ce =xcalloc(1, ce_size);4426memcpy(ce->name, patch->new_name, namelen);4427 ce->ce_mode =create_ce_mode(mode);4428 ce->ce_flags =create_ce_flags(stage);4429 ce->ce_namelen = namelen;4430oidcpy(&ce->oid, &patch->threeway_stage[stage -1]);4431if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0) {4432free(ce);4433returnerror(_("unable to add cache entry for%s"),4434 patch->new_name);4435}4436}44374438return0;4439}44404441static intcreate_file(struct apply_state *state,struct patch *patch)4442{4443char*path = patch->new_name;4444unsigned mode = patch->new_mode;4445unsigned long size = patch->resultsize;4446char*buf = patch->result;44474448if(!mode)4449 mode = S_IFREG |0644;4450if(create_one_file(state, path, mode, buf, size))4451return-1;44524453if(patch->conflicted_threeway)4454returnadd_conflicted_stages_file(state, patch);4455else4456returnadd_index_file(state, path, mode, buf, size);4457}44584459/* phase zero is to remove, phase one is to create */4460static intwrite_out_one_result(struct apply_state *state,4461struct patch *patch,4462int phase)4463{4464if(patch->is_delete >0) {4465if(phase ==0)4466returnremove_file(state, patch,1);4467return0;4468}4469if(patch->is_new >0|| patch->is_copy) {4470if(phase ==1)4471returncreate_file(state, patch);4472return0;4473}4474/*4475 * Rename or modification boils down to the same4476 * thing: remove the old, write the new4477 */4478if(phase ==0)4479returnremove_file(state, patch, patch->is_rename);4480if(phase ==1)4481returncreate_file(state, patch);4482return0;4483}44844485static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4486{4487FILE*rej;4488char namebuf[PATH_MAX];4489struct fragment *frag;4490int cnt =0;4491struct strbuf sb = STRBUF_INIT;44924493for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4494if(!frag->rejected)4495continue;4496 cnt++;4497}44984499if(!cnt) {4500if(state->apply_verbosity > verbosity_normal)4501say_patch_name(stderr,4502_("Applied patch%scleanly."), patch);4503return0;4504}45054506/* This should not happen, because a removal patch that leaves4507 * contents are marked "rejected" at the patch level.4508 */4509if(!patch->new_name)4510die(_("internal error"));45114512/* Say this even without --verbose */4513strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4514"Applying patch %%swith%drejects...",4515 cnt),4516 cnt);4517if(state->apply_verbosity > verbosity_silent)4518say_patch_name(stderr, sb.buf, patch);4519strbuf_release(&sb);45204521 cnt =strlen(patch->new_name);4522if(ARRAY_SIZE(namebuf) <= cnt +5) {4523 cnt =ARRAY_SIZE(namebuf) -5;4524warning(_("truncating .rej filename to %.*s.rej"),4525 cnt -1, patch->new_name);4526}4527memcpy(namebuf, patch->new_name, cnt);4528memcpy(namebuf + cnt,".rej",5);45294530 rej =fopen(namebuf,"w");4531if(!rej)4532returnerror_errno(_("cannot open%s"), namebuf);45334534/* Normal git tools never deal with .rej, so do not pretend4535 * this is a git patch by saying --git or giving extended4536 * headers. While at it, maybe please "kompare" that wants4537 * the trailing TAB and some garbage at the end of line ;-).4538 */4539fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4540 patch->new_name, patch->new_name);4541for(cnt =1, frag = patch->fragments;4542 frag;4543 cnt++, frag = frag->next) {4544if(!frag->rejected) {4545if(state->apply_verbosity > verbosity_silent)4546fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4547continue;4548}4549if(state->apply_verbosity > verbosity_silent)4550fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4551fprintf(rej,"%.*s", frag->size, frag->patch);4552if(frag->patch[frag->size-1] !='\n')4553fputc('\n', rej);4554}4555fclose(rej);4556return-1;4557}45584559/*4560 * Returns:4561 * -1 if an error happened4562 * 0 if the patch applied cleanly4563 * 1 if the patch did not apply cleanly4564 */4565static intwrite_out_results(struct apply_state *state,struct patch *list)4566{4567int phase;4568int errs =0;4569struct patch *l;4570struct string_list cpath = STRING_LIST_INIT_DUP;45714572for(phase =0; phase <2; phase++) {4573 l = list;4574while(l) {4575if(l->rejected)4576 errs =1;4577else{4578if(write_out_one_result(state, l, phase)) {4579string_list_clear(&cpath,0);4580return-1;4581}4582if(phase ==1) {4583if(write_out_one_reject(state, l))4584 errs =1;4585if(l->conflicted_threeway) {4586string_list_append(&cpath, l->new_name);4587 errs =1;4588}4589}4590}4591 l = l->next;4592}4593}45944595if(cpath.nr) {4596struct string_list_item *item;45974598string_list_sort(&cpath);4599if(state->apply_verbosity > verbosity_silent) {4600for_each_string_list_item(item, &cpath)4601fprintf(stderr,"U%s\n", item->string);4602}4603string_list_clear(&cpath,0);46044605rerere(0);4606}46074608return errs;4609}46104611/*4612 * Try to apply a patch.4613 *4614 * Returns:4615 * -128 if a bad error happened (like patch unreadable)4616 * -1 if patch did not apply and user cannot deal with it4617 * 0 if the patch applied4618 * 1 if the patch did not apply but user might fix it4619 */4620static intapply_patch(struct apply_state *state,4621int fd,4622const char*filename,4623int options)4624{4625size_t offset;4626struct strbuf buf = STRBUF_INIT;/* owns the patch text */4627struct patch *list = NULL, **listp = &list;4628int skipped_patch =0;4629int res =0;46304631 state->patch_input_file = filename;4632if(read_patch_file(&buf, fd) <0)4633return-128;4634 offset =0;4635while(offset < buf.len) {4636struct patch *patch;4637int nr;46384639 patch =xcalloc(1,sizeof(*patch));4640 patch->inaccurate_eof = !!(options & APPLY_OPT_INACCURATE_EOF);4641 patch->recount = !!(options & APPLY_OPT_RECOUNT);4642 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4643if(nr <0) {4644free_patch(patch);4645if(nr == -128) {4646 res = -128;4647goto end;4648}4649break;4650}4651if(state->apply_in_reverse)4652reverse_patches(patch);4653if(use_patch(state, patch)) {4654patch_stats(state, patch);4655*listp = patch;4656 listp = &patch->next;4657}4658else{4659if(state->apply_verbosity > verbosity_normal)4660say_patch_name(stderr,_("Skipped patch '%s'."), patch);4661free_patch(patch);4662 skipped_patch++;4663}4664 offset += nr;4665}46664667if(!list && !skipped_patch) {4668error(_("unrecognized input"));4669 res = -128;4670goto end;4671}46724673if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4674 state->apply =0;46754676 state->update_index = state->check_index && state->apply;4677if(state->update_index && state->newfd <0) {4678if(state->index_file)4679 state->newfd =hold_lock_file_for_update(state->lock_file,4680 state->index_file,4681 LOCK_DIE_ON_ERROR);4682else4683 state->newfd =hold_locked_index(state->lock_file, LOCK_DIE_ON_ERROR);4684}46854686if(state->check_index &&read_apply_cache(state) <0) {4687error(_("unable to read index file"));4688 res = -128;4689goto end;4690}46914692if(state->check || state->apply) {4693int r =check_patch_list(state, list);4694if(r == -128) {4695 res = -128;4696goto end;4697}4698if(r <0&& !state->apply_with_reject) {4699 res = -1;4700goto end;4701}4702}47034704if(state->apply) {4705int write_res =write_out_results(state, list);4706if(write_res <0) {4707 res = -128;4708goto end;4709}4710if(write_res >0) {4711/* with --3way, we still need to write the index out */4712 res = state->apply_with_reject ? -1:1;4713goto end;4714}4715}47164717if(state->fake_ancestor &&4718build_fake_ancestor(state, list)) {4719 res = -128;4720goto end;4721}47224723if(state->diffstat && state->apply_verbosity > verbosity_silent)4724stat_patch_list(state, list);47254726if(state->numstat && state->apply_verbosity > verbosity_silent)4727numstat_patch_list(state, list);47284729if(state->summary && state->apply_verbosity > verbosity_silent)4730summary_patch_list(list);47314732end:4733free_patch_list(list);4734strbuf_release(&buf);4735string_list_clear(&state->fn_table,0);4736return res;4737}47384739static intapply_option_parse_exclude(const struct option *opt,4740const char*arg,int unset)4741{4742struct apply_state *state = opt->value;4743add_name_limit(state, arg,1);4744return0;4745}47464747static intapply_option_parse_include(const struct option *opt,4748const char*arg,int unset)4749{4750struct apply_state *state = opt->value;4751add_name_limit(state, arg,0);4752 state->has_include =1;4753return0;4754}47554756static intapply_option_parse_p(const struct option *opt,4757const char*arg,4758int unset)4759{4760struct apply_state *state = opt->value;4761 state->p_value =atoi(arg);4762 state->p_value_known =1;4763return0;4764}47654766static intapply_option_parse_space_change(const struct option *opt,4767const char*arg,int unset)4768{4769struct apply_state *state = opt->value;4770if(unset)4771 state->ws_ignore_action = ignore_ws_none;4772else4773 state->ws_ignore_action = ignore_ws_change;4774return0;4775}47764777static intapply_option_parse_whitespace(const struct option *opt,4778const char*arg,int unset)4779{4780struct apply_state *state = opt->value;4781 state->whitespace_option = arg;4782if(parse_whitespace_option(state, arg))4783exit(1);4784return0;4785}47864787static intapply_option_parse_directory(const struct option *opt,4788const char*arg,int unset)4789{4790struct apply_state *state = opt->value;4791strbuf_reset(&state->root);4792strbuf_addstr(&state->root, arg);4793strbuf_complete(&state->root,'/');4794return0;4795}47964797intapply_all_patches(struct apply_state *state,4798int argc,4799const char**argv,4800int options)4801{4802int i;4803int res;4804int errs =0;4805int read_stdin =1;48064807for(i =0; i < argc; i++) {4808const char*arg = argv[i];4809char*to_free = NULL;4810int fd;48114812if(!strcmp(arg,"-")) {4813 res =apply_patch(state,0,"<stdin>", options);4814if(res <0)4815goto end;4816 errs |= res;4817 read_stdin =0;4818continue;4819}else4820 arg = to_free =prefix_filename(state->prefix, arg);48214822 fd =open(arg, O_RDONLY);4823if(fd <0) {4824error(_("can't open patch '%s':%s"), arg,strerror(errno));4825 res = -128;4826free(to_free);4827goto end;4828}4829 read_stdin =0;4830set_default_whitespace_mode(state);4831 res =apply_patch(state, fd, arg, options);4832close(fd);4833free(to_free);4834if(res <0)4835goto end;4836 errs |= res;4837}4838set_default_whitespace_mode(state);4839if(read_stdin) {4840 res =apply_patch(state,0,"<stdin>", options);4841if(res <0)4842goto end;4843 errs |= res;4844}48454846if(state->whitespace_error) {4847if(state->squelch_whitespace_errors &&4848 state->squelch_whitespace_errors < state->whitespace_error) {4849int squelched =4850 state->whitespace_error - state->squelch_whitespace_errors;4851warning(Q_("squelched%dwhitespace error",4852"squelched%dwhitespace errors",4853 squelched),4854 squelched);4855}4856if(state->ws_error_action == die_on_ws_error) {4857error(Q_("%dline adds whitespace errors.",4858"%dlines add whitespace errors.",4859 state->whitespace_error),4860 state->whitespace_error);4861 res = -128;4862goto end;4863}4864if(state->applied_after_fixing_ws && state->apply)4865warning(Q_("%dline applied after"4866" fixing whitespace errors.",4867"%dlines applied after"4868" fixing whitespace errors.",4869 state->applied_after_fixing_ws),4870 state->applied_after_fixing_ws);4871else if(state->whitespace_error)4872warning(Q_("%dline adds whitespace errors.",4873"%dlines add whitespace errors.",4874 state->whitespace_error),4875 state->whitespace_error);4876}48774878if(state->update_index) {4879 res =write_locked_index(&the_index, state->lock_file, COMMIT_LOCK);4880if(res) {4881error(_("Unable to write new index file"));4882 res = -128;4883goto end;4884}4885 state->newfd = -1;4886}48874888 res = !!errs;48894890end:4891if(state->newfd >=0) {4892rollback_lock_file(state->lock_file);4893 state->newfd = -1;4894}48954896if(state->apply_verbosity <= verbosity_silent) {4897set_error_routine(state->saved_error_routine);4898set_warn_routine(state->saved_warn_routine);4899}49004901if(res > -1)4902return res;4903return(res == -1?1:128);4904}49054906intapply_parse_options(int argc,const char**argv,4907struct apply_state *state,4908int*force_apply,int*options,4909const char*const*apply_usage)4910{4911struct option builtin_apply_options[] = {4912{ OPTION_CALLBACK,0,"exclude", state,N_("path"),4913N_("don't apply changes matching the given path"),49140, apply_option_parse_exclude },4915{ OPTION_CALLBACK,0,"include", state,N_("path"),4916N_("apply changes matching the given path"),49170, apply_option_parse_include },4918{ OPTION_CALLBACK,'p', NULL, state,N_("num"),4919N_("remove <num> leading slashes from traditional diff paths"),49200, apply_option_parse_p },4921OPT_BOOL(0,"no-add", &state->no_add,4922N_("ignore additions made by the patch")),4923OPT_BOOL(0,"stat", &state->diffstat,4924N_("instead of applying the patch, output diffstat for the input")),4925OPT_NOOP_NOARG(0,"allow-binary-replacement"),4926OPT_NOOP_NOARG(0,"binary"),4927OPT_BOOL(0,"numstat", &state->numstat,4928N_("show number of added and deleted lines in decimal notation")),4929OPT_BOOL(0,"summary", &state->summary,4930N_("instead of applying the patch, output a summary for the input")),4931OPT_BOOL(0,"check", &state->check,4932N_("instead of applying the patch, see if the patch is applicable")),4933OPT_BOOL(0,"index", &state->check_index,4934N_("make sure the patch is applicable to the current index")),4935OPT_BOOL(0,"cached", &state->cached,4936N_("apply a patch without touching the working tree")),4937OPT_BOOL(0,"unsafe-paths", &state->unsafe_paths,4938N_("accept a patch that touches outside the working area")),4939OPT_BOOL(0,"apply", force_apply,4940N_("also apply the patch (use with --stat/--summary/--check)")),4941OPT_BOOL('3',"3way", &state->threeway,4942N_("attempt three-way merge if a patch does not apply")),4943OPT_FILENAME(0,"build-fake-ancestor", &state->fake_ancestor,4944N_("build a temporary index based on embedded index information")),4945/* Think twice before adding "--nul" synonym to this */4946OPT_SET_INT('z', NULL, &state->line_termination,4947N_("paths are separated with NUL character"),'\0'),4948OPT_INTEGER('C', NULL, &state->p_context,4949N_("ensure at least <n> lines of context match")),4950{ OPTION_CALLBACK,0,"whitespace", state,N_("action"),4951N_("detect new or modified lines that have whitespace errors"),49520, apply_option_parse_whitespace },4953{ OPTION_CALLBACK,0,"ignore-space-change", state, NULL,4954N_("ignore changes in whitespace when finding context"),4955 PARSE_OPT_NOARG, apply_option_parse_space_change },4956{ OPTION_CALLBACK,0,"ignore-whitespace", state, NULL,4957N_("ignore changes in whitespace when finding context"),4958 PARSE_OPT_NOARG, apply_option_parse_space_change },4959OPT_BOOL('R',"reverse", &state->apply_in_reverse,4960N_("apply the patch in reverse")),4961OPT_BOOL(0,"unidiff-zero", &state->unidiff_zero,4962N_("don't expect at least one line of context")),4963OPT_BOOL(0,"reject", &state->apply_with_reject,4964N_("leave the rejected hunks in corresponding *.rej files")),4965OPT_BOOL(0,"allow-overlap", &state->allow_overlap,4966N_("allow overlapping hunks")),4967OPT__VERBOSE(&state->apply_verbosity,N_("be verbose")),4968OPT_BIT(0,"inaccurate-eof", options,4969N_("tolerate incorrectly detected missing new-line at the end of file"),4970 APPLY_OPT_INACCURATE_EOF),4971OPT_BIT(0,"recount", options,4972N_("do not trust the line counts in the hunk headers"),4973 APPLY_OPT_RECOUNT),4974{ OPTION_CALLBACK,0,"directory", state,N_("root"),4975N_("prepend <root> to all filenames"),49760, apply_option_parse_directory },4977OPT_END()4978};49794980returnparse_options(argc, argv, state->prefix, builtin_apply_options, apply_usage,0);4981}