1/* 2 * apply.c 3 * 4 * Copyright (C) Linus Torvalds, 2005 5 * 6 * This applies patches on top of some (arbitrary) version of the SCM. 7 * 8 */ 9 10#include"cache.h" 11#include"blob.h" 12#include"delta.h" 13#include"diff.h" 14#include"dir.h" 15#include"xdiff-interface.h" 16#include"ll-merge.h" 17#include"lockfile.h" 18#include"parse-options.h" 19#include"quote.h" 20#include"rerere.h" 21#include"apply.h" 22 23static voidgit_apply_config(void) 24{ 25git_config_get_string_const("apply.whitespace", &apply_default_whitespace); 26git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace); 27git_config(git_default_config, NULL); 28} 29 30static intparse_whitespace_option(struct apply_state *state,const char*option) 31{ 32if(!option) { 33 state->ws_error_action = warn_on_ws_error; 34return0; 35} 36if(!strcmp(option,"warn")) { 37 state->ws_error_action = warn_on_ws_error; 38return0; 39} 40if(!strcmp(option,"nowarn")) { 41 state->ws_error_action = nowarn_ws_error; 42return0; 43} 44if(!strcmp(option,"error")) { 45 state->ws_error_action = die_on_ws_error; 46return0; 47} 48if(!strcmp(option,"error-all")) { 49 state->ws_error_action = die_on_ws_error; 50 state->squelch_whitespace_errors =0; 51return0; 52} 53if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 54 state->ws_error_action = correct_ws_error; 55return0; 56} 57returnerror(_("unrecognized whitespace option '%s'"), option); 58} 59 60static intparse_ignorewhitespace_option(struct apply_state *state, 61const char*option) 62{ 63if(!option || !strcmp(option,"no") || 64!strcmp(option,"false") || !strcmp(option,"never") || 65!strcmp(option,"none")) { 66 state->ws_ignore_action = ignore_ws_none; 67return0; 68} 69if(!strcmp(option,"change")) { 70 state->ws_ignore_action = ignore_ws_change; 71return0; 72} 73returnerror(_("unrecognized whitespace ignore option '%s'"), option); 74} 75 76intinit_apply_state(struct apply_state *state, 77const char*prefix, 78struct lock_file *lock_file) 79{ 80memset(state,0,sizeof(*state)); 81 state->prefix = prefix; 82 state->prefix_length = state->prefix ?strlen(state->prefix) :0; 83 state->lock_file = lock_file; 84 state->newfd = -1; 85 state->apply =1; 86 state->line_termination ='\n'; 87 state->p_value =1; 88 state->p_context = UINT_MAX; 89 state->squelch_whitespace_errors =5; 90 state->ws_error_action = warn_on_ws_error; 91 state->ws_ignore_action = ignore_ws_none; 92 state->linenr =1; 93string_list_init(&state->fn_table,0); 94string_list_init(&state->limit_by_name,0); 95string_list_init(&state->symlink_changes,0); 96strbuf_init(&state->root,0); 97 98git_apply_config(); 99if(apply_default_whitespace &&parse_whitespace_option(state, apply_default_whitespace)) 100return-1; 101if(apply_default_ignorewhitespace &&parse_ignorewhitespace_option(state, apply_default_ignorewhitespace)) 102return-1; 103return0; 104} 105 106voidclear_apply_state(struct apply_state *state) 107{ 108string_list_clear(&state->limit_by_name,0); 109string_list_clear(&state->symlink_changes,0); 110strbuf_release(&state->root); 111 112/* &state->fn_table is cleared at the end of apply_patch() */ 113} 114 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{ 973/* expect "/dev/null" */ 974if(memcmp("/dev/null", line,9) || line[9] !='\n') 975returnerror(_("git apply: bad git-diff - expected /dev/null on line%d"), state->linenr); 976} 977 978return0; 979} 980 981static intgitdiff_oldname(struct apply_state *state, 982const char*line, 983struct patch *patch) 984{ 985returngitdiff_verify_name(state, line, 986 patch->is_new, &patch->old_name, 987 DIFF_OLD_NAME); 988} 989 990static intgitdiff_newname(struct apply_state *state, 991const char*line, 992struct patch *patch) 993{ 994returngitdiff_verify_name(state, line, 995 patch->is_delete, &patch->new_name, 996 DIFF_NEW_NAME); 997} 998 999static intgitdiff_oldmode(struct apply_state *state,1000const char*line,1001struct patch *patch)1002{1003 patch->old_mode =strtoul(line, NULL,8);1004return0;1005}10061007static intgitdiff_newmode(struct apply_state *state,1008const char*line,1009struct patch *patch)1010{1011 patch->new_mode =strtoul(line, NULL,8);1012return0;1013}10141015static intgitdiff_delete(struct apply_state *state,1016const char*line,1017struct patch *patch)1018{1019 patch->is_delete =1;1020free(patch->old_name);1021 patch->old_name =xstrdup_or_null(patch->def_name);1022returngitdiff_oldmode(state, line, patch);1023}10241025static intgitdiff_newfile(struct apply_state *state,1026const char*line,1027struct patch *patch)1028{1029 patch->is_new =1;1030free(patch->new_name);1031 patch->new_name =xstrdup_or_null(patch->def_name);1032returngitdiff_newmode(state, line, patch);1033}10341035static intgitdiff_copysrc(struct apply_state *state,1036const char*line,1037struct patch *patch)1038{1039 patch->is_copy =1;1040free(patch->old_name);1041 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1042return0;1043}10441045static intgitdiff_copydst(struct apply_state *state,1046const char*line,1047struct patch *patch)1048{1049 patch->is_copy =1;1050free(patch->new_name);1051 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1052return0;1053}10541055static intgitdiff_renamesrc(struct apply_state *state,1056const char*line,1057struct patch *patch)1058{1059 patch->is_rename =1;1060free(patch->old_name);1061 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1062return0;1063}10641065static intgitdiff_renamedst(struct apply_state *state,1066const char*line,1067struct patch *patch)1068{1069 patch->is_rename =1;1070free(patch->new_name);1071 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1072return0;1073}10741075static intgitdiff_similarity(struct apply_state *state,1076const char*line,1077struct patch *patch)1078{1079unsigned long val =strtoul(line, NULL,10);1080if(val <=100)1081 patch->score = val;1082return0;1083}10841085static intgitdiff_dissimilarity(struct apply_state *state,1086const char*line,1087struct patch *patch)1088{1089unsigned long val =strtoul(line, NULL,10);1090if(val <=100)1091 patch->score = val;1092return0;1093}10941095static intgitdiff_index(struct apply_state *state,1096const char*line,1097struct patch *patch)1098{1099/*1100 * index line is N hexadecimal, "..", N hexadecimal,1101 * and optional space with octal mode.1102 */1103const char*ptr, *eol;1104int len;11051106 ptr =strchr(line,'.');1107if(!ptr || ptr[1] !='.'||40< ptr - line)1108return0;1109 len = ptr - line;1110memcpy(patch->old_sha1_prefix, line, len);1111 patch->old_sha1_prefix[len] =0;11121113 line = ptr +2;1114 ptr =strchr(line,' ');1115 eol =strchrnul(line,'\n');11161117if(!ptr || eol < ptr)1118 ptr = eol;1119 len = ptr - line;11201121if(40< len)1122return0;1123memcpy(patch->new_sha1_prefix, line, len);1124 patch->new_sha1_prefix[len] =0;1125if(*ptr ==' ')1126 patch->old_mode =strtoul(ptr+1, NULL,8);1127return0;1128}11291130/*1131 * This is normal for a diff that doesn't change anything: we'll fall through1132 * into the next diff. Tell the parser to break out.1133 */1134static intgitdiff_unrecognized(struct apply_state *state,1135const char*line,1136struct patch *patch)1137{1138return1;1139}11401141/*1142 * Skip p_value leading components from "line"; as we do not accept1143 * absolute paths, return NULL in that case.1144 */1145static const char*skip_tree_prefix(struct apply_state *state,1146const char*line,1147int llen)1148{1149int nslash;1150int i;11511152if(!state->p_value)1153return(llen && line[0] =='/') ? NULL : line;11541155 nslash = state->p_value;1156for(i =0; i < llen; i++) {1157int ch = line[i];1158if(ch =='/'&& --nslash <=0)1159return(i ==0) ? NULL : &line[i +1];1160}1161return NULL;1162}11631164/*1165 * This is to extract the same name that appears on "diff --git"1166 * line. We do not find and return anything if it is a rename1167 * patch, and it is OK because we will find the name elsewhere.1168 * We need to reliably find name only when it is mode-change only,1169 * creation or deletion of an empty file. In any of these cases,1170 * both sides are the same name under a/ and b/ respectively.1171 */1172static char*git_header_name(struct apply_state *state,1173const char*line,1174int llen)1175{1176const char*name;1177const char*second = NULL;1178size_t len, line_len;11791180 line +=strlen("diff --git ");1181 llen -=strlen("diff --git ");11821183if(*line =='"') {1184const char*cp;1185struct strbuf first = STRBUF_INIT;1186struct strbuf sp = STRBUF_INIT;11871188if(unquote_c_style(&first, line, &second))1189goto free_and_fail1;11901191/* strip the a/b prefix including trailing slash */1192 cp =skip_tree_prefix(state, first.buf, first.len);1193if(!cp)1194goto free_and_fail1;1195strbuf_remove(&first,0, cp - first.buf);11961197/*1198 * second points at one past closing dq of name.1199 * find the second name.1200 */1201while((second < line + llen) &&isspace(*second))1202 second++;12031204if(line + llen <= second)1205goto free_and_fail1;1206if(*second =='"') {1207if(unquote_c_style(&sp, second, NULL))1208goto free_and_fail1;1209 cp =skip_tree_prefix(state, sp.buf, sp.len);1210if(!cp)1211goto free_and_fail1;1212/* They must match, otherwise ignore */1213if(strcmp(cp, first.buf))1214goto free_and_fail1;1215strbuf_release(&sp);1216returnstrbuf_detach(&first, NULL);1217}12181219/* unquoted second */1220 cp =skip_tree_prefix(state, second, line + llen - second);1221if(!cp)1222goto free_and_fail1;1223if(line + llen - cp != first.len ||1224memcmp(first.buf, cp, first.len))1225goto free_and_fail1;1226returnstrbuf_detach(&first, NULL);12271228 free_and_fail1:1229strbuf_release(&first);1230strbuf_release(&sp);1231return NULL;1232}12331234/* unquoted first name */1235 name =skip_tree_prefix(state, line, llen);1236if(!name)1237return NULL;12381239/*1240 * since the first name is unquoted, a dq if exists must be1241 * the beginning of the second name.1242 */1243for(second = name; second < line + llen; second++) {1244if(*second =='"') {1245struct strbuf sp = STRBUF_INIT;1246const char*np;12471248if(unquote_c_style(&sp, second, NULL))1249goto free_and_fail2;12501251 np =skip_tree_prefix(state, sp.buf, sp.len);1252if(!np)1253goto free_and_fail2;12541255 len = sp.buf + sp.len - np;1256if(len < second - name &&1257!strncmp(np, name, len) &&1258isspace(name[len])) {1259/* Good */1260strbuf_remove(&sp,0, np - sp.buf);1261returnstrbuf_detach(&sp, NULL);1262}12631264 free_and_fail2:1265strbuf_release(&sp);1266return NULL;1267}1268}12691270/*1271 * Accept a name only if it shows up twice, exactly the same1272 * form.1273 */1274 second =strchr(name,'\n');1275if(!second)1276return NULL;1277 line_len = second - name;1278for(len =0; ; len++) {1279switch(name[len]) {1280default:1281continue;1282case'\n':1283return NULL;1284case'\t':case' ':1285/*1286 * Is this the separator between the preimage1287 * and the postimage pathname? Again, we are1288 * only interested in the case where there is1289 * no rename, as this is only to set def_name1290 * and a rename patch has the names elsewhere1291 * in an unambiguous form.1292 */1293if(!name[len +1])1294return NULL;/* no postimage name */1295 second =skip_tree_prefix(state, name + len +1,1296 line_len - (len +1));1297if(!second)1298return NULL;1299/*1300 * Does len bytes starting at "name" and "second"1301 * (that are separated by one HT or SP we just1302 * found) exactly match?1303 */1304if(second[len] =='\n'&& !strncmp(name, second, len))1305returnxmemdupz(name, len);1306}1307}1308}13091310/* Verify that we recognize the lines following a git header */1311static intparse_git_header(struct apply_state *state,1312const char*line,1313int len,1314unsigned int size,1315struct patch *patch)1316{1317unsigned long offset;13181319/* A git diff has explicit new/delete information, so we don't guess */1320 patch->is_new =0;1321 patch->is_delete =0;13221323/*1324 * Some things may not have the old name in the1325 * rest of the headers anywhere (pure mode changes,1326 * or removing or adding empty files), so we get1327 * the default name from the header.1328 */1329 patch->def_name =git_header_name(state, line, len);1330if(patch->def_name && state->root.len) {1331char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1332free(patch->def_name);1333 patch->def_name = s;1334}13351336 line += len;1337 size -= len;1338 state->linenr++;1339for(offset = len ; size >0; offset += len, size -= len, line += len, state->linenr++) {1340static const struct opentry {1341const char*str;1342int(*fn)(struct apply_state *,const char*,struct patch *);1343} optable[] = {1344{"@@ -", gitdiff_hdrend },1345{"--- ", gitdiff_oldname },1346{"+++ ", gitdiff_newname },1347{"old mode ", gitdiff_oldmode },1348{"new mode ", gitdiff_newmode },1349{"deleted file mode ", gitdiff_delete },1350{"new file mode ", gitdiff_newfile },1351{"copy from ", gitdiff_copysrc },1352{"copy to ", gitdiff_copydst },1353{"rename old ", gitdiff_renamesrc },1354{"rename new ", gitdiff_renamedst },1355{"rename from ", gitdiff_renamesrc },1356{"rename to ", gitdiff_renamedst },1357{"similarity index ", gitdiff_similarity },1358{"dissimilarity index ", gitdiff_dissimilarity },1359{"index ", gitdiff_index },1360{"", gitdiff_unrecognized },1361};1362int i;13631364 len =linelen(line, size);1365if(!len || line[len-1] !='\n')1366break;1367for(i =0; i <ARRAY_SIZE(optable); i++) {1368const struct opentry *p = optable + i;1369int oplen =strlen(p->str);1370int res;1371if(len < oplen ||memcmp(p->str, line, oplen))1372continue;1373 res = p->fn(state, line + oplen, patch);1374if(res <0)1375return-1;1376if(res >0)1377return offset;1378break;1379}1380}13811382return offset;1383}13841385static intparse_num(const char*line,unsigned long*p)1386{1387char*ptr;13881389if(!isdigit(*line))1390return0;1391*p =strtoul(line, &ptr,10);1392return ptr - line;1393}13941395static intparse_range(const char*line,int len,int offset,const char*expect,1396unsigned long*p1,unsigned long*p2)1397{1398int digits, ex;13991400if(offset <0|| offset >= len)1401return-1;1402 line += offset;1403 len -= offset;14041405 digits =parse_num(line, p1);1406if(!digits)1407return-1;14081409 offset += digits;1410 line += digits;1411 len -= digits;14121413*p2 =1;1414if(*line ==',') {1415 digits =parse_num(line+1, p2);1416if(!digits)1417return-1;14181419 offset += digits+1;1420 line += digits+1;1421 len -= digits+1;1422}14231424 ex =strlen(expect);1425if(ex > len)1426return-1;1427if(memcmp(line, expect, ex))1428return-1;14291430return offset + ex;1431}14321433static voidrecount_diff(const char*line,int size,struct fragment *fragment)1434{1435int oldlines =0, newlines =0, ret =0;14361437if(size <1) {1438warning("recount: ignore empty hunk");1439return;1440}14411442for(;;) {1443int len =linelen(line, size);1444 size -= len;1445 line += len;14461447if(size <1)1448break;14491450switch(*line) {1451case' ':case'\n':1452 newlines++;1453/* fall through */1454case'-':1455 oldlines++;1456continue;1457case'+':1458 newlines++;1459continue;1460case'\\':1461continue;1462case'@':1463 ret = size <3|| !starts_with(line,"@@ ");1464break;1465case'd':1466 ret = size <5|| !starts_with(line,"diff ");1467break;1468default:1469 ret = -1;1470break;1471}1472if(ret) {1473warning(_("recount: unexpected line: %.*s"),1474(int)linelen(line, size), line);1475return;1476}1477break;1478}1479 fragment->oldlines = oldlines;1480 fragment->newlines = newlines;1481}14821483/*1484 * Parse a unified diff fragment header of the1485 * form "@@ -a,b +c,d @@"1486 */1487static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1488{1489int offset;14901491if(!len || line[len-1] !='\n')1492return-1;14931494/* Figure out the number of lines in a fragment */1495 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1496 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14971498return offset;1499}15001501/*1502 * Find file diff header1503 *1504 * Returns:1505 * -1 if no header was found1506 * -128 in case of error1507 * the size of the header in bytes (called "offset") otherwise1508 */1509static intfind_header(struct apply_state *state,1510const char*line,1511unsigned long size,1512int*hdrsize,1513struct patch *patch)1514{1515unsigned long offset, len;15161517 patch->is_toplevel_relative =0;1518 patch->is_rename = patch->is_copy =0;1519 patch->is_new = patch->is_delete = -1;1520 patch->old_mode = patch->new_mode =0;1521 patch->old_name = patch->new_name = NULL;1522for(offset =0; size >0; offset += len, size -= len, line += len, state->linenr++) {1523unsigned long nextlen;15241525 len =linelen(line, size);1526if(!len)1527break;15281529/* Testing this early allows us to take a few shortcuts.. */1530if(len <6)1531continue;15321533/*1534 * Make sure we don't find any unconnected patch fragments.1535 * That's a sign that we didn't find a header, and that a1536 * patch has become corrupted/broken up.1537 */1538if(!memcmp("@@ -", line,4)) {1539struct fragment dummy;1540if(parse_fragment_header(line, len, &dummy) <0)1541continue;1542error(_("patch fragment without header at line%d: %.*s"),1543 state->linenr, (int)len-1, line);1544return-128;1545}15461547if(size < len +6)1548break;15491550/*1551 * Git patch? It might not have a real patch, just a rename1552 * or mode change, so we handle that specially1553 */1554if(!memcmp("diff --git ", line,11)) {1555int git_hdr_len =parse_git_header(state, line, len, size, patch);1556if(git_hdr_len <0)1557return-128;1558if(git_hdr_len <= len)1559continue;1560if(!patch->old_name && !patch->new_name) {1561if(!patch->def_name) {1562error(Q_("git diff header lacks filename information when removing "1563"%dleading pathname component (line%d)",1564"git diff header lacks filename information when removing "1565"%dleading pathname components (line%d)",1566 state->p_value),1567 state->p_value, state->linenr);1568return-128;1569}1570 patch->old_name =xstrdup(patch->def_name);1571 patch->new_name =xstrdup(patch->def_name);1572}1573if(!patch->is_delete && !patch->new_name) {1574error("git diff header lacks filename information "1575"(line%d)", state->linenr);1576return-128;1577}1578 patch->is_toplevel_relative =1;1579*hdrsize = git_hdr_len;1580return offset;1581}15821583/* --- followed by +++ ? */1584if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1585continue;15861587/*1588 * We only accept unified patches, so we want it to1589 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1590 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1591 */1592 nextlen =linelen(line + len, size - len);1593if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1594continue;15951596/* Ok, we'll consider it a patch */1597if(parse_traditional_patch(state, line, line+len, patch))1598return-128;1599*hdrsize = len + nextlen;1600 state->linenr +=2;1601return offset;1602}1603return-1;1604}16051606static voidrecord_ws_error(struct apply_state *state,1607unsigned result,1608const char*line,1609int len,1610int linenr)1611{1612char*err;16131614if(!result)1615return;16161617 state->whitespace_error++;1618if(state->squelch_whitespace_errors &&1619 state->squelch_whitespace_errors < state->whitespace_error)1620return;16211622 err =whitespace_error_string(result);1623fprintf(stderr,"%s:%d:%s.\n%.*s\n",1624 state->patch_input_file, linenr, err, len, line);1625free(err);1626}16271628static voidcheck_whitespace(struct apply_state *state,1629const char*line,1630int len,1631unsigned ws_rule)1632{1633unsigned result =ws_check(line +1, len -1, ws_rule);16341635record_ws_error(state, result, line +1, len -2, state->linenr);1636}16371638/*1639 * Parse a unified diff. Note that this really needs to parse each1640 * fragment separately, since the only way to know the difference1641 * between a "---" that is part of a patch, and a "---" that starts1642 * the next patch is to look at the line counts..1643 */1644static intparse_fragment(struct apply_state *state,1645const char*line,1646unsigned long size,1647struct patch *patch,1648struct fragment *fragment)1649{1650int added, deleted;1651int len =linelen(line, size), offset;1652unsigned long oldlines, newlines;1653unsigned long leading, trailing;16541655 offset =parse_fragment_header(line, len, fragment);1656if(offset <0)1657return-1;1658if(offset >0&& patch->recount)1659recount_diff(line + offset, size - offset, fragment);1660 oldlines = fragment->oldlines;1661 newlines = fragment->newlines;1662 leading =0;1663 trailing =0;16641665/* Parse the thing.. */1666 line += len;1667 size -= len;1668 state->linenr++;1669 added = deleted =0;1670for(offset = len;16710< size;1672 offset += len, size -= len, line += len, state->linenr++) {1673if(!oldlines && !newlines)1674break;1675 len =linelen(line, size);1676if(!len || line[len-1] !='\n')1677return-1;1678switch(*line) {1679default:1680return-1;1681case'\n':/* newer GNU diff, an empty context line */1682case' ':1683 oldlines--;1684 newlines--;1685if(!deleted && !added)1686 leading++;1687 trailing++;1688if(!state->apply_in_reverse &&1689 state->ws_error_action == correct_ws_error)1690check_whitespace(state, line, len, patch->ws_rule);1691break;1692case'-':1693if(state->apply_in_reverse &&1694 state->ws_error_action != nowarn_ws_error)1695check_whitespace(state, line, len, patch->ws_rule);1696 deleted++;1697 oldlines--;1698 trailing =0;1699break;1700case'+':1701if(!state->apply_in_reverse &&1702 state->ws_error_action != nowarn_ws_error)1703check_whitespace(state, line, len, patch->ws_rule);1704 added++;1705 newlines--;1706 trailing =0;1707break;17081709/*1710 * We allow "\ No newline at end of file". Depending1711 * on locale settings when the patch was produced we1712 * don't know what this line looks like. The only1713 * thing we do know is that it begins with "\ ".1714 * Checking for 12 is just for sanity check -- any1715 * l10n of "\ No newline..." is at least that long.1716 */1717case'\\':1718if(len <12||memcmp(line,"\\",2))1719return-1;1720break;1721}1722}1723if(oldlines || newlines)1724return-1;1725if(!deleted && !added)1726return-1;17271728 fragment->leading = leading;1729 fragment->trailing = trailing;17301731/*1732 * If a fragment ends with an incomplete line, we failed to include1733 * it in the above loop because we hit oldlines == newlines == 01734 * before seeing it.1735 */1736if(12< size && !memcmp(line,"\\",2))1737 offset +=linelen(line, size);17381739 patch->lines_added += added;1740 patch->lines_deleted += deleted;17411742if(0< patch->is_new && oldlines)1743returnerror(_("new file depends on old contents"));1744if(0< patch->is_delete && newlines)1745returnerror(_("deleted file still has contents"));1746return offset;1747}17481749/*1750 * We have seen "diff --git a/... b/..." header (or a traditional patch1751 * header). Read hunks that belong to this patch into fragments and hang1752 * them to the given patch structure.1753 *1754 * The (fragment->patch, fragment->size) pair points into the memory given1755 * by the caller, not a copy, when we return.1756 *1757 * Returns:1758 * -1 in case of error,1759 * the number of bytes in the patch otherwise.1760 */1761static intparse_single_patch(struct apply_state *state,1762const char*line,1763unsigned long size,1764struct patch *patch)1765{1766unsigned long offset =0;1767unsigned long oldlines =0, newlines =0, context =0;1768struct fragment **fragp = &patch->fragments;17691770while(size >4&& !memcmp(line,"@@ -",4)) {1771struct fragment *fragment;1772int len;17731774 fragment =xcalloc(1,sizeof(*fragment));1775 fragment->linenr = state->linenr;1776 len =parse_fragment(state, line, size, patch, fragment);1777if(len <=0) {1778free(fragment);1779returnerror(_("corrupt patch at line%d"), state->linenr);1780}1781 fragment->patch = line;1782 fragment->size = len;1783 oldlines += fragment->oldlines;1784 newlines += fragment->newlines;1785 context += fragment->leading + fragment->trailing;17861787*fragp = fragment;1788 fragp = &fragment->next;17891790 offset += len;1791 line += len;1792 size -= len;1793}17941795/*1796 * If something was removed (i.e. we have old-lines) it cannot1797 * be creation, and if something was added it cannot be1798 * deletion. However, the reverse is not true; --unified=01799 * patches that only add are not necessarily creation even1800 * though they do not have any old lines, and ones that only1801 * delete are not necessarily deletion.1802 *1803 * Unfortunately, a real creation/deletion patch do _not_ have1804 * any context line by definition, so we cannot safely tell it1805 * apart with --unified=0 insanity. At least if the patch has1806 * more than one hunk it is not creation or deletion.1807 */1808if(patch->is_new <0&&1809(oldlines || (patch->fragments && patch->fragments->next)))1810 patch->is_new =0;1811if(patch->is_delete <0&&1812(newlines || (patch->fragments && patch->fragments->next)))1813 patch->is_delete =0;18141815if(0< patch->is_new && oldlines)1816returnerror(_("new file%sdepends on old contents"), patch->new_name);1817if(0< patch->is_delete && newlines)1818returnerror(_("deleted file%sstill has contents"), patch->old_name);1819if(!patch->is_delete && !newlines && context)1820fprintf_ln(stderr,1821_("** warning: "1822"file%sbecomes empty but is not deleted"),1823 patch->new_name);18241825return offset;1826}18271828staticinlineintmetadata_changes(struct patch *patch)1829{1830return patch->is_rename >0||1831 patch->is_copy >0||1832 patch->is_new >0||1833 patch->is_delete ||1834(patch->old_mode && patch->new_mode &&1835 patch->old_mode != patch->new_mode);1836}18371838static char*inflate_it(const void*data,unsigned long size,1839unsigned long inflated_size)1840{1841 git_zstream stream;1842void*out;1843int st;18441845memset(&stream,0,sizeof(stream));18461847 stream.next_in = (unsigned char*)data;1848 stream.avail_in = size;1849 stream.next_out = out =xmalloc(inflated_size);1850 stream.avail_out = inflated_size;1851git_inflate_init(&stream);1852 st =git_inflate(&stream, Z_FINISH);1853git_inflate_end(&stream);1854if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1855free(out);1856return NULL;1857}1858return out;1859}18601861/*1862 * Read a binary hunk and return a new fragment; fragment->patch1863 * points at an allocated memory that the caller must free, so1864 * it is marked as "->free_patch = 1".1865 */1866static struct fragment *parse_binary_hunk(struct apply_state *state,1867char**buf_p,1868unsigned long*sz_p,1869int*status_p,1870int*used_p)1871{1872/*1873 * Expect a line that begins with binary patch method ("literal"1874 * or "delta"), followed by the length of data before deflating.1875 * a sequence of 'length-byte' followed by base-85 encoded data1876 * should follow, terminated by a newline.1877 *1878 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1879 * and we would limit the patch line to 66 characters,1880 * so one line can fit up to 13 groups that would decode1881 * to 52 bytes max. The length byte 'A'-'Z' corresponds1882 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1883 */1884int llen, used;1885unsigned long size = *sz_p;1886char*buffer = *buf_p;1887int patch_method;1888unsigned long origlen;1889char*data = NULL;1890int hunk_size =0;1891struct fragment *frag;18921893 llen =linelen(buffer, size);1894 used = llen;18951896*status_p =0;18971898if(starts_with(buffer,"delta ")) {1899 patch_method = BINARY_DELTA_DEFLATED;1900 origlen =strtoul(buffer +6, NULL,10);1901}1902else if(starts_with(buffer,"literal ")) {1903 patch_method = BINARY_LITERAL_DEFLATED;1904 origlen =strtoul(buffer +8, NULL,10);1905}1906else1907return NULL;19081909 state->linenr++;1910 buffer += llen;1911while(1) {1912int byte_length, max_byte_length, newsize;1913 llen =linelen(buffer, size);1914 used += llen;1915 state->linenr++;1916if(llen ==1) {1917/* consume the blank line */1918 buffer++;1919 size--;1920break;1921}1922/*1923 * Minimum line is "A00000\n" which is 7-byte long,1924 * and the line length must be multiple of 5 plus 2.1925 */1926if((llen <7) || (llen-2) %5)1927goto corrupt;1928 max_byte_length = (llen -2) /5*4;1929 byte_length = *buffer;1930if('A'<= byte_length && byte_length <='Z')1931 byte_length = byte_length -'A'+1;1932else if('a'<= byte_length && byte_length <='z')1933 byte_length = byte_length -'a'+27;1934else1935goto corrupt;1936/* if the input length was not multiple of 4, we would1937 * have filler at the end but the filler should never1938 * exceed 3 bytes1939 */1940if(max_byte_length < byte_length ||1941 byte_length <= max_byte_length -4)1942goto corrupt;1943 newsize = hunk_size + byte_length;1944 data =xrealloc(data, newsize);1945if(decode_85(data + hunk_size, buffer +1, byte_length))1946goto corrupt;1947 hunk_size = newsize;1948 buffer += llen;1949 size -= llen;1950}19511952 frag =xcalloc(1,sizeof(*frag));1953 frag->patch =inflate_it(data, hunk_size, origlen);1954 frag->free_patch =1;1955if(!frag->patch)1956goto corrupt;1957free(data);1958 frag->size = origlen;1959*buf_p = buffer;1960*sz_p = size;1961*used_p = used;1962 frag->binary_patch_method = patch_method;1963return frag;19641965 corrupt:1966free(data);1967*status_p = -1;1968error(_("corrupt binary patch at line%d: %.*s"),1969 state->linenr-1, llen-1, buffer);1970return NULL;1971}19721973/*1974 * Returns:1975 * -1 in case of error,1976 * the length of the parsed binary patch otherwise1977 */1978static intparse_binary(struct apply_state *state,1979char*buffer,1980unsigned long size,1981struct patch *patch)1982{1983/*1984 * We have read "GIT binary patch\n"; what follows is a line1985 * that says the patch method (currently, either "literal" or1986 * "delta") and the length of data before deflating; a1987 * sequence of 'length-byte' followed by base-85 encoded data1988 * follows.1989 *1990 * When a binary patch is reversible, there is another binary1991 * hunk in the same format, starting with patch method (either1992 * "literal" or "delta") with the length of data, and a sequence1993 * of length-byte + base-85 encoded data, terminated with another1994 * empty line. This data, when applied to the postimage, produces1995 * the preimage.1996 */1997struct fragment *forward;1998struct fragment *reverse;1999int status;2000int used, used_1;20012002 forward =parse_binary_hunk(state, &buffer, &size, &status, &used);2003if(!forward && !status)2004/* there has to be one hunk (forward hunk) */2005returnerror(_("unrecognized binary patch at line%d"), state->linenr-1);2006if(status)2007/* otherwise we already gave an error message */2008return status;20092010 reverse =parse_binary_hunk(state, &buffer, &size, &status, &used_1);2011if(reverse)2012 used += used_1;2013else if(status) {2014/*2015 * Not having reverse hunk is not an error, but having2016 * a corrupt reverse hunk is.2017 */2018free((void*) forward->patch);2019free(forward);2020return status;2021}2022 forward->next = reverse;2023 patch->fragments = forward;2024 patch->is_binary =1;2025return used;2026}20272028static voidprefix_one(struct apply_state *state,char**name)2029{2030char*old_name = *name;2031if(!old_name)2032return;2033*name =xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));2034free(old_name);2035}20362037static voidprefix_patch(struct apply_state *state,struct patch *p)2038{2039if(!state->prefix || p->is_toplevel_relative)2040return;2041prefix_one(state, &p->new_name);2042prefix_one(state, &p->old_name);2043}20442045/*2046 * include/exclude2047 */20482049static voidadd_name_limit(struct apply_state *state,2050const char*name,2051int exclude)2052{2053struct string_list_item *it;20542055 it =string_list_append(&state->limit_by_name, name);2056 it->util = exclude ? NULL : (void*)1;2057}20582059static intuse_patch(struct apply_state *state,struct patch *p)2060{2061const char*pathname = p->new_name ? p->new_name : p->old_name;2062int i;20632064/* Paths outside are not touched regardless of "--include" */2065if(0< state->prefix_length) {2066int pathlen =strlen(pathname);2067if(pathlen <= state->prefix_length ||2068memcmp(state->prefix, pathname, state->prefix_length))2069return0;2070}20712072/* See if it matches any of exclude/include rule */2073for(i =0; i < state->limit_by_name.nr; i++) {2074struct string_list_item *it = &state->limit_by_name.items[i];2075if(!wildmatch(it->string, pathname,0, NULL))2076return(it->util != NULL);2077}20782079/*2080 * If we had any include, a path that does not match any rule is2081 * not used. Otherwise, we saw bunch of exclude rules (or none)2082 * and such a path is used.2083 */2084return!state->has_include;2085}20862087/*2088 * Read the patch text in "buffer" that extends for "size" bytes; stop2089 * reading after seeing a single patch (i.e. changes to a single file).2090 * Create fragments (i.e. patch hunks) and hang them to the given patch.2091 *2092 * Returns:2093 * -1 if no header was found or parse_binary() failed,2094 * -128 on another error,2095 * the number of bytes consumed otherwise,2096 * so that the caller can call us again for the next patch.2097 */2098static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2099{2100int hdrsize, patchsize;2101int offset =find_header(state, buffer, size, &hdrsize, patch);21022103if(offset <0)2104return offset;21052106prefix_patch(state, patch);21072108if(!use_patch(state, patch))2109 patch->ws_rule =0;2110else2111 patch->ws_rule =whitespace_rule(patch->new_name2112? patch->new_name2113: patch->old_name);21142115 patchsize =parse_single_patch(state,2116 buffer + offset + hdrsize,2117 size - offset - hdrsize,2118 patch);21192120if(patchsize <0)2121return-128;21222123if(!patchsize) {2124static const char git_binary[] ="GIT binary patch\n";2125int hd = hdrsize + offset;2126unsigned long llen =linelen(buffer + hd, size - hd);21272128if(llen ==sizeof(git_binary) -1&&2129!memcmp(git_binary, buffer + hd, llen)) {2130int used;2131 state->linenr++;2132 used =parse_binary(state, buffer + hd + llen,2133 size - hd - llen, patch);2134if(used <0)2135return-1;2136if(used)2137 patchsize = used + llen;2138else2139 patchsize =0;2140}2141else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2142static const char*binhdr[] = {2143"Binary files ",2144"Files ",2145 NULL,2146};2147int i;2148for(i =0; binhdr[i]; i++) {2149int len =strlen(binhdr[i]);2150if(len < size - hd &&2151!memcmp(binhdr[i], buffer + hd, len)) {2152 state->linenr++;2153 patch->is_binary =1;2154 patchsize = llen;2155break;2156}2157}2158}21592160/* Empty patch cannot be applied if it is a text patch2161 * without metadata change. A binary patch appears2162 * empty to us here.2163 */2164if((state->apply || state->check) &&2165(!patch->is_binary && !metadata_changes(patch))) {2166error(_("patch with only garbage at line%d"), state->linenr);2167return-128;2168}2169}21702171return offset + hdrsize + patchsize;2172}21732174#define swap(a,b) myswap((a),(b),sizeof(a))21752176#define myswap(a, b, size) do { \2177 unsigned char mytmp[size]; \2178 memcpy(mytmp, &a, size); \2179 memcpy(&a, &b, size); \2180 memcpy(&b, mytmp, size); \2181} while (0)21822183static voidreverse_patches(struct patch *p)2184{2185for(; p; p = p->next) {2186struct fragment *frag = p->fragments;21872188swap(p->new_name, p->old_name);2189swap(p->new_mode, p->old_mode);2190swap(p->is_new, p->is_delete);2191swap(p->lines_added, p->lines_deleted);2192swap(p->old_sha1_prefix, p->new_sha1_prefix);21932194for(; frag; frag = frag->next) {2195swap(frag->newpos, frag->oldpos);2196swap(frag->newlines, frag->oldlines);2197}2198}2199}22002201static const char pluses[] =2202"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2203static const char minuses[]=2204"----------------------------------------------------------------------";22052206static voidshow_stats(struct apply_state *state,struct patch *patch)2207{2208struct strbuf qname = STRBUF_INIT;2209char*cp = patch->new_name ? patch->new_name : patch->old_name;2210int max, add, del;22112212quote_c_style(cp, &qname, NULL,0);22132214/*2215 * "scale" the filename2216 */2217 max = state->max_len;2218if(max >50)2219 max =50;22202221if(qname.len > max) {2222 cp =strchr(qname.buf + qname.len +3- max,'/');2223if(!cp)2224 cp = qname.buf + qname.len +3- max;2225strbuf_splice(&qname,0, cp - qname.buf,"...",3);2226}22272228if(patch->is_binary) {2229printf(" %-*s | Bin\n", max, qname.buf);2230strbuf_release(&qname);2231return;2232}22332234printf(" %-*s |", max, qname.buf);2235strbuf_release(&qname);22362237/*2238 * scale the add/delete2239 */2240 max = max + state->max_change >70?70- max : state->max_change;2241 add = patch->lines_added;2242 del = patch->lines_deleted;22432244if(state->max_change >0) {2245int total = ((add + del) * max + state->max_change /2) / state->max_change;2246 add = (add * max + state->max_change /2) / state->max_change;2247 del = total - add;2248}2249printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2250 add, pluses, del, minuses);2251}22522253static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2254{2255switch(st->st_mode & S_IFMT) {2256case S_IFLNK:2257if(strbuf_readlink(buf, path, st->st_size) <0)2258returnerror(_("unable to read symlink%s"), path);2259return0;2260case S_IFREG:2261if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2262returnerror(_("unable to open or read%s"), path);2263convert_to_git(path, buf->buf, buf->len, buf,0);2264return0;2265default:2266return-1;2267}2268}22692270/*2271 * Update the preimage, and the common lines in postimage,2272 * from buffer buf of length len. If postlen is 0 the postimage2273 * is updated in place, otherwise it's updated on a new buffer2274 * of length postlen2275 */22762277static voidupdate_pre_post_images(struct image *preimage,2278struct image *postimage,2279char*buf,2280size_t len,size_t postlen)2281{2282int i, ctx, reduced;2283char*new, *old, *fixed;2284struct image fixed_preimage;22852286/*2287 * Update the preimage with whitespace fixes. Note that we2288 * are not losing preimage->buf -- apply_one_fragment() will2289 * free "oldlines".2290 */2291prepare_image(&fixed_preimage, buf, len,1);2292assert(postlen2293? fixed_preimage.nr == preimage->nr2294: fixed_preimage.nr <= preimage->nr);2295for(i =0; i < fixed_preimage.nr; i++)2296 fixed_preimage.line[i].flag = preimage->line[i].flag;2297free(preimage->line_allocated);2298*preimage = fixed_preimage;22992300/*2301 * Adjust the common context lines in postimage. This can be2302 * done in-place when we are shrinking it with whitespace2303 * fixing, but needs a new buffer when ignoring whitespace or2304 * expanding leading tabs to spaces.2305 *2306 * We trust the caller to tell us if the update can be done2307 * in place (postlen==0) or not.2308 */2309 old = postimage->buf;2310if(postlen)2311new= postimage->buf =xmalloc(postlen);2312else2313new= old;2314 fixed = preimage->buf;23152316for(i = reduced = ctx =0; i < postimage->nr; i++) {2317size_t l_len = postimage->line[i].len;2318if(!(postimage->line[i].flag & LINE_COMMON)) {2319/* an added line -- no counterparts in preimage */2320memmove(new, old, l_len);2321 old += l_len;2322new+= l_len;2323continue;2324}23252326/* a common context -- skip it in the original postimage */2327 old += l_len;23282329/* and find the corresponding one in the fixed preimage */2330while(ctx < preimage->nr &&2331!(preimage->line[ctx].flag & LINE_COMMON)) {2332 fixed += preimage->line[ctx].len;2333 ctx++;2334}23352336/*2337 * preimage is expected to run out, if the caller2338 * fixed addition of trailing blank lines.2339 */2340if(preimage->nr <= ctx) {2341 reduced++;2342continue;2343}23442345/* and copy it in, while fixing the line length */2346 l_len = preimage->line[ctx].len;2347memcpy(new, fixed, l_len);2348new+= l_len;2349 fixed += l_len;2350 postimage->line[i].len = l_len;2351 ctx++;2352}23532354if(postlen2355? postlen <new- postimage->buf2356: postimage->len <new- postimage->buf)2357die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2358(int)postlen, (int) postimage->len, (int)(new- postimage->buf));23592360/* Fix the length of the whole thing */2361 postimage->len =new- postimage->buf;2362 postimage->nr -= reduced;2363}23642365static intline_by_line_fuzzy_match(struct image *img,2366struct image *preimage,2367struct image *postimage,2368unsigned longtry,2369int try_lno,2370int preimage_limit)2371{2372int i;2373size_t imgoff =0;2374size_t preoff =0;2375size_t postlen = postimage->len;2376size_t extra_chars;2377char*buf;2378char*preimage_eof;2379char*preimage_end;2380struct strbuf fixed;2381char*fixed_buf;2382size_t fixed_len;23832384for(i =0; i < preimage_limit; i++) {2385size_t prelen = preimage->line[i].len;2386size_t imglen = img->line[try_lno+i].len;23872388if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2389 preimage->buf + preoff, prelen))2390return0;2391if(preimage->line[i].flag & LINE_COMMON)2392 postlen += imglen - prelen;2393 imgoff += imglen;2394 preoff += prelen;2395}23962397/*2398 * Ok, the preimage matches with whitespace fuzz.2399 *2400 * imgoff now holds the true length of the target that2401 * matches the preimage before the end of the file.2402 *2403 * Count the number of characters in the preimage that fall2404 * beyond the end of the file and make sure that all of them2405 * are whitespace characters. (This can only happen if2406 * we are removing blank lines at the end of the file.)2407 */2408 buf = preimage_eof = preimage->buf + preoff;2409for( ; i < preimage->nr; i++)2410 preoff += preimage->line[i].len;2411 preimage_end = preimage->buf + preoff;2412for( ; buf < preimage_end; buf++)2413if(!isspace(*buf))2414return0;24152416/*2417 * Update the preimage and the common postimage context2418 * lines to use the same whitespace as the target.2419 * If whitespace is missing in the target (i.e.2420 * if the preimage extends beyond the end of the file),2421 * use the whitespace from the preimage.2422 */2423 extra_chars = preimage_end - preimage_eof;2424strbuf_init(&fixed, imgoff + extra_chars);2425strbuf_add(&fixed, img->buf +try, imgoff);2426strbuf_add(&fixed, preimage_eof, extra_chars);2427 fixed_buf =strbuf_detach(&fixed, &fixed_len);2428update_pre_post_images(preimage, postimage,2429 fixed_buf, fixed_len, postlen);2430return1;2431}24322433static intmatch_fragment(struct apply_state *state,2434struct image *img,2435struct image *preimage,2436struct image *postimage,2437unsigned longtry,2438int try_lno,2439unsigned ws_rule,2440int match_beginning,int match_end)2441{2442int i;2443char*fixed_buf, *buf, *orig, *target;2444struct strbuf fixed;2445size_t fixed_len, postlen;2446int preimage_limit;24472448if(preimage->nr + try_lno <= img->nr) {2449/*2450 * The hunk falls within the boundaries of img.2451 */2452 preimage_limit = preimage->nr;2453if(match_end && (preimage->nr + try_lno != img->nr))2454return0;2455}else if(state->ws_error_action == correct_ws_error &&2456(ws_rule & WS_BLANK_AT_EOF)) {2457/*2458 * This hunk extends beyond the end of img, and we are2459 * removing blank lines at the end of the file. This2460 * many lines from the beginning of the preimage must2461 * match with img, and the remainder of the preimage2462 * must be blank.2463 */2464 preimage_limit = img->nr - try_lno;2465}else{2466/*2467 * The hunk extends beyond the end of the img and2468 * we are not removing blanks at the end, so we2469 * should reject the hunk at this position.2470 */2471return0;2472}24732474if(match_beginning && try_lno)2475return0;24762477/* Quick hash check */2478for(i =0; i < preimage_limit; i++)2479if((img->line[try_lno + i].flag & LINE_PATCHED) ||2480(preimage->line[i].hash != img->line[try_lno + i].hash))2481return0;24822483if(preimage_limit == preimage->nr) {2484/*2485 * Do we have an exact match? If we were told to match2486 * at the end, size must be exactly at try+fragsize,2487 * otherwise try+fragsize must be still within the preimage,2488 * and either case, the old piece should match the preimage2489 * exactly.2490 */2491if((match_end2492? (try+ preimage->len == img->len)2493: (try+ preimage->len <= img->len)) &&2494!memcmp(img->buf +try, preimage->buf, preimage->len))2495return1;2496}else{2497/*2498 * The preimage extends beyond the end of img, so2499 * there cannot be an exact match.2500 *2501 * There must be one non-blank context line that match2502 * a line before the end of img.2503 */2504char*buf_end;25052506 buf = preimage->buf;2507 buf_end = buf;2508for(i =0; i < preimage_limit; i++)2509 buf_end += preimage->line[i].len;25102511for( ; buf < buf_end; buf++)2512if(!isspace(*buf))2513break;2514if(buf == buf_end)2515return0;2516}25172518/*2519 * No exact match. If we are ignoring whitespace, run a line-by-line2520 * fuzzy matching. We collect all the line length information because2521 * we need it to adjust whitespace if we match.2522 */2523if(state->ws_ignore_action == ignore_ws_change)2524returnline_by_line_fuzzy_match(img, preimage, postimage,2525try, try_lno, preimage_limit);25262527if(state->ws_error_action != correct_ws_error)2528return0;25292530/*2531 * The hunk does not apply byte-by-byte, but the hash says2532 * it might with whitespace fuzz. We weren't asked to2533 * ignore whitespace, we were asked to correct whitespace2534 * errors, so let's try matching after whitespace correction.2535 *2536 * While checking the preimage against the target, whitespace2537 * errors in both fixed, we count how large the corresponding2538 * postimage needs to be. The postimage prepared by2539 * apply_one_fragment() has whitespace errors fixed on added2540 * lines already, but the common lines were propagated as-is,2541 * which may become longer when their whitespace errors are2542 * fixed.2543 */25442545/* First count added lines in postimage */2546 postlen =0;2547for(i =0; i < postimage->nr; i++) {2548if(!(postimage->line[i].flag & LINE_COMMON))2549 postlen += postimage->line[i].len;2550}25512552/*2553 * The preimage may extend beyond the end of the file,2554 * but in this loop we will only handle the part of the2555 * preimage that falls within the file.2556 */2557strbuf_init(&fixed, preimage->len +1);2558 orig = preimage->buf;2559 target = img->buf +try;2560for(i =0; i < preimage_limit; i++) {2561size_t oldlen = preimage->line[i].len;2562size_t tgtlen = img->line[try_lno + i].len;2563size_t fixstart = fixed.len;2564struct strbuf tgtfix;2565int match;25662567/* Try fixing the line in the preimage */2568ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25692570/* Try fixing the line in the target */2571strbuf_init(&tgtfix, tgtlen);2572ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);25732574/*2575 * If they match, either the preimage was based on2576 * a version before our tree fixed whitespace breakage,2577 * or we are lacking a whitespace-fix patch the tree2578 * the preimage was based on already had (i.e. target2579 * has whitespace breakage, the preimage doesn't).2580 * In either case, we are fixing the whitespace breakages2581 * so we might as well take the fix together with their2582 * real change.2583 */2584 match = (tgtfix.len == fixed.len - fixstart &&2585!memcmp(tgtfix.buf, fixed.buf + fixstart,2586 fixed.len - fixstart));25872588/* Add the length if this is common with the postimage */2589if(preimage->line[i].flag & LINE_COMMON)2590 postlen += tgtfix.len;25912592strbuf_release(&tgtfix);2593if(!match)2594goto unmatch_exit;25952596 orig += oldlen;2597 target += tgtlen;2598}259926002601/*2602 * Now handle the lines in the preimage that falls beyond the2603 * end of the file (if any). They will only match if they are2604 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2605 * false).2606 */2607for( ; i < preimage->nr; i++) {2608size_t fixstart = fixed.len;/* start of the fixed preimage */2609size_t oldlen = preimage->line[i].len;2610int j;26112612/* Try fixing the line in the preimage */2613ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);26142615for(j = fixstart; j < fixed.len; j++)2616if(!isspace(fixed.buf[j]))2617goto unmatch_exit;26182619 orig += oldlen;2620}26212622/*2623 * Yes, the preimage is based on an older version that still2624 * has whitespace breakages unfixed, and fixing them makes the2625 * hunk match. Update the context lines in the postimage.2626 */2627 fixed_buf =strbuf_detach(&fixed, &fixed_len);2628if(postlen < postimage->len)2629 postlen =0;2630update_pre_post_images(preimage, postimage,2631 fixed_buf, fixed_len, postlen);2632return1;26332634 unmatch_exit:2635strbuf_release(&fixed);2636return0;2637}26382639static intfind_pos(struct apply_state *state,2640struct image *img,2641struct image *preimage,2642struct image *postimage,2643int line,2644unsigned ws_rule,2645int match_beginning,int match_end)2646{2647int i;2648unsigned long backwards, forwards,try;2649int backwards_lno, forwards_lno, try_lno;26502651/*2652 * If match_beginning or match_end is specified, there is no2653 * point starting from a wrong line that will never match and2654 * wander around and wait for a match at the specified end.2655 */2656if(match_beginning)2657 line =0;2658else if(match_end)2659 line = img->nr - preimage->nr;26602661/*2662 * Because the comparison is unsigned, the following test2663 * will also take care of a negative line number that can2664 * result when match_end and preimage is larger than the target.2665 */2666if((size_t) line > img->nr)2667 line = img->nr;26682669try=0;2670for(i =0; i < line; i++)2671try+= img->line[i].len;26722673/*2674 * There's probably some smart way to do this, but I'll leave2675 * that to the smart and beautiful people. I'm simple and stupid.2676 */2677 backwards =try;2678 backwards_lno = line;2679 forwards =try;2680 forwards_lno = line;2681 try_lno = line;26822683for(i =0; ; i++) {2684if(match_fragment(state, img, preimage, postimage,2685try, try_lno, ws_rule,2686 match_beginning, match_end))2687return try_lno;26882689 again:2690if(backwards_lno ==0&& forwards_lno == img->nr)2691break;26922693if(i &1) {2694if(backwards_lno ==0) {2695 i++;2696goto again;2697}2698 backwards_lno--;2699 backwards -= img->line[backwards_lno].len;2700try= backwards;2701 try_lno = backwards_lno;2702}else{2703if(forwards_lno == img->nr) {2704 i++;2705goto again;2706}2707 forwards += img->line[forwards_lno].len;2708 forwards_lno++;2709try= forwards;2710 try_lno = forwards_lno;2711}27122713}2714return-1;2715}27162717static voidremove_first_line(struct image *img)2718{2719 img->buf += img->line[0].len;2720 img->len -= img->line[0].len;2721 img->line++;2722 img->nr--;2723}27242725static voidremove_last_line(struct image *img)2726{2727 img->len -= img->line[--img->nr].len;2728}27292730/*2731 * The change from "preimage" and "postimage" has been found to2732 * apply at applied_pos (counts in line numbers) in "img".2733 * Update "img" to remove "preimage" and replace it with "postimage".2734 */2735static voidupdate_image(struct apply_state *state,2736struct image *img,2737int applied_pos,2738struct image *preimage,2739struct image *postimage)2740{2741/*2742 * remove the copy of preimage at offset in img2743 * and replace it with postimage2744 */2745int i, nr;2746size_t remove_count, insert_count, applied_at =0;2747char*result;2748int preimage_limit;27492750/*2751 * If we are removing blank lines at the end of img,2752 * the preimage may extend beyond the end.2753 * If that is the case, we must be careful only to2754 * remove the part of the preimage that falls within2755 * the boundaries of img. Initialize preimage_limit2756 * to the number of lines in the preimage that falls2757 * within the boundaries.2758 */2759 preimage_limit = preimage->nr;2760if(preimage_limit > img->nr - applied_pos)2761 preimage_limit = img->nr - applied_pos;27622763for(i =0; i < applied_pos; i++)2764 applied_at += img->line[i].len;27652766 remove_count =0;2767for(i =0; i < preimage_limit; i++)2768 remove_count += img->line[applied_pos + i].len;2769 insert_count = postimage->len;27702771/* Adjust the contents */2772 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2773memcpy(result, img->buf, applied_at);2774memcpy(result + applied_at, postimage->buf, postimage->len);2775memcpy(result + applied_at + postimage->len,2776 img->buf + (applied_at + remove_count),2777 img->len - (applied_at + remove_count));2778free(img->buf);2779 img->buf = result;2780 img->len += insert_count - remove_count;2781 result[img->len] ='\0';27822783/* Adjust the line table */2784 nr = img->nr + postimage->nr - preimage_limit;2785if(preimage_limit < postimage->nr) {2786/*2787 * NOTE: this knows that we never call remove_first_line()2788 * on anything other than pre/post image.2789 */2790REALLOC_ARRAY(img->line, nr);2791 img->line_allocated = img->line;2792}2793if(preimage_limit != postimage->nr)2794memmove(img->line + applied_pos + postimage->nr,2795 img->line + applied_pos + preimage_limit,2796(img->nr - (applied_pos + preimage_limit)) *2797sizeof(*img->line));2798memcpy(img->line + applied_pos,2799 postimage->line,2800 postimage->nr *sizeof(*img->line));2801if(!state->allow_overlap)2802for(i =0; i < postimage->nr; i++)2803 img->line[applied_pos + i].flag |= LINE_PATCHED;2804 img->nr = nr;2805}28062807/*2808 * Use the patch-hunk text in "frag" to prepare two images (preimage and2809 * postimage) for the hunk. Find lines that match "preimage" in "img" and2810 * replace the part of "img" with "postimage" text.2811 */2812static intapply_one_fragment(struct apply_state *state,2813struct image *img,struct fragment *frag,2814int inaccurate_eof,unsigned ws_rule,2815int nth_fragment)2816{2817int match_beginning, match_end;2818const char*patch = frag->patch;2819int size = frag->size;2820char*old, *oldlines;2821struct strbuf newlines;2822int new_blank_lines_at_end =0;2823int found_new_blank_lines_at_end =0;2824int hunk_linenr = frag->linenr;2825unsigned long leading, trailing;2826int pos, applied_pos;2827struct image preimage;2828struct image postimage;28292830memset(&preimage,0,sizeof(preimage));2831memset(&postimage,0,sizeof(postimage));2832 oldlines =xmalloc(size);2833strbuf_init(&newlines, size);28342835 old = oldlines;2836while(size >0) {2837char first;2838int len =linelen(patch, size);2839int plen;2840int added_blank_line =0;2841int is_blank_context =0;2842size_t start;28432844if(!len)2845break;28462847/*2848 * "plen" is how much of the line we should use for2849 * the actual patch data. Normally we just remove the2850 * first character on the line, but if the line is2851 * followed by "\ No newline", then we also remove the2852 * last one (which is the newline, of course).2853 */2854 plen = len -1;2855if(len < size && patch[len] =='\\')2856 plen--;2857 first = *patch;2858if(state->apply_in_reverse) {2859if(first =='-')2860 first ='+';2861else if(first =='+')2862 first ='-';2863}28642865switch(first) {2866case'\n':2867/* Newer GNU diff, empty context line */2868if(plen <0)2869/* ... followed by '\No newline'; nothing */2870break;2871*old++ ='\n';2872strbuf_addch(&newlines,'\n');2873add_line_info(&preimage,"\n",1, LINE_COMMON);2874add_line_info(&postimage,"\n",1, LINE_COMMON);2875 is_blank_context =1;2876break;2877case' ':2878if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2879ws_blank_line(patch +1, plen, ws_rule))2880 is_blank_context =1;2881case'-':2882memcpy(old, patch +1, plen);2883add_line_info(&preimage, old, plen,2884(first ==' '? LINE_COMMON :0));2885 old += plen;2886if(first =='-')2887break;2888/* Fall-through for ' ' */2889case'+':2890/* --no-add does not add new lines */2891if(first =='+'&& state->no_add)2892break;28932894 start = newlines.len;2895if(first !='+'||2896!state->whitespace_error ||2897 state->ws_error_action != correct_ws_error) {2898strbuf_add(&newlines, patch +1, plen);2899}2900else{2901ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2902}2903add_line_info(&postimage, newlines.buf + start, newlines.len - start,2904(first =='+'?0: LINE_COMMON));2905if(first =='+'&&2906(ws_rule & WS_BLANK_AT_EOF) &&2907ws_blank_line(patch +1, plen, ws_rule))2908 added_blank_line =1;2909break;2910case'@':case'\\':2911/* Ignore it, we already handled it */2912break;2913default:2914if(state->apply_verbosely)2915error(_("invalid start of line: '%c'"), first);2916 applied_pos = -1;2917goto out;2918}2919if(added_blank_line) {2920if(!new_blank_lines_at_end)2921 found_new_blank_lines_at_end = hunk_linenr;2922 new_blank_lines_at_end++;2923}2924else if(is_blank_context)2925;2926else2927 new_blank_lines_at_end =0;2928 patch += len;2929 size -= len;2930 hunk_linenr++;2931}2932if(inaccurate_eof &&2933 old > oldlines && old[-1] =='\n'&&2934 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2935 old--;2936strbuf_setlen(&newlines, newlines.len -1);2937}29382939 leading = frag->leading;2940 trailing = frag->trailing;29412942/*2943 * A hunk to change lines at the beginning would begin with2944 * @@ -1,L +N,M @@2945 * but we need to be careful. -U0 that inserts before the second2946 * line also has this pattern.2947 *2948 * And a hunk to add to an empty file would begin with2949 * @@ -0,0 +N,M @@2950 *2951 * In other words, a hunk that is (frag->oldpos <= 1) with or2952 * without leading context must match at the beginning.2953 */2954 match_beginning = (!frag->oldpos ||2955(frag->oldpos ==1&& !state->unidiff_zero));29562957/*2958 * A hunk without trailing lines must match at the end.2959 * However, we simply cannot tell if a hunk must match end2960 * from the lack of trailing lines if the patch was generated2961 * with unidiff without any context.2962 */2963 match_end = !state->unidiff_zero && !trailing;29642965 pos = frag->newpos ? (frag->newpos -1) :0;2966 preimage.buf = oldlines;2967 preimage.len = old - oldlines;2968 postimage.buf = newlines.buf;2969 postimage.len = newlines.len;2970 preimage.line = preimage.line_allocated;2971 postimage.line = postimage.line_allocated;29722973for(;;) {29742975 applied_pos =find_pos(state, img, &preimage, &postimage, pos,2976 ws_rule, match_beginning, match_end);29772978if(applied_pos >=0)2979break;29802981/* Am I at my context limits? */2982if((leading <= state->p_context) && (trailing <= state->p_context))2983break;2984if(match_beginning || match_end) {2985 match_beginning = match_end =0;2986continue;2987}29882989/*2990 * Reduce the number of context lines; reduce both2991 * leading and trailing if they are equal otherwise2992 * just reduce the larger context.2993 */2994if(leading >= trailing) {2995remove_first_line(&preimage);2996remove_first_line(&postimage);2997 pos--;2998 leading--;2999}3000if(trailing > leading) {3001remove_last_line(&preimage);3002remove_last_line(&postimage);3003 trailing--;3004}3005}30063007if(applied_pos >=0) {3008if(new_blank_lines_at_end &&3009 preimage.nr + applied_pos >= img->nr &&3010(ws_rule & WS_BLANK_AT_EOF) &&3011 state->ws_error_action != nowarn_ws_error) {3012record_ws_error(state, WS_BLANK_AT_EOF,"+",1,3013 found_new_blank_lines_at_end);3014if(state->ws_error_action == correct_ws_error) {3015while(new_blank_lines_at_end--)3016remove_last_line(&postimage);3017}3018/*3019 * We would want to prevent write_out_results()3020 * from taking place in apply_patch() that follows3021 * the callchain led us here, which is:3022 * apply_patch->check_patch_list->check_patch->3023 * apply_data->apply_fragments->apply_one_fragment3024 */3025if(state->ws_error_action == die_on_ws_error)3026 state->apply =0;3027}30283029if(state->apply_verbosely && applied_pos != pos) {3030int offset = applied_pos - pos;3031if(state->apply_in_reverse)3032 offset =0- offset;3033fprintf_ln(stderr,3034Q_("Hunk #%dsucceeded at%d(offset%dline).",3035"Hunk #%dsucceeded at%d(offset%dlines).",3036 offset),3037 nth_fragment, applied_pos +1, offset);3038}30393040/*3041 * Warn if it was necessary to reduce the number3042 * of context lines.3043 */3044if((leading != frag->leading) ||3045(trailing != frag->trailing))3046fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"3047" to apply fragment at%d"),3048 leading, trailing, applied_pos+1);3049update_image(state, img, applied_pos, &preimage, &postimage);3050}else{3051if(state->apply_verbosely)3052error(_("while searching for:\n%.*s"),3053(int)(old - oldlines), oldlines);3054}30553056out:3057free(oldlines);3058strbuf_release(&newlines);3059free(preimage.line_allocated);3060free(postimage.line_allocated);30613062return(applied_pos <0);3063}30643065static intapply_binary_fragment(struct apply_state *state,3066struct image *img,3067struct patch *patch)3068{3069struct fragment *fragment = patch->fragments;3070unsigned long len;3071void*dst;30723073if(!fragment)3074returnerror(_("missing binary patch data for '%s'"),3075 patch->new_name ?3076 patch->new_name :3077 patch->old_name);30783079/* Binary patch is irreversible without the optional second hunk */3080if(state->apply_in_reverse) {3081if(!fragment->next)3082returnerror("cannot reverse-apply a binary patch "3083"without the reverse hunk to '%s'",3084 patch->new_name3085? patch->new_name : patch->old_name);3086 fragment = fragment->next;3087}3088switch(fragment->binary_patch_method) {3089case BINARY_DELTA_DEFLATED:3090 dst =patch_delta(img->buf, img->len, fragment->patch,3091 fragment->size, &len);3092if(!dst)3093return-1;3094clear_image(img);3095 img->buf = dst;3096 img->len = len;3097return0;3098case BINARY_LITERAL_DEFLATED:3099clear_image(img);3100 img->len = fragment->size;3101 img->buf =xmemdupz(fragment->patch, img->len);3102return0;3103}3104return-1;3105}31063107/*3108 * Replace "img" with the result of applying the binary patch.3109 * The binary patch data itself in patch->fragment is still kept3110 * but the preimage prepared by the caller in "img" is freed here3111 * or in the helper function apply_binary_fragment() this calls.3112 */3113static intapply_binary(struct apply_state *state,3114struct image *img,3115struct patch *patch)3116{3117const char*name = patch->old_name ? patch->old_name : patch->new_name;3118unsigned char sha1[20];31193120/*3121 * For safety, we require patch index line to contain3122 * full 40-byte textual SHA1 for old and new, at least for now.3123 */3124if(strlen(patch->old_sha1_prefix) !=40||3125strlen(patch->new_sha1_prefix) !=40||3126get_sha1_hex(patch->old_sha1_prefix, sha1) ||3127get_sha1_hex(patch->new_sha1_prefix, sha1))3128returnerror("cannot apply binary patch to '%s' "3129"without full index line", name);31303131if(patch->old_name) {3132/*3133 * See if the old one matches what the patch3134 * applies to.3135 */3136hash_sha1_file(img->buf, img->len, blob_type, sha1);3137if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3138returnerror("the patch applies to '%s' (%s), "3139"which does not match the "3140"current contents.",3141 name,sha1_to_hex(sha1));3142}3143else{3144/* Otherwise, the old one must be empty. */3145if(img->len)3146returnerror("the patch applies to an empty "3147"'%s' but it is not empty", name);3148}31493150get_sha1_hex(patch->new_sha1_prefix, sha1);3151if(is_null_sha1(sha1)) {3152clear_image(img);3153return0;/* deletion patch */3154}31553156if(has_sha1_file(sha1)) {3157/* We already have the postimage */3158enum object_type type;3159unsigned long size;3160char*result;31613162 result =read_sha1_file(sha1, &type, &size);3163if(!result)3164returnerror("the necessary postimage%sfor "3165"'%s' cannot be read",3166 patch->new_sha1_prefix, name);3167clear_image(img);3168 img->buf = result;3169 img->len = size;3170}else{3171/*3172 * We have verified buf matches the preimage;3173 * apply the patch data to it, which is stored3174 * in the patch->fragments->{patch,size}.3175 */3176if(apply_binary_fragment(state, img, patch))3177returnerror(_("binary patch does not apply to '%s'"),3178 name);31793180/* verify that the result matches */3181hash_sha1_file(img->buf, img->len, blob_type, sha1);3182if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3183returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3184 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3185}31863187return0;3188}31893190static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3191{3192struct fragment *frag = patch->fragments;3193const char*name = patch->old_name ? patch->old_name : patch->new_name;3194unsigned ws_rule = patch->ws_rule;3195unsigned inaccurate_eof = patch->inaccurate_eof;3196int nth =0;31973198if(patch->is_binary)3199returnapply_binary(state, img, patch);32003201while(frag) {3202 nth++;3203if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3204error(_("patch failed:%s:%ld"), name, frag->oldpos);3205if(!state->apply_with_reject)3206return-1;3207 frag->rejected =1;3208}3209 frag = frag->next;3210}3211return0;3212}32133214static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3215{3216if(S_ISGITLINK(mode)) {3217strbuf_grow(buf,100);3218strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3219}else{3220enum object_type type;3221unsigned long sz;3222char*result;32233224 result =read_sha1_file(sha1, &type, &sz);3225if(!result)3226return-1;3227/* XXX read_sha1_file NUL-terminates */3228strbuf_attach(buf, result, sz, sz +1);3229}3230return0;3231}32323233static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3234{3235if(!ce)3236return0;3237returnread_blob_object(buf, ce->sha1, ce->ce_mode);3238}32393240static struct patch *in_fn_table(struct apply_state *state,const char*name)3241{3242struct string_list_item *item;32433244if(name == NULL)3245return NULL;32463247 item =string_list_lookup(&state->fn_table, name);3248if(item != NULL)3249return(struct patch *)item->util;32503251return NULL;3252}32533254/*3255 * item->util in the filename table records the status of the path.3256 * Usually it points at a patch (whose result records the contents3257 * of it after applying it), but it could be PATH_WAS_DELETED for a3258 * path that a previously applied patch has already removed, or3259 * PATH_TO_BE_DELETED for a path that a later patch would remove.3260 *3261 * The latter is needed to deal with a case where two paths A and B3262 * are swapped by first renaming A to B and then renaming B to A;3263 * moving A to B should not be prevented due to presence of B as we3264 * will remove it in a later patch.3265 */3266#define PATH_TO_BE_DELETED ((struct patch *) -2)3267#define PATH_WAS_DELETED ((struct patch *) -1)32683269static intto_be_deleted(struct patch *patch)3270{3271return patch == PATH_TO_BE_DELETED;3272}32733274static intwas_deleted(struct patch *patch)3275{3276return patch == PATH_WAS_DELETED;3277}32783279static voidadd_to_fn_table(struct apply_state *state,struct patch *patch)3280{3281struct string_list_item *item;32823283/*3284 * Always add new_name unless patch is a deletion3285 * This should cover the cases for normal diffs,3286 * file creations and copies3287 */3288if(patch->new_name != NULL) {3289 item =string_list_insert(&state->fn_table, patch->new_name);3290 item->util = patch;3291}32923293/*3294 * store a failure on rename/deletion cases because3295 * later chunks shouldn't patch old names3296 */3297if((patch->new_name == NULL) || (patch->is_rename)) {3298 item =string_list_insert(&state->fn_table, patch->old_name);3299 item->util = PATH_WAS_DELETED;3300}3301}33023303static voidprepare_fn_table(struct apply_state *state,struct patch *patch)3304{3305/*3306 * store information about incoming file deletion3307 */3308while(patch) {3309if((patch->new_name == NULL) || (patch->is_rename)) {3310struct string_list_item *item;3311 item =string_list_insert(&state->fn_table, patch->old_name);3312 item->util = PATH_TO_BE_DELETED;3313}3314 patch = patch->next;3315}3316}33173318static intcheckout_target(struct index_state *istate,3319struct cache_entry *ce,struct stat *st)3320{3321struct checkout costate;33223323memset(&costate,0,sizeof(costate));3324 costate.base_dir ="";3325 costate.refresh_cache =1;3326 costate.istate = istate;3327if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3328returnerror(_("cannot checkout%s"), ce->name);3329return0;3330}33313332static struct patch *previous_patch(struct apply_state *state,3333struct patch *patch,3334int*gone)3335{3336struct patch *previous;33373338*gone =0;3339if(patch->is_copy || patch->is_rename)3340return NULL;/* "git" patches do not depend on the order */33413342 previous =in_fn_table(state, patch->old_name);3343if(!previous)3344return NULL;33453346if(to_be_deleted(previous))3347return NULL;/* the deletion hasn't happened yet */33483349if(was_deleted(previous))3350*gone =1;33513352return previous;3353}33543355static intverify_index_match(const struct cache_entry *ce,struct stat *st)3356{3357if(S_ISGITLINK(ce->ce_mode)) {3358if(!S_ISDIR(st->st_mode))3359return-1;3360return0;3361}3362returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3363}33643365#define SUBMODULE_PATCH_WITHOUT_INDEX 133663367static intload_patch_target(struct apply_state *state,3368struct strbuf *buf,3369const struct cache_entry *ce,3370struct stat *st,3371const char*name,3372unsigned expected_mode)3373{3374if(state->cached || state->check_index) {3375if(read_file_or_gitlink(ce, buf))3376returnerror(_("failed to read%s"), name);3377}else if(name) {3378if(S_ISGITLINK(expected_mode)) {3379if(ce)3380returnread_file_or_gitlink(ce, buf);3381else3382return SUBMODULE_PATCH_WITHOUT_INDEX;3383}else if(has_symlink_leading_path(name,strlen(name))) {3384returnerror(_("reading from '%s' beyond a symbolic link"), name);3385}else{3386if(read_old_data(st, name, buf))3387returnerror(_("failed to read%s"), name);3388}3389}3390return0;3391}33923393/*3394 * We are about to apply "patch"; populate the "image" with the3395 * current version we have, from the working tree or from the index,3396 * depending on the situation e.g. --cached/--index. If we are3397 * applying a non-git patch that incrementally updates the tree,3398 * we read from the result of a previous diff.3399 */3400static intload_preimage(struct apply_state *state,3401struct image *image,3402struct patch *patch,struct stat *st,3403const struct cache_entry *ce)3404{3405struct strbuf buf = STRBUF_INIT;3406size_t len;3407char*img;3408struct patch *previous;3409int status;34103411 previous =previous_patch(state, patch, &status);3412if(status)3413returnerror(_("path%shas been renamed/deleted"),3414 patch->old_name);3415if(previous) {3416/* We have a patched copy in memory; use that. */3417strbuf_add(&buf, previous->result, previous->resultsize);3418}else{3419 status =load_patch_target(state, &buf, ce, st,3420 patch->old_name, patch->old_mode);3421if(status <0)3422return status;3423else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3424/*3425 * There is no way to apply subproject3426 * patch without looking at the index.3427 * NEEDSWORK: shouldn't this be flagged3428 * as an error???3429 */3430free_fragment_list(patch->fragments);3431 patch->fragments = NULL;3432}else if(status) {3433returnerror(_("failed to read%s"), patch->old_name);3434}3435}34363437 img =strbuf_detach(&buf, &len);3438prepare_image(image, img, len, !patch->is_binary);3439return0;3440}34413442static intthree_way_merge(struct image *image,3443char*path,3444const unsigned char*base,3445const unsigned char*ours,3446const unsigned char*theirs)3447{3448 mmfile_t base_file, our_file, their_file;3449 mmbuffer_t result = { NULL };3450int status;34513452read_mmblob(&base_file, base);3453read_mmblob(&our_file, ours);3454read_mmblob(&their_file, theirs);3455 status =ll_merge(&result, path,3456&base_file,"base",3457&our_file,"ours",3458&their_file,"theirs", NULL);3459free(base_file.ptr);3460free(our_file.ptr);3461free(their_file.ptr);3462if(status <0|| !result.ptr) {3463free(result.ptr);3464return-1;3465}3466clear_image(image);3467 image->buf = result.ptr;3468 image->len = result.size;34693470return status;3471}34723473/*3474 * When directly falling back to add/add three-way merge, we read from3475 * the current contents of the new_name. In no cases other than that3476 * this function will be called.3477 */3478static intload_current(struct apply_state *state,3479struct image *image,3480struct patch *patch)3481{3482struct strbuf buf = STRBUF_INIT;3483int status, pos;3484size_t len;3485char*img;3486struct stat st;3487struct cache_entry *ce;3488char*name = patch->new_name;3489unsigned mode = patch->new_mode;34903491if(!patch->is_new)3492die("BUG: patch to%sis not a creation", patch->old_name);34933494 pos =cache_name_pos(name,strlen(name));3495if(pos <0)3496returnerror(_("%s: does not exist in index"), name);3497 ce = active_cache[pos];3498if(lstat(name, &st)) {3499if(errno != ENOENT)3500returnerror(_("%s:%s"), name,strerror(errno));3501if(checkout_target(&the_index, ce, &st))3502return-1;3503}3504if(verify_index_match(ce, &st))3505returnerror(_("%s: does not match index"), name);35063507 status =load_patch_target(state, &buf, ce, &st, name, mode);3508if(status <0)3509return status;3510else if(status)3511return-1;3512 img =strbuf_detach(&buf, &len);3513prepare_image(image, img, len, !patch->is_binary);3514return0;3515}35163517static inttry_threeway(struct apply_state *state,3518struct image *image,3519struct patch *patch,3520struct stat *st,3521const struct cache_entry *ce)3522{3523unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3524struct strbuf buf = STRBUF_INIT;3525size_t len;3526int status;3527char*img;3528struct image tmp_image;35293530/* No point falling back to 3-way merge in these cases */3531if(patch->is_delete ||3532S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3533return-1;35343535/* Preimage the patch was prepared for */3536if(patch->is_new)3537write_sha1_file("",0, blob_type, pre_sha1);3538else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3539read_blob_object(&buf, pre_sha1, patch->old_mode))3540returnerror("repository lacks the necessary blob to fall back on 3-way merge.");35413542fprintf(stderr,"Falling back to three-way merge...\n");35433544 img =strbuf_detach(&buf, &len);3545prepare_image(&tmp_image, img, len,1);3546/* Apply the patch to get the post image */3547if(apply_fragments(state, &tmp_image, patch) <0) {3548clear_image(&tmp_image);3549return-1;3550}3551/* post_sha1[] is theirs */3552write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3553clear_image(&tmp_image);35543555/* our_sha1[] is ours */3556if(patch->is_new) {3557if(load_current(state, &tmp_image, patch))3558returnerror("cannot read the current contents of '%s'",3559 patch->new_name);3560}else{3561if(load_preimage(state, &tmp_image, patch, st, ce))3562returnerror("cannot read the current contents of '%s'",3563 patch->old_name);3564}3565write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3566clear_image(&tmp_image);35673568/* in-core three-way merge between post and our using pre as base */3569 status =three_way_merge(image, patch->new_name,3570 pre_sha1, our_sha1, post_sha1);3571if(status <0) {3572fprintf(stderr,"Failed to fall back on three-way merge...\n");3573return status;3574}35753576if(status) {3577 patch->conflicted_threeway =1;3578if(patch->is_new)3579oidclr(&patch->threeway_stage[0]);3580else3581hashcpy(patch->threeway_stage[0].hash, pre_sha1);3582hashcpy(patch->threeway_stage[1].hash, our_sha1);3583hashcpy(patch->threeway_stage[2].hash, post_sha1);3584fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3585}else{3586fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3587}3588return0;3589}35903591static intapply_data(struct apply_state *state,struct patch *patch,3592struct stat *st,const struct cache_entry *ce)3593{3594struct image image;35953596if(load_preimage(state, &image, patch, st, ce) <0)3597return-1;35983599if(patch->direct_to_threeway ||3600apply_fragments(state, &image, patch) <0) {3601/* Note: with --reject, apply_fragments() returns 0 */3602if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3603return-1;3604}3605 patch->result = image.buf;3606 patch->resultsize = image.len;3607add_to_fn_table(state, patch);3608free(image.line_allocated);36093610if(0< patch->is_delete && patch->resultsize)3611returnerror(_("removal patch leaves file contents"));36123613return0;3614}36153616/*3617 * If "patch" that we are looking at modifies or deletes what we have,3618 * we would want it not to lose any local modification we have, either3619 * in the working tree or in the index.3620 *3621 * This also decides if a non-git patch is a creation patch or a3622 * modification to an existing empty file. We do not check the state3623 * of the current tree for a creation patch in this function; the caller3624 * check_patch() separately makes sure (and errors out otherwise) that3625 * the path the patch creates does not exist in the current tree.3626 */3627static intcheck_preimage(struct apply_state *state,3628struct patch *patch,3629struct cache_entry **ce,3630struct stat *st)3631{3632const char*old_name = patch->old_name;3633struct patch *previous = NULL;3634int stat_ret =0, status;3635unsigned st_mode =0;36363637if(!old_name)3638return0;36393640assert(patch->is_new <=0);3641 previous =previous_patch(state, patch, &status);36423643if(status)3644returnerror(_("path%shas been renamed/deleted"), old_name);3645if(previous) {3646 st_mode = previous->new_mode;3647}else if(!state->cached) {3648 stat_ret =lstat(old_name, st);3649if(stat_ret && errno != ENOENT)3650returnerror(_("%s:%s"), old_name,strerror(errno));3651}36523653if(state->check_index && !previous) {3654int pos =cache_name_pos(old_name,strlen(old_name));3655if(pos <0) {3656if(patch->is_new <0)3657goto is_new;3658returnerror(_("%s: does not exist in index"), old_name);3659}3660*ce = active_cache[pos];3661if(stat_ret <0) {3662if(checkout_target(&the_index, *ce, st))3663return-1;3664}3665if(!state->cached &&verify_index_match(*ce, st))3666returnerror(_("%s: does not match index"), old_name);3667if(state->cached)3668 st_mode = (*ce)->ce_mode;3669}else if(stat_ret <0) {3670if(patch->is_new <0)3671goto is_new;3672returnerror(_("%s:%s"), old_name,strerror(errno));3673}36743675if(!state->cached && !previous)3676 st_mode =ce_mode_from_stat(*ce, st->st_mode);36773678if(patch->is_new <0)3679 patch->is_new =0;3680if(!patch->old_mode)3681 patch->old_mode = st_mode;3682if((st_mode ^ patch->old_mode) & S_IFMT)3683returnerror(_("%s: wrong type"), old_name);3684if(st_mode != patch->old_mode)3685warning(_("%shas type%o, expected%o"),3686 old_name, st_mode, patch->old_mode);3687if(!patch->new_mode && !patch->is_delete)3688 patch->new_mode = st_mode;3689return0;36903691 is_new:3692 patch->is_new =1;3693 patch->is_delete =0;3694free(patch->old_name);3695 patch->old_name = NULL;3696return0;3697}369836993700#define EXISTS_IN_INDEX 13701#define EXISTS_IN_WORKTREE 237023703static intcheck_to_create(struct apply_state *state,3704const char*new_name,3705int ok_if_exists)3706{3707struct stat nst;37083709if(state->check_index &&3710cache_name_pos(new_name,strlen(new_name)) >=0&&3711!ok_if_exists)3712return EXISTS_IN_INDEX;3713if(state->cached)3714return0;37153716if(!lstat(new_name, &nst)) {3717if(S_ISDIR(nst.st_mode) || ok_if_exists)3718return0;3719/*3720 * A leading component of new_name might be a symlink3721 * that is going to be removed with this patch, but3722 * still pointing at somewhere that has the path.3723 * In such a case, path "new_name" does not exist as3724 * far as git is concerned.3725 */3726if(has_symlink_leading_path(new_name,strlen(new_name)))3727return0;37283729return EXISTS_IN_WORKTREE;3730}else if((errno != ENOENT) && (errno != ENOTDIR)) {3731returnerror("%s:%s", new_name,strerror(errno));3732}3733return0;3734}37353736static uintptr_tregister_symlink_changes(struct apply_state *state,3737const char*path,3738uintptr_t what)3739{3740struct string_list_item *ent;37413742 ent =string_list_lookup(&state->symlink_changes, path);3743if(!ent) {3744 ent =string_list_insert(&state->symlink_changes, path);3745 ent->util = (void*)0;3746}3747 ent->util = (void*)(what | ((uintptr_t)ent->util));3748return(uintptr_t)ent->util;3749}37503751static uintptr_tcheck_symlink_changes(struct apply_state *state,const char*path)3752{3753struct string_list_item *ent;37543755 ent =string_list_lookup(&state->symlink_changes, path);3756if(!ent)3757return0;3758return(uintptr_t)ent->util;3759}37603761static voidprepare_symlink_changes(struct apply_state *state,struct patch *patch)3762{3763for( ; patch; patch = patch->next) {3764if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3765(patch->is_rename || patch->is_delete))3766/* the symlink at patch->old_name is removed */3767register_symlink_changes(state, patch->old_name, APPLY_SYMLINK_GOES_AWAY);37683769if(patch->new_name &&S_ISLNK(patch->new_mode))3770/* the symlink at patch->new_name is created or remains */3771register_symlink_changes(state, patch->new_name, APPLY_SYMLINK_IN_RESULT);3772}3773}37743775static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3776{3777do{3778unsigned int change;37793780while(--name->len && name->buf[name->len] !='/')3781;/* scan backwards */3782if(!name->len)3783break;3784 name->buf[name->len] ='\0';3785 change =check_symlink_changes(state, name->buf);3786if(change & APPLY_SYMLINK_IN_RESULT)3787return1;3788if(change & APPLY_SYMLINK_GOES_AWAY)3789/*3790 * This cannot be "return 0", because we may3791 * see a new one created at a higher level.3792 */3793continue;37943795/* otherwise, check the preimage */3796if(state->check_index) {3797struct cache_entry *ce;37983799 ce =cache_file_exists(name->buf, name->len, ignore_case);3800if(ce &&S_ISLNK(ce->ce_mode))3801return1;3802}else{3803struct stat st;3804if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3805return1;3806}3807}while(1);3808return0;3809}38103811static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3812{3813int ret;3814struct strbuf name = STRBUF_INIT;38153816assert(*name_ !='\0');3817strbuf_addstr(&name, name_);3818 ret =path_is_beyond_symlink_1(state, &name);3819strbuf_release(&name);38203821return ret;3822}38233824static intcheck_unsafe_path(struct patch *patch)3825{3826const char*old_name = NULL;3827const char*new_name = NULL;3828if(patch->is_delete)3829 old_name = patch->old_name;3830else if(!patch->is_new && !patch->is_copy)3831 old_name = patch->old_name;3832if(!patch->is_delete)3833 new_name = patch->new_name;38343835if(old_name && !verify_path(old_name))3836returnerror(_("invalid path '%s'"), old_name);3837if(new_name && !verify_path(new_name))3838returnerror(_("invalid path '%s'"), new_name);3839return0;3840}38413842/*3843 * Check and apply the patch in-core; leave the result in patch->result3844 * for the caller to write it out to the final destination.3845 */3846static intcheck_patch(struct apply_state *state,struct patch *patch)3847{3848struct stat st;3849const char*old_name = patch->old_name;3850const char*new_name = patch->new_name;3851const char*name = old_name ? old_name : new_name;3852struct cache_entry *ce = NULL;3853struct patch *tpatch;3854int ok_if_exists;3855int status;38563857 patch->rejected =1;/* we will drop this after we succeed */38583859 status =check_preimage(state, patch, &ce, &st);3860if(status)3861return status;3862 old_name = patch->old_name;38633864/*3865 * A type-change diff is always split into a patch to delete3866 * old, immediately followed by a patch to create new (see3867 * diff.c::run_diff()); in such a case it is Ok that the entry3868 * to be deleted by the previous patch is still in the working3869 * tree and in the index.3870 *3871 * A patch to swap-rename between A and B would first rename A3872 * to B and then rename B to A. While applying the first one,3873 * the presence of B should not stop A from getting renamed to3874 * B; ask to_be_deleted() about the later rename. Removal of3875 * B and rename from A to B is handled the same way by asking3876 * was_deleted().3877 */3878if((tpatch =in_fn_table(state, new_name)) &&3879(was_deleted(tpatch) ||to_be_deleted(tpatch)))3880 ok_if_exists =1;3881else3882 ok_if_exists =0;38833884if(new_name &&3885((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3886int err =check_to_create(state, new_name, ok_if_exists);38873888if(err && state->threeway) {3889 patch->direct_to_threeway =1;3890}else switch(err) {3891case0:3892break;/* happy */3893case EXISTS_IN_INDEX:3894returnerror(_("%s: already exists in index"), new_name);3895break;3896case EXISTS_IN_WORKTREE:3897returnerror(_("%s: already exists in working directory"),3898 new_name);3899default:3900return err;3901}39023903if(!patch->new_mode) {3904if(0< patch->is_new)3905 patch->new_mode = S_IFREG |0644;3906else3907 patch->new_mode = patch->old_mode;3908}3909}39103911if(new_name && old_name) {3912int same = !strcmp(old_name, new_name);3913if(!patch->new_mode)3914 patch->new_mode = patch->old_mode;3915if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3916if(same)3917returnerror(_("new mode (%o) of%sdoes not "3918"match old mode (%o)"),3919 patch->new_mode, new_name,3920 patch->old_mode);3921else3922returnerror(_("new mode (%o) of%sdoes not "3923"match old mode (%o) of%s"),3924 patch->new_mode, new_name,3925 patch->old_mode, old_name);3926}3927}39283929if(!state->unsafe_paths &&check_unsafe_path(patch))3930return-128;39313932/*3933 * An attempt to read from or delete a path that is beyond a3934 * symbolic link will be prevented by load_patch_target() that3935 * is called at the beginning of apply_data() so we do not3936 * have to worry about a patch marked with "is_delete" bit3937 * here. We however need to make sure that the patch result3938 * is not deposited to a path that is beyond a symbolic link3939 * here.3940 */3941if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3942returnerror(_("affected file '%s' is beyond a symbolic link"),3943 patch->new_name);39443945if(apply_data(state, patch, &st, ce) <0)3946returnerror(_("%s: patch does not apply"), name);3947 patch->rejected =0;3948return0;3949}39503951static intcheck_patch_list(struct apply_state *state,struct patch *patch)3952{3953int err =0;39543955prepare_symlink_changes(state, patch);3956prepare_fn_table(state, patch);3957while(patch) {3958int res;3959if(state->apply_verbosely)3960say_patch_name(stderr,3961_("Checking patch%s..."), patch);3962 res =check_patch(state, patch);3963if(res == -128)3964return-128;3965 err |= res;3966 patch = patch->next;3967}3968return err;3969}39703971/* This function tries to read the sha1 from the current index */3972static intget_current_sha1(const char*path,unsigned char*sha1)3973{3974int pos;39753976if(read_cache() <0)3977return-1;3978 pos =cache_name_pos(path,strlen(path));3979if(pos <0)3980return-1;3981hashcpy(sha1, active_cache[pos]->sha1);3982return0;3983}39843985static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3986{3987/*3988 * A usable gitlink patch has only one fragment (hunk) that looks like:3989 * @@ -1 +1 @@3990 * -Subproject commit <old sha1>3991 * +Subproject commit <new sha1>3992 * or3993 * @@ -1 +0,0 @@3994 * -Subproject commit <old sha1>3995 * for a removal patch.3996 */3997struct fragment *hunk = p->fragments;3998static const char heading[] ="-Subproject commit ";3999char*preimage;40004001if(/* does the patch have only one hunk? */4002 hunk && !hunk->next &&4003/* is its preimage one line? */4004 hunk->oldpos ==1&& hunk->oldlines ==1&&4005/* does preimage begin with the heading? */4006(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&4007starts_with(++preimage, heading) &&4008/* does it record full SHA-1? */4009!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&4010 preimage[sizeof(heading) +40-1] =='\n'&&4011/* does the abbreviated name on the index line agree with it? */4012starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))4013return0;/* it all looks fine */40144015/* we may have full object name on the index line */4016returnget_sha1_hex(p->old_sha1_prefix, sha1);4017}40184019/* Build an index that contains the just the files needed for a 3way merge */4020static intbuild_fake_ancestor(struct patch *list,const char*filename)4021{4022struct patch *patch;4023struct index_state result = { NULL };4024static struct lock_file lock;4025int res;40264027/* Once we start supporting the reverse patch, it may be4028 * worth showing the new sha1 prefix, but until then...4029 */4030for(patch = list; patch; patch = patch->next) {4031unsigned char sha1[20];4032struct cache_entry *ce;4033const char*name;40344035 name = patch->old_name ? patch->old_name : patch->new_name;4036if(0< patch->is_new)4037continue;40384039if(S_ISGITLINK(patch->old_mode)) {4040if(!preimage_sha1_in_gitlink_patch(patch, sha1))4041;/* ok, the textual part looks sane */4042else4043returnerror("sha1 information is lacking or "4044"useless for submodule%s", name);4045}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {4046;/* ok */4047}else if(!patch->lines_added && !patch->lines_deleted) {4048/* mode-only change: update the current */4049if(get_current_sha1(patch->old_name, sha1))4050returnerror("mode change for%s, which is not "4051"in current HEAD", name);4052}else4053returnerror("sha1 information is lacking or useless "4054"(%s).", name);40554056 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);4057if(!ce)4058returnerror(_("make_cache_entry failed for path '%s'"),4059 name);4060if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) {4061free(ce);4062returnerror("Could not add%sto temporary index",4063 name);4064}4065}40664067hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);4068 res =write_locked_index(&result, &lock, COMMIT_LOCK);4069discard_index(&result);40704071if(res)4072returnerror("Could not write temporary index to%s", filename);40734074return0;4075}40764077static voidstat_patch_list(struct apply_state *state,struct patch *patch)4078{4079int files, adds, dels;40804081for(files = adds = dels =0; patch ; patch = patch->next) {4082 files++;4083 adds += patch->lines_added;4084 dels += patch->lines_deleted;4085show_stats(state, patch);4086}40874088print_stat_summary(stdout, files, adds, dels);4089}40904091static voidnumstat_patch_list(struct apply_state *state,4092struct patch *patch)4093{4094for( ; patch; patch = patch->next) {4095const char*name;4096 name = patch->new_name ? patch->new_name : patch->old_name;4097if(patch->is_binary)4098printf("-\t-\t");4099else4100printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4101write_name_quoted(name, stdout, state->line_termination);4102}4103}41044105static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4106{4107if(mode)4108printf("%smode%06o%s\n", newdelete, mode, name);4109else4110printf("%s %s\n", newdelete, name);4111}41124113static voidshow_mode_change(struct patch *p,int show_name)4114{4115if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4116if(show_name)4117printf(" mode change%06o =>%06o%s\n",4118 p->old_mode, p->new_mode, p->new_name);4119else4120printf(" mode change%06o =>%06o\n",4121 p->old_mode, p->new_mode);4122}4123}41244125static voidshow_rename_copy(struct patch *p)4126{4127const char*renamecopy = p->is_rename ?"rename":"copy";4128const char*old, *new;41294130/* Find common prefix */4131 old = p->old_name;4132new= p->new_name;4133while(1) {4134const char*slash_old, *slash_new;4135 slash_old =strchr(old,'/');4136 slash_new =strchr(new,'/');4137if(!slash_old ||4138!slash_new ||4139 slash_old - old != slash_new -new||4140memcmp(old,new, slash_new -new))4141break;4142 old = slash_old +1;4143new= slash_new +1;4144}4145/* p->old_name thru old is the common prefix, and old and new4146 * through the end of names are renames4147 */4148if(old != p->old_name)4149printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4150(int)(old - p->old_name), p->old_name,4151 old,new, p->score);4152else4153printf("%s %s=>%s(%d%%)\n", renamecopy,4154 p->old_name, p->new_name, p->score);4155show_mode_change(p,0);4156}41574158static voidsummary_patch_list(struct patch *patch)4159{4160struct patch *p;41614162for(p = patch; p; p = p->next) {4163if(p->is_new)4164show_file_mode_name("create", p->new_mode, p->new_name);4165else if(p->is_delete)4166show_file_mode_name("delete", p->old_mode, p->old_name);4167else{4168if(p->is_rename || p->is_copy)4169show_rename_copy(p);4170else{4171if(p->score) {4172printf(" rewrite%s(%d%%)\n",4173 p->new_name, p->score);4174show_mode_change(p,0);4175}4176else4177show_mode_change(p,1);4178}4179}4180}4181}41824183static voidpatch_stats(struct apply_state *state,struct patch *patch)4184{4185int lines = patch->lines_added + patch->lines_deleted;41864187if(lines > state->max_change)4188 state->max_change = lines;4189if(patch->old_name) {4190int len =quote_c_style(patch->old_name, NULL, NULL,0);4191if(!len)4192 len =strlen(patch->old_name);4193if(len > state->max_len)4194 state->max_len = len;4195}4196if(patch->new_name) {4197int len =quote_c_style(patch->new_name, NULL, NULL,0);4198if(!len)4199 len =strlen(patch->new_name);4200if(len > state->max_len)4201 state->max_len = len;4202}4203}42044205static intremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4206{4207if(state->update_index) {4208if(remove_file_from_cache(patch->old_name) <0)4209returnerror(_("unable to remove%sfrom index"), patch->old_name);4210}4211if(!state->cached) {4212if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4213remove_path(patch->old_name);4214}4215}4216return0;4217}42184219static intadd_index_file(struct apply_state *state,4220const char*path,4221unsigned mode,4222void*buf,4223unsigned long size)4224{4225struct stat st;4226struct cache_entry *ce;4227int namelen =strlen(path);4228unsigned ce_size =cache_entry_size(namelen);42294230if(!state->update_index)4231return0;42324233 ce =xcalloc(1, ce_size);4234memcpy(ce->name, path, namelen);4235 ce->ce_mode =create_ce_mode(mode);4236 ce->ce_flags =create_ce_flags(0);4237 ce->ce_namelen = namelen;4238if(S_ISGITLINK(mode)) {4239const char*s;42404241if(!skip_prefix(buf,"Subproject commit ", &s) ||4242get_sha1_hex(s, ce->sha1)) {4243free(ce);4244returnerror(_("corrupt patch for submodule%s"), path);4245}4246}else{4247if(!state->cached) {4248if(lstat(path, &st) <0) {4249free(ce);4250returnerror(_("unable to stat newly "4251"created file '%s':%s"),4252 path,strerror(errno));4253}4254fill_stat_cache_info(ce, &st);4255}4256if(write_sha1_file(buf, size, blob_type, ce->sha1) <0) {4257free(ce);4258returnerror(_("unable to create backing store "4259"for newly created file%s"), path);4260}4261}4262if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0) {4263free(ce);4264returnerror(_("unable to add cache entry for%s"), path);4265}42664267return0;4268}42694270/*4271 * Returns:4272 * -1 if an unrecoverable error happened4273 * 0 if everything went well4274 * 1 if a recoverable error happened4275 */4276static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4277{4278int fd, res;4279struct strbuf nbuf = STRBUF_INIT;42804281if(S_ISGITLINK(mode)) {4282struct stat st;4283if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4284return0;4285return!!mkdir(path,0777);4286}42874288if(has_symlinks &&S_ISLNK(mode))4289/* Although buf:size is counted string, it also is NUL4290 * terminated.4291 */4292return!!symlink(buf, path);42934294 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4295if(fd <0)4296return1;42974298if(convert_to_working_tree(path, buf, size, &nbuf)) {4299 size = nbuf.len;4300 buf = nbuf.buf;4301}43024303 res =write_in_full(fd, buf, size) <0;4304if(res)4305error_errno(_("failed to write to '%s'"), path);4306strbuf_release(&nbuf);43074308if(close(fd) <0&& !res)4309returnerror_errno(_("closing file '%s'"), path);43104311return res ? -1:0;4312}43134314/*4315 * We optimistically assume that the directories exist,4316 * which is true 99% of the time anyway. If they don't,4317 * we create them and try again.4318 *4319 * Returns:4320 * -1 on error4321 * 0 otherwise4322 */4323static intcreate_one_file(struct apply_state *state,4324char*path,4325unsigned mode,4326const char*buf,4327unsigned long size)4328{4329int res;43304331if(state->cached)4332return0;43334334 res =try_create_file(path, mode, buf, size);4335if(res <0)4336return-1;4337if(!res)4338return0;43394340if(errno == ENOENT) {4341if(safe_create_leading_directories(path))4342return0;4343 res =try_create_file(path, mode, buf, size);4344if(res <0)4345return-1;4346if(!res)4347return0;4348}43494350if(errno == EEXIST || errno == EACCES) {4351/* We may be trying to create a file where a directory4352 * used to be.4353 */4354struct stat st;4355if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4356 errno = EEXIST;4357}43584359if(errno == EEXIST) {4360unsigned int nr =getpid();43614362for(;;) {4363char newpath[PATH_MAX];4364mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4365 res =try_create_file(newpath, mode, buf, size);4366if(res <0)4367return-1;4368if(!res) {4369if(!rename(newpath, path))4370return0;4371unlink_or_warn(newpath);4372break;4373}4374if(errno != EEXIST)4375break;4376++nr;4377}4378}4379returnerror_errno(_("unable to write file '%s' mode%o"),4380 path, mode);4381}43824383static intadd_conflicted_stages_file(struct apply_state *state,4384struct patch *patch)4385{4386int stage, namelen;4387unsigned ce_size, mode;4388struct cache_entry *ce;43894390if(!state->update_index)4391return0;4392 namelen =strlen(patch->new_name);4393 ce_size =cache_entry_size(namelen);4394 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);43954396remove_file_from_cache(patch->new_name);4397for(stage =1; stage <4; stage++) {4398if(is_null_oid(&patch->threeway_stage[stage -1]))4399continue;4400 ce =xcalloc(1, ce_size);4401memcpy(ce->name, patch->new_name, namelen);4402 ce->ce_mode =create_ce_mode(mode);4403 ce->ce_flags =create_ce_flags(stage);4404 ce->ce_namelen = namelen;4405hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4406if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0) {4407free(ce);4408returnerror(_("unable to add cache entry for%s"),4409 patch->new_name);4410}4411}44124413return0;4414}44154416static intcreate_file(struct apply_state *state,struct patch *patch)4417{4418char*path = patch->new_name;4419unsigned mode = patch->new_mode;4420unsigned long size = patch->resultsize;4421char*buf = patch->result;44224423if(!mode)4424 mode = S_IFREG |0644;4425if(create_one_file(state, path, mode, buf, size))4426return-1;44274428if(patch->conflicted_threeway)4429returnadd_conflicted_stages_file(state, patch);4430else4431returnadd_index_file(state, path, mode, buf, size);4432}44334434/* phase zero is to remove, phase one is to create */4435static intwrite_out_one_result(struct apply_state *state,4436struct patch *patch,4437int phase)4438{4439if(patch->is_delete >0) {4440if(phase ==0)4441returnremove_file(state, patch,1);4442return0;4443}4444if(patch->is_new >0|| patch->is_copy) {4445if(phase ==1)4446returncreate_file(state, patch);4447return0;4448}4449/*4450 * Rename or modification boils down to the same4451 * thing: remove the old, write the new4452 */4453if(phase ==0)4454returnremove_file(state, patch, patch->is_rename);4455if(phase ==1)4456returncreate_file(state, patch);4457return0;4458}44594460static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4461{4462FILE*rej;4463char namebuf[PATH_MAX];4464struct fragment *frag;4465int cnt =0;4466struct strbuf sb = STRBUF_INIT;44674468for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4469if(!frag->rejected)4470continue;4471 cnt++;4472}44734474if(!cnt) {4475if(state->apply_verbosely)4476say_patch_name(stderr,4477_("Applied patch%scleanly."), patch);4478return0;4479}44804481/* This should not happen, because a removal patch that leaves4482 * contents are marked "rejected" at the patch level.4483 */4484if(!patch->new_name)4485die(_("internal error"));44864487/* Say this even without --verbose */4488strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4489"Applying patch %%swith%drejects...",4490 cnt),4491 cnt);4492say_patch_name(stderr, sb.buf, patch);4493strbuf_release(&sb);44944495 cnt =strlen(patch->new_name);4496if(ARRAY_SIZE(namebuf) <= cnt +5) {4497 cnt =ARRAY_SIZE(namebuf) -5;4498warning(_("truncating .rej filename to %.*s.rej"),4499 cnt -1, patch->new_name);4500}4501memcpy(namebuf, patch->new_name, cnt);4502memcpy(namebuf + cnt,".rej",5);45034504 rej =fopen(namebuf,"w");4505if(!rej)4506returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));45074508/* Normal git tools never deal with .rej, so do not pretend4509 * this is a git patch by saying --git or giving extended4510 * headers. While at it, maybe please "kompare" that wants4511 * the trailing TAB and some garbage at the end of line ;-).4512 */4513fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4514 patch->new_name, patch->new_name);4515for(cnt =1, frag = patch->fragments;4516 frag;4517 cnt++, frag = frag->next) {4518if(!frag->rejected) {4519fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4520continue;4521}4522fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4523fprintf(rej,"%.*s", frag->size, frag->patch);4524if(frag->patch[frag->size-1] !='\n')4525fputc('\n', rej);4526}4527fclose(rej);4528return-1;4529}45304531/*4532 * Returns:4533 * -1 if an error happened4534 * 0 if the patch applied cleanly4535 * 1 if the patch did not apply cleanly4536 */4537static intwrite_out_results(struct apply_state *state,struct patch *list)4538{4539int phase;4540int errs =0;4541struct patch *l;4542struct string_list cpath = STRING_LIST_INIT_DUP;45434544for(phase =0; phase <2; phase++) {4545 l = list;4546while(l) {4547if(l->rejected)4548 errs =1;4549else{4550if(write_out_one_result(state, l, phase)) {4551string_list_clear(&cpath,0);4552return-1;4553}4554if(phase ==1) {4555if(write_out_one_reject(state, l))4556 errs =1;4557if(l->conflicted_threeway) {4558string_list_append(&cpath, l->new_name);4559 errs =1;4560}4561}4562}4563 l = l->next;4564}4565}45664567if(cpath.nr) {4568struct string_list_item *item;45694570string_list_sort(&cpath);4571for_each_string_list_item(item, &cpath)4572fprintf(stderr,"U%s\n", item->string);4573string_list_clear(&cpath,0);45744575rerere(0);4576}45774578return errs;4579}45804581/*4582 * Try to apply a patch.4583 *4584 * Returns:4585 * -128 if a bad error happened (like patch unreadable)4586 * -1 if patch did not apply and user cannot deal with it4587 * 0 if the patch applied4588 * 1 if the patch did not apply but user might fix it4589 */4590static intapply_patch(struct apply_state *state,4591int fd,4592const char*filename,4593int options)4594{4595size_t offset;4596struct strbuf buf = STRBUF_INIT;/* owns the patch text */4597struct patch *list = NULL, **listp = &list;4598int skipped_patch =0;4599int res =0;46004601 state->patch_input_file = filename;4602if(read_patch_file(&buf, fd) <0)4603return-128;4604 offset =0;4605while(offset < buf.len) {4606struct patch *patch;4607int nr;46084609 patch =xcalloc(1,sizeof(*patch));4610 patch->inaccurate_eof = !!(options & APPLY_OPT_INACCURATE_EOF);4611 patch->recount = !!(options & APPLY_OPT_RECOUNT);4612 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4613if(nr <0) {4614free_patch(patch);4615if(nr == -128) {4616 res = -128;4617goto end;4618}4619break;4620}4621if(state->apply_in_reverse)4622reverse_patches(patch);4623if(use_patch(state, patch)) {4624patch_stats(state, patch);4625*listp = patch;4626 listp = &patch->next;4627}4628else{4629if(state->apply_verbosely)4630say_patch_name(stderr,_("Skipped patch '%s'."), patch);4631free_patch(patch);4632 skipped_patch++;4633}4634 offset += nr;4635}46364637if(!list && !skipped_patch) {4638error(_("unrecognized input"));4639 res = -128;4640goto end;4641}46424643if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4644 state->apply =0;46454646 state->update_index = state->check_index && state->apply;4647if(state->update_index && state->newfd <0)4648 state->newfd =hold_locked_index(state->lock_file,1);46494650if(state->check_index &&read_cache() <0) {4651error(_("unable to read index file"));4652 res = -128;4653goto end;4654}46554656if(state->check || state->apply) {4657int r =check_patch_list(state, list);4658if(r == -128) {4659 res = -128;4660goto end;4661}4662if(r <0&& !state->apply_with_reject) {4663 res = -1;4664goto end;4665}4666}46674668if(state->apply) {4669int write_res =write_out_results(state, list);4670if(write_res <0) {4671 res = -128;4672goto end;4673}4674if(write_res >0) {4675/* with --3way, we still need to write the index out */4676 res = state->apply_with_reject ? -1:1;4677goto end;4678}4679}46804681if(state->fake_ancestor &&4682build_fake_ancestor(list, state->fake_ancestor)) {4683 res = -128;4684goto end;4685}46864687if(state->diffstat)4688stat_patch_list(state, list);46894690if(state->numstat)4691numstat_patch_list(state, list);46924693if(state->summary)4694summary_patch_list(list);46954696end:4697free_patch_list(list);4698strbuf_release(&buf);4699string_list_clear(&state->fn_table,0);4700return res;4701}47024703intapply_option_parse_exclude(const struct option *opt,4704const char*arg,int unset)4705{4706struct apply_state *state = opt->value;4707add_name_limit(state, arg,1);4708return0;4709}47104711intapply_option_parse_include(const struct option *opt,4712const char*arg,int unset)4713{4714struct apply_state *state = opt->value;4715add_name_limit(state, arg,0);4716 state->has_include =1;4717return0;4718}47194720intapply_option_parse_p(const struct option *opt,4721const char*arg,4722int unset)4723{4724struct apply_state *state = opt->value;4725 state->p_value =atoi(arg);4726 state->p_value_known =1;4727return0;4728}47294730intapply_option_parse_space_change(const struct option *opt,4731const char*arg,int unset)4732{4733struct apply_state *state = opt->value;4734if(unset)4735 state->ws_ignore_action = ignore_ws_none;4736else4737 state->ws_ignore_action = ignore_ws_change;4738return0;4739}47404741intapply_option_parse_whitespace(const struct option *opt,4742const char*arg,int unset)4743{4744struct apply_state *state = opt->value;4745 state->whitespace_option = arg;4746if(parse_whitespace_option(state, arg))4747exit(1);4748return0;4749}47504751intapply_option_parse_directory(const struct option *opt,4752const char*arg,int unset)4753{4754struct apply_state *state = opt->value;4755strbuf_reset(&state->root);4756strbuf_addstr(&state->root, arg);4757strbuf_complete(&state->root,'/');4758return0;4759}47604761intapply_all_patches(struct apply_state *state,4762int argc,4763const char**argv,4764int options)4765{4766int i;4767int res;4768int errs =0;4769int read_stdin =1;47704771for(i =0; i < argc; i++) {4772const char*arg = argv[i];4773int fd;47744775if(!strcmp(arg,"-")) {4776 res =apply_patch(state,0,"<stdin>", options);4777if(res <0)4778goto end;4779 errs |= res;4780 read_stdin =0;4781continue;4782}else if(0< state->prefix_length)4783 arg =prefix_filename(state->prefix,4784 state->prefix_length,4785 arg);47864787 fd =open(arg, O_RDONLY);4788if(fd <0) {4789error(_("can't open patch '%s':%s"), arg,strerror(errno));4790 res = -128;4791goto end;4792}4793 read_stdin =0;4794set_default_whitespace_mode(state);4795 res =apply_patch(state, fd, arg, options);4796close(fd);4797if(res <0)4798goto end;4799 errs |= res;4800}4801set_default_whitespace_mode(state);4802if(read_stdin) {4803 res =apply_patch(state,0,"<stdin>", options);4804if(res <0)4805goto end;4806 errs |= res;4807}48084809if(state->whitespace_error) {4810if(state->squelch_whitespace_errors &&4811 state->squelch_whitespace_errors < state->whitespace_error) {4812int squelched =4813 state->whitespace_error - state->squelch_whitespace_errors;4814warning(Q_("squelched%dwhitespace error",4815"squelched%dwhitespace errors",4816 squelched),4817 squelched);4818}4819if(state->ws_error_action == die_on_ws_error) {4820error(Q_("%dline adds whitespace errors.",4821"%dlines add whitespace errors.",4822 state->whitespace_error),4823 state->whitespace_error);4824 res = -128;4825goto end;4826}4827if(state->applied_after_fixing_ws && state->apply)4828warning("%dline%sapplied after"4829" fixing whitespace errors.",4830 state->applied_after_fixing_ws,4831 state->applied_after_fixing_ws ==1?"":"s");4832else if(state->whitespace_error)4833warning(Q_("%dline adds whitespace errors.",4834"%dlines add whitespace errors.",4835 state->whitespace_error),4836 state->whitespace_error);4837}48384839if(state->update_index) {4840 res =write_locked_index(&the_index, state->lock_file, COMMIT_LOCK);4841if(res) {4842error(_("Unable to write new index file"));4843 res = -128;4844goto end;4845}4846 state->newfd = -1;4847}48484849return!!errs;48504851end:4852if(state->newfd >=0) {4853rollback_lock_file(state->lock_file);4854 state->newfd = -1;4855}48564857return(res == -1?1:128);4858}