1/* 2 * apply.c 3 * 4 * Copyright (C) Linus Torvalds, 2005 5 * 6 * This applies patches on top of some (arbitrary) version of the SCM. 7 * 8 */ 9 10#include"cache.h" 11#include"blob.h" 12#include"delta.h" 13#include"diff.h" 14#include"dir.h" 15#include"xdiff-interface.h" 16#include"ll-merge.h" 17#include"lockfile.h" 18#include"parse-options.h" 19#include"quote.h" 20#include"rerere.h" 21#include"apply.h" 22 23static voidgit_apply_config(void) 24{ 25git_config_get_string_const("apply.whitespace", &apply_default_whitespace); 26git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace); 27git_config(git_default_config, NULL); 28} 29 30intparse_whitespace_option(struct apply_state *state,const char*option) 31{ 32if(!option) { 33 state->ws_error_action = warn_on_ws_error; 34return0; 35} 36if(!strcmp(option,"warn")) { 37 state->ws_error_action = warn_on_ws_error; 38return0; 39} 40if(!strcmp(option,"nowarn")) { 41 state->ws_error_action = nowarn_ws_error; 42return0; 43} 44if(!strcmp(option,"error")) { 45 state->ws_error_action = die_on_ws_error; 46return0; 47} 48if(!strcmp(option,"error-all")) { 49 state->ws_error_action = die_on_ws_error; 50 state->squelch_whitespace_errors =0; 51return0; 52} 53if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 54 state->ws_error_action = correct_ws_error; 55return0; 56} 57returnerror(_("unrecognized whitespace option '%s'"), option); 58} 59 60intparse_ignorewhitespace_option(struct apply_state *state, 61const char*option) 62{ 63if(!option || !strcmp(option,"no") || 64!strcmp(option,"false") || !strcmp(option,"never") || 65!strcmp(option,"none")) { 66 state->ws_ignore_action = ignore_ws_none; 67return0; 68} 69if(!strcmp(option,"change")) { 70 state->ws_ignore_action = ignore_ws_change; 71return0; 72} 73returnerror(_("unrecognized whitespace ignore option '%s'"), option); 74} 75 76intinit_apply_state(struct apply_state *state, 77const char*prefix, 78struct lock_file *lock_file) 79{ 80memset(state,0,sizeof(*state)); 81 state->prefix = prefix; 82 state->prefix_length = state->prefix ?strlen(state->prefix) :0; 83 state->lock_file = lock_file; 84 state->newfd = -1; 85 state->apply =1; 86 state->line_termination ='\n'; 87 state->p_value =1; 88 state->p_context = UINT_MAX; 89 state->squelch_whitespace_errors =5; 90 state->ws_error_action = warn_on_ws_error; 91 state->ws_ignore_action = ignore_ws_none; 92 state->linenr =1; 93string_list_init(&state->fn_table,0); 94string_list_init(&state->limit_by_name,0); 95string_list_init(&state->symlink_changes,0); 96strbuf_init(&state->root,0); 97 98git_apply_config(); 99if(apply_default_whitespace &&parse_whitespace_option(state, apply_default_whitespace)) 100return-1; 101if(apply_default_ignorewhitespace &&parse_ignorewhitespace_option(state, apply_default_ignorewhitespace)) 102return-1; 103return0; 104} 105 106voidclear_apply_state(struct apply_state *state) 107{ 108string_list_clear(&state->limit_by_name,0); 109string_list_clear(&state->symlink_changes,0); 110strbuf_release(&state->root); 111 112/* &state->fn_table is cleared at the end of apply_patch() */ 113} 114 115intcheck_apply_state(struct apply_state *state,int force_apply) 116{ 117int is_not_gitdir = !startup_info->have_repository; 118 119if(state->apply_with_reject && state->threeway) 120returnerror("--reject and --3way cannot be used together."); 121if(state->cached && state->threeway) 122returnerror("--cached and --3way cannot be used together."); 123if(state->threeway) { 124if(is_not_gitdir) 125returnerror(_("--3way outside a repository")); 126 state->check_index =1; 127} 128if(state->apply_with_reject) 129 state->apply = state->apply_verbosely =1; 130if(!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor)) 131 state->apply =0; 132if(state->check_index && is_not_gitdir) 133returnerror(_("--index outside a repository")); 134if(state->cached) { 135if(is_not_gitdir) 136returnerror(_("--cached outside a repository")); 137 state->check_index =1; 138} 139if(state->check_index) 140 state->unsafe_paths =0; 141if(!state->lock_file) 142returnerror("BUG: state->lock_file should not be NULL"); 143 144return0; 145} 146 147static voidset_default_whitespace_mode(struct apply_state *state) 148{ 149if(!state->whitespace_option && !apply_default_whitespace) 150 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 151} 152 153/* 154 * This represents one "hunk" from a patch, starting with 155 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 156 * patch text is pointed at by patch, and its byte length 157 * is stored in size. leading and trailing are the number 158 * of context lines. 159 */ 160struct fragment { 161unsigned long leading, trailing; 162unsigned long oldpos, oldlines; 163unsigned long newpos, newlines; 164/* 165 * 'patch' is usually borrowed from buf in apply_patch(), 166 * but some codepaths store an allocated buffer. 167 */ 168const char*patch; 169unsigned free_patch:1, 170 rejected:1; 171int size; 172int linenr; 173struct fragment *next; 174}; 175 176/* 177 * When dealing with a binary patch, we reuse "leading" field 178 * to store the type of the binary hunk, either deflated "delta" 179 * or deflated "literal". 180 */ 181#define binary_patch_method leading 182#define BINARY_DELTA_DEFLATED 1 183#define BINARY_LITERAL_DEFLATED 2 184 185/* 186 * This represents a "patch" to a file, both metainfo changes 187 * such as creation/deletion, filemode and content changes represented 188 * as a series of fragments. 189 */ 190struct patch { 191char*new_name, *old_name, *def_name; 192unsigned int old_mode, new_mode; 193int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 194int rejected; 195unsigned ws_rule; 196int lines_added, lines_deleted; 197int score; 198unsigned int is_toplevel_relative:1; 199unsigned int inaccurate_eof:1; 200unsigned int is_binary:1; 201unsigned int is_copy:1; 202unsigned int is_rename:1; 203unsigned int recount:1; 204unsigned int conflicted_threeway:1; 205unsigned int direct_to_threeway:1; 206struct fragment *fragments; 207char*result; 208size_t resultsize; 209char old_sha1_prefix[41]; 210char new_sha1_prefix[41]; 211struct patch *next; 212 213/* three-way fallback result */ 214struct object_id threeway_stage[3]; 215}; 216 217static voidfree_fragment_list(struct fragment *list) 218{ 219while(list) { 220struct fragment *next = list->next; 221if(list->free_patch) 222free((char*)list->patch); 223free(list); 224 list = next; 225} 226} 227 228static voidfree_patch(struct patch *patch) 229{ 230free_fragment_list(patch->fragments); 231free(patch->def_name); 232free(patch->old_name); 233free(patch->new_name); 234free(patch->result); 235free(patch); 236} 237 238static voidfree_patch_list(struct patch *list) 239{ 240while(list) { 241struct patch *next = list->next; 242free_patch(list); 243 list = next; 244} 245} 246 247/* 248 * A line in a file, len-bytes long (includes the terminating LF, 249 * except for an incomplete line at the end if the file ends with 250 * one), and its contents hashes to 'hash'. 251 */ 252struct line { 253size_t len; 254unsigned hash :24; 255unsigned flag :8; 256#define LINE_COMMON 1 257#define LINE_PATCHED 2 258}; 259 260/* 261 * This represents a "file", which is an array of "lines". 262 */ 263struct image { 264char*buf; 265size_t len; 266size_t nr; 267size_t alloc; 268struct line *line_allocated; 269struct line *line; 270}; 271 272static uint32_thash_line(const char*cp,size_t len) 273{ 274size_t i; 275uint32_t h; 276for(i =0, h =0; i < len; i++) { 277if(!isspace(cp[i])) { 278 h = h *3+ (cp[i] &0xff); 279} 280} 281return h; 282} 283 284/* 285 * Compare lines s1 of length n1 and s2 of length n2, ignoring 286 * whitespace difference. Returns 1 if they match, 0 otherwise 287 */ 288static intfuzzy_matchlines(const char*s1,size_t n1, 289const char*s2,size_t n2) 290{ 291const char*last1 = s1 + n1 -1; 292const char*last2 = s2 + n2 -1; 293int result =0; 294 295/* ignore line endings */ 296while((*last1 =='\r') || (*last1 =='\n')) 297 last1--; 298while((*last2 =='\r') || (*last2 =='\n')) 299 last2--; 300 301/* skip leading whitespaces, if both begin with whitespace */ 302if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 303while(isspace(*s1) && (s1 <= last1)) 304 s1++; 305while(isspace(*s2) && (s2 <= last2)) 306 s2++; 307} 308/* early return if both lines are empty */ 309if((s1 > last1) && (s2 > last2)) 310return1; 311while(!result) { 312 result = *s1++ - *s2++; 313/* 314 * Skip whitespace inside. We check for whitespace on 315 * both buffers because we don't want "a b" to match 316 * "ab" 317 */ 318if(isspace(*s1) &&isspace(*s2)) { 319while(isspace(*s1) && s1 <= last1) 320 s1++; 321while(isspace(*s2) && s2 <= last2) 322 s2++; 323} 324/* 325 * If we reached the end on one side only, 326 * lines don't match 327 */ 328if( 329((s2 > last2) && (s1 <= last1)) || 330((s1 > last1) && (s2 <= last2))) 331return0; 332if((s1 > last1) && (s2 > last2)) 333break; 334} 335 336return!result; 337} 338 339static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 340{ 341ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 342 img->line_allocated[img->nr].len = len; 343 img->line_allocated[img->nr].hash =hash_line(bol, len); 344 img->line_allocated[img->nr].flag = flag; 345 img->nr++; 346} 347 348/* 349 * "buf" has the file contents to be patched (read from various sources). 350 * attach it to "image" and add line-based index to it. 351 * "image" now owns the "buf". 352 */ 353static voidprepare_image(struct image *image,char*buf,size_t len, 354int prepare_linetable) 355{ 356const char*cp, *ep; 357 358memset(image,0,sizeof(*image)); 359 image->buf = buf; 360 image->len = len; 361 362if(!prepare_linetable) 363return; 364 365 ep = image->buf + image->len; 366 cp = image->buf; 367while(cp < ep) { 368const char*next; 369for(next = cp; next < ep && *next !='\n'; next++) 370; 371if(next < ep) 372 next++; 373add_line_info(image, cp, next - cp,0); 374 cp = next; 375} 376 image->line = image->line_allocated; 377} 378 379static voidclear_image(struct image *image) 380{ 381free(image->buf); 382free(image->line_allocated); 383memset(image,0,sizeof(*image)); 384} 385 386/* fmt must contain _one_ %s and no other substitution */ 387static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 388{ 389struct strbuf sb = STRBUF_INIT; 390 391if(patch->old_name && patch->new_name && 392strcmp(patch->old_name, patch->new_name)) { 393quote_c_style(patch->old_name, &sb, NULL,0); 394strbuf_addstr(&sb," => "); 395quote_c_style(patch->new_name, &sb, NULL,0); 396}else{ 397const char*n = patch->new_name; 398if(!n) 399 n = patch->old_name; 400quote_c_style(n, &sb, NULL,0); 401} 402fprintf(output, fmt, sb.buf); 403fputc('\n', output); 404strbuf_release(&sb); 405} 406 407#define SLOP (16) 408 409static intread_patch_file(struct strbuf *sb,int fd) 410{ 411if(strbuf_read(sb, fd,0) <0) 412returnerror_errno("git apply: failed to read"); 413 414/* 415 * Make sure that we have some slop in the buffer 416 * so that we can do speculative "memcmp" etc, and 417 * see to it that it is NUL-filled. 418 */ 419strbuf_grow(sb, SLOP); 420memset(sb->buf + sb->len,0, SLOP); 421return0; 422} 423 424static unsigned longlinelen(const char*buffer,unsigned long size) 425{ 426unsigned long len =0; 427while(size--) { 428 len++; 429if(*buffer++ =='\n') 430break; 431} 432return len; 433} 434 435static intis_dev_null(const char*str) 436{ 437returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 438} 439 440#define TERM_SPACE 1 441#define TERM_TAB 2 442 443static intname_terminate(int c,int terminate) 444{ 445if(c ==' '&& !(terminate & TERM_SPACE)) 446return0; 447if(c =='\t'&& !(terminate & TERM_TAB)) 448return0; 449 450return1; 451} 452 453/* remove double slashes to make --index work with such filenames */ 454static char*squash_slash(char*name) 455{ 456int i =0, j =0; 457 458if(!name) 459return NULL; 460 461while(name[i]) { 462if((name[j++] = name[i++]) =='/') 463while(name[i] =='/') 464 i++; 465} 466 name[j] ='\0'; 467return name; 468} 469 470static char*find_name_gnu(struct apply_state *state, 471const char*line, 472const char*def, 473int p_value) 474{ 475struct strbuf name = STRBUF_INIT; 476char*cp; 477 478/* 479 * Proposed "new-style" GNU patch/diff format; see 480 * http://marc.info/?l=git&m=112927316408690&w=2 481 */ 482if(unquote_c_style(&name, line, NULL)) { 483strbuf_release(&name); 484return NULL; 485} 486 487for(cp = name.buf; p_value; p_value--) { 488 cp =strchr(cp,'/'); 489if(!cp) { 490strbuf_release(&name); 491return NULL; 492} 493 cp++; 494} 495 496strbuf_remove(&name,0, cp - name.buf); 497if(state->root.len) 498strbuf_insert(&name,0, state->root.buf, state->root.len); 499returnsquash_slash(strbuf_detach(&name, NULL)); 500} 501 502static size_tsane_tz_len(const char*line,size_t len) 503{ 504const char*tz, *p; 505 506if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 507return0; 508 tz = line + len -strlen(" +0500"); 509 510if(tz[1] !='+'&& tz[1] !='-') 511return0; 512 513for(p = tz +2; p != line + len; p++) 514if(!isdigit(*p)) 515return0; 516 517return line + len - tz; 518} 519 520static size_ttz_with_colon_len(const char*line,size_t len) 521{ 522const char*tz, *p; 523 524if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 525return0; 526 tz = line + len -strlen(" +08:00"); 527 528if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 529return0; 530 p = tz +2; 531if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 532!isdigit(*p++) || !isdigit(*p++)) 533return0; 534 535return line + len - tz; 536} 537 538static size_tdate_len(const char*line,size_t len) 539{ 540const char*date, *p; 541 542if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 543return0; 544 p = date = line + len -strlen("72-02-05"); 545 546if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 547!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 548!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 549return0; 550 551if(date - line >=strlen("19") && 552isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 553 date -=strlen("19"); 554 555return line + len - date; 556} 557 558static size_tshort_time_len(const char*line,size_t len) 559{ 560const char*time, *p; 561 562if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 563return0; 564 p = time = line + len -strlen(" 07:01:32"); 565 566/* Permit 1-digit hours? */ 567if(*p++ !=' '|| 568!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 569!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 570!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 571return0; 572 573return line + len - time; 574} 575 576static size_tfractional_time_len(const char*line,size_t len) 577{ 578const char*p; 579size_t n; 580 581/* Expected format: 19:41:17.620000023 */ 582if(!len || !isdigit(line[len -1])) 583return0; 584 p = line + len -1; 585 586/* Fractional seconds. */ 587while(p > line &&isdigit(*p)) 588 p--; 589if(*p !='.') 590return0; 591 592/* Hours, minutes, and whole seconds. */ 593 n =short_time_len(line, p - line); 594if(!n) 595return0; 596 597return line + len - p + n; 598} 599 600static size_ttrailing_spaces_len(const char*line,size_t len) 601{ 602const char*p; 603 604/* Expected format: ' ' x (1 or more) */ 605if(!len || line[len -1] !=' ') 606return0; 607 608 p = line + len; 609while(p != line) { 610 p--; 611if(*p !=' ') 612return line + len - (p +1); 613} 614 615/* All spaces! */ 616return len; 617} 618 619static size_tdiff_timestamp_len(const char*line,size_t len) 620{ 621const char*end = line + len; 622size_t n; 623 624/* 625 * Posix: 2010-07-05 19:41:17 626 * GNU: 2010-07-05 19:41:17.620000023 -0500 627 */ 628 629if(!isdigit(end[-1])) 630return0; 631 632 n =sane_tz_len(line, end - line); 633if(!n) 634 n =tz_with_colon_len(line, end - line); 635 end -= n; 636 637 n =short_time_len(line, end - line); 638if(!n) 639 n =fractional_time_len(line, end - line); 640 end -= n; 641 642 n =date_len(line, end - line); 643if(!n)/* No date. Too bad. */ 644return0; 645 end -= n; 646 647if(end == line)/* No space before date. */ 648return0; 649if(end[-1] =='\t') {/* Success! */ 650 end--; 651return line + len - end; 652} 653if(end[-1] !=' ')/* No space before date. */ 654return0; 655 656/* Whitespace damage. */ 657 end -=trailing_spaces_len(line, end - line); 658return line + len - end; 659} 660 661static char*find_name_common(struct apply_state *state, 662const char*line, 663const char*def, 664int p_value, 665const char*end, 666int terminate) 667{ 668int len; 669const char*start = NULL; 670 671if(p_value ==0) 672 start = line; 673while(line != end) { 674char c = *line; 675 676if(!end &&isspace(c)) { 677if(c =='\n') 678break; 679if(name_terminate(c, terminate)) 680break; 681} 682 line++; 683if(c =='/'&& !--p_value) 684 start = line; 685} 686if(!start) 687returnsquash_slash(xstrdup_or_null(def)); 688 len = line - start; 689if(!len) 690returnsquash_slash(xstrdup_or_null(def)); 691 692/* 693 * Generally we prefer the shorter name, especially 694 * if the other one is just a variation of that with 695 * something else tacked on to the end (ie "file.orig" 696 * or "file~"). 697 */ 698if(def) { 699int deflen =strlen(def); 700if(deflen < len && !strncmp(start, def, deflen)) 701returnsquash_slash(xstrdup(def)); 702} 703 704if(state->root.len) { 705char*ret =xstrfmt("%s%.*s", state->root.buf, len, start); 706returnsquash_slash(ret); 707} 708 709returnsquash_slash(xmemdupz(start, len)); 710} 711 712static char*find_name(struct apply_state *state, 713const char*line, 714char*def, 715int p_value, 716int terminate) 717{ 718if(*line =='"') { 719char*name =find_name_gnu(state, line, def, p_value); 720if(name) 721return name; 722} 723 724returnfind_name_common(state, line, def, p_value, NULL, terminate); 725} 726 727static char*find_name_traditional(struct apply_state *state, 728const char*line, 729char*def, 730int p_value) 731{ 732size_t len; 733size_t date_len; 734 735if(*line =='"') { 736char*name =find_name_gnu(state, line, def, p_value); 737if(name) 738return name; 739} 740 741 len =strchrnul(line,'\n') - line; 742 date_len =diff_timestamp_len(line, len); 743if(!date_len) 744returnfind_name_common(state, line, def, p_value, NULL, TERM_TAB); 745 len -= date_len; 746 747returnfind_name_common(state, line, def, p_value, line + len,0); 748} 749 750static intcount_slashes(const char*cp) 751{ 752int cnt =0; 753char ch; 754 755while((ch = *cp++)) 756if(ch =='/') 757 cnt++; 758return cnt; 759} 760 761/* 762 * Given the string after "--- " or "+++ ", guess the appropriate 763 * p_value for the given patch. 764 */ 765static intguess_p_value(struct apply_state *state,const char*nameline) 766{ 767char*name, *cp; 768int val = -1; 769 770if(is_dev_null(nameline)) 771return-1; 772 name =find_name_traditional(state, nameline, NULL,0); 773if(!name) 774return-1; 775 cp =strchr(name,'/'); 776if(!cp) 777 val =0; 778else if(state->prefix) { 779/* 780 * Does it begin with "a/$our-prefix" and such? Then this is 781 * very likely to apply to our directory. 782 */ 783if(!strncmp(name, state->prefix, state->prefix_length)) 784 val =count_slashes(state->prefix); 785else{ 786 cp++; 787if(!strncmp(cp, state->prefix, state->prefix_length)) 788 val =count_slashes(state->prefix) +1; 789} 790} 791free(name); 792return val; 793} 794 795/* 796 * Does the ---/+++ line have the POSIX timestamp after the last HT? 797 * GNU diff puts epoch there to signal a creation/deletion event. Is 798 * this such a timestamp? 799 */ 800static inthas_epoch_timestamp(const char*nameline) 801{ 802/* 803 * We are only interested in epoch timestamp; any non-zero 804 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 805 * For the same reason, the date must be either 1969-12-31 or 806 * 1970-01-01, and the seconds part must be "00". 807 */ 808const char stamp_regexp[] = 809"^(1969-12-31|1970-01-01)" 810" " 811"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 812" " 813"([-+][0-2][0-9]:?[0-5][0-9])\n"; 814const char*timestamp = NULL, *cp, *colon; 815static regex_t *stamp; 816 regmatch_t m[10]; 817int zoneoffset; 818int hourminute; 819int status; 820 821for(cp = nameline; *cp !='\n'; cp++) { 822if(*cp =='\t') 823 timestamp = cp +1; 824} 825if(!timestamp) 826return0; 827if(!stamp) { 828 stamp =xmalloc(sizeof(*stamp)); 829if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 830warning(_("Cannot prepare timestamp regexp%s"), 831 stamp_regexp); 832return0; 833} 834} 835 836 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 837if(status) { 838if(status != REG_NOMATCH) 839warning(_("regexec returned%dfor input:%s"), 840 status, timestamp); 841return0; 842} 843 844 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 845if(*colon ==':') 846 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 847else 848 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 849if(timestamp[m[3].rm_so] =='-') 850 zoneoffset = -zoneoffset; 851 852/* 853 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 854 * (west of GMT) or 1970-01-01 (east of GMT) 855 */ 856if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 857(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 858return0; 859 860 hourminute = (strtol(timestamp +11, NULL,10) *60+ 861strtol(timestamp +14, NULL,10) - 862 zoneoffset); 863 864return((zoneoffset <0&& hourminute ==1440) || 865(0<= zoneoffset && !hourminute)); 866} 867 868/* 869 * Get the name etc info from the ---/+++ lines of a traditional patch header 870 * 871 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 872 * files, we can happily check the index for a match, but for creating a 873 * new file we should try to match whatever "patch" does. I have no idea. 874 */ 875static intparse_traditional_patch(struct apply_state *state, 876const char*first, 877const char*second, 878struct patch *patch) 879{ 880char*name; 881 882 first +=4;/* skip "--- " */ 883 second +=4;/* skip "+++ " */ 884if(!state->p_value_known) { 885int p, q; 886 p =guess_p_value(state, first); 887 q =guess_p_value(state, second); 888if(p <0) p = q; 889if(0<= p && p == q) { 890 state->p_value = p; 891 state->p_value_known =1; 892} 893} 894if(is_dev_null(first)) { 895 patch->is_new =1; 896 patch->is_delete =0; 897 name =find_name_traditional(state, second, NULL, state->p_value); 898 patch->new_name = name; 899}else if(is_dev_null(second)) { 900 patch->is_new =0; 901 patch->is_delete =1; 902 name =find_name_traditional(state, first, NULL, state->p_value); 903 patch->old_name = name; 904}else{ 905char*first_name; 906 first_name =find_name_traditional(state, first, NULL, state->p_value); 907 name =find_name_traditional(state, second, first_name, state->p_value); 908free(first_name); 909if(has_epoch_timestamp(first)) { 910 patch->is_new =1; 911 patch->is_delete =0; 912 patch->new_name = name; 913}else if(has_epoch_timestamp(second)) { 914 patch->is_new =0; 915 patch->is_delete =1; 916 patch->old_name = name; 917}else{ 918 patch->old_name = name; 919 patch->new_name =xstrdup_or_null(name); 920} 921} 922if(!name) 923returnerror(_("unable to find filename in patch at line%d"), state->linenr); 924 925return0; 926} 927 928static intgitdiff_hdrend(struct apply_state *state, 929const char*line, 930struct patch *patch) 931{ 932return1; 933} 934 935/* 936 * We're anal about diff header consistency, to make 937 * sure that we don't end up having strange ambiguous 938 * patches floating around. 939 * 940 * As a result, gitdiff_{old|new}name() will check 941 * their names against any previous information, just 942 * to make sure.. 943 */ 944#define DIFF_OLD_NAME 0 945#define DIFF_NEW_NAME 1 946 947static intgitdiff_verify_name(struct apply_state *state, 948const char*line, 949int isnull, 950char**name, 951int side) 952{ 953if(!*name && !isnull) { 954*name =find_name(state, line, NULL, state->p_value, TERM_TAB); 955return0; 956} 957 958if(*name) { 959int len =strlen(*name); 960char*another; 961if(isnull) 962returnerror(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 963*name, state->linenr); 964 another =find_name(state, line, NULL, state->p_value, TERM_TAB); 965if(!another ||memcmp(another, *name, len +1)) { 966free(another); 967returnerror((side == DIFF_NEW_NAME) ? 968_("git apply: bad git-diff - inconsistent new filename on line%d") : 969_("git apply: bad git-diff - inconsistent old filename on line%d"), state->linenr); 970} 971free(another); 972}else{ 973if(!starts_with(line,"/dev/null\n")) 974returnerror(_("git apply: bad git-diff - expected /dev/null on line%d"), state->linenr); 975} 976 977return0; 978} 979 980static intgitdiff_oldname(struct apply_state *state, 981const char*line, 982struct patch *patch) 983{ 984returngitdiff_verify_name(state, line, 985 patch->is_new, &patch->old_name, 986 DIFF_OLD_NAME); 987} 988 989static intgitdiff_newname(struct apply_state *state, 990const char*line, 991struct patch *patch) 992{ 993returngitdiff_verify_name(state, line, 994 patch->is_delete, &patch->new_name, 995 DIFF_NEW_NAME); 996} 997 998static intgitdiff_oldmode(struct apply_state *state, 999const char*line,1000struct patch *patch)1001{1002 patch->old_mode =strtoul(line, NULL,8);1003return0;1004}10051006static intgitdiff_newmode(struct apply_state *state,1007const char*line,1008struct patch *patch)1009{1010 patch->new_mode =strtoul(line, NULL,8);1011return0;1012}10131014static intgitdiff_delete(struct apply_state *state,1015const char*line,1016struct patch *patch)1017{1018 patch->is_delete =1;1019free(patch->old_name);1020 patch->old_name =xstrdup_or_null(patch->def_name);1021returngitdiff_oldmode(state, line, patch);1022}10231024static intgitdiff_newfile(struct apply_state *state,1025const char*line,1026struct patch *patch)1027{1028 patch->is_new =1;1029free(patch->new_name);1030 patch->new_name =xstrdup_or_null(patch->def_name);1031returngitdiff_newmode(state, line, patch);1032}10331034static intgitdiff_copysrc(struct apply_state *state,1035const char*line,1036struct patch *patch)1037{1038 patch->is_copy =1;1039free(patch->old_name);1040 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1041return0;1042}10431044static intgitdiff_copydst(struct apply_state *state,1045const char*line,1046struct patch *patch)1047{1048 patch->is_copy =1;1049free(patch->new_name);1050 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1051return0;1052}10531054static intgitdiff_renamesrc(struct apply_state *state,1055const char*line,1056struct patch *patch)1057{1058 patch->is_rename =1;1059free(patch->old_name);1060 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1061return0;1062}10631064static intgitdiff_renamedst(struct apply_state *state,1065const char*line,1066struct patch *patch)1067{1068 patch->is_rename =1;1069free(patch->new_name);1070 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1071return0;1072}10731074static intgitdiff_similarity(struct apply_state *state,1075const char*line,1076struct patch *patch)1077{1078unsigned long val =strtoul(line, NULL,10);1079if(val <=100)1080 patch->score = val;1081return0;1082}10831084static intgitdiff_dissimilarity(struct apply_state *state,1085const char*line,1086struct patch *patch)1087{1088unsigned long val =strtoul(line, NULL,10);1089if(val <=100)1090 patch->score = val;1091return0;1092}10931094static intgitdiff_index(struct apply_state *state,1095const char*line,1096struct patch *patch)1097{1098/*1099 * index line is N hexadecimal, "..", N hexadecimal,1100 * and optional space with octal mode.1101 */1102const char*ptr, *eol;1103int len;11041105 ptr =strchr(line,'.');1106if(!ptr || ptr[1] !='.'||40< ptr - line)1107return0;1108 len = ptr - line;1109memcpy(patch->old_sha1_prefix, line, len);1110 patch->old_sha1_prefix[len] =0;11111112 line = ptr +2;1113 ptr =strchr(line,' ');1114 eol =strchrnul(line,'\n');11151116if(!ptr || eol < ptr)1117 ptr = eol;1118 len = ptr - line;11191120if(40< len)1121return0;1122memcpy(patch->new_sha1_prefix, line, len);1123 patch->new_sha1_prefix[len] =0;1124if(*ptr ==' ')1125 patch->old_mode =strtoul(ptr+1, NULL,8);1126return0;1127}11281129/*1130 * This is normal for a diff that doesn't change anything: we'll fall through1131 * into the next diff. Tell the parser to break out.1132 */1133static intgitdiff_unrecognized(struct apply_state *state,1134const char*line,1135struct patch *patch)1136{1137return1;1138}11391140/*1141 * Skip p_value leading components from "line"; as we do not accept1142 * absolute paths, return NULL in that case.1143 */1144static const char*skip_tree_prefix(struct apply_state *state,1145const char*line,1146int llen)1147{1148int nslash;1149int i;11501151if(!state->p_value)1152return(llen && line[0] =='/') ? NULL : line;11531154 nslash = state->p_value;1155for(i =0; i < llen; i++) {1156int ch = line[i];1157if(ch =='/'&& --nslash <=0)1158return(i ==0) ? NULL : &line[i +1];1159}1160return NULL;1161}11621163/*1164 * This is to extract the same name that appears on "diff --git"1165 * line. We do not find and return anything if it is a rename1166 * patch, and it is OK because we will find the name elsewhere.1167 * We need to reliably find name only when it is mode-change only,1168 * creation or deletion of an empty file. In any of these cases,1169 * both sides are the same name under a/ and b/ respectively.1170 */1171static char*git_header_name(struct apply_state *state,1172const char*line,1173int llen)1174{1175const char*name;1176const char*second = NULL;1177size_t len, line_len;11781179 line +=strlen("diff --git ");1180 llen -=strlen("diff --git ");11811182if(*line =='"') {1183const char*cp;1184struct strbuf first = STRBUF_INIT;1185struct strbuf sp = STRBUF_INIT;11861187if(unquote_c_style(&first, line, &second))1188goto free_and_fail1;11891190/* strip the a/b prefix including trailing slash */1191 cp =skip_tree_prefix(state, first.buf, first.len);1192if(!cp)1193goto free_and_fail1;1194strbuf_remove(&first,0, cp - first.buf);11951196/*1197 * second points at one past closing dq of name.1198 * find the second name.1199 */1200while((second < line + llen) &&isspace(*second))1201 second++;12021203if(line + llen <= second)1204goto free_and_fail1;1205if(*second =='"') {1206if(unquote_c_style(&sp, second, NULL))1207goto free_and_fail1;1208 cp =skip_tree_prefix(state, sp.buf, sp.len);1209if(!cp)1210goto free_and_fail1;1211/* They must match, otherwise ignore */1212if(strcmp(cp, first.buf))1213goto free_and_fail1;1214strbuf_release(&sp);1215returnstrbuf_detach(&first, NULL);1216}12171218/* unquoted second */1219 cp =skip_tree_prefix(state, second, line + llen - second);1220if(!cp)1221goto free_and_fail1;1222if(line + llen - cp != first.len ||1223memcmp(first.buf, cp, first.len))1224goto free_and_fail1;1225returnstrbuf_detach(&first, NULL);12261227 free_and_fail1:1228strbuf_release(&first);1229strbuf_release(&sp);1230return NULL;1231}12321233/* unquoted first name */1234 name =skip_tree_prefix(state, line, llen);1235if(!name)1236return NULL;12371238/*1239 * since the first name is unquoted, a dq if exists must be1240 * the beginning of the second name.1241 */1242for(second = name; second < line + llen; second++) {1243if(*second =='"') {1244struct strbuf sp = STRBUF_INIT;1245const char*np;12461247if(unquote_c_style(&sp, second, NULL))1248goto free_and_fail2;12491250 np =skip_tree_prefix(state, sp.buf, sp.len);1251if(!np)1252goto free_and_fail2;12531254 len = sp.buf + sp.len - np;1255if(len < second - name &&1256!strncmp(np, name, len) &&1257isspace(name[len])) {1258/* Good */1259strbuf_remove(&sp,0, np - sp.buf);1260returnstrbuf_detach(&sp, NULL);1261}12621263 free_and_fail2:1264strbuf_release(&sp);1265return NULL;1266}1267}12681269/*1270 * Accept a name only if it shows up twice, exactly the same1271 * form.1272 */1273 second =strchr(name,'\n');1274if(!second)1275return NULL;1276 line_len = second - name;1277for(len =0; ; len++) {1278switch(name[len]) {1279default:1280continue;1281case'\n':1282return NULL;1283case'\t':case' ':1284/*1285 * Is this the separator between the preimage1286 * and the postimage pathname? Again, we are1287 * only interested in the case where there is1288 * no rename, as this is only to set def_name1289 * and a rename patch has the names elsewhere1290 * in an unambiguous form.1291 */1292if(!name[len +1])1293return NULL;/* no postimage name */1294 second =skip_tree_prefix(state, name + len +1,1295 line_len - (len +1));1296if(!second)1297return NULL;1298/*1299 * Does len bytes starting at "name" and "second"1300 * (that are separated by one HT or SP we just1301 * found) exactly match?1302 */1303if(second[len] =='\n'&& !strncmp(name, second, len))1304returnxmemdupz(name, len);1305}1306}1307}13081309/* Verify that we recognize the lines following a git header */1310static intparse_git_header(struct apply_state *state,1311const char*line,1312int len,1313unsigned int size,1314struct patch *patch)1315{1316unsigned long offset;13171318/* A git diff has explicit new/delete information, so we don't guess */1319 patch->is_new =0;1320 patch->is_delete =0;13211322/*1323 * Some things may not have the old name in the1324 * rest of the headers anywhere (pure mode changes,1325 * or removing or adding empty files), so we get1326 * the default name from the header.1327 */1328 patch->def_name =git_header_name(state, line, len);1329if(patch->def_name && state->root.len) {1330char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1331free(patch->def_name);1332 patch->def_name = s;1333}13341335 line += len;1336 size -= len;1337 state->linenr++;1338for(offset = len ; size >0; offset += len, size -= len, line += len, state->linenr++) {1339static const struct opentry {1340const char*str;1341int(*fn)(struct apply_state *,const char*,struct patch *);1342} optable[] = {1343{"@@ -", gitdiff_hdrend },1344{"--- ", gitdiff_oldname },1345{"+++ ", gitdiff_newname },1346{"old mode ", gitdiff_oldmode },1347{"new mode ", gitdiff_newmode },1348{"deleted file mode ", gitdiff_delete },1349{"new file mode ", gitdiff_newfile },1350{"copy from ", gitdiff_copysrc },1351{"copy to ", gitdiff_copydst },1352{"rename old ", gitdiff_renamesrc },1353{"rename new ", gitdiff_renamedst },1354{"rename from ", gitdiff_renamesrc },1355{"rename to ", gitdiff_renamedst },1356{"similarity index ", gitdiff_similarity },1357{"dissimilarity index ", gitdiff_dissimilarity },1358{"index ", gitdiff_index },1359{"", gitdiff_unrecognized },1360};1361int i;13621363 len =linelen(line, size);1364if(!len || line[len-1] !='\n')1365break;1366for(i =0; i <ARRAY_SIZE(optable); i++) {1367const struct opentry *p = optable + i;1368int oplen =strlen(p->str);1369int res;1370if(len < oplen ||memcmp(p->str, line, oplen))1371continue;1372 res = p->fn(state, line + oplen, patch);1373if(res <0)1374return-1;1375if(res >0)1376return offset;1377break;1378}1379}13801381return offset;1382}13831384static intparse_num(const char*line,unsigned long*p)1385{1386char*ptr;13871388if(!isdigit(*line))1389return0;1390*p =strtoul(line, &ptr,10);1391return ptr - line;1392}13931394static intparse_range(const char*line,int len,int offset,const char*expect,1395unsigned long*p1,unsigned long*p2)1396{1397int digits, ex;13981399if(offset <0|| offset >= len)1400return-1;1401 line += offset;1402 len -= offset;14031404 digits =parse_num(line, p1);1405if(!digits)1406return-1;14071408 offset += digits;1409 line += digits;1410 len -= digits;14111412*p2 =1;1413if(*line ==',') {1414 digits =parse_num(line+1, p2);1415if(!digits)1416return-1;14171418 offset += digits+1;1419 line += digits+1;1420 len -= digits+1;1421}14221423 ex =strlen(expect);1424if(ex > len)1425return-1;1426if(memcmp(line, expect, ex))1427return-1;14281429return offset + ex;1430}14311432static voidrecount_diff(const char*line,int size,struct fragment *fragment)1433{1434int oldlines =0, newlines =0, ret =0;14351436if(size <1) {1437warning("recount: ignore empty hunk");1438return;1439}14401441for(;;) {1442int len =linelen(line, size);1443 size -= len;1444 line += len;14451446if(size <1)1447break;14481449switch(*line) {1450case' ':case'\n':1451 newlines++;1452/* fall through */1453case'-':1454 oldlines++;1455continue;1456case'+':1457 newlines++;1458continue;1459case'\\':1460continue;1461case'@':1462 ret = size <3|| !starts_with(line,"@@ ");1463break;1464case'd':1465 ret = size <5|| !starts_with(line,"diff ");1466break;1467default:1468 ret = -1;1469break;1470}1471if(ret) {1472warning(_("recount: unexpected line: %.*s"),1473(int)linelen(line, size), line);1474return;1475}1476break;1477}1478 fragment->oldlines = oldlines;1479 fragment->newlines = newlines;1480}14811482/*1483 * Parse a unified diff fragment header of the1484 * form "@@ -a,b +c,d @@"1485 */1486static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1487{1488int offset;14891490if(!len || line[len-1] !='\n')1491return-1;14921493/* Figure out the number of lines in a fragment */1494 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1495 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14961497return offset;1498}14991500/*1501 * Find file diff header1502 *1503 * Returns:1504 * -1 if no header was found1505 * -128 in case of error1506 * the size of the header in bytes (called "offset") otherwise1507 */1508static intfind_header(struct apply_state *state,1509const char*line,1510unsigned long size,1511int*hdrsize,1512struct patch *patch)1513{1514unsigned long offset, len;15151516 patch->is_toplevel_relative =0;1517 patch->is_rename = patch->is_copy =0;1518 patch->is_new = patch->is_delete = -1;1519 patch->old_mode = patch->new_mode =0;1520 patch->old_name = patch->new_name = NULL;1521for(offset =0; size >0; offset += len, size -= len, line += len, state->linenr++) {1522unsigned long nextlen;15231524 len =linelen(line, size);1525if(!len)1526break;15271528/* Testing this early allows us to take a few shortcuts.. */1529if(len <6)1530continue;15311532/*1533 * Make sure we don't find any unconnected patch fragments.1534 * That's a sign that we didn't find a header, and that a1535 * patch has become corrupted/broken up.1536 */1537if(!memcmp("@@ -", line,4)) {1538struct fragment dummy;1539if(parse_fragment_header(line, len, &dummy) <0)1540continue;1541error(_("patch fragment without header at line%d: %.*s"),1542 state->linenr, (int)len-1, line);1543return-128;1544}15451546if(size < len +6)1547break;15481549/*1550 * Git patch? It might not have a real patch, just a rename1551 * or mode change, so we handle that specially1552 */1553if(!memcmp("diff --git ", line,11)) {1554int git_hdr_len =parse_git_header(state, line, len, size, patch);1555if(git_hdr_len <0)1556return-128;1557if(git_hdr_len <= len)1558continue;1559if(!patch->old_name && !patch->new_name) {1560if(!patch->def_name) {1561error(Q_("git diff header lacks filename information when removing "1562"%dleading pathname component (line%d)",1563"git diff header lacks filename information when removing "1564"%dleading pathname components (line%d)",1565 state->p_value),1566 state->p_value, state->linenr);1567return-128;1568}1569 patch->old_name =xstrdup(patch->def_name);1570 patch->new_name =xstrdup(patch->def_name);1571}1572if(!patch->is_delete && !patch->new_name) {1573error("git diff header lacks filename information "1574"(line%d)", state->linenr);1575return-128;1576}1577 patch->is_toplevel_relative =1;1578*hdrsize = git_hdr_len;1579return offset;1580}15811582/* --- followed by +++ ? */1583if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1584continue;15851586/*1587 * We only accept unified patches, so we want it to1588 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1589 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1590 */1591 nextlen =linelen(line + len, size - len);1592if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1593continue;15941595/* Ok, we'll consider it a patch */1596if(parse_traditional_patch(state, line, line+len, patch))1597return-128;1598*hdrsize = len + nextlen;1599 state->linenr +=2;1600return offset;1601}1602return-1;1603}16041605static voidrecord_ws_error(struct apply_state *state,1606unsigned result,1607const char*line,1608int len,1609int linenr)1610{1611char*err;16121613if(!result)1614return;16151616 state->whitespace_error++;1617if(state->squelch_whitespace_errors &&1618 state->squelch_whitespace_errors < state->whitespace_error)1619return;16201621 err =whitespace_error_string(result);1622fprintf(stderr,"%s:%d:%s.\n%.*s\n",1623 state->patch_input_file, linenr, err, len, line);1624free(err);1625}16261627static voidcheck_whitespace(struct apply_state *state,1628const char*line,1629int len,1630unsigned ws_rule)1631{1632unsigned result =ws_check(line +1, len -1, ws_rule);16331634record_ws_error(state, result, line +1, len -2, state->linenr);1635}16361637/*1638 * Parse a unified diff. Note that this really needs to parse each1639 * fragment separately, since the only way to know the difference1640 * between a "---" that is part of a patch, and a "---" that starts1641 * the next patch is to look at the line counts..1642 */1643static intparse_fragment(struct apply_state *state,1644const char*line,1645unsigned long size,1646struct patch *patch,1647struct fragment *fragment)1648{1649int added, deleted;1650int len =linelen(line, size), offset;1651unsigned long oldlines, newlines;1652unsigned long leading, trailing;16531654 offset =parse_fragment_header(line, len, fragment);1655if(offset <0)1656return-1;1657if(offset >0&& patch->recount)1658recount_diff(line + offset, size - offset, fragment);1659 oldlines = fragment->oldlines;1660 newlines = fragment->newlines;1661 leading =0;1662 trailing =0;16631664/* Parse the thing.. */1665 line += len;1666 size -= len;1667 state->linenr++;1668 added = deleted =0;1669for(offset = len;16700< size;1671 offset += len, size -= len, line += len, state->linenr++) {1672if(!oldlines && !newlines)1673break;1674 len =linelen(line, size);1675if(!len || line[len-1] !='\n')1676return-1;1677switch(*line) {1678default:1679return-1;1680case'\n':/* newer GNU diff, an empty context line */1681case' ':1682 oldlines--;1683 newlines--;1684if(!deleted && !added)1685 leading++;1686 trailing++;1687if(!state->apply_in_reverse &&1688 state->ws_error_action == correct_ws_error)1689check_whitespace(state, line, len, patch->ws_rule);1690break;1691case'-':1692if(state->apply_in_reverse &&1693 state->ws_error_action != nowarn_ws_error)1694check_whitespace(state, line, len, patch->ws_rule);1695 deleted++;1696 oldlines--;1697 trailing =0;1698break;1699case'+':1700if(!state->apply_in_reverse &&1701 state->ws_error_action != nowarn_ws_error)1702check_whitespace(state, line, len, patch->ws_rule);1703 added++;1704 newlines--;1705 trailing =0;1706break;17071708/*1709 * We allow "\ No newline at end of file". Depending1710 * on locale settings when the patch was produced we1711 * don't know what this line looks like. The only1712 * thing we do know is that it begins with "\ ".1713 * Checking for 12 is just for sanity check -- any1714 * l10n of "\ No newline..." is at least that long.1715 */1716case'\\':1717if(len <12||memcmp(line,"\\",2))1718return-1;1719break;1720}1721}1722if(oldlines || newlines)1723return-1;1724if(!deleted && !added)1725return-1;17261727 fragment->leading = leading;1728 fragment->trailing = trailing;17291730/*1731 * If a fragment ends with an incomplete line, we failed to include1732 * it in the above loop because we hit oldlines == newlines == 01733 * before seeing it.1734 */1735if(12< size && !memcmp(line,"\\",2))1736 offset +=linelen(line, size);17371738 patch->lines_added += added;1739 patch->lines_deleted += deleted;17401741if(0< patch->is_new && oldlines)1742returnerror(_("new file depends on old contents"));1743if(0< patch->is_delete && newlines)1744returnerror(_("deleted file still has contents"));1745return offset;1746}17471748/*1749 * We have seen "diff --git a/... b/..." header (or a traditional patch1750 * header). Read hunks that belong to this patch into fragments and hang1751 * them to the given patch structure.1752 *1753 * The (fragment->patch, fragment->size) pair points into the memory given1754 * by the caller, not a copy, when we return.1755 *1756 * Returns:1757 * -1 in case of error,1758 * the number of bytes in the patch otherwise.1759 */1760static intparse_single_patch(struct apply_state *state,1761const char*line,1762unsigned long size,1763struct patch *patch)1764{1765unsigned long offset =0;1766unsigned long oldlines =0, newlines =0, context =0;1767struct fragment **fragp = &patch->fragments;17681769while(size >4&& !memcmp(line,"@@ -",4)) {1770struct fragment *fragment;1771int len;17721773 fragment =xcalloc(1,sizeof(*fragment));1774 fragment->linenr = state->linenr;1775 len =parse_fragment(state, line, size, patch, fragment);1776if(len <=0) {1777free(fragment);1778returnerror(_("corrupt patch at line%d"), state->linenr);1779}1780 fragment->patch = line;1781 fragment->size = len;1782 oldlines += fragment->oldlines;1783 newlines += fragment->newlines;1784 context += fragment->leading + fragment->trailing;17851786*fragp = fragment;1787 fragp = &fragment->next;17881789 offset += len;1790 line += len;1791 size -= len;1792}17931794/*1795 * If something was removed (i.e. we have old-lines) it cannot1796 * be creation, and if something was added it cannot be1797 * deletion. However, the reverse is not true; --unified=01798 * patches that only add are not necessarily creation even1799 * though they do not have any old lines, and ones that only1800 * delete are not necessarily deletion.1801 *1802 * Unfortunately, a real creation/deletion patch do _not_ have1803 * any context line by definition, so we cannot safely tell it1804 * apart with --unified=0 insanity. At least if the patch has1805 * more than one hunk it is not creation or deletion.1806 */1807if(patch->is_new <0&&1808(oldlines || (patch->fragments && patch->fragments->next)))1809 patch->is_new =0;1810if(patch->is_delete <0&&1811(newlines || (patch->fragments && patch->fragments->next)))1812 patch->is_delete =0;18131814if(0< patch->is_new && oldlines)1815returnerror(_("new file%sdepends on old contents"), patch->new_name);1816if(0< patch->is_delete && newlines)1817returnerror(_("deleted file%sstill has contents"), patch->old_name);1818if(!patch->is_delete && !newlines && context)1819fprintf_ln(stderr,1820_("** warning: "1821"file%sbecomes empty but is not deleted"),1822 patch->new_name);18231824return offset;1825}18261827staticinlineintmetadata_changes(struct patch *patch)1828{1829return patch->is_rename >0||1830 patch->is_copy >0||1831 patch->is_new >0||1832 patch->is_delete ||1833(patch->old_mode && patch->new_mode &&1834 patch->old_mode != patch->new_mode);1835}18361837static char*inflate_it(const void*data,unsigned long size,1838unsigned long inflated_size)1839{1840 git_zstream stream;1841void*out;1842int st;18431844memset(&stream,0,sizeof(stream));18451846 stream.next_in = (unsigned char*)data;1847 stream.avail_in = size;1848 stream.next_out = out =xmalloc(inflated_size);1849 stream.avail_out = inflated_size;1850git_inflate_init(&stream);1851 st =git_inflate(&stream, Z_FINISH);1852git_inflate_end(&stream);1853if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1854free(out);1855return NULL;1856}1857return out;1858}18591860/*1861 * Read a binary hunk and return a new fragment; fragment->patch1862 * points at an allocated memory that the caller must free, so1863 * it is marked as "->free_patch = 1".1864 */1865static struct fragment *parse_binary_hunk(struct apply_state *state,1866char**buf_p,1867unsigned long*sz_p,1868int*status_p,1869int*used_p)1870{1871/*1872 * Expect a line that begins with binary patch method ("literal"1873 * or "delta"), followed by the length of data before deflating.1874 * a sequence of 'length-byte' followed by base-85 encoded data1875 * should follow, terminated by a newline.1876 *1877 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1878 * and we would limit the patch line to 66 characters,1879 * so one line can fit up to 13 groups that would decode1880 * to 52 bytes max. The length byte 'A'-'Z' corresponds1881 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1882 */1883int llen, used;1884unsigned long size = *sz_p;1885char*buffer = *buf_p;1886int patch_method;1887unsigned long origlen;1888char*data = NULL;1889int hunk_size =0;1890struct fragment *frag;18911892 llen =linelen(buffer, size);1893 used = llen;18941895*status_p =0;18961897if(starts_with(buffer,"delta ")) {1898 patch_method = BINARY_DELTA_DEFLATED;1899 origlen =strtoul(buffer +6, NULL,10);1900}1901else if(starts_with(buffer,"literal ")) {1902 patch_method = BINARY_LITERAL_DEFLATED;1903 origlen =strtoul(buffer +8, NULL,10);1904}1905else1906return NULL;19071908 state->linenr++;1909 buffer += llen;1910while(1) {1911int byte_length, max_byte_length, newsize;1912 llen =linelen(buffer, size);1913 used += llen;1914 state->linenr++;1915if(llen ==1) {1916/* consume the blank line */1917 buffer++;1918 size--;1919break;1920}1921/*1922 * Minimum line is "A00000\n" which is 7-byte long,1923 * and the line length must be multiple of 5 plus 2.1924 */1925if((llen <7) || (llen-2) %5)1926goto corrupt;1927 max_byte_length = (llen -2) /5*4;1928 byte_length = *buffer;1929if('A'<= byte_length && byte_length <='Z')1930 byte_length = byte_length -'A'+1;1931else if('a'<= byte_length && byte_length <='z')1932 byte_length = byte_length -'a'+27;1933else1934goto corrupt;1935/* if the input length was not multiple of 4, we would1936 * have filler at the end but the filler should never1937 * exceed 3 bytes1938 */1939if(max_byte_length < byte_length ||1940 byte_length <= max_byte_length -4)1941goto corrupt;1942 newsize = hunk_size + byte_length;1943 data =xrealloc(data, newsize);1944if(decode_85(data + hunk_size, buffer +1, byte_length))1945goto corrupt;1946 hunk_size = newsize;1947 buffer += llen;1948 size -= llen;1949}19501951 frag =xcalloc(1,sizeof(*frag));1952 frag->patch =inflate_it(data, hunk_size, origlen);1953 frag->free_patch =1;1954if(!frag->patch)1955goto corrupt;1956free(data);1957 frag->size = origlen;1958*buf_p = buffer;1959*sz_p = size;1960*used_p = used;1961 frag->binary_patch_method = patch_method;1962return frag;19631964 corrupt:1965free(data);1966*status_p = -1;1967error(_("corrupt binary patch at line%d: %.*s"),1968 state->linenr-1, llen-1, buffer);1969return NULL;1970}19711972/*1973 * Returns:1974 * -1 in case of error,1975 * the length of the parsed binary patch otherwise1976 */1977static intparse_binary(struct apply_state *state,1978char*buffer,1979unsigned long size,1980struct patch *patch)1981{1982/*1983 * We have read "GIT binary patch\n"; what follows is a line1984 * that says the patch method (currently, either "literal" or1985 * "delta") and the length of data before deflating; a1986 * sequence of 'length-byte' followed by base-85 encoded data1987 * follows.1988 *1989 * When a binary patch is reversible, there is another binary1990 * hunk in the same format, starting with patch method (either1991 * "literal" or "delta") with the length of data, and a sequence1992 * of length-byte + base-85 encoded data, terminated with another1993 * empty line. This data, when applied to the postimage, produces1994 * the preimage.1995 */1996struct fragment *forward;1997struct fragment *reverse;1998int status;1999int used, used_1;20002001 forward =parse_binary_hunk(state, &buffer, &size, &status, &used);2002if(!forward && !status)2003/* there has to be one hunk (forward hunk) */2004returnerror(_("unrecognized binary patch at line%d"), state->linenr-1);2005if(status)2006/* otherwise we already gave an error message */2007return status;20082009 reverse =parse_binary_hunk(state, &buffer, &size, &status, &used_1);2010if(reverse)2011 used += used_1;2012else if(status) {2013/*2014 * Not having reverse hunk is not an error, but having2015 * a corrupt reverse hunk is.2016 */2017free((void*) forward->patch);2018free(forward);2019return status;2020}2021 forward->next = reverse;2022 patch->fragments = forward;2023 patch->is_binary =1;2024return used;2025}20262027static voidprefix_one(struct apply_state *state,char**name)2028{2029char*old_name = *name;2030if(!old_name)2031return;2032*name =xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));2033free(old_name);2034}20352036static voidprefix_patch(struct apply_state *state,struct patch *p)2037{2038if(!state->prefix || p->is_toplevel_relative)2039return;2040prefix_one(state, &p->new_name);2041prefix_one(state, &p->old_name);2042}20432044/*2045 * include/exclude2046 */20472048static voidadd_name_limit(struct apply_state *state,2049const char*name,2050int exclude)2051{2052struct string_list_item *it;20532054 it =string_list_append(&state->limit_by_name, name);2055 it->util = exclude ? NULL : (void*)1;2056}20572058static intuse_patch(struct apply_state *state,struct patch *p)2059{2060const char*pathname = p->new_name ? p->new_name : p->old_name;2061int i;20622063/* Paths outside are not touched regardless of "--include" */2064if(0< state->prefix_length) {2065int pathlen =strlen(pathname);2066if(pathlen <= state->prefix_length ||2067memcmp(state->prefix, pathname, state->prefix_length))2068return0;2069}20702071/* See if it matches any of exclude/include rule */2072for(i =0; i < state->limit_by_name.nr; i++) {2073struct string_list_item *it = &state->limit_by_name.items[i];2074if(!wildmatch(it->string, pathname,0, NULL))2075return(it->util != NULL);2076}20772078/*2079 * If we had any include, a path that does not match any rule is2080 * not used. Otherwise, we saw bunch of exclude rules (or none)2081 * and such a path is used.2082 */2083return!state->has_include;2084}20852086/*2087 * Read the patch text in "buffer" that extends for "size" bytes; stop2088 * reading after seeing a single patch (i.e. changes to a single file).2089 * Create fragments (i.e. patch hunks) and hang them to the given patch.2090 *2091 * Returns:2092 * -1 if no header was found or parse_binary() failed,2093 * -128 on another error,2094 * the number of bytes consumed otherwise,2095 * so that the caller can call us again for the next patch.2096 */2097static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2098{2099int hdrsize, patchsize;2100int offset =find_header(state, buffer, size, &hdrsize, patch);21012102if(offset <0)2103return offset;21042105prefix_patch(state, patch);21062107if(!use_patch(state, patch))2108 patch->ws_rule =0;2109else2110 patch->ws_rule =whitespace_rule(patch->new_name2111? patch->new_name2112: patch->old_name);21132114 patchsize =parse_single_patch(state,2115 buffer + offset + hdrsize,2116 size - offset - hdrsize,2117 patch);21182119if(patchsize <0)2120return-128;21212122if(!patchsize) {2123static const char git_binary[] ="GIT binary patch\n";2124int hd = hdrsize + offset;2125unsigned long llen =linelen(buffer + hd, size - hd);21262127if(llen ==sizeof(git_binary) -1&&2128!memcmp(git_binary, buffer + hd, llen)) {2129int used;2130 state->linenr++;2131 used =parse_binary(state, buffer + hd + llen,2132 size - hd - llen, patch);2133if(used <0)2134return-1;2135if(used)2136 patchsize = used + llen;2137else2138 patchsize =0;2139}2140else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2141static const char*binhdr[] = {2142"Binary files ",2143"Files ",2144 NULL,2145};2146int i;2147for(i =0; binhdr[i]; i++) {2148int len =strlen(binhdr[i]);2149if(len < size - hd &&2150!memcmp(binhdr[i], buffer + hd, len)) {2151 state->linenr++;2152 patch->is_binary =1;2153 patchsize = llen;2154break;2155}2156}2157}21582159/* Empty patch cannot be applied if it is a text patch2160 * without metadata change. A binary patch appears2161 * empty to us here.2162 */2163if((state->apply || state->check) &&2164(!patch->is_binary && !metadata_changes(patch))) {2165error(_("patch with only garbage at line%d"), state->linenr);2166return-128;2167}2168}21692170return offset + hdrsize + patchsize;2171}21722173#define swap(a,b) myswap((a),(b),sizeof(a))21742175#define myswap(a, b, size) do { \2176 unsigned char mytmp[size]; \2177 memcpy(mytmp, &a, size); \2178 memcpy(&a, &b, size); \2179 memcpy(&b, mytmp, size); \2180} while (0)21812182static voidreverse_patches(struct patch *p)2183{2184for(; p; p = p->next) {2185struct fragment *frag = p->fragments;21862187swap(p->new_name, p->old_name);2188swap(p->new_mode, p->old_mode);2189swap(p->is_new, p->is_delete);2190swap(p->lines_added, p->lines_deleted);2191swap(p->old_sha1_prefix, p->new_sha1_prefix);21922193for(; frag; frag = frag->next) {2194swap(frag->newpos, frag->oldpos);2195swap(frag->newlines, frag->oldlines);2196}2197}2198}21992200static const char pluses[] =2201"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2202static const char minuses[]=2203"----------------------------------------------------------------------";22042205static voidshow_stats(struct apply_state *state,struct patch *patch)2206{2207struct strbuf qname = STRBUF_INIT;2208char*cp = patch->new_name ? patch->new_name : patch->old_name;2209int max, add, del;22102211quote_c_style(cp, &qname, NULL,0);22122213/*2214 * "scale" the filename2215 */2216 max = state->max_len;2217if(max >50)2218 max =50;22192220if(qname.len > max) {2221 cp =strchr(qname.buf + qname.len +3- max,'/');2222if(!cp)2223 cp = qname.buf + qname.len +3- max;2224strbuf_splice(&qname,0, cp - qname.buf,"...",3);2225}22262227if(patch->is_binary) {2228printf(" %-*s | Bin\n", max, qname.buf);2229strbuf_release(&qname);2230return;2231}22322233printf(" %-*s |", max, qname.buf);2234strbuf_release(&qname);22352236/*2237 * scale the add/delete2238 */2239 max = max + state->max_change >70?70- max : state->max_change;2240 add = patch->lines_added;2241 del = patch->lines_deleted;22422243if(state->max_change >0) {2244int total = ((add + del) * max + state->max_change /2) / state->max_change;2245 add = (add * max + state->max_change /2) / state->max_change;2246 del = total - add;2247}2248printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2249 add, pluses, del, minuses);2250}22512252static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2253{2254switch(st->st_mode & S_IFMT) {2255case S_IFLNK:2256if(strbuf_readlink(buf, path, st->st_size) <0)2257returnerror(_("unable to read symlink%s"), path);2258return0;2259case S_IFREG:2260if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2261returnerror(_("unable to open or read%s"), path);2262convert_to_git(path, buf->buf, buf->len, buf,0);2263return0;2264default:2265return-1;2266}2267}22682269/*2270 * Update the preimage, and the common lines in postimage,2271 * from buffer buf of length len. If postlen is 0 the postimage2272 * is updated in place, otherwise it's updated on a new buffer2273 * of length postlen2274 */22752276static voidupdate_pre_post_images(struct image *preimage,2277struct image *postimage,2278char*buf,2279size_t len,size_t postlen)2280{2281int i, ctx, reduced;2282char*new, *old, *fixed;2283struct image fixed_preimage;22842285/*2286 * Update the preimage with whitespace fixes. Note that we2287 * are not losing preimage->buf -- apply_one_fragment() will2288 * free "oldlines".2289 */2290prepare_image(&fixed_preimage, buf, len,1);2291assert(postlen2292? fixed_preimage.nr == preimage->nr2293: fixed_preimage.nr <= preimage->nr);2294for(i =0; i < fixed_preimage.nr; i++)2295 fixed_preimage.line[i].flag = preimage->line[i].flag;2296free(preimage->line_allocated);2297*preimage = fixed_preimage;22982299/*2300 * Adjust the common context lines in postimage. This can be2301 * done in-place when we are shrinking it with whitespace2302 * fixing, but needs a new buffer when ignoring whitespace or2303 * expanding leading tabs to spaces.2304 *2305 * We trust the caller to tell us if the update can be done2306 * in place (postlen==0) or not.2307 */2308 old = postimage->buf;2309if(postlen)2310new= postimage->buf =xmalloc(postlen);2311else2312new= old;2313 fixed = preimage->buf;23142315for(i = reduced = ctx =0; i < postimage->nr; i++) {2316size_t l_len = postimage->line[i].len;2317if(!(postimage->line[i].flag & LINE_COMMON)) {2318/* an added line -- no counterparts in preimage */2319memmove(new, old, l_len);2320 old += l_len;2321new+= l_len;2322continue;2323}23242325/* a common context -- skip it in the original postimage */2326 old += l_len;23272328/* and find the corresponding one in the fixed preimage */2329while(ctx < preimage->nr &&2330!(preimage->line[ctx].flag & LINE_COMMON)) {2331 fixed += preimage->line[ctx].len;2332 ctx++;2333}23342335/*2336 * preimage is expected to run out, if the caller2337 * fixed addition of trailing blank lines.2338 */2339if(preimage->nr <= ctx) {2340 reduced++;2341continue;2342}23432344/* and copy it in, while fixing the line length */2345 l_len = preimage->line[ctx].len;2346memcpy(new, fixed, l_len);2347new+= l_len;2348 fixed += l_len;2349 postimage->line[i].len = l_len;2350 ctx++;2351}23522353if(postlen2354? postlen <new- postimage->buf2355: postimage->len <new- postimage->buf)2356die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2357(int)postlen, (int) postimage->len, (int)(new- postimage->buf));23582359/* Fix the length of the whole thing */2360 postimage->len =new- postimage->buf;2361 postimage->nr -= reduced;2362}23632364static intline_by_line_fuzzy_match(struct image *img,2365struct image *preimage,2366struct image *postimage,2367unsigned longtry,2368int try_lno,2369int preimage_limit)2370{2371int i;2372size_t imgoff =0;2373size_t preoff =0;2374size_t postlen = postimage->len;2375size_t extra_chars;2376char*buf;2377char*preimage_eof;2378char*preimage_end;2379struct strbuf fixed;2380char*fixed_buf;2381size_t fixed_len;23822383for(i =0; i < preimage_limit; i++) {2384size_t prelen = preimage->line[i].len;2385size_t imglen = img->line[try_lno+i].len;23862387if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2388 preimage->buf + preoff, prelen))2389return0;2390if(preimage->line[i].flag & LINE_COMMON)2391 postlen += imglen - prelen;2392 imgoff += imglen;2393 preoff += prelen;2394}23952396/*2397 * Ok, the preimage matches with whitespace fuzz.2398 *2399 * imgoff now holds the true length of the target that2400 * matches the preimage before the end of the file.2401 *2402 * Count the number of characters in the preimage that fall2403 * beyond the end of the file and make sure that all of them2404 * are whitespace characters. (This can only happen if2405 * we are removing blank lines at the end of the file.)2406 */2407 buf = preimage_eof = preimage->buf + preoff;2408for( ; i < preimage->nr; i++)2409 preoff += preimage->line[i].len;2410 preimage_end = preimage->buf + preoff;2411for( ; buf < preimage_end; buf++)2412if(!isspace(*buf))2413return0;24142415/*2416 * Update the preimage and the common postimage context2417 * lines to use the same whitespace as the target.2418 * If whitespace is missing in the target (i.e.2419 * if the preimage extends beyond the end of the file),2420 * use the whitespace from the preimage.2421 */2422 extra_chars = preimage_end - preimage_eof;2423strbuf_init(&fixed, imgoff + extra_chars);2424strbuf_add(&fixed, img->buf +try, imgoff);2425strbuf_add(&fixed, preimage_eof, extra_chars);2426 fixed_buf =strbuf_detach(&fixed, &fixed_len);2427update_pre_post_images(preimage, postimage,2428 fixed_buf, fixed_len, postlen);2429return1;2430}24312432static intmatch_fragment(struct apply_state *state,2433struct image *img,2434struct image *preimage,2435struct image *postimage,2436unsigned longtry,2437int try_lno,2438unsigned ws_rule,2439int match_beginning,int match_end)2440{2441int i;2442char*fixed_buf, *buf, *orig, *target;2443struct strbuf fixed;2444size_t fixed_len, postlen;2445int preimage_limit;24462447if(preimage->nr + try_lno <= img->nr) {2448/*2449 * The hunk falls within the boundaries of img.2450 */2451 preimage_limit = preimage->nr;2452if(match_end && (preimage->nr + try_lno != img->nr))2453return0;2454}else if(state->ws_error_action == correct_ws_error &&2455(ws_rule & WS_BLANK_AT_EOF)) {2456/*2457 * This hunk extends beyond the end of img, and we are2458 * removing blank lines at the end of the file. This2459 * many lines from the beginning of the preimage must2460 * match with img, and the remainder of the preimage2461 * must be blank.2462 */2463 preimage_limit = img->nr - try_lno;2464}else{2465/*2466 * The hunk extends beyond the end of the img and2467 * we are not removing blanks at the end, so we2468 * should reject the hunk at this position.2469 */2470return0;2471}24722473if(match_beginning && try_lno)2474return0;24752476/* Quick hash check */2477for(i =0; i < preimage_limit; i++)2478if((img->line[try_lno + i].flag & LINE_PATCHED) ||2479(preimage->line[i].hash != img->line[try_lno + i].hash))2480return0;24812482if(preimage_limit == preimage->nr) {2483/*2484 * Do we have an exact match? If we were told to match2485 * at the end, size must be exactly at try+fragsize,2486 * otherwise try+fragsize must be still within the preimage,2487 * and either case, the old piece should match the preimage2488 * exactly.2489 */2490if((match_end2491? (try+ preimage->len == img->len)2492: (try+ preimage->len <= img->len)) &&2493!memcmp(img->buf +try, preimage->buf, preimage->len))2494return1;2495}else{2496/*2497 * The preimage extends beyond the end of img, so2498 * there cannot be an exact match.2499 *2500 * There must be one non-blank context line that match2501 * a line before the end of img.2502 */2503char*buf_end;25042505 buf = preimage->buf;2506 buf_end = buf;2507for(i =0; i < preimage_limit; i++)2508 buf_end += preimage->line[i].len;25092510for( ; buf < buf_end; buf++)2511if(!isspace(*buf))2512break;2513if(buf == buf_end)2514return0;2515}25162517/*2518 * No exact match. If we are ignoring whitespace, run a line-by-line2519 * fuzzy matching. We collect all the line length information because2520 * we need it to adjust whitespace if we match.2521 */2522if(state->ws_ignore_action == ignore_ws_change)2523returnline_by_line_fuzzy_match(img, preimage, postimage,2524try, try_lno, preimage_limit);25252526if(state->ws_error_action != correct_ws_error)2527return0;25282529/*2530 * The hunk does not apply byte-by-byte, but the hash says2531 * it might with whitespace fuzz. We weren't asked to2532 * ignore whitespace, we were asked to correct whitespace2533 * errors, so let's try matching after whitespace correction.2534 *2535 * While checking the preimage against the target, whitespace2536 * errors in both fixed, we count how large the corresponding2537 * postimage needs to be. The postimage prepared by2538 * apply_one_fragment() has whitespace errors fixed on added2539 * lines already, but the common lines were propagated as-is,2540 * which may become longer when their whitespace errors are2541 * fixed.2542 */25432544/* First count added lines in postimage */2545 postlen =0;2546for(i =0; i < postimage->nr; i++) {2547if(!(postimage->line[i].flag & LINE_COMMON))2548 postlen += postimage->line[i].len;2549}25502551/*2552 * The preimage may extend beyond the end of the file,2553 * but in this loop we will only handle the part of the2554 * preimage that falls within the file.2555 */2556strbuf_init(&fixed, preimage->len +1);2557 orig = preimage->buf;2558 target = img->buf +try;2559for(i =0; i < preimage_limit; i++) {2560size_t oldlen = preimage->line[i].len;2561size_t tgtlen = img->line[try_lno + i].len;2562size_t fixstart = fixed.len;2563struct strbuf tgtfix;2564int match;25652566/* Try fixing the line in the preimage */2567ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25682569/* Try fixing the line in the target */2570strbuf_init(&tgtfix, tgtlen);2571ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);25722573/*2574 * If they match, either the preimage was based on2575 * a version before our tree fixed whitespace breakage,2576 * or we are lacking a whitespace-fix patch the tree2577 * the preimage was based on already had (i.e. target2578 * has whitespace breakage, the preimage doesn't).2579 * In either case, we are fixing the whitespace breakages2580 * so we might as well take the fix together with their2581 * real change.2582 */2583 match = (tgtfix.len == fixed.len - fixstart &&2584!memcmp(tgtfix.buf, fixed.buf + fixstart,2585 fixed.len - fixstart));25862587/* Add the length if this is common with the postimage */2588if(preimage->line[i].flag & LINE_COMMON)2589 postlen += tgtfix.len;25902591strbuf_release(&tgtfix);2592if(!match)2593goto unmatch_exit;25942595 orig += oldlen;2596 target += tgtlen;2597}259825992600/*2601 * Now handle the lines in the preimage that falls beyond the2602 * end of the file (if any). They will only match if they are2603 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2604 * false).2605 */2606for( ; i < preimage->nr; i++) {2607size_t fixstart = fixed.len;/* start of the fixed preimage */2608size_t oldlen = preimage->line[i].len;2609int j;26102611/* Try fixing the line in the preimage */2612ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);26132614for(j = fixstart; j < fixed.len; j++)2615if(!isspace(fixed.buf[j]))2616goto unmatch_exit;26172618 orig += oldlen;2619}26202621/*2622 * Yes, the preimage is based on an older version that still2623 * has whitespace breakages unfixed, and fixing them makes the2624 * hunk match. Update the context lines in the postimage.2625 */2626 fixed_buf =strbuf_detach(&fixed, &fixed_len);2627if(postlen < postimage->len)2628 postlen =0;2629update_pre_post_images(preimage, postimage,2630 fixed_buf, fixed_len, postlen);2631return1;26322633 unmatch_exit:2634strbuf_release(&fixed);2635return0;2636}26372638static intfind_pos(struct apply_state *state,2639struct image *img,2640struct image *preimage,2641struct image *postimage,2642int line,2643unsigned ws_rule,2644int match_beginning,int match_end)2645{2646int i;2647unsigned long backwards, forwards,try;2648int backwards_lno, forwards_lno, try_lno;26492650/*2651 * If match_beginning or match_end is specified, there is no2652 * point starting from a wrong line that will never match and2653 * wander around and wait for a match at the specified end.2654 */2655if(match_beginning)2656 line =0;2657else if(match_end)2658 line = img->nr - preimage->nr;26592660/*2661 * Because the comparison is unsigned, the following test2662 * will also take care of a negative line number that can2663 * result when match_end and preimage is larger than the target.2664 */2665if((size_t) line > img->nr)2666 line = img->nr;26672668try=0;2669for(i =0; i < line; i++)2670try+= img->line[i].len;26712672/*2673 * There's probably some smart way to do this, but I'll leave2674 * that to the smart and beautiful people. I'm simple and stupid.2675 */2676 backwards =try;2677 backwards_lno = line;2678 forwards =try;2679 forwards_lno = line;2680 try_lno = line;26812682for(i =0; ; i++) {2683if(match_fragment(state, img, preimage, postimage,2684try, try_lno, ws_rule,2685 match_beginning, match_end))2686return try_lno;26872688 again:2689if(backwards_lno ==0&& forwards_lno == img->nr)2690break;26912692if(i &1) {2693if(backwards_lno ==0) {2694 i++;2695goto again;2696}2697 backwards_lno--;2698 backwards -= img->line[backwards_lno].len;2699try= backwards;2700 try_lno = backwards_lno;2701}else{2702if(forwards_lno == img->nr) {2703 i++;2704goto again;2705}2706 forwards += img->line[forwards_lno].len;2707 forwards_lno++;2708try= forwards;2709 try_lno = forwards_lno;2710}27112712}2713return-1;2714}27152716static voidremove_first_line(struct image *img)2717{2718 img->buf += img->line[0].len;2719 img->len -= img->line[0].len;2720 img->line++;2721 img->nr--;2722}27232724static voidremove_last_line(struct image *img)2725{2726 img->len -= img->line[--img->nr].len;2727}27282729/*2730 * The change from "preimage" and "postimage" has been found to2731 * apply at applied_pos (counts in line numbers) in "img".2732 * Update "img" to remove "preimage" and replace it with "postimage".2733 */2734static voidupdate_image(struct apply_state *state,2735struct image *img,2736int applied_pos,2737struct image *preimage,2738struct image *postimage)2739{2740/*2741 * remove the copy of preimage at offset in img2742 * and replace it with postimage2743 */2744int i, nr;2745size_t remove_count, insert_count, applied_at =0;2746char*result;2747int preimage_limit;27482749/*2750 * If we are removing blank lines at the end of img,2751 * the preimage may extend beyond the end.2752 * If that is the case, we must be careful only to2753 * remove the part of the preimage that falls within2754 * the boundaries of img. Initialize preimage_limit2755 * to the number of lines in the preimage that falls2756 * within the boundaries.2757 */2758 preimage_limit = preimage->nr;2759if(preimage_limit > img->nr - applied_pos)2760 preimage_limit = img->nr - applied_pos;27612762for(i =0; i < applied_pos; i++)2763 applied_at += img->line[i].len;27642765 remove_count =0;2766for(i =0; i < preimage_limit; i++)2767 remove_count += img->line[applied_pos + i].len;2768 insert_count = postimage->len;27692770/* Adjust the contents */2771 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2772memcpy(result, img->buf, applied_at);2773memcpy(result + applied_at, postimage->buf, postimage->len);2774memcpy(result + applied_at + postimage->len,2775 img->buf + (applied_at + remove_count),2776 img->len - (applied_at + remove_count));2777free(img->buf);2778 img->buf = result;2779 img->len += insert_count - remove_count;2780 result[img->len] ='\0';27812782/* Adjust the line table */2783 nr = img->nr + postimage->nr - preimage_limit;2784if(preimage_limit < postimage->nr) {2785/*2786 * NOTE: this knows that we never call remove_first_line()2787 * on anything other than pre/post image.2788 */2789REALLOC_ARRAY(img->line, nr);2790 img->line_allocated = img->line;2791}2792if(preimage_limit != postimage->nr)2793memmove(img->line + applied_pos + postimage->nr,2794 img->line + applied_pos + preimage_limit,2795(img->nr - (applied_pos + preimage_limit)) *2796sizeof(*img->line));2797memcpy(img->line + applied_pos,2798 postimage->line,2799 postimage->nr *sizeof(*img->line));2800if(!state->allow_overlap)2801for(i =0; i < postimage->nr; i++)2802 img->line[applied_pos + i].flag |= LINE_PATCHED;2803 img->nr = nr;2804}28052806/*2807 * Use the patch-hunk text in "frag" to prepare two images (preimage and2808 * postimage) for the hunk. Find lines that match "preimage" in "img" and2809 * replace the part of "img" with "postimage" text.2810 */2811static intapply_one_fragment(struct apply_state *state,2812struct image *img,struct fragment *frag,2813int inaccurate_eof,unsigned ws_rule,2814int nth_fragment)2815{2816int match_beginning, match_end;2817const char*patch = frag->patch;2818int size = frag->size;2819char*old, *oldlines;2820struct strbuf newlines;2821int new_blank_lines_at_end =0;2822int found_new_blank_lines_at_end =0;2823int hunk_linenr = frag->linenr;2824unsigned long leading, trailing;2825int pos, applied_pos;2826struct image preimage;2827struct image postimage;28282829memset(&preimage,0,sizeof(preimage));2830memset(&postimage,0,sizeof(postimage));2831 oldlines =xmalloc(size);2832strbuf_init(&newlines, size);28332834 old = oldlines;2835while(size >0) {2836char first;2837int len =linelen(patch, size);2838int plen;2839int added_blank_line =0;2840int is_blank_context =0;2841size_t start;28422843if(!len)2844break;28452846/*2847 * "plen" is how much of the line we should use for2848 * the actual patch data. Normally we just remove the2849 * first character on the line, but if the line is2850 * followed by "\ No newline", then we also remove the2851 * last one (which is the newline, of course).2852 */2853 plen = len -1;2854if(len < size && patch[len] =='\\')2855 plen--;2856 first = *patch;2857if(state->apply_in_reverse) {2858if(first =='-')2859 first ='+';2860else if(first =='+')2861 first ='-';2862}28632864switch(first) {2865case'\n':2866/* Newer GNU diff, empty context line */2867if(plen <0)2868/* ... followed by '\No newline'; nothing */2869break;2870*old++ ='\n';2871strbuf_addch(&newlines,'\n');2872add_line_info(&preimage,"\n",1, LINE_COMMON);2873add_line_info(&postimage,"\n",1, LINE_COMMON);2874 is_blank_context =1;2875break;2876case' ':2877if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2878ws_blank_line(patch +1, plen, ws_rule))2879 is_blank_context =1;2880case'-':2881memcpy(old, patch +1, plen);2882add_line_info(&preimage, old, plen,2883(first ==' '? LINE_COMMON :0));2884 old += plen;2885if(first =='-')2886break;2887/* Fall-through for ' ' */2888case'+':2889/* --no-add does not add new lines */2890if(first =='+'&& state->no_add)2891break;28922893 start = newlines.len;2894if(first !='+'||2895!state->whitespace_error ||2896 state->ws_error_action != correct_ws_error) {2897strbuf_add(&newlines, patch +1, plen);2898}2899else{2900ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2901}2902add_line_info(&postimage, newlines.buf + start, newlines.len - start,2903(first =='+'?0: LINE_COMMON));2904if(first =='+'&&2905(ws_rule & WS_BLANK_AT_EOF) &&2906ws_blank_line(patch +1, plen, ws_rule))2907 added_blank_line =1;2908break;2909case'@':case'\\':2910/* Ignore it, we already handled it */2911break;2912default:2913if(state->apply_verbosely)2914error(_("invalid start of line: '%c'"), first);2915 applied_pos = -1;2916goto out;2917}2918if(added_blank_line) {2919if(!new_blank_lines_at_end)2920 found_new_blank_lines_at_end = hunk_linenr;2921 new_blank_lines_at_end++;2922}2923else if(is_blank_context)2924;2925else2926 new_blank_lines_at_end =0;2927 patch += len;2928 size -= len;2929 hunk_linenr++;2930}2931if(inaccurate_eof &&2932 old > oldlines && old[-1] =='\n'&&2933 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2934 old--;2935strbuf_setlen(&newlines, newlines.len -1);2936}29372938 leading = frag->leading;2939 trailing = frag->trailing;29402941/*2942 * A hunk to change lines at the beginning would begin with2943 * @@ -1,L +N,M @@2944 * but we need to be careful. -U0 that inserts before the second2945 * line also has this pattern.2946 *2947 * And a hunk to add to an empty file would begin with2948 * @@ -0,0 +N,M @@2949 *2950 * In other words, a hunk that is (frag->oldpos <= 1) with or2951 * without leading context must match at the beginning.2952 */2953 match_beginning = (!frag->oldpos ||2954(frag->oldpos ==1&& !state->unidiff_zero));29552956/*2957 * A hunk without trailing lines must match at the end.2958 * However, we simply cannot tell if a hunk must match end2959 * from the lack of trailing lines if the patch was generated2960 * with unidiff without any context.2961 */2962 match_end = !state->unidiff_zero && !trailing;29632964 pos = frag->newpos ? (frag->newpos -1) :0;2965 preimage.buf = oldlines;2966 preimage.len = old - oldlines;2967 postimage.buf = newlines.buf;2968 postimage.len = newlines.len;2969 preimage.line = preimage.line_allocated;2970 postimage.line = postimage.line_allocated;29712972for(;;) {29732974 applied_pos =find_pos(state, img, &preimage, &postimage, pos,2975 ws_rule, match_beginning, match_end);29762977if(applied_pos >=0)2978break;29792980/* Am I at my context limits? */2981if((leading <= state->p_context) && (trailing <= state->p_context))2982break;2983if(match_beginning || match_end) {2984 match_beginning = match_end =0;2985continue;2986}29872988/*2989 * Reduce the number of context lines; reduce both2990 * leading and trailing if they are equal otherwise2991 * just reduce the larger context.2992 */2993if(leading >= trailing) {2994remove_first_line(&preimage);2995remove_first_line(&postimage);2996 pos--;2997 leading--;2998}2999if(trailing > leading) {3000remove_last_line(&preimage);3001remove_last_line(&postimage);3002 trailing--;3003}3004}30053006if(applied_pos >=0) {3007if(new_blank_lines_at_end &&3008 preimage.nr + applied_pos >= img->nr &&3009(ws_rule & WS_BLANK_AT_EOF) &&3010 state->ws_error_action != nowarn_ws_error) {3011record_ws_error(state, WS_BLANK_AT_EOF,"+",1,3012 found_new_blank_lines_at_end);3013if(state->ws_error_action == correct_ws_error) {3014while(new_blank_lines_at_end--)3015remove_last_line(&postimage);3016}3017/*3018 * We would want to prevent write_out_results()3019 * from taking place in apply_patch() that follows3020 * the callchain led us here, which is:3021 * apply_patch->check_patch_list->check_patch->3022 * apply_data->apply_fragments->apply_one_fragment3023 */3024if(state->ws_error_action == die_on_ws_error)3025 state->apply =0;3026}30273028if(state->apply_verbosely && applied_pos != pos) {3029int offset = applied_pos - pos;3030if(state->apply_in_reverse)3031 offset =0- offset;3032fprintf_ln(stderr,3033Q_("Hunk #%dsucceeded at%d(offset%dline).",3034"Hunk #%dsucceeded at%d(offset%dlines).",3035 offset),3036 nth_fragment, applied_pos +1, offset);3037}30383039/*3040 * Warn if it was necessary to reduce the number3041 * of context lines.3042 */3043if((leading != frag->leading) ||3044(trailing != frag->trailing))3045fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"3046" to apply fragment at%d"),3047 leading, trailing, applied_pos+1);3048update_image(state, img, applied_pos, &preimage, &postimage);3049}else{3050if(state->apply_verbosely)3051error(_("while searching for:\n%.*s"),3052(int)(old - oldlines), oldlines);3053}30543055out:3056free(oldlines);3057strbuf_release(&newlines);3058free(preimage.line_allocated);3059free(postimage.line_allocated);30603061return(applied_pos <0);3062}30633064static intapply_binary_fragment(struct apply_state *state,3065struct image *img,3066struct patch *patch)3067{3068struct fragment *fragment = patch->fragments;3069unsigned long len;3070void*dst;30713072if(!fragment)3073returnerror(_("missing binary patch data for '%s'"),3074 patch->new_name ?3075 patch->new_name :3076 patch->old_name);30773078/* Binary patch is irreversible without the optional second hunk */3079if(state->apply_in_reverse) {3080if(!fragment->next)3081returnerror("cannot reverse-apply a binary patch "3082"without the reverse hunk to '%s'",3083 patch->new_name3084? patch->new_name : patch->old_name);3085 fragment = fragment->next;3086}3087switch(fragment->binary_patch_method) {3088case BINARY_DELTA_DEFLATED:3089 dst =patch_delta(img->buf, img->len, fragment->patch,3090 fragment->size, &len);3091if(!dst)3092return-1;3093clear_image(img);3094 img->buf = dst;3095 img->len = len;3096return0;3097case BINARY_LITERAL_DEFLATED:3098clear_image(img);3099 img->len = fragment->size;3100 img->buf =xmemdupz(fragment->patch, img->len);3101return0;3102}3103return-1;3104}31053106/*3107 * Replace "img" with the result of applying the binary patch.3108 * The binary patch data itself in patch->fragment is still kept3109 * but the preimage prepared by the caller in "img" is freed here3110 * or in the helper function apply_binary_fragment() this calls.3111 */3112static intapply_binary(struct apply_state *state,3113struct image *img,3114struct patch *patch)3115{3116const char*name = patch->old_name ? patch->old_name : patch->new_name;3117unsigned char sha1[20];31183119/*3120 * For safety, we require patch index line to contain3121 * full 40-byte textual SHA1 for old and new, at least for now.3122 */3123if(strlen(patch->old_sha1_prefix) !=40||3124strlen(patch->new_sha1_prefix) !=40||3125get_sha1_hex(patch->old_sha1_prefix, sha1) ||3126get_sha1_hex(patch->new_sha1_prefix, sha1))3127returnerror("cannot apply binary patch to '%s' "3128"without full index line", name);31293130if(patch->old_name) {3131/*3132 * See if the old one matches what the patch3133 * applies to.3134 */3135hash_sha1_file(img->buf, img->len, blob_type, sha1);3136if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3137returnerror("the patch applies to '%s' (%s), "3138"which does not match the "3139"current contents.",3140 name,sha1_to_hex(sha1));3141}3142else{3143/* Otherwise, the old one must be empty. */3144if(img->len)3145returnerror("the patch applies to an empty "3146"'%s' but it is not empty", name);3147}31483149get_sha1_hex(patch->new_sha1_prefix, sha1);3150if(is_null_sha1(sha1)) {3151clear_image(img);3152return0;/* deletion patch */3153}31543155if(has_sha1_file(sha1)) {3156/* We already have the postimage */3157enum object_type type;3158unsigned long size;3159char*result;31603161 result =read_sha1_file(sha1, &type, &size);3162if(!result)3163returnerror("the necessary postimage%sfor "3164"'%s' cannot be read",3165 patch->new_sha1_prefix, name);3166clear_image(img);3167 img->buf = result;3168 img->len = size;3169}else{3170/*3171 * We have verified buf matches the preimage;3172 * apply the patch data to it, which is stored3173 * in the patch->fragments->{patch,size}.3174 */3175if(apply_binary_fragment(state, img, patch))3176returnerror(_("binary patch does not apply to '%s'"),3177 name);31783179/* verify that the result matches */3180hash_sha1_file(img->buf, img->len, blob_type, sha1);3181if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3182returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3183 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3184}31853186return0;3187}31883189static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3190{3191struct fragment *frag = patch->fragments;3192const char*name = patch->old_name ? patch->old_name : patch->new_name;3193unsigned ws_rule = patch->ws_rule;3194unsigned inaccurate_eof = patch->inaccurate_eof;3195int nth =0;31963197if(patch->is_binary)3198returnapply_binary(state, img, patch);31993200while(frag) {3201 nth++;3202if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3203error(_("patch failed:%s:%ld"), name, frag->oldpos);3204if(!state->apply_with_reject)3205return-1;3206 frag->rejected =1;3207}3208 frag = frag->next;3209}3210return0;3211}32123213static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3214{3215if(S_ISGITLINK(mode)) {3216strbuf_grow(buf,100);3217strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3218}else{3219enum object_type type;3220unsigned long sz;3221char*result;32223223 result =read_sha1_file(sha1, &type, &sz);3224if(!result)3225return-1;3226/* XXX read_sha1_file NUL-terminates */3227strbuf_attach(buf, result, sz, sz +1);3228}3229return0;3230}32313232static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3233{3234if(!ce)3235return0;3236returnread_blob_object(buf, ce->sha1, ce->ce_mode);3237}32383239static struct patch *in_fn_table(struct apply_state *state,const char*name)3240{3241struct string_list_item *item;32423243if(name == NULL)3244return NULL;32453246 item =string_list_lookup(&state->fn_table, name);3247if(item != NULL)3248return(struct patch *)item->util;32493250return NULL;3251}32523253/*3254 * item->util in the filename table records the status of the path.3255 * Usually it points at a patch (whose result records the contents3256 * of it after applying it), but it could be PATH_WAS_DELETED for a3257 * path that a previously applied patch has already removed, or3258 * PATH_TO_BE_DELETED for a path that a later patch would remove.3259 *3260 * The latter is needed to deal with a case where two paths A and B3261 * are swapped by first renaming A to B and then renaming B to A;3262 * moving A to B should not be prevented due to presence of B as we3263 * will remove it in a later patch.3264 */3265#define PATH_TO_BE_DELETED ((struct patch *) -2)3266#define PATH_WAS_DELETED ((struct patch *) -1)32673268static intto_be_deleted(struct patch *patch)3269{3270return patch == PATH_TO_BE_DELETED;3271}32723273static intwas_deleted(struct patch *patch)3274{3275return patch == PATH_WAS_DELETED;3276}32773278static voidadd_to_fn_table(struct apply_state *state,struct patch *patch)3279{3280struct string_list_item *item;32813282/*3283 * Always add new_name unless patch is a deletion3284 * This should cover the cases for normal diffs,3285 * file creations and copies3286 */3287if(patch->new_name != NULL) {3288 item =string_list_insert(&state->fn_table, patch->new_name);3289 item->util = patch;3290}32913292/*3293 * store a failure on rename/deletion cases because3294 * later chunks shouldn't patch old names3295 */3296if((patch->new_name == NULL) || (patch->is_rename)) {3297 item =string_list_insert(&state->fn_table, patch->old_name);3298 item->util = PATH_WAS_DELETED;3299}3300}33013302static voidprepare_fn_table(struct apply_state *state,struct patch *patch)3303{3304/*3305 * store information about incoming file deletion3306 */3307while(patch) {3308if((patch->new_name == NULL) || (patch->is_rename)) {3309struct string_list_item *item;3310 item =string_list_insert(&state->fn_table, patch->old_name);3311 item->util = PATH_TO_BE_DELETED;3312}3313 patch = patch->next;3314}3315}33163317static intcheckout_target(struct index_state *istate,3318struct cache_entry *ce,struct stat *st)3319{3320struct checkout costate;33213322memset(&costate,0,sizeof(costate));3323 costate.base_dir ="";3324 costate.refresh_cache =1;3325 costate.istate = istate;3326if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3327returnerror(_("cannot checkout%s"), ce->name);3328return0;3329}33303331static struct patch *previous_patch(struct apply_state *state,3332struct patch *patch,3333int*gone)3334{3335struct patch *previous;33363337*gone =0;3338if(patch->is_copy || patch->is_rename)3339return NULL;/* "git" patches do not depend on the order */33403341 previous =in_fn_table(state, patch->old_name);3342if(!previous)3343return NULL;33443345if(to_be_deleted(previous))3346return NULL;/* the deletion hasn't happened yet */33473348if(was_deleted(previous))3349*gone =1;33503351return previous;3352}33533354static intverify_index_match(const struct cache_entry *ce,struct stat *st)3355{3356if(S_ISGITLINK(ce->ce_mode)) {3357if(!S_ISDIR(st->st_mode))3358return-1;3359return0;3360}3361returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3362}33633364#define SUBMODULE_PATCH_WITHOUT_INDEX 133653366static intload_patch_target(struct apply_state *state,3367struct strbuf *buf,3368const struct cache_entry *ce,3369struct stat *st,3370const char*name,3371unsigned expected_mode)3372{3373if(state->cached || state->check_index) {3374if(read_file_or_gitlink(ce, buf))3375returnerror(_("failed to read%s"), name);3376}else if(name) {3377if(S_ISGITLINK(expected_mode)) {3378if(ce)3379returnread_file_or_gitlink(ce, buf);3380else3381return SUBMODULE_PATCH_WITHOUT_INDEX;3382}else if(has_symlink_leading_path(name,strlen(name))) {3383returnerror(_("reading from '%s' beyond a symbolic link"), name);3384}else{3385if(read_old_data(st, name, buf))3386returnerror(_("failed to read%s"), name);3387}3388}3389return0;3390}33913392/*3393 * We are about to apply "patch"; populate the "image" with the3394 * current version we have, from the working tree or from the index,3395 * depending on the situation e.g. --cached/--index. If we are3396 * applying a non-git patch that incrementally updates the tree,3397 * we read from the result of a previous diff.3398 */3399static intload_preimage(struct apply_state *state,3400struct image *image,3401struct patch *patch,struct stat *st,3402const struct cache_entry *ce)3403{3404struct strbuf buf = STRBUF_INIT;3405size_t len;3406char*img;3407struct patch *previous;3408int status;34093410 previous =previous_patch(state, patch, &status);3411if(status)3412returnerror(_("path%shas been renamed/deleted"),3413 patch->old_name);3414if(previous) {3415/* We have a patched copy in memory; use that. */3416strbuf_add(&buf, previous->result, previous->resultsize);3417}else{3418 status =load_patch_target(state, &buf, ce, st,3419 patch->old_name, patch->old_mode);3420if(status <0)3421return status;3422else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3423/*3424 * There is no way to apply subproject3425 * patch without looking at the index.3426 * NEEDSWORK: shouldn't this be flagged3427 * as an error???3428 */3429free_fragment_list(patch->fragments);3430 patch->fragments = NULL;3431}else if(status) {3432returnerror(_("failed to read%s"), patch->old_name);3433}3434}34353436 img =strbuf_detach(&buf, &len);3437prepare_image(image, img, len, !patch->is_binary);3438return0;3439}34403441static intthree_way_merge(struct image *image,3442char*path,3443const unsigned char*base,3444const unsigned char*ours,3445const unsigned char*theirs)3446{3447 mmfile_t base_file, our_file, their_file;3448 mmbuffer_t result = { NULL };3449int status;34503451read_mmblob(&base_file, base);3452read_mmblob(&our_file, ours);3453read_mmblob(&their_file, theirs);3454 status =ll_merge(&result, path,3455&base_file,"base",3456&our_file,"ours",3457&their_file,"theirs", NULL);3458free(base_file.ptr);3459free(our_file.ptr);3460free(their_file.ptr);3461if(status <0|| !result.ptr) {3462free(result.ptr);3463return-1;3464}3465clear_image(image);3466 image->buf = result.ptr;3467 image->len = result.size;34683469return status;3470}34713472/*3473 * When directly falling back to add/add three-way merge, we read from3474 * the current contents of the new_name. In no cases other than that3475 * this function will be called.3476 */3477static intload_current(struct apply_state *state,3478struct image *image,3479struct patch *patch)3480{3481struct strbuf buf = STRBUF_INIT;3482int status, pos;3483size_t len;3484char*img;3485struct stat st;3486struct cache_entry *ce;3487char*name = patch->new_name;3488unsigned mode = patch->new_mode;34893490if(!patch->is_new)3491die("BUG: patch to%sis not a creation", patch->old_name);34923493 pos =cache_name_pos(name,strlen(name));3494if(pos <0)3495returnerror(_("%s: does not exist in index"), name);3496 ce = active_cache[pos];3497if(lstat(name, &st)) {3498if(errno != ENOENT)3499returnerror(_("%s:%s"), name,strerror(errno));3500if(checkout_target(&the_index, ce, &st))3501return-1;3502}3503if(verify_index_match(ce, &st))3504returnerror(_("%s: does not match index"), name);35053506 status =load_patch_target(state, &buf, ce, &st, name, mode);3507if(status <0)3508return status;3509else if(status)3510return-1;3511 img =strbuf_detach(&buf, &len);3512prepare_image(image, img, len, !patch->is_binary);3513return0;3514}35153516static inttry_threeway(struct apply_state *state,3517struct image *image,3518struct patch *patch,3519struct stat *st,3520const struct cache_entry *ce)3521{3522unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3523struct strbuf buf = STRBUF_INIT;3524size_t len;3525int status;3526char*img;3527struct image tmp_image;35283529/* No point falling back to 3-way merge in these cases */3530if(patch->is_delete ||3531S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3532return-1;35333534/* Preimage the patch was prepared for */3535if(patch->is_new)3536write_sha1_file("",0, blob_type, pre_sha1);3537else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3538read_blob_object(&buf, pre_sha1, patch->old_mode))3539returnerror("repository lacks the necessary blob to fall back on 3-way merge.");35403541fprintf(stderr,"Falling back to three-way merge...\n");35423543 img =strbuf_detach(&buf, &len);3544prepare_image(&tmp_image, img, len,1);3545/* Apply the patch to get the post image */3546if(apply_fragments(state, &tmp_image, patch) <0) {3547clear_image(&tmp_image);3548return-1;3549}3550/* post_sha1[] is theirs */3551write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3552clear_image(&tmp_image);35533554/* our_sha1[] is ours */3555if(patch->is_new) {3556if(load_current(state, &tmp_image, patch))3557returnerror("cannot read the current contents of '%s'",3558 patch->new_name);3559}else{3560if(load_preimage(state, &tmp_image, patch, st, ce))3561returnerror("cannot read the current contents of '%s'",3562 patch->old_name);3563}3564write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3565clear_image(&tmp_image);35663567/* in-core three-way merge between post and our using pre as base */3568 status =three_way_merge(image, patch->new_name,3569 pre_sha1, our_sha1, post_sha1);3570if(status <0) {3571fprintf(stderr,"Failed to fall back on three-way merge...\n");3572return status;3573}35743575if(status) {3576 patch->conflicted_threeway =1;3577if(patch->is_new)3578oidclr(&patch->threeway_stage[0]);3579else3580hashcpy(patch->threeway_stage[0].hash, pre_sha1);3581hashcpy(patch->threeway_stage[1].hash, our_sha1);3582hashcpy(patch->threeway_stage[2].hash, post_sha1);3583fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3584}else{3585fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3586}3587return0;3588}35893590static intapply_data(struct apply_state *state,struct patch *patch,3591struct stat *st,const struct cache_entry *ce)3592{3593struct image image;35943595if(load_preimage(state, &image, patch, st, ce) <0)3596return-1;35973598if(patch->direct_to_threeway ||3599apply_fragments(state, &image, patch) <0) {3600/* Note: with --reject, apply_fragments() returns 0 */3601if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3602return-1;3603}3604 patch->result = image.buf;3605 patch->resultsize = image.len;3606add_to_fn_table(state, patch);3607free(image.line_allocated);36083609if(0< patch->is_delete && patch->resultsize)3610returnerror(_("removal patch leaves file contents"));36113612return0;3613}36143615/*3616 * If "patch" that we are looking at modifies or deletes what we have,3617 * we would want it not to lose any local modification we have, either3618 * in the working tree or in the index.3619 *3620 * This also decides if a non-git patch is a creation patch or a3621 * modification to an existing empty file. We do not check the state3622 * of the current tree for a creation patch in this function; the caller3623 * check_patch() separately makes sure (and errors out otherwise) that3624 * the path the patch creates does not exist in the current tree.3625 */3626static intcheck_preimage(struct apply_state *state,3627struct patch *patch,3628struct cache_entry **ce,3629struct stat *st)3630{3631const char*old_name = patch->old_name;3632struct patch *previous = NULL;3633int stat_ret =0, status;3634unsigned st_mode =0;36353636if(!old_name)3637return0;36383639assert(patch->is_new <=0);3640 previous =previous_patch(state, patch, &status);36413642if(status)3643returnerror(_("path%shas been renamed/deleted"), old_name);3644if(previous) {3645 st_mode = previous->new_mode;3646}else if(!state->cached) {3647 stat_ret =lstat(old_name, st);3648if(stat_ret && errno != ENOENT)3649returnerror(_("%s:%s"), old_name,strerror(errno));3650}36513652if(state->check_index && !previous) {3653int pos =cache_name_pos(old_name,strlen(old_name));3654if(pos <0) {3655if(patch->is_new <0)3656goto is_new;3657returnerror(_("%s: does not exist in index"), old_name);3658}3659*ce = active_cache[pos];3660if(stat_ret <0) {3661if(checkout_target(&the_index, *ce, st))3662return-1;3663}3664if(!state->cached &&verify_index_match(*ce, st))3665returnerror(_("%s: does not match index"), old_name);3666if(state->cached)3667 st_mode = (*ce)->ce_mode;3668}else if(stat_ret <0) {3669if(patch->is_new <0)3670goto is_new;3671returnerror(_("%s:%s"), old_name,strerror(errno));3672}36733674if(!state->cached && !previous)3675 st_mode =ce_mode_from_stat(*ce, st->st_mode);36763677if(patch->is_new <0)3678 patch->is_new =0;3679if(!patch->old_mode)3680 patch->old_mode = st_mode;3681if((st_mode ^ patch->old_mode) & S_IFMT)3682returnerror(_("%s: wrong type"), old_name);3683if(st_mode != patch->old_mode)3684warning(_("%shas type%o, expected%o"),3685 old_name, st_mode, patch->old_mode);3686if(!patch->new_mode && !patch->is_delete)3687 patch->new_mode = st_mode;3688return0;36893690 is_new:3691 patch->is_new =1;3692 patch->is_delete =0;3693free(patch->old_name);3694 patch->old_name = NULL;3695return0;3696}369736983699#define EXISTS_IN_INDEX 13700#define EXISTS_IN_WORKTREE 237013702static intcheck_to_create(struct apply_state *state,3703const char*new_name,3704int ok_if_exists)3705{3706struct stat nst;37073708if(state->check_index &&3709cache_name_pos(new_name,strlen(new_name)) >=0&&3710!ok_if_exists)3711return EXISTS_IN_INDEX;3712if(state->cached)3713return0;37143715if(!lstat(new_name, &nst)) {3716if(S_ISDIR(nst.st_mode) || ok_if_exists)3717return0;3718/*3719 * A leading component of new_name might be a symlink3720 * that is going to be removed with this patch, but3721 * still pointing at somewhere that has the path.3722 * In such a case, path "new_name" does not exist as3723 * far as git is concerned.3724 */3725if(has_symlink_leading_path(new_name,strlen(new_name)))3726return0;37273728return EXISTS_IN_WORKTREE;3729}else if((errno != ENOENT) && (errno != ENOTDIR)) {3730returnerror("%s:%s", new_name,strerror(errno));3731}3732return0;3733}37343735static uintptr_tregister_symlink_changes(struct apply_state *state,3736const char*path,3737uintptr_t what)3738{3739struct string_list_item *ent;37403741 ent =string_list_lookup(&state->symlink_changes, path);3742if(!ent) {3743 ent =string_list_insert(&state->symlink_changes, path);3744 ent->util = (void*)0;3745}3746 ent->util = (void*)(what | ((uintptr_t)ent->util));3747return(uintptr_t)ent->util;3748}37493750static uintptr_tcheck_symlink_changes(struct apply_state *state,const char*path)3751{3752struct string_list_item *ent;37533754 ent =string_list_lookup(&state->symlink_changes, path);3755if(!ent)3756return0;3757return(uintptr_t)ent->util;3758}37593760static voidprepare_symlink_changes(struct apply_state *state,struct patch *patch)3761{3762for( ; patch; patch = patch->next) {3763if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3764(patch->is_rename || patch->is_delete))3765/* the symlink at patch->old_name is removed */3766register_symlink_changes(state, patch->old_name, APPLY_SYMLINK_GOES_AWAY);37673768if(patch->new_name &&S_ISLNK(patch->new_mode))3769/* the symlink at patch->new_name is created or remains */3770register_symlink_changes(state, patch->new_name, APPLY_SYMLINK_IN_RESULT);3771}3772}37733774static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3775{3776do{3777unsigned int change;37783779while(--name->len && name->buf[name->len] !='/')3780;/* scan backwards */3781if(!name->len)3782break;3783 name->buf[name->len] ='\0';3784 change =check_symlink_changes(state, name->buf);3785if(change & APPLY_SYMLINK_IN_RESULT)3786return1;3787if(change & APPLY_SYMLINK_GOES_AWAY)3788/*3789 * This cannot be "return 0", because we may3790 * see a new one created at a higher level.3791 */3792continue;37933794/* otherwise, check the preimage */3795if(state->check_index) {3796struct cache_entry *ce;37973798 ce =cache_file_exists(name->buf, name->len, ignore_case);3799if(ce &&S_ISLNK(ce->ce_mode))3800return1;3801}else{3802struct stat st;3803if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3804return1;3805}3806}while(1);3807return0;3808}38093810static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3811{3812int ret;3813struct strbuf name = STRBUF_INIT;38143815assert(*name_ !='\0');3816strbuf_addstr(&name, name_);3817 ret =path_is_beyond_symlink_1(state, &name);3818strbuf_release(&name);38193820return ret;3821}38223823static intcheck_unsafe_path(struct patch *patch)3824{3825const char*old_name = NULL;3826const char*new_name = NULL;3827if(patch->is_delete)3828 old_name = patch->old_name;3829else if(!patch->is_new && !patch->is_copy)3830 old_name = patch->old_name;3831if(!patch->is_delete)3832 new_name = patch->new_name;38333834if(old_name && !verify_path(old_name))3835returnerror(_("invalid path '%s'"), old_name);3836if(new_name && !verify_path(new_name))3837returnerror(_("invalid path '%s'"), new_name);3838return0;3839}38403841/*3842 * Check and apply the patch in-core; leave the result in patch->result3843 * for the caller to write it out to the final destination.3844 */3845static intcheck_patch(struct apply_state *state,struct patch *patch)3846{3847struct stat st;3848const char*old_name = patch->old_name;3849const char*new_name = patch->new_name;3850const char*name = old_name ? old_name : new_name;3851struct cache_entry *ce = NULL;3852struct patch *tpatch;3853int ok_if_exists;3854int status;38553856 patch->rejected =1;/* we will drop this after we succeed */38573858 status =check_preimage(state, patch, &ce, &st);3859if(status)3860return status;3861 old_name = patch->old_name;38623863/*3864 * A type-change diff is always split into a patch to delete3865 * old, immediately followed by a patch to create new (see3866 * diff.c::run_diff()); in such a case it is Ok that the entry3867 * to be deleted by the previous patch is still in the working3868 * tree and in the index.3869 *3870 * A patch to swap-rename between A and B would first rename A3871 * to B and then rename B to A. While applying the first one,3872 * the presence of B should not stop A from getting renamed to3873 * B; ask to_be_deleted() about the later rename. Removal of3874 * B and rename from A to B is handled the same way by asking3875 * was_deleted().3876 */3877if((tpatch =in_fn_table(state, new_name)) &&3878(was_deleted(tpatch) ||to_be_deleted(tpatch)))3879 ok_if_exists =1;3880else3881 ok_if_exists =0;38823883if(new_name &&3884((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3885int err =check_to_create(state, new_name, ok_if_exists);38863887if(err && state->threeway) {3888 patch->direct_to_threeway =1;3889}else switch(err) {3890case0:3891break;/* happy */3892case EXISTS_IN_INDEX:3893returnerror(_("%s: already exists in index"), new_name);3894break;3895case EXISTS_IN_WORKTREE:3896returnerror(_("%s: already exists in working directory"),3897 new_name);3898default:3899return err;3900}39013902if(!patch->new_mode) {3903if(0< patch->is_new)3904 patch->new_mode = S_IFREG |0644;3905else3906 patch->new_mode = patch->old_mode;3907}3908}39093910if(new_name && old_name) {3911int same = !strcmp(old_name, new_name);3912if(!patch->new_mode)3913 patch->new_mode = patch->old_mode;3914if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3915if(same)3916returnerror(_("new mode (%o) of%sdoes not "3917"match old mode (%o)"),3918 patch->new_mode, new_name,3919 patch->old_mode);3920else3921returnerror(_("new mode (%o) of%sdoes not "3922"match old mode (%o) of%s"),3923 patch->new_mode, new_name,3924 patch->old_mode, old_name);3925}3926}39273928if(!state->unsafe_paths &&check_unsafe_path(patch))3929return-128;39303931/*3932 * An attempt to read from or delete a path that is beyond a3933 * symbolic link will be prevented by load_patch_target() that3934 * is called at the beginning of apply_data() so we do not3935 * have to worry about a patch marked with "is_delete" bit3936 * here. We however need to make sure that the patch result3937 * is not deposited to a path that is beyond a symbolic link3938 * here.3939 */3940if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3941returnerror(_("affected file '%s' is beyond a symbolic link"),3942 patch->new_name);39433944if(apply_data(state, patch, &st, ce) <0)3945returnerror(_("%s: patch does not apply"), name);3946 patch->rejected =0;3947return0;3948}39493950static intcheck_patch_list(struct apply_state *state,struct patch *patch)3951{3952int err =0;39533954prepare_symlink_changes(state, patch);3955prepare_fn_table(state, patch);3956while(patch) {3957int res;3958if(state->apply_verbosely)3959say_patch_name(stderr,3960_("Checking patch%s..."), patch);3961 res =check_patch(state, patch);3962if(res == -128)3963return-128;3964 err |= res;3965 patch = patch->next;3966}3967return err;3968}39693970/* This function tries to read the sha1 from the current index */3971static intget_current_sha1(const char*path,unsigned char*sha1)3972{3973int pos;39743975if(read_cache() <0)3976return-1;3977 pos =cache_name_pos(path,strlen(path));3978if(pos <0)3979return-1;3980hashcpy(sha1, active_cache[pos]->sha1);3981return0;3982}39833984static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3985{3986/*3987 * A usable gitlink patch has only one fragment (hunk) that looks like:3988 * @@ -1 +1 @@3989 * -Subproject commit <old sha1>3990 * +Subproject commit <new sha1>3991 * or3992 * @@ -1 +0,0 @@3993 * -Subproject commit <old sha1>3994 * for a removal patch.3995 */3996struct fragment *hunk = p->fragments;3997static const char heading[] ="-Subproject commit ";3998char*preimage;39994000if(/* does the patch have only one hunk? */4001 hunk && !hunk->next &&4002/* is its preimage one line? */4003 hunk->oldpos ==1&& hunk->oldlines ==1&&4004/* does preimage begin with the heading? */4005(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&4006starts_with(++preimage, heading) &&4007/* does it record full SHA-1? */4008!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&4009 preimage[sizeof(heading) +40-1] =='\n'&&4010/* does the abbreviated name on the index line agree with it? */4011starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))4012return0;/* it all looks fine */40134014/* we may have full object name on the index line */4015returnget_sha1_hex(p->old_sha1_prefix, sha1);4016}40174018/* Build an index that contains the just the files needed for a 3way merge */4019static intbuild_fake_ancestor(struct patch *list,const char*filename)4020{4021struct patch *patch;4022struct index_state result = { NULL };4023static struct lock_file lock;4024int res;40254026/* Once we start supporting the reverse patch, it may be4027 * worth showing the new sha1 prefix, but until then...4028 */4029for(patch = list; patch; patch = patch->next) {4030unsigned char sha1[20];4031struct cache_entry *ce;4032const char*name;40334034 name = patch->old_name ? patch->old_name : patch->new_name;4035if(0< patch->is_new)4036continue;40374038if(S_ISGITLINK(patch->old_mode)) {4039if(!preimage_sha1_in_gitlink_patch(patch, sha1))4040;/* ok, the textual part looks sane */4041else4042returnerror("sha1 information is lacking or "4043"useless for submodule%s", name);4044}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {4045;/* ok */4046}else if(!patch->lines_added && !patch->lines_deleted) {4047/* mode-only change: update the current */4048if(get_current_sha1(patch->old_name, sha1))4049returnerror("mode change for%s, which is not "4050"in current HEAD", name);4051}else4052returnerror("sha1 information is lacking or useless "4053"(%s).", name);40544055 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);4056if(!ce)4057returnerror(_("make_cache_entry failed for path '%s'"),4058 name);4059if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) {4060free(ce);4061returnerror("Could not add%sto temporary index",4062 name);4063}4064}40654066hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);4067 res =write_locked_index(&result, &lock, COMMIT_LOCK);4068discard_index(&result);40694070if(res)4071returnerror("Could not write temporary index to%s", filename);40724073return0;4074}40754076static voidstat_patch_list(struct apply_state *state,struct patch *patch)4077{4078int files, adds, dels;40794080for(files = adds = dels =0; patch ; patch = patch->next) {4081 files++;4082 adds += patch->lines_added;4083 dels += patch->lines_deleted;4084show_stats(state, patch);4085}40864087print_stat_summary(stdout, files, adds, dels);4088}40894090static voidnumstat_patch_list(struct apply_state *state,4091struct patch *patch)4092{4093for( ; patch; patch = patch->next) {4094const char*name;4095 name = patch->new_name ? patch->new_name : patch->old_name;4096if(patch->is_binary)4097printf("-\t-\t");4098else4099printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4100write_name_quoted(name, stdout, state->line_termination);4101}4102}41034104static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4105{4106if(mode)4107printf("%smode%06o%s\n", newdelete, mode, name);4108else4109printf("%s %s\n", newdelete, name);4110}41114112static voidshow_mode_change(struct patch *p,int show_name)4113{4114if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4115if(show_name)4116printf(" mode change%06o =>%06o%s\n",4117 p->old_mode, p->new_mode, p->new_name);4118else4119printf(" mode change%06o =>%06o\n",4120 p->old_mode, p->new_mode);4121}4122}41234124static voidshow_rename_copy(struct patch *p)4125{4126const char*renamecopy = p->is_rename ?"rename":"copy";4127const char*old, *new;41284129/* Find common prefix */4130 old = p->old_name;4131new= p->new_name;4132while(1) {4133const char*slash_old, *slash_new;4134 slash_old =strchr(old,'/');4135 slash_new =strchr(new,'/');4136if(!slash_old ||4137!slash_new ||4138 slash_old - old != slash_new -new||4139memcmp(old,new, slash_new -new))4140break;4141 old = slash_old +1;4142new= slash_new +1;4143}4144/* p->old_name thru old is the common prefix, and old and new4145 * through the end of names are renames4146 */4147if(old != p->old_name)4148printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4149(int)(old - p->old_name), p->old_name,4150 old,new, p->score);4151else4152printf("%s %s=>%s(%d%%)\n", renamecopy,4153 p->old_name, p->new_name, p->score);4154show_mode_change(p,0);4155}41564157static voidsummary_patch_list(struct patch *patch)4158{4159struct patch *p;41604161for(p = patch; p; p = p->next) {4162if(p->is_new)4163show_file_mode_name("create", p->new_mode, p->new_name);4164else if(p->is_delete)4165show_file_mode_name("delete", p->old_mode, p->old_name);4166else{4167if(p->is_rename || p->is_copy)4168show_rename_copy(p);4169else{4170if(p->score) {4171printf(" rewrite%s(%d%%)\n",4172 p->new_name, p->score);4173show_mode_change(p,0);4174}4175else4176show_mode_change(p,1);4177}4178}4179}4180}41814182static voidpatch_stats(struct apply_state *state,struct patch *patch)4183{4184int lines = patch->lines_added + patch->lines_deleted;41854186if(lines > state->max_change)4187 state->max_change = lines;4188if(patch->old_name) {4189int len =quote_c_style(patch->old_name, NULL, NULL,0);4190if(!len)4191 len =strlen(patch->old_name);4192if(len > state->max_len)4193 state->max_len = len;4194}4195if(patch->new_name) {4196int len =quote_c_style(patch->new_name, NULL, NULL,0);4197if(!len)4198 len =strlen(patch->new_name);4199if(len > state->max_len)4200 state->max_len = len;4201}4202}42034204static intremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4205{4206if(state->update_index) {4207if(remove_file_from_cache(patch->old_name) <0)4208returnerror(_("unable to remove%sfrom index"), patch->old_name);4209}4210if(!state->cached) {4211if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4212remove_path(patch->old_name);4213}4214}4215return0;4216}42174218static intadd_index_file(struct apply_state *state,4219const char*path,4220unsigned mode,4221void*buf,4222unsigned long size)4223{4224struct stat st;4225struct cache_entry *ce;4226int namelen =strlen(path);4227unsigned ce_size =cache_entry_size(namelen);42284229if(!state->update_index)4230return0;42314232 ce =xcalloc(1, ce_size);4233memcpy(ce->name, path, namelen);4234 ce->ce_mode =create_ce_mode(mode);4235 ce->ce_flags =create_ce_flags(0);4236 ce->ce_namelen = namelen;4237if(S_ISGITLINK(mode)) {4238const char*s;42394240if(!skip_prefix(buf,"Subproject commit ", &s) ||4241get_sha1_hex(s, ce->sha1)) {4242free(ce);4243returnerror(_("corrupt patch for submodule%s"), path);4244}4245}else{4246if(!state->cached) {4247if(lstat(path, &st) <0) {4248free(ce);4249returnerror(_("unable to stat newly "4250"created file '%s':%s"),4251 path,strerror(errno));4252}4253fill_stat_cache_info(ce, &st);4254}4255if(write_sha1_file(buf, size, blob_type, ce->sha1) <0) {4256free(ce);4257returnerror(_("unable to create backing store "4258"for newly created file%s"), path);4259}4260}4261if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0) {4262free(ce);4263returnerror(_("unable to add cache entry for%s"), path);4264}42654266return0;4267}42684269/*4270 * Returns:4271 * -1 if an unrecoverable error happened4272 * 0 if everything went well4273 * 1 if a recoverable error happened4274 */4275static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4276{4277int fd, res;4278struct strbuf nbuf = STRBUF_INIT;42794280if(S_ISGITLINK(mode)) {4281struct stat st;4282if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4283return0;4284return!!mkdir(path,0777);4285}42864287if(has_symlinks &&S_ISLNK(mode))4288/* Although buf:size is counted string, it also is NUL4289 * terminated.4290 */4291return!!symlink(buf, path);42924293 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4294if(fd <0)4295return1;42964297if(convert_to_working_tree(path, buf, size, &nbuf)) {4298 size = nbuf.len;4299 buf = nbuf.buf;4300}43014302 res =write_in_full(fd, buf, size) <0;4303if(res)4304error_errno(_("failed to write to '%s'"), path);4305strbuf_release(&nbuf);43064307if(close(fd) <0&& !res)4308returnerror_errno(_("closing file '%s'"), path);43094310return res ? -1:0;4311}43124313/*4314 * We optimistically assume that the directories exist,4315 * which is true 99% of the time anyway. If they don't,4316 * we create them and try again.4317 *4318 * Returns:4319 * -1 on error4320 * 0 otherwise4321 */4322static intcreate_one_file(struct apply_state *state,4323char*path,4324unsigned mode,4325const char*buf,4326unsigned long size)4327{4328int res;43294330if(state->cached)4331return0;43324333 res =try_create_file(path, mode, buf, size);4334if(res <0)4335return-1;4336if(!res)4337return0;43384339if(errno == ENOENT) {4340if(safe_create_leading_directories(path))4341return0;4342 res =try_create_file(path, mode, buf, size);4343if(res <0)4344return-1;4345if(!res)4346return0;4347}43484349if(errno == EEXIST || errno == EACCES) {4350/* We may be trying to create a file where a directory4351 * used to be.4352 */4353struct stat st;4354if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4355 errno = EEXIST;4356}43574358if(errno == EEXIST) {4359unsigned int nr =getpid();43604361for(;;) {4362char newpath[PATH_MAX];4363mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4364 res =try_create_file(newpath, mode, buf, size);4365if(res <0)4366return-1;4367if(!res) {4368if(!rename(newpath, path))4369return0;4370unlink_or_warn(newpath);4371break;4372}4373if(errno != EEXIST)4374break;4375++nr;4376}4377}4378returnerror_errno(_("unable to write file '%s' mode%o"),4379 path, mode);4380}43814382static intadd_conflicted_stages_file(struct apply_state *state,4383struct patch *patch)4384{4385int stage, namelen;4386unsigned ce_size, mode;4387struct cache_entry *ce;43884389if(!state->update_index)4390return0;4391 namelen =strlen(patch->new_name);4392 ce_size =cache_entry_size(namelen);4393 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);43944395remove_file_from_cache(patch->new_name);4396for(stage =1; stage <4; stage++) {4397if(is_null_oid(&patch->threeway_stage[stage -1]))4398continue;4399 ce =xcalloc(1, ce_size);4400memcpy(ce->name, patch->new_name, namelen);4401 ce->ce_mode =create_ce_mode(mode);4402 ce->ce_flags =create_ce_flags(stage);4403 ce->ce_namelen = namelen;4404hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4405if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0) {4406free(ce);4407returnerror(_("unable to add cache entry for%s"),4408 patch->new_name);4409}4410}44114412return0;4413}44144415static intcreate_file(struct apply_state *state,struct patch *patch)4416{4417char*path = patch->new_name;4418unsigned mode = patch->new_mode;4419unsigned long size = patch->resultsize;4420char*buf = patch->result;44214422if(!mode)4423 mode = S_IFREG |0644;4424if(create_one_file(state, path, mode, buf, size))4425return-1;44264427if(patch->conflicted_threeway)4428returnadd_conflicted_stages_file(state, patch);4429else4430returnadd_index_file(state, path, mode, buf, size);4431}44324433/* phase zero is to remove, phase one is to create */4434static intwrite_out_one_result(struct apply_state *state,4435struct patch *patch,4436int phase)4437{4438if(patch->is_delete >0) {4439if(phase ==0)4440returnremove_file(state, patch,1);4441return0;4442}4443if(patch->is_new >0|| patch->is_copy) {4444if(phase ==1)4445returncreate_file(state, patch);4446return0;4447}4448/*4449 * Rename or modification boils down to the same4450 * thing: remove the old, write the new4451 */4452if(phase ==0)4453returnremove_file(state, patch, patch->is_rename);4454if(phase ==1)4455returncreate_file(state, patch);4456return0;4457}44584459static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4460{4461FILE*rej;4462char namebuf[PATH_MAX];4463struct fragment *frag;4464int cnt =0;4465struct strbuf sb = STRBUF_INIT;44664467for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4468if(!frag->rejected)4469continue;4470 cnt++;4471}44724473if(!cnt) {4474if(state->apply_verbosely)4475say_patch_name(stderr,4476_("Applied patch%scleanly."), patch);4477return0;4478}44794480/* This should not happen, because a removal patch that leaves4481 * contents are marked "rejected" at the patch level.4482 */4483if(!patch->new_name)4484die(_("internal error"));44854486/* Say this even without --verbose */4487strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4488"Applying patch %%swith%drejects...",4489 cnt),4490 cnt);4491say_patch_name(stderr, sb.buf, patch);4492strbuf_release(&sb);44934494 cnt =strlen(patch->new_name);4495if(ARRAY_SIZE(namebuf) <= cnt +5) {4496 cnt =ARRAY_SIZE(namebuf) -5;4497warning(_("truncating .rej filename to %.*s.rej"),4498 cnt -1, patch->new_name);4499}4500memcpy(namebuf, patch->new_name, cnt);4501memcpy(namebuf + cnt,".rej",5);45024503 rej =fopen(namebuf,"w");4504if(!rej)4505returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));45064507/* Normal git tools never deal with .rej, so do not pretend4508 * this is a git patch by saying --git or giving extended4509 * headers. While at it, maybe please "kompare" that wants4510 * the trailing TAB and some garbage at the end of line ;-).4511 */4512fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4513 patch->new_name, patch->new_name);4514for(cnt =1, frag = patch->fragments;4515 frag;4516 cnt++, frag = frag->next) {4517if(!frag->rejected) {4518fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4519continue;4520}4521fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4522fprintf(rej,"%.*s", frag->size, frag->patch);4523if(frag->patch[frag->size-1] !='\n')4524fputc('\n', rej);4525}4526fclose(rej);4527return-1;4528}45294530/*4531 * Returns:4532 * -1 if an error happened4533 * 0 if the patch applied cleanly4534 * 1 if the patch did not apply cleanly4535 */4536static intwrite_out_results(struct apply_state *state,struct patch *list)4537{4538int phase;4539int errs =0;4540struct patch *l;4541struct string_list cpath = STRING_LIST_INIT_DUP;45424543for(phase =0; phase <2; phase++) {4544 l = list;4545while(l) {4546if(l->rejected)4547 errs =1;4548else{4549if(write_out_one_result(state, l, phase)) {4550string_list_clear(&cpath,0);4551return-1;4552}4553if(phase ==1) {4554if(write_out_one_reject(state, l))4555 errs =1;4556if(l->conflicted_threeway) {4557string_list_append(&cpath, l->new_name);4558 errs =1;4559}4560}4561}4562 l = l->next;4563}4564}45654566if(cpath.nr) {4567struct string_list_item *item;45684569string_list_sort(&cpath);4570for_each_string_list_item(item, &cpath)4571fprintf(stderr,"U%s\n", item->string);4572string_list_clear(&cpath,0);45734574rerere(0);4575}45764577return errs;4578}45794580/*4581 * Try to apply a patch.4582 *4583 * Returns:4584 * -128 if a bad error happened (like patch unreadable)4585 * -1 if patch did not apply and user cannot deal with it4586 * 0 if the patch applied4587 * 1 if the patch did not apply but user might fix it4588 */4589static intapply_patch(struct apply_state *state,4590int fd,4591const char*filename,4592int options)4593{4594size_t offset;4595struct strbuf buf = STRBUF_INIT;/* owns the patch text */4596struct patch *list = NULL, **listp = &list;4597int skipped_patch =0;4598int res =0;45994600 state->patch_input_file = filename;4601if(read_patch_file(&buf, fd) <0)4602return-128;4603 offset =0;4604while(offset < buf.len) {4605struct patch *patch;4606int nr;46074608 patch =xcalloc(1,sizeof(*patch));4609 patch->inaccurate_eof = !!(options & APPLY_OPT_INACCURATE_EOF);4610 patch->recount = !!(options & APPLY_OPT_RECOUNT);4611 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4612if(nr <0) {4613free_patch(patch);4614if(nr == -128) {4615 res = -128;4616goto end;4617}4618break;4619}4620if(state->apply_in_reverse)4621reverse_patches(patch);4622if(use_patch(state, patch)) {4623patch_stats(state, patch);4624*listp = patch;4625 listp = &patch->next;4626}4627else{4628if(state->apply_verbosely)4629say_patch_name(stderr,_("Skipped patch '%s'."), patch);4630free_patch(patch);4631 skipped_patch++;4632}4633 offset += nr;4634}46354636if(!list && !skipped_patch) {4637error(_("unrecognized input"));4638 res = -128;4639goto end;4640}46414642if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4643 state->apply =0;46444645 state->update_index = state->check_index && state->apply;4646if(state->update_index && state->newfd <0)4647 state->newfd =hold_locked_index(state->lock_file,1);46484649if(state->check_index &&read_cache() <0) {4650error(_("unable to read index file"));4651 res = -128;4652goto end;4653}46544655if(state->check || state->apply) {4656int r =check_patch_list(state, list);4657if(r == -128) {4658 res = -128;4659goto end;4660}4661if(r <0&& !state->apply_with_reject) {4662 res = -1;4663goto end;4664}4665}46664667if(state->apply) {4668int write_res =write_out_results(state, list);4669if(write_res <0) {4670 res = -128;4671goto end;4672}4673if(write_res >0) {4674/* with --3way, we still need to write the index out */4675 res = state->apply_with_reject ? -1:1;4676goto end;4677}4678}46794680if(state->fake_ancestor &&4681build_fake_ancestor(list, state->fake_ancestor)) {4682 res = -128;4683goto end;4684}46854686if(state->diffstat)4687stat_patch_list(state, list);46884689if(state->numstat)4690numstat_patch_list(state, list);46914692if(state->summary)4693summary_patch_list(list);46944695end:4696free_patch_list(list);4697strbuf_release(&buf);4698string_list_clear(&state->fn_table,0);4699return res;4700}47014702intapply_option_parse_exclude(const struct option *opt,4703const char*arg,int unset)4704{4705struct apply_state *state = opt->value;4706add_name_limit(state, arg,1);4707return0;4708}47094710intapply_option_parse_include(const struct option *opt,4711const char*arg,int unset)4712{4713struct apply_state *state = opt->value;4714add_name_limit(state, arg,0);4715 state->has_include =1;4716return0;4717}47184719intapply_option_parse_p(const struct option *opt,4720const char*arg,4721int unset)4722{4723struct apply_state *state = opt->value;4724 state->p_value =atoi(arg);4725 state->p_value_known =1;4726return0;4727}47284729intapply_option_parse_space_change(const struct option *opt,4730const char*arg,int unset)4731{4732struct apply_state *state = opt->value;4733if(unset)4734 state->ws_ignore_action = ignore_ws_none;4735else4736 state->ws_ignore_action = ignore_ws_change;4737return0;4738}47394740intapply_option_parse_whitespace(const struct option *opt,4741const char*arg,int unset)4742{4743struct apply_state *state = opt->value;4744 state->whitespace_option = arg;4745if(parse_whitespace_option(state, arg))4746exit(1);4747return0;4748}47494750intapply_option_parse_directory(const struct option *opt,4751const char*arg,int unset)4752{4753struct apply_state *state = opt->value;4754strbuf_reset(&state->root);4755strbuf_addstr(&state->root, arg);4756strbuf_complete(&state->root,'/');4757return0;4758}47594760intapply_all_patches(struct apply_state *state,4761int argc,4762const char**argv,4763int options)4764{4765int i;4766int res;4767int errs =0;4768int read_stdin =1;47694770for(i =0; i < argc; i++) {4771const char*arg = argv[i];4772int fd;47734774if(!strcmp(arg,"-")) {4775 res =apply_patch(state,0,"<stdin>", options);4776if(res <0)4777goto end;4778 errs |= res;4779 read_stdin =0;4780continue;4781}else if(0< state->prefix_length)4782 arg =prefix_filename(state->prefix,4783 state->prefix_length,4784 arg);47854786 fd =open(arg, O_RDONLY);4787if(fd <0) {4788error(_("can't open patch '%s':%s"), arg,strerror(errno));4789 res = -128;4790goto end;4791}4792 read_stdin =0;4793set_default_whitespace_mode(state);4794 res =apply_patch(state, fd, arg, options);4795close(fd);4796if(res <0)4797goto end;4798 errs |= res;4799}4800set_default_whitespace_mode(state);4801if(read_stdin) {4802 res =apply_patch(state,0,"<stdin>", options);4803if(res <0)4804goto end;4805 errs |= res;4806}48074808if(state->whitespace_error) {4809if(state->squelch_whitespace_errors &&4810 state->squelch_whitespace_errors < state->whitespace_error) {4811int squelched =4812 state->whitespace_error - state->squelch_whitespace_errors;4813warning(Q_("squelched%dwhitespace error",4814"squelched%dwhitespace errors",4815 squelched),4816 squelched);4817}4818if(state->ws_error_action == die_on_ws_error) {4819error(Q_("%dline adds whitespace errors.",4820"%dlines add whitespace errors.",4821 state->whitespace_error),4822 state->whitespace_error);4823 res = -128;4824goto end;4825}4826if(state->applied_after_fixing_ws && state->apply)4827warning("%dline%sapplied after"4828" fixing whitespace errors.",4829 state->applied_after_fixing_ws,4830 state->applied_after_fixing_ws ==1?"":"s");4831else if(state->whitespace_error)4832warning(Q_("%dline adds whitespace errors.",4833"%dlines add whitespace errors.",4834 state->whitespace_error),4835 state->whitespace_error);4836}48374838if(state->update_index) {4839 res =write_locked_index(&the_index, state->lock_file, COMMIT_LOCK);4840if(res) {4841error(_("Unable to write new index file"));4842 res = -128;4843goto end;4844}4845 state->newfd = -1;4846}48474848return!!errs;48494850end:4851if(state->newfd >=0) {4852rollback_lock_file(state->lock_file);4853 state->newfd = -1;4854}48554856return(res == -1?1:128);4857}