1/* 2 * apply.c 3 * 4 * Copyright (C) Linus Torvalds, 2005 5 * 6 * This applies patches on top of some (arbitrary) version of the SCM. 7 * 8 */ 9 10#include"cache.h" 11#include"config.h" 12#include"blob.h" 13#include"delta.h" 14#include"diff.h" 15#include"dir.h" 16#include"xdiff-interface.h" 17#include"ll-merge.h" 18#include"lockfile.h" 19#include"parse-options.h" 20#include"quote.h" 21#include"rerere.h" 22#include"apply.h" 23 24static voidgit_apply_config(void) 25{ 26git_config_get_string_const("apply.whitespace", &apply_default_whitespace); 27git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace); 28git_config(git_default_config, NULL); 29} 30 31static intparse_whitespace_option(struct apply_state *state,const char*option) 32{ 33if(!option) { 34 state->ws_error_action = warn_on_ws_error; 35return0; 36} 37if(!strcmp(option,"warn")) { 38 state->ws_error_action = warn_on_ws_error; 39return0; 40} 41if(!strcmp(option,"nowarn")) { 42 state->ws_error_action = nowarn_ws_error; 43return0; 44} 45if(!strcmp(option,"error")) { 46 state->ws_error_action = die_on_ws_error; 47return0; 48} 49if(!strcmp(option,"error-all")) { 50 state->ws_error_action = die_on_ws_error; 51 state->squelch_whitespace_errors =0; 52return0; 53} 54if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 55 state->ws_error_action = correct_ws_error; 56return0; 57} 58returnerror(_("unrecognized whitespace option '%s'"), option); 59} 60 61static intparse_ignorewhitespace_option(struct apply_state *state, 62const char*option) 63{ 64if(!option || !strcmp(option,"no") || 65!strcmp(option,"false") || !strcmp(option,"never") || 66!strcmp(option,"none")) { 67 state->ws_ignore_action = ignore_ws_none; 68return0; 69} 70if(!strcmp(option,"change")) { 71 state->ws_ignore_action = ignore_ws_change; 72return0; 73} 74returnerror(_("unrecognized whitespace ignore option '%s'"), option); 75} 76 77intinit_apply_state(struct apply_state *state, 78const char*prefix) 79{ 80memset(state,0,sizeof(*state)); 81 state->prefix = prefix; 82 state->apply =1; 83 state->line_termination ='\n'; 84 state->p_value =1; 85 state->p_context = UINT_MAX; 86 state->squelch_whitespace_errors =5; 87 state->ws_error_action = warn_on_ws_error; 88 state->ws_ignore_action = ignore_ws_none; 89 state->linenr =1; 90string_list_init(&state->fn_table,0); 91string_list_init(&state->limit_by_name,0); 92string_list_init(&state->symlink_changes,0); 93strbuf_init(&state->root,0); 94 95git_apply_config(); 96if(apply_default_whitespace &&parse_whitespace_option(state, apply_default_whitespace)) 97return-1; 98if(apply_default_ignorewhitespace &&parse_ignorewhitespace_option(state, apply_default_ignorewhitespace)) 99return-1; 100return0; 101} 102 103voidclear_apply_state(struct apply_state *state) 104{ 105string_list_clear(&state->limit_by_name,0); 106string_list_clear(&state->symlink_changes,0); 107strbuf_release(&state->root); 108 109/* &state->fn_table is cleared at the end of apply_patch() */ 110} 111 112static voidmute_routine(const char*msg,va_list params) 113{ 114/* do nothing */ 115} 116 117intcheck_apply_state(struct apply_state *state,int force_apply) 118{ 119int is_not_gitdir = !startup_info->have_repository; 120 121if(state->apply_with_reject && state->threeway) 122returnerror(_("--reject and --3way cannot be used together.")); 123if(state->cached && state->threeway) 124returnerror(_("--cached and --3way cannot be used together.")); 125if(state->threeway) { 126if(is_not_gitdir) 127returnerror(_("--3way outside a repository")); 128 state->check_index =1; 129} 130if(state->apply_with_reject) { 131 state->apply =1; 132if(state->apply_verbosity == verbosity_normal) 133 state->apply_verbosity = verbosity_verbose; 134} 135if(!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor)) 136 state->apply =0; 137if(state->check_index && is_not_gitdir) 138returnerror(_("--index outside a repository")); 139if(state->cached) { 140if(is_not_gitdir) 141returnerror(_("--cached outside a repository")); 142 state->check_index =1; 143} 144if(state->check_index) 145 state->unsafe_paths =0; 146 147if(state->apply_verbosity <= verbosity_silent) { 148 state->saved_error_routine =get_error_routine(); 149 state->saved_warn_routine =get_warn_routine(); 150set_error_routine(mute_routine); 151set_warn_routine(mute_routine); 152} 153 154return0; 155} 156 157static voidset_default_whitespace_mode(struct apply_state *state) 158{ 159if(!state->whitespace_option && !apply_default_whitespace) 160 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 161} 162 163/* 164 * This represents one "hunk" from a patch, starting with 165 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 166 * patch text is pointed at by patch, and its byte length 167 * is stored in size. leading and trailing are the number 168 * of context lines. 169 */ 170struct fragment { 171unsigned long leading, trailing; 172unsigned long oldpos, oldlines; 173unsigned long newpos, newlines; 174/* 175 * 'patch' is usually borrowed from buf in apply_patch(), 176 * but some codepaths store an allocated buffer. 177 */ 178const char*patch; 179unsigned free_patch:1, 180 rejected:1; 181int size; 182int linenr; 183struct fragment *next; 184}; 185 186/* 187 * When dealing with a binary patch, we reuse "leading" field 188 * to store the type of the binary hunk, either deflated "delta" 189 * or deflated "literal". 190 */ 191#define binary_patch_method leading 192#define BINARY_DELTA_DEFLATED 1 193#define BINARY_LITERAL_DEFLATED 2 194 195/* 196 * This represents a "patch" to a file, both metainfo changes 197 * such as creation/deletion, filemode and content changes represented 198 * as a series of fragments. 199 */ 200struct patch { 201char*new_name, *old_name, *def_name; 202unsigned int old_mode, new_mode; 203int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 204int rejected; 205unsigned ws_rule; 206int lines_added, lines_deleted; 207int score; 208int extension_linenr;/* first line specifying delete/new/rename/copy */ 209unsigned int is_toplevel_relative:1; 210unsigned int inaccurate_eof:1; 211unsigned int is_binary:1; 212unsigned int is_copy:1; 213unsigned int is_rename:1; 214unsigned int recount:1; 215unsigned int conflicted_threeway:1; 216unsigned int direct_to_threeway:1; 217unsigned int crlf_in_old:1; 218struct fragment *fragments; 219char*result; 220size_t resultsize; 221char old_sha1_prefix[41]; 222char new_sha1_prefix[41]; 223struct patch *next; 224 225/* three-way fallback result */ 226struct object_id threeway_stage[3]; 227}; 228 229static voidfree_fragment_list(struct fragment *list) 230{ 231while(list) { 232struct fragment *next = list->next; 233if(list->free_patch) 234free((char*)list->patch); 235free(list); 236 list = next; 237} 238} 239 240static voidfree_patch(struct patch *patch) 241{ 242free_fragment_list(patch->fragments); 243free(patch->def_name); 244free(patch->old_name); 245free(patch->new_name); 246free(patch->result); 247free(patch); 248} 249 250static voidfree_patch_list(struct patch *list) 251{ 252while(list) { 253struct patch *next = list->next; 254free_patch(list); 255 list = next; 256} 257} 258 259/* 260 * A line in a file, len-bytes long (includes the terminating LF, 261 * except for an incomplete line at the end if the file ends with 262 * one), and its contents hashes to 'hash'. 263 */ 264struct line { 265size_t len; 266unsigned hash :24; 267unsigned flag :8; 268#define LINE_COMMON 1 269#define LINE_PATCHED 2 270}; 271 272/* 273 * This represents a "file", which is an array of "lines". 274 */ 275struct image { 276char*buf; 277size_t len; 278size_t nr; 279size_t alloc; 280struct line *line_allocated; 281struct line *line; 282}; 283 284static uint32_thash_line(const char*cp,size_t len) 285{ 286size_t i; 287uint32_t h; 288for(i =0, h =0; i < len; i++) { 289if(!isspace(cp[i])) { 290 h = h *3+ (cp[i] &0xff); 291} 292} 293return h; 294} 295 296/* 297 * Compare lines s1 of length n1 and s2 of length n2, ignoring 298 * whitespace difference. Returns 1 if they match, 0 otherwise 299 */ 300static intfuzzy_matchlines(const char*s1,size_t n1, 301const char*s2,size_t n2) 302{ 303const char*end1 = s1 + n1; 304const char*end2 = s2 + n2; 305 306/* ignore line endings */ 307while(s1 < end1 && (end1[-1] =='\r'|| end1[-1] =='\n')) 308 end1--; 309while(s2 < end2 && (end2[-1] =='\r'|| end2[-1] =='\n')) 310 end2--; 311 312while(s1 < end1 && s2 < end2) { 313if(isspace(*s1)) { 314/* 315 * Skip whitespace. We check on both buffers 316 * because we don't want "a b" to match "ab". 317 */ 318if(!isspace(*s2)) 319return0; 320while(s1 < end1 &&isspace(*s1)) 321 s1++; 322while(s2 < end2 &&isspace(*s2)) 323 s2++; 324}else if(*s1++ != *s2++) 325return0; 326} 327 328/* If we reached the end on one side only, lines don't match. */ 329return s1 == end1 && s2 == end2; 330} 331 332static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 333{ 334ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 335 img->line_allocated[img->nr].len = len; 336 img->line_allocated[img->nr].hash =hash_line(bol, len); 337 img->line_allocated[img->nr].flag = flag; 338 img->nr++; 339} 340 341/* 342 * "buf" has the file contents to be patched (read from various sources). 343 * attach it to "image" and add line-based index to it. 344 * "image" now owns the "buf". 345 */ 346static voidprepare_image(struct image *image,char*buf,size_t len, 347int prepare_linetable) 348{ 349const char*cp, *ep; 350 351memset(image,0,sizeof(*image)); 352 image->buf = buf; 353 image->len = len; 354 355if(!prepare_linetable) 356return; 357 358 ep = image->buf + image->len; 359 cp = image->buf; 360while(cp < ep) { 361const char*next; 362for(next = cp; next < ep && *next !='\n'; next++) 363; 364if(next < ep) 365 next++; 366add_line_info(image, cp, next - cp,0); 367 cp = next; 368} 369 image->line = image->line_allocated; 370} 371 372static voidclear_image(struct image *image) 373{ 374free(image->buf); 375free(image->line_allocated); 376memset(image,0,sizeof(*image)); 377} 378 379/* fmt must contain _one_ %s and no other substitution */ 380static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 381{ 382struct strbuf sb = STRBUF_INIT; 383 384if(patch->old_name && patch->new_name && 385strcmp(patch->old_name, patch->new_name)) { 386quote_c_style(patch->old_name, &sb, NULL,0); 387strbuf_addstr(&sb," => "); 388quote_c_style(patch->new_name, &sb, NULL,0); 389}else{ 390const char*n = patch->new_name; 391if(!n) 392 n = patch->old_name; 393quote_c_style(n, &sb, NULL,0); 394} 395fprintf(output, fmt, sb.buf); 396fputc('\n', output); 397strbuf_release(&sb); 398} 399 400#define SLOP (16) 401 402static intread_patch_file(struct strbuf *sb,int fd) 403{ 404if(strbuf_read(sb, fd,0) <0) 405returnerror_errno("git apply: failed to read"); 406 407/* 408 * Make sure that we have some slop in the buffer 409 * so that we can do speculative "memcmp" etc, and 410 * see to it that it is NUL-filled. 411 */ 412strbuf_grow(sb, SLOP); 413memset(sb->buf + sb->len,0, SLOP); 414return0; 415} 416 417static unsigned longlinelen(const char*buffer,unsigned long size) 418{ 419unsigned long len =0; 420while(size--) { 421 len++; 422if(*buffer++ =='\n') 423break; 424} 425return len; 426} 427 428static intis_dev_null(const char*str) 429{ 430returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 431} 432 433#define TERM_SPACE 1 434#define TERM_TAB 2 435 436static intname_terminate(int c,int terminate) 437{ 438if(c ==' '&& !(terminate & TERM_SPACE)) 439return0; 440if(c =='\t'&& !(terminate & TERM_TAB)) 441return0; 442 443return1; 444} 445 446/* remove double slashes to make --index work with such filenames */ 447static char*squash_slash(char*name) 448{ 449int i =0, j =0; 450 451if(!name) 452return NULL; 453 454while(name[i]) { 455if((name[j++] = name[i++]) =='/') 456while(name[i] =='/') 457 i++; 458} 459 name[j] ='\0'; 460return name; 461} 462 463static char*find_name_gnu(struct apply_state *state, 464const char*line, 465const char*def, 466int p_value) 467{ 468struct strbuf name = STRBUF_INIT; 469char*cp; 470 471/* 472 * Proposed "new-style" GNU patch/diff format; see 473 * http://marc.info/?l=git&m=112927316408690&w=2 474 */ 475if(unquote_c_style(&name, line, NULL)) { 476strbuf_release(&name); 477return NULL; 478} 479 480for(cp = name.buf; p_value; p_value--) { 481 cp =strchr(cp,'/'); 482if(!cp) { 483strbuf_release(&name); 484return NULL; 485} 486 cp++; 487} 488 489strbuf_remove(&name,0, cp - name.buf); 490if(state->root.len) 491strbuf_insert(&name,0, state->root.buf, state->root.len); 492returnsquash_slash(strbuf_detach(&name, NULL)); 493} 494 495static size_tsane_tz_len(const char*line,size_t len) 496{ 497const char*tz, *p; 498 499if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 500return0; 501 tz = line + len -strlen(" +0500"); 502 503if(tz[1] !='+'&& tz[1] !='-') 504return0; 505 506for(p = tz +2; p != line + len; p++) 507if(!isdigit(*p)) 508return0; 509 510return line + len - tz; 511} 512 513static size_ttz_with_colon_len(const char*line,size_t len) 514{ 515const char*tz, *p; 516 517if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 518return0; 519 tz = line + len -strlen(" +08:00"); 520 521if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 522return0; 523 p = tz +2; 524if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 525!isdigit(*p++) || !isdigit(*p++)) 526return0; 527 528return line + len - tz; 529} 530 531static size_tdate_len(const char*line,size_t len) 532{ 533const char*date, *p; 534 535if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 536return0; 537 p = date = line + len -strlen("72-02-05"); 538 539if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 540!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 541!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 542return0; 543 544if(date - line >=strlen("19") && 545isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 546 date -=strlen("19"); 547 548return line + len - date; 549} 550 551static size_tshort_time_len(const char*line,size_t len) 552{ 553const char*time, *p; 554 555if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 556return0; 557 p = time = line + len -strlen(" 07:01:32"); 558 559/* Permit 1-digit hours? */ 560if(*p++ !=' '|| 561!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 562!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 563!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 564return0; 565 566return line + len - time; 567} 568 569static size_tfractional_time_len(const char*line,size_t len) 570{ 571const char*p; 572size_t n; 573 574/* Expected format: 19:41:17.620000023 */ 575if(!len || !isdigit(line[len -1])) 576return0; 577 p = line + len -1; 578 579/* Fractional seconds. */ 580while(p > line &&isdigit(*p)) 581 p--; 582if(*p !='.') 583return0; 584 585/* Hours, minutes, and whole seconds. */ 586 n =short_time_len(line, p - line); 587if(!n) 588return0; 589 590return line + len - p + n; 591} 592 593static size_ttrailing_spaces_len(const char*line,size_t len) 594{ 595const char*p; 596 597/* Expected format: ' ' x (1 or more) */ 598if(!len || line[len -1] !=' ') 599return0; 600 601 p = line + len; 602while(p != line) { 603 p--; 604if(*p !=' ') 605return line + len - (p +1); 606} 607 608/* All spaces! */ 609return len; 610} 611 612static size_tdiff_timestamp_len(const char*line,size_t len) 613{ 614const char*end = line + len; 615size_t n; 616 617/* 618 * Posix: 2010-07-05 19:41:17 619 * GNU: 2010-07-05 19:41:17.620000023 -0500 620 */ 621 622if(!isdigit(end[-1])) 623return0; 624 625 n =sane_tz_len(line, end - line); 626if(!n) 627 n =tz_with_colon_len(line, end - line); 628 end -= n; 629 630 n =short_time_len(line, end - line); 631if(!n) 632 n =fractional_time_len(line, end - line); 633 end -= n; 634 635 n =date_len(line, end - line); 636if(!n)/* No date. Too bad. */ 637return0; 638 end -= n; 639 640if(end == line)/* No space before date. */ 641return0; 642if(end[-1] =='\t') {/* Success! */ 643 end--; 644return line + len - end; 645} 646if(end[-1] !=' ')/* No space before date. */ 647return0; 648 649/* Whitespace damage. */ 650 end -=trailing_spaces_len(line, end - line); 651return line + len - end; 652} 653 654static char*find_name_common(struct apply_state *state, 655const char*line, 656const char*def, 657int p_value, 658const char*end, 659int terminate) 660{ 661int len; 662const char*start = NULL; 663 664if(p_value ==0) 665 start = line; 666while(line != end) { 667char c = *line; 668 669if(!end &&isspace(c)) { 670if(c =='\n') 671break; 672if(name_terminate(c, terminate)) 673break; 674} 675 line++; 676if(c =='/'&& !--p_value) 677 start = line; 678} 679if(!start) 680returnsquash_slash(xstrdup_or_null(def)); 681 len = line - start; 682if(!len) 683returnsquash_slash(xstrdup_or_null(def)); 684 685/* 686 * Generally we prefer the shorter name, especially 687 * if the other one is just a variation of that with 688 * something else tacked on to the end (ie "file.orig" 689 * or "file~"). 690 */ 691if(def) { 692int deflen =strlen(def); 693if(deflen < len && !strncmp(start, def, deflen)) 694returnsquash_slash(xstrdup(def)); 695} 696 697if(state->root.len) { 698char*ret =xstrfmt("%s%.*s", state->root.buf, len, start); 699returnsquash_slash(ret); 700} 701 702returnsquash_slash(xmemdupz(start, len)); 703} 704 705static char*find_name(struct apply_state *state, 706const char*line, 707char*def, 708int p_value, 709int terminate) 710{ 711if(*line =='"') { 712char*name =find_name_gnu(state, line, def, p_value); 713if(name) 714return name; 715} 716 717returnfind_name_common(state, line, def, p_value, NULL, terminate); 718} 719 720static char*find_name_traditional(struct apply_state *state, 721const char*line, 722char*def, 723int p_value) 724{ 725size_t len; 726size_t date_len; 727 728if(*line =='"') { 729char*name =find_name_gnu(state, line, def, p_value); 730if(name) 731return name; 732} 733 734 len =strchrnul(line,'\n') - line; 735 date_len =diff_timestamp_len(line, len); 736if(!date_len) 737returnfind_name_common(state, line, def, p_value, NULL, TERM_TAB); 738 len -= date_len; 739 740returnfind_name_common(state, line, def, p_value, line + len,0); 741} 742 743/* 744 * Given the string after "--- " or "+++ ", guess the appropriate 745 * p_value for the given patch. 746 */ 747static intguess_p_value(struct apply_state *state,const char*nameline) 748{ 749char*name, *cp; 750int val = -1; 751 752if(is_dev_null(nameline)) 753return-1; 754 name =find_name_traditional(state, nameline, NULL,0); 755if(!name) 756return-1; 757 cp =strchr(name,'/'); 758if(!cp) 759 val =0; 760else if(state->prefix) { 761/* 762 * Does it begin with "a/$our-prefix" and such? Then this is 763 * very likely to apply to our directory. 764 */ 765if(starts_with(name, state->prefix)) 766 val =count_slashes(state->prefix); 767else{ 768 cp++; 769if(starts_with(cp, state->prefix)) 770 val =count_slashes(state->prefix) +1; 771} 772} 773free(name); 774return val; 775} 776 777/* 778 * Does the ---/+++ line have the POSIX timestamp after the last HT? 779 * GNU diff puts epoch there to signal a creation/deletion event. Is 780 * this such a timestamp? 781 */ 782static inthas_epoch_timestamp(const char*nameline) 783{ 784/* 785 * We are only interested in epoch timestamp; any non-zero 786 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 787 * For the same reason, the date must be either 1969-12-31 or 788 * 1970-01-01, and the seconds part must be "00". 789 */ 790const char stamp_regexp[] = 791"^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?" 792" " 793"([-+][0-2][0-9]:?[0-5][0-9])\n"; 794const char*timestamp = NULL, *cp, *colon; 795static regex_t *stamp; 796 regmatch_t m[10]; 797int zoneoffset, epoch_hour, hour, minute; 798int status; 799 800for(cp = nameline; *cp !='\n'; cp++) { 801if(*cp =='\t') 802 timestamp = cp +1; 803} 804if(!timestamp) 805return0; 806 807/* 808 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 809 * (west of GMT) or 1970-01-01 (east of GMT) 810 */ 811if(skip_prefix(timestamp,"1969-12-31 ", ×tamp)) 812 epoch_hour =24; 813else if(skip_prefix(timestamp,"1970-01-01 ", ×tamp)) 814 epoch_hour =0; 815else 816return0; 817 818if(!stamp) { 819 stamp =xmalloc(sizeof(*stamp)); 820if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 821warning(_("Cannot prepare timestamp regexp%s"), 822 stamp_regexp); 823return0; 824} 825} 826 827 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 828if(status) { 829if(status != REG_NOMATCH) 830warning(_("regexec returned%dfor input:%s"), 831 status, timestamp); 832return0; 833} 834 835 hour =strtol(timestamp, NULL,10); 836 minute =strtol(timestamp + m[1].rm_so, NULL,10); 837 838 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 839if(*colon ==':') 840 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 841else 842 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 843if(timestamp[m[3].rm_so] =='-') 844 zoneoffset = -zoneoffset; 845 846return hour *60+ minute - zoneoffset == epoch_hour *60; 847} 848 849/* 850 * Get the name etc info from the ---/+++ lines of a traditional patch header 851 * 852 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 853 * files, we can happily check the index for a match, but for creating a 854 * new file we should try to match whatever "patch" does. I have no idea. 855 */ 856static intparse_traditional_patch(struct apply_state *state, 857const char*first, 858const char*second, 859struct patch *patch) 860{ 861char*name; 862 863 first +=4;/* skip "--- " */ 864 second +=4;/* skip "+++ " */ 865if(!state->p_value_known) { 866int p, q; 867 p =guess_p_value(state, first); 868 q =guess_p_value(state, second); 869if(p <0) p = q; 870if(0<= p && p == q) { 871 state->p_value = p; 872 state->p_value_known =1; 873} 874} 875if(is_dev_null(first)) { 876 patch->is_new =1; 877 patch->is_delete =0; 878 name =find_name_traditional(state, second, NULL, state->p_value); 879 patch->new_name = name; 880}else if(is_dev_null(second)) { 881 patch->is_new =0; 882 patch->is_delete =1; 883 name =find_name_traditional(state, first, NULL, state->p_value); 884 patch->old_name = name; 885}else{ 886char*first_name; 887 first_name =find_name_traditional(state, first, NULL, state->p_value); 888 name =find_name_traditional(state, second, first_name, state->p_value); 889free(first_name); 890if(has_epoch_timestamp(first)) { 891 patch->is_new =1; 892 patch->is_delete =0; 893 patch->new_name = name; 894}else if(has_epoch_timestamp(second)) { 895 patch->is_new =0; 896 patch->is_delete =1; 897 patch->old_name = name; 898}else{ 899 patch->old_name = name; 900 patch->new_name =xstrdup_or_null(name); 901} 902} 903if(!name) 904returnerror(_("unable to find filename in patch at line%d"), state->linenr); 905 906return0; 907} 908 909static intgitdiff_hdrend(struct apply_state *state, 910const char*line, 911struct patch *patch) 912{ 913return1; 914} 915 916/* 917 * We're anal about diff header consistency, to make 918 * sure that we don't end up having strange ambiguous 919 * patches floating around. 920 * 921 * As a result, gitdiff_{old|new}name() will check 922 * their names against any previous information, just 923 * to make sure.. 924 */ 925#define DIFF_OLD_NAME 0 926#define DIFF_NEW_NAME 1 927 928static intgitdiff_verify_name(struct apply_state *state, 929const char*line, 930int isnull, 931char**name, 932int side) 933{ 934if(!*name && !isnull) { 935*name =find_name(state, line, NULL, state->p_value, TERM_TAB); 936return0; 937} 938 939if(*name) { 940char*another; 941if(isnull) 942returnerror(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 943*name, state->linenr); 944 another =find_name(state, line, NULL, state->p_value, TERM_TAB); 945if(!another ||strcmp(another, *name)) { 946free(another); 947returnerror((side == DIFF_NEW_NAME) ? 948_("git apply: bad git-diff - inconsistent new filename on line%d") : 949_("git apply: bad git-diff - inconsistent old filename on line%d"), state->linenr); 950} 951free(another); 952}else{ 953if(!starts_with(line,"/dev/null\n")) 954returnerror(_("git apply: bad git-diff - expected /dev/null on line%d"), state->linenr); 955} 956 957return0; 958} 959 960static intgitdiff_oldname(struct apply_state *state, 961const char*line, 962struct patch *patch) 963{ 964returngitdiff_verify_name(state, line, 965 patch->is_new, &patch->old_name, 966 DIFF_OLD_NAME); 967} 968 969static intgitdiff_newname(struct apply_state *state, 970const char*line, 971struct patch *patch) 972{ 973returngitdiff_verify_name(state, line, 974 patch->is_delete, &patch->new_name, 975 DIFF_NEW_NAME); 976} 977 978static intparse_mode_line(const char*line,int linenr,unsigned int*mode) 979{ 980char*end; 981*mode =strtoul(line, &end,8); 982if(end == line || !isspace(*end)) 983returnerror(_("invalid mode on line%d:%s"), linenr, line); 984return0; 985} 986 987static intgitdiff_oldmode(struct apply_state *state, 988const char*line, 989struct patch *patch) 990{ 991returnparse_mode_line(line, state->linenr, &patch->old_mode); 992} 993 994static intgitdiff_newmode(struct apply_state *state, 995const char*line, 996struct patch *patch) 997{ 998returnparse_mode_line(line, state->linenr, &patch->new_mode); 999}10001001static intgitdiff_delete(struct apply_state *state,1002const char*line,1003struct patch *patch)1004{1005 patch->is_delete =1;1006free(patch->old_name);1007 patch->old_name =xstrdup_or_null(patch->def_name);1008returngitdiff_oldmode(state, line, patch);1009}10101011static intgitdiff_newfile(struct apply_state *state,1012const char*line,1013struct patch *patch)1014{1015 patch->is_new =1;1016free(patch->new_name);1017 patch->new_name =xstrdup_or_null(patch->def_name);1018returngitdiff_newmode(state, line, patch);1019}10201021static intgitdiff_copysrc(struct apply_state *state,1022const char*line,1023struct patch *patch)1024{1025 patch->is_copy =1;1026free(patch->old_name);1027 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1028return0;1029}10301031static intgitdiff_copydst(struct apply_state *state,1032const char*line,1033struct patch *patch)1034{1035 patch->is_copy =1;1036free(patch->new_name);1037 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1038return0;1039}10401041static intgitdiff_renamesrc(struct apply_state *state,1042const char*line,1043struct patch *patch)1044{1045 patch->is_rename =1;1046free(patch->old_name);1047 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1048return0;1049}10501051static intgitdiff_renamedst(struct apply_state *state,1052const char*line,1053struct patch *patch)1054{1055 patch->is_rename =1;1056free(patch->new_name);1057 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1058return0;1059}10601061static intgitdiff_similarity(struct apply_state *state,1062const char*line,1063struct patch *patch)1064{1065unsigned long val =strtoul(line, NULL,10);1066if(val <=100)1067 patch->score = val;1068return0;1069}10701071static intgitdiff_dissimilarity(struct apply_state *state,1072const char*line,1073struct patch *patch)1074{1075unsigned long val =strtoul(line, NULL,10);1076if(val <=100)1077 patch->score = val;1078return0;1079}10801081static intgitdiff_index(struct apply_state *state,1082const char*line,1083struct patch *patch)1084{1085/*1086 * index line is N hexadecimal, "..", N hexadecimal,1087 * and optional space with octal mode.1088 */1089const char*ptr, *eol;1090int len;10911092 ptr =strchr(line,'.');1093if(!ptr || ptr[1] !='.'||40< ptr - line)1094return0;1095 len = ptr - line;1096memcpy(patch->old_sha1_prefix, line, len);1097 patch->old_sha1_prefix[len] =0;10981099 line = ptr +2;1100 ptr =strchr(line,' ');1101 eol =strchrnul(line,'\n');11021103if(!ptr || eol < ptr)1104 ptr = eol;1105 len = ptr - line;11061107if(40< len)1108return0;1109memcpy(patch->new_sha1_prefix, line, len);1110 patch->new_sha1_prefix[len] =0;1111if(*ptr ==' ')1112returngitdiff_oldmode(state, ptr +1, patch);1113return0;1114}11151116/*1117 * This is normal for a diff that doesn't change anything: we'll fall through1118 * into the next diff. Tell the parser to break out.1119 */1120static intgitdiff_unrecognized(struct apply_state *state,1121const char*line,1122struct patch *patch)1123{1124return1;1125}11261127/*1128 * Skip p_value leading components from "line"; as we do not accept1129 * absolute paths, return NULL in that case.1130 */1131static const char*skip_tree_prefix(struct apply_state *state,1132const char*line,1133int llen)1134{1135int nslash;1136int i;11371138if(!state->p_value)1139return(llen && line[0] =='/') ? NULL : line;11401141 nslash = state->p_value;1142for(i =0; i < llen; i++) {1143int ch = line[i];1144if(ch =='/'&& --nslash <=0)1145return(i ==0) ? NULL : &line[i +1];1146}1147return NULL;1148}11491150/*1151 * This is to extract the same name that appears on "diff --git"1152 * line. We do not find and return anything if it is a rename1153 * patch, and it is OK because we will find the name elsewhere.1154 * We need to reliably find name only when it is mode-change only,1155 * creation or deletion of an empty file. In any of these cases,1156 * both sides are the same name under a/ and b/ respectively.1157 */1158static char*git_header_name(struct apply_state *state,1159const char*line,1160int llen)1161{1162const char*name;1163const char*second = NULL;1164size_t len, line_len;11651166 line +=strlen("diff --git ");1167 llen -=strlen("diff --git ");11681169if(*line =='"') {1170const char*cp;1171struct strbuf first = STRBUF_INIT;1172struct strbuf sp = STRBUF_INIT;11731174if(unquote_c_style(&first, line, &second))1175goto free_and_fail1;11761177/* strip the a/b prefix including trailing slash */1178 cp =skip_tree_prefix(state, first.buf, first.len);1179if(!cp)1180goto free_and_fail1;1181strbuf_remove(&first,0, cp - first.buf);11821183/*1184 * second points at one past closing dq of name.1185 * find the second name.1186 */1187while((second < line + llen) &&isspace(*second))1188 second++;11891190if(line + llen <= second)1191goto free_and_fail1;1192if(*second =='"') {1193if(unquote_c_style(&sp, second, NULL))1194goto free_and_fail1;1195 cp =skip_tree_prefix(state, sp.buf, sp.len);1196if(!cp)1197goto free_and_fail1;1198/* They must match, otherwise ignore */1199if(strcmp(cp, first.buf))1200goto free_and_fail1;1201strbuf_release(&sp);1202returnstrbuf_detach(&first, NULL);1203}12041205/* unquoted second */1206 cp =skip_tree_prefix(state, second, line + llen - second);1207if(!cp)1208goto free_and_fail1;1209if(line + llen - cp != first.len ||1210memcmp(first.buf, cp, first.len))1211goto free_and_fail1;1212returnstrbuf_detach(&first, NULL);12131214 free_and_fail1:1215strbuf_release(&first);1216strbuf_release(&sp);1217return NULL;1218}12191220/* unquoted first name */1221 name =skip_tree_prefix(state, line, llen);1222if(!name)1223return NULL;12241225/*1226 * since the first name is unquoted, a dq if exists must be1227 * the beginning of the second name.1228 */1229for(second = name; second < line + llen; second++) {1230if(*second =='"') {1231struct strbuf sp = STRBUF_INIT;1232const char*np;12331234if(unquote_c_style(&sp, second, NULL))1235goto free_and_fail2;12361237 np =skip_tree_prefix(state, sp.buf, sp.len);1238if(!np)1239goto free_and_fail2;12401241 len = sp.buf + sp.len - np;1242if(len < second - name &&1243!strncmp(np, name, len) &&1244isspace(name[len])) {1245/* Good */1246strbuf_remove(&sp,0, np - sp.buf);1247returnstrbuf_detach(&sp, NULL);1248}12491250 free_and_fail2:1251strbuf_release(&sp);1252return NULL;1253}1254}12551256/*1257 * Accept a name only if it shows up twice, exactly the same1258 * form.1259 */1260 second =strchr(name,'\n');1261if(!second)1262return NULL;1263 line_len = second - name;1264for(len =0; ; len++) {1265switch(name[len]) {1266default:1267continue;1268case'\n':1269return NULL;1270case'\t':case' ':1271/*1272 * Is this the separator between the preimage1273 * and the postimage pathname? Again, we are1274 * only interested in the case where there is1275 * no rename, as this is only to set def_name1276 * and a rename patch has the names elsewhere1277 * in an unambiguous form.1278 */1279if(!name[len +1])1280return NULL;/* no postimage name */1281 second =skip_tree_prefix(state, name + len +1,1282 line_len - (len +1));1283if(!second)1284return NULL;1285/*1286 * Does len bytes starting at "name" and "second"1287 * (that are separated by one HT or SP we just1288 * found) exactly match?1289 */1290if(second[len] =='\n'&& !strncmp(name, second, len))1291returnxmemdupz(name, len);1292}1293}1294}12951296static intcheck_header_line(struct apply_state *state,struct patch *patch)1297{1298int extensions = (patch->is_delete ==1) + (patch->is_new ==1) +1299(patch->is_rename ==1) + (patch->is_copy ==1);1300if(extensions >1)1301returnerror(_("inconsistent header lines%dand%d"),1302 patch->extension_linenr, state->linenr);1303if(extensions && !patch->extension_linenr)1304 patch->extension_linenr = state->linenr;1305return0;1306}13071308/* Verify that we recognize the lines following a git header */1309static intparse_git_header(struct apply_state *state,1310const char*line,1311int len,1312unsigned int size,1313struct patch *patch)1314{1315unsigned long offset;13161317/* A git diff has explicit new/delete information, so we don't guess */1318 patch->is_new =0;1319 patch->is_delete =0;13201321/*1322 * Some things may not have the old name in the1323 * rest of the headers anywhere (pure mode changes,1324 * or removing or adding empty files), so we get1325 * the default name from the header.1326 */1327 patch->def_name =git_header_name(state, line, len);1328if(patch->def_name && state->root.len) {1329char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1330free(patch->def_name);1331 patch->def_name = s;1332}13331334 line += len;1335 size -= len;1336 state->linenr++;1337for(offset = len ; size >0; offset += len, size -= len, line += len, state->linenr++) {1338static const struct opentry {1339const char*str;1340int(*fn)(struct apply_state *,const char*,struct patch *);1341} optable[] = {1342{"@@ -", gitdiff_hdrend },1343{"--- ", gitdiff_oldname },1344{"+++ ", gitdiff_newname },1345{"old mode ", gitdiff_oldmode },1346{"new mode ", gitdiff_newmode },1347{"deleted file mode ", gitdiff_delete },1348{"new file mode ", gitdiff_newfile },1349{"copy from ", gitdiff_copysrc },1350{"copy to ", gitdiff_copydst },1351{"rename old ", gitdiff_renamesrc },1352{"rename new ", gitdiff_renamedst },1353{"rename from ", gitdiff_renamesrc },1354{"rename to ", gitdiff_renamedst },1355{"similarity index ", gitdiff_similarity },1356{"dissimilarity index ", gitdiff_dissimilarity },1357{"index ", gitdiff_index },1358{"", gitdiff_unrecognized },1359};1360int i;13611362 len =linelen(line, size);1363if(!len || line[len-1] !='\n')1364break;1365for(i =0; i <ARRAY_SIZE(optable); i++) {1366const struct opentry *p = optable + i;1367int oplen =strlen(p->str);1368int res;1369if(len < oplen ||memcmp(p->str, line, oplen))1370continue;1371 res = p->fn(state, line + oplen, patch);1372if(res <0)1373return-1;1374if(check_header_line(state, patch))1375return-1;1376if(res >0)1377return offset;1378break;1379}1380}13811382return offset;1383}13841385static intparse_num(const char*line,unsigned long*p)1386{1387char*ptr;13881389if(!isdigit(*line))1390return0;1391*p =strtoul(line, &ptr,10);1392return ptr - line;1393}13941395static intparse_range(const char*line,int len,int offset,const char*expect,1396unsigned long*p1,unsigned long*p2)1397{1398int digits, ex;13991400if(offset <0|| offset >= len)1401return-1;1402 line += offset;1403 len -= offset;14041405 digits =parse_num(line, p1);1406if(!digits)1407return-1;14081409 offset += digits;1410 line += digits;1411 len -= digits;14121413*p2 =1;1414if(*line ==',') {1415 digits =parse_num(line+1, p2);1416if(!digits)1417return-1;14181419 offset += digits+1;1420 line += digits+1;1421 len -= digits+1;1422}14231424 ex =strlen(expect);1425if(ex > len)1426return-1;1427if(memcmp(line, expect, ex))1428return-1;14291430return offset + ex;1431}14321433static voidrecount_diff(const char*line,int size,struct fragment *fragment)1434{1435int oldlines =0, newlines =0, ret =0;14361437if(size <1) {1438warning("recount: ignore empty hunk");1439return;1440}14411442for(;;) {1443int len =linelen(line, size);1444 size -= len;1445 line += len;14461447if(size <1)1448break;14491450switch(*line) {1451case' ':case'\n':1452 newlines++;1453/* fall through */1454case'-':1455 oldlines++;1456continue;1457case'+':1458 newlines++;1459continue;1460case'\\':1461continue;1462case'@':1463 ret = size <3|| !starts_with(line,"@@ ");1464break;1465case'd':1466 ret = size <5|| !starts_with(line,"diff ");1467break;1468default:1469 ret = -1;1470break;1471}1472if(ret) {1473warning(_("recount: unexpected line: %.*s"),1474(int)linelen(line, size), line);1475return;1476}1477break;1478}1479 fragment->oldlines = oldlines;1480 fragment->newlines = newlines;1481}14821483/*1484 * Parse a unified diff fragment header of the1485 * form "@@ -a,b +c,d @@"1486 */1487static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1488{1489int offset;14901491if(!len || line[len-1] !='\n')1492return-1;14931494/* Figure out the number of lines in a fragment */1495 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1496 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14971498return offset;1499}15001501/*1502 * Find file diff header1503 *1504 * Returns:1505 * -1 if no header was found1506 * -128 in case of error1507 * the size of the header in bytes (called "offset") otherwise1508 */1509static intfind_header(struct apply_state *state,1510const char*line,1511unsigned long size,1512int*hdrsize,1513struct patch *patch)1514{1515unsigned long offset, len;15161517 patch->is_toplevel_relative =0;1518 patch->is_rename = patch->is_copy =0;1519 patch->is_new = patch->is_delete = -1;1520 patch->old_mode = patch->new_mode =0;1521 patch->old_name = patch->new_name = NULL;1522for(offset =0; size >0; offset += len, size -= len, line += len, state->linenr++) {1523unsigned long nextlen;15241525 len =linelen(line, size);1526if(!len)1527break;15281529/* Testing this early allows us to take a few shortcuts.. */1530if(len <6)1531continue;15321533/*1534 * Make sure we don't find any unconnected patch fragments.1535 * That's a sign that we didn't find a header, and that a1536 * patch has become corrupted/broken up.1537 */1538if(!memcmp("@@ -", line,4)) {1539struct fragment dummy;1540if(parse_fragment_header(line, len, &dummy) <0)1541continue;1542error(_("patch fragment without header at line%d: %.*s"),1543 state->linenr, (int)len-1, line);1544return-128;1545}15461547if(size < len +6)1548break;15491550/*1551 * Git patch? It might not have a real patch, just a rename1552 * or mode change, so we handle that specially1553 */1554if(!memcmp("diff --git ", line,11)) {1555int git_hdr_len =parse_git_header(state, line, len, size, patch);1556if(git_hdr_len <0)1557return-128;1558if(git_hdr_len <= len)1559continue;1560if(!patch->old_name && !patch->new_name) {1561if(!patch->def_name) {1562error(Q_("git diff header lacks filename information when removing "1563"%dleading pathname component (line%d)",1564"git diff header lacks filename information when removing "1565"%dleading pathname components (line%d)",1566 state->p_value),1567 state->p_value, state->linenr);1568return-128;1569}1570 patch->old_name =xstrdup(patch->def_name);1571 patch->new_name =xstrdup(patch->def_name);1572}1573if((!patch->new_name && !patch->is_delete) ||1574(!patch->old_name && !patch->is_new)) {1575error(_("git diff header lacks filename information "1576"(line%d)"), state->linenr);1577return-128;1578}1579 patch->is_toplevel_relative =1;1580*hdrsize = git_hdr_len;1581return offset;1582}15831584/* --- followed by +++ ? */1585if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1586continue;15871588/*1589 * We only accept unified patches, so we want it to1590 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1591 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1592 */1593 nextlen =linelen(line + len, size - len);1594if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1595continue;15961597/* Ok, we'll consider it a patch */1598if(parse_traditional_patch(state, line, line+len, patch))1599return-128;1600*hdrsize = len + nextlen;1601 state->linenr +=2;1602return offset;1603}1604return-1;1605}16061607static voidrecord_ws_error(struct apply_state *state,1608unsigned result,1609const char*line,1610int len,1611int linenr)1612{1613char*err;16141615if(!result)1616return;16171618 state->whitespace_error++;1619if(state->squelch_whitespace_errors &&1620 state->squelch_whitespace_errors < state->whitespace_error)1621return;16221623 err =whitespace_error_string(result);1624if(state->apply_verbosity > verbosity_silent)1625fprintf(stderr,"%s:%d:%s.\n%.*s\n",1626 state->patch_input_file, linenr, err, len, line);1627free(err);1628}16291630static voidcheck_whitespace(struct apply_state *state,1631const char*line,1632int len,1633unsigned ws_rule)1634{1635unsigned result =ws_check(line +1, len -1, ws_rule);16361637record_ws_error(state, result, line +1, len -2, state->linenr);1638}16391640/*1641 * Check if the patch has context lines with CRLF or1642 * the patch wants to remove lines with CRLF.1643 */1644static voidcheck_old_for_crlf(struct patch *patch,const char*line,int len)1645{1646if(len >=2&& line[len-1] =='\n'&& line[len-2] =='\r') {1647 patch->ws_rule |= WS_CR_AT_EOL;1648 patch->crlf_in_old =1;1649}1650}165116521653/*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++;1703check_old_for_crlf(patch, line, len);1704if(!state->apply_in_reverse &&1705 state->ws_error_action == correct_ws_error)1706check_whitespace(state, line, len, patch->ws_rule);1707break;1708case'-':1709if(!state->apply_in_reverse)1710check_old_for_crlf(patch, line, len);1711if(state->apply_in_reverse &&1712 state->ws_error_action != nowarn_ws_error)1713check_whitespace(state, line, len, patch->ws_rule);1714 deleted++;1715 oldlines--;1716 trailing =0;1717break;1718case'+':1719if(state->apply_in_reverse)1720check_old_for_crlf(patch, line, len);1721if(!state->apply_in_reverse &&1722 state->ws_error_action != nowarn_ws_error)1723check_whitespace(state, line, len, patch->ws_rule);1724 added++;1725 newlines--;1726 trailing =0;1727break;17281729/*1730 * We allow "\ No newline at end of file". Depending1731 * on locale settings when the patch was produced we1732 * don't know what this line looks like. The only1733 * thing we do know is that it begins with "\ ".1734 * Checking for 12 is just for sanity check -- any1735 * l10n of "\ No newline..." is at least that long.1736 */1737case'\\':1738if(len <12||memcmp(line,"\\",2))1739return-1;1740break;1741}1742}1743if(oldlines || newlines)1744return-1;1745if(!deleted && !added)1746return-1;17471748 fragment->leading = leading;1749 fragment->trailing = trailing;17501751/*1752 * If a fragment ends with an incomplete line, we failed to include1753 * it in the above loop because we hit oldlines == newlines == 01754 * before seeing it.1755 */1756if(12< size && !memcmp(line,"\\",2))1757 offset +=linelen(line, size);17581759 patch->lines_added += added;1760 patch->lines_deleted += deleted;17611762if(0< patch->is_new && oldlines)1763returnerror(_("new file depends on old contents"));1764if(0< patch->is_delete && newlines)1765returnerror(_("deleted file still has contents"));1766return offset;1767}17681769/*1770 * We have seen "diff --git a/... b/..." header (or a traditional patch1771 * header). Read hunks that belong to this patch into fragments and hang1772 * them to the given patch structure.1773 *1774 * The (fragment->patch, fragment->size) pair points into the memory given1775 * by the caller, not a copy, when we return.1776 *1777 * Returns:1778 * -1 in case of error,1779 * the number of bytes in the patch otherwise.1780 */1781static intparse_single_patch(struct apply_state *state,1782const char*line,1783unsigned long size,1784struct patch *patch)1785{1786unsigned long offset =0;1787unsigned long oldlines =0, newlines =0, context =0;1788struct fragment **fragp = &patch->fragments;17891790while(size >4&& !memcmp(line,"@@ -",4)) {1791struct fragment *fragment;1792int len;17931794 fragment =xcalloc(1,sizeof(*fragment));1795 fragment->linenr = state->linenr;1796 len =parse_fragment(state, line, size, patch, fragment);1797if(len <=0) {1798free(fragment);1799returnerror(_("corrupt patch at line%d"), state->linenr);1800}1801 fragment->patch = line;1802 fragment->size = len;1803 oldlines += fragment->oldlines;1804 newlines += fragment->newlines;1805 context += fragment->leading + fragment->trailing;18061807*fragp = fragment;1808 fragp = &fragment->next;18091810 offset += len;1811 line += len;1812 size -= len;1813}18141815/*1816 * If something was removed (i.e. we have old-lines) it cannot1817 * be creation, and if something was added it cannot be1818 * deletion. However, the reverse is not true; --unified=01819 * patches that only add are not necessarily creation even1820 * though they do not have any old lines, and ones that only1821 * delete are not necessarily deletion.1822 *1823 * Unfortunately, a real creation/deletion patch do _not_ have1824 * any context line by definition, so we cannot safely tell it1825 * apart with --unified=0 insanity. At least if the patch has1826 * more than one hunk it is not creation or deletion.1827 */1828if(patch->is_new <0&&1829(oldlines || (patch->fragments && patch->fragments->next)))1830 patch->is_new =0;1831if(patch->is_delete <0&&1832(newlines || (patch->fragments && patch->fragments->next)))1833 patch->is_delete =0;18341835if(0< patch->is_new && oldlines)1836returnerror(_("new file%sdepends on old contents"), patch->new_name);1837if(0< patch->is_delete && newlines)1838returnerror(_("deleted file%sstill has contents"), patch->old_name);1839if(!patch->is_delete && !newlines && context && state->apply_verbosity > verbosity_silent)1840fprintf_ln(stderr,1841_("** warning: "1842"file%sbecomes empty but is not deleted"),1843 patch->new_name);18441845return offset;1846}18471848staticinlineintmetadata_changes(struct patch *patch)1849{1850return patch->is_rename >0||1851 patch->is_copy >0||1852 patch->is_new >0||1853 patch->is_delete ||1854(patch->old_mode && patch->new_mode &&1855 patch->old_mode != patch->new_mode);1856}18571858static char*inflate_it(const void*data,unsigned long size,1859unsigned long inflated_size)1860{1861 git_zstream stream;1862void*out;1863int st;18641865memset(&stream,0,sizeof(stream));18661867 stream.next_in = (unsigned char*)data;1868 stream.avail_in = size;1869 stream.next_out = out =xmalloc(inflated_size);1870 stream.avail_out = inflated_size;1871git_inflate_init(&stream);1872 st =git_inflate(&stream, Z_FINISH);1873git_inflate_end(&stream);1874if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1875free(out);1876return NULL;1877}1878return out;1879}18801881/*1882 * Read a binary hunk and return a new fragment; fragment->patch1883 * points at an allocated memory that the caller must free, so1884 * it is marked as "->free_patch = 1".1885 */1886static struct fragment *parse_binary_hunk(struct apply_state *state,1887char**buf_p,1888unsigned long*sz_p,1889int*status_p,1890int*used_p)1891{1892/*1893 * Expect a line that begins with binary patch method ("literal"1894 * or "delta"), followed by the length of data before deflating.1895 * a sequence of 'length-byte' followed by base-85 encoded data1896 * should follow, terminated by a newline.1897 *1898 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1899 * and we would limit the patch line to 66 characters,1900 * so one line can fit up to 13 groups that would decode1901 * to 52 bytes max. The length byte 'A'-'Z' corresponds1902 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1903 */1904int llen, used;1905unsigned long size = *sz_p;1906char*buffer = *buf_p;1907int patch_method;1908unsigned long origlen;1909char*data = NULL;1910int hunk_size =0;1911struct fragment *frag;19121913 llen =linelen(buffer, size);1914 used = llen;19151916*status_p =0;19171918if(starts_with(buffer,"delta ")) {1919 patch_method = BINARY_DELTA_DEFLATED;1920 origlen =strtoul(buffer +6, NULL,10);1921}1922else if(starts_with(buffer,"literal ")) {1923 patch_method = BINARY_LITERAL_DEFLATED;1924 origlen =strtoul(buffer +8, NULL,10);1925}1926else1927return NULL;19281929 state->linenr++;1930 buffer += llen;1931while(1) {1932int byte_length, max_byte_length, newsize;1933 llen =linelen(buffer, size);1934 used += llen;1935 state->linenr++;1936if(llen ==1) {1937/* consume the blank line */1938 buffer++;1939 size--;1940break;1941}1942/*1943 * Minimum line is "A00000\n" which is 7-byte long,1944 * and the line length must be multiple of 5 plus 2.1945 */1946if((llen <7) || (llen-2) %5)1947goto corrupt;1948 max_byte_length = (llen -2) /5*4;1949 byte_length = *buffer;1950if('A'<= byte_length && byte_length <='Z')1951 byte_length = byte_length -'A'+1;1952else if('a'<= byte_length && byte_length <='z')1953 byte_length = byte_length -'a'+27;1954else1955goto corrupt;1956/* if the input length was not multiple of 4, we would1957 * have filler at the end but the filler should never1958 * exceed 3 bytes1959 */1960if(max_byte_length < byte_length ||1961 byte_length <= max_byte_length -4)1962goto corrupt;1963 newsize = hunk_size + byte_length;1964 data =xrealloc(data, newsize);1965if(decode_85(data + hunk_size, buffer +1, byte_length))1966goto corrupt;1967 hunk_size = newsize;1968 buffer += llen;1969 size -= llen;1970}19711972 frag =xcalloc(1,sizeof(*frag));1973 frag->patch =inflate_it(data, hunk_size, origlen);1974 frag->free_patch =1;1975if(!frag->patch)1976goto corrupt;1977free(data);1978 frag->size = origlen;1979*buf_p = buffer;1980*sz_p = size;1981*used_p = used;1982 frag->binary_patch_method = patch_method;1983return frag;19841985 corrupt:1986free(data);1987*status_p = -1;1988error(_("corrupt binary patch at line%d: %.*s"),1989 state->linenr-1, llen-1, buffer);1990return NULL;1991}19921993/*1994 * Returns:1995 * -1 in case of error,1996 * the length of the parsed binary patch otherwise1997 */1998static intparse_binary(struct apply_state *state,1999char*buffer,2000unsigned long size,2001struct patch *patch)2002{2003/*2004 * We have read "GIT binary patch\n"; what follows is a line2005 * that says the patch method (currently, either "literal" or2006 * "delta") and the length of data before deflating; a2007 * sequence of 'length-byte' followed by base-85 encoded data2008 * follows.2009 *2010 * When a binary patch is reversible, there is another binary2011 * hunk in the same format, starting with patch method (either2012 * "literal" or "delta") with the length of data, and a sequence2013 * of length-byte + base-85 encoded data, terminated with another2014 * empty line. This data, when applied to the postimage, produces2015 * the preimage.2016 */2017struct fragment *forward;2018struct fragment *reverse;2019int status;2020int used, used_1;20212022 forward =parse_binary_hunk(state, &buffer, &size, &status, &used);2023if(!forward && !status)2024/* there has to be one hunk (forward hunk) */2025returnerror(_("unrecognized binary patch at line%d"), state->linenr-1);2026if(status)2027/* otherwise we already gave an error message */2028return status;20292030 reverse =parse_binary_hunk(state, &buffer, &size, &status, &used_1);2031if(reverse)2032 used += used_1;2033else if(status) {2034/*2035 * Not having reverse hunk is not an error, but having2036 * a corrupt reverse hunk is.2037 */2038free((void*) forward->patch);2039free(forward);2040return status;2041}2042 forward->next = reverse;2043 patch->fragments = forward;2044 patch->is_binary =1;2045return used;2046}20472048static voidprefix_one(struct apply_state *state,char**name)2049{2050char*old_name = *name;2051if(!old_name)2052return;2053*name =prefix_filename(state->prefix, *name);2054free(old_name);2055}20562057static voidprefix_patch(struct apply_state *state,struct patch *p)2058{2059if(!state->prefix || p->is_toplevel_relative)2060return;2061prefix_one(state, &p->new_name);2062prefix_one(state, &p->old_name);2063}20642065/*2066 * include/exclude2067 */20682069static voidadd_name_limit(struct apply_state *state,2070const char*name,2071int exclude)2072{2073struct string_list_item *it;20742075 it =string_list_append(&state->limit_by_name, name);2076 it->util = exclude ? NULL : (void*)1;2077}20782079static intuse_patch(struct apply_state *state,struct patch *p)2080{2081const char*pathname = p->new_name ? p->new_name : p->old_name;2082int i;20832084/* Paths outside are not touched regardless of "--include" */2085if(state->prefix && *state->prefix) {2086const char*rest;2087if(!skip_prefix(pathname, state->prefix, &rest) || !*rest)2088return0;2089}20902091/* See if it matches any of exclude/include rule */2092for(i =0; i < state->limit_by_name.nr; i++) {2093struct string_list_item *it = &state->limit_by_name.items[i];2094if(!wildmatch(it->string, pathname,0))2095return(it->util != NULL);2096}20972098/*2099 * If we had any include, a path that does not match any rule is2100 * not used. Otherwise, we saw bunch of exclude rules (or none)2101 * and such a path is used.2102 */2103return!state->has_include;2104}21052106/*2107 * Read the patch text in "buffer" that extends for "size" bytes; stop2108 * reading after seeing a single patch (i.e. changes to a single file).2109 * Create fragments (i.e. patch hunks) and hang them to the given patch.2110 *2111 * Returns:2112 * -1 if no header was found or parse_binary() failed,2113 * -128 on another error,2114 * the number of bytes consumed otherwise,2115 * so that the caller can call us again for the next patch.2116 */2117static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2118{2119int hdrsize, patchsize;2120int offset =find_header(state, buffer, size, &hdrsize, patch);21212122if(offset <0)2123return offset;21242125prefix_patch(state, patch);21262127if(!use_patch(state, patch))2128 patch->ws_rule =0;2129else2130 patch->ws_rule =whitespace_rule(patch->new_name2131? patch->new_name2132: patch->old_name);21332134 patchsize =parse_single_patch(state,2135 buffer + offset + hdrsize,2136 size - offset - hdrsize,2137 patch);21382139if(patchsize <0)2140return-128;21412142if(!patchsize) {2143static const char git_binary[] ="GIT binary patch\n";2144int hd = hdrsize + offset;2145unsigned long llen =linelen(buffer + hd, size - hd);21462147if(llen ==sizeof(git_binary) -1&&2148!memcmp(git_binary, buffer + hd, llen)) {2149int used;2150 state->linenr++;2151 used =parse_binary(state, buffer + hd + llen,2152 size - hd - llen, patch);2153if(used <0)2154return-1;2155if(used)2156 patchsize = used + llen;2157else2158 patchsize =0;2159}2160else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2161static const char*binhdr[] = {2162"Binary files ",2163"Files ",2164 NULL,2165};2166int i;2167for(i =0; binhdr[i]; i++) {2168int len =strlen(binhdr[i]);2169if(len < size - hd &&2170!memcmp(binhdr[i], buffer + hd, len)) {2171 state->linenr++;2172 patch->is_binary =1;2173 patchsize = llen;2174break;2175}2176}2177}21782179/* Empty patch cannot be applied if it is a text patch2180 * without metadata change. A binary patch appears2181 * empty to us here.2182 */2183if((state->apply || state->check) &&2184(!patch->is_binary && !metadata_changes(patch))) {2185error(_("patch with only garbage at line%d"), state->linenr);2186return-128;2187}2188}21892190return offset + hdrsize + patchsize;2191}21922193static voidreverse_patches(struct patch *p)2194{2195for(; p; p = p->next) {2196struct fragment *frag = p->fragments;21972198SWAP(p->new_name, p->old_name);2199SWAP(p->new_mode, p->old_mode);2200SWAP(p->is_new, p->is_delete);2201SWAP(p->lines_added, p->lines_deleted);2202SWAP(p->old_sha1_prefix, p->new_sha1_prefix);22032204for(; frag; frag = frag->next) {2205SWAP(frag->newpos, frag->oldpos);2206SWAP(frag->newlines, frag->oldlines);2207}2208}2209}22102211static const char pluses[] =2212"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2213static const char minuses[]=2214"----------------------------------------------------------------------";22152216static voidshow_stats(struct apply_state *state,struct patch *patch)2217{2218struct strbuf qname = STRBUF_INIT;2219char*cp = patch->new_name ? patch->new_name : patch->old_name;2220int max, add, del;22212222quote_c_style(cp, &qname, NULL,0);22232224/*2225 * "scale" the filename2226 */2227 max = state->max_len;2228if(max >50)2229 max =50;22302231if(qname.len > max) {2232 cp =strchr(qname.buf + qname.len +3- max,'/');2233if(!cp)2234 cp = qname.buf + qname.len +3- max;2235strbuf_splice(&qname,0, cp - qname.buf,"...",3);2236}22372238if(patch->is_binary) {2239printf(" %-*s | Bin\n", max, qname.buf);2240strbuf_release(&qname);2241return;2242}22432244printf(" %-*s |", max, qname.buf);2245strbuf_release(&qname);22462247/*2248 * scale the add/delete2249 */2250 max = max + state->max_change >70?70- max : state->max_change;2251 add = patch->lines_added;2252 del = patch->lines_deleted;22532254if(state->max_change >0) {2255int total = ((add + del) * max + state->max_change /2) / state->max_change;2256 add = (add * max + state->max_change /2) / state->max_change;2257 del = total - add;2258}2259printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2260 add, pluses, del, minuses);2261}22622263static intread_old_data(struct stat *st,struct patch *patch,2264const char*path,struct strbuf *buf)2265{2266enum safe_crlf safe_crlf = patch->crlf_in_old ?2267 SAFE_CRLF_KEEP_CRLF : SAFE_CRLF_RENORMALIZE;2268switch(st->st_mode & S_IFMT) {2269case S_IFLNK:2270if(strbuf_readlink(buf, path, st->st_size) <0)2271returnerror(_("unable to read symlink%s"), path);2272return0;2273case S_IFREG:2274if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2275returnerror(_("unable to open or read%s"), path);2276/*2277 * "git apply" without "--index/--cached" should never look2278 * at the index; the target file may not have been added to2279 * the index yet, and we may not even be in any Git repository.2280 * Pass NULL to convert_to_git() to stress this; the function2281 * should never look at the index when explicit crlf option2282 * is given.2283 */2284convert_to_git(NULL, path, buf->buf, buf->len, buf, safe_crlf);2285return0;2286default:2287return-1;2288}2289}22902291/*2292 * Update the preimage, and the common lines in postimage,2293 * from buffer buf of length len. If postlen is 0 the postimage2294 * is updated in place, otherwise it's updated on a new buffer2295 * of length postlen2296 */22972298static voidupdate_pre_post_images(struct image *preimage,2299struct image *postimage,2300char*buf,2301size_t len,size_t postlen)2302{2303int i, ctx, reduced;2304char*new, *old, *fixed;2305struct image fixed_preimage;23062307/*2308 * Update the preimage with whitespace fixes. Note that we2309 * are not losing preimage->buf -- apply_one_fragment() will2310 * free "oldlines".2311 */2312prepare_image(&fixed_preimage, buf, len,1);2313assert(postlen2314? fixed_preimage.nr == preimage->nr2315: fixed_preimage.nr <= preimage->nr);2316for(i =0; i < fixed_preimage.nr; i++)2317 fixed_preimage.line[i].flag = preimage->line[i].flag;2318free(preimage->line_allocated);2319*preimage = fixed_preimage;23202321/*2322 * Adjust the common context lines in postimage. This can be2323 * done in-place when we are shrinking it with whitespace2324 * fixing, but needs a new buffer when ignoring whitespace or2325 * expanding leading tabs to spaces.2326 *2327 * We trust the caller to tell us if the update can be done2328 * in place (postlen==0) or not.2329 */2330 old = postimage->buf;2331if(postlen)2332new= postimage->buf =xmalloc(postlen);2333else2334new= old;2335 fixed = preimage->buf;23362337for(i = reduced = ctx =0; i < postimage->nr; i++) {2338size_t l_len = postimage->line[i].len;2339if(!(postimage->line[i].flag & LINE_COMMON)) {2340/* an added line -- no counterparts in preimage */2341memmove(new, old, l_len);2342 old += l_len;2343new+= l_len;2344continue;2345}23462347/* a common context -- skip it in the original postimage */2348 old += l_len;23492350/* and find the corresponding one in the fixed preimage */2351while(ctx < preimage->nr &&2352!(preimage->line[ctx].flag & LINE_COMMON)) {2353 fixed += preimage->line[ctx].len;2354 ctx++;2355}23562357/*2358 * preimage is expected to run out, if the caller2359 * fixed addition of trailing blank lines.2360 */2361if(preimage->nr <= ctx) {2362 reduced++;2363continue;2364}23652366/* and copy it in, while fixing the line length */2367 l_len = preimage->line[ctx].len;2368memcpy(new, fixed, l_len);2369new+= l_len;2370 fixed += l_len;2371 postimage->line[i].len = l_len;2372 ctx++;2373}23742375if(postlen2376? postlen <new- postimage->buf2377: postimage->len <new- postimage->buf)2378die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2379(int)postlen, (int) postimage->len, (int)(new- postimage->buf));23802381/* Fix the length of the whole thing */2382 postimage->len =new- postimage->buf;2383 postimage->nr -= reduced;2384}23852386static intline_by_line_fuzzy_match(struct image *img,2387struct image *preimage,2388struct image *postimage,2389unsigned longtry,2390int try_lno,2391int preimage_limit)2392{2393int i;2394size_t imgoff =0;2395size_t preoff =0;2396size_t postlen = postimage->len;2397size_t extra_chars;2398char*buf;2399char*preimage_eof;2400char*preimage_end;2401struct strbuf fixed;2402char*fixed_buf;2403size_t fixed_len;24042405for(i =0; i < preimage_limit; i++) {2406size_t prelen = preimage->line[i].len;2407size_t imglen = img->line[try_lno+i].len;24082409if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2410 preimage->buf + preoff, prelen))2411return0;2412if(preimage->line[i].flag & LINE_COMMON)2413 postlen += imglen - prelen;2414 imgoff += imglen;2415 preoff += prelen;2416}24172418/*2419 * Ok, the preimage matches with whitespace fuzz.2420 *2421 * imgoff now holds the true length of the target that2422 * matches the preimage before the end of the file.2423 *2424 * Count the number of characters in the preimage that fall2425 * beyond the end of the file and make sure that all of them2426 * are whitespace characters. (This can only happen if2427 * we are removing blank lines at the end of the file.)2428 */2429 buf = preimage_eof = preimage->buf + preoff;2430for( ; i < preimage->nr; i++)2431 preoff += preimage->line[i].len;2432 preimage_end = preimage->buf + preoff;2433for( ; buf < preimage_end; buf++)2434if(!isspace(*buf))2435return0;24362437/*2438 * Update the preimage and the common postimage context2439 * lines to use the same whitespace as the target.2440 * If whitespace is missing in the target (i.e.2441 * if the preimage extends beyond the end of the file),2442 * use the whitespace from the preimage.2443 */2444 extra_chars = preimage_end - preimage_eof;2445strbuf_init(&fixed, imgoff + extra_chars);2446strbuf_add(&fixed, img->buf +try, imgoff);2447strbuf_add(&fixed, preimage_eof, extra_chars);2448 fixed_buf =strbuf_detach(&fixed, &fixed_len);2449update_pre_post_images(preimage, postimage,2450 fixed_buf, fixed_len, postlen);2451return1;2452}24532454static intmatch_fragment(struct apply_state *state,2455struct image *img,2456struct image *preimage,2457struct image *postimage,2458unsigned longtry,2459int try_lno,2460unsigned ws_rule,2461int match_beginning,int match_end)2462{2463int i;2464char*fixed_buf, *buf, *orig, *target;2465struct strbuf fixed;2466size_t fixed_len, postlen;2467int preimage_limit;24682469if(preimage->nr + try_lno <= img->nr) {2470/*2471 * The hunk falls within the boundaries of img.2472 */2473 preimage_limit = preimage->nr;2474if(match_end && (preimage->nr + try_lno != img->nr))2475return0;2476}else if(state->ws_error_action == correct_ws_error &&2477(ws_rule & WS_BLANK_AT_EOF)) {2478/*2479 * This hunk extends beyond the end of img, and we are2480 * removing blank lines at the end of the file. This2481 * many lines from the beginning of the preimage must2482 * match with img, and the remainder of the preimage2483 * must be blank.2484 */2485 preimage_limit = img->nr - try_lno;2486}else{2487/*2488 * The hunk extends beyond the end of the img and2489 * we are not removing blanks at the end, so we2490 * should reject the hunk at this position.2491 */2492return0;2493}24942495if(match_beginning && try_lno)2496return0;24972498/* Quick hash check */2499for(i =0; i < preimage_limit; i++)2500if((img->line[try_lno + i].flag & LINE_PATCHED) ||2501(preimage->line[i].hash != img->line[try_lno + i].hash))2502return0;25032504if(preimage_limit == preimage->nr) {2505/*2506 * Do we have an exact match? If we were told to match2507 * at the end, size must be exactly at try+fragsize,2508 * otherwise try+fragsize must be still within the preimage,2509 * and either case, the old piece should match the preimage2510 * exactly.2511 */2512if((match_end2513? (try+ preimage->len == img->len)2514: (try+ preimage->len <= img->len)) &&2515!memcmp(img->buf +try, preimage->buf, preimage->len))2516return1;2517}else{2518/*2519 * The preimage extends beyond the end of img, so2520 * there cannot be an exact match.2521 *2522 * There must be one non-blank context line that match2523 * a line before the end of img.2524 */2525char*buf_end;25262527 buf = preimage->buf;2528 buf_end = buf;2529for(i =0; i < preimage_limit; i++)2530 buf_end += preimage->line[i].len;25312532for( ; buf < buf_end; buf++)2533if(!isspace(*buf))2534break;2535if(buf == buf_end)2536return0;2537}25382539/*2540 * No exact match. If we are ignoring whitespace, run a line-by-line2541 * fuzzy matching. We collect all the line length information because2542 * we need it to adjust whitespace if we match.2543 */2544if(state->ws_ignore_action == ignore_ws_change)2545returnline_by_line_fuzzy_match(img, preimage, postimage,2546try, try_lno, preimage_limit);25472548if(state->ws_error_action != correct_ws_error)2549return0;25502551/*2552 * The hunk does not apply byte-by-byte, but the hash says2553 * it might with whitespace fuzz. We weren't asked to2554 * ignore whitespace, we were asked to correct whitespace2555 * errors, so let's try matching after whitespace correction.2556 *2557 * While checking the preimage against the target, whitespace2558 * errors in both fixed, we count how large the corresponding2559 * postimage needs to be. The postimage prepared by2560 * apply_one_fragment() has whitespace errors fixed on added2561 * lines already, but the common lines were propagated as-is,2562 * which may become longer when their whitespace errors are2563 * fixed.2564 */25652566/* First count added lines in postimage */2567 postlen =0;2568for(i =0; i < postimage->nr; i++) {2569if(!(postimage->line[i].flag & LINE_COMMON))2570 postlen += postimage->line[i].len;2571}25722573/*2574 * The preimage may extend beyond the end of the file,2575 * but in this loop we will only handle the part of the2576 * preimage that falls within the file.2577 */2578strbuf_init(&fixed, preimage->len +1);2579 orig = preimage->buf;2580 target = img->buf +try;2581for(i =0; i < preimage_limit; i++) {2582size_t oldlen = preimage->line[i].len;2583size_t tgtlen = img->line[try_lno + i].len;2584size_t fixstart = fixed.len;2585struct strbuf tgtfix;2586int match;25872588/* Try fixing the line in the preimage */2589ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25902591/* Try fixing the line in the target */2592strbuf_init(&tgtfix, tgtlen);2593ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);25942595/*2596 * If they match, either the preimage was based on2597 * a version before our tree fixed whitespace breakage,2598 * or we are lacking a whitespace-fix patch the tree2599 * the preimage was based on already had (i.e. target2600 * has whitespace breakage, the preimage doesn't).2601 * In either case, we are fixing the whitespace breakages2602 * so we might as well take the fix together with their2603 * real change.2604 */2605 match = (tgtfix.len == fixed.len - fixstart &&2606!memcmp(tgtfix.buf, fixed.buf + fixstart,2607 fixed.len - fixstart));26082609/* Add the length if this is common with the postimage */2610if(preimage->line[i].flag & LINE_COMMON)2611 postlen += tgtfix.len;26122613strbuf_release(&tgtfix);2614if(!match)2615goto unmatch_exit;26162617 orig += oldlen;2618 target += tgtlen;2619}262026212622/*2623 * Now handle the lines in the preimage that falls beyond the2624 * end of the file (if any). They will only match if they are2625 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2626 * false).2627 */2628for( ; i < preimage->nr; i++) {2629size_t fixstart = fixed.len;/* start of the fixed preimage */2630size_t oldlen = preimage->line[i].len;2631int j;26322633/* Try fixing the line in the preimage */2634ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);26352636for(j = fixstart; j < fixed.len; j++)2637if(!isspace(fixed.buf[j]))2638goto unmatch_exit;26392640 orig += oldlen;2641}26422643/*2644 * Yes, the preimage is based on an older version that still2645 * has whitespace breakages unfixed, and fixing them makes the2646 * hunk match. Update the context lines in the postimage.2647 */2648 fixed_buf =strbuf_detach(&fixed, &fixed_len);2649if(postlen < postimage->len)2650 postlen =0;2651update_pre_post_images(preimage, postimage,2652 fixed_buf, fixed_len, postlen);2653return1;26542655 unmatch_exit:2656strbuf_release(&fixed);2657return0;2658}26592660static intfind_pos(struct apply_state *state,2661struct image *img,2662struct image *preimage,2663struct image *postimage,2664int line,2665unsigned ws_rule,2666int match_beginning,int match_end)2667{2668int i;2669unsigned long backwards, forwards,try;2670int backwards_lno, forwards_lno, try_lno;26712672/*2673 * If match_beginning or match_end is specified, there is no2674 * point starting from a wrong line that will never match and2675 * wander around and wait for a match at the specified end.2676 */2677if(match_beginning)2678 line =0;2679else if(match_end)2680 line = img->nr - preimage->nr;26812682/*2683 * Because the comparison is unsigned, the following test2684 * will also take care of a negative line number that can2685 * result when match_end and preimage is larger than the target.2686 */2687if((size_t) line > img->nr)2688 line = img->nr;26892690try=0;2691for(i =0; i < line; i++)2692try+= img->line[i].len;26932694/*2695 * There's probably some smart way to do this, but I'll leave2696 * that to the smart and beautiful people. I'm simple and stupid.2697 */2698 backwards =try;2699 backwards_lno = line;2700 forwards =try;2701 forwards_lno = line;2702 try_lno = line;27032704for(i =0; ; i++) {2705if(match_fragment(state, img, preimage, postimage,2706try, try_lno, ws_rule,2707 match_beginning, match_end))2708return try_lno;27092710 again:2711if(backwards_lno ==0&& forwards_lno == img->nr)2712break;27132714if(i &1) {2715if(backwards_lno ==0) {2716 i++;2717goto again;2718}2719 backwards_lno--;2720 backwards -= img->line[backwards_lno].len;2721try= backwards;2722 try_lno = backwards_lno;2723}else{2724if(forwards_lno == img->nr) {2725 i++;2726goto again;2727}2728 forwards += img->line[forwards_lno].len;2729 forwards_lno++;2730try= forwards;2731 try_lno = forwards_lno;2732}27332734}2735return-1;2736}27372738static voidremove_first_line(struct image *img)2739{2740 img->buf += img->line[0].len;2741 img->len -= img->line[0].len;2742 img->line++;2743 img->nr--;2744}27452746static voidremove_last_line(struct image *img)2747{2748 img->len -= img->line[--img->nr].len;2749}27502751/*2752 * The change from "preimage" and "postimage" has been found to2753 * apply at applied_pos (counts in line numbers) in "img".2754 * Update "img" to remove "preimage" and replace it with "postimage".2755 */2756static voidupdate_image(struct apply_state *state,2757struct image *img,2758int applied_pos,2759struct image *preimage,2760struct image *postimage)2761{2762/*2763 * remove the copy of preimage at offset in img2764 * and replace it with postimage2765 */2766int i, nr;2767size_t remove_count, insert_count, applied_at =0;2768char*result;2769int preimage_limit;27702771/*2772 * If we are removing blank lines at the end of img,2773 * the preimage may extend beyond the end.2774 * If that is the case, we must be careful only to2775 * remove the part of the preimage that falls within2776 * the boundaries of img. Initialize preimage_limit2777 * to the number of lines in the preimage that falls2778 * within the boundaries.2779 */2780 preimage_limit = preimage->nr;2781if(preimage_limit > img->nr - applied_pos)2782 preimage_limit = img->nr - applied_pos;27832784for(i =0; i < applied_pos; i++)2785 applied_at += img->line[i].len;27862787 remove_count =0;2788for(i =0; i < preimage_limit; i++)2789 remove_count += img->line[applied_pos + i].len;2790 insert_count = postimage->len;27912792/* Adjust the contents */2793 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2794memcpy(result, img->buf, applied_at);2795memcpy(result + applied_at, postimage->buf, postimage->len);2796memcpy(result + applied_at + postimage->len,2797 img->buf + (applied_at + remove_count),2798 img->len - (applied_at + remove_count));2799free(img->buf);2800 img->buf = result;2801 img->len += insert_count - remove_count;2802 result[img->len] ='\0';28032804/* Adjust the line table */2805 nr = img->nr + postimage->nr - preimage_limit;2806if(preimage_limit < postimage->nr) {2807/*2808 * NOTE: this knows that we never call remove_first_line()2809 * on anything other than pre/post image.2810 */2811REALLOC_ARRAY(img->line, nr);2812 img->line_allocated = img->line;2813}2814if(preimage_limit != postimage->nr)2815MOVE_ARRAY(img->line + applied_pos + postimage->nr,2816 img->line + applied_pos + preimage_limit,2817 img->nr - (applied_pos + preimage_limit));2818COPY_ARRAY(img->line + applied_pos, postimage->line, postimage->nr);2819if(!state->allow_overlap)2820for(i =0; i < postimage->nr; i++)2821 img->line[applied_pos + i].flag |= LINE_PATCHED;2822 img->nr = nr;2823}28242825/*2826 * Use the patch-hunk text in "frag" to prepare two images (preimage and2827 * postimage) for the hunk. Find lines that match "preimage" in "img" and2828 * replace the part of "img" with "postimage" text.2829 */2830static intapply_one_fragment(struct apply_state *state,2831struct image *img,struct fragment *frag,2832int inaccurate_eof,unsigned ws_rule,2833int nth_fragment)2834{2835int match_beginning, match_end;2836const char*patch = frag->patch;2837int size = frag->size;2838char*old, *oldlines;2839struct strbuf newlines;2840int new_blank_lines_at_end =0;2841int found_new_blank_lines_at_end =0;2842int hunk_linenr = frag->linenr;2843unsigned long leading, trailing;2844int pos, applied_pos;2845struct image preimage;2846struct image postimage;28472848memset(&preimage,0,sizeof(preimage));2849memset(&postimage,0,sizeof(postimage));2850 oldlines =xmalloc(size);2851strbuf_init(&newlines, size);28522853 old = oldlines;2854while(size >0) {2855char first;2856int len =linelen(patch, size);2857int plen;2858int added_blank_line =0;2859int is_blank_context =0;2860size_t start;28612862if(!len)2863break;28642865/*2866 * "plen" is how much of the line we should use for2867 * the actual patch data. Normally we just remove the2868 * first character on the line, but if the line is2869 * followed by "\ No newline", then we also remove the2870 * last one (which is the newline, of course).2871 */2872 plen = len -1;2873if(len < size && patch[len] =='\\')2874 plen--;2875 first = *patch;2876if(state->apply_in_reverse) {2877if(first =='-')2878 first ='+';2879else if(first =='+')2880 first ='-';2881}28822883switch(first) {2884case'\n':2885/* Newer GNU diff, empty context line */2886if(plen <0)2887/* ... followed by '\No newline'; nothing */2888break;2889*old++ ='\n';2890strbuf_addch(&newlines,'\n');2891add_line_info(&preimage,"\n",1, LINE_COMMON);2892add_line_info(&postimage,"\n",1, LINE_COMMON);2893 is_blank_context =1;2894break;2895case' ':2896if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2897ws_blank_line(patch +1, plen, ws_rule))2898 is_blank_context =1;2899/* fallthrough */2900case'-':2901memcpy(old, patch +1, plen);2902add_line_info(&preimage, old, plen,2903(first ==' '? LINE_COMMON :0));2904 old += plen;2905if(first =='-')2906break;2907/* fallthrough */2908case'+':2909/* --no-add does not add new lines */2910if(first =='+'&& state->no_add)2911break;29122913 start = newlines.len;2914if(first !='+'||2915!state->whitespace_error ||2916 state->ws_error_action != correct_ws_error) {2917strbuf_add(&newlines, patch +1, plen);2918}2919else{2920ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2921}2922add_line_info(&postimage, newlines.buf + start, newlines.len - start,2923(first =='+'?0: LINE_COMMON));2924if(first =='+'&&2925(ws_rule & WS_BLANK_AT_EOF) &&2926ws_blank_line(patch +1, plen, ws_rule))2927 added_blank_line =1;2928break;2929case'@':case'\\':2930/* Ignore it, we already handled it */2931break;2932default:2933if(state->apply_verbosity > verbosity_normal)2934error(_("invalid start of line: '%c'"), first);2935 applied_pos = -1;2936goto out;2937}2938if(added_blank_line) {2939if(!new_blank_lines_at_end)2940 found_new_blank_lines_at_end = hunk_linenr;2941 new_blank_lines_at_end++;2942}2943else if(is_blank_context)2944;2945else2946 new_blank_lines_at_end =0;2947 patch += len;2948 size -= len;2949 hunk_linenr++;2950}2951if(inaccurate_eof &&2952 old > oldlines && old[-1] =='\n'&&2953 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2954 old--;2955strbuf_setlen(&newlines, newlines.len -1);2956}29572958 leading = frag->leading;2959 trailing = frag->trailing;29602961/*2962 * A hunk to change lines at the beginning would begin with2963 * @@ -1,L +N,M @@2964 * but we need to be careful. -U0 that inserts before the second2965 * line also has this pattern.2966 *2967 * And a hunk to add to an empty file would begin with2968 * @@ -0,0 +N,M @@2969 *2970 * In other words, a hunk that is (frag->oldpos <= 1) with or2971 * without leading context must match at the beginning.2972 */2973 match_beginning = (!frag->oldpos ||2974(frag->oldpos ==1&& !state->unidiff_zero));29752976/*2977 * A hunk without trailing lines must match at the end.2978 * However, we simply cannot tell if a hunk must match end2979 * from the lack of trailing lines if the patch was generated2980 * with unidiff without any context.2981 */2982 match_end = !state->unidiff_zero && !trailing;29832984 pos = frag->newpos ? (frag->newpos -1) :0;2985 preimage.buf = oldlines;2986 preimage.len = old - oldlines;2987 postimage.buf = newlines.buf;2988 postimage.len = newlines.len;2989 preimage.line = preimage.line_allocated;2990 postimage.line = postimage.line_allocated;29912992for(;;) {29932994 applied_pos =find_pos(state, img, &preimage, &postimage, pos,2995 ws_rule, match_beginning, match_end);29962997if(applied_pos >=0)2998break;29993000/* Am I at my context limits? */3001if((leading <= state->p_context) && (trailing <= state->p_context))3002break;3003if(match_beginning || match_end) {3004 match_beginning = match_end =0;3005continue;3006}30073008/*3009 * Reduce the number of context lines; reduce both3010 * leading and trailing if they are equal otherwise3011 * just reduce the larger context.3012 */3013if(leading >= trailing) {3014remove_first_line(&preimage);3015remove_first_line(&postimage);3016 pos--;3017 leading--;3018}3019if(trailing > leading) {3020remove_last_line(&preimage);3021remove_last_line(&postimage);3022 trailing--;3023}3024}30253026if(applied_pos >=0) {3027if(new_blank_lines_at_end &&3028 preimage.nr + applied_pos >= img->nr &&3029(ws_rule & WS_BLANK_AT_EOF) &&3030 state->ws_error_action != nowarn_ws_error) {3031record_ws_error(state, WS_BLANK_AT_EOF,"+",1,3032 found_new_blank_lines_at_end);3033if(state->ws_error_action == correct_ws_error) {3034while(new_blank_lines_at_end--)3035remove_last_line(&postimage);3036}3037/*3038 * We would want to prevent write_out_results()3039 * from taking place in apply_patch() that follows3040 * the callchain led us here, which is:3041 * apply_patch->check_patch_list->check_patch->3042 * apply_data->apply_fragments->apply_one_fragment3043 */3044if(state->ws_error_action == die_on_ws_error)3045 state->apply =0;3046}30473048if(state->apply_verbosity > verbosity_normal && applied_pos != pos) {3049int offset = applied_pos - pos;3050if(state->apply_in_reverse)3051 offset =0- offset;3052fprintf_ln(stderr,3053Q_("Hunk #%dsucceeded at%d(offset%dline).",3054"Hunk #%dsucceeded at%d(offset%dlines).",3055 offset),3056 nth_fragment, applied_pos +1, offset);3057}30583059/*3060 * Warn if it was necessary to reduce the number3061 * of context lines.3062 */3063if((leading != frag->leading ||3064 trailing != frag->trailing) && state->apply_verbosity > verbosity_silent)3065fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"3066" to apply fragment at%d"),3067 leading, trailing, applied_pos+1);3068update_image(state, img, applied_pos, &preimage, &postimage);3069}else{3070if(state->apply_verbosity > verbosity_normal)3071error(_("while searching for:\n%.*s"),3072(int)(old - oldlines), oldlines);3073}30743075out:3076free(oldlines);3077strbuf_release(&newlines);3078free(preimage.line_allocated);3079free(postimage.line_allocated);30803081return(applied_pos <0);3082}30833084static intapply_binary_fragment(struct apply_state *state,3085struct image *img,3086struct patch *patch)3087{3088struct fragment *fragment = patch->fragments;3089unsigned long len;3090void*dst;30913092if(!fragment)3093returnerror(_("missing binary patch data for '%s'"),3094 patch->new_name ?3095 patch->new_name :3096 patch->old_name);30973098/* Binary patch is irreversible without the optional second hunk */3099if(state->apply_in_reverse) {3100if(!fragment->next)3101returnerror(_("cannot reverse-apply a binary patch "3102"without the reverse hunk to '%s'"),3103 patch->new_name3104? patch->new_name : patch->old_name);3105 fragment = fragment->next;3106}3107switch(fragment->binary_patch_method) {3108case BINARY_DELTA_DEFLATED:3109 dst =patch_delta(img->buf, img->len, fragment->patch,3110 fragment->size, &len);3111if(!dst)3112return-1;3113clear_image(img);3114 img->buf = dst;3115 img->len = len;3116return0;3117case BINARY_LITERAL_DEFLATED:3118clear_image(img);3119 img->len = fragment->size;3120 img->buf =xmemdupz(fragment->patch, img->len);3121return0;3122}3123return-1;3124}31253126/*3127 * Replace "img" with the result of applying the binary patch.3128 * The binary patch data itself in patch->fragment is still kept3129 * but the preimage prepared by the caller in "img" is freed here3130 * or in the helper function apply_binary_fragment() this calls.3131 */3132static intapply_binary(struct apply_state *state,3133struct image *img,3134struct patch *patch)3135{3136const char*name = patch->old_name ? patch->old_name : patch->new_name;3137struct object_id oid;31383139/*3140 * For safety, we require patch index line to contain3141 * full 40-byte textual SHA1 for old and new, at least for now.3142 */3143if(strlen(patch->old_sha1_prefix) !=40||3144strlen(patch->new_sha1_prefix) !=40||3145get_oid_hex(patch->old_sha1_prefix, &oid) ||3146get_oid_hex(patch->new_sha1_prefix, &oid))3147returnerror(_("cannot apply binary patch to '%s' "3148"without full index line"), name);31493150if(patch->old_name) {3151/*3152 * See if the old one matches what the patch3153 * applies to.3154 */3155hash_sha1_file(img->buf, img->len, blob_type, oid.hash);3156if(strcmp(oid_to_hex(&oid), patch->old_sha1_prefix))3157returnerror(_("the patch applies to '%s' (%s), "3158"which does not match the "3159"current contents."),3160 name,oid_to_hex(&oid));3161}3162else{3163/* Otherwise, the old one must be empty. */3164if(img->len)3165returnerror(_("the patch applies to an empty "3166"'%s' but it is not empty"), name);3167}31683169get_oid_hex(patch->new_sha1_prefix, &oid);3170if(is_null_oid(&oid)) {3171clear_image(img);3172return0;/* deletion patch */3173}31743175if(has_sha1_file(oid.hash)) {3176/* We already have the postimage */3177enum object_type type;3178unsigned long size;3179char*result;31803181 result =read_sha1_file(oid.hash, &type, &size);3182if(!result)3183returnerror(_("the necessary postimage%sfor "3184"'%s' cannot be read"),3185 patch->new_sha1_prefix, name);3186clear_image(img);3187 img->buf = result;3188 img->len = size;3189}else{3190/*3191 * We have verified buf matches the preimage;3192 * apply the patch data to it, which is stored3193 * in the patch->fragments->{patch,size}.3194 */3195if(apply_binary_fragment(state, img, patch))3196returnerror(_("binary patch does not apply to '%s'"),3197 name);31983199/* verify that the result matches */3200hash_sha1_file(img->buf, img->len, blob_type, oid.hash);3201if(strcmp(oid_to_hex(&oid), patch->new_sha1_prefix))3202returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3203 name, patch->new_sha1_prefix,oid_to_hex(&oid));3204}32053206return0;3207}32083209static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3210{3211struct fragment *frag = patch->fragments;3212const char*name = patch->old_name ? patch->old_name : patch->new_name;3213unsigned ws_rule = patch->ws_rule;3214unsigned inaccurate_eof = patch->inaccurate_eof;3215int nth =0;32163217if(patch->is_binary)3218returnapply_binary(state, img, patch);32193220while(frag) {3221 nth++;3222if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3223error(_("patch failed:%s:%ld"), name, frag->oldpos);3224if(!state->apply_with_reject)3225return-1;3226 frag->rejected =1;3227}3228 frag = frag->next;3229}3230return0;3231}32323233static intread_blob_object(struct strbuf *buf,const struct object_id *oid,unsigned mode)3234{3235if(S_ISGITLINK(mode)) {3236strbuf_grow(buf,100);3237strbuf_addf(buf,"Subproject commit%s\n",oid_to_hex(oid));3238}else{3239enum object_type type;3240unsigned long sz;3241char*result;32423243 result =read_sha1_file(oid->hash, &type, &sz);3244if(!result)3245return-1;3246/* XXX read_sha1_file NUL-terminates */3247strbuf_attach(buf, result, sz, sz +1);3248}3249return0;3250}32513252static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3253{3254if(!ce)3255return0;3256returnread_blob_object(buf, &ce->oid, ce->ce_mode);3257}32583259static struct patch *in_fn_table(struct apply_state *state,const char*name)3260{3261struct string_list_item *item;32623263if(name == NULL)3264return NULL;32653266 item =string_list_lookup(&state->fn_table, name);3267if(item != NULL)3268return(struct patch *)item->util;32693270return NULL;3271}32723273/*3274 * item->util in the filename table records the status of the path.3275 * Usually it points at a patch (whose result records the contents3276 * of it after applying it), but it could be PATH_WAS_DELETED for a3277 * path that a previously applied patch has already removed, or3278 * PATH_TO_BE_DELETED for a path that a later patch would remove.3279 *3280 * The latter is needed to deal with a case where two paths A and B3281 * are swapped by first renaming A to B and then renaming B to A;3282 * moving A to B should not be prevented due to presence of B as we3283 * will remove it in a later patch.3284 */3285#define PATH_TO_BE_DELETED ((struct patch *) -2)3286#define PATH_WAS_DELETED ((struct patch *) -1)32873288static intto_be_deleted(struct patch *patch)3289{3290return patch == PATH_TO_BE_DELETED;3291}32923293static intwas_deleted(struct patch *patch)3294{3295return patch == PATH_WAS_DELETED;3296}32973298static voidadd_to_fn_table(struct apply_state *state,struct patch *patch)3299{3300struct string_list_item *item;33013302/*3303 * Always add new_name unless patch is a deletion3304 * This should cover the cases for normal diffs,3305 * file creations and copies3306 */3307if(patch->new_name != NULL) {3308 item =string_list_insert(&state->fn_table, patch->new_name);3309 item->util = patch;3310}33113312/*3313 * store a failure on rename/deletion cases because3314 * later chunks shouldn't patch old names3315 */3316if((patch->new_name == NULL) || (patch->is_rename)) {3317 item =string_list_insert(&state->fn_table, patch->old_name);3318 item->util = PATH_WAS_DELETED;3319}3320}33213322static voidprepare_fn_table(struct apply_state *state,struct patch *patch)3323{3324/*3325 * store information about incoming file deletion3326 */3327while(patch) {3328if((patch->new_name == NULL) || (patch->is_rename)) {3329struct string_list_item *item;3330 item =string_list_insert(&state->fn_table, patch->old_name);3331 item->util = PATH_TO_BE_DELETED;3332}3333 patch = patch->next;3334}3335}33363337static intcheckout_target(struct index_state *istate,3338struct cache_entry *ce,struct stat *st)3339{3340struct checkout costate = CHECKOUT_INIT;33413342 costate.refresh_cache =1;3343 costate.istate = istate;3344if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3345returnerror(_("cannot checkout%s"), ce->name);3346return0;3347}33483349static struct patch *previous_patch(struct apply_state *state,3350struct patch *patch,3351int*gone)3352{3353struct patch *previous;33543355*gone =0;3356if(patch->is_copy || patch->is_rename)3357return NULL;/* "git" patches do not depend on the order */33583359 previous =in_fn_table(state, patch->old_name);3360if(!previous)3361return NULL;33623363if(to_be_deleted(previous))3364return NULL;/* the deletion hasn't happened yet */33653366if(was_deleted(previous))3367*gone =1;33683369return previous;3370}33713372static intverify_index_match(const struct cache_entry *ce,struct stat *st)3373{3374if(S_ISGITLINK(ce->ce_mode)) {3375if(!S_ISDIR(st->st_mode))3376return-1;3377return0;3378}3379returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3380}33813382#define SUBMODULE_PATCH_WITHOUT_INDEX 133833384static intload_patch_target(struct apply_state *state,3385struct strbuf *buf,3386const struct cache_entry *ce,3387struct stat *st,3388struct patch *patch,3389const char*name,3390unsigned expected_mode)3391{3392if(state->cached || state->check_index) {3393if(read_file_or_gitlink(ce, buf))3394returnerror(_("failed to read%s"), name);3395}else if(name) {3396if(S_ISGITLINK(expected_mode)) {3397if(ce)3398returnread_file_or_gitlink(ce, buf);3399else3400return SUBMODULE_PATCH_WITHOUT_INDEX;3401}else if(has_symlink_leading_path(name,strlen(name))) {3402returnerror(_("reading from '%s' beyond a symbolic link"), name);3403}else{3404if(read_old_data(st, patch, name, buf))3405returnerror(_("failed to read%s"), name);3406}3407}3408return0;3409}34103411/*3412 * We are about to apply "patch"; populate the "image" with the3413 * current version we have, from the working tree or from the index,3414 * depending on the situation e.g. --cached/--index. If we are3415 * applying a non-git patch that incrementally updates the tree,3416 * we read from the result of a previous diff.3417 */3418static intload_preimage(struct apply_state *state,3419struct image *image,3420struct patch *patch,struct stat *st,3421const struct cache_entry *ce)3422{3423struct strbuf buf = STRBUF_INIT;3424size_t len;3425char*img;3426struct patch *previous;3427int status;34283429 previous =previous_patch(state, patch, &status);3430if(status)3431returnerror(_("path%shas been renamed/deleted"),3432 patch->old_name);3433if(previous) {3434/* We have a patched copy in memory; use that. */3435strbuf_add(&buf, previous->result, previous->resultsize);3436}else{3437 status =load_patch_target(state, &buf, ce, st, patch,3438 patch->old_name, patch->old_mode);3439if(status <0)3440return status;3441else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3442/*3443 * There is no way to apply subproject3444 * patch without looking at the index.3445 * NEEDSWORK: shouldn't this be flagged3446 * as an error???3447 */3448free_fragment_list(patch->fragments);3449 patch->fragments = NULL;3450}else if(status) {3451returnerror(_("failed to read%s"), patch->old_name);3452}3453}34543455 img =strbuf_detach(&buf, &len);3456prepare_image(image, img, len, !patch->is_binary);3457return0;3458}34593460static intthree_way_merge(struct image *image,3461char*path,3462const struct object_id *base,3463const struct object_id *ours,3464const struct object_id *theirs)3465{3466 mmfile_t base_file, our_file, their_file;3467 mmbuffer_t result = { NULL };3468int status;34693470read_mmblob(&base_file, base);3471read_mmblob(&our_file, ours);3472read_mmblob(&their_file, theirs);3473 status =ll_merge(&result, path,3474&base_file,"base",3475&our_file,"ours",3476&their_file,"theirs", NULL);3477free(base_file.ptr);3478free(our_file.ptr);3479free(their_file.ptr);3480if(status <0|| !result.ptr) {3481free(result.ptr);3482return-1;3483}3484clear_image(image);3485 image->buf = result.ptr;3486 image->len = result.size;34873488return status;3489}34903491/*3492 * When directly falling back to add/add three-way merge, we read from3493 * the current contents of the new_name. In no cases other than that3494 * this function will be called.3495 */3496static intload_current(struct apply_state *state,3497struct image *image,3498struct patch *patch)3499{3500struct strbuf buf = STRBUF_INIT;3501int status, pos;3502size_t len;3503char*img;3504struct stat st;3505struct cache_entry *ce;3506char*name = patch->new_name;3507unsigned mode = patch->new_mode;35083509if(!patch->is_new)3510die("BUG: patch to%sis not a creation", patch->old_name);35113512 pos =cache_name_pos(name,strlen(name));3513if(pos <0)3514returnerror(_("%s: does not exist in index"), name);3515 ce = active_cache[pos];3516if(lstat(name, &st)) {3517if(errno != ENOENT)3518returnerror_errno("%s", name);3519if(checkout_target(&the_index, ce, &st))3520return-1;3521}3522if(verify_index_match(ce, &st))3523returnerror(_("%s: does not match index"), name);35243525 status =load_patch_target(state, &buf, ce, &st, patch, name, mode);3526if(status <0)3527return status;3528else if(status)3529return-1;3530 img =strbuf_detach(&buf, &len);3531prepare_image(image, img, len, !patch->is_binary);3532return0;3533}35343535static inttry_threeway(struct apply_state *state,3536struct image *image,3537struct patch *patch,3538struct stat *st,3539const struct cache_entry *ce)3540{3541struct object_id pre_oid, post_oid, our_oid;3542struct strbuf buf = STRBUF_INIT;3543size_t len;3544int status;3545char*img;3546struct image tmp_image;35473548/* No point falling back to 3-way merge in these cases */3549if(patch->is_delete ||3550S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3551return-1;35523553/* Preimage the patch was prepared for */3554if(patch->is_new)3555write_sha1_file("",0, blob_type, pre_oid.hash);3556else if(get_oid(patch->old_sha1_prefix, &pre_oid) ||3557read_blob_object(&buf, &pre_oid, patch->old_mode))3558returnerror(_("repository lacks the necessary blob to fall back on 3-way merge."));35593560if(state->apply_verbosity > verbosity_silent)3561fprintf(stderr,_("Falling back to three-way merge...\n"));35623563 img =strbuf_detach(&buf, &len);3564prepare_image(&tmp_image, img, len,1);3565/* Apply the patch to get the post image */3566if(apply_fragments(state, &tmp_image, patch) <0) {3567clear_image(&tmp_image);3568return-1;3569}3570/* post_oid is theirs */3571write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_oid.hash);3572clear_image(&tmp_image);35733574/* our_oid is ours */3575if(patch->is_new) {3576if(load_current(state, &tmp_image, patch))3577returnerror(_("cannot read the current contents of '%s'"),3578 patch->new_name);3579}else{3580if(load_preimage(state, &tmp_image, patch, st, ce))3581returnerror(_("cannot read the current contents of '%s'"),3582 patch->old_name);3583}3584write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_oid.hash);3585clear_image(&tmp_image);35863587/* in-core three-way merge between post and our using pre as base */3588 status =three_way_merge(image, patch->new_name,3589&pre_oid, &our_oid, &post_oid);3590if(status <0) {3591if(state->apply_verbosity > verbosity_silent)3592fprintf(stderr,3593_("Failed to fall back on three-way merge...\n"));3594return status;3595}35963597if(status) {3598 patch->conflicted_threeway =1;3599if(patch->is_new)3600oidclr(&patch->threeway_stage[0]);3601else3602oidcpy(&patch->threeway_stage[0], &pre_oid);3603oidcpy(&patch->threeway_stage[1], &our_oid);3604oidcpy(&patch->threeway_stage[2], &post_oid);3605if(state->apply_verbosity > verbosity_silent)3606fprintf(stderr,3607_("Applied patch to '%s' with conflicts.\n"),3608 patch->new_name);3609}else{3610if(state->apply_verbosity > verbosity_silent)3611fprintf(stderr,3612_("Applied patch to '%s' cleanly.\n"),3613 patch->new_name);3614}3615return0;3616}36173618static intapply_data(struct apply_state *state,struct patch *patch,3619struct stat *st,const struct cache_entry *ce)3620{3621struct image image;36223623if(load_preimage(state, &image, patch, st, ce) <0)3624return-1;36253626if(patch->direct_to_threeway ||3627apply_fragments(state, &image, patch) <0) {3628/* Note: with --reject, apply_fragments() returns 0 */3629if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3630return-1;3631}3632 patch->result = image.buf;3633 patch->resultsize = image.len;3634add_to_fn_table(state, patch);3635free(image.line_allocated);36363637if(0< patch->is_delete && patch->resultsize)3638returnerror(_("removal patch leaves file contents"));36393640return0;3641}36423643/*3644 * If "patch" that we are looking at modifies or deletes what we have,3645 * we would want it not to lose any local modification we have, either3646 * in the working tree or in the index.3647 *3648 * This also decides if a non-git patch is a creation patch or a3649 * modification to an existing empty file. We do not check the state3650 * of the current tree for a creation patch in this function; the caller3651 * check_patch() separately makes sure (and errors out otherwise) that3652 * the path the patch creates does not exist in the current tree.3653 */3654static intcheck_preimage(struct apply_state *state,3655struct patch *patch,3656struct cache_entry **ce,3657struct stat *st)3658{3659const char*old_name = patch->old_name;3660struct patch *previous = NULL;3661int stat_ret =0, status;3662unsigned st_mode =0;36633664if(!old_name)3665return0;36663667assert(patch->is_new <=0);3668 previous =previous_patch(state, patch, &status);36693670if(status)3671returnerror(_("path%shas been renamed/deleted"), old_name);3672if(previous) {3673 st_mode = previous->new_mode;3674}else if(!state->cached) {3675 stat_ret =lstat(old_name, st);3676if(stat_ret && errno != ENOENT)3677returnerror_errno("%s", old_name);3678}36793680if(state->check_index && !previous) {3681int pos =cache_name_pos(old_name,strlen(old_name));3682if(pos <0) {3683if(patch->is_new <0)3684goto is_new;3685returnerror(_("%s: does not exist in index"), old_name);3686}3687*ce = active_cache[pos];3688if(stat_ret <0) {3689if(checkout_target(&the_index, *ce, st))3690return-1;3691}3692if(!state->cached &&verify_index_match(*ce, st))3693returnerror(_("%s: does not match index"), old_name);3694if(state->cached)3695 st_mode = (*ce)->ce_mode;3696}else if(stat_ret <0) {3697if(patch->is_new <0)3698goto is_new;3699returnerror_errno("%s", old_name);3700}37013702if(!state->cached && !previous)3703 st_mode =ce_mode_from_stat(*ce, st->st_mode);37043705if(patch->is_new <0)3706 patch->is_new =0;3707if(!patch->old_mode)3708 patch->old_mode = st_mode;3709if((st_mode ^ patch->old_mode) & S_IFMT)3710returnerror(_("%s: wrong type"), old_name);3711if(st_mode != patch->old_mode)3712warning(_("%shas type%o, expected%o"),3713 old_name, st_mode, patch->old_mode);3714if(!patch->new_mode && !patch->is_delete)3715 patch->new_mode = st_mode;3716return0;37173718 is_new:3719 patch->is_new =1;3720 patch->is_delete =0;3721FREE_AND_NULL(patch->old_name);3722return0;3723}372437253726#define EXISTS_IN_INDEX 13727#define EXISTS_IN_WORKTREE 237283729static intcheck_to_create(struct apply_state *state,3730const char*new_name,3731int ok_if_exists)3732{3733struct stat nst;37343735if(state->check_index &&3736cache_name_pos(new_name,strlen(new_name)) >=0&&3737!ok_if_exists)3738return EXISTS_IN_INDEX;3739if(state->cached)3740return0;37413742if(!lstat(new_name, &nst)) {3743if(S_ISDIR(nst.st_mode) || ok_if_exists)3744return0;3745/*3746 * A leading component of new_name might be a symlink3747 * that is going to be removed with this patch, but3748 * still pointing at somewhere that has the path.3749 * In such a case, path "new_name" does not exist as3750 * far as git is concerned.3751 */3752if(has_symlink_leading_path(new_name,strlen(new_name)))3753return0;37543755return EXISTS_IN_WORKTREE;3756}else if(!is_missing_file_error(errno)) {3757returnerror_errno("%s", new_name);3758}3759return0;3760}37613762static uintptr_tregister_symlink_changes(struct apply_state *state,3763const char*path,3764uintptr_t what)3765{3766struct string_list_item *ent;37673768 ent =string_list_lookup(&state->symlink_changes, path);3769if(!ent) {3770 ent =string_list_insert(&state->symlink_changes, path);3771 ent->util = (void*)0;3772}3773 ent->util = (void*)(what | ((uintptr_t)ent->util));3774return(uintptr_t)ent->util;3775}37763777static uintptr_tcheck_symlink_changes(struct apply_state *state,const char*path)3778{3779struct string_list_item *ent;37803781 ent =string_list_lookup(&state->symlink_changes, path);3782if(!ent)3783return0;3784return(uintptr_t)ent->util;3785}37863787static voidprepare_symlink_changes(struct apply_state *state,struct patch *patch)3788{3789for( ; patch; patch = patch->next) {3790if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3791(patch->is_rename || patch->is_delete))3792/* the symlink at patch->old_name is removed */3793register_symlink_changes(state, patch->old_name, APPLY_SYMLINK_GOES_AWAY);37943795if(patch->new_name &&S_ISLNK(patch->new_mode))3796/* the symlink at patch->new_name is created or remains */3797register_symlink_changes(state, patch->new_name, APPLY_SYMLINK_IN_RESULT);3798}3799}38003801static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3802{3803do{3804unsigned int change;38053806while(--name->len && name->buf[name->len] !='/')3807;/* scan backwards */3808if(!name->len)3809break;3810 name->buf[name->len] ='\0';3811 change =check_symlink_changes(state, name->buf);3812if(change & APPLY_SYMLINK_IN_RESULT)3813return1;3814if(change & APPLY_SYMLINK_GOES_AWAY)3815/*3816 * This cannot be "return 0", because we may3817 * see a new one created at a higher level.3818 */3819continue;38203821/* otherwise, check the preimage */3822if(state->check_index) {3823struct cache_entry *ce;38243825 ce =cache_file_exists(name->buf, name->len, ignore_case);3826if(ce &&S_ISLNK(ce->ce_mode))3827return1;3828}else{3829struct stat st;3830if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3831return1;3832}3833}while(1);3834return0;3835}38363837static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3838{3839int ret;3840struct strbuf name = STRBUF_INIT;38413842assert(*name_ !='\0');3843strbuf_addstr(&name, name_);3844 ret =path_is_beyond_symlink_1(state, &name);3845strbuf_release(&name);38463847return ret;3848}38493850static intcheck_unsafe_path(struct patch *patch)3851{3852const char*old_name = NULL;3853const char*new_name = NULL;3854if(patch->is_delete)3855 old_name = patch->old_name;3856else if(!patch->is_new && !patch->is_copy)3857 old_name = patch->old_name;3858if(!patch->is_delete)3859 new_name = patch->new_name;38603861if(old_name && !verify_path(old_name))3862returnerror(_("invalid path '%s'"), old_name);3863if(new_name && !verify_path(new_name))3864returnerror(_("invalid path '%s'"), new_name);3865return0;3866}38673868/*3869 * Check and apply the patch in-core; leave the result in patch->result3870 * for the caller to write it out to the final destination.3871 */3872static intcheck_patch(struct apply_state *state,struct patch *patch)3873{3874struct stat st;3875const char*old_name = patch->old_name;3876const char*new_name = patch->new_name;3877const char*name = old_name ? old_name : new_name;3878struct cache_entry *ce = NULL;3879struct patch *tpatch;3880int ok_if_exists;3881int status;38823883 patch->rejected =1;/* we will drop this after we succeed */38843885 status =check_preimage(state, patch, &ce, &st);3886if(status)3887return status;3888 old_name = patch->old_name;38893890/*3891 * A type-change diff is always split into a patch to delete3892 * old, immediately followed by a patch to create new (see3893 * diff.c::run_diff()); in such a case it is Ok that the entry3894 * to be deleted by the previous patch is still in the working3895 * tree and in the index.3896 *3897 * A patch to swap-rename between A and B would first rename A3898 * to B and then rename B to A. While applying the first one,3899 * the presence of B should not stop A from getting renamed to3900 * B; ask to_be_deleted() about the later rename. Removal of3901 * B and rename from A to B is handled the same way by asking3902 * was_deleted().3903 */3904if((tpatch =in_fn_table(state, new_name)) &&3905(was_deleted(tpatch) ||to_be_deleted(tpatch)))3906 ok_if_exists =1;3907else3908 ok_if_exists =0;39093910if(new_name &&3911((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3912int err =check_to_create(state, new_name, ok_if_exists);39133914if(err && state->threeway) {3915 patch->direct_to_threeway =1;3916}else switch(err) {3917case0:3918break;/* happy */3919case EXISTS_IN_INDEX:3920returnerror(_("%s: already exists in index"), new_name);3921break;3922case EXISTS_IN_WORKTREE:3923returnerror(_("%s: already exists in working directory"),3924 new_name);3925default:3926return err;3927}39283929if(!patch->new_mode) {3930if(0< patch->is_new)3931 patch->new_mode = S_IFREG |0644;3932else3933 patch->new_mode = patch->old_mode;3934}3935}39363937if(new_name && old_name) {3938int same = !strcmp(old_name, new_name);3939if(!patch->new_mode)3940 patch->new_mode = patch->old_mode;3941if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3942if(same)3943returnerror(_("new mode (%o) of%sdoes not "3944"match old mode (%o)"),3945 patch->new_mode, new_name,3946 patch->old_mode);3947else3948returnerror(_("new mode (%o) of%sdoes not "3949"match old mode (%o) of%s"),3950 patch->new_mode, new_name,3951 patch->old_mode, old_name);3952}3953}39543955if(!state->unsafe_paths &&check_unsafe_path(patch))3956return-128;39573958/*3959 * An attempt to read from or delete a path that is beyond a3960 * symbolic link will be prevented by load_patch_target() that3961 * is called at the beginning of apply_data() so we do not3962 * have to worry about a patch marked with "is_delete" bit3963 * here. We however need to make sure that the patch result3964 * is not deposited to a path that is beyond a symbolic link3965 * here.3966 */3967if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3968returnerror(_("affected file '%s' is beyond a symbolic link"),3969 patch->new_name);39703971if(apply_data(state, patch, &st, ce) <0)3972returnerror(_("%s: patch does not apply"), name);3973 patch->rejected =0;3974return0;3975}39763977static intcheck_patch_list(struct apply_state *state,struct patch *patch)3978{3979int err =0;39803981prepare_symlink_changes(state, patch);3982prepare_fn_table(state, patch);3983while(patch) {3984int res;3985if(state->apply_verbosity > verbosity_normal)3986say_patch_name(stderr,3987_("Checking patch%s..."), patch);3988 res =check_patch(state, patch);3989if(res == -128)3990return-128;3991 err |= res;3992 patch = patch->next;3993}3994return err;3995}39963997static intread_apply_cache(struct apply_state *state)3998{3999if(state->index_file)4000returnread_cache_from(state->index_file);4001else4002returnread_cache();4003}40044005/* This function tries to read the object name from the current index */4006static intget_current_oid(struct apply_state *state,const char*path,4007struct object_id *oid)4008{4009int pos;40104011if(read_apply_cache(state) <0)4012return-1;4013 pos =cache_name_pos(path,strlen(path));4014if(pos <0)4015return-1;4016oidcpy(oid, &active_cache[pos]->oid);4017return0;4018}40194020static intpreimage_oid_in_gitlink_patch(struct patch *p,struct object_id *oid)4021{4022/*4023 * A usable gitlink patch has only one fragment (hunk) that looks like:4024 * @@ -1 +1 @@4025 * -Subproject commit <old sha1>4026 * +Subproject commit <new sha1>4027 * or4028 * @@ -1 +0,0 @@4029 * -Subproject commit <old sha1>4030 * for a removal patch.4031 */4032struct fragment *hunk = p->fragments;4033static const char heading[] ="-Subproject commit ";4034char*preimage;40354036if(/* does the patch have only one hunk? */4037 hunk && !hunk->next &&4038/* is its preimage one line? */4039 hunk->oldpos ==1&& hunk->oldlines ==1&&4040/* does preimage begin with the heading? */4041(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&4042starts_with(++preimage, heading) &&4043/* does it record full SHA-1? */4044!get_oid_hex(preimage +sizeof(heading) -1, oid) &&4045 preimage[sizeof(heading) + GIT_SHA1_HEXSZ -1] =='\n'&&4046/* does the abbreviated name on the index line agree with it? */4047starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))4048return0;/* it all looks fine */40494050/* we may have full object name on the index line */4051returnget_oid_hex(p->old_sha1_prefix, oid);4052}40534054/* Build an index that contains the just the files needed for a 3way merge */4055static intbuild_fake_ancestor(struct apply_state *state,struct patch *list)4056{4057struct patch *patch;4058struct index_state result = { NULL };4059static struct lock_file lock;4060int res;40614062/* Once we start supporting the reverse patch, it may be4063 * worth showing the new sha1 prefix, but until then...4064 */4065for(patch = list; patch; patch = patch->next) {4066struct object_id oid;4067struct cache_entry *ce;4068const char*name;40694070 name = patch->old_name ? patch->old_name : patch->new_name;4071if(0< patch->is_new)4072continue;40734074if(S_ISGITLINK(patch->old_mode)) {4075if(!preimage_oid_in_gitlink_patch(patch, &oid))4076;/* ok, the textual part looks sane */4077else4078returnerror(_("sha1 information is lacking or "4079"useless for submodule%s"), name);4080}else if(!get_oid_blob(patch->old_sha1_prefix, &oid)) {4081;/* ok */4082}else if(!patch->lines_added && !patch->lines_deleted) {4083/* mode-only change: update the current */4084if(get_current_oid(state, patch->old_name, &oid))4085returnerror(_("mode change for%s, which is not "4086"in current HEAD"), name);4087}else4088returnerror(_("sha1 information is lacking or useless "4089"(%s)."), name);40904091 ce =make_cache_entry(patch->old_mode, oid.hash, name,0,0);4092if(!ce)4093returnerror(_("make_cache_entry failed for path '%s'"),4094 name);4095if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) {4096free(ce);4097returnerror(_("could not add%sto temporary index"),4098 name);4099}4100}41014102hold_lock_file_for_update(&lock, state->fake_ancestor, LOCK_DIE_ON_ERROR);4103 res =write_locked_index(&result, &lock, COMMIT_LOCK);4104discard_index(&result);41054106if(res)4107returnerror(_("could not write temporary index to%s"),4108 state->fake_ancestor);41094110return0;4111}41124113static voidstat_patch_list(struct apply_state *state,struct patch *patch)4114{4115int files, adds, dels;41164117for(files = adds = dels =0; patch ; patch = patch->next) {4118 files++;4119 adds += patch->lines_added;4120 dels += patch->lines_deleted;4121show_stats(state, patch);4122}41234124print_stat_summary(stdout, files, adds, dels);4125}41264127static voidnumstat_patch_list(struct apply_state *state,4128struct patch *patch)4129{4130for( ; patch; patch = patch->next) {4131const char*name;4132 name = patch->new_name ? patch->new_name : patch->old_name;4133if(patch->is_binary)4134printf("-\t-\t");4135else4136printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4137write_name_quoted(name, stdout, state->line_termination);4138}4139}41404141static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4142{4143if(mode)4144printf("%smode%06o%s\n", newdelete, mode, name);4145else4146printf("%s %s\n", newdelete, name);4147}41484149static voidshow_mode_change(struct patch *p,int show_name)4150{4151if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4152if(show_name)4153printf(" mode change%06o =>%06o%s\n",4154 p->old_mode, p->new_mode, p->new_name);4155else4156printf(" mode change%06o =>%06o\n",4157 p->old_mode, p->new_mode);4158}4159}41604161static voidshow_rename_copy(struct patch *p)4162{4163const char*renamecopy = p->is_rename ?"rename":"copy";4164const char*old, *new;41654166/* Find common prefix */4167 old = p->old_name;4168new= p->new_name;4169while(1) {4170const char*slash_old, *slash_new;4171 slash_old =strchr(old,'/');4172 slash_new =strchr(new,'/');4173if(!slash_old ||4174!slash_new ||4175 slash_old - old != slash_new -new||4176memcmp(old,new, slash_new -new))4177break;4178 old = slash_old +1;4179new= slash_new +1;4180}4181/* p->old_name thru old is the common prefix, and old and new4182 * through the end of names are renames4183 */4184if(old != p->old_name)4185printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4186(int)(old - p->old_name), p->old_name,4187 old,new, p->score);4188else4189printf("%s %s=>%s(%d%%)\n", renamecopy,4190 p->old_name, p->new_name, p->score);4191show_mode_change(p,0);4192}41934194static voidsummary_patch_list(struct patch *patch)4195{4196struct patch *p;41974198for(p = patch; p; p = p->next) {4199if(p->is_new)4200show_file_mode_name("create", p->new_mode, p->new_name);4201else if(p->is_delete)4202show_file_mode_name("delete", p->old_mode, p->old_name);4203else{4204if(p->is_rename || p->is_copy)4205show_rename_copy(p);4206else{4207if(p->score) {4208printf(" rewrite%s(%d%%)\n",4209 p->new_name, p->score);4210show_mode_change(p,0);4211}4212else4213show_mode_change(p,1);4214}4215}4216}4217}42184219static voidpatch_stats(struct apply_state *state,struct patch *patch)4220{4221int lines = patch->lines_added + patch->lines_deleted;42224223if(lines > state->max_change)4224 state->max_change = lines;4225if(patch->old_name) {4226int len =quote_c_style(patch->old_name, NULL, NULL,0);4227if(!len)4228 len =strlen(patch->old_name);4229if(len > state->max_len)4230 state->max_len = len;4231}4232if(patch->new_name) {4233int len =quote_c_style(patch->new_name, NULL, NULL,0);4234if(!len)4235 len =strlen(patch->new_name);4236if(len > state->max_len)4237 state->max_len = len;4238}4239}42404241static intremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4242{4243if(state->update_index) {4244if(remove_file_from_cache(patch->old_name) <0)4245returnerror(_("unable to remove%sfrom index"), patch->old_name);4246}4247if(!state->cached) {4248if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4249remove_path(patch->old_name);4250}4251}4252return0;4253}42544255static intadd_index_file(struct apply_state *state,4256const char*path,4257unsigned mode,4258void*buf,4259unsigned long size)4260{4261struct stat st;4262struct cache_entry *ce;4263int namelen =strlen(path);4264unsigned ce_size =cache_entry_size(namelen);42654266if(!state->update_index)4267return0;42684269 ce =xcalloc(1, ce_size);4270memcpy(ce->name, path, namelen);4271 ce->ce_mode =create_ce_mode(mode);4272 ce->ce_flags =create_ce_flags(0);4273 ce->ce_namelen = namelen;4274if(S_ISGITLINK(mode)) {4275const char*s;42764277if(!skip_prefix(buf,"Subproject commit ", &s) ||4278get_oid_hex(s, &ce->oid)) {4279free(ce);4280returnerror(_("corrupt patch for submodule%s"), path);4281}4282}else{4283if(!state->cached) {4284if(lstat(path, &st) <0) {4285free(ce);4286returnerror_errno(_("unable to stat newly "4287"created file '%s'"),4288 path);4289}4290fill_stat_cache_info(ce, &st);4291}4292if(write_sha1_file(buf, size, blob_type, ce->oid.hash) <0) {4293free(ce);4294returnerror(_("unable to create backing store "4295"for newly created file%s"), path);4296}4297}4298if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0) {4299free(ce);4300returnerror(_("unable to add cache entry for%s"), path);4301}43024303return0;4304}43054306/*4307 * Returns:4308 * -1 if an unrecoverable error happened4309 * 0 if everything went well4310 * 1 if a recoverable error happened4311 */4312static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4313{4314int fd, res;4315struct strbuf nbuf = STRBUF_INIT;43164317if(S_ISGITLINK(mode)) {4318struct stat st;4319if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4320return0;4321return!!mkdir(path,0777);4322}43234324if(has_symlinks &&S_ISLNK(mode))4325/* Although buf:size is counted string, it also is NUL4326 * terminated.4327 */4328return!!symlink(buf, path);43294330 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4331if(fd <0)4332return1;43334334if(convert_to_working_tree(path, buf, size, &nbuf)) {4335 size = nbuf.len;4336 buf = nbuf.buf;4337}43384339 res =write_in_full(fd, buf, size) <0;4340if(res)4341error_errno(_("failed to write to '%s'"), path);4342strbuf_release(&nbuf);43434344if(close(fd) <0&& !res)4345returnerror_errno(_("closing file '%s'"), path);43464347return res ? -1:0;4348}43494350/*4351 * We optimistically assume that the directories exist,4352 * which is true 99% of the time anyway. If they don't,4353 * we create them and try again.4354 *4355 * Returns:4356 * -1 on error4357 * 0 otherwise4358 */4359static intcreate_one_file(struct apply_state *state,4360char*path,4361unsigned mode,4362const char*buf,4363unsigned long size)4364{4365int res;43664367if(state->cached)4368return0;43694370 res =try_create_file(path, mode, buf, size);4371if(res <0)4372return-1;4373if(!res)4374return0;43754376if(errno == ENOENT) {4377if(safe_create_leading_directories(path))4378return0;4379 res =try_create_file(path, mode, buf, size);4380if(res <0)4381return-1;4382if(!res)4383return0;4384}43854386if(errno == EEXIST || errno == EACCES) {4387/* We may be trying to create a file where a directory4388 * used to be.4389 */4390struct stat st;4391if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4392 errno = EEXIST;4393}43944395if(errno == EEXIST) {4396unsigned int nr =getpid();43974398for(;;) {4399char newpath[PATH_MAX];4400mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4401 res =try_create_file(newpath, mode, buf, size);4402if(res <0)4403return-1;4404if(!res) {4405if(!rename(newpath, path))4406return0;4407unlink_or_warn(newpath);4408break;4409}4410if(errno != EEXIST)4411break;4412++nr;4413}4414}4415returnerror_errno(_("unable to write file '%s' mode%o"),4416 path, mode);4417}44184419static intadd_conflicted_stages_file(struct apply_state *state,4420struct patch *patch)4421{4422int stage, namelen;4423unsigned ce_size, mode;4424struct cache_entry *ce;44254426if(!state->update_index)4427return0;4428 namelen =strlen(patch->new_name);4429 ce_size =cache_entry_size(namelen);4430 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);44314432remove_file_from_cache(patch->new_name);4433for(stage =1; stage <4; stage++) {4434if(is_null_oid(&patch->threeway_stage[stage -1]))4435continue;4436 ce =xcalloc(1, ce_size);4437memcpy(ce->name, patch->new_name, namelen);4438 ce->ce_mode =create_ce_mode(mode);4439 ce->ce_flags =create_ce_flags(stage);4440 ce->ce_namelen = namelen;4441oidcpy(&ce->oid, &patch->threeway_stage[stage -1]);4442if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0) {4443free(ce);4444returnerror(_("unable to add cache entry for%s"),4445 patch->new_name);4446}4447}44484449return0;4450}44514452static intcreate_file(struct apply_state *state,struct patch *patch)4453{4454char*path = patch->new_name;4455unsigned mode = patch->new_mode;4456unsigned long size = patch->resultsize;4457char*buf = patch->result;44584459if(!mode)4460 mode = S_IFREG |0644;4461if(create_one_file(state, path, mode, buf, size))4462return-1;44634464if(patch->conflicted_threeway)4465returnadd_conflicted_stages_file(state, patch);4466else4467returnadd_index_file(state, path, mode, buf, size);4468}44694470/* phase zero is to remove, phase one is to create */4471static intwrite_out_one_result(struct apply_state *state,4472struct patch *patch,4473int phase)4474{4475if(patch->is_delete >0) {4476if(phase ==0)4477returnremove_file(state, patch,1);4478return0;4479}4480if(patch->is_new >0|| patch->is_copy) {4481if(phase ==1)4482returncreate_file(state, patch);4483return0;4484}4485/*4486 * Rename or modification boils down to the same4487 * thing: remove the old, write the new4488 */4489if(phase ==0)4490returnremove_file(state, patch, patch->is_rename);4491if(phase ==1)4492returncreate_file(state, patch);4493return0;4494}44954496static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4497{4498FILE*rej;4499char namebuf[PATH_MAX];4500struct fragment *frag;4501int cnt =0;4502struct strbuf sb = STRBUF_INIT;45034504for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4505if(!frag->rejected)4506continue;4507 cnt++;4508}45094510if(!cnt) {4511if(state->apply_verbosity > verbosity_normal)4512say_patch_name(stderr,4513_("Applied patch%scleanly."), patch);4514return0;4515}45164517/* This should not happen, because a removal patch that leaves4518 * contents are marked "rejected" at the patch level.4519 */4520if(!patch->new_name)4521die(_("internal error"));45224523/* Say this even without --verbose */4524strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4525"Applying patch %%swith%drejects...",4526 cnt),4527 cnt);4528if(state->apply_verbosity > verbosity_silent)4529say_patch_name(stderr, sb.buf, patch);4530strbuf_release(&sb);45314532 cnt =strlen(patch->new_name);4533if(ARRAY_SIZE(namebuf) <= cnt +5) {4534 cnt =ARRAY_SIZE(namebuf) -5;4535warning(_("truncating .rej filename to %.*s.rej"),4536 cnt -1, patch->new_name);4537}4538memcpy(namebuf, patch->new_name, cnt);4539memcpy(namebuf + cnt,".rej",5);45404541 rej =fopen(namebuf,"w");4542if(!rej)4543returnerror_errno(_("cannot open%s"), namebuf);45444545/* Normal git tools never deal with .rej, so do not pretend4546 * this is a git patch by saying --git or giving extended4547 * headers. While at it, maybe please "kompare" that wants4548 * the trailing TAB and some garbage at the end of line ;-).4549 */4550fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4551 patch->new_name, patch->new_name);4552for(cnt =1, frag = patch->fragments;4553 frag;4554 cnt++, frag = frag->next) {4555if(!frag->rejected) {4556if(state->apply_verbosity > verbosity_silent)4557fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4558continue;4559}4560if(state->apply_verbosity > verbosity_silent)4561fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4562fprintf(rej,"%.*s", frag->size, frag->patch);4563if(frag->patch[frag->size-1] !='\n')4564fputc('\n', rej);4565}4566fclose(rej);4567return-1;4568}45694570/*4571 * Returns:4572 * -1 if an error happened4573 * 0 if the patch applied cleanly4574 * 1 if the patch did not apply cleanly4575 */4576static intwrite_out_results(struct apply_state *state,struct patch *list)4577{4578int phase;4579int errs =0;4580struct patch *l;4581struct string_list cpath = STRING_LIST_INIT_DUP;45824583for(phase =0; phase <2; phase++) {4584 l = list;4585while(l) {4586if(l->rejected)4587 errs =1;4588else{4589if(write_out_one_result(state, l, phase)) {4590string_list_clear(&cpath,0);4591return-1;4592}4593if(phase ==1) {4594if(write_out_one_reject(state, l))4595 errs =1;4596if(l->conflicted_threeway) {4597string_list_append(&cpath, l->new_name);4598 errs =1;4599}4600}4601}4602 l = l->next;4603}4604}46054606if(cpath.nr) {4607struct string_list_item *item;46084609string_list_sort(&cpath);4610if(state->apply_verbosity > verbosity_silent) {4611for_each_string_list_item(item, &cpath)4612fprintf(stderr,"U%s\n", item->string);4613}4614string_list_clear(&cpath,0);46154616rerere(0);4617}46184619return errs;4620}46214622/*4623 * Try to apply a patch.4624 *4625 * Returns:4626 * -128 if a bad error happened (like patch unreadable)4627 * -1 if patch did not apply and user cannot deal with it4628 * 0 if the patch applied4629 * 1 if the patch did not apply but user might fix it4630 */4631static intapply_patch(struct apply_state *state,4632int fd,4633const char*filename,4634int options)4635{4636size_t offset;4637struct strbuf buf = STRBUF_INIT;/* owns the patch text */4638struct patch *list = NULL, **listp = &list;4639int skipped_patch =0;4640int res =0;46414642 state->patch_input_file = filename;4643if(read_patch_file(&buf, fd) <0)4644return-128;4645 offset =0;4646while(offset < buf.len) {4647struct patch *patch;4648int nr;46494650 patch =xcalloc(1,sizeof(*patch));4651 patch->inaccurate_eof = !!(options & APPLY_OPT_INACCURATE_EOF);4652 patch->recount = !!(options & APPLY_OPT_RECOUNT);4653 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4654if(nr <0) {4655free_patch(patch);4656if(nr == -128) {4657 res = -128;4658goto end;4659}4660break;4661}4662if(state->apply_in_reverse)4663reverse_patches(patch);4664if(use_patch(state, patch)) {4665patch_stats(state, patch);4666*listp = patch;4667 listp = &patch->next;4668}4669else{4670if(state->apply_verbosity > verbosity_normal)4671say_patch_name(stderr,_("Skipped patch '%s'."), patch);4672free_patch(patch);4673 skipped_patch++;4674}4675 offset += nr;4676}46774678if(!list && !skipped_patch) {4679error(_("unrecognized input"));4680 res = -128;4681goto end;4682}46834684if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4685 state->apply =0;46864687 state->update_index = state->check_index && state->apply;4688if(state->update_index && !is_lock_file_locked(&state->lock_file)) {4689if(state->index_file)4690hold_lock_file_for_update(&state->lock_file,4691 state->index_file,4692 LOCK_DIE_ON_ERROR);4693else4694hold_locked_index(&state->lock_file, LOCK_DIE_ON_ERROR);4695}46964697if(state->check_index &&read_apply_cache(state) <0) {4698error(_("unable to read index file"));4699 res = -128;4700goto end;4701}47024703if(state->check || state->apply) {4704int r =check_patch_list(state, list);4705if(r == -128) {4706 res = -128;4707goto end;4708}4709if(r <0&& !state->apply_with_reject) {4710 res = -1;4711goto end;4712}4713}47144715if(state->apply) {4716int write_res =write_out_results(state, list);4717if(write_res <0) {4718 res = -128;4719goto end;4720}4721if(write_res >0) {4722/* with --3way, we still need to write the index out */4723 res = state->apply_with_reject ? -1:1;4724goto end;4725}4726}47274728if(state->fake_ancestor &&4729build_fake_ancestor(state, list)) {4730 res = -128;4731goto end;4732}47334734if(state->diffstat && state->apply_verbosity > verbosity_silent)4735stat_patch_list(state, list);47364737if(state->numstat && state->apply_verbosity > verbosity_silent)4738numstat_patch_list(state, list);47394740if(state->summary && state->apply_verbosity > verbosity_silent)4741summary_patch_list(list);47424743end:4744free_patch_list(list);4745strbuf_release(&buf);4746string_list_clear(&state->fn_table,0);4747return res;4748}47494750static intapply_option_parse_exclude(const struct option *opt,4751const char*arg,int unset)4752{4753struct apply_state *state = opt->value;4754add_name_limit(state, arg,1);4755return0;4756}47574758static intapply_option_parse_include(const struct option *opt,4759const char*arg,int unset)4760{4761struct apply_state *state = opt->value;4762add_name_limit(state, arg,0);4763 state->has_include =1;4764return0;4765}47664767static intapply_option_parse_p(const struct option *opt,4768const char*arg,4769int unset)4770{4771struct apply_state *state = opt->value;4772 state->p_value =atoi(arg);4773 state->p_value_known =1;4774return0;4775}47764777static intapply_option_parse_space_change(const struct option *opt,4778const char*arg,int unset)4779{4780struct apply_state *state = opt->value;4781if(unset)4782 state->ws_ignore_action = ignore_ws_none;4783else4784 state->ws_ignore_action = ignore_ws_change;4785return0;4786}47874788static intapply_option_parse_whitespace(const struct option *opt,4789const char*arg,int unset)4790{4791struct apply_state *state = opt->value;4792 state->whitespace_option = arg;4793if(parse_whitespace_option(state, arg))4794exit(1);4795return0;4796}47974798static intapply_option_parse_directory(const struct option *opt,4799const char*arg,int unset)4800{4801struct apply_state *state = opt->value;4802strbuf_reset(&state->root);4803strbuf_addstr(&state->root, arg);4804strbuf_complete(&state->root,'/');4805return0;4806}48074808intapply_all_patches(struct apply_state *state,4809int argc,4810const char**argv,4811int options)4812{4813int i;4814int res;4815int errs =0;4816int read_stdin =1;48174818for(i =0; i < argc; i++) {4819const char*arg = argv[i];4820char*to_free = NULL;4821int fd;48224823if(!strcmp(arg,"-")) {4824 res =apply_patch(state,0,"<stdin>", options);4825if(res <0)4826goto end;4827 errs |= res;4828 read_stdin =0;4829continue;4830}else4831 arg = to_free =prefix_filename(state->prefix, arg);48324833 fd =open(arg, O_RDONLY);4834if(fd <0) {4835error(_("can't open patch '%s':%s"), arg,strerror(errno));4836 res = -128;4837free(to_free);4838goto end;4839}4840 read_stdin =0;4841set_default_whitespace_mode(state);4842 res =apply_patch(state, fd, arg, options);4843close(fd);4844free(to_free);4845if(res <0)4846goto end;4847 errs |= res;4848}4849set_default_whitespace_mode(state);4850if(read_stdin) {4851 res =apply_patch(state,0,"<stdin>", options);4852if(res <0)4853goto end;4854 errs |= res;4855}48564857if(state->whitespace_error) {4858if(state->squelch_whitespace_errors &&4859 state->squelch_whitespace_errors < state->whitespace_error) {4860int squelched =4861 state->whitespace_error - state->squelch_whitespace_errors;4862warning(Q_("squelched%dwhitespace error",4863"squelched%dwhitespace errors",4864 squelched),4865 squelched);4866}4867if(state->ws_error_action == die_on_ws_error) {4868error(Q_("%dline adds whitespace errors.",4869"%dlines add whitespace errors.",4870 state->whitespace_error),4871 state->whitespace_error);4872 res = -128;4873goto end;4874}4875if(state->applied_after_fixing_ws && state->apply)4876warning(Q_("%dline applied after"4877" fixing whitespace errors.",4878"%dlines applied after"4879" fixing whitespace errors.",4880 state->applied_after_fixing_ws),4881 state->applied_after_fixing_ws);4882else if(state->whitespace_error)4883warning(Q_("%dline adds whitespace errors.",4884"%dlines add whitespace errors.",4885 state->whitespace_error),4886 state->whitespace_error);4887}48884889if(state->update_index) {4890 res =write_locked_index(&the_index, &state->lock_file, COMMIT_LOCK);4891if(res) {4892error(_("Unable to write new index file"));4893 res = -128;4894goto end;4895}4896}48974898 res = !!errs;48994900end:4901rollback_lock_file(&state->lock_file);49024903if(state->apply_verbosity <= verbosity_silent) {4904set_error_routine(state->saved_error_routine);4905set_warn_routine(state->saved_warn_routine);4906}49074908if(res > -1)4909return res;4910return(res == -1?1:128);4911}49124913intapply_parse_options(int argc,const char**argv,4914struct apply_state *state,4915int*force_apply,int*options,4916const char*const*apply_usage)4917{4918struct option builtin_apply_options[] = {4919{ OPTION_CALLBACK,0,"exclude", state,N_("path"),4920N_("don't apply changes matching the given path"),49210, apply_option_parse_exclude },4922{ OPTION_CALLBACK,0,"include", state,N_("path"),4923N_("apply changes matching the given path"),49240, apply_option_parse_include },4925{ OPTION_CALLBACK,'p', NULL, state,N_("num"),4926N_("remove <num> leading slashes from traditional diff paths"),49270, apply_option_parse_p },4928OPT_BOOL(0,"no-add", &state->no_add,4929N_("ignore additions made by the patch")),4930OPT_BOOL(0,"stat", &state->diffstat,4931N_("instead of applying the patch, output diffstat for the input")),4932OPT_NOOP_NOARG(0,"allow-binary-replacement"),4933OPT_NOOP_NOARG(0,"binary"),4934OPT_BOOL(0,"numstat", &state->numstat,4935N_("show number of added and deleted lines in decimal notation")),4936OPT_BOOL(0,"summary", &state->summary,4937N_("instead of applying the patch, output a summary for the input")),4938OPT_BOOL(0,"check", &state->check,4939N_("instead of applying the patch, see if the patch is applicable")),4940OPT_BOOL(0,"index", &state->check_index,4941N_("make sure the patch is applicable to the current index")),4942OPT_BOOL(0,"cached", &state->cached,4943N_("apply a patch without touching the working tree")),4944OPT_BOOL(0,"unsafe-paths", &state->unsafe_paths,4945N_("accept a patch that touches outside the working area")),4946OPT_BOOL(0,"apply", force_apply,4947N_("also apply the patch (use with --stat/--summary/--check)")),4948OPT_BOOL('3',"3way", &state->threeway,4949N_("attempt three-way merge if a patch does not apply")),4950OPT_FILENAME(0,"build-fake-ancestor", &state->fake_ancestor,4951N_("build a temporary index based on embedded index information")),4952/* Think twice before adding "--nul" synonym to this */4953OPT_SET_INT('z', NULL, &state->line_termination,4954N_("paths are separated with NUL character"),'\0'),4955OPT_INTEGER('C', NULL, &state->p_context,4956N_("ensure at least <n> lines of context match")),4957{ OPTION_CALLBACK,0,"whitespace", state,N_("action"),4958N_("detect new or modified lines that have whitespace errors"),49590, apply_option_parse_whitespace },4960{ OPTION_CALLBACK,0,"ignore-space-change", state, NULL,4961N_("ignore changes in whitespace when finding context"),4962 PARSE_OPT_NOARG, apply_option_parse_space_change },4963{ OPTION_CALLBACK,0,"ignore-whitespace", state, NULL,4964N_("ignore changes in whitespace when finding context"),4965 PARSE_OPT_NOARG, apply_option_parse_space_change },4966OPT_BOOL('R',"reverse", &state->apply_in_reverse,4967N_("apply the patch in reverse")),4968OPT_BOOL(0,"unidiff-zero", &state->unidiff_zero,4969N_("don't expect at least one line of context")),4970OPT_BOOL(0,"reject", &state->apply_with_reject,4971N_("leave the rejected hunks in corresponding *.rej files")),4972OPT_BOOL(0,"allow-overlap", &state->allow_overlap,4973N_("allow overlapping hunks")),4974OPT__VERBOSE(&state->apply_verbosity,N_("be verbose")),4975OPT_BIT(0,"inaccurate-eof", options,4976N_("tolerate incorrectly detected missing new-line at the end of file"),4977 APPLY_OPT_INACCURATE_EOF),4978OPT_BIT(0,"recount", options,4979N_("do not trust the line counts in the hunk headers"),4980 APPLY_OPT_RECOUNT),4981{ OPTION_CALLBACK,0,"directory", state,N_("root"),4982N_("prepend <root> to all filenames"),49830, apply_option_parse_directory },4984OPT_END()4985};49864987returnparse_options(argc, argv, state->prefix, builtin_apply_options, apply_usage,0);4988}