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->lock_file = lock_file; 83 state->newfd = -1; 84 state->apply =1; 85 state->line_termination ='\n'; 86 state->p_value =1; 87 state->p_context = UINT_MAX; 88 state->squelch_whitespace_errors =5; 89 state->ws_error_action = warn_on_ws_error; 90 state->ws_ignore_action = ignore_ws_none; 91 state->linenr =1; 92string_list_init(&state->fn_table,0); 93string_list_init(&state->limit_by_name,0); 94string_list_init(&state->symlink_changes,0); 95strbuf_init(&state->root,0); 96 97git_apply_config(); 98if(apply_default_whitespace &&parse_whitespace_option(state, apply_default_whitespace)) 99return-1; 100if(apply_default_ignorewhitespace &&parse_ignorewhitespace_option(state, apply_default_ignorewhitespace)) 101return-1; 102return0; 103} 104 105voidclear_apply_state(struct apply_state *state) 106{ 107string_list_clear(&state->limit_by_name,0); 108string_list_clear(&state->symlink_changes,0); 109strbuf_release(&state->root); 110 111/* &state->fn_table is cleared at the end of apply_patch() */ 112} 113 114static voidmute_routine(const char*msg,va_list params) 115{ 116/* do nothing */ 117} 118 119intcheck_apply_state(struct apply_state *state,int force_apply) 120{ 121int is_not_gitdir = !startup_info->have_repository; 122 123if(state->apply_with_reject && state->threeway) 124returnerror(_("--reject and --3way cannot be used together.")); 125if(state->cached && state->threeway) 126returnerror(_("--cached and --3way cannot be used together.")); 127if(state->threeway) { 128if(is_not_gitdir) 129returnerror(_("--3way outside a repository")); 130 state->check_index =1; 131} 132if(state->apply_with_reject) { 133 state->apply =1; 134if(state->apply_verbosity == verbosity_normal) 135 state->apply_verbosity = verbosity_verbose; 136} 137if(!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor)) 138 state->apply =0; 139if(state->check_index && is_not_gitdir) 140returnerror(_("--index outside a repository")); 141if(state->cached) { 142if(is_not_gitdir) 143returnerror(_("--cached outside a repository")); 144 state->check_index =1; 145} 146if(state->check_index) 147 state->unsafe_paths =0; 148if(!state->lock_file) 149returnerror("BUG: state->lock_file should not be NULL"); 150 151if(state->apply_verbosity <= verbosity_silent) { 152 state->saved_error_routine =get_error_routine(); 153 state->saved_warn_routine =get_warn_routine(); 154set_error_routine(mute_routine); 155set_warn_routine(mute_routine); 156} 157 158return0; 159} 160 161static voidset_default_whitespace_mode(struct apply_state *state) 162{ 163if(!state->whitespace_option && !apply_default_whitespace) 164 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 165} 166 167/* 168 * This represents one "hunk" from a patch, starting with 169 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 170 * patch text is pointed at by patch, and its byte length 171 * is stored in size. leading and trailing are the number 172 * of context lines. 173 */ 174struct fragment { 175unsigned long leading, trailing; 176unsigned long oldpos, oldlines; 177unsigned long newpos, newlines; 178/* 179 * 'patch' is usually borrowed from buf in apply_patch(), 180 * but some codepaths store an allocated buffer. 181 */ 182const char*patch; 183unsigned free_patch:1, 184 rejected:1; 185int size; 186int linenr; 187struct fragment *next; 188}; 189 190/* 191 * When dealing with a binary patch, we reuse "leading" field 192 * to store the type of the binary hunk, either deflated "delta" 193 * or deflated "literal". 194 */ 195#define binary_patch_method leading 196#define BINARY_DELTA_DEFLATED 1 197#define BINARY_LITERAL_DEFLATED 2 198 199/* 200 * This represents a "patch" to a file, both metainfo changes 201 * such as creation/deletion, filemode and content changes represented 202 * as a series of fragments. 203 */ 204struct patch { 205char*new_name, *old_name, *def_name; 206unsigned int old_mode, new_mode; 207int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 208int rejected; 209unsigned ws_rule; 210int lines_added, lines_deleted; 211int score; 212unsigned int is_toplevel_relative:1; 213unsigned int inaccurate_eof:1; 214unsigned int is_binary:1; 215unsigned int is_copy:1; 216unsigned int is_rename:1; 217unsigned int recount:1; 218unsigned int conflicted_threeway:1; 219unsigned int direct_to_threeway:1; 220struct fragment *fragments; 221char*result; 222size_t resultsize; 223char old_sha1_prefix[41]; 224char new_sha1_prefix[41]; 225struct patch *next; 226 227/* three-way fallback result */ 228struct object_id threeway_stage[3]; 229}; 230 231static voidfree_fragment_list(struct fragment *list) 232{ 233while(list) { 234struct fragment *next = list->next; 235if(list->free_patch) 236free((char*)list->patch); 237free(list); 238 list = next; 239} 240} 241 242static voidfree_patch(struct patch *patch) 243{ 244free_fragment_list(patch->fragments); 245free(patch->def_name); 246free(patch->old_name); 247free(patch->new_name); 248free(patch->result); 249free(patch); 250} 251 252static voidfree_patch_list(struct patch *list) 253{ 254while(list) { 255struct patch *next = list->next; 256free_patch(list); 257 list = next; 258} 259} 260 261/* 262 * A line in a file, len-bytes long (includes the terminating LF, 263 * except for an incomplete line at the end if the file ends with 264 * one), and its contents hashes to 'hash'. 265 */ 266struct line { 267size_t len; 268unsigned hash :24; 269unsigned flag :8; 270#define LINE_COMMON 1 271#define LINE_PATCHED 2 272}; 273 274/* 275 * This represents a "file", which is an array of "lines". 276 */ 277struct image { 278char*buf; 279size_t len; 280size_t nr; 281size_t alloc; 282struct line *line_allocated; 283struct line *line; 284}; 285 286static uint32_thash_line(const char*cp,size_t len) 287{ 288size_t i; 289uint32_t h; 290for(i =0, h =0; i < len; i++) { 291if(!isspace(cp[i])) { 292 h = h *3+ (cp[i] &0xff); 293} 294} 295return h; 296} 297 298/* 299 * Compare lines s1 of length n1 and s2 of length n2, ignoring 300 * whitespace difference. Returns 1 if they match, 0 otherwise 301 */ 302static intfuzzy_matchlines(const char*s1,size_t n1, 303const char*s2,size_t n2) 304{ 305const char*last1 = s1 + n1 -1; 306const char*last2 = s2 + n2 -1; 307int result =0; 308 309/* ignore line endings */ 310while((*last1 =='\r') || (*last1 =='\n')) 311 last1--; 312while((*last2 =='\r') || (*last2 =='\n')) 313 last2--; 314 315/* skip leading whitespaces, if both begin with whitespace */ 316if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 317while(isspace(*s1) && (s1 <= last1)) 318 s1++; 319while(isspace(*s2) && (s2 <= last2)) 320 s2++; 321} 322/* early return if both lines are empty */ 323if((s1 > last1) && (s2 > last2)) 324return1; 325while(!result) { 326 result = *s1++ - *s2++; 327/* 328 * Skip whitespace inside. We check for whitespace on 329 * both buffers because we don't want "a b" to match 330 * "ab" 331 */ 332if(isspace(*s1) &&isspace(*s2)) { 333while(isspace(*s1) && s1 <= last1) 334 s1++; 335while(isspace(*s2) && s2 <= last2) 336 s2++; 337} 338/* 339 * If we reached the end on one side only, 340 * lines don't match 341 */ 342if( 343((s2 > last2) && (s1 <= last1)) || 344((s1 > last1) && (s2 <= last2))) 345return0; 346if((s1 > last1) && (s2 > last2)) 347break; 348} 349 350return!result; 351} 352 353static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 354{ 355ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 356 img->line_allocated[img->nr].len = len; 357 img->line_allocated[img->nr].hash =hash_line(bol, len); 358 img->line_allocated[img->nr].flag = flag; 359 img->nr++; 360} 361 362/* 363 * "buf" has the file contents to be patched (read from various sources). 364 * attach it to "image" and add line-based index to it. 365 * "image" now owns the "buf". 366 */ 367static voidprepare_image(struct image *image,char*buf,size_t len, 368int prepare_linetable) 369{ 370const char*cp, *ep; 371 372memset(image,0,sizeof(*image)); 373 image->buf = buf; 374 image->len = len; 375 376if(!prepare_linetable) 377return; 378 379 ep = image->buf + image->len; 380 cp = image->buf; 381while(cp < ep) { 382const char*next; 383for(next = cp; next < ep && *next !='\n'; next++) 384; 385if(next < ep) 386 next++; 387add_line_info(image, cp, next - cp,0); 388 cp = next; 389} 390 image->line = image->line_allocated; 391} 392 393static voidclear_image(struct image *image) 394{ 395free(image->buf); 396free(image->line_allocated); 397memset(image,0,sizeof(*image)); 398} 399 400/* fmt must contain _one_ %s and no other substitution */ 401static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 402{ 403struct strbuf sb = STRBUF_INIT; 404 405if(patch->old_name && patch->new_name && 406strcmp(patch->old_name, patch->new_name)) { 407quote_c_style(patch->old_name, &sb, NULL,0); 408strbuf_addstr(&sb," => "); 409quote_c_style(patch->new_name, &sb, NULL,0); 410}else{ 411const char*n = patch->new_name; 412if(!n) 413 n = patch->old_name; 414quote_c_style(n, &sb, NULL,0); 415} 416fprintf(output, fmt, sb.buf); 417fputc('\n', output); 418strbuf_release(&sb); 419} 420 421#define SLOP (16) 422 423static intread_patch_file(struct strbuf *sb,int fd) 424{ 425if(strbuf_read(sb, fd,0) <0) 426returnerror_errno("git apply: failed to read"); 427 428/* 429 * Make sure that we have some slop in the buffer 430 * so that we can do speculative "memcmp" etc, and 431 * see to it that it is NUL-filled. 432 */ 433strbuf_grow(sb, SLOP); 434memset(sb->buf + sb->len,0, SLOP); 435return0; 436} 437 438static unsigned longlinelen(const char*buffer,unsigned long size) 439{ 440unsigned long len =0; 441while(size--) { 442 len++; 443if(*buffer++ =='\n') 444break; 445} 446return len; 447} 448 449static intis_dev_null(const char*str) 450{ 451returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 452} 453 454#define TERM_SPACE 1 455#define TERM_TAB 2 456 457static intname_terminate(int c,int terminate) 458{ 459if(c ==' '&& !(terminate & TERM_SPACE)) 460return0; 461if(c =='\t'&& !(terminate & TERM_TAB)) 462return0; 463 464return1; 465} 466 467/* remove double slashes to make --index work with such filenames */ 468static char*squash_slash(char*name) 469{ 470int i =0, j =0; 471 472if(!name) 473return NULL; 474 475while(name[i]) { 476if((name[j++] = name[i++]) =='/') 477while(name[i] =='/') 478 i++; 479} 480 name[j] ='\0'; 481return name; 482} 483 484static char*find_name_gnu(struct apply_state *state, 485const char*line, 486const char*def, 487int p_value) 488{ 489struct strbuf name = STRBUF_INIT; 490char*cp; 491 492/* 493 * Proposed "new-style" GNU patch/diff format; see 494 * http://marc.info/?l=git&m=112927316408690&w=2 495 */ 496if(unquote_c_style(&name, line, NULL)) { 497strbuf_release(&name); 498return NULL; 499} 500 501for(cp = name.buf; p_value; p_value--) { 502 cp =strchr(cp,'/'); 503if(!cp) { 504strbuf_release(&name); 505return NULL; 506} 507 cp++; 508} 509 510strbuf_remove(&name,0, cp - name.buf); 511if(state->root.len) 512strbuf_insert(&name,0, state->root.buf, state->root.len); 513returnsquash_slash(strbuf_detach(&name, NULL)); 514} 515 516static size_tsane_tz_len(const char*line,size_t len) 517{ 518const char*tz, *p; 519 520if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 521return0; 522 tz = line + len -strlen(" +0500"); 523 524if(tz[1] !='+'&& tz[1] !='-') 525return0; 526 527for(p = tz +2; p != line + len; p++) 528if(!isdigit(*p)) 529return0; 530 531return line + len - tz; 532} 533 534static size_ttz_with_colon_len(const char*line,size_t len) 535{ 536const char*tz, *p; 537 538if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 539return0; 540 tz = line + len -strlen(" +08:00"); 541 542if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 543return0; 544 p = tz +2; 545if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 546!isdigit(*p++) || !isdigit(*p++)) 547return0; 548 549return line + len - tz; 550} 551 552static size_tdate_len(const char*line,size_t len) 553{ 554const char*date, *p; 555 556if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 557return0; 558 p = date = line + len -strlen("72-02-05"); 559 560if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 561!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 562!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 563return0; 564 565if(date - line >=strlen("19") && 566isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 567 date -=strlen("19"); 568 569return line + len - date; 570} 571 572static size_tshort_time_len(const char*line,size_t len) 573{ 574const char*time, *p; 575 576if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 577return0; 578 p = time = line + len -strlen(" 07:01:32"); 579 580/* Permit 1-digit hours? */ 581if(*p++ !=' '|| 582!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 583!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 584!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 585return0; 586 587return line + len - time; 588} 589 590static size_tfractional_time_len(const char*line,size_t len) 591{ 592const char*p; 593size_t n; 594 595/* Expected format: 19:41:17.620000023 */ 596if(!len || !isdigit(line[len -1])) 597return0; 598 p = line + len -1; 599 600/* Fractional seconds. */ 601while(p > line &&isdigit(*p)) 602 p--; 603if(*p !='.') 604return0; 605 606/* Hours, minutes, and whole seconds. */ 607 n =short_time_len(line, p - line); 608if(!n) 609return0; 610 611return line + len - p + n; 612} 613 614static size_ttrailing_spaces_len(const char*line,size_t len) 615{ 616const char*p; 617 618/* Expected format: ' ' x (1 or more) */ 619if(!len || line[len -1] !=' ') 620return0; 621 622 p = line + len; 623while(p != line) { 624 p--; 625if(*p !=' ') 626return line + len - (p +1); 627} 628 629/* All spaces! */ 630return len; 631} 632 633static size_tdiff_timestamp_len(const char*line,size_t len) 634{ 635const char*end = line + len; 636size_t n; 637 638/* 639 * Posix: 2010-07-05 19:41:17 640 * GNU: 2010-07-05 19:41:17.620000023 -0500 641 */ 642 643if(!isdigit(end[-1])) 644return0; 645 646 n =sane_tz_len(line, end - line); 647if(!n) 648 n =tz_with_colon_len(line, end - line); 649 end -= n; 650 651 n =short_time_len(line, end - line); 652if(!n) 653 n =fractional_time_len(line, end - line); 654 end -= n; 655 656 n =date_len(line, end - line); 657if(!n)/* No date. Too bad. */ 658return0; 659 end -= n; 660 661if(end == line)/* No space before date. */ 662return0; 663if(end[-1] =='\t') {/* Success! */ 664 end--; 665return line + len - end; 666} 667if(end[-1] !=' ')/* No space before date. */ 668return0; 669 670/* Whitespace damage. */ 671 end -=trailing_spaces_len(line, end - line); 672return line + len - end; 673} 674 675static char*find_name_common(struct apply_state *state, 676const char*line, 677const char*def, 678int p_value, 679const char*end, 680int terminate) 681{ 682int len; 683const char*start = NULL; 684 685if(p_value ==0) 686 start = line; 687while(line != end) { 688char c = *line; 689 690if(!end &&isspace(c)) { 691if(c =='\n') 692break; 693if(name_terminate(c, terminate)) 694break; 695} 696 line++; 697if(c =='/'&& !--p_value) 698 start = line; 699} 700if(!start) 701returnsquash_slash(xstrdup_or_null(def)); 702 len = line - start; 703if(!len) 704returnsquash_slash(xstrdup_or_null(def)); 705 706/* 707 * Generally we prefer the shorter name, especially 708 * if the other one is just a variation of that with 709 * something else tacked on to the end (ie "file.orig" 710 * or "file~"). 711 */ 712if(def) { 713int deflen =strlen(def); 714if(deflen < len && !strncmp(start, def, deflen)) 715returnsquash_slash(xstrdup(def)); 716} 717 718if(state->root.len) { 719char*ret =xstrfmt("%s%.*s", state->root.buf, len, start); 720returnsquash_slash(ret); 721} 722 723returnsquash_slash(xmemdupz(start, len)); 724} 725 726static char*find_name(struct apply_state *state, 727const char*line, 728char*def, 729int p_value, 730int terminate) 731{ 732if(*line =='"') { 733char*name =find_name_gnu(state, line, def, p_value); 734if(name) 735return name; 736} 737 738returnfind_name_common(state, line, def, p_value, NULL, terminate); 739} 740 741static char*find_name_traditional(struct apply_state *state, 742const char*line, 743char*def, 744int p_value) 745{ 746size_t len; 747size_t date_len; 748 749if(*line =='"') { 750char*name =find_name_gnu(state, line, def, p_value); 751if(name) 752return name; 753} 754 755 len =strchrnul(line,'\n') - line; 756 date_len =diff_timestamp_len(line, len); 757if(!date_len) 758returnfind_name_common(state, line, def, p_value, NULL, TERM_TAB); 759 len -= date_len; 760 761returnfind_name_common(state, line, def, p_value, line + len,0); 762} 763 764static intcount_slashes(const char*cp) 765{ 766int cnt =0; 767char ch; 768 769while((ch = *cp++)) 770if(ch =='/') 771 cnt++; 772return cnt; 773} 774 775/* 776 * Given the string after "--- " or "+++ ", guess the appropriate 777 * p_value for the given patch. 778 */ 779static intguess_p_value(struct apply_state *state,const char*nameline) 780{ 781char*name, *cp; 782int val = -1; 783 784if(is_dev_null(nameline)) 785return-1; 786 name =find_name_traditional(state, nameline, NULL,0); 787if(!name) 788return-1; 789 cp =strchr(name,'/'); 790if(!cp) 791 val =0; 792else if(state->prefix) { 793/* 794 * Does it begin with "a/$our-prefix" and such? Then this is 795 * very likely to apply to our directory. 796 */ 797if(starts_with(name, state->prefix)) 798 val =count_slashes(state->prefix); 799else{ 800 cp++; 801if(starts_with(cp, state->prefix)) 802 val =count_slashes(state->prefix) +1; 803} 804} 805free(name); 806return val; 807} 808 809/* 810 * Does the ---/+++ line have the POSIX timestamp after the last HT? 811 * GNU diff puts epoch there to signal a creation/deletion event. Is 812 * this such a timestamp? 813 */ 814static inthas_epoch_timestamp(const char*nameline) 815{ 816/* 817 * We are only interested in epoch timestamp; any non-zero 818 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 819 * For the same reason, the date must be either 1969-12-31 or 820 * 1970-01-01, and the seconds part must be "00". 821 */ 822const char stamp_regexp[] = 823"^(1969-12-31|1970-01-01)" 824" " 825"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 826" " 827"([-+][0-2][0-9]:?[0-5][0-9])\n"; 828const char*timestamp = NULL, *cp, *colon; 829static regex_t *stamp; 830 regmatch_t m[10]; 831int zoneoffset; 832int hourminute; 833int status; 834 835for(cp = nameline; *cp !='\n'; cp++) { 836if(*cp =='\t') 837 timestamp = cp +1; 838} 839if(!timestamp) 840return0; 841if(!stamp) { 842 stamp =xmalloc(sizeof(*stamp)); 843if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 844warning(_("Cannot prepare timestamp regexp%s"), 845 stamp_regexp); 846return0; 847} 848} 849 850 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 851if(status) { 852if(status != REG_NOMATCH) 853warning(_("regexec returned%dfor input:%s"), 854 status, timestamp); 855return0; 856} 857 858 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 859if(*colon ==':') 860 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 861else 862 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 863if(timestamp[m[3].rm_so] =='-') 864 zoneoffset = -zoneoffset; 865 866/* 867 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 868 * (west of GMT) or 1970-01-01 (east of GMT) 869 */ 870if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 871(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 872return0; 873 874 hourminute = (strtol(timestamp +11, NULL,10) *60+ 875strtol(timestamp +14, NULL,10) - 876 zoneoffset); 877 878return((zoneoffset <0&& hourminute ==1440) || 879(0<= zoneoffset && !hourminute)); 880} 881 882/* 883 * Get the name etc info from the ---/+++ lines of a traditional patch header 884 * 885 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 886 * files, we can happily check the index for a match, but for creating a 887 * new file we should try to match whatever "patch" does. I have no idea. 888 */ 889static intparse_traditional_patch(struct apply_state *state, 890const char*first, 891const char*second, 892struct patch *patch) 893{ 894char*name; 895 896 first +=4;/* skip "--- " */ 897 second +=4;/* skip "+++ " */ 898if(!state->p_value_known) { 899int p, q; 900 p =guess_p_value(state, first); 901 q =guess_p_value(state, second); 902if(p <0) p = q; 903if(0<= p && p == q) { 904 state->p_value = p; 905 state->p_value_known =1; 906} 907} 908if(is_dev_null(first)) { 909 patch->is_new =1; 910 patch->is_delete =0; 911 name =find_name_traditional(state, second, NULL, state->p_value); 912 patch->new_name = name; 913}else if(is_dev_null(second)) { 914 patch->is_new =0; 915 patch->is_delete =1; 916 name =find_name_traditional(state, first, NULL, state->p_value); 917 patch->old_name = name; 918}else{ 919char*first_name; 920 first_name =find_name_traditional(state, first, NULL, state->p_value); 921 name =find_name_traditional(state, second, first_name, state->p_value); 922free(first_name); 923if(has_epoch_timestamp(first)) { 924 patch->is_new =1; 925 patch->is_delete =0; 926 patch->new_name = name; 927}else if(has_epoch_timestamp(second)) { 928 patch->is_new =0; 929 patch->is_delete =1; 930 patch->old_name = name; 931}else{ 932 patch->old_name = name; 933 patch->new_name =xstrdup_or_null(name); 934} 935} 936if(!name) 937returnerror(_("unable to find filename in patch at line%d"), state->linenr); 938 939return0; 940} 941 942static intgitdiff_hdrend(struct apply_state *state, 943const char*line, 944struct patch *patch) 945{ 946return1; 947} 948 949/* 950 * We're anal about diff header consistency, to make 951 * sure that we don't end up having strange ambiguous 952 * patches floating around. 953 * 954 * As a result, gitdiff_{old|new}name() will check 955 * their names against any previous information, just 956 * to make sure.. 957 */ 958#define DIFF_OLD_NAME 0 959#define DIFF_NEW_NAME 1 960 961static intgitdiff_verify_name(struct apply_state *state, 962const char*line, 963int isnull, 964char**name, 965int side) 966{ 967if(!*name && !isnull) { 968*name =find_name(state, line, NULL, state->p_value, TERM_TAB); 969return0; 970} 971 972if(*name) { 973int len =strlen(*name); 974char*another; 975if(isnull) 976returnerror(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 977*name, state->linenr); 978 another =find_name(state, line, NULL, state->p_value, TERM_TAB); 979if(!another ||memcmp(another, *name, len +1)) { 980free(another); 981returnerror((side == DIFF_NEW_NAME) ? 982_("git apply: bad git-diff - inconsistent new filename on line%d") : 983_("git apply: bad git-diff - inconsistent old filename on line%d"), state->linenr); 984} 985free(another); 986}else{ 987/* expect "/dev/null" */ 988if(memcmp("/dev/null", line,9) || line[9] !='\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 intgitdiff_oldmode(struct apply_state *state,1014const char*line,1015struct patch *patch)1016{1017 patch->old_mode =strtoul(line, NULL,8);1018return0;1019}10201021static intgitdiff_newmode(struct apply_state *state,1022const char*line,1023struct patch *patch)1024{1025 patch->new_mode =strtoul(line, NULL,8);1026return0;1027}10281029static intgitdiff_delete(struct apply_state *state,1030const char*line,1031struct patch *patch)1032{1033 patch->is_delete =1;1034free(patch->old_name);1035 patch->old_name =xstrdup_or_null(patch->def_name);1036returngitdiff_oldmode(state, line, patch);1037}10381039static intgitdiff_newfile(struct apply_state *state,1040const char*line,1041struct patch *patch)1042{1043 patch->is_new =1;1044free(patch->new_name);1045 patch->new_name =xstrdup_or_null(patch->def_name);1046returngitdiff_newmode(state, line, patch);1047}10481049static intgitdiff_copysrc(struct apply_state *state,1050const char*line,1051struct patch *patch)1052{1053 patch->is_copy =1;1054free(patch->old_name);1055 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1056return0;1057}10581059static intgitdiff_copydst(struct apply_state *state,1060const char*line,1061struct patch *patch)1062{1063 patch->is_copy =1;1064free(patch->new_name);1065 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1066return0;1067}10681069static intgitdiff_renamesrc(struct apply_state *state,1070const char*line,1071struct patch *patch)1072{1073 patch->is_rename =1;1074free(patch->old_name);1075 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1076return0;1077}10781079static intgitdiff_renamedst(struct apply_state *state,1080const char*line,1081struct patch *patch)1082{1083 patch->is_rename =1;1084free(patch->new_name);1085 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1086return0;1087}10881089static intgitdiff_similarity(struct apply_state *state,1090const char*line,1091struct patch *patch)1092{1093unsigned long val =strtoul(line, NULL,10);1094if(val <=100)1095 patch->score = val;1096return0;1097}10981099static intgitdiff_dissimilarity(struct apply_state *state,1100const char*line,1101struct patch *patch)1102{1103unsigned long val =strtoul(line, NULL,10);1104if(val <=100)1105 patch->score = val;1106return0;1107}11081109static intgitdiff_index(struct apply_state *state,1110const char*line,1111struct patch *patch)1112{1113/*1114 * index line is N hexadecimal, "..", N hexadecimal,1115 * and optional space with octal mode.1116 */1117const char*ptr, *eol;1118int len;11191120 ptr =strchr(line,'.');1121if(!ptr || ptr[1] !='.'||40< ptr - line)1122return0;1123 len = ptr - line;1124memcpy(patch->old_sha1_prefix, line, len);1125 patch->old_sha1_prefix[len] =0;11261127 line = ptr +2;1128 ptr =strchr(line,' ');1129 eol =strchrnul(line,'\n');11301131if(!ptr || eol < ptr)1132 ptr = eol;1133 len = ptr - line;11341135if(40< len)1136return0;1137memcpy(patch->new_sha1_prefix, line, len);1138 patch->new_sha1_prefix[len] =0;1139if(*ptr ==' ')1140 patch->old_mode =strtoul(ptr+1, NULL,8);1141return0;1142}11431144/*1145 * This is normal for a diff that doesn't change anything: we'll fall through1146 * into the next diff. Tell the parser to break out.1147 */1148static intgitdiff_unrecognized(struct apply_state *state,1149const char*line,1150struct patch *patch)1151{1152return1;1153}11541155/*1156 * Skip p_value leading components from "line"; as we do not accept1157 * absolute paths, return NULL in that case.1158 */1159static const char*skip_tree_prefix(struct apply_state *state,1160const char*line,1161int llen)1162{1163int nslash;1164int i;11651166if(!state->p_value)1167return(llen && line[0] =='/') ? NULL : line;11681169 nslash = state->p_value;1170for(i =0; i < llen; i++) {1171int ch = line[i];1172if(ch =='/'&& --nslash <=0)1173return(i ==0) ? NULL : &line[i +1];1174}1175return NULL;1176}11771178/*1179 * This is to extract the same name that appears on "diff --git"1180 * line. We do not find and return anything if it is a rename1181 * patch, and it is OK because we will find the name elsewhere.1182 * We need to reliably find name only when it is mode-change only,1183 * creation or deletion of an empty file. In any of these cases,1184 * both sides are the same name under a/ and b/ respectively.1185 */1186static char*git_header_name(struct apply_state *state,1187const char*line,1188int llen)1189{1190const char*name;1191const char*second = NULL;1192size_t len, line_len;11931194 line +=strlen("diff --git ");1195 llen -=strlen("diff --git ");11961197if(*line =='"') {1198const char*cp;1199struct strbuf first = STRBUF_INIT;1200struct strbuf sp = STRBUF_INIT;12011202if(unquote_c_style(&first, line, &second))1203goto free_and_fail1;12041205/* strip the a/b prefix including trailing slash */1206 cp =skip_tree_prefix(state, first.buf, first.len);1207if(!cp)1208goto free_and_fail1;1209strbuf_remove(&first,0, cp - first.buf);12101211/*1212 * second points at one past closing dq of name.1213 * find the second name.1214 */1215while((second < line + llen) &&isspace(*second))1216 second++;12171218if(line + llen <= second)1219goto free_and_fail1;1220if(*second =='"') {1221if(unquote_c_style(&sp, second, NULL))1222goto free_and_fail1;1223 cp =skip_tree_prefix(state, sp.buf, sp.len);1224if(!cp)1225goto free_and_fail1;1226/* They must match, otherwise ignore */1227if(strcmp(cp, first.buf))1228goto free_and_fail1;1229strbuf_release(&sp);1230returnstrbuf_detach(&first, NULL);1231}12321233/* unquoted second */1234 cp =skip_tree_prefix(state, second, line + llen - second);1235if(!cp)1236goto free_and_fail1;1237if(line + llen - cp != first.len ||1238memcmp(first.buf, cp, first.len))1239goto free_and_fail1;1240returnstrbuf_detach(&first, NULL);12411242 free_and_fail1:1243strbuf_release(&first);1244strbuf_release(&sp);1245return NULL;1246}12471248/* unquoted first name */1249 name =skip_tree_prefix(state, line, llen);1250if(!name)1251return NULL;12521253/*1254 * since the first name is unquoted, a dq if exists must be1255 * the beginning of the second name.1256 */1257for(second = name; second < line + llen; second++) {1258if(*second =='"') {1259struct strbuf sp = STRBUF_INIT;1260const char*np;12611262if(unquote_c_style(&sp, second, NULL))1263goto free_and_fail2;12641265 np =skip_tree_prefix(state, sp.buf, sp.len);1266if(!np)1267goto free_and_fail2;12681269 len = sp.buf + sp.len - np;1270if(len < second - name &&1271!strncmp(np, name, len) &&1272isspace(name[len])) {1273/* Good */1274strbuf_remove(&sp,0, np - sp.buf);1275returnstrbuf_detach(&sp, NULL);1276}12771278 free_and_fail2:1279strbuf_release(&sp);1280return NULL;1281}1282}12831284/*1285 * Accept a name only if it shows up twice, exactly the same1286 * form.1287 */1288 second =strchr(name,'\n');1289if(!second)1290return NULL;1291 line_len = second - name;1292for(len =0; ; len++) {1293switch(name[len]) {1294default:1295continue;1296case'\n':1297return NULL;1298case'\t':case' ':1299/*1300 * Is this the separator between the preimage1301 * and the postimage pathname? Again, we are1302 * only interested in the case where there is1303 * no rename, as this is only to set def_name1304 * and a rename patch has the names elsewhere1305 * in an unambiguous form.1306 */1307if(!name[len +1])1308return NULL;/* no postimage name */1309 second =skip_tree_prefix(state, name + len +1,1310 line_len - (len +1));1311if(!second)1312return NULL;1313/*1314 * Does len bytes starting at "name" and "second"1315 * (that are separated by one HT or SP we just1316 * found) exactly match?1317 */1318if(second[len] =='\n'&& !strncmp(name, second, len))1319returnxmemdupz(name, len);1320}1321}1322}13231324/* Verify that we recognize the lines following a git header */1325static intparse_git_header(struct apply_state *state,1326const char*line,1327int len,1328unsigned int size,1329struct patch *patch)1330{1331unsigned long offset;13321333/* A git diff has explicit new/delete information, so we don't guess */1334 patch->is_new =0;1335 patch->is_delete =0;13361337/*1338 * Some things may not have the old name in the1339 * rest of the headers anywhere (pure mode changes,1340 * or removing or adding empty files), so we get1341 * the default name from the header.1342 */1343 patch->def_name =git_header_name(state, line, len);1344if(patch->def_name && state->root.len) {1345char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1346free(patch->def_name);1347 patch->def_name = s;1348}13491350 line += len;1351 size -= len;1352 state->linenr++;1353for(offset = len ; size >0; offset += len, size -= len, line += len, state->linenr++) {1354static const struct opentry {1355const char*str;1356int(*fn)(struct apply_state *,const char*,struct patch *);1357} optable[] = {1358{"@@ -", gitdiff_hdrend },1359{"--- ", gitdiff_oldname },1360{"+++ ", gitdiff_newname },1361{"old mode ", gitdiff_oldmode },1362{"new mode ", gitdiff_newmode },1363{"deleted file mode ", gitdiff_delete },1364{"new file mode ", gitdiff_newfile },1365{"copy from ", gitdiff_copysrc },1366{"copy to ", gitdiff_copydst },1367{"rename old ", gitdiff_renamesrc },1368{"rename new ", gitdiff_renamedst },1369{"rename from ", gitdiff_renamesrc },1370{"rename to ", gitdiff_renamedst },1371{"similarity index ", gitdiff_similarity },1372{"dissimilarity index ", gitdiff_dissimilarity },1373{"index ", gitdiff_index },1374{"", gitdiff_unrecognized },1375};1376int i;13771378 len =linelen(line, size);1379if(!len || line[len-1] !='\n')1380break;1381for(i =0; i <ARRAY_SIZE(optable); i++) {1382const struct opentry *p = optable + i;1383int oplen =strlen(p->str);1384int res;1385if(len < oplen ||memcmp(p->str, line, oplen))1386continue;1387 res = p->fn(state, line + oplen, patch);1388if(res <0)1389return-1;1390if(res >0)1391return offset;1392break;1393}1394}13951396return offset;1397}13981399static intparse_num(const char*line,unsigned long*p)1400{1401char*ptr;14021403if(!isdigit(*line))1404return0;1405*p =strtoul(line, &ptr,10);1406return ptr - line;1407}14081409static intparse_range(const char*line,int len,int offset,const char*expect,1410unsigned long*p1,unsigned long*p2)1411{1412int digits, ex;14131414if(offset <0|| offset >= len)1415return-1;1416 line += offset;1417 len -= offset;14181419 digits =parse_num(line, p1);1420if(!digits)1421return-1;14221423 offset += digits;1424 line += digits;1425 len -= digits;14261427*p2 =1;1428if(*line ==',') {1429 digits =parse_num(line+1, p2);1430if(!digits)1431return-1;14321433 offset += digits+1;1434 line += digits+1;1435 len -= digits+1;1436}14371438 ex =strlen(expect);1439if(ex > len)1440return-1;1441if(memcmp(line, expect, ex))1442return-1;14431444return offset + ex;1445}14461447static voidrecount_diff(const char*line,int size,struct fragment *fragment)1448{1449int oldlines =0, newlines =0, ret =0;14501451if(size <1) {1452warning("recount: ignore empty hunk");1453return;1454}14551456for(;;) {1457int len =linelen(line, size);1458 size -= len;1459 line += len;14601461if(size <1)1462break;14631464switch(*line) {1465case' ':case'\n':1466 newlines++;1467/* fall through */1468case'-':1469 oldlines++;1470continue;1471case'+':1472 newlines++;1473continue;1474case'\\':1475continue;1476case'@':1477 ret = size <3|| !starts_with(line,"@@ ");1478break;1479case'd':1480 ret = size <5|| !starts_with(line,"diff ");1481break;1482default:1483 ret = -1;1484break;1485}1486if(ret) {1487warning(_("recount: unexpected line: %.*s"),1488(int)linelen(line, size), line);1489return;1490}1491break;1492}1493 fragment->oldlines = oldlines;1494 fragment->newlines = newlines;1495}14961497/*1498 * Parse a unified diff fragment header of the1499 * form "@@ -a,b +c,d @@"1500 */1501static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1502{1503int offset;15041505if(!len || line[len-1] !='\n')1506return-1;15071508/* Figure out the number of lines in a fragment */1509 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1510 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);15111512return offset;1513}15141515/*1516 * Find file diff header1517 *1518 * Returns:1519 * -1 if no header was found1520 * -128 in case of error1521 * the size of the header in bytes (called "offset") otherwise1522 */1523static intfind_header(struct apply_state *state,1524const char*line,1525unsigned long size,1526int*hdrsize,1527struct patch *patch)1528{1529unsigned long offset, len;15301531 patch->is_toplevel_relative =0;1532 patch->is_rename = patch->is_copy =0;1533 patch->is_new = patch->is_delete = -1;1534 patch->old_mode = patch->new_mode =0;1535 patch->old_name = patch->new_name = NULL;1536for(offset =0; size >0; offset += len, size -= len, line += len, state->linenr++) {1537unsigned long nextlen;15381539 len =linelen(line, size);1540if(!len)1541break;15421543/* Testing this early allows us to take a few shortcuts.. */1544if(len <6)1545continue;15461547/*1548 * Make sure we don't find any unconnected patch fragments.1549 * That's a sign that we didn't find a header, and that a1550 * patch has become corrupted/broken up.1551 */1552if(!memcmp("@@ -", line,4)) {1553struct fragment dummy;1554if(parse_fragment_header(line, len, &dummy) <0)1555continue;1556error(_("patch fragment without header at line%d: %.*s"),1557 state->linenr, (int)len-1, line);1558return-128;1559}15601561if(size < len +6)1562break;15631564/*1565 * Git patch? It might not have a real patch, just a rename1566 * or mode change, so we handle that specially1567 */1568if(!memcmp("diff --git ", line,11)) {1569int git_hdr_len =parse_git_header(state, line, len, size, patch);1570if(git_hdr_len <0)1571return-128;1572if(git_hdr_len <= len)1573continue;1574if(!patch->old_name && !patch->new_name) {1575if(!patch->def_name) {1576error(Q_("git diff header lacks filename information when removing "1577"%dleading pathname component (line%d)",1578"git diff header lacks filename information when removing "1579"%dleading pathname components (line%d)",1580 state->p_value),1581 state->p_value, state->linenr);1582return-128;1583}1584 patch->old_name =xstrdup(patch->def_name);1585 patch->new_name =xstrdup(patch->def_name);1586}1587if(!patch->is_delete && !patch->new_name) {1588error(_("git diff header lacks filename information "1589"(line%d)"), state->linenr);1590return-128;1591}1592 patch->is_toplevel_relative =1;1593*hdrsize = git_hdr_len;1594return offset;1595}15961597/* --- followed by +++ ? */1598if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1599continue;16001601/*1602 * We only accept unified patches, so we want it to1603 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1604 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1605 */1606 nextlen =linelen(line + len, size - len);1607if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1608continue;16091610/* Ok, we'll consider it a patch */1611if(parse_traditional_patch(state, line, line+len, patch))1612return-128;1613*hdrsize = len + nextlen;1614 state->linenr +=2;1615return offset;1616}1617return-1;1618}16191620static voidrecord_ws_error(struct apply_state *state,1621unsigned result,1622const char*line,1623int len,1624int linenr)1625{1626char*err;16271628if(!result)1629return;16301631 state->whitespace_error++;1632if(state->squelch_whitespace_errors &&1633 state->squelch_whitespace_errors < state->whitespace_error)1634return;16351636 err =whitespace_error_string(result);1637if(state->apply_verbosity > verbosity_silent)1638fprintf(stderr,"%s:%d:%s.\n%.*s\n",1639 state->patch_input_file, linenr, err, len, line);1640free(err);1641}16421643static voidcheck_whitespace(struct apply_state *state,1644const char*line,1645int len,1646unsigned ws_rule)1647{1648unsigned result =ws_check(line +1, len -1, ws_rule);16491650record_ws_error(state, result, line +1, len -2, state->linenr);1651}16521653/*1654 * Parse a unified diff. Note that this really needs to parse each1655 * fragment separately, since the only way to know the difference1656 * between a "---" that is part of a patch, and a "---" that starts1657 * the next patch is to look at the line counts..1658 */1659static intparse_fragment(struct apply_state *state,1660const char*line,1661unsigned long size,1662struct patch *patch,1663struct fragment *fragment)1664{1665int added, deleted;1666int len =linelen(line, size), offset;1667unsigned long oldlines, newlines;1668unsigned long leading, trailing;16691670 offset =parse_fragment_header(line, len, fragment);1671if(offset <0)1672return-1;1673if(offset >0&& patch->recount)1674recount_diff(line + offset, size - offset, fragment);1675 oldlines = fragment->oldlines;1676 newlines = fragment->newlines;1677 leading =0;1678 trailing =0;16791680/* Parse the thing.. */1681 line += len;1682 size -= len;1683 state->linenr++;1684 added = deleted =0;1685for(offset = len;16860< size;1687 offset += len, size -= len, line += len, state->linenr++) {1688if(!oldlines && !newlines)1689break;1690 len =linelen(line, size);1691if(!len || line[len-1] !='\n')1692return-1;1693switch(*line) {1694default:1695return-1;1696case'\n':/* newer GNU diff, an empty context line */1697case' ':1698 oldlines--;1699 newlines--;1700if(!deleted && !added)1701 leading++;1702 trailing++;1703if(!state->apply_in_reverse &&1704 state->ws_error_action == correct_ws_error)1705check_whitespace(state, line, len, patch->ws_rule);1706break;1707case'-':1708if(state->apply_in_reverse &&1709 state->ws_error_action != nowarn_ws_error)1710check_whitespace(state, line, len, patch->ws_rule);1711 deleted++;1712 oldlines--;1713 trailing =0;1714break;1715case'+':1716if(!state->apply_in_reverse &&1717 state->ws_error_action != nowarn_ws_error)1718check_whitespace(state, line, len, patch->ws_rule);1719 added++;1720 newlines--;1721 trailing =0;1722break;17231724/*1725 * We allow "\ No newline at end of file". Depending1726 * on locale settings when the patch was produced we1727 * don't know what this line looks like. The only1728 * thing we do know is that it begins with "\ ".1729 * Checking for 12 is just for sanity check -- any1730 * l10n of "\ No newline..." is at least that long.1731 */1732case'\\':1733if(len <12||memcmp(line,"\\",2))1734return-1;1735break;1736}1737}1738if(oldlines || newlines)1739return-1;1740if(!deleted && !added)1741return-1;17421743 fragment->leading = leading;1744 fragment->trailing = trailing;17451746/*1747 * If a fragment ends with an incomplete line, we failed to include1748 * it in the above loop because we hit oldlines == newlines == 01749 * before seeing it.1750 */1751if(12< size && !memcmp(line,"\\",2))1752 offset +=linelen(line, size);17531754 patch->lines_added += added;1755 patch->lines_deleted += deleted;17561757if(0< patch->is_new && oldlines)1758returnerror(_("new file depends on old contents"));1759if(0< patch->is_delete && newlines)1760returnerror(_("deleted file still has contents"));1761return offset;1762}17631764/*1765 * We have seen "diff --git a/... b/..." header (or a traditional patch1766 * header). Read hunks that belong to this patch into fragments and hang1767 * them to the given patch structure.1768 *1769 * The (fragment->patch, fragment->size) pair points into the memory given1770 * by the caller, not a copy, when we return.1771 *1772 * Returns:1773 * -1 in case of error,1774 * the number of bytes in the patch otherwise.1775 */1776static intparse_single_patch(struct apply_state *state,1777const char*line,1778unsigned long size,1779struct patch *patch)1780{1781unsigned long offset =0;1782unsigned long oldlines =0, newlines =0, context =0;1783struct fragment **fragp = &patch->fragments;17841785while(size >4&& !memcmp(line,"@@ -",4)) {1786struct fragment *fragment;1787int len;17881789 fragment =xcalloc(1,sizeof(*fragment));1790 fragment->linenr = state->linenr;1791 len =parse_fragment(state, line, size, patch, fragment);1792if(len <=0) {1793free(fragment);1794returnerror(_("corrupt patch at line%d"), state->linenr);1795}1796 fragment->patch = line;1797 fragment->size = len;1798 oldlines += fragment->oldlines;1799 newlines += fragment->newlines;1800 context += fragment->leading + fragment->trailing;18011802*fragp = fragment;1803 fragp = &fragment->next;18041805 offset += len;1806 line += len;1807 size -= len;1808}18091810/*1811 * If something was removed (i.e. we have old-lines) it cannot1812 * be creation, and if something was added it cannot be1813 * deletion. However, the reverse is not true; --unified=01814 * patches that only add are not necessarily creation even1815 * though they do not have any old lines, and ones that only1816 * delete are not necessarily deletion.1817 *1818 * Unfortunately, a real creation/deletion patch do _not_ have1819 * any context line by definition, so we cannot safely tell it1820 * apart with --unified=0 insanity. At least if the patch has1821 * more than one hunk it is not creation or deletion.1822 */1823if(patch->is_new <0&&1824(oldlines || (patch->fragments && patch->fragments->next)))1825 patch->is_new =0;1826if(patch->is_delete <0&&1827(newlines || (patch->fragments && patch->fragments->next)))1828 patch->is_delete =0;18291830if(0< patch->is_new && oldlines)1831returnerror(_("new file%sdepends on old contents"), patch->new_name);1832if(0< patch->is_delete && newlines)1833returnerror(_("deleted file%sstill has contents"), patch->old_name);1834if(!patch->is_delete && !newlines && context && state->apply_verbosity > verbosity_silent)1835fprintf_ln(stderr,1836_("** warning: "1837"file%sbecomes empty but is not deleted"),1838 patch->new_name);18391840return offset;1841}18421843staticinlineintmetadata_changes(struct patch *patch)1844{1845return patch->is_rename >0||1846 patch->is_copy >0||1847 patch->is_new >0||1848 patch->is_delete ||1849(patch->old_mode && patch->new_mode &&1850 patch->old_mode != patch->new_mode);1851}18521853static char*inflate_it(const void*data,unsigned long size,1854unsigned long inflated_size)1855{1856 git_zstream stream;1857void*out;1858int st;18591860memset(&stream,0,sizeof(stream));18611862 stream.next_in = (unsigned char*)data;1863 stream.avail_in = size;1864 stream.next_out = out =xmalloc(inflated_size);1865 stream.avail_out = inflated_size;1866git_inflate_init(&stream);1867 st =git_inflate(&stream, Z_FINISH);1868git_inflate_end(&stream);1869if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1870free(out);1871return NULL;1872}1873return out;1874}18751876/*1877 * Read a binary hunk and return a new fragment; fragment->patch1878 * points at an allocated memory that the caller must free, so1879 * it is marked as "->free_patch = 1".1880 */1881static struct fragment *parse_binary_hunk(struct apply_state *state,1882char**buf_p,1883unsigned long*sz_p,1884int*status_p,1885int*used_p)1886{1887/*1888 * Expect a line that begins with binary patch method ("literal"1889 * or "delta"), followed by the length of data before deflating.1890 * a sequence of 'length-byte' followed by base-85 encoded data1891 * should follow, terminated by a newline.1892 *1893 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1894 * and we would limit the patch line to 66 characters,1895 * so one line can fit up to 13 groups that would decode1896 * to 52 bytes max. The length byte 'A'-'Z' corresponds1897 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1898 */1899int llen, used;1900unsigned long size = *sz_p;1901char*buffer = *buf_p;1902int patch_method;1903unsigned long origlen;1904char*data = NULL;1905int hunk_size =0;1906struct fragment *frag;19071908 llen =linelen(buffer, size);1909 used = llen;19101911*status_p =0;19121913if(starts_with(buffer,"delta ")) {1914 patch_method = BINARY_DELTA_DEFLATED;1915 origlen =strtoul(buffer +6, NULL,10);1916}1917else if(starts_with(buffer,"literal ")) {1918 patch_method = BINARY_LITERAL_DEFLATED;1919 origlen =strtoul(buffer +8, NULL,10);1920}1921else1922return NULL;19231924 state->linenr++;1925 buffer += llen;1926while(1) {1927int byte_length, max_byte_length, newsize;1928 llen =linelen(buffer, size);1929 used += llen;1930 state->linenr++;1931if(llen ==1) {1932/* consume the blank line */1933 buffer++;1934 size--;1935break;1936}1937/*1938 * Minimum line is "A00000\n" which is 7-byte long,1939 * and the line length must be multiple of 5 plus 2.1940 */1941if((llen <7) || (llen-2) %5)1942goto corrupt;1943 max_byte_length = (llen -2) /5*4;1944 byte_length = *buffer;1945if('A'<= byte_length && byte_length <='Z')1946 byte_length = byte_length -'A'+1;1947else if('a'<= byte_length && byte_length <='z')1948 byte_length = byte_length -'a'+27;1949else1950goto corrupt;1951/* if the input length was not multiple of 4, we would1952 * have filler at the end but the filler should never1953 * exceed 3 bytes1954 */1955if(max_byte_length < byte_length ||1956 byte_length <= max_byte_length -4)1957goto corrupt;1958 newsize = hunk_size + byte_length;1959 data =xrealloc(data, newsize);1960if(decode_85(data + hunk_size, buffer +1, byte_length))1961goto corrupt;1962 hunk_size = newsize;1963 buffer += llen;1964 size -= llen;1965}19661967 frag =xcalloc(1,sizeof(*frag));1968 frag->patch =inflate_it(data, hunk_size, origlen);1969 frag->free_patch =1;1970if(!frag->patch)1971goto corrupt;1972free(data);1973 frag->size = origlen;1974*buf_p = buffer;1975*sz_p = size;1976*used_p = used;1977 frag->binary_patch_method = patch_method;1978return frag;19791980 corrupt:1981free(data);1982*status_p = -1;1983error(_("corrupt binary patch at line%d: %.*s"),1984 state->linenr-1, llen-1, buffer);1985return NULL;1986}19871988/*1989 * Returns:1990 * -1 in case of error,1991 * the length of the parsed binary patch otherwise1992 */1993static intparse_binary(struct apply_state *state,1994char*buffer,1995unsigned long size,1996struct patch *patch)1997{1998/*1999 * We have read "GIT binary patch\n"; what follows is a line2000 * that says the patch method (currently, either "literal" or2001 * "delta") and the length of data before deflating; a2002 * sequence of 'length-byte' followed by base-85 encoded data2003 * follows.2004 *2005 * When a binary patch is reversible, there is another binary2006 * hunk in the same format, starting with patch method (either2007 * "literal" or "delta") with the length of data, and a sequence2008 * of length-byte + base-85 encoded data, terminated with another2009 * empty line. This data, when applied to the postimage, produces2010 * the preimage.2011 */2012struct fragment *forward;2013struct fragment *reverse;2014int status;2015int used, used_1;20162017 forward =parse_binary_hunk(state, &buffer, &size, &status, &used);2018if(!forward && !status)2019/* there has to be one hunk (forward hunk) */2020returnerror(_("unrecognized binary patch at line%d"), state->linenr-1);2021if(status)2022/* otherwise we already gave an error message */2023return status;20242025 reverse =parse_binary_hunk(state, &buffer, &size, &status, &used_1);2026if(reverse)2027 used += used_1;2028else if(status) {2029/*2030 * Not having reverse hunk is not an error, but having2031 * a corrupt reverse hunk is.2032 */2033free((void*) forward->patch);2034free(forward);2035return status;2036}2037 forward->next = reverse;2038 patch->fragments = forward;2039 patch->is_binary =1;2040return used;2041}20422043static voidprefix_one(struct apply_state *state,char**name)2044{2045char*old_name = *name;2046if(!old_name)2047return;2048*name =xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));2049free(old_name);2050}20512052static voidprefix_patch(struct apply_state *state,struct patch *p)2053{2054if(!state->prefix || p->is_toplevel_relative)2055return;2056prefix_one(state, &p->new_name);2057prefix_one(state, &p->old_name);2058}20592060/*2061 * include/exclude2062 */20632064static voidadd_name_limit(struct apply_state *state,2065const char*name,2066int exclude)2067{2068struct string_list_item *it;20692070 it =string_list_append(&state->limit_by_name, name);2071 it->util = exclude ? NULL : (void*)1;2072}20732074static intuse_patch(struct apply_state *state,struct patch *p)2075{2076const char*pathname = p->new_name ? p->new_name : p->old_name;2077int i;20782079/* Paths outside are not touched regardless of "--include" */2080if(state->prefix && *state->prefix) {2081const char*rest;2082if(!skip_prefix(pathname, state->prefix, &rest) || !*rest)2083return0;2084}20852086/* See if it matches any of exclude/include rule */2087for(i =0; i < state->limit_by_name.nr; i++) {2088struct string_list_item *it = &state->limit_by_name.items[i];2089if(!wildmatch(it->string, pathname,0, NULL))2090return(it->util != NULL);2091}20922093/*2094 * If we had any include, a path that does not match any rule is2095 * not used. Otherwise, we saw bunch of exclude rules (or none)2096 * and such a path is used.2097 */2098return!state->has_include;2099}21002101/*2102 * Read the patch text in "buffer" that extends for "size" bytes; stop2103 * reading after seeing a single patch (i.e. changes to a single file).2104 * Create fragments (i.e. patch hunks) and hang them to the given patch.2105 *2106 * Returns:2107 * -1 if no header was found or parse_binary() failed,2108 * -128 on another error,2109 * the number of bytes consumed otherwise,2110 * so that the caller can call us again for the next patch.2111 */2112static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2113{2114int hdrsize, patchsize;2115int offset =find_header(state, buffer, size, &hdrsize, patch);21162117if(offset <0)2118return offset;21192120prefix_patch(state, patch);21212122if(!use_patch(state, patch))2123 patch->ws_rule =0;2124else2125 patch->ws_rule =whitespace_rule(patch->new_name2126? patch->new_name2127: patch->old_name);21282129 patchsize =parse_single_patch(state,2130 buffer + offset + hdrsize,2131 size - offset - hdrsize,2132 patch);21332134if(patchsize <0)2135return-128;21362137if(!patchsize) {2138static const char git_binary[] ="GIT binary patch\n";2139int hd = hdrsize + offset;2140unsigned long llen =linelen(buffer + hd, size - hd);21412142if(llen ==sizeof(git_binary) -1&&2143!memcmp(git_binary, buffer + hd, llen)) {2144int used;2145 state->linenr++;2146 used =parse_binary(state, buffer + hd + llen,2147 size - hd - llen, patch);2148if(used <0)2149return-1;2150if(used)2151 patchsize = used + llen;2152else2153 patchsize =0;2154}2155else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2156static const char*binhdr[] = {2157"Binary files ",2158"Files ",2159 NULL,2160};2161int i;2162for(i =0; binhdr[i]; i++) {2163int len =strlen(binhdr[i]);2164if(len < size - hd &&2165!memcmp(binhdr[i], buffer + hd, len)) {2166 state->linenr++;2167 patch->is_binary =1;2168 patchsize = llen;2169break;2170}2171}2172}21732174/* Empty patch cannot be applied if it is a text patch2175 * without metadata change. A binary patch appears2176 * empty to us here.2177 */2178if((state->apply || state->check) &&2179(!patch->is_binary && !metadata_changes(patch))) {2180error(_("patch with only garbage at line%d"), state->linenr);2181return-128;2182}2183}21842185return offset + hdrsize + patchsize;2186}21872188static voidreverse_patches(struct patch *p)2189{2190for(; p; p = p->next) {2191struct fragment *frag = p->fragments;21922193SWAP(p->new_name, p->old_name);2194SWAP(p->new_mode, p->old_mode);2195SWAP(p->is_new, p->is_delete);2196SWAP(p->lines_added, p->lines_deleted);2197SWAP(p->old_sha1_prefix, p->new_sha1_prefix);21982199for(; frag; frag = frag->next) {2200SWAP(frag->newpos, frag->oldpos);2201SWAP(frag->newlines, frag->oldlines);2202}2203}2204}22052206static const char pluses[] =2207"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2208static const char minuses[]=2209"----------------------------------------------------------------------";22102211static voidshow_stats(struct apply_state *state,struct patch *patch)2212{2213struct strbuf qname = STRBUF_INIT;2214char*cp = patch->new_name ? patch->new_name : patch->old_name;2215int max, add, del;22162217quote_c_style(cp, &qname, NULL,0);22182219/*2220 * "scale" the filename2221 */2222 max = state->max_len;2223if(max >50)2224 max =50;22252226if(qname.len > max) {2227 cp =strchr(qname.buf + qname.len +3- max,'/');2228if(!cp)2229 cp = qname.buf + qname.len +3- max;2230strbuf_splice(&qname,0, cp - qname.buf,"...",3);2231}22322233if(patch->is_binary) {2234printf(" %-*s | Bin\n", max, qname.buf);2235strbuf_release(&qname);2236return;2237}22382239printf(" %-*s |", max, qname.buf);2240strbuf_release(&qname);22412242/*2243 * scale the add/delete2244 */2245 max = max + state->max_change >70?70- max : state->max_change;2246 add = patch->lines_added;2247 del = patch->lines_deleted;22482249if(state->max_change >0) {2250int total = ((add + del) * max + state->max_change /2) / state->max_change;2251 add = (add * max + state->max_change /2) / state->max_change;2252 del = total - add;2253}2254printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2255 add, pluses, del, minuses);2256}22572258static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2259{2260switch(st->st_mode & S_IFMT) {2261case S_IFLNK:2262if(strbuf_readlink(buf, path, st->st_size) <0)2263returnerror(_("unable to read symlink%s"), path);2264return0;2265case S_IFREG:2266if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2267returnerror(_("unable to open or read%s"), path);2268convert_to_git(path, buf->buf, buf->len, buf,0);2269return0;2270default:2271return-1;2272}2273}22742275/*2276 * Update the preimage, and the common lines in postimage,2277 * from buffer buf of length len. If postlen is 0 the postimage2278 * is updated in place, otherwise it's updated on a new buffer2279 * of length postlen2280 */22812282static voidupdate_pre_post_images(struct image *preimage,2283struct image *postimage,2284char*buf,2285size_t len,size_t postlen)2286{2287int i, ctx, reduced;2288char*new, *old, *fixed;2289struct image fixed_preimage;22902291/*2292 * Update the preimage with whitespace fixes. Note that we2293 * are not losing preimage->buf -- apply_one_fragment() will2294 * free "oldlines".2295 */2296prepare_image(&fixed_preimage, buf, len,1);2297assert(postlen2298? fixed_preimage.nr == preimage->nr2299: fixed_preimage.nr <= preimage->nr);2300for(i =0; i < fixed_preimage.nr; i++)2301 fixed_preimage.line[i].flag = preimage->line[i].flag;2302free(preimage->line_allocated);2303*preimage = fixed_preimage;23042305/*2306 * Adjust the common context lines in postimage. This can be2307 * done in-place when we are shrinking it with whitespace2308 * fixing, but needs a new buffer when ignoring whitespace or2309 * expanding leading tabs to spaces.2310 *2311 * We trust the caller to tell us if the update can be done2312 * in place (postlen==0) or not.2313 */2314 old = postimage->buf;2315if(postlen)2316new= postimage->buf =xmalloc(postlen);2317else2318new= old;2319 fixed = preimage->buf;23202321for(i = reduced = ctx =0; i < postimage->nr; i++) {2322size_t l_len = postimage->line[i].len;2323if(!(postimage->line[i].flag & LINE_COMMON)) {2324/* an added line -- no counterparts in preimage */2325memmove(new, old, l_len);2326 old += l_len;2327new+= l_len;2328continue;2329}23302331/* a common context -- skip it in the original postimage */2332 old += l_len;23332334/* and find the corresponding one in the fixed preimage */2335while(ctx < preimage->nr &&2336!(preimage->line[ctx].flag & LINE_COMMON)) {2337 fixed += preimage->line[ctx].len;2338 ctx++;2339}23402341/*2342 * preimage is expected to run out, if the caller2343 * fixed addition of trailing blank lines.2344 */2345if(preimage->nr <= ctx) {2346 reduced++;2347continue;2348}23492350/* and copy it in, while fixing the line length */2351 l_len = preimage->line[ctx].len;2352memcpy(new, fixed, l_len);2353new+= l_len;2354 fixed += l_len;2355 postimage->line[i].len = l_len;2356 ctx++;2357}23582359if(postlen2360? postlen <new- postimage->buf2361: postimage->len <new- postimage->buf)2362die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2363(int)postlen, (int) postimage->len, (int)(new- postimage->buf));23642365/* Fix the length of the whole thing */2366 postimage->len =new- postimage->buf;2367 postimage->nr -= reduced;2368}23692370static intline_by_line_fuzzy_match(struct image *img,2371struct image *preimage,2372struct image *postimage,2373unsigned longtry,2374int try_lno,2375int preimage_limit)2376{2377int i;2378size_t imgoff =0;2379size_t preoff =0;2380size_t postlen = postimage->len;2381size_t extra_chars;2382char*buf;2383char*preimage_eof;2384char*preimage_end;2385struct strbuf fixed;2386char*fixed_buf;2387size_t fixed_len;23882389for(i =0; i < preimage_limit; i++) {2390size_t prelen = preimage->line[i].len;2391size_t imglen = img->line[try_lno+i].len;23922393if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2394 preimage->buf + preoff, prelen))2395return0;2396if(preimage->line[i].flag & LINE_COMMON)2397 postlen += imglen - prelen;2398 imgoff += imglen;2399 preoff += prelen;2400}24012402/*2403 * Ok, the preimage matches with whitespace fuzz.2404 *2405 * imgoff now holds the true length of the target that2406 * matches the preimage before the end of the file.2407 *2408 * Count the number of characters in the preimage that fall2409 * beyond the end of the file and make sure that all of them2410 * are whitespace characters. (This can only happen if2411 * we are removing blank lines at the end of the file.)2412 */2413 buf = preimage_eof = preimage->buf + preoff;2414for( ; i < preimage->nr; i++)2415 preoff += preimage->line[i].len;2416 preimage_end = preimage->buf + preoff;2417for( ; buf < preimage_end; buf++)2418if(!isspace(*buf))2419return0;24202421/*2422 * Update the preimage and the common postimage context2423 * lines to use the same whitespace as the target.2424 * If whitespace is missing in the target (i.e.2425 * if the preimage extends beyond the end of the file),2426 * use the whitespace from the preimage.2427 */2428 extra_chars = preimage_end - preimage_eof;2429strbuf_init(&fixed, imgoff + extra_chars);2430strbuf_add(&fixed, img->buf +try, imgoff);2431strbuf_add(&fixed, preimage_eof, extra_chars);2432 fixed_buf =strbuf_detach(&fixed, &fixed_len);2433update_pre_post_images(preimage, postimage,2434 fixed_buf, fixed_len, postlen);2435return1;2436}24372438static intmatch_fragment(struct apply_state *state,2439struct image *img,2440struct image *preimage,2441struct image *postimage,2442unsigned longtry,2443int try_lno,2444unsigned ws_rule,2445int match_beginning,int match_end)2446{2447int i;2448char*fixed_buf, *buf, *orig, *target;2449struct strbuf fixed;2450size_t fixed_len, postlen;2451int preimage_limit;24522453if(preimage->nr + try_lno <= img->nr) {2454/*2455 * The hunk falls within the boundaries of img.2456 */2457 preimage_limit = preimage->nr;2458if(match_end && (preimage->nr + try_lno != img->nr))2459return0;2460}else if(state->ws_error_action == correct_ws_error &&2461(ws_rule & WS_BLANK_AT_EOF)) {2462/*2463 * This hunk extends beyond the end of img, and we are2464 * removing blank lines at the end of the file. This2465 * many lines from the beginning of the preimage must2466 * match with img, and the remainder of the preimage2467 * must be blank.2468 */2469 preimage_limit = img->nr - try_lno;2470}else{2471/*2472 * The hunk extends beyond the end of the img and2473 * we are not removing blanks at the end, so we2474 * should reject the hunk at this position.2475 */2476return0;2477}24782479if(match_beginning && try_lno)2480return0;24812482/* Quick hash check */2483for(i =0; i < preimage_limit; i++)2484if((img->line[try_lno + i].flag & LINE_PATCHED) ||2485(preimage->line[i].hash != img->line[try_lno + i].hash))2486return0;24872488if(preimage_limit == preimage->nr) {2489/*2490 * Do we have an exact match? If we were told to match2491 * at the end, size must be exactly at try+fragsize,2492 * otherwise try+fragsize must be still within the preimage,2493 * and either case, the old piece should match the preimage2494 * exactly.2495 */2496if((match_end2497? (try+ preimage->len == img->len)2498: (try+ preimage->len <= img->len)) &&2499!memcmp(img->buf +try, preimage->buf, preimage->len))2500return1;2501}else{2502/*2503 * The preimage extends beyond the end of img, so2504 * there cannot be an exact match.2505 *2506 * There must be one non-blank context line that match2507 * a line before the end of img.2508 */2509char*buf_end;25102511 buf = preimage->buf;2512 buf_end = buf;2513for(i =0; i < preimage_limit; i++)2514 buf_end += preimage->line[i].len;25152516for( ; buf < buf_end; buf++)2517if(!isspace(*buf))2518break;2519if(buf == buf_end)2520return0;2521}25222523/*2524 * No exact match. If we are ignoring whitespace, run a line-by-line2525 * fuzzy matching. We collect all the line length information because2526 * we need it to adjust whitespace if we match.2527 */2528if(state->ws_ignore_action == ignore_ws_change)2529returnline_by_line_fuzzy_match(img, preimage, postimage,2530try, try_lno, preimage_limit);25312532if(state->ws_error_action != correct_ws_error)2533return0;25342535/*2536 * The hunk does not apply byte-by-byte, but the hash says2537 * it might with whitespace fuzz. We weren't asked to2538 * ignore whitespace, we were asked to correct whitespace2539 * errors, so let's try matching after whitespace correction.2540 *2541 * While checking the preimage against the target, whitespace2542 * errors in both fixed, we count how large the corresponding2543 * postimage needs to be. The postimage prepared by2544 * apply_one_fragment() has whitespace errors fixed on added2545 * lines already, but the common lines were propagated as-is,2546 * which may become longer when their whitespace errors are2547 * fixed.2548 */25492550/* First count added lines in postimage */2551 postlen =0;2552for(i =0; i < postimage->nr; i++) {2553if(!(postimage->line[i].flag & LINE_COMMON))2554 postlen += postimage->line[i].len;2555}25562557/*2558 * The preimage may extend beyond the end of the file,2559 * but in this loop we will only handle the part of the2560 * preimage that falls within the file.2561 */2562strbuf_init(&fixed, preimage->len +1);2563 orig = preimage->buf;2564 target = img->buf +try;2565for(i =0; i < preimage_limit; i++) {2566size_t oldlen = preimage->line[i].len;2567size_t tgtlen = img->line[try_lno + i].len;2568size_t fixstart = fixed.len;2569struct strbuf tgtfix;2570int match;25712572/* Try fixing the line in the preimage */2573ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25742575/* Try fixing the line in the target */2576strbuf_init(&tgtfix, tgtlen);2577ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);25782579/*2580 * If they match, either the preimage was based on2581 * a version before our tree fixed whitespace breakage,2582 * or we are lacking a whitespace-fix patch the tree2583 * the preimage was based on already had (i.e. target2584 * has whitespace breakage, the preimage doesn't).2585 * In either case, we are fixing the whitespace breakages2586 * so we might as well take the fix together with their2587 * real change.2588 */2589 match = (tgtfix.len == fixed.len - fixstart &&2590!memcmp(tgtfix.buf, fixed.buf + fixstart,2591 fixed.len - fixstart));25922593/* Add the length if this is common with the postimage */2594if(preimage->line[i].flag & LINE_COMMON)2595 postlen += tgtfix.len;25962597strbuf_release(&tgtfix);2598if(!match)2599goto unmatch_exit;26002601 orig += oldlen;2602 target += tgtlen;2603}260426052606/*2607 * Now handle the lines in the preimage that falls beyond the2608 * end of the file (if any). They will only match if they are2609 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2610 * false).2611 */2612for( ; i < preimage->nr; i++) {2613size_t fixstart = fixed.len;/* start of the fixed preimage */2614size_t oldlen = preimage->line[i].len;2615int j;26162617/* Try fixing the line in the preimage */2618ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);26192620for(j = fixstart; j < fixed.len; j++)2621if(!isspace(fixed.buf[j]))2622goto unmatch_exit;26232624 orig += oldlen;2625}26262627/*2628 * Yes, the preimage is based on an older version that still2629 * has whitespace breakages unfixed, and fixing them makes the2630 * hunk match. Update the context lines in the postimage.2631 */2632 fixed_buf =strbuf_detach(&fixed, &fixed_len);2633if(postlen < postimage->len)2634 postlen =0;2635update_pre_post_images(preimage, postimage,2636 fixed_buf, fixed_len, postlen);2637return1;26382639 unmatch_exit:2640strbuf_release(&fixed);2641return0;2642}26432644static intfind_pos(struct apply_state *state,2645struct image *img,2646struct image *preimage,2647struct image *postimage,2648int line,2649unsigned ws_rule,2650int match_beginning,int match_end)2651{2652int i;2653unsigned long backwards, forwards,try;2654int backwards_lno, forwards_lno, try_lno;26552656/*2657 * If match_beginning or match_end is specified, there is no2658 * point starting from a wrong line that will never match and2659 * wander around and wait for a match at the specified end.2660 */2661if(match_beginning)2662 line =0;2663else if(match_end)2664 line = img->nr - preimage->nr;26652666/*2667 * Because the comparison is unsigned, the following test2668 * will also take care of a negative line number that can2669 * result when match_end and preimage is larger than the target.2670 */2671if((size_t) line > img->nr)2672 line = img->nr;26732674try=0;2675for(i =0; i < line; i++)2676try+= img->line[i].len;26772678/*2679 * There's probably some smart way to do this, but I'll leave2680 * that to the smart and beautiful people. I'm simple and stupid.2681 */2682 backwards =try;2683 backwards_lno = line;2684 forwards =try;2685 forwards_lno = line;2686 try_lno = line;26872688for(i =0; ; i++) {2689if(match_fragment(state, img, preimage, postimage,2690try, try_lno, ws_rule,2691 match_beginning, match_end))2692return try_lno;26932694 again:2695if(backwards_lno ==0&& forwards_lno == img->nr)2696break;26972698if(i &1) {2699if(backwards_lno ==0) {2700 i++;2701goto again;2702}2703 backwards_lno--;2704 backwards -= img->line[backwards_lno].len;2705try= backwards;2706 try_lno = backwards_lno;2707}else{2708if(forwards_lno == img->nr) {2709 i++;2710goto again;2711}2712 forwards += img->line[forwards_lno].len;2713 forwards_lno++;2714try= forwards;2715 try_lno = forwards_lno;2716}27172718}2719return-1;2720}27212722static voidremove_first_line(struct image *img)2723{2724 img->buf += img->line[0].len;2725 img->len -= img->line[0].len;2726 img->line++;2727 img->nr--;2728}27292730static voidremove_last_line(struct image *img)2731{2732 img->len -= img->line[--img->nr].len;2733}27342735/*2736 * The change from "preimage" and "postimage" has been found to2737 * apply at applied_pos (counts in line numbers) in "img".2738 * Update "img" to remove "preimage" and replace it with "postimage".2739 */2740static voidupdate_image(struct apply_state *state,2741struct image *img,2742int applied_pos,2743struct image *preimage,2744struct image *postimage)2745{2746/*2747 * remove the copy of preimage at offset in img2748 * and replace it with postimage2749 */2750int i, nr;2751size_t remove_count, insert_count, applied_at =0;2752char*result;2753int preimage_limit;27542755/*2756 * If we are removing blank lines at the end of img,2757 * the preimage may extend beyond the end.2758 * If that is the case, we must be careful only to2759 * remove the part of the preimage that falls within2760 * the boundaries of img. Initialize preimage_limit2761 * to the number of lines in the preimage that falls2762 * within the boundaries.2763 */2764 preimage_limit = preimage->nr;2765if(preimage_limit > img->nr - applied_pos)2766 preimage_limit = img->nr - applied_pos;27672768for(i =0; i < applied_pos; i++)2769 applied_at += img->line[i].len;27702771 remove_count =0;2772for(i =0; i < preimage_limit; i++)2773 remove_count += img->line[applied_pos + i].len;2774 insert_count = postimage->len;27752776/* Adjust the contents */2777 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2778memcpy(result, img->buf, applied_at);2779memcpy(result + applied_at, postimage->buf, postimage->len);2780memcpy(result + applied_at + postimage->len,2781 img->buf + (applied_at + remove_count),2782 img->len - (applied_at + remove_count));2783free(img->buf);2784 img->buf = result;2785 img->len += insert_count - remove_count;2786 result[img->len] ='\0';27872788/* Adjust the line table */2789 nr = img->nr + postimage->nr - preimage_limit;2790if(preimage_limit < postimage->nr) {2791/*2792 * NOTE: this knows that we never call remove_first_line()2793 * on anything other than pre/post image.2794 */2795REALLOC_ARRAY(img->line, nr);2796 img->line_allocated = img->line;2797}2798if(preimage_limit != postimage->nr)2799memmove(img->line + applied_pos + postimage->nr,2800 img->line + applied_pos + preimage_limit,2801(img->nr - (applied_pos + preimage_limit)) *2802sizeof(*img->line));2803memcpy(img->line + applied_pos,2804 postimage->line,2805 postimage->nr *sizeof(*img->line));2806if(!state->allow_overlap)2807for(i =0; i < postimage->nr; i++)2808 img->line[applied_pos + i].flag |= LINE_PATCHED;2809 img->nr = nr;2810}28112812/*2813 * Use the patch-hunk text in "frag" to prepare two images (preimage and2814 * postimage) for the hunk. Find lines that match "preimage" in "img" and2815 * replace the part of "img" with "postimage" text.2816 */2817static intapply_one_fragment(struct apply_state *state,2818struct image *img,struct fragment *frag,2819int inaccurate_eof,unsigned ws_rule,2820int nth_fragment)2821{2822int match_beginning, match_end;2823const char*patch = frag->patch;2824int size = frag->size;2825char*old, *oldlines;2826struct strbuf newlines;2827int new_blank_lines_at_end =0;2828int found_new_blank_lines_at_end =0;2829int hunk_linenr = frag->linenr;2830unsigned long leading, trailing;2831int pos, applied_pos;2832struct image preimage;2833struct image postimage;28342835memset(&preimage,0,sizeof(preimage));2836memset(&postimage,0,sizeof(postimage));2837 oldlines =xmalloc(size);2838strbuf_init(&newlines, size);28392840 old = oldlines;2841while(size >0) {2842char first;2843int len =linelen(patch, size);2844int plen;2845int added_blank_line =0;2846int is_blank_context =0;2847size_t start;28482849if(!len)2850break;28512852/*2853 * "plen" is how much of the line we should use for2854 * the actual patch data. Normally we just remove the2855 * first character on the line, but if the line is2856 * followed by "\ No newline", then we also remove the2857 * last one (which is the newline, of course).2858 */2859 plen = len -1;2860if(len < size && patch[len] =='\\')2861 plen--;2862 first = *patch;2863if(state->apply_in_reverse) {2864if(first =='-')2865 first ='+';2866else if(first =='+')2867 first ='-';2868}28692870switch(first) {2871case'\n':2872/* Newer GNU diff, empty context line */2873if(plen <0)2874/* ... followed by '\No newline'; nothing */2875break;2876*old++ ='\n';2877strbuf_addch(&newlines,'\n');2878add_line_info(&preimage,"\n",1, LINE_COMMON);2879add_line_info(&postimage,"\n",1, LINE_COMMON);2880 is_blank_context =1;2881break;2882case' ':2883if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2884ws_blank_line(patch +1, plen, ws_rule))2885 is_blank_context =1;2886case'-':2887memcpy(old, patch +1, plen);2888add_line_info(&preimage, old, plen,2889(first ==' '? LINE_COMMON :0));2890 old += plen;2891if(first =='-')2892break;2893/* Fall-through for ' ' */2894case'+':2895/* --no-add does not add new lines */2896if(first =='+'&& state->no_add)2897break;28982899 start = newlines.len;2900if(first !='+'||2901!state->whitespace_error ||2902 state->ws_error_action != correct_ws_error) {2903strbuf_add(&newlines, patch +1, plen);2904}2905else{2906ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2907}2908add_line_info(&postimage, newlines.buf + start, newlines.len - start,2909(first =='+'?0: LINE_COMMON));2910if(first =='+'&&2911(ws_rule & WS_BLANK_AT_EOF) &&2912ws_blank_line(patch +1, plen, ws_rule))2913 added_blank_line =1;2914break;2915case'@':case'\\':2916/* Ignore it, we already handled it */2917break;2918default:2919if(state->apply_verbosity > verbosity_normal)2920error(_("invalid start of line: '%c'"), first);2921 applied_pos = -1;2922goto out;2923}2924if(added_blank_line) {2925if(!new_blank_lines_at_end)2926 found_new_blank_lines_at_end = hunk_linenr;2927 new_blank_lines_at_end++;2928}2929else if(is_blank_context)2930;2931else2932 new_blank_lines_at_end =0;2933 patch += len;2934 size -= len;2935 hunk_linenr++;2936}2937if(inaccurate_eof &&2938 old > oldlines && old[-1] =='\n'&&2939 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2940 old--;2941strbuf_setlen(&newlines, newlines.len -1);2942}29432944 leading = frag->leading;2945 trailing = frag->trailing;29462947/*2948 * A hunk to change lines at the beginning would begin with2949 * @@ -1,L +N,M @@2950 * but we need to be careful. -U0 that inserts before the second2951 * line also has this pattern.2952 *2953 * And a hunk to add to an empty file would begin with2954 * @@ -0,0 +N,M @@2955 *2956 * In other words, a hunk that is (frag->oldpos <= 1) with or2957 * without leading context must match at the beginning.2958 */2959 match_beginning = (!frag->oldpos ||2960(frag->oldpos ==1&& !state->unidiff_zero));29612962/*2963 * A hunk without trailing lines must match at the end.2964 * However, we simply cannot tell if a hunk must match end2965 * from the lack of trailing lines if the patch was generated2966 * with unidiff without any context.2967 */2968 match_end = !state->unidiff_zero && !trailing;29692970 pos = frag->newpos ? (frag->newpos -1) :0;2971 preimage.buf = oldlines;2972 preimage.len = old - oldlines;2973 postimage.buf = newlines.buf;2974 postimage.len = newlines.len;2975 preimage.line = preimage.line_allocated;2976 postimage.line = postimage.line_allocated;29772978for(;;) {29792980 applied_pos =find_pos(state, img, &preimage, &postimage, pos,2981 ws_rule, match_beginning, match_end);29822983if(applied_pos >=0)2984break;29852986/* Am I at my context limits? */2987if((leading <= state->p_context) && (trailing <= state->p_context))2988break;2989if(match_beginning || match_end) {2990 match_beginning = match_end =0;2991continue;2992}29932994/*2995 * Reduce the number of context lines; reduce both2996 * leading and trailing if they are equal otherwise2997 * just reduce the larger context.2998 */2999if(leading >= trailing) {3000remove_first_line(&preimage);3001remove_first_line(&postimage);3002 pos--;3003 leading--;3004}3005if(trailing > leading) {3006remove_last_line(&preimage);3007remove_last_line(&postimage);3008 trailing--;3009}3010}30113012if(applied_pos >=0) {3013if(new_blank_lines_at_end &&3014 preimage.nr + applied_pos >= img->nr &&3015(ws_rule & WS_BLANK_AT_EOF) &&3016 state->ws_error_action != nowarn_ws_error) {3017record_ws_error(state, WS_BLANK_AT_EOF,"+",1,3018 found_new_blank_lines_at_end);3019if(state->ws_error_action == correct_ws_error) {3020while(new_blank_lines_at_end--)3021remove_last_line(&postimage);3022}3023/*3024 * We would want to prevent write_out_results()3025 * from taking place in apply_patch() that follows3026 * the callchain led us here, which is:3027 * apply_patch->check_patch_list->check_patch->3028 * apply_data->apply_fragments->apply_one_fragment3029 */3030if(state->ws_error_action == die_on_ws_error)3031 state->apply =0;3032}30333034if(state->apply_verbosity > verbosity_normal && applied_pos != pos) {3035int offset = applied_pos - pos;3036if(state->apply_in_reverse)3037 offset =0- offset;3038fprintf_ln(stderr,3039Q_("Hunk #%dsucceeded at%d(offset%dline).",3040"Hunk #%dsucceeded at%d(offset%dlines).",3041 offset),3042 nth_fragment, applied_pos +1, offset);3043}30443045/*3046 * Warn if it was necessary to reduce the number3047 * of context lines.3048 */3049if((leading != frag->leading ||3050 trailing != frag->trailing) && state->apply_verbosity > verbosity_silent)3051fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"3052" to apply fragment at%d"),3053 leading, trailing, applied_pos+1);3054update_image(state, img, applied_pos, &preimage, &postimage);3055}else{3056if(state->apply_verbosity > verbosity_normal)3057error(_("while searching for:\n%.*s"),3058(int)(old - oldlines), oldlines);3059}30603061out:3062free(oldlines);3063strbuf_release(&newlines);3064free(preimage.line_allocated);3065free(postimage.line_allocated);30663067return(applied_pos <0);3068}30693070static intapply_binary_fragment(struct apply_state *state,3071struct image *img,3072struct patch *patch)3073{3074struct fragment *fragment = patch->fragments;3075unsigned long len;3076void*dst;30773078if(!fragment)3079returnerror(_("missing binary patch data for '%s'"),3080 patch->new_name ?3081 patch->new_name :3082 patch->old_name);30833084/* Binary patch is irreversible without the optional second hunk */3085if(state->apply_in_reverse) {3086if(!fragment->next)3087returnerror(_("cannot reverse-apply a binary patch "3088"without the reverse hunk to '%s'"),3089 patch->new_name3090? patch->new_name : patch->old_name);3091 fragment = fragment->next;3092}3093switch(fragment->binary_patch_method) {3094case BINARY_DELTA_DEFLATED:3095 dst =patch_delta(img->buf, img->len, fragment->patch,3096 fragment->size, &len);3097if(!dst)3098return-1;3099clear_image(img);3100 img->buf = dst;3101 img->len = len;3102return0;3103case BINARY_LITERAL_DEFLATED:3104clear_image(img);3105 img->len = fragment->size;3106 img->buf =xmemdupz(fragment->patch, img->len);3107return0;3108}3109return-1;3110}31113112/*3113 * Replace "img" with the result of applying the binary patch.3114 * The binary patch data itself in patch->fragment is still kept3115 * but the preimage prepared by the caller in "img" is freed here3116 * or in the helper function apply_binary_fragment() this calls.3117 */3118static intapply_binary(struct apply_state *state,3119struct image *img,3120struct patch *patch)3121{3122const char*name = patch->old_name ? patch->old_name : patch->new_name;3123struct object_id oid;31243125/*3126 * For safety, we require patch index line to contain3127 * full 40-byte textual SHA1 for old and new, at least for now.3128 */3129if(strlen(patch->old_sha1_prefix) !=40||3130strlen(patch->new_sha1_prefix) !=40||3131get_oid_hex(patch->old_sha1_prefix, &oid) ||3132get_oid_hex(patch->new_sha1_prefix, &oid))3133returnerror(_("cannot apply binary patch to '%s' "3134"without full index line"), name);31353136if(patch->old_name) {3137/*3138 * See if the old one matches what the patch3139 * applies to.3140 */3141hash_sha1_file(img->buf, img->len, blob_type, oid.hash);3142if(strcmp(oid_to_hex(&oid), patch->old_sha1_prefix))3143returnerror(_("the patch applies to '%s' (%s), "3144"which does not match the "3145"current contents."),3146 name,oid_to_hex(&oid));3147}3148else{3149/* Otherwise, the old one must be empty. */3150if(img->len)3151returnerror(_("the patch applies to an empty "3152"'%s' but it is not empty"), name);3153}31543155get_oid_hex(patch->new_sha1_prefix, &oid);3156if(is_null_oid(&oid)) {3157clear_image(img);3158return0;/* deletion patch */3159}31603161if(has_sha1_file(oid.hash)) {3162/* We already have the postimage */3163enum object_type type;3164unsigned long size;3165char*result;31663167 result =read_sha1_file(oid.hash, &type, &size);3168if(!result)3169returnerror(_("the necessary postimage%sfor "3170"'%s' cannot be read"),3171 patch->new_sha1_prefix, name);3172clear_image(img);3173 img->buf = result;3174 img->len = size;3175}else{3176/*3177 * We have verified buf matches the preimage;3178 * apply the patch data to it, which is stored3179 * in the patch->fragments->{patch,size}.3180 */3181if(apply_binary_fragment(state, img, patch))3182returnerror(_("binary patch does not apply to '%s'"),3183 name);31843185/* verify that the result matches */3186hash_sha1_file(img->buf, img->len, blob_type, oid.hash);3187if(strcmp(oid_to_hex(&oid), patch->new_sha1_prefix))3188returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3189 name, patch->new_sha1_prefix,oid_to_hex(&oid));3190}31913192return0;3193}31943195static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3196{3197struct fragment *frag = patch->fragments;3198const char*name = patch->old_name ? patch->old_name : patch->new_name;3199unsigned ws_rule = patch->ws_rule;3200unsigned inaccurate_eof = patch->inaccurate_eof;3201int nth =0;32023203if(patch->is_binary)3204returnapply_binary(state, img, patch);32053206while(frag) {3207 nth++;3208if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3209error(_("patch failed:%s:%ld"), name, frag->oldpos);3210if(!state->apply_with_reject)3211return-1;3212 frag->rejected =1;3213}3214 frag = frag->next;3215}3216return0;3217}32183219static intread_blob_object(struct strbuf *buf,const struct object_id *oid,unsigned mode)3220{3221if(S_ISGITLINK(mode)) {3222strbuf_grow(buf,100);3223strbuf_addf(buf,"Subproject commit%s\n",oid_to_hex(oid));3224}else{3225enum object_type type;3226unsigned long sz;3227char*result;32283229 result =read_sha1_file(oid->hash, &type, &sz);3230if(!result)3231return-1;3232/* XXX read_sha1_file NUL-terminates */3233strbuf_attach(buf, result, sz, sz +1);3234}3235return0;3236}32373238static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3239{3240if(!ce)3241return0;3242returnread_blob_object(buf, &ce->oid, ce->ce_mode);3243}32443245static struct patch *in_fn_table(struct apply_state *state,const char*name)3246{3247struct string_list_item *item;32483249if(name == NULL)3250return NULL;32513252 item =string_list_lookup(&state->fn_table, name);3253if(item != NULL)3254return(struct patch *)item->util;32553256return NULL;3257}32583259/*3260 * item->util in the filename table records the status of the path.3261 * Usually it points at a patch (whose result records the contents3262 * of it after applying it), but it could be PATH_WAS_DELETED for a3263 * path that a previously applied patch has already removed, or3264 * PATH_TO_BE_DELETED for a path that a later patch would remove.3265 *3266 * The latter is needed to deal with a case where two paths A and B3267 * are swapped by first renaming A to B and then renaming B to A;3268 * moving A to B should not be prevented due to presence of B as we3269 * will remove it in a later patch.3270 */3271#define PATH_TO_BE_DELETED ((struct patch *) -2)3272#define PATH_WAS_DELETED ((struct patch *) -1)32733274static intto_be_deleted(struct patch *patch)3275{3276return patch == PATH_TO_BE_DELETED;3277}32783279static intwas_deleted(struct patch *patch)3280{3281return patch == PATH_WAS_DELETED;3282}32833284static voidadd_to_fn_table(struct apply_state *state,struct patch *patch)3285{3286struct string_list_item *item;32873288/*3289 * Always add new_name unless patch is a deletion3290 * This should cover the cases for normal diffs,3291 * file creations and copies3292 */3293if(patch->new_name != NULL) {3294 item =string_list_insert(&state->fn_table, patch->new_name);3295 item->util = patch;3296}32973298/*3299 * store a failure on rename/deletion cases because3300 * later chunks shouldn't patch old names3301 */3302if((patch->new_name == NULL) || (patch->is_rename)) {3303 item =string_list_insert(&state->fn_table, patch->old_name);3304 item->util = PATH_WAS_DELETED;3305}3306}33073308static voidprepare_fn_table(struct apply_state *state,struct patch *patch)3309{3310/*3311 * store information about incoming file deletion3312 */3313while(patch) {3314if((patch->new_name == NULL) || (patch->is_rename)) {3315struct string_list_item *item;3316 item =string_list_insert(&state->fn_table, patch->old_name);3317 item->util = PATH_TO_BE_DELETED;3318}3319 patch = patch->next;3320}3321}33223323static intcheckout_target(struct index_state *istate,3324struct cache_entry *ce,struct stat *st)3325{3326struct checkout costate = CHECKOUT_INIT;33273328 costate.refresh_cache =1;3329 costate.istate = istate;3330if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3331returnerror(_("cannot checkout%s"), ce->name);3332return0;3333}33343335static struct patch *previous_patch(struct apply_state *state,3336struct patch *patch,3337int*gone)3338{3339struct patch *previous;33403341*gone =0;3342if(patch->is_copy || patch->is_rename)3343return NULL;/* "git" patches do not depend on the order */33443345 previous =in_fn_table(state, patch->old_name);3346if(!previous)3347return NULL;33483349if(to_be_deleted(previous))3350return NULL;/* the deletion hasn't happened yet */33513352if(was_deleted(previous))3353*gone =1;33543355return previous;3356}33573358static intverify_index_match(const struct cache_entry *ce,struct stat *st)3359{3360if(S_ISGITLINK(ce->ce_mode)) {3361if(!S_ISDIR(st->st_mode))3362return-1;3363return0;3364}3365returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3366}33673368#define SUBMODULE_PATCH_WITHOUT_INDEX 133693370static intload_patch_target(struct apply_state *state,3371struct strbuf *buf,3372const struct cache_entry *ce,3373struct stat *st,3374const char*name,3375unsigned expected_mode)3376{3377if(state->cached || state->check_index) {3378if(read_file_or_gitlink(ce, buf))3379returnerror(_("failed to read%s"), name);3380}else if(name) {3381if(S_ISGITLINK(expected_mode)) {3382if(ce)3383returnread_file_or_gitlink(ce, buf);3384else3385return SUBMODULE_PATCH_WITHOUT_INDEX;3386}else if(has_symlink_leading_path(name,strlen(name))) {3387returnerror(_("reading from '%s' beyond a symbolic link"), name);3388}else{3389if(read_old_data(st, name, buf))3390returnerror(_("failed to read%s"), name);3391}3392}3393return0;3394}33953396/*3397 * We are about to apply "patch"; populate the "image" with the3398 * current version we have, from the working tree or from the index,3399 * depending on the situation e.g. --cached/--index. If we are3400 * applying a non-git patch that incrementally updates the tree,3401 * we read from the result of a previous diff.3402 */3403static intload_preimage(struct apply_state *state,3404struct image *image,3405struct patch *patch,struct stat *st,3406const struct cache_entry *ce)3407{3408struct strbuf buf = STRBUF_INIT;3409size_t len;3410char*img;3411struct patch *previous;3412int status;34133414 previous =previous_patch(state, patch, &status);3415if(status)3416returnerror(_("path%shas been renamed/deleted"),3417 patch->old_name);3418if(previous) {3419/* We have a patched copy in memory; use that. */3420strbuf_add(&buf, previous->result, previous->resultsize);3421}else{3422 status =load_patch_target(state, &buf, ce, st,3423 patch->old_name, patch->old_mode);3424if(status <0)3425return status;3426else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3427/*3428 * There is no way to apply subproject3429 * patch without looking at the index.3430 * NEEDSWORK: shouldn't this be flagged3431 * as an error???3432 */3433free_fragment_list(patch->fragments);3434 patch->fragments = NULL;3435}else if(status) {3436returnerror(_("failed to read%s"), patch->old_name);3437}3438}34393440 img =strbuf_detach(&buf, &len);3441prepare_image(image, img, len, !patch->is_binary);3442return0;3443}34443445static intthree_way_merge(struct image *image,3446char*path,3447const struct object_id *base,3448const struct object_id *ours,3449const struct object_id *theirs)3450{3451 mmfile_t base_file, our_file, their_file;3452 mmbuffer_t result = { NULL };3453int status;34543455read_mmblob(&base_file, base);3456read_mmblob(&our_file, ours);3457read_mmblob(&their_file, theirs);3458 status =ll_merge(&result, path,3459&base_file,"base",3460&our_file,"ours",3461&their_file,"theirs", NULL);3462free(base_file.ptr);3463free(our_file.ptr);3464free(their_file.ptr);3465if(status <0|| !result.ptr) {3466free(result.ptr);3467return-1;3468}3469clear_image(image);3470 image->buf = result.ptr;3471 image->len = result.size;34723473return status;3474}34753476/*3477 * When directly falling back to add/add three-way merge, we read from3478 * the current contents of the new_name. In no cases other than that3479 * this function will be called.3480 */3481static intload_current(struct apply_state *state,3482struct image *image,3483struct patch *patch)3484{3485struct strbuf buf = STRBUF_INIT;3486int status, pos;3487size_t len;3488char*img;3489struct stat st;3490struct cache_entry *ce;3491char*name = patch->new_name;3492unsigned mode = patch->new_mode;34933494if(!patch->is_new)3495die("BUG: patch to%sis not a creation", patch->old_name);34963497 pos =cache_name_pos(name,strlen(name));3498if(pos <0)3499returnerror(_("%s: does not exist in index"), name);3500 ce = active_cache[pos];3501if(lstat(name, &st)) {3502if(errno != ENOENT)3503returnerror_errno("%s", name);3504if(checkout_target(&the_index, ce, &st))3505return-1;3506}3507if(verify_index_match(ce, &st))3508returnerror(_("%s: does not match index"), name);35093510 status =load_patch_target(state, &buf, ce, &st, name, mode);3511if(status <0)3512return status;3513else if(status)3514return-1;3515 img =strbuf_detach(&buf, &len);3516prepare_image(image, img, len, !patch->is_binary);3517return0;3518}35193520static inttry_threeway(struct apply_state *state,3521struct image *image,3522struct patch *patch,3523struct stat *st,3524const struct cache_entry *ce)3525{3526struct object_id pre_oid, post_oid, our_oid;3527struct strbuf buf = STRBUF_INIT;3528size_t len;3529int status;3530char*img;3531struct image tmp_image;35323533/* No point falling back to 3-way merge in these cases */3534if(patch->is_delete ||3535S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3536return-1;35373538/* Preimage the patch was prepared for */3539if(patch->is_new)3540write_sha1_file("",0, blob_type, pre_oid.hash);3541else if(get_sha1(patch->old_sha1_prefix, pre_oid.hash) ||3542read_blob_object(&buf, &pre_oid, patch->old_mode))3543returnerror(_("repository lacks the necessary blob to fall back on 3-way merge."));35443545if(state->apply_verbosity > verbosity_silent)3546fprintf(stderr,_("Falling back to three-way merge...\n"));35473548 img =strbuf_detach(&buf, &len);3549prepare_image(&tmp_image, img, len,1);3550/* Apply the patch to get the post image */3551if(apply_fragments(state, &tmp_image, patch) <0) {3552clear_image(&tmp_image);3553return-1;3554}3555/* post_oid is theirs */3556write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_oid.hash);3557clear_image(&tmp_image);35583559/* our_oid is ours */3560if(patch->is_new) {3561if(load_current(state, &tmp_image, patch))3562returnerror(_("cannot read the current contents of '%s'"),3563 patch->new_name);3564}else{3565if(load_preimage(state, &tmp_image, patch, st, ce))3566returnerror(_("cannot read the current contents of '%s'"),3567 patch->old_name);3568}3569write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_oid.hash);3570clear_image(&tmp_image);35713572/* in-core three-way merge between post and our using pre as base */3573 status =three_way_merge(image, patch->new_name,3574&pre_oid, &our_oid, &post_oid);3575if(status <0) {3576if(state->apply_verbosity > verbosity_silent)3577fprintf(stderr,3578_("Failed to fall back on three-way merge...\n"));3579return status;3580}35813582if(status) {3583 patch->conflicted_threeway =1;3584if(patch->is_new)3585oidclr(&patch->threeway_stage[0]);3586else3587oidcpy(&patch->threeway_stage[0], &pre_oid);3588oidcpy(&patch->threeway_stage[1], &our_oid);3589oidcpy(&patch->threeway_stage[2], &post_oid);3590if(state->apply_verbosity > verbosity_silent)3591fprintf(stderr,3592_("Applied patch to '%s' with conflicts.\n"),3593 patch->new_name);3594}else{3595if(state->apply_verbosity > verbosity_silent)3596fprintf(stderr,3597_("Applied patch to '%s' cleanly.\n"),3598 patch->new_name);3599}3600return0;3601}36023603static intapply_data(struct apply_state *state,struct patch *patch,3604struct stat *st,const struct cache_entry *ce)3605{3606struct image image;36073608if(load_preimage(state, &image, patch, st, ce) <0)3609return-1;36103611if(patch->direct_to_threeway ||3612apply_fragments(state, &image, patch) <0) {3613/* Note: with --reject, apply_fragments() returns 0 */3614if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3615return-1;3616}3617 patch->result = image.buf;3618 patch->resultsize = image.len;3619add_to_fn_table(state, patch);3620free(image.line_allocated);36213622if(0< patch->is_delete && patch->resultsize)3623returnerror(_("removal patch leaves file contents"));36243625return0;3626}36273628/*3629 * If "patch" that we are looking at modifies or deletes what we have,3630 * we would want it not to lose any local modification we have, either3631 * in the working tree or in the index.3632 *3633 * This also decides if a non-git patch is a creation patch or a3634 * modification to an existing empty file. We do not check the state3635 * of the current tree for a creation patch in this function; the caller3636 * check_patch() separately makes sure (and errors out otherwise) that3637 * the path the patch creates does not exist in the current tree.3638 */3639static intcheck_preimage(struct apply_state *state,3640struct patch *patch,3641struct cache_entry **ce,3642struct stat *st)3643{3644const char*old_name = patch->old_name;3645struct patch *previous = NULL;3646int stat_ret =0, status;3647unsigned st_mode =0;36483649if(!old_name)3650return0;36513652assert(patch->is_new <=0);3653 previous =previous_patch(state, patch, &status);36543655if(status)3656returnerror(_("path%shas been renamed/deleted"), old_name);3657if(previous) {3658 st_mode = previous->new_mode;3659}else if(!state->cached) {3660 stat_ret =lstat(old_name, st);3661if(stat_ret && errno != ENOENT)3662returnerror_errno("%s", old_name);3663}36643665if(state->check_index && !previous) {3666int pos =cache_name_pos(old_name,strlen(old_name));3667if(pos <0) {3668if(patch->is_new <0)3669goto is_new;3670returnerror(_("%s: does not exist in index"), old_name);3671}3672*ce = active_cache[pos];3673if(stat_ret <0) {3674if(checkout_target(&the_index, *ce, st))3675return-1;3676}3677if(!state->cached &&verify_index_match(*ce, st))3678returnerror(_("%s: does not match index"), old_name);3679if(state->cached)3680 st_mode = (*ce)->ce_mode;3681}else if(stat_ret <0) {3682if(patch->is_new <0)3683goto is_new;3684returnerror_errno("%s", old_name);3685}36863687if(!state->cached && !previous)3688 st_mode =ce_mode_from_stat(*ce, st->st_mode);36893690if(patch->is_new <0)3691 patch->is_new =0;3692if(!patch->old_mode)3693 patch->old_mode = st_mode;3694if((st_mode ^ patch->old_mode) & S_IFMT)3695returnerror(_("%s: wrong type"), old_name);3696if(st_mode != patch->old_mode)3697warning(_("%shas type%o, expected%o"),3698 old_name, st_mode, patch->old_mode);3699if(!patch->new_mode && !patch->is_delete)3700 patch->new_mode = st_mode;3701return0;37023703 is_new:3704 patch->is_new =1;3705 patch->is_delete =0;3706free(patch->old_name);3707 patch->old_name = NULL;3708return0;3709}371037113712#define EXISTS_IN_INDEX 13713#define EXISTS_IN_WORKTREE 237143715static intcheck_to_create(struct apply_state *state,3716const char*new_name,3717int ok_if_exists)3718{3719struct stat nst;37203721if(state->check_index &&3722cache_name_pos(new_name,strlen(new_name)) >=0&&3723!ok_if_exists)3724return EXISTS_IN_INDEX;3725if(state->cached)3726return0;37273728if(!lstat(new_name, &nst)) {3729if(S_ISDIR(nst.st_mode) || ok_if_exists)3730return0;3731/*3732 * A leading component of new_name might be a symlink3733 * that is going to be removed with this patch, but3734 * still pointing at somewhere that has the path.3735 * In such a case, path "new_name" does not exist as3736 * far as git is concerned.3737 */3738if(has_symlink_leading_path(new_name,strlen(new_name)))3739return0;37403741return EXISTS_IN_WORKTREE;3742}else if((errno != ENOENT) && (errno != ENOTDIR)) {3743returnerror_errno("%s", new_name);3744}3745return0;3746}37473748static uintptr_tregister_symlink_changes(struct apply_state *state,3749const char*path,3750uintptr_t what)3751{3752struct string_list_item *ent;37533754 ent =string_list_lookup(&state->symlink_changes, path);3755if(!ent) {3756 ent =string_list_insert(&state->symlink_changes, path);3757 ent->util = (void*)0;3758}3759 ent->util = (void*)(what | ((uintptr_t)ent->util));3760return(uintptr_t)ent->util;3761}37623763static uintptr_tcheck_symlink_changes(struct apply_state *state,const char*path)3764{3765struct string_list_item *ent;37663767 ent =string_list_lookup(&state->symlink_changes, path);3768if(!ent)3769return0;3770return(uintptr_t)ent->util;3771}37723773static voidprepare_symlink_changes(struct apply_state *state,struct patch *patch)3774{3775for( ; patch; patch = patch->next) {3776if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3777(patch->is_rename || patch->is_delete))3778/* the symlink at patch->old_name is removed */3779register_symlink_changes(state, patch->old_name, APPLY_SYMLINK_GOES_AWAY);37803781if(patch->new_name &&S_ISLNK(patch->new_mode))3782/* the symlink at patch->new_name is created or remains */3783register_symlink_changes(state, patch->new_name, APPLY_SYMLINK_IN_RESULT);3784}3785}37863787static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3788{3789do{3790unsigned int change;37913792while(--name->len && name->buf[name->len] !='/')3793;/* scan backwards */3794if(!name->len)3795break;3796 name->buf[name->len] ='\0';3797 change =check_symlink_changes(state, name->buf);3798if(change & APPLY_SYMLINK_IN_RESULT)3799return1;3800if(change & APPLY_SYMLINK_GOES_AWAY)3801/*3802 * This cannot be "return 0", because we may3803 * see a new one created at a higher level.3804 */3805continue;38063807/* otherwise, check the preimage */3808if(state->check_index) {3809struct cache_entry *ce;38103811 ce =cache_file_exists(name->buf, name->len, ignore_case);3812if(ce &&S_ISLNK(ce->ce_mode))3813return1;3814}else{3815struct stat st;3816if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3817return1;3818}3819}while(1);3820return0;3821}38223823static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3824{3825int ret;3826struct strbuf name = STRBUF_INIT;38273828assert(*name_ !='\0');3829strbuf_addstr(&name, name_);3830 ret =path_is_beyond_symlink_1(state, &name);3831strbuf_release(&name);38323833return ret;3834}38353836static intcheck_unsafe_path(struct patch *patch)3837{3838const char*old_name = NULL;3839const char*new_name = NULL;3840if(patch->is_delete)3841 old_name = patch->old_name;3842else if(!patch->is_new && !patch->is_copy)3843 old_name = patch->old_name;3844if(!patch->is_delete)3845 new_name = patch->new_name;38463847if(old_name && !verify_path(old_name))3848returnerror(_("invalid path '%s'"), old_name);3849if(new_name && !verify_path(new_name))3850returnerror(_("invalid path '%s'"), new_name);3851return0;3852}38533854/*3855 * Check and apply the patch in-core; leave the result in patch->result3856 * for the caller to write it out to the final destination.3857 */3858static intcheck_patch(struct apply_state *state,struct patch *patch)3859{3860struct stat st;3861const char*old_name = patch->old_name;3862const char*new_name = patch->new_name;3863const char*name = old_name ? old_name : new_name;3864struct cache_entry *ce = NULL;3865struct patch *tpatch;3866int ok_if_exists;3867int status;38683869 patch->rejected =1;/* we will drop this after we succeed */38703871 status =check_preimage(state, patch, &ce, &st);3872if(status)3873return status;3874 old_name = patch->old_name;38753876/*3877 * A type-change diff is always split into a patch to delete3878 * old, immediately followed by a patch to create new (see3879 * diff.c::run_diff()); in such a case it is Ok that the entry3880 * to be deleted by the previous patch is still in the working3881 * tree and in the index.3882 *3883 * A patch to swap-rename between A and B would first rename A3884 * to B and then rename B to A. While applying the first one,3885 * the presence of B should not stop A from getting renamed to3886 * B; ask to_be_deleted() about the later rename. Removal of3887 * B and rename from A to B is handled the same way by asking3888 * was_deleted().3889 */3890if((tpatch =in_fn_table(state, new_name)) &&3891(was_deleted(tpatch) ||to_be_deleted(tpatch)))3892 ok_if_exists =1;3893else3894 ok_if_exists =0;38953896if(new_name &&3897((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3898int err =check_to_create(state, new_name, ok_if_exists);38993900if(err && state->threeway) {3901 patch->direct_to_threeway =1;3902}else switch(err) {3903case0:3904break;/* happy */3905case EXISTS_IN_INDEX:3906returnerror(_("%s: already exists in index"), new_name);3907break;3908case EXISTS_IN_WORKTREE:3909returnerror(_("%s: already exists in working directory"),3910 new_name);3911default:3912return err;3913}39143915if(!patch->new_mode) {3916if(0< patch->is_new)3917 patch->new_mode = S_IFREG |0644;3918else3919 patch->new_mode = patch->old_mode;3920}3921}39223923if(new_name && old_name) {3924int same = !strcmp(old_name, new_name);3925if(!patch->new_mode)3926 patch->new_mode = patch->old_mode;3927if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3928if(same)3929returnerror(_("new mode (%o) of%sdoes not "3930"match old mode (%o)"),3931 patch->new_mode, new_name,3932 patch->old_mode);3933else3934returnerror(_("new mode (%o) of%sdoes not "3935"match old mode (%o) of%s"),3936 patch->new_mode, new_name,3937 patch->old_mode, old_name);3938}3939}39403941if(!state->unsafe_paths &&check_unsafe_path(patch))3942return-128;39433944/*3945 * An attempt to read from or delete a path that is beyond a3946 * symbolic link will be prevented by load_patch_target() that3947 * is called at the beginning of apply_data() so we do not3948 * have to worry about a patch marked with "is_delete" bit3949 * here. We however need to make sure that the patch result3950 * is not deposited to a path that is beyond a symbolic link3951 * here.3952 */3953if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3954returnerror(_("affected file '%s' is beyond a symbolic link"),3955 patch->new_name);39563957if(apply_data(state, patch, &st, ce) <0)3958returnerror(_("%s: patch does not apply"), name);3959 patch->rejected =0;3960return0;3961}39623963static intcheck_patch_list(struct apply_state *state,struct patch *patch)3964{3965int err =0;39663967prepare_symlink_changes(state, patch);3968prepare_fn_table(state, patch);3969while(patch) {3970int res;3971if(state->apply_verbosity > verbosity_normal)3972say_patch_name(stderr,3973_("Checking patch%s..."), patch);3974 res =check_patch(state, patch);3975if(res == -128)3976return-128;3977 err |= res;3978 patch = patch->next;3979}3980return err;3981}39823983static intread_apply_cache(struct apply_state *state)3984{3985if(state->index_file)3986returnread_cache_from(state->index_file);3987else3988returnread_cache();3989}39903991/* This function tries to read the object name from the current index */3992static intget_current_oid(struct apply_state *state,const char*path,3993struct object_id *oid)3994{3995int pos;39963997if(read_apply_cache(state) <0)3998return-1;3999 pos =cache_name_pos(path,strlen(path));4000if(pos <0)4001return-1;4002oidcpy(oid, &active_cache[pos]->oid);4003return0;4004}40054006static intpreimage_oid_in_gitlink_patch(struct patch *p,struct object_id *oid)4007{4008/*4009 * A usable gitlink patch has only one fragment (hunk) that looks like:4010 * @@ -1 +1 @@4011 * -Subproject commit <old sha1>4012 * +Subproject commit <new sha1>4013 * or4014 * @@ -1 +0,0 @@4015 * -Subproject commit <old sha1>4016 * for a removal patch.4017 */4018struct fragment *hunk = p->fragments;4019static const char heading[] ="-Subproject commit ";4020char*preimage;40214022if(/* does the patch have only one hunk? */4023 hunk && !hunk->next &&4024/* is its preimage one line? */4025 hunk->oldpos ==1&& hunk->oldlines ==1&&4026/* does preimage begin with the heading? */4027(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&4028starts_with(++preimage, heading) &&4029/* does it record full SHA-1? */4030!get_oid_hex(preimage +sizeof(heading) -1, oid) &&4031 preimage[sizeof(heading) + GIT_SHA1_HEXSZ -1] =='\n'&&4032/* does the abbreviated name on the index line agree with it? */4033starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))4034return0;/* it all looks fine */40354036/* we may have full object name on the index line */4037returnget_oid_hex(p->old_sha1_prefix, oid);4038}40394040/* Build an index that contains the just the files needed for a 3way merge */4041static intbuild_fake_ancestor(struct apply_state *state,struct patch *list)4042{4043struct patch *patch;4044struct index_state result = { NULL };4045static struct lock_file lock;4046int res;40474048/* Once we start supporting the reverse patch, it may be4049 * worth showing the new sha1 prefix, but until then...4050 */4051for(patch = list; patch; patch = patch->next) {4052struct object_id oid;4053struct cache_entry *ce;4054const char*name;40554056 name = patch->old_name ? patch->old_name : patch->new_name;4057if(0< patch->is_new)4058continue;40594060if(S_ISGITLINK(patch->old_mode)) {4061if(!preimage_oid_in_gitlink_patch(patch, &oid))4062;/* ok, the textual part looks sane */4063else4064returnerror(_("sha1 information is lacking or "4065"useless for submodule%s"), name);4066}else if(!get_sha1_blob(patch->old_sha1_prefix, oid.hash)) {4067;/* ok */4068}else if(!patch->lines_added && !patch->lines_deleted) {4069/* mode-only change: update the current */4070if(get_current_oid(state, patch->old_name, &oid))4071returnerror(_("mode change for%s, which is not "4072"in current HEAD"), name);4073}else4074returnerror(_("sha1 information is lacking or useless "4075"(%s)."), name);40764077 ce =make_cache_entry(patch->old_mode, oid.hash, name,0,0);4078if(!ce)4079returnerror(_("make_cache_entry failed for path '%s'"),4080 name);4081if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) {4082free(ce);4083returnerror(_("could not add%sto temporary index"),4084 name);4085}4086}40874088hold_lock_file_for_update(&lock, state->fake_ancestor, LOCK_DIE_ON_ERROR);4089 res =write_locked_index(&result, &lock, COMMIT_LOCK);4090discard_index(&result);40914092if(res)4093returnerror(_("could not write temporary index to%s"),4094 state->fake_ancestor);40954096return0;4097}40984099static voidstat_patch_list(struct apply_state *state,struct patch *patch)4100{4101int files, adds, dels;41024103for(files = adds = dels =0; patch ; patch = patch->next) {4104 files++;4105 adds += patch->lines_added;4106 dels += patch->lines_deleted;4107show_stats(state, patch);4108}41094110print_stat_summary(stdout, files, adds, dels);4111}41124113static voidnumstat_patch_list(struct apply_state *state,4114struct patch *patch)4115{4116for( ; patch; patch = patch->next) {4117const char*name;4118 name = patch->new_name ? patch->new_name : patch->old_name;4119if(patch->is_binary)4120printf("-\t-\t");4121else4122printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4123write_name_quoted(name, stdout, state->line_termination);4124}4125}41264127static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4128{4129if(mode)4130printf("%smode%06o%s\n", newdelete, mode, name);4131else4132printf("%s %s\n", newdelete, name);4133}41344135static voidshow_mode_change(struct patch *p,int show_name)4136{4137if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4138if(show_name)4139printf(" mode change%06o =>%06o%s\n",4140 p->old_mode, p->new_mode, p->new_name);4141else4142printf(" mode change%06o =>%06o\n",4143 p->old_mode, p->new_mode);4144}4145}41464147static voidshow_rename_copy(struct patch *p)4148{4149const char*renamecopy = p->is_rename ?"rename":"copy";4150const char*old, *new;41514152/* Find common prefix */4153 old = p->old_name;4154new= p->new_name;4155while(1) {4156const char*slash_old, *slash_new;4157 slash_old =strchr(old,'/');4158 slash_new =strchr(new,'/');4159if(!slash_old ||4160!slash_new ||4161 slash_old - old != slash_new -new||4162memcmp(old,new, slash_new -new))4163break;4164 old = slash_old +1;4165new= slash_new +1;4166}4167/* p->old_name thru old is the common prefix, and old and new4168 * through the end of names are renames4169 */4170if(old != p->old_name)4171printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4172(int)(old - p->old_name), p->old_name,4173 old,new, p->score);4174else4175printf("%s %s=>%s(%d%%)\n", renamecopy,4176 p->old_name, p->new_name, p->score);4177show_mode_change(p,0);4178}41794180static voidsummary_patch_list(struct patch *patch)4181{4182struct patch *p;41834184for(p = patch; p; p = p->next) {4185if(p->is_new)4186show_file_mode_name("create", p->new_mode, p->new_name);4187else if(p->is_delete)4188show_file_mode_name("delete", p->old_mode, p->old_name);4189else{4190if(p->is_rename || p->is_copy)4191show_rename_copy(p);4192else{4193if(p->score) {4194printf(" rewrite%s(%d%%)\n",4195 p->new_name, p->score);4196show_mode_change(p,0);4197}4198else4199show_mode_change(p,1);4200}4201}4202}4203}42044205static voidpatch_stats(struct apply_state *state,struct patch *patch)4206{4207int lines = patch->lines_added + patch->lines_deleted;42084209if(lines > state->max_change)4210 state->max_change = lines;4211if(patch->old_name) {4212int len =quote_c_style(patch->old_name, NULL, NULL,0);4213if(!len)4214 len =strlen(patch->old_name);4215if(len > state->max_len)4216 state->max_len = len;4217}4218if(patch->new_name) {4219int len =quote_c_style(patch->new_name, NULL, NULL,0);4220if(!len)4221 len =strlen(patch->new_name);4222if(len > state->max_len)4223 state->max_len = len;4224}4225}42264227static intremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4228{4229if(state->update_index) {4230if(remove_file_from_cache(patch->old_name) <0)4231returnerror(_("unable to remove%sfrom index"), patch->old_name);4232}4233if(!state->cached) {4234if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4235remove_path(patch->old_name);4236}4237}4238return0;4239}42404241static intadd_index_file(struct apply_state *state,4242const char*path,4243unsigned mode,4244void*buf,4245unsigned long size)4246{4247struct stat st;4248struct cache_entry *ce;4249int namelen =strlen(path);4250unsigned ce_size =cache_entry_size(namelen);42514252if(!state->update_index)4253return0;42544255 ce =xcalloc(1, ce_size);4256memcpy(ce->name, path, namelen);4257 ce->ce_mode =create_ce_mode(mode);4258 ce->ce_flags =create_ce_flags(0);4259 ce->ce_namelen = namelen;4260if(S_ISGITLINK(mode)) {4261const char*s;42624263if(!skip_prefix(buf,"Subproject commit ", &s) ||4264get_oid_hex(s, &ce->oid)) {4265free(ce);4266returnerror(_("corrupt patch for submodule%s"), path);4267}4268}else{4269if(!state->cached) {4270if(lstat(path, &st) <0) {4271free(ce);4272returnerror_errno(_("unable to stat newly "4273"created file '%s'"),4274 path);4275}4276fill_stat_cache_info(ce, &st);4277}4278if(write_sha1_file(buf, size, blob_type, ce->oid.hash) <0) {4279free(ce);4280returnerror(_("unable to create backing store "4281"for newly created file%s"), path);4282}4283}4284if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0) {4285free(ce);4286returnerror(_("unable to add cache entry for%s"), path);4287}42884289return0;4290}42914292/*4293 * Returns:4294 * -1 if an unrecoverable error happened4295 * 0 if everything went well4296 * 1 if a recoverable error happened4297 */4298static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4299{4300int fd, res;4301struct strbuf nbuf = STRBUF_INIT;43024303if(S_ISGITLINK(mode)) {4304struct stat st;4305if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4306return0;4307return!!mkdir(path,0777);4308}43094310if(has_symlinks &&S_ISLNK(mode))4311/* Although buf:size is counted string, it also is NUL4312 * terminated.4313 */4314return!!symlink(buf, path);43154316 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4317if(fd <0)4318return1;43194320if(convert_to_working_tree(path, buf, size, &nbuf)) {4321 size = nbuf.len;4322 buf = nbuf.buf;4323}43244325 res =write_in_full(fd, buf, size) <0;4326if(res)4327error_errno(_("failed to write to '%s'"), path);4328strbuf_release(&nbuf);43294330if(close(fd) <0&& !res)4331returnerror_errno(_("closing file '%s'"), path);43324333return res ? -1:0;4334}43354336/*4337 * We optimistically assume that the directories exist,4338 * which is true 99% of the time anyway. If they don't,4339 * we create them and try again.4340 *4341 * Returns:4342 * -1 on error4343 * 0 otherwise4344 */4345static intcreate_one_file(struct apply_state *state,4346char*path,4347unsigned mode,4348const char*buf,4349unsigned long size)4350{4351int res;43524353if(state->cached)4354return0;43554356 res =try_create_file(path, mode, buf, size);4357if(res <0)4358return-1;4359if(!res)4360return0;43614362if(errno == ENOENT) {4363if(safe_create_leading_directories(path))4364return0;4365 res =try_create_file(path, mode, buf, size);4366if(res <0)4367return-1;4368if(!res)4369return0;4370}43714372if(errno == EEXIST || errno == EACCES) {4373/* We may be trying to create a file where a directory4374 * used to be.4375 */4376struct stat st;4377if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4378 errno = EEXIST;4379}43804381if(errno == EEXIST) {4382unsigned int nr =getpid();43834384for(;;) {4385char newpath[PATH_MAX];4386mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4387 res =try_create_file(newpath, mode, buf, size);4388if(res <0)4389return-1;4390if(!res) {4391if(!rename(newpath, path))4392return0;4393unlink_or_warn(newpath);4394break;4395}4396if(errno != EEXIST)4397break;4398++nr;4399}4400}4401returnerror_errno(_("unable to write file '%s' mode%o"),4402 path, mode);4403}44044405static intadd_conflicted_stages_file(struct apply_state *state,4406struct patch *patch)4407{4408int stage, namelen;4409unsigned ce_size, mode;4410struct cache_entry *ce;44114412if(!state->update_index)4413return0;4414 namelen =strlen(patch->new_name);4415 ce_size =cache_entry_size(namelen);4416 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);44174418remove_file_from_cache(patch->new_name);4419for(stage =1; stage <4; stage++) {4420if(is_null_oid(&patch->threeway_stage[stage -1]))4421continue;4422 ce =xcalloc(1, ce_size);4423memcpy(ce->name, patch->new_name, namelen);4424 ce->ce_mode =create_ce_mode(mode);4425 ce->ce_flags =create_ce_flags(stage);4426 ce->ce_namelen = namelen;4427oidcpy(&ce->oid, &patch->threeway_stage[stage -1]);4428if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0) {4429free(ce);4430returnerror(_("unable to add cache entry for%s"),4431 patch->new_name);4432}4433}44344435return0;4436}44374438static intcreate_file(struct apply_state *state,struct patch *patch)4439{4440char*path = patch->new_name;4441unsigned mode = patch->new_mode;4442unsigned long size = patch->resultsize;4443char*buf = patch->result;44444445if(!mode)4446 mode = S_IFREG |0644;4447if(create_one_file(state, path, mode, buf, size))4448return-1;44494450if(patch->conflicted_threeway)4451returnadd_conflicted_stages_file(state, patch);4452else4453returnadd_index_file(state, path, mode, buf, size);4454}44554456/* phase zero is to remove, phase one is to create */4457static intwrite_out_one_result(struct apply_state *state,4458struct patch *patch,4459int phase)4460{4461if(patch->is_delete >0) {4462if(phase ==0)4463returnremove_file(state, patch,1);4464return0;4465}4466if(patch->is_new >0|| patch->is_copy) {4467if(phase ==1)4468returncreate_file(state, patch);4469return0;4470}4471/*4472 * Rename or modification boils down to the same4473 * thing: remove the old, write the new4474 */4475if(phase ==0)4476returnremove_file(state, patch, patch->is_rename);4477if(phase ==1)4478returncreate_file(state, patch);4479return0;4480}44814482static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4483{4484FILE*rej;4485char namebuf[PATH_MAX];4486struct fragment *frag;4487int cnt =0;4488struct strbuf sb = STRBUF_INIT;44894490for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4491if(!frag->rejected)4492continue;4493 cnt++;4494}44954496if(!cnt) {4497if(state->apply_verbosity > verbosity_normal)4498say_patch_name(stderr,4499_("Applied patch%scleanly."), patch);4500return0;4501}45024503/* This should not happen, because a removal patch that leaves4504 * contents are marked "rejected" at the patch level.4505 */4506if(!patch->new_name)4507die(_("internal error"));45084509/* Say this even without --verbose */4510strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4511"Applying patch %%swith%drejects...",4512 cnt),4513 cnt);4514if(state->apply_verbosity > verbosity_silent)4515say_patch_name(stderr, sb.buf, patch);4516strbuf_release(&sb);45174518 cnt =strlen(patch->new_name);4519if(ARRAY_SIZE(namebuf) <= cnt +5) {4520 cnt =ARRAY_SIZE(namebuf) -5;4521warning(_("truncating .rej filename to %.*s.rej"),4522 cnt -1, patch->new_name);4523}4524memcpy(namebuf, patch->new_name, cnt);4525memcpy(namebuf + cnt,".rej",5);45264527 rej =fopen(namebuf,"w");4528if(!rej)4529returnerror_errno(_("cannot open%s"), namebuf);45304531/* Normal git tools never deal with .rej, so do not pretend4532 * this is a git patch by saying --git or giving extended4533 * headers. While at it, maybe please "kompare" that wants4534 * the trailing TAB and some garbage at the end of line ;-).4535 */4536fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4537 patch->new_name, patch->new_name);4538for(cnt =1, frag = patch->fragments;4539 frag;4540 cnt++, frag = frag->next) {4541if(!frag->rejected) {4542if(state->apply_verbosity > verbosity_silent)4543fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4544continue;4545}4546if(state->apply_verbosity > verbosity_silent)4547fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4548fprintf(rej,"%.*s", frag->size, frag->patch);4549if(frag->patch[frag->size-1] !='\n')4550fputc('\n', rej);4551}4552fclose(rej);4553return-1;4554}45554556/*4557 * Returns:4558 * -1 if an error happened4559 * 0 if the patch applied cleanly4560 * 1 if the patch did not apply cleanly4561 */4562static intwrite_out_results(struct apply_state *state,struct patch *list)4563{4564int phase;4565int errs =0;4566struct patch *l;4567struct string_list cpath = STRING_LIST_INIT_DUP;45684569for(phase =0; phase <2; phase++) {4570 l = list;4571while(l) {4572if(l->rejected)4573 errs =1;4574else{4575if(write_out_one_result(state, l, phase)) {4576string_list_clear(&cpath,0);4577return-1;4578}4579if(phase ==1) {4580if(write_out_one_reject(state, l))4581 errs =1;4582if(l->conflicted_threeway) {4583string_list_append(&cpath, l->new_name);4584 errs =1;4585}4586}4587}4588 l = l->next;4589}4590}45914592if(cpath.nr) {4593struct string_list_item *item;45944595string_list_sort(&cpath);4596if(state->apply_verbosity > verbosity_silent) {4597for_each_string_list_item(item, &cpath)4598fprintf(stderr,"U%s\n", item->string);4599}4600string_list_clear(&cpath,0);46014602rerere(0);4603}46044605return errs;4606}46074608/*4609 * Try to apply a patch.4610 *4611 * Returns:4612 * -128 if a bad error happened (like patch unreadable)4613 * -1 if patch did not apply and user cannot deal with it4614 * 0 if the patch applied4615 * 1 if the patch did not apply but user might fix it4616 */4617static intapply_patch(struct apply_state *state,4618int fd,4619const char*filename,4620int options)4621{4622size_t offset;4623struct strbuf buf = STRBUF_INIT;/* owns the patch text */4624struct patch *list = NULL, **listp = &list;4625int skipped_patch =0;4626int res =0;46274628 state->patch_input_file = filename;4629if(read_patch_file(&buf, fd) <0)4630return-128;4631 offset =0;4632while(offset < buf.len) {4633struct patch *patch;4634int nr;46354636 patch =xcalloc(1,sizeof(*patch));4637 patch->inaccurate_eof = !!(options & APPLY_OPT_INACCURATE_EOF);4638 patch->recount = !!(options & APPLY_OPT_RECOUNT);4639 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4640if(nr <0) {4641free_patch(patch);4642if(nr == -128) {4643 res = -128;4644goto end;4645}4646break;4647}4648if(state->apply_in_reverse)4649reverse_patches(patch);4650if(use_patch(state, patch)) {4651patch_stats(state, patch);4652*listp = patch;4653 listp = &patch->next;4654}4655else{4656if(state->apply_verbosity > verbosity_normal)4657say_patch_name(stderr,_("Skipped patch '%s'."), patch);4658free_patch(patch);4659 skipped_patch++;4660}4661 offset += nr;4662}46634664if(!list && !skipped_patch) {4665error(_("unrecognized input"));4666 res = -128;4667goto end;4668}46694670if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4671 state->apply =0;46724673 state->update_index = state->check_index && state->apply;4674if(state->update_index && state->newfd <0) {4675if(state->index_file)4676 state->newfd =hold_lock_file_for_update(state->lock_file,4677 state->index_file,4678 LOCK_DIE_ON_ERROR);4679else4680 state->newfd =hold_locked_index(state->lock_file, LOCK_DIE_ON_ERROR);4681}46824683if(state->check_index &&read_apply_cache(state) <0) {4684error(_("unable to read index file"));4685 res = -128;4686goto end;4687}46884689if(state->check || state->apply) {4690int r =check_patch_list(state, list);4691if(r == -128) {4692 res = -128;4693goto end;4694}4695if(r <0&& !state->apply_with_reject) {4696 res = -1;4697goto end;4698}4699}47004701if(state->apply) {4702int write_res =write_out_results(state, list);4703if(write_res <0) {4704 res = -128;4705goto end;4706}4707if(write_res >0) {4708/* with --3way, we still need to write the index out */4709 res = state->apply_with_reject ? -1:1;4710goto end;4711}4712}47134714if(state->fake_ancestor &&4715build_fake_ancestor(state, list)) {4716 res = -128;4717goto end;4718}47194720if(state->diffstat && state->apply_verbosity > verbosity_silent)4721stat_patch_list(state, list);47224723if(state->numstat && state->apply_verbosity > verbosity_silent)4724numstat_patch_list(state, list);47254726if(state->summary && state->apply_verbosity > verbosity_silent)4727summary_patch_list(list);47284729end:4730free_patch_list(list);4731strbuf_release(&buf);4732string_list_clear(&state->fn_table,0);4733return res;4734}47354736static intapply_option_parse_exclude(const struct option *opt,4737const char*arg,int unset)4738{4739struct apply_state *state = opt->value;4740add_name_limit(state, arg,1);4741return0;4742}47434744static intapply_option_parse_include(const struct option *opt,4745const char*arg,int unset)4746{4747struct apply_state *state = opt->value;4748add_name_limit(state, arg,0);4749 state->has_include =1;4750return0;4751}47524753static intapply_option_parse_p(const struct option *opt,4754const char*arg,4755int unset)4756{4757struct apply_state *state = opt->value;4758 state->p_value =atoi(arg);4759 state->p_value_known =1;4760return0;4761}47624763static intapply_option_parse_space_change(const struct option *opt,4764const char*arg,int unset)4765{4766struct apply_state *state = opt->value;4767if(unset)4768 state->ws_ignore_action = ignore_ws_none;4769else4770 state->ws_ignore_action = ignore_ws_change;4771return0;4772}47734774static intapply_option_parse_whitespace(const struct option *opt,4775const char*arg,int unset)4776{4777struct apply_state *state = opt->value;4778 state->whitespace_option = arg;4779if(parse_whitespace_option(state, arg))4780exit(1);4781return0;4782}47834784static intapply_option_parse_directory(const struct option *opt,4785const char*arg,int unset)4786{4787struct apply_state *state = opt->value;4788strbuf_reset(&state->root);4789strbuf_addstr(&state->root, arg);4790strbuf_complete(&state->root,'/');4791return0;4792}47934794intapply_all_patches(struct apply_state *state,4795int argc,4796const char**argv,4797int options)4798{4799int i;4800int res;4801int errs =0;4802int read_stdin =1;48034804for(i =0; i < argc; i++) {4805const char*arg = argv[i];4806int fd;48074808if(!strcmp(arg,"-")) {4809 res =apply_patch(state,0,"<stdin>", options);4810if(res <0)4811goto end;4812 errs |= res;4813 read_stdin =0;4814continue;4815}else if(0< state->prefix_length)4816 arg =prefix_filename(state->prefix,4817 state->prefix_length,4818 arg);48194820 fd =open(arg, O_RDONLY);4821if(fd <0) {4822error(_("can't open patch '%s':%s"), arg,strerror(errno));4823 res = -128;4824goto end;4825}4826 read_stdin =0;4827set_default_whitespace_mode(state);4828 res =apply_patch(state, fd, arg, options);4829close(fd);4830if(res <0)4831goto end;4832 errs |= res;4833}4834set_default_whitespace_mode(state);4835if(read_stdin) {4836 res =apply_patch(state,0,"<stdin>", options);4837if(res <0)4838goto end;4839 errs |= res;4840}48414842if(state->whitespace_error) {4843if(state->squelch_whitespace_errors &&4844 state->squelch_whitespace_errors < state->whitespace_error) {4845int squelched =4846 state->whitespace_error - state->squelch_whitespace_errors;4847warning(Q_("squelched%dwhitespace error",4848"squelched%dwhitespace errors",4849 squelched),4850 squelched);4851}4852if(state->ws_error_action == die_on_ws_error) {4853error(Q_("%dline adds whitespace errors.",4854"%dlines add whitespace errors.",4855 state->whitespace_error),4856 state->whitespace_error);4857 res = -128;4858goto end;4859}4860if(state->applied_after_fixing_ws && state->apply)4861warning(Q_("%dline applied after"4862" fixing whitespace errors.",4863"%dlines applied after"4864" fixing whitespace errors.",4865 state->applied_after_fixing_ws),4866 state->applied_after_fixing_ws);4867else if(state->whitespace_error)4868warning(Q_("%dline adds whitespace errors.",4869"%dlines add whitespace errors.",4870 state->whitespace_error),4871 state->whitespace_error);4872}48734874if(state->update_index) {4875 res =write_locked_index(&the_index, state->lock_file, COMMIT_LOCK);4876if(res) {4877error(_("Unable to write new index file"));4878 res = -128;4879goto end;4880}4881 state->newfd = -1;4882}48834884 res = !!errs;48854886end:4887if(state->newfd >=0) {4888rollback_lock_file(state->lock_file);4889 state->newfd = -1;4890}48914892if(state->apply_verbosity <= verbosity_silent) {4893set_error_routine(state->saved_error_routine);4894set_warn_routine(state->saved_warn_routine);4895}48964897if(res > -1)4898return res;4899return(res == -1?1:128);4900}49014902intapply_parse_options(int argc,const char**argv,4903struct apply_state *state,4904int*force_apply,int*options,4905const char*const*apply_usage)4906{4907struct option builtin_apply_options[] = {4908{ OPTION_CALLBACK,0,"exclude", state,N_("path"),4909N_("don't apply changes matching the given path"),49100, apply_option_parse_exclude },4911{ OPTION_CALLBACK,0,"include", state,N_("path"),4912N_("apply changes matching the given path"),49130, apply_option_parse_include },4914{ OPTION_CALLBACK,'p', NULL, state,N_("num"),4915N_("remove <num> leading slashes from traditional diff paths"),49160, apply_option_parse_p },4917OPT_BOOL(0,"no-add", &state->no_add,4918N_("ignore additions made by the patch")),4919OPT_BOOL(0,"stat", &state->diffstat,4920N_("instead of applying the patch, output diffstat for the input")),4921OPT_NOOP_NOARG(0,"allow-binary-replacement"),4922OPT_NOOP_NOARG(0,"binary"),4923OPT_BOOL(0,"numstat", &state->numstat,4924N_("show number of added and deleted lines in decimal notation")),4925OPT_BOOL(0,"summary", &state->summary,4926N_("instead of applying the patch, output a summary for the input")),4927OPT_BOOL(0,"check", &state->check,4928N_("instead of applying the patch, see if the patch is applicable")),4929OPT_BOOL(0,"index", &state->check_index,4930N_("make sure the patch is applicable to the current index")),4931OPT_BOOL(0,"cached", &state->cached,4932N_("apply a patch without touching the working tree")),4933OPT_BOOL(0,"unsafe-paths", &state->unsafe_paths,4934N_("accept a patch that touches outside the working area")),4935OPT_BOOL(0,"apply", force_apply,4936N_("also apply the patch (use with --stat/--summary/--check)")),4937OPT_BOOL('3',"3way", &state->threeway,4938N_("attempt three-way merge if a patch does not apply")),4939OPT_FILENAME(0,"build-fake-ancestor", &state->fake_ancestor,4940N_("build a temporary index based on embedded index information")),4941/* Think twice before adding "--nul" synonym to this */4942OPT_SET_INT('z', NULL, &state->line_termination,4943N_("paths are separated with NUL character"),'\0'),4944OPT_INTEGER('C', NULL, &state->p_context,4945N_("ensure at least <n> lines of context match")),4946{ OPTION_CALLBACK,0,"whitespace", state,N_("action"),4947N_("detect new or modified lines that have whitespace errors"),49480, apply_option_parse_whitespace },4949{ OPTION_CALLBACK,0,"ignore-space-change", state, NULL,4950N_("ignore changes in whitespace when finding context"),4951 PARSE_OPT_NOARG, apply_option_parse_space_change },4952{ OPTION_CALLBACK,0,"ignore-whitespace", state, NULL,4953N_("ignore changes in whitespace when finding context"),4954 PARSE_OPT_NOARG, apply_option_parse_space_change },4955OPT_BOOL('R',"reverse", &state->apply_in_reverse,4956N_("apply the patch in reverse")),4957OPT_BOOL(0,"unidiff-zero", &state->unidiff_zero,4958N_("don't expect at least one line of context")),4959OPT_BOOL(0,"reject", &state->apply_with_reject,4960N_("leave the rejected hunks in corresponding *.rej files")),4961OPT_BOOL(0,"allow-overlap", &state->allow_overlap,4962N_("allow overlapping hunks")),4963OPT__VERBOSE(&state->apply_verbosity,N_("be verbose")),4964OPT_BIT(0,"inaccurate-eof", options,4965N_("tolerate incorrectly detected missing new-line at the end of file"),4966 APPLY_OPT_INACCURATE_EOF),4967OPT_BIT(0,"recount", options,4968N_("do not trust the line counts in the hunk headers"),4969 APPLY_OPT_RECOUNT),4970{ OPTION_CALLBACK,0,"directory", state,N_("root"),4971N_("prepend <root> to all filenames"),49720, apply_option_parse_directory },4973OPT_END()4974};49754976returnparse_options(argc, argv, state->prefix, builtin_apply_options, apply_usage,0);4977}