1/* 2 * apply.c 3 * 4 * Copyright (C) Linus Torvalds, 2005 5 * 6 * This applies patches on top of some (arbitrary) version of the SCM. 7 * 8 */ 9 10#include"cache.h" 11#include"blob.h" 12#include"delta.h" 13#include"diff.h" 14#include"dir.h" 15#include"xdiff-interface.h" 16#include"ll-merge.h" 17#include"lockfile.h" 18#include"parse-options.h" 19#include"quote.h" 20#include"rerere.h" 21#include"apply.h" 22 23static voidgit_apply_config(void) 24{ 25git_config_get_string_const("apply.whitespace", &apply_default_whitespace); 26git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace); 27git_config(git_default_config, NULL); 28} 29 30static intparse_whitespace_option(struct apply_state *state,const char*option) 31{ 32if(!option) { 33 state->ws_error_action = warn_on_ws_error; 34return0; 35} 36if(!strcmp(option,"warn")) { 37 state->ws_error_action = warn_on_ws_error; 38return0; 39} 40if(!strcmp(option,"nowarn")) { 41 state->ws_error_action = nowarn_ws_error; 42return0; 43} 44if(!strcmp(option,"error")) { 45 state->ws_error_action = die_on_ws_error; 46return0; 47} 48if(!strcmp(option,"error-all")) { 49 state->ws_error_action = die_on_ws_error; 50 state->squelch_whitespace_errors =0; 51return0; 52} 53if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 54 state->ws_error_action = correct_ws_error; 55return0; 56} 57returnerror(_("unrecognized whitespace option '%s'"), option); 58} 59 60static intparse_ignorewhitespace_option(struct apply_state *state, 61const char*option) 62{ 63if(!option || !strcmp(option,"no") || 64!strcmp(option,"false") || !strcmp(option,"never") || 65!strcmp(option,"none")) { 66 state->ws_ignore_action = ignore_ws_none; 67return0; 68} 69if(!strcmp(option,"change")) { 70 state->ws_ignore_action = ignore_ws_change; 71return0; 72} 73returnerror(_("unrecognized whitespace ignore option '%s'"), option); 74} 75 76intinit_apply_state(struct apply_state *state, 77const char*prefix, 78struct lock_file *lock_file) 79{ 80memset(state,0,sizeof(*state)); 81 state->prefix = prefix; 82 state->prefix_length = state->prefix ?strlen(state->prefix) :0; 83 state->lock_file = lock_file; 84 state->newfd = -1; 85 state->apply =1; 86 state->line_termination ='\n'; 87 state->p_value =1; 88 state->p_context = UINT_MAX; 89 state->squelch_whitespace_errors =5; 90 state->ws_error_action = warn_on_ws_error; 91 state->ws_ignore_action = ignore_ws_none; 92 state->linenr =1; 93string_list_init(&state->fn_table,0); 94string_list_init(&state->limit_by_name,0); 95string_list_init(&state->symlink_changes,0); 96strbuf_init(&state->root,0); 97 98git_apply_config(); 99if(apply_default_whitespace &&parse_whitespace_option(state, apply_default_whitespace)) 100return-1; 101if(apply_default_ignorewhitespace &&parse_ignorewhitespace_option(state, apply_default_ignorewhitespace)) 102return-1; 103return0; 104} 105 106voidclear_apply_state(struct apply_state *state) 107{ 108string_list_clear(&state->limit_by_name,0); 109string_list_clear(&state->symlink_changes,0); 110strbuf_release(&state->root); 111 112/* &state->fn_table is cleared at the end of apply_patch() */ 113} 114 115static voidmute_routine(const char*msg,va_list params) 116{ 117/* do nothing */ 118} 119 120intcheck_apply_state(struct apply_state *state,int force_apply) 121{ 122int is_not_gitdir = !startup_info->have_repository; 123 124if(state->apply_with_reject && state->threeway) 125returnerror(_("--reject and --3way cannot be used together.")); 126if(state->cached && state->threeway) 127returnerror(_("--cached and --3way cannot be used together.")); 128if(state->threeway) { 129if(is_not_gitdir) 130returnerror(_("--3way outside a repository")); 131 state->check_index =1; 132} 133if(state->apply_with_reject) { 134 state->apply =1; 135if(state->apply_verbosity == verbosity_normal) 136 state->apply_verbosity = verbosity_verbose; 137} 138if(!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor)) 139 state->apply =0; 140if(state->check_index && is_not_gitdir) 141returnerror(_("--index outside a repository")); 142if(state->cached) { 143if(is_not_gitdir) 144returnerror(_("--cached outside a repository")); 145 state->check_index =1; 146} 147if(state->check_index) 148 state->unsafe_paths =0; 149if(!state->lock_file) 150returnerror("BUG: state->lock_file should not be NULL"); 151 152if(state->apply_verbosity <= verbosity_silent) { 153 state->saved_error_routine =get_error_routine(); 154 state->saved_warn_routine =get_warn_routine(); 155set_error_routine(mute_routine); 156set_warn_routine(mute_routine); 157} 158 159return0; 160} 161 162static voidset_default_whitespace_mode(struct apply_state *state) 163{ 164if(!state->whitespace_option && !apply_default_whitespace) 165 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 166} 167 168/* 169 * This represents one "hunk" from a patch, starting with 170 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 171 * patch text is pointed at by patch, and its byte length 172 * is stored in size. leading and trailing are the number 173 * of context lines. 174 */ 175struct fragment { 176unsigned long leading, trailing; 177unsigned long oldpos, oldlines; 178unsigned long newpos, newlines; 179/* 180 * 'patch' is usually borrowed from buf in apply_patch(), 181 * but some codepaths store an allocated buffer. 182 */ 183const char*patch; 184unsigned free_patch:1, 185 rejected:1; 186int size; 187int linenr; 188struct fragment *next; 189}; 190 191/* 192 * When dealing with a binary patch, we reuse "leading" field 193 * to store the type of the binary hunk, either deflated "delta" 194 * or deflated "literal". 195 */ 196#define binary_patch_method leading 197#define BINARY_DELTA_DEFLATED 1 198#define BINARY_LITERAL_DEFLATED 2 199 200/* 201 * This represents a "patch" to a file, both metainfo changes 202 * such as creation/deletion, filemode and content changes represented 203 * as a series of fragments. 204 */ 205struct patch { 206char*new_name, *old_name, *def_name; 207unsigned int old_mode, new_mode; 208int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 209int rejected; 210unsigned ws_rule; 211int lines_added, lines_deleted; 212int score; 213int extension_linenr;/* first line specifying delete/new/rename/copy */ 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) { 975char*another; 976if(isnull) 977returnerror(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 978*name, state->linenr); 979 another =find_name(state, line, NULL, state->p_value, TERM_TAB); 980if(!another ||strcmp(another, *name)) { 981free(another); 982returnerror((side == DIFF_NEW_NAME) ? 983_("git apply: bad git-diff - inconsistent new filename on line%d") : 984_("git apply: bad git-diff - inconsistent old filename on line%d"), state->linenr); 985} 986free(another); 987}else{ 988if(!starts_with(line,"/dev/null\n")) 989returnerror(_("git apply: bad git-diff - expected /dev/null on line%d"), state->linenr); 990} 991 992return0; 993} 994 995static intgitdiff_oldname(struct apply_state *state, 996const char*line, 997struct patch *patch) 998{ 999returngitdiff_verify_name(state, line,1000 patch->is_new, &patch->old_name,1001 DIFF_OLD_NAME);1002}10031004static intgitdiff_newname(struct apply_state *state,1005const char*line,1006struct patch *patch)1007{1008returngitdiff_verify_name(state, line,1009 patch->is_delete, &patch->new_name,1010 DIFF_NEW_NAME);1011}10121013static intparse_mode_line(const char*line,int linenr,unsigned int*mode)1014{1015char*end;1016*mode =strtoul(line, &end,8);1017if(end == line || !isspace(*end))1018returnerror(_("invalid mode on line%d:%s"), linenr, line);1019return0;1020}10211022static intgitdiff_oldmode(struct apply_state *state,1023const char*line,1024struct patch *patch)1025{1026returnparse_mode_line(line, state->linenr, &patch->old_mode);1027}10281029static intgitdiff_newmode(struct apply_state *state,1030const char*line,1031struct patch *patch)1032{1033returnparse_mode_line(line, state->linenr, &patch->new_mode);1034}10351036static intgitdiff_delete(struct apply_state *state,1037const char*line,1038struct patch *patch)1039{1040 patch->is_delete =1;1041free(patch->old_name);1042 patch->old_name =xstrdup_or_null(patch->def_name);1043returngitdiff_oldmode(state, line, patch);1044}10451046static intgitdiff_newfile(struct apply_state *state,1047const char*line,1048struct patch *patch)1049{1050 patch->is_new =1;1051free(patch->new_name);1052 patch->new_name =xstrdup_or_null(patch->def_name);1053returngitdiff_newmode(state, line, patch);1054}10551056static intgitdiff_copysrc(struct apply_state *state,1057const char*line,1058struct patch *patch)1059{1060 patch->is_copy =1;1061free(patch->old_name);1062 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1063return0;1064}10651066static intgitdiff_copydst(struct apply_state *state,1067const char*line,1068struct patch *patch)1069{1070 patch->is_copy =1;1071free(patch->new_name);1072 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1073return0;1074}10751076static intgitdiff_renamesrc(struct apply_state *state,1077const char*line,1078struct patch *patch)1079{1080 patch->is_rename =1;1081free(patch->old_name);1082 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1083return0;1084}10851086static intgitdiff_renamedst(struct apply_state *state,1087const char*line,1088struct patch *patch)1089{1090 patch->is_rename =1;1091free(patch->new_name);1092 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1093return0;1094}10951096static intgitdiff_similarity(struct apply_state *state,1097const char*line,1098struct patch *patch)1099{1100unsigned long val =strtoul(line, NULL,10);1101if(val <=100)1102 patch->score = val;1103return0;1104}11051106static intgitdiff_dissimilarity(struct apply_state *state,1107const char*line,1108struct patch *patch)1109{1110unsigned long val =strtoul(line, NULL,10);1111if(val <=100)1112 patch->score = val;1113return0;1114}11151116static intgitdiff_index(struct apply_state *state,1117const char*line,1118struct patch *patch)1119{1120/*1121 * index line is N hexadecimal, "..", N hexadecimal,1122 * and optional space with octal mode.1123 */1124const char*ptr, *eol;1125int len;11261127 ptr =strchr(line,'.');1128if(!ptr || ptr[1] !='.'||40< ptr - line)1129return0;1130 len = ptr - line;1131memcpy(patch->old_sha1_prefix, line, len);1132 patch->old_sha1_prefix[len] =0;11331134 line = ptr +2;1135 ptr =strchr(line,' ');1136 eol =strchrnul(line,'\n');11371138if(!ptr || eol < ptr)1139 ptr = eol;1140 len = ptr - line;11411142if(40< len)1143return0;1144memcpy(patch->new_sha1_prefix, line, len);1145 patch->new_sha1_prefix[len] =0;1146if(*ptr ==' ')1147returngitdiff_oldmode(state, ptr +1, patch);1148return0;1149}11501151/*1152 * This is normal for a diff that doesn't change anything: we'll fall through1153 * into the next diff. Tell the parser to break out.1154 */1155static intgitdiff_unrecognized(struct apply_state *state,1156const char*line,1157struct patch *patch)1158{1159return1;1160}11611162/*1163 * Skip p_value leading components from "line"; as we do not accept1164 * absolute paths, return NULL in that case.1165 */1166static const char*skip_tree_prefix(struct apply_state *state,1167const char*line,1168int llen)1169{1170int nslash;1171int i;11721173if(!state->p_value)1174return(llen && line[0] =='/') ? NULL : line;11751176 nslash = state->p_value;1177for(i =0; i < llen; i++) {1178int ch = line[i];1179if(ch =='/'&& --nslash <=0)1180return(i ==0) ? NULL : &line[i +1];1181}1182return NULL;1183}11841185/*1186 * This is to extract the same name that appears on "diff --git"1187 * line. We do not find and return anything if it is a rename1188 * patch, and it is OK because we will find the name elsewhere.1189 * We need to reliably find name only when it is mode-change only,1190 * creation or deletion of an empty file. In any of these cases,1191 * both sides are the same name under a/ and b/ respectively.1192 */1193static char*git_header_name(struct apply_state *state,1194const char*line,1195int llen)1196{1197const char*name;1198const char*second = NULL;1199size_t len, line_len;12001201 line +=strlen("diff --git ");1202 llen -=strlen("diff --git ");12031204if(*line =='"') {1205const char*cp;1206struct strbuf first = STRBUF_INIT;1207struct strbuf sp = STRBUF_INIT;12081209if(unquote_c_style(&first, line, &second))1210goto free_and_fail1;12111212/* strip the a/b prefix including trailing slash */1213 cp =skip_tree_prefix(state, first.buf, first.len);1214if(!cp)1215goto free_and_fail1;1216strbuf_remove(&first,0, cp - first.buf);12171218/*1219 * second points at one past closing dq of name.1220 * find the second name.1221 */1222while((second < line + llen) &&isspace(*second))1223 second++;12241225if(line + llen <= second)1226goto free_and_fail1;1227if(*second =='"') {1228if(unquote_c_style(&sp, second, NULL))1229goto free_and_fail1;1230 cp =skip_tree_prefix(state, sp.buf, sp.len);1231if(!cp)1232goto free_and_fail1;1233/* They must match, otherwise ignore */1234if(strcmp(cp, first.buf))1235goto free_and_fail1;1236strbuf_release(&sp);1237returnstrbuf_detach(&first, NULL);1238}12391240/* unquoted second */1241 cp =skip_tree_prefix(state, second, line + llen - second);1242if(!cp)1243goto free_and_fail1;1244if(line + llen - cp != first.len ||1245memcmp(first.buf, cp, first.len))1246goto free_and_fail1;1247returnstrbuf_detach(&first, NULL);12481249 free_and_fail1:1250strbuf_release(&first);1251strbuf_release(&sp);1252return NULL;1253}12541255/* unquoted first name */1256 name =skip_tree_prefix(state, line, llen);1257if(!name)1258return NULL;12591260/*1261 * since the first name is unquoted, a dq if exists must be1262 * the beginning of the second name.1263 */1264for(second = name; second < line + llen; second++) {1265if(*second =='"') {1266struct strbuf sp = STRBUF_INIT;1267const char*np;12681269if(unquote_c_style(&sp, second, NULL))1270goto free_and_fail2;12711272 np =skip_tree_prefix(state, sp.buf, sp.len);1273if(!np)1274goto free_and_fail2;12751276 len = sp.buf + sp.len - np;1277if(len < second - name &&1278!strncmp(np, name, len) &&1279isspace(name[len])) {1280/* Good */1281strbuf_remove(&sp,0, np - sp.buf);1282returnstrbuf_detach(&sp, NULL);1283}12841285 free_and_fail2:1286strbuf_release(&sp);1287return NULL;1288}1289}12901291/*1292 * Accept a name only if it shows up twice, exactly the same1293 * form.1294 */1295 second =strchr(name,'\n');1296if(!second)1297return NULL;1298 line_len = second - name;1299for(len =0; ; len++) {1300switch(name[len]) {1301default:1302continue;1303case'\n':1304return NULL;1305case'\t':case' ':1306/*1307 * Is this the separator between the preimage1308 * and the postimage pathname? Again, we are1309 * only interested in the case where there is1310 * no rename, as this is only to set def_name1311 * and a rename patch has the names elsewhere1312 * in an unambiguous form.1313 */1314if(!name[len +1])1315return NULL;/* no postimage name */1316 second =skip_tree_prefix(state, name + len +1,1317 line_len - (len +1));1318if(!second)1319return NULL;1320/*1321 * Does len bytes starting at "name" and "second"1322 * (that are separated by one HT or SP we just1323 * found) exactly match?1324 */1325if(second[len] =='\n'&& !strncmp(name, second, len))1326returnxmemdupz(name, len);1327}1328}1329}13301331static intcheck_header_line(struct apply_state *state,struct patch *patch)1332{1333int extensions = (patch->is_delete ==1) + (patch->is_new ==1) +1334(patch->is_rename ==1) + (patch->is_copy ==1);1335if(extensions >1)1336returnerror(_("inconsistent header lines%dand%d"),1337 patch->extension_linenr, state->linenr);1338if(extensions && !patch->extension_linenr)1339 patch->extension_linenr = state->linenr;1340return0;1341}13421343/* Verify that we recognize the lines following a git header */1344static intparse_git_header(struct apply_state *state,1345const char*line,1346int len,1347unsigned int size,1348struct patch *patch)1349{1350unsigned long offset;13511352/* A git diff has explicit new/delete information, so we don't guess */1353 patch->is_new =0;1354 patch->is_delete =0;13551356/*1357 * Some things may not have the old name in the1358 * rest of the headers anywhere (pure mode changes,1359 * or removing or adding empty files), so we get1360 * the default name from the header.1361 */1362 patch->def_name =git_header_name(state, line, len);1363if(patch->def_name && state->root.len) {1364char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1365free(patch->def_name);1366 patch->def_name = s;1367}13681369 line += len;1370 size -= len;1371 state->linenr++;1372for(offset = len ; size >0; offset += len, size -= len, line += len, state->linenr++) {1373static const struct opentry {1374const char*str;1375int(*fn)(struct apply_state *,const char*,struct patch *);1376} optable[] = {1377{"@@ -", gitdiff_hdrend },1378{"--- ", gitdiff_oldname },1379{"+++ ", gitdiff_newname },1380{"old mode ", gitdiff_oldmode },1381{"new mode ", gitdiff_newmode },1382{"deleted file mode ", gitdiff_delete },1383{"new file mode ", gitdiff_newfile },1384{"copy from ", gitdiff_copysrc },1385{"copy to ", gitdiff_copydst },1386{"rename old ", gitdiff_renamesrc },1387{"rename new ", gitdiff_renamedst },1388{"rename from ", gitdiff_renamesrc },1389{"rename to ", gitdiff_renamedst },1390{"similarity index ", gitdiff_similarity },1391{"dissimilarity index ", gitdiff_dissimilarity },1392{"index ", gitdiff_index },1393{"", gitdiff_unrecognized },1394};1395int i;13961397 len =linelen(line, size);1398if(!len || line[len-1] !='\n')1399break;1400for(i =0; i <ARRAY_SIZE(optable); i++) {1401const struct opentry *p = optable + i;1402int oplen =strlen(p->str);1403int res;1404if(len < oplen ||memcmp(p->str, line, oplen))1405continue;1406 res = p->fn(state, line + oplen, patch);1407if(res <0)1408return-1;1409if(check_header_line(state, patch))1410return-1;1411if(res >0)1412return offset;1413break;1414}1415}14161417return offset;1418}14191420static intparse_num(const char*line,unsigned long*p)1421{1422char*ptr;14231424if(!isdigit(*line))1425return0;1426*p =strtoul(line, &ptr,10);1427return ptr - line;1428}14291430static intparse_range(const char*line,int len,int offset,const char*expect,1431unsigned long*p1,unsigned long*p2)1432{1433int digits, ex;14341435if(offset <0|| offset >= len)1436return-1;1437 line += offset;1438 len -= offset;14391440 digits =parse_num(line, p1);1441if(!digits)1442return-1;14431444 offset += digits;1445 line += digits;1446 len -= digits;14471448*p2 =1;1449if(*line ==',') {1450 digits =parse_num(line+1, p2);1451if(!digits)1452return-1;14531454 offset += digits+1;1455 line += digits+1;1456 len -= digits+1;1457}14581459 ex =strlen(expect);1460if(ex > len)1461return-1;1462if(memcmp(line, expect, ex))1463return-1;14641465return offset + ex;1466}14671468static voidrecount_diff(const char*line,int size,struct fragment *fragment)1469{1470int oldlines =0, newlines =0, ret =0;14711472if(size <1) {1473warning("recount: ignore empty hunk");1474return;1475}14761477for(;;) {1478int len =linelen(line, size);1479 size -= len;1480 line += len;14811482if(size <1)1483break;14841485switch(*line) {1486case' ':case'\n':1487 newlines++;1488/* fall through */1489case'-':1490 oldlines++;1491continue;1492case'+':1493 newlines++;1494continue;1495case'\\':1496continue;1497case'@':1498 ret = size <3|| !starts_with(line,"@@ ");1499break;1500case'd':1501 ret = size <5|| !starts_with(line,"diff ");1502break;1503default:1504 ret = -1;1505break;1506}1507if(ret) {1508warning(_("recount: unexpected line: %.*s"),1509(int)linelen(line, size), line);1510return;1511}1512break;1513}1514 fragment->oldlines = oldlines;1515 fragment->newlines = newlines;1516}15171518/*1519 * Parse a unified diff fragment header of the1520 * form "@@ -a,b +c,d @@"1521 */1522static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1523{1524int offset;15251526if(!len || line[len-1] !='\n')1527return-1;15281529/* Figure out the number of lines in a fragment */1530 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1531 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);15321533return offset;1534}15351536/*1537 * Find file diff header1538 *1539 * Returns:1540 * -1 if no header was found1541 * -128 in case of error1542 * the size of the header in bytes (called "offset") otherwise1543 */1544static intfind_header(struct apply_state *state,1545const char*line,1546unsigned long size,1547int*hdrsize,1548struct patch *patch)1549{1550unsigned long offset, len;15511552 patch->is_toplevel_relative =0;1553 patch->is_rename = patch->is_copy =0;1554 patch->is_new = patch->is_delete = -1;1555 patch->old_mode = patch->new_mode =0;1556 patch->old_name = patch->new_name = NULL;1557for(offset =0; size >0; offset += len, size -= len, line += len, state->linenr++) {1558unsigned long nextlen;15591560 len =linelen(line, size);1561if(!len)1562break;15631564/* Testing this early allows us to take a few shortcuts.. */1565if(len <6)1566continue;15671568/*1569 * Make sure we don't find any unconnected patch fragments.1570 * That's a sign that we didn't find a header, and that a1571 * patch has become corrupted/broken up.1572 */1573if(!memcmp("@@ -", line,4)) {1574struct fragment dummy;1575if(parse_fragment_header(line, len, &dummy) <0)1576continue;1577error(_("patch fragment without header at line%d: %.*s"),1578 state->linenr, (int)len-1, line);1579return-128;1580}15811582if(size < len +6)1583break;15841585/*1586 * Git patch? It might not have a real patch, just a rename1587 * or mode change, so we handle that specially1588 */1589if(!memcmp("diff --git ", line,11)) {1590int git_hdr_len =parse_git_header(state, line, len, size, patch);1591if(git_hdr_len <0)1592return-128;1593if(git_hdr_len <= len)1594continue;1595if(!patch->old_name && !patch->new_name) {1596if(!patch->def_name) {1597error(Q_("git diff header lacks filename information when removing "1598"%dleading pathname component (line%d)",1599"git diff header lacks filename information when removing "1600"%dleading pathname components (line%d)",1601 state->p_value),1602 state->p_value, state->linenr);1603return-128;1604}1605 patch->old_name =xstrdup(patch->def_name);1606 patch->new_name =xstrdup(patch->def_name);1607}1608if((!patch->new_name && !patch->is_delete) ||1609(!patch->old_name && !patch->is_new)) {1610error(_("git diff header lacks filename information "1611"(line%d)"), state->linenr);1612return-128;1613}1614 patch->is_toplevel_relative =1;1615*hdrsize = git_hdr_len;1616return offset;1617}16181619/* --- followed by +++ ? */1620if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1621continue;16221623/*1624 * We only accept unified patches, so we want it to1625 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1626 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1627 */1628 nextlen =linelen(line + len, size - len);1629if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1630continue;16311632/* Ok, we'll consider it a patch */1633if(parse_traditional_patch(state, line, line+len, patch))1634return-128;1635*hdrsize = len + nextlen;1636 state->linenr +=2;1637return offset;1638}1639return-1;1640}16411642static voidrecord_ws_error(struct apply_state *state,1643unsigned result,1644const char*line,1645int len,1646int linenr)1647{1648char*err;16491650if(!result)1651return;16521653 state->whitespace_error++;1654if(state->squelch_whitespace_errors &&1655 state->squelch_whitespace_errors < state->whitespace_error)1656return;16571658 err =whitespace_error_string(result);1659if(state->apply_verbosity > verbosity_silent)1660fprintf(stderr,"%s:%d:%s.\n%.*s\n",1661 state->patch_input_file, linenr, err, len, line);1662free(err);1663}16641665static voidcheck_whitespace(struct apply_state *state,1666const char*line,1667int len,1668unsigned ws_rule)1669{1670unsigned result =ws_check(line +1, len -1, ws_rule);16711672record_ws_error(state, result, line +1, len -2, state->linenr);1673}16741675/*1676 * Parse a unified diff. Note that this really needs to parse each1677 * fragment separately, since the only way to know the difference1678 * between a "---" that is part of a patch, and a "---" that starts1679 * the next patch is to look at the line counts..1680 */1681static intparse_fragment(struct apply_state *state,1682const char*line,1683unsigned long size,1684struct patch *patch,1685struct fragment *fragment)1686{1687int added, deleted;1688int len =linelen(line, size), offset;1689unsigned long oldlines, newlines;1690unsigned long leading, trailing;16911692 offset =parse_fragment_header(line, len, fragment);1693if(offset <0)1694return-1;1695if(offset >0&& patch->recount)1696recount_diff(line + offset, size - offset, fragment);1697 oldlines = fragment->oldlines;1698 newlines = fragment->newlines;1699 leading =0;1700 trailing =0;17011702/* Parse the thing.. */1703 line += len;1704 size -= len;1705 state->linenr++;1706 added = deleted =0;1707for(offset = len;17080< size;1709 offset += len, size -= len, line += len, state->linenr++) {1710if(!oldlines && !newlines)1711break;1712 len =linelen(line, size);1713if(!len || line[len-1] !='\n')1714return-1;1715switch(*line) {1716default:1717return-1;1718case'\n':/* newer GNU diff, an empty context line */1719case' ':1720 oldlines--;1721 newlines--;1722if(!deleted && !added)1723 leading++;1724 trailing++;1725if(!state->apply_in_reverse &&1726 state->ws_error_action == correct_ws_error)1727check_whitespace(state, line, len, patch->ws_rule);1728break;1729case'-':1730if(state->apply_in_reverse &&1731 state->ws_error_action != nowarn_ws_error)1732check_whitespace(state, line, len, patch->ws_rule);1733 deleted++;1734 oldlines--;1735 trailing =0;1736break;1737case'+':1738if(!state->apply_in_reverse &&1739 state->ws_error_action != nowarn_ws_error)1740check_whitespace(state, line, len, patch->ws_rule);1741 added++;1742 newlines--;1743 trailing =0;1744break;17451746/*1747 * We allow "\ No newline at end of file". Depending1748 * on locale settings when the patch was produced we1749 * don't know what this line looks like. The only1750 * thing we do know is that it begins with "\ ".1751 * Checking for 12 is just for sanity check -- any1752 * l10n of "\ No newline..." is at least that long.1753 */1754case'\\':1755if(len <12||memcmp(line,"\\",2))1756return-1;1757break;1758}1759}1760if(oldlines || newlines)1761return-1;1762if(!deleted && !added)1763return-1;17641765 fragment->leading = leading;1766 fragment->trailing = trailing;17671768/*1769 * If a fragment ends with an incomplete line, we failed to include1770 * it in the above loop because we hit oldlines == newlines == 01771 * before seeing it.1772 */1773if(12< size && !memcmp(line,"\\",2))1774 offset +=linelen(line, size);17751776 patch->lines_added += added;1777 patch->lines_deleted += deleted;17781779if(0< patch->is_new && oldlines)1780returnerror(_("new file depends on old contents"));1781if(0< patch->is_delete && newlines)1782returnerror(_("deleted file still has contents"));1783return offset;1784}17851786/*1787 * We have seen "diff --git a/... b/..." header (or a traditional patch1788 * header). Read hunks that belong to this patch into fragments and hang1789 * them to the given patch structure.1790 *1791 * The (fragment->patch, fragment->size) pair points into the memory given1792 * by the caller, not a copy, when we return.1793 *1794 * Returns:1795 * -1 in case of error,1796 * the number of bytes in the patch otherwise.1797 */1798static intparse_single_patch(struct apply_state *state,1799const char*line,1800unsigned long size,1801struct patch *patch)1802{1803unsigned long offset =0;1804unsigned long oldlines =0, newlines =0, context =0;1805struct fragment **fragp = &patch->fragments;18061807while(size >4&& !memcmp(line,"@@ -",4)) {1808struct fragment *fragment;1809int len;18101811 fragment =xcalloc(1,sizeof(*fragment));1812 fragment->linenr = state->linenr;1813 len =parse_fragment(state, line, size, patch, fragment);1814if(len <=0) {1815free(fragment);1816returnerror(_("corrupt patch at line%d"), state->linenr);1817}1818 fragment->patch = line;1819 fragment->size = len;1820 oldlines += fragment->oldlines;1821 newlines += fragment->newlines;1822 context += fragment->leading + fragment->trailing;18231824*fragp = fragment;1825 fragp = &fragment->next;18261827 offset += len;1828 line += len;1829 size -= len;1830}18311832/*1833 * If something was removed (i.e. we have old-lines) it cannot1834 * be creation, and if something was added it cannot be1835 * deletion. However, the reverse is not true; --unified=01836 * patches that only add are not necessarily creation even1837 * though they do not have any old lines, and ones that only1838 * delete are not necessarily deletion.1839 *1840 * Unfortunately, a real creation/deletion patch do _not_ have1841 * any context line by definition, so we cannot safely tell it1842 * apart with --unified=0 insanity. At least if the patch has1843 * more than one hunk it is not creation or deletion.1844 */1845if(patch->is_new <0&&1846(oldlines || (patch->fragments && patch->fragments->next)))1847 patch->is_new =0;1848if(patch->is_delete <0&&1849(newlines || (patch->fragments && patch->fragments->next)))1850 patch->is_delete =0;18511852if(0< patch->is_new && oldlines)1853returnerror(_("new file%sdepends on old contents"), patch->new_name);1854if(0< patch->is_delete && newlines)1855returnerror(_("deleted file%sstill has contents"), patch->old_name);1856if(!patch->is_delete && !newlines && context && state->apply_verbosity > verbosity_silent)1857fprintf_ln(stderr,1858_("** warning: "1859"file%sbecomes empty but is not deleted"),1860 patch->new_name);18611862return offset;1863}18641865staticinlineintmetadata_changes(struct patch *patch)1866{1867return patch->is_rename >0||1868 patch->is_copy >0||1869 patch->is_new >0||1870 patch->is_delete ||1871(patch->old_mode && patch->new_mode &&1872 patch->old_mode != patch->new_mode);1873}18741875static char*inflate_it(const void*data,unsigned long size,1876unsigned long inflated_size)1877{1878 git_zstream stream;1879void*out;1880int st;18811882memset(&stream,0,sizeof(stream));18831884 stream.next_in = (unsigned char*)data;1885 stream.avail_in = size;1886 stream.next_out = out =xmalloc(inflated_size);1887 stream.avail_out = inflated_size;1888git_inflate_init(&stream);1889 st =git_inflate(&stream, Z_FINISH);1890git_inflate_end(&stream);1891if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1892free(out);1893return NULL;1894}1895return out;1896}18971898/*1899 * Read a binary hunk and return a new fragment; fragment->patch1900 * points at an allocated memory that the caller must free, so1901 * it is marked as "->free_patch = 1".1902 */1903static struct fragment *parse_binary_hunk(struct apply_state *state,1904char**buf_p,1905unsigned long*sz_p,1906int*status_p,1907int*used_p)1908{1909/*1910 * Expect a line that begins with binary patch method ("literal"1911 * or "delta"), followed by the length of data before deflating.1912 * a sequence of 'length-byte' followed by base-85 encoded data1913 * should follow, terminated by a newline.1914 *1915 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1916 * and we would limit the patch line to 66 characters,1917 * so one line can fit up to 13 groups that would decode1918 * to 52 bytes max. The length byte 'A'-'Z' corresponds1919 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1920 */1921int llen, used;1922unsigned long size = *sz_p;1923char*buffer = *buf_p;1924int patch_method;1925unsigned long origlen;1926char*data = NULL;1927int hunk_size =0;1928struct fragment *frag;19291930 llen =linelen(buffer, size);1931 used = llen;19321933*status_p =0;19341935if(starts_with(buffer,"delta ")) {1936 patch_method = BINARY_DELTA_DEFLATED;1937 origlen =strtoul(buffer +6, NULL,10);1938}1939else if(starts_with(buffer,"literal ")) {1940 patch_method = BINARY_LITERAL_DEFLATED;1941 origlen =strtoul(buffer +8, NULL,10);1942}1943else1944return NULL;19451946 state->linenr++;1947 buffer += llen;1948while(1) {1949int byte_length, max_byte_length, newsize;1950 llen =linelen(buffer, size);1951 used += llen;1952 state->linenr++;1953if(llen ==1) {1954/* consume the blank line */1955 buffer++;1956 size--;1957break;1958}1959/*1960 * Minimum line is "A00000\n" which is 7-byte long,1961 * and the line length must be multiple of 5 plus 2.1962 */1963if((llen <7) || (llen-2) %5)1964goto corrupt;1965 max_byte_length = (llen -2) /5*4;1966 byte_length = *buffer;1967if('A'<= byte_length && byte_length <='Z')1968 byte_length = byte_length -'A'+1;1969else if('a'<= byte_length && byte_length <='z')1970 byte_length = byte_length -'a'+27;1971else1972goto corrupt;1973/* if the input length was not multiple of 4, we would1974 * have filler at the end but the filler should never1975 * exceed 3 bytes1976 */1977if(max_byte_length < byte_length ||1978 byte_length <= max_byte_length -4)1979goto corrupt;1980 newsize = hunk_size + byte_length;1981 data =xrealloc(data, newsize);1982if(decode_85(data + hunk_size, buffer +1, byte_length))1983goto corrupt;1984 hunk_size = newsize;1985 buffer += llen;1986 size -= llen;1987}19881989 frag =xcalloc(1,sizeof(*frag));1990 frag->patch =inflate_it(data, hunk_size, origlen);1991 frag->free_patch =1;1992if(!frag->patch)1993goto corrupt;1994free(data);1995 frag->size = origlen;1996*buf_p = buffer;1997*sz_p = size;1998*used_p = used;1999 frag->binary_patch_method = patch_method;2000return frag;20012002 corrupt:2003free(data);2004*status_p = -1;2005error(_("corrupt binary patch at line%d: %.*s"),2006 state->linenr-1, llen-1, buffer);2007return NULL;2008}20092010/*2011 * Returns:2012 * -1 in case of error,2013 * the length of the parsed binary patch otherwise2014 */2015static intparse_binary(struct apply_state *state,2016char*buffer,2017unsigned long size,2018struct patch *patch)2019{2020/*2021 * We have read "GIT binary patch\n"; what follows is a line2022 * that says the patch method (currently, either "literal" or2023 * "delta") and the length of data before deflating; a2024 * sequence of 'length-byte' followed by base-85 encoded data2025 * follows.2026 *2027 * When a binary patch is reversible, there is another binary2028 * hunk in the same format, starting with patch method (either2029 * "literal" or "delta") with the length of data, and a sequence2030 * of length-byte + base-85 encoded data, terminated with another2031 * empty line. This data, when applied to the postimage, produces2032 * the preimage.2033 */2034struct fragment *forward;2035struct fragment *reverse;2036int status;2037int used, used_1;20382039 forward =parse_binary_hunk(state, &buffer, &size, &status, &used);2040if(!forward && !status)2041/* there has to be one hunk (forward hunk) */2042returnerror(_("unrecognized binary patch at line%d"), state->linenr-1);2043if(status)2044/* otherwise we already gave an error message */2045return status;20462047 reverse =parse_binary_hunk(state, &buffer, &size, &status, &used_1);2048if(reverse)2049 used += used_1;2050else if(status) {2051/*2052 * Not having reverse hunk is not an error, but having2053 * a corrupt reverse hunk is.2054 */2055free((void*) forward->patch);2056free(forward);2057return status;2058}2059 forward->next = reverse;2060 patch->fragments = forward;2061 patch->is_binary =1;2062return used;2063}20642065static voidprefix_one(struct apply_state *state,char**name)2066{2067char*old_name = *name;2068if(!old_name)2069return;2070*name =prefix_filename(state->prefix, *name);2071free(old_name);2072}20732074static voidprefix_patch(struct apply_state *state,struct patch *p)2075{2076if(!state->prefix || p->is_toplevel_relative)2077return;2078prefix_one(state, &p->new_name);2079prefix_one(state, &p->old_name);2080}20812082/*2083 * include/exclude2084 */20852086static voidadd_name_limit(struct apply_state *state,2087const char*name,2088int exclude)2089{2090struct string_list_item *it;20912092 it =string_list_append(&state->limit_by_name, name);2093 it->util = exclude ? NULL : (void*)1;2094}20952096static intuse_patch(struct apply_state *state,struct patch *p)2097{2098const char*pathname = p->new_name ? p->new_name : p->old_name;2099int i;21002101/* Paths outside are not touched regardless of "--include" */2102if(0< state->prefix_length) {2103int pathlen =strlen(pathname);2104if(pathlen <= state->prefix_length ||2105memcmp(state->prefix, pathname, state->prefix_length))2106return0;2107}21082109/* See if it matches any of exclude/include rule */2110for(i =0; i < state->limit_by_name.nr; i++) {2111struct string_list_item *it = &state->limit_by_name.items[i];2112if(!wildmatch(it->string, pathname,0, NULL))2113return(it->util != NULL);2114}21152116/*2117 * If we had any include, a path that does not match any rule is2118 * not used. Otherwise, we saw bunch of exclude rules (or none)2119 * and such a path is used.2120 */2121return!state->has_include;2122}21232124/*2125 * Read the patch text in "buffer" that extends for "size" bytes; stop2126 * reading after seeing a single patch (i.e. changes to a single file).2127 * Create fragments (i.e. patch hunks) and hang them to the given patch.2128 *2129 * Returns:2130 * -1 if no header was found or parse_binary() failed,2131 * -128 on another error,2132 * the number of bytes consumed otherwise,2133 * so that the caller can call us again for the next patch.2134 */2135static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2136{2137int hdrsize, patchsize;2138int offset =find_header(state, buffer, size, &hdrsize, patch);21392140if(offset <0)2141return offset;21422143prefix_patch(state, patch);21442145if(!use_patch(state, patch))2146 patch->ws_rule =0;2147else2148 patch->ws_rule =whitespace_rule(patch->new_name2149? patch->new_name2150: patch->old_name);21512152 patchsize =parse_single_patch(state,2153 buffer + offset + hdrsize,2154 size - offset - hdrsize,2155 patch);21562157if(patchsize <0)2158return-128;21592160if(!patchsize) {2161static const char git_binary[] ="GIT binary patch\n";2162int hd = hdrsize + offset;2163unsigned long llen =linelen(buffer + hd, size - hd);21642165if(llen ==sizeof(git_binary) -1&&2166!memcmp(git_binary, buffer + hd, llen)) {2167int used;2168 state->linenr++;2169 used =parse_binary(state, buffer + hd + llen,2170 size - hd - llen, patch);2171if(used <0)2172return-1;2173if(used)2174 patchsize = used + llen;2175else2176 patchsize =0;2177}2178else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2179static const char*binhdr[] = {2180"Binary files ",2181"Files ",2182 NULL,2183};2184int i;2185for(i =0; binhdr[i]; i++) {2186int len =strlen(binhdr[i]);2187if(len < size - hd &&2188!memcmp(binhdr[i], buffer + hd, len)) {2189 state->linenr++;2190 patch->is_binary =1;2191 patchsize = llen;2192break;2193}2194}2195}21962197/* Empty patch cannot be applied if it is a text patch2198 * without metadata change. A binary patch appears2199 * empty to us here.2200 */2201if((state->apply || state->check) &&2202(!patch->is_binary && !metadata_changes(patch))) {2203error(_("patch with only garbage at line%d"), state->linenr);2204return-128;2205}2206}22072208return offset + hdrsize + patchsize;2209}22102211static voidreverse_patches(struct patch *p)2212{2213for(; p; p = p->next) {2214struct fragment *frag = p->fragments;22152216SWAP(p->new_name, p->old_name);2217SWAP(p->new_mode, p->old_mode);2218SWAP(p->is_new, p->is_delete);2219SWAP(p->lines_added, p->lines_deleted);2220SWAP(p->old_sha1_prefix, p->new_sha1_prefix);22212222for(; frag; frag = frag->next) {2223SWAP(frag->newpos, frag->oldpos);2224SWAP(frag->newlines, frag->oldlines);2225}2226}2227}22282229static const char pluses[] =2230"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2231static const char minuses[]=2232"----------------------------------------------------------------------";22332234static voidshow_stats(struct apply_state *state,struct patch *patch)2235{2236struct strbuf qname = STRBUF_INIT;2237char*cp = patch->new_name ? patch->new_name : patch->old_name;2238int max, add, del;22392240quote_c_style(cp, &qname, NULL,0);22412242/*2243 * "scale" the filename2244 */2245 max = state->max_len;2246if(max >50)2247 max =50;22482249if(qname.len > max) {2250 cp =strchr(qname.buf + qname.len +3- max,'/');2251if(!cp)2252 cp = qname.buf + qname.len +3- max;2253strbuf_splice(&qname,0, cp - qname.buf,"...",3);2254}22552256if(patch->is_binary) {2257printf(" %-*s | Bin\n", max, qname.buf);2258strbuf_release(&qname);2259return;2260}22612262printf(" %-*s |", max, qname.buf);2263strbuf_release(&qname);22642265/*2266 * scale the add/delete2267 */2268 max = max + state->max_change >70?70- max : state->max_change;2269 add = patch->lines_added;2270 del = patch->lines_deleted;22712272if(state->max_change >0) {2273int total = ((add + del) * max + state->max_change /2) / state->max_change;2274 add = (add * max + state->max_change /2) / state->max_change;2275 del = total - add;2276}2277printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2278 add, pluses, del, minuses);2279}22802281static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2282{2283switch(st->st_mode & S_IFMT) {2284case S_IFLNK:2285if(strbuf_readlink(buf, path, st->st_size) <0)2286returnerror(_("unable to read symlink%s"), path);2287return0;2288case S_IFREG:2289if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2290returnerror(_("unable to open or read%s"), path);2291convert_to_git(path, buf->buf, buf->len, buf,0);2292return0;2293default:2294return-1;2295}2296}22972298/*2299 * Update the preimage, and the common lines in postimage,2300 * from buffer buf of length len. If postlen is 0 the postimage2301 * is updated in place, otherwise it's updated on a new buffer2302 * of length postlen2303 */23042305static voidupdate_pre_post_images(struct image *preimage,2306struct image *postimage,2307char*buf,2308size_t len,size_t postlen)2309{2310int i, ctx, reduced;2311char*new, *old, *fixed;2312struct image fixed_preimage;23132314/*2315 * Update the preimage with whitespace fixes. Note that we2316 * are not losing preimage->buf -- apply_one_fragment() will2317 * free "oldlines".2318 */2319prepare_image(&fixed_preimage, buf, len,1);2320assert(postlen2321? fixed_preimage.nr == preimage->nr2322: fixed_preimage.nr <= preimage->nr);2323for(i =0; i < fixed_preimage.nr; i++)2324 fixed_preimage.line[i].flag = preimage->line[i].flag;2325free(preimage->line_allocated);2326*preimage = fixed_preimage;23272328/*2329 * Adjust the common context lines in postimage. This can be2330 * done in-place when we are shrinking it with whitespace2331 * fixing, but needs a new buffer when ignoring whitespace or2332 * expanding leading tabs to spaces.2333 *2334 * We trust the caller to tell us if the update can be done2335 * in place (postlen==0) or not.2336 */2337 old = postimage->buf;2338if(postlen)2339new= postimage->buf =xmalloc(postlen);2340else2341new= old;2342 fixed = preimage->buf;23432344for(i = reduced = ctx =0; i < postimage->nr; i++) {2345size_t l_len = postimage->line[i].len;2346if(!(postimage->line[i].flag & LINE_COMMON)) {2347/* an added line -- no counterparts in preimage */2348memmove(new, old, l_len);2349 old += l_len;2350new+= l_len;2351continue;2352}23532354/* a common context -- skip it in the original postimage */2355 old += l_len;23562357/* and find the corresponding one in the fixed preimage */2358while(ctx < preimage->nr &&2359!(preimage->line[ctx].flag & LINE_COMMON)) {2360 fixed += preimage->line[ctx].len;2361 ctx++;2362}23632364/*2365 * preimage is expected to run out, if the caller2366 * fixed addition of trailing blank lines.2367 */2368if(preimage->nr <= ctx) {2369 reduced++;2370continue;2371}23722373/* and copy it in, while fixing the line length */2374 l_len = preimage->line[ctx].len;2375memcpy(new, fixed, l_len);2376new+= l_len;2377 fixed += l_len;2378 postimage->line[i].len = l_len;2379 ctx++;2380}23812382if(postlen2383? postlen <new- postimage->buf2384: postimage->len <new- postimage->buf)2385die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2386(int)postlen, (int) postimage->len, (int)(new- postimage->buf));23872388/* Fix the length of the whole thing */2389 postimage->len =new- postimage->buf;2390 postimage->nr -= reduced;2391}23922393static intline_by_line_fuzzy_match(struct image *img,2394struct image *preimage,2395struct image *postimage,2396unsigned longtry,2397int try_lno,2398int preimage_limit)2399{2400int i;2401size_t imgoff =0;2402size_t preoff =0;2403size_t postlen = postimage->len;2404size_t extra_chars;2405char*buf;2406char*preimage_eof;2407char*preimage_end;2408struct strbuf fixed;2409char*fixed_buf;2410size_t fixed_len;24112412for(i =0; i < preimage_limit; i++) {2413size_t prelen = preimage->line[i].len;2414size_t imglen = img->line[try_lno+i].len;24152416if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2417 preimage->buf + preoff, prelen))2418return0;2419if(preimage->line[i].flag & LINE_COMMON)2420 postlen += imglen - prelen;2421 imgoff += imglen;2422 preoff += prelen;2423}24242425/*2426 * Ok, the preimage matches with whitespace fuzz.2427 *2428 * imgoff now holds the true length of the target that2429 * matches the preimage before the end of the file.2430 *2431 * Count the number of characters in the preimage that fall2432 * beyond the end of the file and make sure that all of them2433 * are whitespace characters. (This can only happen if2434 * we are removing blank lines at the end of the file.)2435 */2436 buf = preimage_eof = preimage->buf + preoff;2437for( ; i < preimage->nr; i++)2438 preoff += preimage->line[i].len;2439 preimage_end = preimage->buf + preoff;2440for( ; buf < preimage_end; buf++)2441if(!isspace(*buf))2442return0;24432444/*2445 * Update the preimage and the common postimage context2446 * lines to use the same whitespace as the target.2447 * If whitespace is missing in the target (i.e.2448 * if the preimage extends beyond the end of the file),2449 * use the whitespace from the preimage.2450 */2451 extra_chars = preimage_end - preimage_eof;2452strbuf_init(&fixed, imgoff + extra_chars);2453strbuf_add(&fixed, img->buf +try, imgoff);2454strbuf_add(&fixed, preimage_eof, extra_chars);2455 fixed_buf =strbuf_detach(&fixed, &fixed_len);2456update_pre_post_images(preimage, postimage,2457 fixed_buf, fixed_len, postlen);2458return1;2459}24602461static intmatch_fragment(struct apply_state *state,2462struct image *img,2463struct image *preimage,2464struct image *postimage,2465unsigned longtry,2466int try_lno,2467unsigned ws_rule,2468int match_beginning,int match_end)2469{2470int i;2471char*fixed_buf, *buf, *orig, *target;2472struct strbuf fixed;2473size_t fixed_len, postlen;2474int preimage_limit;24752476if(preimage->nr + try_lno <= img->nr) {2477/*2478 * The hunk falls within the boundaries of img.2479 */2480 preimage_limit = preimage->nr;2481if(match_end && (preimage->nr + try_lno != img->nr))2482return0;2483}else if(state->ws_error_action == correct_ws_error &&2484(ws_rule & WS_BLANK_AT_EOF)) {2485/*2486 * This hunk extends beyond the end of img, and we are2487 * removing blank lines at the end of the file. This2488 * many lines from the beginning of the preimage must2489 * match with img, and the remainder of the preimage2490 * must be blank.2491 */2492 preimage_limit = img->nr - try_lno;2493}else{2494/*2495 * The hunk extends beyond the end of the img and2496 * we are not removing blanks at the end, so we2497 * should reject the hunk at this position.2498 */2499return0;2500}25012502if(match_beginning && try_lno)2503return0;25042505/* Quick hash check */2506for(i =0; i < preimage_limit; i++)2507if((img->line[try_lno + i].flag & LINE_PATCHED) ||2508(preimage->line[i].hash != img->line[try_lno + i].hash))2509return0;25102511if(preimage_limit == preimage->nr) {2512/*2513 * Do we have an exact match? If we were told to match2514 * at the end, size must be exactly at try+fragsize,2515 * otherwise try+fragsize must be still within the preimage,2516 * and either case, the old piece should match the preimage2517 * exactly.2518 */2519if((match_end2520? (try+ preimage->len == img->len)2521: (try+ preimage->len <= img->len)) &&2522!memcmp(img->buf +try, preimage->buf, preimage->len))2523return1;2524}else{2525/*2526 * The preimage extends beyond the end of img, so2527 * there cannot be an exact match.2528 *2529 * There must be one non-blank context line that match2530 * a line before the end of img.2531 */2532char*buf_end;25332534 buf = preimage->buf;2535 buf_end = buf;2536for(i =0; i < preimage_limit; i++)2537 buf_end += preimage->line[i].len;25382539for( ; buf < buf_end; buf++)2540if(!isspace(*buf))2541break;2542if(buf == buf_end)2543return0;2544}25452546/*2547 * No exact match. If we are ignoring whitespace, run a line-by-line2548 * fuzzy matching. We collect all the line length information because2549 * we need it to adjust whitespace if we match.2550 */2551if(state->ws_ignore_action == ignore_ws_change)2552returnline_by_line_fuzzy_match(img, preimage, postimage,2553try, try_lno, preimage_limit);25542555if(state->ws_error_action != correct_ws_error)2556return0;25572558/*2559 * The hunk does not apply byte-by-byte, but the hash says2560 * it might with whitespace fuzz. We weren't asked to2561 * ignore whitespace, we were asked to correct whitespace2562 * errors, so let's try matching after whitespace correction.2563 *2564 * While checking the preimage against the target, whitespace2565 * errors in both fixed, we count how large the corresponding2566 * postimage needs to be. The postimage prepared by2567 * apply_one_fragment() has whitespace errors fixed on added2568 * lines already, but the common lines were propagated as-is,2569 * which may become longer when their whitespace errors are2570 * fixed.2571 */25722573/* First count added lines in postimage */2574 postlen =0;2575for(i =0; i < postimage->nr; i++) {2576if(!(postimage->line[i].flag & LINE_COMMON))2577 postlen += postimage->line[i].len;2578}25792580/*2581 * The preimage may extend beyond the end of the file,2582 * but in this loop we will only handle the part of the2583 * preimage that falls within the file.2584 */2585strbuf_init(&fixed, preimage->len +1);2586 orig = preimage->buf;2587 target = img->buf +try;2588for(i =0; i < preimage_limit; i++) {2589size_t oldlen = preimage->line[i].len;2590size_t tgtlen = img->line[try_lno + i].len;2591size_t fixstart = fixed.len;2592struct strbuf tgtfix;2593int match;25942595/* Try fixing the line in the preimage */2596ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25972598/* Try fixing the line in the target */2599strbuf_init(&tgtfix, tgtlen);2600ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);26012602/*2603 * If they match, either the preimage was based on2604 * a version before our tree fixed whitespace breakage,2605 * or we are lacking a whitespace-fix patch the tree2606 * the preimage was based on already had (i.e. target2607 * has whitespace breakage, the preimage doesn't).2608 * In either case, we are fixing the whitespace breakages2609 * so we might as well take the fix together with their2610 * real change.2611 */2612 match = (tgtfix.len == fixed.len - fixstart &&2613!memcmp(tgtfix.buf, fixed.buf + fixstart,2614 fixed.len - fixstart));26152616/* Add the length if this is common with the postimage */2617if(preimage->line[i].flag & LINE_COMMON)2618 postlen += tgtfix.len;26192620strbuf_release(&tgtfix);2621if(!match)2622goto unmatch_exit;26232624 orig += oldlen;2625 target += tgtlen;2626}262726282629/*2630 * Now handle the lines in the preimage that falls beyond the2631 * end of the file (if any). They will only match if they are2632 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2633 * false).2634 */2635for( ; i < preimage->nr; i++) {2636size_t fixstart = fixed.len;/* start of the fixed preimage */2637size_t oldlen = preimage->line[i].len;2638int j;26392640/* Try fixing the line in the preimage */2641ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);26422643for(j = fixstart; j < fixed.len; j++)2644if(!isspace(fixed.buf[j]))2645goto unmatch_exit;26462647 orig += oldlen;2648}26492650/*2651 * Yes, the preimage is based on an older version that still2652 * has whitespace breakages unfixed, and fixing them makes the2653 * hunk match. Update the context lines in the postimage.2654 */2655 fixed_buf =strbuf_detach(&fixed, &fixed_len);2656if(postlen < postimage->len)2657 postlen =0;2658update_pre_post_images(preimage, postimage,2659 fixed_buf, fixed_len, postlen);2660return1;26612662 unmatch_exit:2663strbuf_release(&fixed);2664return0;2665}26662667static intfind_pos(struct apply_state *state,2668struct image *img,2669struct image *preimage,2670struct image *postimage,2671int line,2672unsigned ws_rule,2673int match_beginning,int match_end)2674{2675int i;2676unsigned long backwards, forwards,try;2677int backwards_lno, forwards_lno, try_lno;26782679/*2680 * If match_beginning or match_end is specified, there is no2681 * point starting from a wrong line that will never match and2682 * wander around and wait for a match at the specified end.2683 */2684if(match_beginning)2685 line =0;2686else if(match_end)2687 line = img->nr - preimage->nr;26882689/*2690 * Because the comparison is unsigned, the following test2691 * will also take care of a negative line number that can2692 * result when match_end and preimage is larger than the target.2693 */2694if((size_t) line > img->nr)2695 line = img->nr;26962697try=0;2698for(i =0; i < line; i++)2699try+= img->line[i].len;27002701/*2702 * There's probably some smart way to do this, but I'll leave2703 * that to the smart and beautiful people. I'm simple and stupid.2704 */2705 backwards =try;2706 backwards_lno = line;2707 forwards =try;2708 forwards_lno = line;2709 try_lno = line;27102711for(i =0; ; i++) {2712if(match_fragment(state, img, preimage, postimage,2713try, try_lno, ws_rule,2714 match_beginning, match_end))2715return try_lno;27162717 again:2718if(backwards_lno ==0&& forwards_lno == img->nr)2719break;27202721if(i &1) {2722if(backwards_lno ==0) {2723 i++;2724goto again;2725}2726 backwards_lno--;2727 backwards -= img->line[backwards_lno].len;2728try= backwards;2729 try_lno = backwards_lno;2730}else{2731if(forwards_lno == img->nr) {2732 i++;2733goto again;2734}2735 forwards += img->line[forwards_lno].len;2736 forwards_lno++;2737try= forwards;2738 try_lno = forwards_lno;2739}27402741}2742return-1;2743}27442745static voidremove_first_line(struct image *img)2746{2747 img->buf += img->line[0].len;2748 img->len -= img->line[0].len;2749 img->line++;2750 img->nr--;2751}27522753static voidremove_last_line(struct image *img)2754{2755 img->len -= img->line[--img->nr].len;2756}27572758/*2759 * The change from "preimage" and "postimage" has been found to2760 * apply at applied_pos (counts in line numbers) in "img".2761 * Update "img" to remove "preimage" and replace it with "postimage".2762 */2763static voidupdate_image(struct apply_state *state,2764struct image *img,2765int applied_pos,2766struct image *preimage,2767struct image *postimage)2768{2769/*2770 * remove the copy of preimage at offset in img2771 * and replace it with postimage2772 */2773int i, nr;2774size_t remove_count, insert_count, applied_at =0;2775char*result;2776int preimage_limit;27772778/*2779 * If we are removing blank lines at the end of img,2780 * the preimage may extend beyond the end.2781 * If that is the case, we must be careful only to2782 * remove the part of the preimage that falls within2783 * the boundaries of img. Initialize preimage_limit2784 * to the number of lines in the preimage that falls2785 * within the boundaries.2786 */2787 preimage_limit = preimage->nr;2788if(preimage_limit > img->nr - applied_pos)2789 preimage_limit = img->nr - applied_pos;27902791for(i =0; i < applied_pos; i++)2792 applied_at += img->line[i].len;27932794 remove_count =0;2795for(i =0; i < preimage_limit; i++)2796 remove_count += img->line[applied_pos + i].len;2797 insert_count = postimage->len;27982799/* Adjust the contents */2800 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2801memcpy(result, img->buf, applied_at);2802memcpy(result + applied_at, postimage->buf, postimage->len);2803memcpy(result + applied_at + postimage->len,2804 img->buf + (applied_at + remove_count),2805 img->len - (applied_at + remove_count));2806free(img->buf);2807 img->buf = result;2808 img->len += insert_count - remove_count;2809 result[img->len] ='\0';28102811/* Adjust the line table */2812 nr = img->nr + postimage->nr - preimage_limit;2813if(preimage_limit < postimage->nr) {2814/*2815 * NOTE: this knows that we never call remove_first_line()2816 * on anything other than pre/post image.2817 */2818REALLOC_ARRAY(img->line, nr);2819 img->line_allocated = img->line;2820}2821if(preimage_limit != postimage->nr)2822memmove(img->line + applied_pos + postimage->nr,2823 img->line + applied_pos + preimage_limit,2824(img->nr - (applied_pos + preimage_limit)) *2825sizeof(*img->line));2826memcpy(img->line + applied_pos,2827 postimage->line,2828 postimage->nr *sizeof(*img->line));2829if(!state->allow_overlap)2830for(i =0; i < postimage->nr; i++)2831 img->line[applied_pos + i].flag |= LINE_PATCHED;2832 img->nr = nr;2833}28342835/*2836 * Use the patch-hunk text in "frag" to prepare two images (preimage and2837 * postimage) for the hunk. Find lines that match "preimage" in "img" and2838 * replace the part of "img" with "postimage" text.2839 */2840static intapply_one_fragment(struct apply_state *state,2841struct image *img,struct fragment *frag,2842int inaccurate_eof,unsigned ws_rule,2843int nth_fragment)2844{2845int match_beginning, match_end;2846const char*patch = frag->patch;2847int size = frag->size;2848char*old, *oldlines;2849struct strbuf newlines;2850int new_blank_lines_at_end =0;2851int found_new_blank_lines_at_end =0;2852int hunk_linenr = frag->linenr;2853unsigned long leading, trailing;2854int pos, applied_pos;2855struct image preimage;2856struct image postimage;28572858memset(&preimage,0,sizeof(preimage));2859memset(&postimage,0,sizeof(postimage));2860 oldlines =xmalloc(size);2861strbuf_init(&newlines, size);28622863 old = oldlines;2864while(size >0) {2865char first;2866int len =linelen(patch, size);2867int plen;2868int added_blank_line =0;2869int is_blank_context =0;2870size_t start;28712872if(!len)2873break;28742875/*2876 * "plen" is how much of the line we should use for2877 * the actual patch data. Normally we just remove the2878 * first character on the line, but if the line is2879 * followed by "\ No newline", then we also remove the2880 * last one (which is the newline, of course).2881 */2882 plen = len -1;2883if(len < size && patch[len] =='\\')2884 plen--;2885 first = *patch;2886if(state->apply_in_reverse) {2887if(first =='-')2888 first ='+';2889else if(first =='+')2890 first ='-';2891}28922893switch(first) {2894case'\n':2895/* Newer GNU diff, empty context line */2896if(plen <0)2897/* ... followed by '\No newline'; nothing */2898break;2899*old++ ='\n';2900strbuf_addch(&newlines,'\n');2901add_line_info(&preimage,"\n",1, LINE_COMMON);2902add_line_info(&postimage,"\n",1, LINE_COMMON);2903 is_blank_context =1;2904break;2905case' ':2906if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2907ws_blank_line(patch +1, plen, ws_rule))2908 is_blank_context =1;2909case'-':2910memcpy(old, patch +1, plen);2911add_line_info(&preimage, old, plen,2912(first ==' '? LINE_COMMON :0));2913 old += plen;2914if(first =='-')2915break;2916/* Fall-through for ' ' */2917case'+':2918/* --no-add does not add new lines */2919if(first =='+'&& state->no_add)2920break;29212922 start = newlines.len;2923if(first !='+'||2924!state->whitespace_error ||2925 state->ws_error_action != correct_ws_error) {2926strbuf_add(&newlines, patch +1, plen);2927}2928else{2929ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2930}2931add_line_info(&postimage, newlines.buf + start, newlines.len - start,2932(first =='+'?0: LINE_COMMON));2933if(first =='+'&&2934(ws_rule & WS_BLANK_AT_EOF) &&2935ws_blank_line(patch +1, plen, ws_rule))2936 added_blank_line =1;2937break;2938case'@':case'\\':2939/* Ignore it, we already handled it */2940break;2941default:2942if(state->apply_verbosity > verbosity_normal)2943error(_("invalid start of line: '%c'"), first);2944 applied_pos = -1;2945goto out;2946}2947if(added_blank_line) {2948if(!new_blank_lines_at_end)2949 found_new_blank_lines_at_end = hunk_linenr;2950 new_blank_lines_at_end++;2951}2952else if(is_blank_context)2953;2954else2955 new_blank_lines_at_end =0;2956 patch += len;2957 size -= len;2958 hunk_linenr++;2959}2960if(inaccurate_eof &&2961 old > oldlines && old[-1] =='\n'&&2962 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2963 old--;2964strbuf_setlen(&newlines, newlines.len -1);2965}29662967 leading = frag->leading;2968 trailing = frag->trailing;29692970/*2971 * A hunk to change lines at the beginning would begin with2972 * @@ -1,L +N,M @@2973 * but we need to be careful. -U0 that inserts before the second2974 * line also has this pattern.2975 *2976 * And a hunk to add to an empty file would begin with2977 * @@ -0,0 +N,M @@2978 *2979 * In other words, a hunk that is (frag->oldpos <= 1) with or2980 * without leading context must match at the beginning.2981 */2982 match_beginning = (!frag->oldpos ||2983(frag->oldpos ==1&& !state->unidiff_zero));29842985/*2986 * A hunk without trailing lines must match at the end.2987 * However, we simply cannot tell if a hunk must match end2988 * from the lack of trailing lines if the patch was generated2989 * with unidiff without any context.2990 */2991 match_end = !state->unidiff_zero && !trailing;29922993 pos = frag->newpos ? (frag->newpos -1) :0;2994 preimage.buf = oldlines;2995 preimage.len = old - oldlines;2996 postimage.buf = newlines.buf;2997 postimage.len = newlines.len;2998 preimage.line = preimage.line_allocated;2999 postimage.line = postimage.line_allocated;30003001for(;;) {30023003 applied_pos =find_pos(state, img, &preimage, &postimage, pos,3004 ws_rule, match_beginning, match_end);30053006if(applied_pos >=0)3007break;30083009/* Am I at my context limits? */3010if((leading <= state->p_context) && (trailing <= state->p_context))3011break;3012if(match_beginning || match_end) {3013 match_beginning = match_end =0;3014continue;3015}30163017/*3018 * Reduce the number of context lines; reduce both3019 * leading and trailing if they are equal otherwise3020 * just reduce the larger context.3021 */3022if(leading >= trailing) {3023remove_first_line(&preimage);3024remove_first_line(&postimage);3025 pos--;3026 leading--;3027}3028if(trailing > leading) {3029remove_last_line(&preimage);3030remove_last_line(&postimage);3031 trailing--;3032}3033}30343035if(applied_pos >=0) {3036if(new_blank_lines_at_end &&3037 preimage.nr + applied_pos >= img->nr &&3038(ws_rule & WS_BLANK_AT_EOF) &&3039 state->ws_error_action != nowarn_ws_error) {3040record_ws_error(state, WS_BLANK_AT_EOF,"+",1,3041 found_new_blank_lines_at_end);3042if(state->ws_error_action == correct_ws_error) {3043while(new_blank_lines_at_end--)3044remove_last_line(&postimage);3045}3046/*3047 * We would want to prevent write_out_results()3048 * from taking place in apply_patch() that follows3049 * the callchain led us here, which is:3050 * apply_patch->check_patch_list->check_patch->3051 * apply_data->apply_fragments->apply_one_fragment3052 */3053if(state->ws_error_action == die_on_ws_error)3054 state->apply =0;3055}30563057if(state->apply_verbosity > verbosity_normal && applied_pos != pos) {3058int offset = applied_pos - pos;3059if(state->apply_in_reverse)3060 offset =0- offset;3061fprintf_ln(stderr,3062Q_("Hunk #%dsucceeded at%d(offset%dline).",3063"Hunk #%dsucceeded at%d(offset%dlines).",3064 offset),3065 nth_fragment, applied_pos +1, offset);3066}30673068/*3069 * Warn if it was necessary to reduce the number3070 * of context lines.3071 */3072if((leading != frag->leading ||3073 trailing != frag->trailing) && state->apply_verbosity > verbosity_silent)3074fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"3075" to apply fragment at%d"),3076 leading, trailing, applied_pos+1);3077update_image(state, img, applied_pos, &preimage, &postimage);3078}else{3079if(state->apply_verbosity > verbosity_normal)3080error(_("while searching for:\n%.*s"),3081(int)(old - oldlines), oldlines);3082}30833084out:3085free(oldlines);3086strbuf_release(&newlines);3087free(preimage.line_allocated);3088free(postimage.line_allocated);30893090return(applied_pos <0);3091}30923093static intapply_binary_fragment(struct apply_state *state,3094struct image *img,3095struct patch *patch)3096{3097struct fragment *fragment = patch->fragments;3098unsigned long len;3099void*dst;31003101if(!fragment)3102returnerror(_("missing binary patch data for '%s'"),3103 patch->new_name ?3104 patch->new_name :3105 patch->old_name);31063107/* Binary patch is irreversible without the optional second hunk */3108if(state->apply_in_reverse) {3109if(!fragment->next)3110returnerror(_("cannot reverse-apply a binary patch "3111"without the reverse hunk to '%s'"),3112 patch->new_name3113? patch->new_name : patch->old_name);3114 fragment = fragment->next;3115}3116switch(fragment->binary_patch_method) {3117case BINARY_DELTA_DEFLATED:3118 dst =patch_delta(img->buf, img->len, fragment->patch,3119 fragment->size, &len);3120if(!dst)3121return-1;3122clear_image(img);3123 img->buf = dst;3124 img->len = len;3125return0;3126case BINARY_LITERAL_DEFLATED:3127clear_image(img);3128 img->len = fragment->size;3129 img->buf =xmemdupz(fragment->patch, img->len);3130return0;3131}3132return-1;3133}31343135/*3136 * Replace "img" with the result of applying the binary patch.3137 * The binary patch data itself in patch->fragment is still kept3138 * but the preimage prepared by the caller in "img" is freed here3139 * or in the helper function apply_binary_fragment() this calls.3140 */3141static intapply_binary(struct apply_state *state,3142struct image *img,3143struct patch *patch)3144{3145const char*name = patch->old_name ? patch->old_name : patch->new_name;3146struct object_id oid;31473148/*3149 * For safety, we require patch index line to contain3150 * full 40-byte textual SHA1 for old and new, at least for now.3151 */3152if(strlen(patch->old_sha1_prefix) !=40||3153strlen(patch->new_sha1_prefix) !=40||3154get_oid_hex(patch->old_sha1_prefix, &oid) ||3155get_oid_hex(patch->new_sha1_prefix, &oid))3156returnerror(_("cannot apply binary patch to '%s' "3157"without full index line"), name);31583159if(patch->old_name) {3160/*3161 * See if the old one matches what the patch3162 * applies to.3163 */3164hash_sha1_file(img->buf, img->len, blob_type, oid.hash);3165if(strcmp(oid_to_hex(&oid), patch->old_sha1_prefix))3166returnerror(_("the patch applies to '%s' (%s), "3167"which does not match the "3168"current contents."),3169 name,oid_to_hex(&oid));3170}3171else{3172/* Otherwise, the old one must be empty. */3173if(img->len)3174returnerror(_("the patch applies to an empty "3175"'%s' but it is not empty"), name);3176}31773178get_oid_hex(patch->new_sha1_prefix, &oid);3179if(is_null_oid(&oid)) {3180clear_image(img);3181return0;/* deletion patch */3182}31833184if(has_sha1_file(oid.hash)) {3185/* We already have the postimage */3186enum object_type type;3187unsigned long size;3188char*result;31893190 result =read_sha1_file(oid.hash, &type, &size);3191if(!result)3192returnerror(_("the necessary postimage%sfor "3193"'%s' cannot be read"),3194 patch->new_sha1_prefix, name);3195clear_image(img);3196 img->buf = result;3197 img->len = size;3198}else{3199/*3200 * We have verified buf matches the preimage;3201 * apply the patch data to it, which is stored3202 * in the patch->fragments->{patch,size}.3203 */3204if(apply_binary_fragment(state, img, patch))3205returnerror(_("binary patch does not apply to '%s'"),3206 name);32073208/* verify that the result matches */3209hash_sha1_file(img->buf, img->len, blob_type, oid.hash);3210if(strcmp(oid_to_hex(&oid), patch->new_sha1_prefix))3211returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3212 name, patch->new_sha1_prefix,oid_to_hex(&oid));3213}32143215return0;3216}32173218static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3219{3220struct fragment *frag = patch->fragments;3221const char*name = patch->old_name ? patch->old_name : patch->new_name;3222unsigned ws_rule = patch->ws_rule;3223unsigned inaccurate_eof = patch->inaccurate_eof;3224int nth =0;32253226if(patch->is_binary)3227returnapply_binary(state, img, patch);32283229while(frag) {3230 nth++;3231if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3232error(_("patch failed:%s:%ld"), name, frag->oldpos);3233if(!state->apply_with_reject)3234return-1;3235 frag->rejected =1;3236}3237 frag = frag->next;3238}3239return0;3240}32413242static intread_blob_object(struct strbuf *buf,const struct object_id *oid,unsigned mode)3243{3244if(S_ISGITLINK(mode)) {3245strbuf_grow(buf,100);3246strbuf_addf(buf,"Subproject commit%s\n",oid_to_hex(oid));3247}else{3248enum object_type type;3249unsigned long sz;3250char*result;32513252 result =read_sha1_file(oid->hash, &type, &sz);3253if(!result)3254return-1;3255/* XXX read_sha1_file NUL-terminates */3256strbuf_attach(buf, result, sz, sz +1);3257}3258return0;3259}32603261static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3262{3263if(!ce)3264return0;3265returnread_blob_object(buf, &ce->oid, ce->ce_mode);3266}32673268static struct patch *in_fn_table(struct apply_state *state,const char*name)3269{3270struct string_list_item *item;32713272if(name == NULL)3273return NULL;32743275 item =string_list_lookup(&state->fn_table, name);3276if(item != NULL)3277return(struct patch *)item->util;32783279return NULL;3280}32813282/*3283 * item->util in the filename table records the status of the path.3284 * Usually it points at a patch (whose result records the contents3285 * of it after applying it), but it could be PATH_WAS_DELETED for a3286 * path that a previously applied patch has already removed, or3287 * PATH_TO_BE_DELETED for a path that a later patch would remove.3288 *3289 * The latter is needed to deal with a case where two paths A and B3290 * are swapped by first renaming A to B and then renaming B to A;3291 * moving A to B should not be prevented due to presence of B as we3292 * will remove it in a later patch.3293 */3294#define PATH_TO_BE_DELETED ((struct patch *) -2)3295#define PATH_WAS_DELETED ((struct patch *) -1)32963297static intto_be_deleted(struct patch *patch)3298{3299return patch == PATH_TO_BE_DELETED;3300}33013302static intwas_deleted(struct patch *patch)3303{3304return patch == PATH_WAS_DELETED;3305}33063307static voidadd_to_fn_table(struct apply_state *state,struct patch *patch)3308{3309struct string_list_item *item;33103311/*3312 * Always add new_name unless patch is a deletion3313 * This should cover the cases for normal diffs,3314 * file creations and copies3315 */3316if(patch->new_name != NULL) {3317 item =string_list_insert(&state->fn_table, patch->new_name);3318 item->util = patch;3319}33203321/*3322 * store a failure on rename/deletion cases because3323 * later chunks shouldn't patch old names3324 */3325if((patch->new_name == NULL) || (patch->is_rename)) {3326 item =string_list_insert(&state->fn_table, patch->old_name);3327 item->util = PATH_WAS_DELETED;3328}3329}33303331static voidprepare_fn_table(struct apply_state *state,struct patch *patch)3332{3333/*3334 * store information about incoming file deletion3335 */3336while(patch) {3337if((patch->new_name == NULL) || (patch->is_rename)) {3338struct string_list_item *item;3339 item =string_list_insert(&state->fn_table, patch->old_name);3340 item->util = PATH_TO_BE_DELETED;3341}3342 patch = patch->next;3343}3344}33453346static intcheckout_target(struct index_state *istate,3347struct cache_entry *ce,struct stat *st)3348{3349struct checkout costate = CHECKOUT_INIT;33503351 costate.refresh_cache =1;3352 costate.istate = istate;3353if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3354returnerror(_("cannot checkout%s"), ce->name);3355return0;3356}33573358static struct patch *previous_patch(struct apply_state *state,3359struct patch *patch,3360int*gone)3361{3362struct patch *previous;33633364*gone =0;3365if(patch->is_copy || patch->is_rename)3366return NULL;/* "git" patches do not depend on the order */33673368 previous =in_fn_table(state, patch->old_name);3369if(!previous)3370return NULL;33713372if(to_be_deleted(previous))3373return NULL;/* the deletion hasn't happened yet */33743375if(was_deleted(previous))3376*gone =1;33773378return previous;3379}33803381static intverify_index_match(const struct cache_entry *ce,struct stat *st)3382{3383if(S_ISGITLINK(ce->ce_mode)) {3384if(!S_ISDIR(st->st_mode))3385return-1;3386return0;3387}3388returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3389}33903391#define SUBMODULE_PATCH_WITHOUT_INDEX 133923393static intload_patch_target(struct apply_state *state,3394struct strbuf *buf,3395const struct cache_entry *ce,3396struct stat *st,3397const char*name,3398unsigned expected_mode)3399{3400if(state->cached || state->check_index) {3401if(read_file_or_gitlink(ce, buf))3402returnerror(_("failed to read%s"), name);3403}else if(name) {3404if(S_ISGITLINK(expected_mode)) {3405if(ce)3406returnread_file_or_gitlink(ce, buf);3407else3408return SUBMODULE_PATCH_WITHOUT_INDEX;3409}else if(has_symlink_leading_path(name,strlen(name))) {3410returnerror(_("reading from '%s' beyond a symbolic link"), name);3411}else{3412if(read_old_data(st, name, buf))3413returnerror(_("failed to read%s"), name);3414}3415}3416return0;3417}34183419/*3420 * We are about to apply "patch"; populate the "image" with the3421 * current version we have, from the working tree or from the index,3422 * depending on the situation e.g. --cached/--index. If we are3423 * applying a non-git patch that incrementally updates the tree,3424 * we read from the result of a previous diff.3425 */3426static intload_preimage(struct apply_state *state,3427struct image *image,3428struct patch *patch,struct stat *st,3429const struct cache_entry *ce)3430{3431struct strbuf buf = STRBUF_INIT;3432size_t len;3433char*img;3434struct patch *previous;3435int status;34363437 previous =previous_patch(state, patch, &status);3438if(status)3439returnerror(_("path%shas been renamed/deleted"),3440 patch->old_name);3441if(previous) {3442/* We have a patched copy in memory; use that. */3443strbuf_add(&buf, previous->result, previous->resultsize);3444}else{3445 status =load_patch_target(state, &buf, ce, st,3446 patch->old_name, patch->old_mode);3447if(status <0)3448return status;3449else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3450/*3451 * There is no way to apply subproject3452 * patch without looking at the index.3453 * NEEDSWORK: shouldn't this be flagged3454 * as an error???3455 */3456free_fragment_list(patch->fragments);3457 patch->fragments = NULL;3458}else if(status) {3459returnerror(_("failed to read%s"), patch->old_name);3460}3461}34623463 img =strbuf_detach(&buf, &len);3464prepare_image(image, img, len, !patch->is_binary);3465return0;3466}34673468static intthree_way_merge(struct image *image,3469char*path,3470const struct object_id *base,3471const struct object_id *ours,3472const struct object_id *theirs)3473{3474 mmfile_t base_file, our_file, their_file;3475 mmbuffer_t result = { NULL };3476int status;34773478read_mmblob(&base_file, base);3479read_mmblob(&our_file, ours);3480read_mmblob(&their_file, theirs);3481 status =ll_merge(&result, path,3482&base_file,"base",3483&our_file,"ours",3484&their_file,"theirs", NULL);3485free(base_file.ptr);3486free(our_file.ptr);3487free(their_file.ptr);3488if(status <0|| !result.ptr) {3489free(result.ptr);3490return-1;3491}3492clear_image(image);3493 image->buf = result.ptr;3494 image->len = result.size;34953496return status;3497}34983499/*3500 * When directly falling back to add/add three-way merge, we read from3501 * the current contents of the new_name. In no cases other than that3502 * this function will be called.3503 */3504static intload_current(struct apply_state *state,3505struct image *image,3506struct patch *patch)3507{3508struct strbuf buf = STRBUF_INIT;3509int status, pos;3510size_t len;3511char*img;3512struct stat st;3513struct cache_entry *ce;3514char*name = patch->new_name;3515unsigned mode = patch->new_mode;35163517if(!patch->is_new)3518die("BUG: patch to%sis not a creation", patch->old_name);35193520 pos =cache_name_pos(name,strlen(name));3521if(pos <0)3522returnerror(_("%s: does not exist in index"), name);3523 ce = active_cache[pos];3524if(lstat(name, &st)) {3525if(errno != ENOENT)3526returnerror_errno("%s", name);3527if(checkout_target(&the_index, ce, &st))3528return-1;3529}3530if(verify_index_match(ce, &st))3531returnerror(_("%s: does not match index"), name);35323533 status =load_patch_target(state, &buf, ce, &st, name, mode);3534if(status <0)3535return status;3536else if(status)3537return-1;3538 img =strbuf_detach(&buf, &len);3539prepare_image(image, img, len, !patch->is_binary);3540return0;3541}35423543static inttry_threeway(struct apply_state *state,3544struct image *image,3545struct patch *patch,3546struct stat *st,3547const struct cache_entry *ce)3548{3549struct object_id pre_oid, post_oid, our_oid;3550struct strbuf buf = STRBUF_INIT;3551size_t len;3552int status;3553char*img;3554struct image tmp_image;35553556/* No point falling back to 3-way merge in these cases */3557if(patch->is_delete ||3558S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3559return-1;35603561/* Preimage the patch was prepared for */3562if(patch->is_new)3563write_sha1_file("",0, blob_type, pre_oid.hash);3564else if(get_sha1(patch->old_sha1_prefix, pre_oid.hash) ||3565read_blob_object(&buf, &pre_oid, patch->old_mode))3566returnerror(_("repository lacks the necessary blob to fall back on 3-way merge."));35673568if(state->apply_verbosity > verbosity_silent)3569fprintf(stderr,_("Falling back to three-way merge...\n"));35703571 img =strbuf_detach(&buf, &len);3572prepare_image(&tmp_image, img, len,1);3573/* Apply the patch to get the post image */3574if(apply_fragments(state, &tmp_image, patch) <0) {3575clear_image(&tmp_image);3576return-1;3577}3578/* post_oid is theirs */3579write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_oid.hash);3580clear_image(&tmp_image);35813582/* our_oid is ours */3583if(patch->is_new) {3584if(load_current(state, &tmp_image, patch))3585returnerror(_("cannot read the current contents of '%s'"),3586 patch->new_name);3587}else{3588if(load_preimage(state, &tmp_image, patch, st, ce))3589returnerror(_("cannot read the current contents of '%s'"),3590 patch->old_name);3591}3592write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_oid.hash);3593clear_image(&tmp_image);35943595/* in-core three-way merge between post and our using pre as base */3596 status =three_way_merge(image, patch->new_name,3597&pre_oid, &our_oid, &post_oid);3598if(status <0) {3599if(state->apply_verbosity > verbosity_silent)3600fprintf(stderr,3601_("Failed to fall back on three-way merge...\n"));3602return status;3603}36043605if(status) {3606 patch->conflicted_threeway =1;3607if(patch->is_new)3608oidclr(&patch->threeway_stage[0]);3609else3610oidcpy(&patch->threeway_stage[0], &pre_oid);3611oidcpy(&patch->threeway_stage[1], &our_oid);3612oidcpy(&patch->threeway_stage[2], &post_oid);3613if(state->apply_verbosity > verbosity_silent)3614fprintf(stderr,3615_("Applied patch to '%s' with conflicts.\n"),3616 patch->new_name);3617}else{3618if(state->apply_verbosity > verbosity_silent)3619fprintf(stderr,3620_("Applied patch to '%s' cleanly.\n"),3621 patch->new_name);3622}3623return0;3624}36253626static intapply_data(struct apply_state *state,struct patch *patch,3627struct stat *st,const struct cache_entry *ce)3628{3629struct image image;36303631if(load_preimage(state, &image, patch, st, ce) <0)3632return-1;36333634if(patch->direct_to_threeway ||3635apply_fragments(state, &image, patch) <0) {3636/* Note: with --reject, apply_fragments() returns 0 */3637if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3638return-1;3639}3640 patch->result = image.buf;3641 patch->resultsize = image.len;3642add_to_fn_table(state, patch);3643free(image.line_allocated);36443645if(0< patch->is_delete && patch->resultsize)3646returnerror(_("removal patch leaves file contents"));36473648return0;3649}36503651/*3652 * If "patch" that we are looking at modifies or deletes what we have,3653 * we would want it not to lose any local modification we have, either3654 * in the working tree or in the index.3655 *3656 * This also decides if a non-git patch is a creation patch or a3657 * modification to an existing empty file. We do not check the state3658 * of the current tree for a creation patch in this function; the caller3659 * check_patch() separately makes sure (and errors out otherwise) that3660 * the path the patch creates does not exist in the current tree.3661 */3662static intcheck_preimage(struct apply_state *state,3663struct patch *patch,3664struct cache_entry **ce,3665struct stat *st)3666{3667const char*old_name = patch->old_name;3668struct patch *previous = NULL;3669int stat_ret =0, status;3670unsigned st_mode =0;36713672if(!old_name)3673return0;36743675assert(patch->is_new <=0);3676 previous =previous_patch(state, patch, &status);36773678if(status)3679returnerror(_("path%shas been renamed/deleted"), old_name);3680if(previous) {3681 st_mode = previous->new_mode;3682}else if(!state->cached) {3683 stat_ret =lstat(old_name, st);3684if(stat_ret && errno != ENOENT)3685returnerror_errno("%s", old_name);3686}36873688if(state->check_index && !previous) {3689int pos =cache_name_pos(old_name,strlen(old_name));3690if(pos <0) {3691if(patch->is_new <0)3692goto is_new;3693returnerror(_("%s: does not exist in index"), old_name);3694}3695*ce = active_cache[pos];3696if(stat_ret <0) {3697if(checkout_target(&the_index, *ce, st))3698return-1;3699}3700if(!state->cached &&verify_index_match(*ce, st))3701returnerror(_("%s: does not match index"), old_name);3702if(state->cached)3703 st_mode = (*ce)->ce_mode;3704}else if(stat_ret <0) {3705if(patch->is_new <0)3706goto is_new;3707returnerror_errno("%s", old_name);3708}37093710if(!state->cached && !previous)3711 st_mode =ce_mode_from_stat(*ce, st->st_mode);37123713if(patch->is_new <0)3714 patch->is_new =0;3715if(!patch->old_mode)3716 patch->old_mode = st_mode;3717if((st_mode ^ patch->old_mode) & S_IFMT)3718returnerror(_("%s: wrong type"), old_name);3719if(st_mode != patch->old_mode)3720warning(_("%shas type%o, expected%o"),3721 old_name, st_mode, patch->old_mode);3722if(!patch->new_mode && !patch->is_delete)3723 patch->new_mode = st_mode;3724return0;37253726 is_new:3727 patch->is_new =1;3728 patch->is_delete =0;3729free(patch->old_name);3730 patch->old_name = NULL;3731return0;3732}373337343735#define EXISTS_IN_INDEX 13736#define EXISTS_IN_WORKTREE 237373738static intcheck_to_create(struct apply_state *state,3739const char*new_name,3740int ok_if_exists)3741{3742struct stat nst;37433744if(state->check_index &&3745cache_name_pos(new_name,strlen(new_name)) >=0&&3746!ok_if_exists)3747return EXISTS_IN_INDEX;3748if(state->cached)3749return0;37503751if(!lstat(new_name, &nst)) {3752if(S_ISDIR(nst.st_mode) || ok_if_exists)3753return0;3754/*3755 * A leading component of new_name might be a symlink3756 * that is going to be removed with this patch, but3757 * still pointing at somewhere that has the path.3758 * In such a case, path "new_name" does not exist as3759 * far as git is concerned.3760 */3761if(has_symlink_leading_path(new_name,strlen(new_name)))3762return0;37633764return EXISTS_IN_WORKTREE;3765}else if((errno != ENOENT) && (errno != ENOTDIR)) {3766returnerror_errno("%s", new_name);3767}3768return0;3769}37703771static uintptr_tregister_symlink_changes(struct apply_state *state,3772const char*path,3773uintptr_t what)3774{3775struct string_list_item *ent;37763777 ent =string_list_lookup(&state->symlink_changes, path);3778if(!ent) {3779 ent =string_list_insert(&state->symlink_changes, path);3780 ent->util = (void*)0;3781}3782 ent->util = (void*)(what | ((uintptr_t)ent->util));3783return(uintptr_t)ent->util;3784}37853786static uintptr_tcheck_symlink_changes(struct apply_state *state,const char*path)3787{3788struct string_list_item *ent;37893790 ent =string_list_lookup(&state->symlink_changes, path);3791if(!ent)3792return0;3793return(uintptr_t)ent->util;3794}37953796static voidprepare_symlink_changes(struct apply_state *state,struct patch *patch)3797{3798for( ; patch; patch = patch->next) {3799if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3800(patch->is_rename || patch->is_delete))3801/* the symlink at patch->old_name is removed */3802register_symlink_changes(state, patch->old_name, APPLY_SYMLINK_GOES_AWAY);38033804if(patch->new_name &&S_ISLNK(patch->new_mode))3805/* the symlink at patch->new_name is created or remains */3806register_symlink_changes(state, patch->new_name, APPLY_SYMLINK_IN_RESULT);3807}3808}38093810static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3811{3812do{3813unsigned int change;38143815while(--name->len && name->buf[name->len] !='/')3816;/* scan backwards */3817if(!name->len)3818break;3819 name->buf[name->len] ='\0';3820 change =check_symlink_changes(state, name->buf);3821if(change & APPLY_SYMLINK_IN_RESULT)3822return1;3823if(change & APPLY_SYMLINK_GOES_AWAY)3824/*3825 * This cannot be "return 0", because we may3826 * see a new one created at a higher level.3827 */3828continue;38293830/* otherwise, check the preimage */3831if(state->check_index) {3832struct cache_entry *ce;38333834 ce =cache_file_exists(name->buf, name->len, ignore_case);3835if(ce &&S_ISLNK(ce->ce_mode))3836return1;3837}else{3838struct stat st;3839if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3840return1;3841}3842}while(1);3843return0;3844}38453846static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3847{3848int ret;3849struct strbuf name = STRBUF_INIT;38503851assert(*name_ !='\0');3852strbuf_addstr(&name, name_);3853 ret =path_is_beyond_symlink_1(state, &name);3854strbuf_release(&name);38553856return ret;3857}38583859static intcheck_unsafe_path(struct patch *patch)3860{3861const char*old_name = NULL;3862const char*new_name = NULL;3863if(patch->is_delete)3864 old_name = patch->old_name;3865else if(!patch->is_new && !patch->is_copy)3866 old_name = patch->old_name;3867if(!patch->is_delete)3868 new_name = patch->new_name;38693870if(old_name && !verify_path(old_name))3871returnerror(_("invalid path '%s'"), old_name);3872if(new_name && !verify_path(new_name))3873returnerror(_("invalid path '%s'"), new_name);3874return0;3875}38763877/*3878 * Check and apply the patch in-core; leave the result in patch->result3879 * for the caller to write it out to the final destination.3880 */3881static intcheck_patch(struct apply_state *state,struct patch *patch)3882{3883struct stat st;3884const char*old_name = patch->old_name;3885const char*new_name = patch->new_name;3886const char*name = old_name ? old_name : new_name;3887struct cache_entry *ce = NULL;3888struct patch *tpatch;3889int ok_if_exists;3890int status;38913892 patch->rejected =1;/* we will drop this after we succeed */38933894 status =check_preimage(state, patch, &ce, &st);3895if(status)3896return status;3897 old_name = patch->old_name;38983899/*3900 * A type-change diff is always split into a patch to delete3901 * old, immediately followed by a patch to create new (see3902 * diff.c::run_diff()); in such a case it is Ok that the entry3903 * to be deleted by the previous patch is still in the working3904 * tree and in the index.3905 *3906 * A patch to swap-rename between A and B would first rename A3907 * to B and then rename B to A. While applying the first one,3908 * the presence of B should not stop A from getting renamed to3909 * B; ask to_be_deleted() about the later rename. Removal of3910 * B and rename from A to B is handled the same way by asking3911 * was_deleted().3912 */3913if((tpatch =in_fn_table(state, new_name)) &&3914(was_deleted(tpatch) ||to_be_deleted(tpatch)))3915 ok_if_exists =1;3916else3917 ok_if_exists =0;39183919if(new_name &&3920((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3921int err =check_to_create(state, new_name, ok_if_exists);39223923if(err && state->threeway) {3924 patch->direct_to_threeway =1;3925}else switch(err) {3926case0:3927break;/* happy */3928case EXISTS_IN_INDEX:3929returnerror(_("%s: already exists in index"), new_name);3930break;3931case EXISTS_IN_WORKTREE:3932returnerror(_("%s: already exists in working directory"),3933 new_name);3934default:3935return err;3936}39373938if(!patch->new_mode) {3939if(0< patch->is_new)3940 patch->new_mode = S_IFREG |0644;3941else3942 patch->new_mode = patch->old_mode;3943}3944}39453946if(new_name && old_name) {3947int same = !strcmp(old_name, new_name);3948if(!patch->new_mode)3949 patch->new_mode = patch->old_mode;3950if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3951if(same)3952returnerror(_("new mode (%o) of%sdoes not "3953"match old mode (%o)"),3954 patch->new_mode, new_name,3955 patch->old_mode);3956else3957returnerror(_("new mode (%o) of%sdoes not "3958"match old mode (%o) of%s"),3959 patch->new_mode, new_name,3960 patch->old_mode, old_name);3961}3962}39633964if(!state->unsafe_paths &&check_unsafe_path(patch))3965return-128;39663967/*3968 * An attempt to read from or delete a path that is beyond a3969 * symbolic link will be prevented by load_patch_target() that3970 * is called at the beginning of apply_data() so we do not3971 * have to worry about a patch marked with "is_delete" bit3972 * here. We however need to make sure that the patch result3973 * is not deposited to a path that is beyond a symbolic link3974 * here.3975 */3976if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3977returnerror(_("affected file '%s' is beyond a symbolic link"),3978 patch->new_name);39793980if(apply_data(state, patch, &st, ce) <0)3981returnerror(_("%s: patch does not apply"), name);3982 patch->rejected =0;3983return0;3984}39853986static intcheck_patch_list(struct apply_state *state,struct patch *patch)3987{3988int err =0;39893990prepare_symlink_changes(state, patch);3991prepare_fn_table(state, patch);3992while(patch) {3993int res;3994if(state->apply_verbosity > verbosity_normal)3995say_patch_name(stderr,3996_("Checking patch%s..."), patch);3997 res =check_patch(state, patch);3998if(res == -128)3999return-128;4000 err |= res;4001 patch = patch->next;4002}4003return err;4004}40054006static intread_apply_cache(struct apply_state *state)4007{4008if(state->index_file)4009returnread_cache_from(state->index_file);4010else4011returnread_cache();4012}40134014/* This function tries to read the object name from the current index */4015static intget_current_oid(struct apply_state *state,const char*path,4016struct object_id *oid)4017{4018int pos;40194020if(read_apply_cache(state) <0)4021return-1;4022 pos =cache_name_pos(path,strlen(path));4023if(pos <0)4024return-1;4025oidcpy(oid, &active_cache[pos]->oid);4026return0;4027}40284029static intpreimage_oid_in_gitlink_patch(struct patch *p,struct object_id *oid)4030{4031/*4032 * A usable gitlink patch has only one fragment (hunk) that looks like:4033 * @@ -1 +1 @@4034 * -Subproject commit <old sha1>4035 * +Subproject commit <new sha1>4036 * or4037 * @@ -1 +0,0 @@4038 * -Subproject commit <old sha1>4039 * for a removal patch.4040 */4041struct fragment *hunk = p->fragments;4042static const char heading[] ="-Subproject commit ";4043char*preimage;40444045if(/* does the patch have only one hunk? */4046 hunk && !hunk->next &&4047/* is its preimage one line? */4048 hunk->oldpos ==1&& hunk->oldlines ==1&&4049/* does preimage begin with the heading? */4050(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&4051starts_with(++preimage, heading) &&4052/* does it record full SHA-1? */4053!get_oid_hex(preimage +sizeof(heading) -1, oid) &&4054 preimage[sizeof(heading) + GIT_SHA1_HEXSZ -1] =='\n'&&4055/* does the abbreviated name on the index line agree with it? */4056starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))4057return0;/* it all looks fine */40584059/* we may have full object name on the index line */4060returnget_oid_hex(p->old_sha1_prefix, oid);4061}40624063/* Build an index that contains the just the files needed for a 3way merge */4064static intbuild_fake_ancestor(struct apply_state *state,struct patch *list)4065{4066struct patch *patch;4067struct index_state result = { NULL };4068static struct lock_file lock;4069int res;40704071/* Once we start supporting the reverse patch, it may be4072 * worth showing the new sha1 prefix, but until then...4073 */4074for(patch = list; patch; patch = patch->next) {4075struct object_id oid;4076struct cache_entry *ce;4077const char*name;40784079 name = patch->old_name ? patch->old_name : patch->new_name;4080if(0< patch->is_new)4081continue;40824083if(S_ISGITLINK(patch->old_mode)) {4084if(!preimage_oid_in_gitlink_patch(patch, &oid))4085;/* ok, the textual part looks sane */4086else4087returnerror(_("sha1 information is lacking or "4088"useless for submodule%s"), name);4089}else if(!get_sha1_blob(patch->old_sha1_prefix, oid.hash)) {4090;/* ok */4091}else if(!patch->lines_added && !patch->lines_deleted) {4092/* mode-only change: update the current */4093if(get_current_oid(state, patch->old_name, &oid))4094returnerror(_("mode change for%s, which is not "4095"in current HEAD"), name);4096}else4097returnerror(_("sha1 information is lacking or useless "4098"(%s)."), name);40994100 ce =make_cache_entry(patch->old_mode, oid.hash, name,0,0);4101if(!ce)4102returnerror(_("make_cache_entry failed for path '%s'"),4103 name);4104if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) {4105free(ce);4106returnerror(_("could not add%sto temporary index"),4107 name);4108}4109}41104111hold_lock_file_for_update(&lock, state->fake_ancestor, LOCK_DIE_ON_ERROR);4112 res =write_locked_index(&result, &lock, COMMIT_LOCK);4113discard_index(&result);41144115if(res)4116returnerror(_("could not write temporary index to%s"),4117 state->fake_ancestor);41184119return0;4120}41214122static voidstat_patch_list(struct apply_state *state,struct patch *patch)4123{4124int files, adds, dels;41254126for(files = adds = dels =0; patch ; patch = patch->next) {4127 files++;4128 adds += patch->lines_added;4129 dels += patch->lines_deleted;4130show_stats(state, patch);4131}41324133print_stat_summary(stdout, files, adds, dels);4134}41354136static voidnumstat_patch_list(struct apply_state *state,4137struct patch *patch)4138{4139for( ; patch; patch = patch->next) {4140const char*name;4141 name = patch->new_name ? patch->new_name : patch->old_name;4142if(patch->is_binary)4143printf("-\t-\t");4144else4145printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4146write_name_quoted(name, stdout, state->line_termination);4147}4148}41494150static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4151{4152if(mode)4153printf("%smode%06o%s\n", newdelete, mode, name);4154else4155printf("%s %s\n", newdelete, name);4156}41574158static voidshow_mode_change(struct patch *p,int show_name)4159{4160if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4161if(show_name)4162printf(" mode change%06o =>%06o%s\n",4163 p->old_mode, p->new_mode, p->new_name);4164else4165printf(" mode change%06o =>%06o\n",4166 p->old_mode, p->new_mode);4167}4168}41694170static voidshow_rename_copy(struct patch *p)4171{4172const char*renamecopy = p->is_rename ?"rename":"copy";4173const char*old, *new;41744175/* Find common prefix */4176 old = p->old_name;4177new= p->new_name;4178while(1) {4179const char*slash_old, *slash_new;4180 slash_old =strchr(old,'/');4181 slash_new =strchr(new,'/');4182if(!slash_old ||4183!slash_new ||4184 slash_old - old != slash_new -new||4185memcmp(old,new, slash_new -new))4186break;4187 old = slash_old +1;4188new= slash_new +1;4189}4190/* p->old_name thru old is the common prefix, and old and new4191 * through the end of names are renames4192 */4193if(old != p->old_name)4194printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4195(int)(old - p->old_name), p->old_name,4196 old,new, p->score);4197else4198printf("%s %s=>%s(%d%%)\n", renamecopy,4199 p->old_name, p->new_name, p->score);4200show_mode_change(p,0);4201}42024203static voidsummary_patch_list(struct patch *patch)4204{4205struct patch *p;42064207for(p = patch; p; p = p->next) {4208if(p->is_new)4209show_file_mode_name("create", p->new_mode, p->new_name);4210else if(p->is_delete)4211show_file_mode_name("delete", p->old_mode, p->old_name);4212else{4213if(p->is_rename || p->is_copy)4214show_rename_copy(p);4215else{4216if(p->score) {4217printf(" rewrite%s(%d%%)\n",4218 p->new_name, p->score);4219show_mode_change(p,0);4220}4221else4222show_mode_change(p,1);4223}4224}4225}4226}42274228static voidpatch_stats(struct apply_state *state,struct patch *patch)4229{4230int lines = patch->lines_added + patch->lines_deleted;42314232if(lines > state->max_change)4233 state->max_change = lines;4234if(patch->old_name) {4235int len =quote_c_style(patch->old_name, NULL, NULL,0);4236if(!len)4237 len =strlen(patch->old_name);4238if(len > state->max_len)4239 state->max_len = len;4240}4241if(patch->new_name) {4242int len =quote_c_style(patch->new_name, NULL, NULL,0);4243if(!len)4244 len =strlen(patch->new_name);4245if(len > state->max_len)4246 state->max_len = len;4247}4248}42494250static intremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4251{4252if(state->update_index) {4253if(remove_file_from_cache(patch->old_name) <0)4254returnerror(_("unable to remove%sfrom index"), patch->old_name);4255}4256if(!state->cached) {4257if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4258remove_path(patch->old_name);4259}4260}4261return0;4262}42634264static intadd_index_file(struct apply_state *state,4265const char*path,4266unsigned mode,4267void*buf,4268unsigned long size)4269{4270struct stat st;4271struct cache_entry *ce;4272int namelen =strlen(path);4273unsigned ce_size =cache_entry_size(namelen);42744275if(!state->update_index)4276return0;42774278 ce =xcalloc(1, ce_size);4279memcpy(ce->name, path, namelen);4280 ce->ce_mode =create_ce_mode(mode);4281 ce->ce_flags =create_ce_flags(0);4282 ce->ce_namelen = namelen;4283if(S_ISGITLINK(mode)) {4284const char*s;42854286if(!skip_prefix(buf,"Subproject commit ", &s) ||4287get_oid_hex(s, &ce->oid)) {4288free(ce);4289returnerror(_("corrupt patch for submodule%s"), path);4290}4291}else{4292if(!state->cached) {4293if(lstat(path, &st) <0) {4294free(ce);4295returnerror_errno(_("unable to stat newly "4296"created file '%s'"),4297 path);4298}4299fill_stat_cache_info(ce, &st);4300}4301if(write_sha1_file(buf, size, blob_type, ce->oid.hash) <0) {4302free(ce);4303returnerror(_("unable to create backing store "4304"for newly created file%s"), path);4305}4306}4307if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0) {4308free(ce);4309returnerror(_("unable to add cache entry for%s"), path);4310}43114312return0;4313}43144315/*4316 * Returns:4317 * -1 if an unrecoverable error happened4318 * 0 if everything went well4319 * 1 if a recoverable error happened4320 */4321static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4322{4323int fd, res;4324struct strbuf nbuf = STRBUF_INIT;43254326if(S_ISGITLINK(mode)) {4327struct stat st;4328if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4329return0;4330return!!mkdir(path,0777);4331}43324333if(has_symlinks &&S_ISLNK(mode))4334/* Although buf:size is counted string, it also is NUL4335 * terminated.4336 */4337return!!symlink(buf, path);43384339 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4340if(fd <0)4341return1;43424343if(convert_to_working_tree(path, buf, size, &nbuf)) {4344 size = nbuf.len;4345 buf = nbuf.buf;4346}43474348 res =write_in_full(fd, buf, size) <0;4349if(res)4350error_errno(_("failed to write to '%s'"), path);4351strbuf_release(&nbuf);43524353if(close(fd) <0&& !res)4354returnerror_errno(_("closing file '%s'"), path);43554356return res ? -1:0;4357}43584359/*4360 * We optimistically assume that the directories exist,4361 * which is true 99% of the time anyway. If they don't,4362 * we create them and try again.4363 *4364 * Returns:4365 * -1 on error4366 * 0 otherwise4367 */4368static intcreate_one_file(struct apply_state *state,4369char*path,4370unsigned mode,4371const char*buf,4372unsigned long size)4373{4374int res;43754376if(state->cached)4377return0;43784379 res =try_create_file(path, mode, buf, size);4380if(res <0)4381return-1;4382if(!res)4383return0;43844385if(errno == ENOENT) {4386if(safe_create_leading_directories(path))4387return0;4388 res =try_create_file(path, mode, buf, size);4389if(res <0)4390return-1;4391if(!res)4392return0;4393}43944395if(errno == EEXIST || errno == EACCES) {4396/* We may be trying to create a file where a directory4397 * used to be.4398 */4399struct stat st;4400if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4401 errno = EEXIST;4402}44034404if(errno == EEXIST) {4405unsigned int nr =getpid();44064407for(;;) {4408char newpath[PATH_MAX];4409mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4410 res =try_create_file(newpath, mode, buf, size);4411if(res <0)4412return-1;4413if(!res) {4414if(!rename(newpath, path))4415return0;4416unlink_or_warn(newpath);4417break;4418}4419if(errno != EEXIST)4420break;4421++nr;4422}4423}4424returnerror_errno(_("unable to write file '%s' mode%o"),4425 path, mode);4426}44274428static intadd_conflicted_stages_file(struct apply_state *state,4429struct patch *patch)4430{4431int stage, namelen;4432unsigned ce_size, mode;4433struct cache_entry *ce;44344435if(!state->update_index)4436return0;4437 namelen =strlen(patch->new_name);4438 ce_size =cache_entry_size(namelen);4439 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);44404441remove_file_from_cache(patch->new_name);4442for(stage =1; stage <4; stage++) {4443if(is_null_oid(&patch->threeway_stage[stage -1]))4444continue;4445 ce =xcalloc(1, ce_size);4446memcpy(ce->name, patch->new_name, namelen);4447 ce->ce_mode =create_ce_mode(mode);4448 ce->ce_flags =create_ce_flags(stage);4449 ce->ce_namelen = namelen;4450oidcpy(&ce->oid, &patch->threeway_stage[stage -1]);4451if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0) {4452free(ce);4453returnerror(_("unable to add cache entry for%s"),4454 patch->new_name);4455}4456}44574458return0;4459}44604461static intcreate_file(struct apply_state *state,struct patch *patch)4462{4463char*path = patch->new_name;4464unsigned mode = patch->new_mode;4465unsigned long size = patch->resultsize;4466char*buf = patch->result;44674468if(!mode)4469 mode = S_IFREG |0644;4470if(create_one_file(state, path, mode, buf, size))4471return-1;44724473if(patch->conflicted_threeway)4474returnadd_conflicted_stages_file(state, patch);4475else4476returnadd_index_file(state, path, mode, buf, size);4477}44784479/* phase zero is to remove, phase one is to create */4480static intwrite_out_one_result(struct apply_state *state,4481struct patch *patch,4482int phase)4483{4484if(patch->is_delete >0) {4485if(phase ==0)4486returnremove_file(state, patch,1);4487return0;4488}4489if(patch->is_new >0|| patch->is_copy) {4490if(phase ==1)4491returncreate_file(state, patch);4492return0;4493}4494/*4495 * Rename or modification boils down to the same4496 * thing: remove the old, write the new4497 */4498if(phase ==0)4499returnremove_file(state, patch, patch->is_rename);4500if(phase ==1)4501returncreate_file(state, patch);4502return0;4503}45044505static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4506{4507FILE*rej;4508char namebuf[PATH_MAX];4509struct fragment *frag;4510int cnt =0;4511struct strbuf sb = STRBUF_INIT;45124513for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4514if(!frag->rejected)4515continue;4516 cnt++;4517}45184519if(!cnt) {4520if(state->apply_verbosity > verbosity_normal)4521say_patch_name(stderr,4522_("Applied patch%scleanly."), patch);4523return0;4524}45254526/* This should not happen, because a removal patch that leaves4527 * contents are marked "rejected" at the patch level.4528 */4529if(!patch->new_name)4530die(_("internal error"));45314532/* Say this even without --verbose */4533strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4534"Applying patch %%swith%drejects...",4535 cnt),4536 cnt);4537if(state->apply_verbosity > verbosity_silent)4538say_patch_name(stderr, sb.buf, patch);4539strbuf_release(&sb);45404541 cnt =strlen(patch->new_name);4542if(ARRAY_SIZE(namebuf) <= cnt +5) {4543 cnt =ARRAY_SIZE(namebuf) -5;4544warning(_("truncating .rej filename to %.*s.rej"),4545 cnt -1, patch->new_name);4546}4547memcpy(namebuf, patch->new_name, cnt);4548memcpy(namebuf + cnt,".rej",5);45494550 rej =fopen(namebuf,"w");4551if(!rej)4552returnerror_errno(_("cannot open%s"), namebuf);45534554/* Normal git tools never deal with .rej, so do not pretend4555 * this is a git patch by saying --git or giving extended4556 * headers. While at it, maybe please "kompare" that wants4557 * the trailing TAB and some garbage at the end of line ;-).4558 */4559fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4560 patch->new_name, patch->new_name);4561for(cnt =1, frag = patch->fragments;4562 frag;4563 cnt++, frag = frag->next) {4564if(!frag->rejected) {4565if(state->apply_verbosity > verbosity_silent)4566fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4567continue;4568}4569if(state->apply_verbosity > verbosity_silent)4570fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4571fprintf(rej,"%.*s", frag->size, frag->patch);4572if(frag->patch[frag->size-1] !='\n')4573fputc('\n', rej);4574}4575fclose(rej);4576return-1;4577}45784579/*4580 * Returns:4581 * -1 if an error happened4582 * 0 if the patch applied cleanly4583 * 1 if the patch did not apply cleanly4584 */4585static intwrite_out_results(struct apply_state *state,struct patch *list)4586{4587int phase;4588int errs =0;4589struct patch *l;4590struct string_list cpath = STRING_LIST_INIT_DUP;45914592for(phase =0; phase <2; phase++) {4593 l = list;4594while(l) {4595if(l->rejected)4596 errs =1;4597else{4598if(write_out_one_result(state, l, phase)) {4599string_list_clear(&cpath,0);4600return-1;4601}4602if(phase ==1) {4603if(write_out_one_reject(state, l))4604 errs =1;4605if(l->conflicted_threeway) {4606string_list_append(&cpath, l->new_name);4607 errs =1;4608}4609}4610}4611 l = l->next;4612}4613}46144615if(cpath.nr) {4616struct string_list_item *item;46174618string_list_sort(&cpath);4619if(state->apply_verbosity > verbosity_silent) {4620for_each_string_list_item(item, &cpath)4621fprintf(stderr,"U%s\n", item->string);4622}4623string_list_clear(&cpath,0);46244625rerere(0);4626}46274628return errs;4629}46304631/*4632 * Try to apply a patch.4633 *4634 * Returns:4635 * -128 if a bad error happened (like patch unreadable)4636 * -1 if patch did not apply and user cannot deal with it4637 * 0 if the patch applied4638 * 1 if the patch did not apply but user might fix it4639 */4640static intapply_patch(struct apply_state *state,4641int fd,4642const char*filename,4643int options)4644{4645size_t offset;4646struct strbuf buf = STRBUF_INIT;/* owns the patch text */4647struct patch *list = NULL, **listp = &list;4648int skipped_patch =0;4649int res =0;46504651 state->patch_input_file = filename;4652if(read_patch_file(&buf, fd) <0)4653return-128;4654 offset =0;4655while(offset < buf.len) {4656struct patch *patch;4657int nr;46584659 patch =xcalloc(1,sizeof(*patch));4660 patch->inaccurate_eof = !!(options & APPLY_OPT_INACCURATE_EOF);4661 patch->recount = !!(options & APPLY_OPT_RECOUNT);4662 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4663if(nr <0) {4664free_patch(patch);4665if(nr == -128) {4666 res = -128;4667goto end;4668}4669break;4670}4671if(state->apply_in_reverse)4672reverse_patches(patch);4673if(use_patch(state, patch)) {4674patch_stats(state, patch);4675*listp = patch;4676 listp = &patch->next;4677}4678else{4679if(state->apply_verbosity > verbosity_normal)4680say_patch_name(stderr,_("Skipped patch '%s'."), patch);4681free_patch(patch);4682 skipped_patch++;4683}4684 offset += nr;4685}46864687if(!list && !skipped_patch) {4688error(_("unrecognized input"));4689 res = -128;4690goto end;4691}46924693if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4694 state->apply =0;46954696 state->update_index = state->check_index && state->apply;4697if(state->update_index && state->newfd <0) {4698if(state->index_file)4699 state->newfd =hold_lock_file_for_update(state->lock_file,4700 state->index_file,4701 LOCK_DIE_ON_ERROR);4702else4703 state->newfd =hold_locked_index(state->lock_file, LOCK_DIE_ON_ERROR);4704}47054706if(state->check_index &&read_apply_cache(state) <0) {4707error(_("unable to read index file"));4708 res = -128;4709goto end;4710}47114712if(state->check || state->apply) {4713int r =check_patch_list(state, list);4714if(r == -128) {4715 res = -128;4716goto end;4717}4718if(r <0&& !state->apply_with_reject) {4719 res = -1;4720goto end;4721}4722}47234724if(state->apply) {4725int write_res =write_out_results(state, list);4726if(write_res <0) {4727 res = -128;4728goto end;4729}4730if(write_res >0) {4731/* with --3way, we still need to write the index out */4732 res = state->apply_with_reject ? -1:1;4733goto end;4734}4735}47364737if(state->fake_ancestor &&4738build_fake_ancestor(state, list)) {4739 res = -128;4740goto end;4741}47424743if(state->diffstat && state->apply_verbosity > verbosity_silent)4744stat_patch_list(state, list);47454746if(state->numstat && state->apply_verbosity > verbosity_silent)4747numstat_patch_list(state, list);47484749if(state->summary && state->apply_verbosity > verbosity_silent)4750summary_patch_list(list);47514752end:4753free_patch_list(list);4754strbuf_release(&buf);4755string_list_clear(&state->fn_table,0);4756return res;4757}47584759static intapply_option_parse_exclude(const struct option *opt,4760const char*arg,int unset)4761{4762struct apply_state *state = opt->value;4763add_name_limit(state, arg,1);4764return0;4765}47664767static intapply_option_parse_include(const struct option *opt,4768const char*arg,int unset)4769{4770struct apply_state *state = opt->value;4771add_name_limit(state, arg,0);4772 state->has_include =1;4773return0;4774}47754776static intapply_option_parse_p(const struct option *opt,4777const char*arg,4778int unset)4779{4780struct apply_state *state = opt->value;4781 state->p_value =atoi(arg);4782 state->p_value_known =1;4783return0;4784}47854786static intapply_option_parse_space_change(const struct option *opt,4787const char*arg,int unset)4788{4789struct apply_state *state = opt->value;4790if(unset)4791 state->ws_ignore_action = ignore_ws_none;4792else4793 state->ws_ignore_action = ignore_ws_change;4794return0;4795}47964797static intapply_option_parse_whitespace(const struct option *opt,4798const char*arg,int unset)4799{4800struct apply_state *state = opt->value;4801 state->whitespace_option = arg;4802if(parse_whitespace_option(state, arg))4803exit(1);4804return0;4805}48064807static intapply_option_parse_directory(const struct option *opt,4808const char*arg,int unset)4809{4810struct apply_state *state = opt->value;4811strbuf_reset(&state->root);4812strbuf_addstr(&state->root, arg);4813strbuf_complete(&state->root,'/');4814return0;4815}48164817intapply_all_patches(struct apply_state *state,4818int argc,4819const char**argv,4820int options)4821{4822int i;4823int res;4824int errs =0;4825int read_stdin =1;48264827for(i =0; i < argc; i++) {4828const char*arg = argv[i];4829char*to_free = NULL;4830int fd;48314832if(!strcmp(arg,"-")) {4833 res =apply_patch(state,0,"<stdin>", options);4834if(res <0)4835goto end;4836 errs |= res;4837 read_stdin =0;4838continue;4839}else4840 arg = to_free =prefix_filename(state->prefix, arg);48414842 fd =open(arg, O_RDONLY);4843if(fd <0) {4844error(_("can't open patch '%s':%s"), arg,strerror(errno));4845 res = -128;4846free(to_free);4847goto end;4848}4849 read_stdin =0;4850set_default_whitespace_mode(state);4851 res =apply_patch(state, fd, arg, options);4852close(fd);4853free(to_free);4854if(res <0)4855goto end;4856 errs |= res;4857}4858set_default_whitespace_mode(state);4859if(read_stdin) {4860 res =apply_patch(state,0,"<stdin>", options);4861if(res <0)4862goto end;4863 errs |= res;4864}48654866if(state->whitespace_error) {4867if(state->squelch_whitespace_errors &&4868 state->squelch_whitespace_errors < state->whitespace_error) {4869int squelched =4870 state->whitespace_error - state->squelch_whitespace_errors;4871warning(Q_("squelched%dwhitespace error",4872"squelched%dwhitespace errors",4873 squelched),4874 squelched);4875}4876if(state->ws_error_action == die_on_ws_error) {4877error(Q_("%dline adds whitespace errors.",4878"%dlines add whitespace errors.",4879 state->whitespace_error),4880 state->whitespace_error);4881 res = -128;4882goto end;4883}4884if(state->applied_after_fixing_ws && state->apply)4885warning(Q_("%dline applied after"4886" fixing whitespace errors.",4887"%dlines applied after"4888" fixing whitespace errors.",4889 state->applied_after_fixing_ws),4890 state->applied_after_fixing_ws);4891else if(state->whitespace_error)4892warning(Q_("%dline adds whitespace errors.",4893"%dlines add whitespace errors.",4894 state->whitespace_error),4895 state->whitespace_error);4896}48974898if(state->update_index) {4899 res =write_locked_index(&the_index, state->lock_file, COMMIT_LOCK);4900if(res) {4901error(_("Unable to write new index file"));4902 res = -128;4903goto end;4904}4905 state->newfd = -1;4906}49074908 res = !!errs;49094910end:4911if(state->newfd >=0) {4912rollback_lock_file(state->lock_file);4913 state->newfd = -1;4914}49154916if(state->apply_verbosity <= verbosity_silent) {4917set_error_routine(state->saved_error_routine);4918set_warn_routine(state->saved_warn_routine);4919}49204921if(res > -1)4922return res;4923return(res == -1?1:128);4924}49254926intapply_parse_options(int argc,const char**argv,4927struct apply_state *state,4928int*force_apply,int*options,4929const char*const*apply_usage)4930{4931struct option builtin_apply_options[] = {4932{ OPTION_CALLBACK,0,"exclude", state,N_("path"),4933N_("don't apply changes matching the given path"),49340, apply_option_parse_exclude },4935{ OPTION_CALLBACK,0,"include", state,N_("path"),4936N_("apply changes matching the given path"),49370, apply_option_parse_include },4938{ OPTION_CALLBACK,'p', NULL, state,N_("num"),4939N_("remove <num> leading slashes from traditional diff paths"),49400, apply_option_parse_p },4941OPT_BOOL(0,"no-add", &state->no_add,4942N_("ignore additions made by the patch")),4943OPT_BOOL(0,"stat", &state->diffstat,4944N_("instead of applying the patch, output diffstat for the input")),4945OPT_NOOP_NOARG(0,"allow-binary-replacement"),4946OPT_NOOP_NOARG(0,"binary"),4947OPT_BOOL(0,"numstat", &state->numstat,4948N_("show number of added and deleted lines in decimal notation")),4949OPT_BOOL(0,"summary", &state->summary,4950N_("instead of applying the patch, output a summary for the input")),4951OPT_BOOL(0,"check", &state->check,4952N_("instead of applying the patch, see if the patch is applicable")),4953OPT_BOOL(0,"index", &state->check_index,4954N_("make sure the patch is applicable to the current index")),4955OPT_BOOL(0,"cached", &state->cached,4956N_("apply a patch without touching the working tree")),4957OPT_BOOL(0,"unsafe-paths", &state->unsafe_paths,4958N_("accept a patch that touches outside the working area")),4959OPT_BOOL(0,"apply", force_apply,4960N_("also apply the patch (use with --stat/--summary/--check)")),4961OPT_BOOL('3',"3way", &state->threeway,4962N_("attempt three-way merge if a patch does not apply")),4963OPT_FILENAME(0,"build-fake-ancestor", &state->fake_ancestor,4964N_("build a temporary index based on embedded index information")),4965/* Think twice before adding "--nul" synonym to this */4966OPT_SET_INT('z', NULL, &state->line_termination,4967N_("paths are separated with NUL character"),'\0'),4968OPT_INTEGER('C', NULL, &state->p_context,4969N_("ensure at least <n> lines of context match")),4970{ OPTION_CALLBACK,0,"whitespace", state,N_("action"),4971N_("detect new or modified lines that have whitespace errors"),49720, apply_option_parse_whitespace },4973{ OPTION_CALLBACK,0,"ignore-space-change", state, NULL,4974N_("ignore changes in whitespace when finding context"),4975 PARSE_OPT_NOARG, apply_option_parse_space_change },4976{ OPTION_CALLBACK,0,"ignore-whitespace", state, NULL,4977N_("ignore changes in whitespace when finding context"),4978 PARSE_OPT_NOARG, apply_option_parse_space_change },4979OPT_BOOL('R',"reverse", &state->apply_in_reverse,4980N_("apply the patch in reverse")),4981OPT_BOOL(0,"unidiff-zero", &state->unidiff_zero,4982N_("don't expect at least one line of context")),4983OPT_BOOL(0,"reject", &state->apply_with_reject,4984N_("leave the rejected hunks in corresponding *.rej files")),4985OPT_BOOL(0,"allow-overlap", &state->allow_overlap,4986N_("allow overlapping hunks")),4987OPT__VERBOSE(&state->apply_verbosity,N_("be verbose")),4988OPT_BIT(0,"inaccurate-eof", options,4989N_("tolerate incorrectly detected missing new-line at the end of file"),4990 APPLY_OPT_INACCURATE_EOF),4991OPT_BIT(0,"recount", options,4992N_("do not trust the line counts in the hunk headers"),4993 APPLY_OPT_RECOUNT),4994{ OPTION_CALLBACK,0,"directory", state,N_("root"),4995N_("prepend <root> to all filenames"),49960, apply_option_parse_directory },4997OPT_END()4998};49995000returnparse_options(argc, argv, state->prefix, builtin_apply_options, apply_usage,0);5001}