1/* 2 * apply.c 3 * 4 * Copyright (C) Linus Torvalds, 2005 5 * 6 * This applies patches on top of some (arbitrary) version of the SCM. 7 * 8 */ 9 10#include"cache.h" 11#include"config.h" 12#include"object-store.h" 13#include"blob.h" 14#include"delta.h" 15#include"diff.h" 16#include"dir.h" 17#include"xdiff-interface.h" 18#include"ll-merge.h" 19#include"lockfile.h" 20#include"parse-options.h" 21#include"quote.h" 22#include"rerere.h" 23#include"apply.h" 24 25static voidgit_apply_config(void) 26{ 27git_config_get_string_const("apply.whitespace", &apply_default_whitespace); 28git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace); 29git_config(git_default_config, NULL); 30} 31 32static intparse_whitespace_option(struct apply_state *state,const char*option) 33{ 34if(!option) { 35 state->ws_error_action = warn_on_ws_error; 36return0; 37} 38if(!strcmp(option,"warn")) { 39 state->ws_error_action = warn_on_ws_error; 40return0; 41} 42if(!strcmp(option,"nowarn")) { 43 state->ws_error_action = nowarn_ws_error; 44return0; 45} 46if(!strcmp(option,"error")) { 47 state->ws_error_action = die_on_ws_error; 48return0; 49} 50if(!strcmp(option,"error-all")) { 51 state->ws_error_action = die_on_ws_error; 52 state->squelch_whitespace_errors =0; 53return0; 54} 55if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 56 state->ws_error_action = correct_ws_error; 57return0; 58} 59returnerror(_("unrecognized whitespace option '%s'"), option); 60} 61 62static intparse_ignorewhitespace_option(struct apply_state *state, 63const char*option) 64{ 65if(!option || !strcmp(option,"no") || 66!strcmp(option,"false") || !strcmp(option,"never") || 67!strcmp(option,"none")) { 68 state->ws_ignore_action = ignore_ws_none; 69return0; 70} 71if(!strcmp(option,"change")) { 72 state->ws_ignore_action = ignore_ws_change; 73return0; 74} 75returnerror(_("unrecognized whitespace ignore option '%s'"), option); 76} 77 78intinit_apply_state(struct apply_state *state, 79struct repository *repo, 80const char*prefix) 81{ 82memset(state,0,sizeof(*state)); 83 state->prefix = prefix; 84 state->repo = repo; 85 state->apply =1; 86 state->line_termination ='\n'; 87 state->p_value =1; 88 state->p_context = UINT_MAX; 89 state->squelch_whitespace_errors =5; 90 state->ws_error_action = warn_on_ws_error; 91 state->ws_ignore_action = ignore_ws_none; 92 state->linenr =1; 93string_list_init(&state->fn_table,0); 94string_list_init(&state->limit_by_name,0); 95string_list_init(&state->symlink_changes,0); 96strbuf_init(&state->root,0); 97 98git_apply_config(); 99if(apply_default_whitespace &&parse_whitespace_option(state, apply_default_whitespace)) 100return-1; 101if(apply_default_ignorewhitespace &&parse_ignorewhitespace_option(state, apply_default_ignorewhitespace)) 102return-1; 103return0; 104} 105 106voidclear_apply_state(struct apply_state *state) 107{ 108string_list_clear(&state->limit_by_name,0); 109string_list_clear(&state->symlink_changes,0); 110strbuf_release(&state->root); 111 112/* &state->fn_table is cleared at the end of apply_patch() */ 113} 114 115static voidmute_routine(const char*msg,va_list params) 116{ 117/* do nothing */ 118} 119 120intcheck_apply_state(struct apply_state *state,int force_apply) 121{ 122int is_not_gitdir = !startup_info->have_repository; 123 124if(state->apply_with_reject && state->threeway) 125returnerror(_("--reject and --3way cannot be used together.")); 126if(state->cached && state->threeway) 127returnerror(_("--cached and --3way cannot be used together.")); 128if(state->threeway) { 129if(is_not_gitdir) 130returnerror(_("--3way outside a repository")); 131 state->check_index =1; 132} 133if(state->apply_with_reject) { 134 state->apply =1; 135if(state->apply_verbosity == verbosity_normal) 136 state->apply_verbosity = verbosity_verbose; 137} 138if(!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor)) 139 state->apply =0; 140if(state->check_index && is_not_gitdir) 141returnerror(_("--index outside a repository")); 142if(state->cached) { 143if(is_not_gitdir) 144returnerror(_("--cached outside a repository")); 145 state->check_index =1; 146} 147if(state->ita_only && (state->check_index || is_not_gitdir)) 148 state->ita_only =0; 149if(state->check_index) 150 state->unsafe_paths =0; 151 152if(state->apply_verbosity <= verbosity_silent) { 153 state->saved_error_routine =get_error_routine(); 154 state->saved_warn_routine =get_warn_routine(); 155set_error_routine(mute_routine); 156set_warn_routine(mute_routine); 157} 158 159return0; 160} 161 162static voidset_default_whitespace_mode(struct apply_state *state) 163{ 164if(!state->whitespace_option && !apply_default_whitespace) 165 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 166} 167 168/* 169 * This represents one "hunk" from a patch, starting with 170 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 171 * patch text is pointed at by patch, and its byte length 172 * is stored in size. leading and trailing are the number 173 * of context lines. 174 */ 175struct fragment { 176unsigned long leading, trailing; 177unsigned long oldpos, oldlines; 178unsigned long newpos, newlines; 179/* 180 * 'patch' is usually borrowed from buf in apply_patch(), 181 * but some codepaths store an allocated buffer. 182 */ 183const char*patch; 184unsigned free_patch:1, 185 rejected:1; 186int size; 187int linenr; 188struct fragment *next; 189}; 190 191/* 192 * When dealing with a binary patch, we reuse "leading" field 193 * to store the type of the binary hunk, either deflated "delta" 194 * or deflated "literal". 195 */ 196#define binary_patch_method leading 197#define BINARY_DELTA_DEFLATED 1 198#define BINARY_LITERAL_DEFLATED 2 199 200/* 201 * This represents a "patch" to a file, both metainfo changes 202 * such as creation/deletion, filemode and content changes represented 203 * as a series of fragments. 204 */ 205struct patch { 206char*new_name, *old_name, *def_name; 207unsigned int old_mode, new_mode; 208int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 209int rejected; 210unsigned ws_rule; 211int lines_added, lines_deleted; 212int score; 213int extension_linenr;/* first line specifying delete/new/rename/copy */ 214unsigned int is_toplevel_relative:1; 215unsigned int inaccurate_eof:1; 216unsigned int is_binary:1; 217unsigned int is_copy:1; 218unsigned int is_rename:1; 219unsigned int recount:1; 220unsigned int conflicted_threeway:1; 221unsigned int direct_to_threeway:1; 222unsigned int crlf_in_old:1; 223struct fragment *fragments; 224char*result; 225size_t resultsize; 226char old_sha1_prefix[GIT_MAX_HEXSZ +1]; 227char new_sha1_prefix[GIT_MAX_HEXSZ +1]; 228struct patch *next; 229 230/* three-way fallback result */ 231struct object_id threeway_stage[3]; 232}; 233 234static voidfree_fragment_list(struct fragment *list) 235{ 236while(list) { 237struct fragment *next = list->next; 238if(list->free_patch) 239free((char*)list->patch); 240free(list); 241 list = next; 242} 243} 244 245static voidfree_patch(struct patch *patch) 246{ 247free_fragment_list(patch->fragments); 248free(patch->def_name); 249free(patch->old_name); 250free(patch->new_name); 251free(patch->result); 252free(patch); 253} 254 255static voidfree_patch_list(struct patch *list) 256{ 257while(list) { 258struct patch *next = list->next; 259free_patch(list); 260 list = next; 261} 262} 263 264/* 265 * A line in a file, len-bytes long (includes the terminating LF, 266 * except for an incomplete line at the end if the file ends with 267 * one), and its contents hashes to 'hash'. 268 */ 269struct line { 270size_t len; 271unsigned hash :24; 272unsigned flag :8; 273#define LINE_COMMON 1 274#define LINE_PATCHED 2 275}; 276 277/* 278 * This represents a "file", which is an array of "lines". 279 */ 280struct image { 281char*buf; 282size_t len; 283size_t nr; 284size_t alloc; 285struct line *line_allocated; 286struct line *line; 287}; 288 289static uint32_thash_line(const char*cp,size_t len) 290{ 291size_t i; 292uint32_t h; 293for(i =0, h =0; i < len; i++) { 294if(!isspace(cp[i])) { 295 h = h *3+ (cp[i] &0xff); 296} 297} 298return h; 299} 300 301/* 302 * Compare lines s1 of length n1 and s2 of length n2, ignoring 303 * whitespace difference. Returns 1 if they match, 0 otherwise 304 */ 305static intfuzzy_matchlines(const char*s1,size_t n1, 306const char*s2,size_t n2) 307{ 308const char*end1 = s1 + n1; 309const char*end2 = s2 + n2; 310 311/* ignore line endings */ 312while(s1 < end1 && (end1[-1] =='\r'|| end1[-1] =='\n')) 313 end1--; 314while(s2 < end2 && (end2[-1] =='\r'|| end2[-1] =='\n')) 315 end2--; 316 317while(s1 < end1 && s2 < end2) { 318if(isspace(*s1)) { 319/* 320 * Skip whitespace. We check on both buffers 321 * because we don't want "a b" to match "ab". 322 */ 323if(!isspace(*s2)) 324return0; 325while(s1 < end1 &&isspace(*s1)) 326 s1++; 327while(s2 < end2 &&isspace(*s2)) 328 s2++; 329}else if(*s1++ != *s2++) 330return0; 331} 332 333/* If we reached the end on one side only, lines don't match. */ 334return s1 == end1 && s2 == end2; 335} 336 337static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 338{ 339ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 340 img->line_allocated[img->nr].len = len; 341 img->line_allocated[img->nr].hash =hash_line(bol, len); 342 img->line_allocated[img->nr].flag = flag; 343 img->nr++; 344} 345 346/* 347 * "buf" has the file contents to be patched (read from various sources). 348 * attach it to "image" and add line-based index to it. 349 * "image" now owns the "buf". 350 */ 351static voidprepare_image(struct image *image,char*buf,size_t len, 352int prepare_linetable) 353{ 354const char*cp, *ep; 355 356memset(image,0,sizeof(*image)); 357 image->buf = buf; 358 image->len = len; 359 360if(!prepare_linetable) 361return; 362 363 ep = image->buf + image->len; 364 cp = image->buf; 365while(cp < ep) { 366const char*next; 367for(next = cp; next < ep && *next !='\n'; next++) 368; 369if(next < ep) 370 next++; 371add_line_info(image, cp, next - cp,0); 372 cp = next; 373} 374 image->line = image->line_allocated; 375} 376 377static voidclear_image(struct image *image) 378{ 379free(image->buf); 380free(image->line_allocated); 381memset(image,0,sizeof(*image)); 382} 383 384/* fmt must contain _one_ %s and no other substitution */ 385static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 386{ 387struct strbuf sb = STRBUF_INIT; 388 389if(patch->old_name && patch->new_name && 390strcmp(patch->old_name, patch->new_name)) { 391quote_c_style(patch->old_name, &sb, NULL,0); 392strbuf_addstr(&sb," => "); 393quote_c_style(patch->new_name, &sb, NULL,0); 394}else{ 395const char*n = patch->new_name; 396if(!n) 397 n = patch->old_name; 398quote_c_style(n, &sb, NULL,0); 399} 400fprintf(output, fmt, sb.buf); 401fputc('\n', output); 402strbuf_release(&sb); 403} 404 405#define SLOP (16) 406 407static intread_patch_file(struct strbuf *sb,int fd) 408{ 409if(strbuf_read(sb, fd,0) <0) 410returnerror_errno("git apply: failed to read"); 411 412/* 413 * Make sure that we have some slop in the buffer 414 * so that we can do speculative "memcmp" etc, and 415 * see to it that it is NUL-filled. 416 */ 417strbuf_grow(sb, SLOP); 418memset(sb->buf + sb->len,0, SLOP); 419return0; 420} 421 422static unsigned longlinelen(const char*buffer,unsigned long size) 423{ 424unsigned long len =0; 425while(size--) { 426 len++; 427if(*buffer++ =='\n') 428break; 429} 430return len; 431} 432 433static intis_dev_null(const char*str) 434{ 435returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 436} 437 438#define TERM_SPACE 1 439#define TERM_TAB 2 440 441static intname_terminate(int c,int terminate) 442{ 443if(c ==' '&& !(terminate & TERM_SPACE)) 444return0; 445if(c =='\t'&& !(terminate & TERM_TAB)) 446return0; 447 448return1; 449} 450 451/* remove double slashes to make --index work with such filenames */ 452static char*squash_slash(char*name) 453{ 454int i =0, j =0; 455 456if(!name) 457return NULL; 458 459while(name[i]) { 460if((name[j++] = name[i++]) =='/') 461while(name[i] =='/') 462 i++; 463} 464 name[j] ='\0'; 465return name; 466} 467 468static char*find_name_gnu(struct apply_state *state, 469const char*line, 470const char*def, 471int p_value) 472{ 473struct strbuf name = STRBUF_INIT; 474char*cp; 475 476/* 477 * Proposed "new-style" GNU patch/diff format; see 478 * http://marc.info/?l=git&m=112927316408690&w=2 479 */ 480if(unquote_c_style(&name, line, NULL)) { 481strbuf_release(&name); 482return NULL; 483} 484 485for(cp = name.buf; p_value; p_value--) { 486 cp =strchr(cp,'/'); 487if(!cp) { 488strbuf_release(&name); 489return NULL; 490} 491 cp++; 492} 493 494strbuf_remove(&name,0, cp - name.buf); 495if(state->root.len) 496strbuf_insert(&name,0, state->root.buf, state->root.len); 497returnsquash_slash(strbuf_detach(&name, NULL)); 498} 499 500static size_tsane_tz_len(const char*line,size_t len) 501{ 502const char*tz, *p; 503 504if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 505return0; 506 tz = line + len -strlen(" +0500"); 507 508if(tz[1] !='+'&& tz[1] !='-') 509return0; 510 511for(p = tz +2; p != line + len; p++) 512if(!isdigit(*p)) 513return0; 514 515return line + len - tz; 516} 517 518static size_ttz_with_colon_len(const char*line,size_t len) 519{ 520const char*tz, *p; 521 522if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 523return0; 524 tz = line + len -strlen(" +08:00"); 525 526if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 527return0; 528 p = tz +2; 529if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 530!isdigit(*p++) || !isdigit(*p++)) 531return0; 532 533return line + len - tz; 534} 535 536static size_tdate_len(const char*line,size_t len) 537{ 538const char*date, *p; 539 540if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 541return0; 542 p = date = line + len -strlen("72-02-05"); 543 544if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 545!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 546!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 547return0; 548 549if(date - line >=strlen("19") && 550isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 551 date -=strlen("19"); 552 553return line + len - date; 554} 555 556static size_tshort_time_len(const char*line,size_t len) 557{ 558const char*time, *p; 559 560if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 561return0; 562 p = time = line + len -strlen(" 07:01:32"); 563 564/* Permit 1-digit hours? */ 565if(*p++ !=' '|| 566!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 567!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 568!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 569return0; 570 571return line + len - time; 572} 573 574static size_tfractional_time_len(const char*line,size_t len) 575{ 576const char*p; 577size_t n; 578 579/* Expected format: 19:41:17.620000023 */ 580if(!len || !isdigit(line[len -1])) 581return0; 582 p = line + len -1; 583 584/* Fractional seconds. */ 585while(p > line &&isdigit(*p)) 586 p--; 587if(*p !='.') 588return0; 589 590/* Hours, minutes, and whole seconds. */ 591 n =short_time_len(line, p - line); 592if(!n) 593return0; 594 595return line + len - p + n; 596} 597 598static size_ttrailing_spaces_len(const char*line,size_t len) 599{ 600const char*p; 601 602/* Expected format: ' ' x (1 or more) */ 603if(!len || line[len -1] !=' ') 604return0; 605 606 p = line + len; 607while(p != line) { 608 p--; 609if(*p !=' ') 610return line + len - (p +1); 611} 612 613/* All spaces! */ 614return len; 615} 616 617static size_tdiff_timestamp_len(const char*line,size_t len) 618{ 619const char*end = line + len; 620size_t n; 621 622/* 623 * Posix: 2010-07-05 19:41:17 624 * GNU: 2010-07-05 19:41:17.620000023 -0500 625 */ 626 627if(!isdigit(end[-1])) 628return0; 629 630 n =sane_tz_len(line, end - line); 631if(!n) 632 n =tz_with_colon_len(line, end - line); 633 end -= n; 634 635 n =short_time_len(line, end - line); 636if(!n) 637 n =fractional_time_len(line, end - line); 638 end -= n; 639 640 n =date_len(line, end - line); 641if(!n)/* No date. Too bad. */ 642return0; 643 end -= n; 644 645if(end == line)/* No space before date. */ 646return0; 647if(end[-1] =='\t') {/* Success! */ 648 end--; 649return line + len - end; 650} 651if(end[-1] !=' ')/* No space before date. */ 652return0; 653 654/* Whitespace damage. */ 655 end -=trailing_spaces_len(line, end - line); 656return line + len - end; 657} 658 659static char*find_name_common(struct apply_state *state, 660const char*line, 661const char*def, 662int p_value, 663const char*end, 664int terminate) 665{ 666int len; 667const char*start = NULL; 668 669if(p_value ==0) 670 start = line; 671while(line != end) { 672char c = *line; 673 674if(!end &&isspace(c)) { 675if(c =='\n') 676break; 677if(name_terminate(c, terminate)) 678break; 679} 680 line++; 681if(c =='/'&& !--p_value) 682 start = line; 683} 684if(!start) 685returnsquash_slash(xstrdup_or_null(def)); 686 len = line - start; 687if(!len) 688returnsquash_slash(xstrdup_or_null(def)); 689 690/* 691 * Generally we prefer the shorter name, especially 692 * if the other one is just a variation of that with 693 * something else tacked on to the end (ie "file.orig" 694 * or "file~"). 695 */ 696if(def) { 697int deflen =strlen(def); 698if(deflen < len && !strncmp(start, def, deflen)) 699returnsquash_slash(xstrdup(def)); 700} 701 702if(state->root.len) { 703char*ret =xstrfmt("%s%.*s", state->root.buf, len, start); 704returnsquash_slash(ret); 705} 706 707returnsquash_slash(xmemdupz(start, len)); 708} 709 710static char*find_name(struct apply_state *state, 711const char*line, 712char*def, 713int p_value, 714int terminate) 715{ 716if(*line =='"') { 717char*name =find_name_gnu(state, line, def, p_value); 718if(name) 719return name; 720} 721 722returnfind_name_common(state, line, def, p_value, NULL, terminate); 723} 724 725static char*find_name_traditional(struct apply_state *state, 726const char*line, 727char*def, 728int p_value) 729{ 730size_t len; 731size_t date_len; 732 733if(*line =='"') { 734char*name =find_name_gnu(state, line, def, p_value); 735if(name) 736return name; 737} 738 739 len =strchrnul(line,'\n') - line; 740 date_len =diff_timestamp_len(line, len); 741if(!date_len) 742returnfind_name_common(state, line, def, p_value, NULL, TERM_TAB); 743 len -= date_len; 744 745returnfind_name_common(state, line, def, p_value, line + len,0); 746} 747 748/* 749 * Given the string after "--- " or "+++ ", guess the appropriate 750 * p_value for the given patch. 751 */ 752static intguess_p_value(struct apply_state *state,const char*nameline) 753{ 754char*name, *cp; 755int val = -1; 756 757if(is_dev_null(nameline)) 758return-1; 759 name =find_name_traditional(state, nameline, NULL,0); 760if(!name) 761return-1; 762 cp =strchr(name,'/'); 763if(!cp) 764 val =0; 765else if(state->prefix) { 766/* 767 * Does it begin with "a/$our-prefix" and such? Then this is 768 * very likely to apply to our directory. 769 */ 770if(starts_with(name, state->prefix)) 771 val =count_slashes(state->prefix); 772else{ 773 cp++; 774if(starts_with(cp, state->prefix)) 775 val =count_slashes(state->prefix) +1; 776} 777} 778free(name); 779return val; 780} 781 782/* 783 * Does the ---/+++ line have the POSIX timestamp after the last HT? 784 * GNU diff puts epoch there to signal a creation/deletion event. Is 785 * this such a timestamp? 786 */ 787static inthas_epoch_timestamp(const char*nameline) 788{ 789/* 790 * We are only interested in epoch timestamp; any non-zero 791 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 792 * For the same reason, the date must be either 1969-12-31 or 793 * 1970-01-01, and the seconds part must be "00". 794 */ 795const char stamp_regexp[] = 796"^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?" 797" " 798"([-+][0-2][0-9]:?[0-5][0-9])\n"; 799const char*timestamp = NULL, *cp, *colon; 800static regex_t *stamp; 801 regmatch_t m[10]; 802int zoneoffset, epoch_hour, hour, minute; 803int status; 804 805for(cp = nameline; *cp !='\n'; cp++) { 806if(*cp =='\t') 807 timestamp = cp +1; 808} 809if(!timestamp) 810return0; 811 812/* 813 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 814 * (west of GMT) or 1970-01-01 (east of GMT) 815 */ 816if(skip_prefix(timestamp,"1969-12-31 ", ×tamp)) 817 epoch_hour =24; 818else if(skip_prefix(timestamp,"1970-01-01 ", ×tamp)) 819 epoch_hour =0; 820else 821return0; 822 823if(!stamp) { 824 stamp =xmalloc(sizeof(*stamp)); 825if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 826warning(_("Cannot prepare timestamp regexp%s"), 827 stamp_regexp); 828return0; 829} 830} 831 832 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 833if(status) { 834if(status != REG_NOMATCH) 835warning(_("regexec returned%dfor input:%s"), 836 status, timestamp); 837return0; 838} 839 840 hour =strtol(timestamp, NULL,10); 841 minute =strtol(timestamp + m[1].rm_so, NULL,10); 842 843 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 844if(*colon ==':') 845 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 846else 847 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 848if(timestamp[m[3].rm_so] =='-') 849 zoneoffset = -zoneoffset; 850 851return hour *60+ minute - zoneoffset == epoch_hour *60; 852} 853 854/* 855 * Get the name etc info from the ---/+++ lines of a traditional patch header 856 * 857 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 858 * files, we can happily check the index for a match, but for creating a 859 * new file we should try to match whatever "patch" does. I have no idea. 860 */ 861static intparse_traditional_patch(struct apply_state *state, 862const char*first, 863const char*second, 864struct patch *patch) 865{ 866char*name; 867 868 first +=4;/* skip "--- " */ 869 second +=4;/* skip "+++ " */ 870if(!state->p_value_known) { 871int p, q; 872 p =guess_p_value(state, first); 873 q =guess_p_value(state, second); 874if(p <0) p = q; 875if(0<= p && p == q) { 876 state->p_value = p; 877 state->p_value_known =1; 878} 879} 880if(is_dev_null(first)) { 881 patch->is_new =1; 882 patch->is_delete =0; 883 name =find_name_traditional(state, second, NULL, state->p_value); 884 patch->new_name = name; 885}else if(is_dev_null(second)) { 886 patch->is_new =0; 887 patch->is_delete =1; 888 name =find_name_traditional(state, first, NULL, state->p_value); 889 patch->old_name = name; 890}else{ 891char*first_name; 892 first_name =find_name_traditional(state, first, NULL, state->p_value); 893 name =find_name_traditional(state, second, first_name, state->p_value); 894free(first_name); 895if(has_epoch_timestamp(first)) { 896 patch->is_new =1; 897 patch->is_delete =0; 898 patch->new_name = name; 899}else if(has_epoch_timestamp(second)) { 900 patch->is_new =0; 901 patch->is_delete =1; 902 patch->old_name = name; 903}else{ 904 patch->old_name = name; 905 patch->new_name =xstrdup_or_null(name); 906} 907} 908if(!name) 909returnerror(_("unable to find filename in patch at line%d"), state->linenr); 910 911return0; 912} 913 914static intgitdiff_hdrend(struct apply_state *state, 915const char*line, 916struct patch *patch) 917{ 918return1; 919} 920 921/* 922 * We're anal about diff header consistency, to make 923 * sure that we don't end up having strange ambiguous 924 * patches floating around. 925 * 926 * As a result, gitdiff_{old|new}name() will check 927 * their names against any previous information, just 928 * to make sure.. 929 */ 930#define DIFF_OLD_NAME 0 931#define DIFF_NEW_NAME 1 932 933static intgitdiff_verify_name(struct apply_state *state, 934const char*line, 935int isnull, 936char**name, 937int side) 938{ 939if(!*name && !isnull) { 940*name =find_name(state, line, NULL, state->p_value, TERM_TAB); 941return0; 942} 943 944if(*name) { 945char*another; 946if(isnull) 947returnerror(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 948*name, state->linenr); 949 another =find_name(state, line, NULL, state->p_value, TERM_TAB); 950if(!another ||strcmp(another, *name)) { 951free(another); 952returnerror((side == DIFF_NEW_NAME) ? 953_("git apply: bad git-diff - inconsistent new filename on line%d") : 954_("git apply: bad git-diff - inconsistent old filename on line%d"), state->linenr); 955} 956free(another); 957}else{ 958if(!is_dev_null(line)) 959returnerror(_("git apply: bad git-diff - expected /dev/null on line%d"), state->linenr); 960} 961 962return0; 963} 964 965static intgitdiff_oldname(struct apply_state *state, 966const char*line, 967struct patch *patch) 968{ 969returngitdiff_verify_name(state, line, 970 patch->is_new, &patch->old_name, 971 DIFF_OLD_NAME); 972} 973 974static intgitdiff_newname(struct apply_state *state, 975const char*line, 976struct patch *patch) 977{ 978returngitdiff_verify_name(state, line, 979 patch->is_delete, &patch->new_name, 980 DIFF_NEW_NAME); 981} 982 983static intparse_mode_line(const char*line,int linenr,unsigned int*mode) 984{ 985char*end; 986*mode =strtoul(line, &end,8); 987if(end == line || !isspace(*end)) 988returnerror(_("invalid mode on line%d:%s"), linenr, line); 989return0; 990} 991 992static intgitdiff_oldmode(struct apply_state *state, 993const char*line, 994struct patch *patch) 995{ 996returnparse_mode_line(line, state->linenr, &patch->old_mode); 997} 998 999static intgitdiff_newmode(struct apply_state *state,1000const char*line,1001struct patch *patch)1002{1003returnparse_mode_line(line, state->linenr, &patch->new_mode);1004}10051006static intgitdiff_delete(struct apply_state *state,1007const char*line,1008struct patch *patch)1009{1010 patch->is_delete =1;1011free(patch->old_name);1012 patch->old_name =xstrdup_or_null(patch->def_name);1013returngitdiff_oldmode(state, line, patch);1014}10151016static intgitdiff_newfile(struct apply_state *state,1017const char*line,1018struct patch *patch)1019{1020 patch->is_new =1;1021free(patch->new_name);1022 patch->new_name =xstrdup_or_null(patch->def_name);1023returngitdiff_newmode(state, line, patch);1024}10251026static intgitdiff_copysrc(struct apply_state *state,1027const char*line,1028struct patch *patch)1029{1030 patch->is_copy =1;1031free(patch->old_name);1032 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1033return0;1034}10351036static intgitdiff_copydst(struct apply_state *state,1037const char*line,1038struct patch *patch)1039{1040 patch->is_copy =1;1041free(patch->new_name);1042 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1043return0;1044}10451046static intgitdiff_renamesrc(struct apply_state *state,1047const char*line,1048struct patch *patch)1049{1050 patch->is_rename =1;1051free(patch->old_name);1052 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1053return0;1054}10551056static intgitdiff_renamedst(struct apply_state *state,1057const char*line,1058struct patch *patch)1059{1060 patch->is_rename =1;1061free(patch->new_name);1062 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1063return0;1064}10651066static intgitdiff_similarity(struct apply_state *state,1067const char*line,1068struct patch *patch)1069{1070unsigned long val =strtoul(line, NULL,10);1071if(val <=100)1072 patch->score = val;1073return0;1074}10751076static intgitdiff_dissimilarity(struct apply_state *state,1077const char*line,1078struct patch *patch)1079{1080unsigned long val =strtoul(line, NULL,10);1081if(val <=100)1082 patch->score = val;1083return0;1084}10851086static intgitdiff_index(struct apply_state *state,1087const char*line,1088struct patch *patch)1089{1090/*1091 * index line is N hexadecimal, "..", N hexadecimal,1092 * and optional space with octal mode.1093 */1094const char*ptr, *eol;1095int len;1096const unsigned hexsz = the_hash_algo->hexsz;10971098 ptr =strchr(line,'.');1099if(!ptr || ptr[1] !='.'|| hexsz < ptr - line)1100return0;1101 len = ptr - line;1102memcpy(patch->old_sha1_prefix, line, len);1103 patch->old_sha1_prefix[len] =0;11041105 line = ptr +2;1106 ptr =strchr(line,' ');1107 eol =strchrnul(line,'\n');11081109if(!ptr || eol < ptr)1110 ptr = eol;1111 len = ptr - line;11121113if(hexsz < len)1114return0;1115memcpy(patch->new_sha1_prefix, line, len);1116 patch->new_sha1_prefix[len] =0;1117if(*ptr ==' ')1118returngitdiff_oldmode(state, ptr +1, patch);1119return0;1120}11211122/*1123 * This is normal for a diff that doesn't change anything: we'll fall through1124 * into the next diff. Tell the parser to break out.1125 */1126static intgitdiff_unrecognized(struct apply_state *state,1127const char*line,1128struct patch *patch)1129{1130return1;1131}11321133/*1134 * Skip p_value leading components from "line"; as we do not accept1135 * absolute paths, return NULL in that case.1136 */1137static const char*skip_tree_prefix(struct apply_state *state,1138const char*line,1139int llen)1140{1141int nslash;1142int i;11431144if(!state->p_value)1145return(llen && line[0] =='/') ? NULL : line;11461147 nslash = state->p_value;1148for(i =0; i < llen; i++) {1149int ch = line[i];1150if(ch =='/'&& --nslash <=0)1151return(i ==0) ? NULL : &line[i +1];1152}1153return NULL;1154}11551156/*1157 * This is to extract the same name that appears on "diff --git"1158 * line. We do not find and return anything if it is a rename1159 * patch, and it is OK because we will find the name elsewhere.1160 * We need to reliably find name only when it is mode-change only,1161 * creation or deletion of an empty file. In any of these cases,1162 * both sides are the same name under a/ and b/ respectively.1163 */1164static char*git_header_name(struct apply_state *state,1165const char*line,1166int llen)1167{1168const char*name;1169const char*second = NULL;1170size_t len, line_len;11711172 line +=strlen("diff --git ");1173 llen -=strlen("diff --git ");11741175if(*line =='"') {1176const char*cp;1177struct strbuf first = STRBUF_INIT;1178struct strbuf sp = STRBUF_INIT;11791180if(unquote_c_style(&first, line, &second))1181goto free_and_fail1;11821183/* strip the a/b prefix including trailing slash */1184 cp =skip_tree_prefix(state, first.buf, first.len);1185if(!cp)1186goto free_and_fail1;1187strbuf_remove(&first,0, cp - first.buf);11881189/*1190 * second points at one past closing dq of name.1191 * find the second name.1192 */1193while((second < line + llen) &&isspace(*second))1194 second++;11951196if(line + llen <= second)1197goto free_and_fail1;1198if(*second =='"') {1199if(unquote_c_style(&sp, second, NULL))1200goto free_and_fail1;1201 cp =skip_tree_prefix(state, sp.buf, sp.len);1202if(!cp)1203goto free_and_fail1;1204/* They must match, otherwise ignore */1205if(strcmp(cp, first.buf))1206goto free_and_fail1;1207strbuf_release(&sp);1208returnstrbuf_detach(&first, NULL);1209}12101211/* unquoted second */1212 cp =skip_tree_prefix(state, second, line + llen - second);1213if(!cp)1214goto free_and_fail1;1215if(line + llen - cp != first.len ||1216memcmp(first.buf, cp, first.len))1217goto free_and_fail1;1218returnstrbuf_detach(&first, NULL);12191220 free_and_fail1:1221strbuf_release(&first);1222strbuf_release(&sp);1223return NULL;1224}12251226/* unquoted first name */1227 name =skip_tree_prefix(state, line, llen);1228if(!name)1229return NULL;12301231/*1232 * since the first name is unquoted, a dq if exists must be1233 * the beginning of the second name.1234 */1235for(second = name; second < line + llen; second++) {1236if(*second =='"') {1237struct strbuf sp = STRBUF_INIT;1238const char*np;12391240if(unquote_c_style(&sp, second, NULL))1241goto free_and_fail2;12421243 np =skip_tree_prefix(state, sp.buf, sp.len);1244if(!np)1245goto free_and_fail2;12461247 len = sp.buf + sp.len - np;1248if(len < second - name &&1249!strncmp(np, name, len) &&1250isspace(name[len])) {1251/* Good */1252strbuf_remove(&sp,0, np - sp.buf);1253returnstrbuf_detach(&sp, NULL);1254}12551256 free_and_fail2:1257strbuf_release(&sp);1258return NULL;1259}1260}12611262/*1263 * Accept a name only if it shows up twice, exactly the same1264 * form.1265 */1266 second =strchr(name,'\n');1267if(!second)1268return NULL;1269 line_len = second - name;1270for(len =0; ; len++) {1271switch(name[len]) {1272default:1273continue;1274case'\n':1275return NULL;1276case'\t':case' ':1277/*1278 * Is this the separator between the preimage1279 * and the postimage pathname? Again, we are1280 * only interested in the case where there is1281 * no rename, as this is only to set def_name1282 * and a rename patch has the names elsewhere1283 * in an unambiguous form.1284 */1285if(!name[len +1])1286return NULL;/* no postimage name */1287 second =skip_tree_prefix(state, name + len +1,1288 line_len - (len +1));1289if(!second)1290return NULL;1291/*1292 * Does len bytes starting at "name" and "second"1293 * (that are separated by one HT or SP we just1294 * found) exactly match?1295 */1296if(second[len] =='\n'&& !strncmp(name, second, len))1297returnxmemdupz(name, len);1298}1299}1300}13011302static intcheck_header_line(struct apply_state *state,struct patch *patch)1303{1304int extensions = (patch->is_delete ==1) + (patch->is_new ==1) +1305(patch->is_rename ==1) + (patch->is_copy ==1);1306if(extensions >1)1307returnerror(_("inconsistent header lines%dand%d"),1308 patch->extension_linenr, state->linenr);1309if(extensions && !patch->extension_linenr)1310 patch->extension_linenr = state->linenr;1311return0;1312}13131314/* Verify that we recognize the lines following a git header */1315static intparse_git_header(struct apply_state *state,1316const char*line,1317int len,1318unsigned int size,1319struct patch *patch)1320{1321unsigned long offset;13221323/* A git diff has explicit new/delete information, so we don't guess */1324 patch->is_new =0;1325 patch->is_delete =0;13261327/*1328 * Some things may not have the old name in the1329 * rest of the headers anywhere (pure mode changes,1330 * or removing or adding empty files), so we get1331 * the default name from the header.1332 */1333 patch->def_name =git_header_name(state, line, len);1334if(patch->def_name && state->root.len) {1335char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1336free(patch->def_name);1337 patch->def_name = s;1338}13391340 line += len;1341 size -= len;1342 state->linenr++;1343for(offset = len ; size >0; offset += len, size -= len, line += len, state->linenr++) {1344static const struct opentry {1345const char*str;1346int(*fn)(struct apply_state *,const char*,struct patch *);1347} optable[] = {1348{"@@ -", gitdiff_hdrend },1349{"--- ", gitdiff_oldname },1350{"+++ ", gitdiff_newname },1351{"old mode ", gitdiff_oldmode },1352{"new mode ", gitdiff_newmode },1353{"deleted file mode ", gitdiff_delete },1354{"new file mode ", gitdiff_newfile },1355{"copy from ", gitdiff_copysrc },1356{"copy to ", gitdiff_copydst },1357{"rename old ", gitdiff_renamesrc },1358{"rename new ", gitdiff_renamedst },1359{"rename from ", gitdiff_renamesrc },1360{"rename to ", gitdiff_renamedst },1361{"similarity index ", gitdiff_similarity },1362{"dissimilarity index ", gitdiff_dissimilarity },1363{"index ", gitdiff_index },1364{"", gitdiff_unrecognized },1365};1366int i;13671368 len =linelen(line, size);1369if(!len || line[len-1] !='\n')1370break;1371for(i =0; i <ARRAY_SIZE(optable); i++) {1372const struct opentry *p = optable + i;1373int oplen =strlen(p->str);1374int res;1375if(len < oplen ||memcmp(p->str, line, oplen))1376continue;1377 res = p->fn(state, line + oplen, patch);1378if(res <0)1379return-1;1380if(check_header_line(state, patch))1381return-1;1382if(res >0)1383return offset;1384break;1385}1386}13871388return offset;1389}13901391static intparse_num(const char*line,unsigned long*p)1392{1393char*ptr;13941395if(!isdigit(*line))1396return0;1397*p =strtoul(line, &ptr,10);1398return ptr - line;1399}14001401static intparse_range(const char*line,int len,int offset,const char*expect,1402unsigned long*p1,unsigned long*p2)1403{1404int digits, ex;14051406if(offset <0|| offset >= len)1407return-1;1408 line += offset;1409 len -= offset;14101411 digits =parse_num(line, p1);1412if(!digits)1413return-1;14141415 offset += digits;1416 line += digits;1417 len -= digits;14181419*p2 =1;1420if(*line ==',') {1421 digits =parse_num(line+1, p2);1422if(!digits)1423return-1;14241425 offset += digits+1;1426 line += digits+1;1427 len -= digits+1;1428}14291430 ex =strlen(expect);1431if(ex > len)1432return-1;1433if(memcmp(line, expect, ex))1434return-1;14351436return offset + ex;1437}14381439static voidrecount_diff(const char*line,int size,struct fragment *fragment)1440{1441int oldlines =0, newlines =0, ret =0;14421443if(size <1) {1444warning("recount: ignore empty hunk");1445return;1446}14471448for(;;) {1449int len =linelen(line, size);1450 size -= len;1451 line += len;14521453if(size <1)1454break;14551456switch(*line) {1457case' ':case'\n':1458 newlines++;1459/* fall through */1460case'-':1461 oldlines++;1462continue;1463case'+':1464 newlines++;1465continue;1466case'\\':1467continue;1468case'@':1469 ret = size <3|| !starts_with(line,"@@ ");1470break;1471case'd':1472 ret = size <5|| !starts_with(line,"diff ");1473break;1474default:1475 ret = -1;1476break;1477}1478if(ret) {1479warning(_("recount: unexpected line: %.*s"),1480(int)linelen(line, size), line);1481return;1482}1483break;1484}1485 fragment->oldlines = oldlines;1486 fragment->newlines = newlines;1487}14881489/*1490 * Parse a unified diff fragment header of the1491 * form "@@ -a,b +c,d @@"1492 */1493static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1494{1495int offset;14961497if(!len || line[len-1] !='\n')1498return-1;14991500/* Figure out the number of lines in a fragment */1501 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1502 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);15031504return offset;1505}15061507/*1508 * Find file diff header1509 *1510 * Returns:1511 * -1 if no header was found1512 * -128 in case of error1513 * the size of the header in bytes (called "offset") otherwise1514 */1515static intfind_header(struct apply_state *state,1516const char*line,1517unsigned long size,1518int*hdrsize,1519struct patch *patch)1520{1521unsigned long offset, len;15221523 patch->is_toplevel_relative =0;1524 patch->is_rename = patch->is_copy =0;1525 patch->is_new = patch->is_delete = -1;1526 patch->old_mode = patch->new_mode =0;1527 patch->old_name = patch->new_name = NULL;1528for(offset =0; size >0; offset += len, size -= len, line += len, state->linenr++) {1529unsigned long nextlen;15301531 len =linelen(line, size);1532if(!len)1533break;15341535/* Testing this early allows us to take a few shortcuts.. */1536if(len <6)1537continue;15381539/*1540 * Make sure we don't find any unconnected patch fragments.1541 * That's a sign that we didn't find a header, and that a1542 * patch has become corrupted/broken up.1543 */1544if(!memcmp("@@ -", line,4)) {1545struct fragment dummy;1546if(parse_fragment_header(line, len, &dummy) <0)1547continue;1548error(_("patch fragment without header at line%d: %.*s"),1549 state->linenr, (int)len-1, line);1550return-128;1551}15521553if(size < len +6)1554break;15551556/*1557 * Git patch? It might not have a real patch, just a rename1558 * or mode change, so we handle that specially1559 */1560if(!memcmp("diff --git ", line,11)) {1561int git_hdr_len =parse_git_header(state, line, len, size, patch);1562if(git_hdr_len <0)1563return-128;1564if(git_hdr_len <= len)1565continue;1566if(!patch->old_name && !patch->new_name) {1567if(!patch->def_name) {1568error(Q_("git diff header lacks filename information when removing "1569"%dleading pathname component (line%d)",1570"git diff header lacks filename information when removing "1571"%dleading pathname components (line%d)",1572 state->p_value),1573 state->p_value, state->linenr);1574return-128;1575}1576 patch->old_name =xstrdup(patch->def_name);1577 patch->new_name =xstrdup(patch->def_name);1578}1579if((!patch->new_name && !patch->is_delete) ||1580(!patch->old_name && !patch->is_new)) {1581error(_("git diff header lacks filename information "1582"(line%d)"), state->linenr);1583return-128;1584}1585 patch->is_toplevel_relative =1;1586*hdrsize = git_hdr_len;1587return offset;1588}15891590/* --- followed by +++ ? */1591if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1592continue;15931594/*1595 * We only accept unified patches, so we want it to1596 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1597 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1598 */1599 nextlen =linelen(line + len, size - len);1600if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1601continue;16021603/* Ok, we'll consider it a patch */1604if(parse_traditional_patch(state, line, line+len, patch))1605return-128;1606*hdrsize = len + nextlen;1607 state->linenr +=2;1608return offset;1609}1610return-1;1611}16121613static voidrecord_ws_error(struct apply_state *state,1614unsigned result,1615const char*line,1616int len,1617int linenr)1618{1619char*err;16201621if(!result)1622return;16231624 state->whitespace_error++;1625if(state->squelch_whitespace_errors &&1626 state->squelch_whitespace_errors < state->whitespace_error)1627return;16281629 err =whitespace_error_string(result);1630if(state->apply_verbosity > verbosity_silent)1631fprintf(stderr,"%s:%d:%s.\n%.*s\n",1632 state->patch_input_file, linenr, err, len, line);1633free(err);1634}16351636static voidcheck_whitespace(struct apply_state *state,1637const char*line,1638int len,1639unsigned ws_rule)1640{1641unsigned result =ws_check(line +1, len -1, ws_rule);16421643record_ws_error(state, result, line +1, len -2, state->linenr);1644}16451646/*1647 * Check if the patch has context lines with CRLF or1648 * the patch wants to remove lines with CRLF.1649 */1650static voidcheck_old_for_crlf(struct patch *patch,const char*line,int len)1651{1652if(len >=2&& line[len-1] =='\n'&& line[len-2] =='\r') {1653 patch->ws_rule |= WS_CR_AT_EOL;1654 patch->crlf_in_old =1;1655}1656}165716581659/*1660 * Parse a unified diff. Note that this really needs to parse each1661 * fragment separately, since the only way to know the difference1662 * between a "---" that is part of a patch, and a "---" that starts1663 * the next patch is to look at the line counts..1664 */1665static intparse_fragment(struct apply_state *state,1666const char*line,1667unsigned long size,1668struct patch *patch,1669struct fragment *fragment)1670{1671int added, deleted;1672int len =linelen(line, size), offset;1673unsigned long oldlines, newlines;1674unsigned long leading, trailing;16751676 offset =parse_fragment_header(line, len, fragment);1677if(offset <0)1678return-1;1679if(offset >0&& patch->recount)1680recount_diff(line + offset, size - offset, fragment);1681 oldlines = fragment->oldlines;1682 newlines = fragment->newlines;1683 leading =0;1684 trailing =0;16851686/* Parse the thing.. */1687 line += len;1688 size -= len;1689 state->linenr++;1690 added = deleted =0;1691for(offset = len;16920< size;1693 offset += len, size -= len, line += len, state->linenr++) {1694if(!oldlines && !newlines)1695break;1696 len =linelen(line, size);1697if(!len || line[len-1] !='\n')1698return-1;1699switch(*line) {1700default:1701return-1;1702case'\n':/* newer GNU diff, an empty context line */1703case' ':1704 oldlines--;1705 newlines--;1706if(!deleted && !added)1707 leading++;1708 trailing++;1709check_old_for_crlf(patch, line, len);1710if(!state->apply_in_reverse &&1711 state->ws_error_action == correct_ws_error)1712check_whitespace(state, line, len, patch->ws_rule);1713break;1714case'-':1715if(!state->apply_in_reverse)1716check_old_for_crlf(patch, line, len);1717if(state->apply_in_reverse &&1718 state->ws_error_action != nowarn_ws_error)1719check_whitespace(state, line, len, patch->ws_rule);1720 deleted++;1721 oldlines--;1722 trailing =0;1723break;1724case'+':1725if(state->apply_in_reverse)1726check_old_for_crlf(patch, line, len);1727if(!state->apply_in_reverse &&1728 state->ws_error_action != nowarn_ws_error)1729check_whitespace(state, line, len, patch->ws_rule);1730 added++;1731 newlines--;1732 trailing =0;1733break;17341735/*1736 * We allow "\ No newline at end of file". Depending1737 * on locale settings when the patch was produced we1738 * don't know what this line looks like. The only1739 * thing we do know is that it begins with "\ ".1740 * Checking for 12 is just for sanity check -- any1741 * l10n of "\ No newline..." is at least that long.1742 */1743case'\\':1744if(len <12||memcmp(line,"\\",2))1745return-1;1746break;1747}1748}1749if(oldlines || newlines)1750return-1;1751if(!deleted && !added)1752return-1;17531754 fragment->leading = leading;1755 fragment->trailing = trailing;17561757/*1758 * If a fragment ends with an incomplete line, we failed to include1759 * it in the above loop because we hit oldlines == newlines == 01760 * before seeing it.1761 */1762if(12< size && !memcmp(line,"\\",2))1763 offset +=linelen(line, size);17641765 patch->lines_added += added;1766 patch->lines_deleted += deleted;17671768if(0< patch->is_new && oldlines)1769returnerror(_("new file depends on old contents"));1770if(0< patch->is_delete && newlines)1771returnerror(_("deleted file still has contents"));1772return offset;1773}17741775/*1776 * We have seen "diff --git a/... b/..." header (or a traditional patch1777 * header). Read hunks that belong to this patch into fragments and hang1778 * them to the given patch structure.1779 *1780 * The (fragment->patch, fragment->size) pair points into the memory given1781 * by the caller, not a copy, when we return.1782 *1783 * Returns:1784 * -1 in case of error,1785 * the number of bytes in the patch otherwise.1786 */1787static intparse_single_patch(struct apply_state *state,1788const char*line,1789unsigned long size,1790struct patch *patch)1791{1792unsigned long offset =0;1793unsigned long oldlines =0, newlines =0, context =0;1794struct fragment **fragp = &patch->fragments;17951796while(size >4&& !memcmp(line,"@@ -",4)) {1797struct fragment *fragment;1798int len;17991800 fragment =xcalloc(1,sizeof(*fragment));1801 fragment->linenr = state->linenr;1802 len =parse_fragment(state, line, size, patch, fragment);1803if(len <=0) {1804free(fragment);1805returnerror(_("corrupt patch at line%d"), state->linenr);1806}1807 fragment->patch = line;1808 fragment->size = len;1809 oldlines += fragment->oldlines;1810 newlines += fragment->newlines;1811 context += fragment->leading + fragment->trailing;18121813*fragp = fragment;1814 fragp = &fragment->next;18151816 offset += len;1817 line += len;1818 size -= len;1819}18201821/*1822 * If something was removed (i.e. we have old-lines) it cannot1823 * be creation, and if something was added it cannot be1824 * deletion. However, the reverse is not true; --unified=01825 * patches that only add are not necessarily creation even1826 * though they do not have any old lines, and ones that only1827 * delete are not necessarily deletion.1828 *1829 * Unfortunately, a real creation/deletion patch do _not_ have1830 * any context line by definition, so we cannot safely tell it1831 * apart with --unified=0 insanity. At least if the patch has1832 * more than one hunk it is not creation or deletion.1833 */1834if(patch->is_new <0&&1835(oldlines || (patch->fragments && patch->fragments->next)))1836 patch->is_new =0;1837if(patch->is_delete <0&&1838(newlines || (patch->fragments && patch->fragments->next)))1839 patch->is_delete =0;18401841if(0< patch->is_new && oldlines)1842returnerror(_("new file%sdepends on old contents"), patch->new_name);1843if(0< patch->is_delete && newlines)1844returnerror(_("deleted file%sstill has contents"), patch->old_name);1845if(!patch->is_delete && !newlines && context && state->apply_verbosity > verbosity_silent)1846fprintf_ln(stderr,1847_("** warning: "1848"file%sbecomes empty but is not deleted"),1849 patch->new_name);18501851return offset;1852}18531854staticinlineintmetadata_changes(struct patch *patch)1855{1856return patch->is_rename >0||1857 patch->is_copy >0||1858 patch->is_new >0||1859 patch->is_delete ||1860(patch->old_mode && patch->new_mode &&1861 patch->old_mode != patch->new_mode);1862}18631864static char*inflate_it(const void*data,unsigned long size,1865unsigned long inflated_size)1866{1867 git_zstream stream;1868void*out;1869int st;18701871memset(&stream,0,sizeof(stream));18721873 stream.next_in = (unsigned char*)data;1874 stream.avail_in = size;1875 stream.next_out = out =xmalloc(inflated_size);1876 stream.avail_out = inflated_size;1877git_inflate_init(&stream);1878 st =git_inflate(&stream, Z_FINISH);1879git_inflate_end(&stream);1880if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1881free(out);1882return NULL;1883}1884return out;1885}18861887/*1888 * Read a binary hunk and return a new fragment; fragment->patch1889 * points at an allocated memory that the caller must free, so1890 * it is marked as "->free_patch = 1".1891 */1892static struct fragment *parse_binary_hunk(struct apply_state *state,1893char**buf_p,1894unsigned long*sz_p,1895int*status_p,1896int*used_p)1897{1898/*1899 * Expect a line that begins with binary patch method ("literal"1900 * or "delta"), followed by the length of data before deflating.1901 * a sequence of 'length-byte' followed by base-85 encoded data1902 * should follow, terminated by a newline.1903 *1904 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1905 * and we would limit the patch line to 66 characters,1906 * so one line can fit up to 13 groups that would decode1907 * to 52 bytes max. The length byte 'A'-'Z' corresponds1908 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1909 */1910int llen, used;1911unsigned long size = *sz_p;1912char*buffer = *buf_p;1913int patch_method;1914unsigned long origlen;1915char*data = NULL;1916int hunk_size =0;1917struct fragment *frag;19181919 llen =linelen(buffer, size);1920 used = llen;19211922*status_p =0;19231924if(starts_with(buffer,"delta ")) {1925 patch_method = BINARY_DELTA_DEFLATED;1926 origlen =strtoul(buffer +6, NULL,10);1927}1928else if(starts_with(buffer,"literal ")) {1929 patch_method = BINARY_LITERAL_DEFLATED;1930 origlen =strtoul(buffer +8, NULL,10);1931}1932else1933return NULL;19341935 state->linenr++;1936 buffer += llen;1937while(1) {1938int byte_length, max_byte_length, newsize;1939 llen =linelen(buffer, size);1940 used += llen;1941 state->linenr++;1942if(llen ==1) {1943/* consume the blank line */1944 buffer++;1945 size--;1946break;1947}1948/*1949 * Minimum line is "A00000\n" which is 7-byte long,1950 * and the line length must be multiple of 5 plus 2.1951 */1952if((llen <7) || (llen-2) %5)1953goto corrupt;1954 max_byte_length = (llen -2) /5*4;1955 byte_length = *buffer;1956if('A'<= byte_length && byte_length <='Z')1957 byte_length = byte_length -'A'+1;1958else if('a'<= byte_length && byte_length <='z')1959 byte_length = byte_length -'a'+27;1960else1961goto corrupt;1962/* if the input length was not multiple of 4, we would1963 * have filler at the end but the filler should never1964 * exceed 3 bytes1965 */1966if(max_byte_length < byte_length ||1967 byte_length <= max_byte_length -4)1968goto corrupt;1969 newsize = hunk_size + byte_length;1970 data =xrealloc(data, newsize);1971if(decode_85(data + hunk_size, buffer +1, byte_length))1972goto corrupt;1973 hunk_size = newsize;1974 buffer += llen;1975 size -= llen;1976}19771978 frag =xcalloc(1,sizeof(*frag));1979 frag->patch =inflate_it(data, hunk_size, origlen);1980 frag->free_patch =1;1981if(!frag->patch)1982goto corrupt;1983free(data);1984 frag->size = origlen;1985*buf_p = buffer;1986*sz_p = size;1987*used_p = used;1988 frag->binary_patch_method = patch_method;1989return frag;19901991 corrupt:1992free(data);1993*status_p = -1;1994error(_("corrupt binary patch at line%d: %.*s"),1995 state->linenr-1, llen-1, buffer);1996return NULL;1997}19981999/*2000 * Returns:2001 * -1 in case of error,2002 * the length of the parsed binary patch otherwise2003 */2004static intparse_binary(struct apply_state *state,2005char*buffer,2006unsigned long size,2007struct patch *patch)2008{2009/*2010 * We have read "GIT binary patch\n"; what follows is a line2011 * that says the patch method (currently, either "literal" or2012 * "delta") and the length of data before deflating; a2013 * sequence of 'length-byte' followed by base-85 encoded data2014 * follows.2015 *2016 * When a binary patch is reversible, there is another binary2017 * hunk in the same format, starting with patch method (either2018 * "literal" or "delta") with the length of data, and a sequence2019 * of length-byte + base-85 encoded data, terminated with another2020 * empty line. This data, when applied to the postimage, produces2021 * the preimage.2022 */2023struct fragment *forward;2024struct fragment *reverse;2025int status;2026int used, used_1;20272028 forward =parse_binary_hunk(state, &buffer, &size, &status, &used);2029if(!forward && !status)2030/* there has to be one hunk (forward hunk) */2031returnerror(_("unrecognized binary patch at line%d"), state->linenr-1);2032if(status)2033/* otherwise we already gave an error message */2034return status;20352036 reverse =parse_binary_hunk(state, &buffer, &size, &status, &used_1);2037if(reverse)2038 used += used_1;2039else if(status) {2040/*2041 * Not having reverse hunk is not an error, but having2042 * a corrupt reverse hunk is.2043 */2044free((void*) forward->patch);2045free(forward);2046return status;2047}2048 forward->next = reverse;2049 patch->fragments = forward;2050 patch->is_binary =1;2051return used;2052}20532054static voidprefix_one(struct apply_state *state,char**name)2055{2056char*old_name = *name;2057if(!old_name)2058return;2059*name =prefix_filename(state->prefix, *name);2060free(old_name);2061}20622063static voidprefix_patch(struct apply_state *state,struct patch *p)2064{2065if(!state->prefix || p->is_toplevel_relative)2066return;2067prefix_one(state, &p->new_name);2068prefix_one(state, &p->old_name);2069}20702071/*2072 * include/exclude2073 */20742075static voidadd_name_limit(struct apply_state *state,2076const char*name,2077int exclude)2078{2079struct string_list_item *it;20802081 it =string_list_append(&state->limit_by_name, name);2082 it->util = exclude ? NULL : (void*)1;2083}20842085static intuse_patch(struct apply_state *state,struct patch *p)2086{2087const char*pathname = p->new_name ? p->new_name : p->old_name;2088int i;20892090/* Paths outside are not touched regardless of "--include" */2091if(state->prefix && *state->prefix) {2092const char*rest;2093if(!skip_prefix(pathname, state->prefix, &rest) || !*rest)2094return0;2095}20962097/* See if it matches any of exclude/include rule */2098for(i =0; i < state->limit_by_name.nr; i++) {2099struct string_list_item *it = &state->limit_by_name.items[i];2100if(!wildmatch(it->string, pathname,0))2101return(it->util != NULL);2102}21032104/*2105 * If we had any include, a path that does not match any rule is2106 * not used. Otherwise, we saw bunch of exclude rules (or none)2107 * and such a path is used.2108 */2109return!state->has_include;2110}21112112/*2113 * Read the patch text in "buffer" that extends for "size" bytes; stop2114 * reading after seeing a single patch (i.e. changes to a single file).2115 * Create fragments (i.e. patch hunks) and hang them to the given patch.2116 *2117 * Returns:2118 * -1 if no header was found or parse_binary() failed,2119 * -128 on another error,2120 * the number of bytes consumed otherwise,2121 * so that the caller can call us again for the next patch.2122 */2123static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2124{2125int hdrsize, patchsize;2126int offset =find_header(state, buffer, size, &hdrsize, patch);21272128if(offset <0)2129return offset;21302131prefix_patch(state, patch);21322133if(!use_patch(state, patch))2134 patch->ws_rule =0;2135else2136 patch->ws_rule =whitespace_rule(patch->new_name2137? patch->new_name2138: patch->old_name);21392140 patchsize =parse_single_patch(state,2141 buffer + offset + hdrsize,2142 size - offset - hdrsize,2143 patch);21442145if(patchsize <0)2146return-128;21472148if(!patchsize) {2149static const char git_binary[] ="GIT binary patch\n";2150int hd = hdrsize + offset;2151unsigned long llen =linelen(buffer + hd, size - hd);21522153if(llen ==sizeof(git_binary) -1&&2154!memcmp(git_binary, buffer + hd, llen)) {2155int used;2156 state->linenr++;2157 used =parse_binary(state, buffer + hd + llen,2158 size - hd - llen, patch);2159if(used <0)2160return-1;2161if(used)2162 patchsize = used + llen;2163else2164 patchsize =0;2165}2166else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2167static const char*binhdr[] = {2168"Binary files ",2169"Files ",2170 NULL,2171};2172int i;2173for(i =0; binhdr[i]; i++) {2174int len =strlen(binhdr[i]);2175if(len < size - hd &&2176!memcmp(binhdr[i], buffer + hd, len)) {2177 state->linenr++;2178 patch->is_binary =1;2179 patchsize = llen;2180break;2181}2182}2183}21842185/* Empty patch cannot be applied if it is a text patch2186 * without metadata change. A binary patch appears2187 * empty to us here.2188 */2189if((state->apply || state->check) &&2190(!patch->is_binary && !metadata_changes(patch))) {2191error(_("patch with only garbage at line%d"), state->linenr);2192return-128;2193}2194}21952196return offset + hdrsize + patchsize;2197}21982199static voidreverse_patches(struct patch *p)2200{2201for(; p; p = p->next) {2202struct fragment *frag = p->fragments;22032204SWAP(p->new_name, p->old_name);2205SWAP(p->new_mode, p->old_mode);2206SWAP(p->is_new, p->is_delete);2207SWAP(p->lines_added, p->lines_deleted);2208SWAP(p->old_sha1_prefix, p->new_sha1_prefix);22092210for(; frag; frag = frag->next) {2211SWAP(frag->newpos, frag->oldpos);2212SWAP(frag->newlines, frag->oldlines);2213}2214}2215}22162217static const char pluses[] =2218"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2219static const char minuses[]=2220"----------------------------------------------------------------------";22212222static voidshow_stats(struct apply_state *state,struct patch *patch)2223{2224struct strbuf qname = STRBUF_INIT;2225char*cp = patch->new_name ? patch->new_name : patch->old_name;2226int max, add, del;22272228quote_c_style(cp, &qname, NULL,0);22292230/*2231 * "scale" the filename2232 */2233 max = state->max_len;2234if(max >50)2235 max =50;22362237if(qname.len > max) {2238 cp =strchr(qname.buf + qname.len +3- max,'/');2239if(!cp)2240 cp = qname.buf + qname.len +3- max;2241strbuf_splice(&qname,0, cp - qname.buf,"...",3);2242}22432244if(patch->is_binary) {2245printf(" %-*s | Bin\n", max, qname.buf);2246strbuf_release(&qname);2247return;2248}22492250printf(" %-*s |", max, qname.buf);2251strbuf_release(&qname);22522253/*2254 * scale the add/delete2255 */2256 max = max + state->max_change >70?70- max : state->max_change;2257 add = patch->lines_added;2258 del = patch->lines_deleted;22592260if(state->max_change >0) {2261int total = ((add + del) * max + state->max_change /2) / state->max_change;2262 add = (add * max + state->max_change /2) / state->max_change;2263 del = total - add;2264}2265printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2266 add, pluses, del, minuses);2267}22682269static intread_old_data(struct stat *st,struct patch *patch,2270const char*path,struct strbuf *buf)2271{2272int conv_flags = patch->crlf_in_old ?2273 CONV_EOL_KEEP_CRLF : CONV_EOL_RENORMALIZE;2274switch(st->st_mode & S_IFMT) {2275case S_IFLNK:2276if(strbuf_readlink(buf, path, st->st_size) <0)2277returnerror(_("unable to read symlink%s"), path);2278return0;2279case S_IFREG:2280if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2281returnerror(_("unable to open or read%s"), path);2282/*2283 * "git apply" without "--index/--cached" should never look2284 * at the index; the target file may not have been added to2285 * the index yet, and we may not even be in any Git repository.2286 * Pass NULL to convert_to_git() to stress this; the function2287 * should never look at the index when explicit crlf option2288 * is given.2289 */2290convert_to_git(NULL, path, buf->buf, buf->len, buf, conv_flags);2291return0;2292default:2293return-1;2294}2295}22962297/*2298 * Update the preimage, and the common lines in postimage,2299 * from buffer buf of length len. If postlen is 0 the postimage2300 * is updated in place, otherwise it's updated on a new buffer2301 * of length postlen2302 */23032304static voidupdate_pre_post_images(struct image *preimage,2305struct image *postimage,2306char*buf,2307size_t len,size_t postlen)2308{2309int i, ctx, reduced;2310char*new_buf, *old_buf, *fixed;2311struct image fixed_preimage;23122313/*2314 * Update the preimage with whitespace fixes. Note that we2315 * are not losing preimage->buf -- apply_one_fragment() will2316 * free "oldlines".2317 */2318prepare_image(&fixed_preimage, buf, len,1);2319assert(postlen2320? fixed_preimage.nr == preimage->nr2321: fixed_preimage.nr <= preimage->nr);2322for(i =0; i < fixed_preimage.nr; i++)2323 fixed_preimage.line[i].flag = preimage->line[i].flag;2324free(preimage->line_allocated);2325*preimage = fixed_preimage;23262327/*2328 * Adjust the common context lines in postimage. This can be2329 * done in-place when we are shrinking it with whitespace2330 * fixing, but needs a new buffer when ignoring whitespace or2331 * expanding leading tabs to spaces.2332 *2333 * We trust the caller to tell us if the update can be done2334 * in place (postlen==0) or not.2335 */2336 old_buf = postimage->buf;2337if(postlen)2338 new_buf = postimage->buf =xmalloc(postlen);2339else2340 new_buf = old_buf;2341 fixed = preimage->buf;23422343for(i = reduced = ctx =0; i < postimage->nr; i++) {2344size_t l_len = postimage->line[i].len;2345if(!(postimage->line[i].flag & LINE_COMMON)) {2346/* an added line -- no counterparts in preimage */2347memmove(new_buf, old_buf, l_len);2348 old_buf += l_len;2349 new_buf += l_len;2350continue;2351}23522353/* a common context -- skip it in the original postimage */2354 old_buf += l_len;23552356/* and find the corresponding one in the fixed preimage */2357while(ctx < preimage->nr &&2358!(preimage->line[ctx].flag & LINE_COMMON)) {2359 fixed += preimage->line[ctx].len;2360 ctx++;2361}23622363/*2364 * preimage is expected to run out, if the caller2365 * fixed addition of trailing blank lines.2366 */2367if(preimage->nr <= ctx) {2368 reduced++;2369continue;2370}23712372/* and copy it in, while fixing the line length */2373 l_len = preimage->line[ctx].len;2374memcpy(new_buf, fixed, l_len);2375 new_buf += l_len;2376 fixed += l_len;2377 postimage->line[i].len = l_len;2378 ctx++;2379}23802381if(postlen2382? postlen < new_buf - postimage->buf2383: postimage->len < new_buf - postimage->buf)2384BUG("caller miscounted postlen: asked%d, orig =%d, used =%d",2385(int)postlen, (int) postimage->len, (int)(new_buf - postimage->buf));23862387/* Fix the length of the whole thing */2388 postimage->len = new_buf - postimage->buf;2389 postimage->nr -= reduced;2390}23912392static intline_by_line_fuzzy_match(struct image *img,2393struct image *preimage,2394struct image *postimage,2395unsigned long current,2396int current_lno,2397int preimage_limit)2398{2399int i;2400size_t imgoff =0;2401size_t preoff =0;2402size_t postlen = postimage->len;2403size_t extra_chars;2404char*buf;2405char*preimage_eof;2406char*preimage_end;2407struct strbuf fixed;2408char*fixed_buf;2409size_t fixed_len;24102411for(i =0; i < preimage_limit; i++) {2412size_t prelen = preimage->line[i].len;2413size_t imglen = img->line[current_lno+i].len;24142415if(!fuzzy_matchlines(img->buf + current + imgoff, imglen,2416 preimage->buf + preoff, prelen))2417return0;2418if(preimage->line[i].flag & LINE_COMMON)2419 postlen += imglen - prelen;2420 imgoff += imglen;2421 preoff += prelen;2422}24232424/*2425 * Ok, the preimage matches with whitespace fuzz.2426 *2427 * imgoff now holds the true length of the target that2428 * matches the preimage before the end of the file.2429 *2430 * Count the number of characters in the preimage that fall2431 * beyond the end of the file and make sure that all of them2432 * are whitespace characters. (This can only happen if2433 * we are removing blank lines at the end of the file.)2434 */2435 buf = preimage_eof = preimage->buf + preoff;2436for( ; i < preimage->nr; i++)2437 preoff += preimage->line[i].len;2438 preimage_end = preimage->buf + preoff;2439for( ; buf < preimage_end; buf++)2440if(!isspace(*buf))2441return0;24422443/*2444 * Update the preimage and the common postimage context2445 * lines to use the same whitespace as the target.2446 * If whitespace is missing in the target (i.e.2447 * if the preimage extends beyond the end of the file),2448 * use the whitespace from the preimage.2449 */2450 extra_chars = preimage_end - preimage_eof;2451strbuf_init(&fixed, imgoff + extra_chars);2452strbuf_add(&fixed, img->buf + current, imgoff);2453strbuf_add(&fixed, preimage_eof, extra_chars);2454 fixed_buf =strbuf_detach(&fixed, &fixed_len);2455update_pre_post_images(preimage, postimage,2456 fixed_buf, fixed_len, postlen);2457return1;2458}24592460static intmatch_fragment(struct apply_state *state,2461struct image *img,2462struct image *preimage,2463struct image *postimage,2464unsigned long current,2465int current_lno,2466unsigned ws_rule,2467int match_beginning,int match_end)2468{2469int i;2470char*fixed_buf, *buf, *orig, *target;2471struct strbuf fixed;2472size_t fixed_len, postlen;2473int preimage_limit;24742475if(preimage->nr + current_lno <= img->nr) {2476/*2477 * The hunk falls within the boundaries of img.2478 */2479 preimage_limit = preimage->nr;2480if(match_end && (preimage->nr + current_lno != img->nr))2481return0;2482}else if(state->ws_error_action == correct_ws_error &&2483(ws_rule & WS_BLANK_AT_EOF)) {2484/*2485 * This hunk extends beyond the end of img, and we are2486 * removing blank lines at the end of the file. This2487 * many lines from the beginning of the preimage must2488 * match with img, and the remainder of the preimage2489 * must be blank.2490 */2491 preimage_limit = img->nr - current_lno;2492}else{2493/*2494 * The hunk extends beyond the end of the img and2495 * we are not removing blanks at the end, so we2496 * should reject the hunk at this position.2497 */2498return0;2499}25002501if(match_beginning && current_lno)2502return0;25032504/* Quick hash check */2505for(i =0; i < preimage_limit; i++)2506if((img->line[current_lno + i].flag & LINE_PATCHED) ||2507(preimage->line[i].hash != img->line[current_lno + i].hash))2508return0;25092510if(preimage_limit == preimage->nr) {2511/*2512 * Do we have an exact match? If we were told to match2513 * at the end, size must be exactly at current+fragsize,2514 * otherwise current+fragsize must be still within the preimage,2515 * and either case, the old piece should match the preimage2516 * exactly.2517 */2518if((match_end2519? (current + preimage->len == img->len)2520: (current + preimage->len <= img->len)) &&2521!memcmp(img->buf + current, preimage->buf, preimage->len))2522return1;2523}else{2524/*2525 * The preimage extends beyond the end of img, so2526 * there cannot be an exact match.2527 *2528 * There must be one non-blank context line that match2529 * a line before the end of img.2530 */2531char*buf_end;25322533 buf = preimage->buf;2534 buf_end = buf;2535for(i =0; i < preimage_limit; i++)2536 buf_end += preimage->line[i].len;25372538for( ; buf < buf_end; buf++)2539if(!isspace(*buf))2540break;2541if(buf == buf_end)2542return0;2543}25442545/*2546 * No exact match. If we are ignoring whitespace, run a line-by-line2547 * fuzzy matching. We collect all the line length information because2548 * we need it to adjust whitespace if we match.2549 */2550if(state->ws_ignore_action == ignore_ws_change)2551returnline_by_line_fuzzy_match(img, preimage, postimage,2552 current, current_lno, preimage_limit);25532554if(state->ws_error_action != correct_ws_error)2555return0;25562557/*2558 * The hunk does not apply byte-by-byte, but the hash says2559 * it might with whitespace fuzz. We weren't asked to2560 * ignore whitespace, we were asked to correct whitespace2561 * errors, so let's try matching after whitespace correction.2562 *2563 * While checking the preimage against the target, whitespace2564 * errors in both fixed, we count how large the corresponding2565 * postimage needs to be. The postimage prepared by2566 * apply_one_fragment() has whitespace errors fixed on added2567 * lines already, but the common lines were propagated as-is,2568 * which may become longer when their whitespace errors are2569 * fixed.2570 */25712572/* First count added lines in postimage */2573 postlen =0;2574for(i =0; i < postimage->nr; i++) {2575if(!(postimage->line[i].flag & LINE_COMMON))2576 postlen += postimage->line[i].len;2577}25782579/*2580 * The preimage may extend beyond the end of the file,2581 * but in this loop we will only handle the part of the2582 * preimage that falls within the file.2583 */2584strbuf_init(&fixed, preimage->len +1);2585 orig = preimage->buf;2586 target = img->buf + current;2587for(i =0; i < preimage_limit; i++) {2588size_t oldlen = preimage->line[i].len;2589size_t tgtlen = img->line[current_lno + i].len;2590size_t fixstart = fixed.len;2591struct strbuf tgtfix;2592int match;25932594/* Try fixing the line in the preimage */2595ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25962597/* Try fixing the line in the target */2598strbuf_init(&tgtfix, tgtlen);2599ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);26002601/*2602 * If they match, either the preimage was based on2603 * a version before our tree fixed whitespace breakage,2604 * or we are lacking a whitespace-fix patch the tree2605 * the preimage was based on already had (i.e. target2606 * has whitespace breakage, the preimage doesn't).2607 * In either case, we are fixing the whitespace breakages2608 * so we might as well take the fix together with their2609 * real change.2610 */2611 match = (tgtfix.len == fixed.len - fixstart &&2612!memcmp(tgtfix.buf, fixed.buf + fixstart,2613 fixed.len - fixstart));26142615/* Add the length if this is common with the postimage */2616if(preimage->line[i].flag & LINE_COMMON)2617 postlen += tgtfix.len;26182619strbuf_release(&tgtfix);2620if(!match)2621goto unmatch_exit;26222623 orig += oldlen;2624 target += tgtlen;2625}262626272628/*2629 * Now handle the lines in the preimage that falls beyond the2630 * end of the file (if any). They will only match if they are2631 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2632 * false).2633 */2634for( ; i < preimage->nr; i++) {2635size_t fixstart = fixed.len;/* start of the fixed preimage */2636size_t oldlen = preimage->line[i].len;2637int j;26382639/* Try fixing the line in the preimage */2640ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);26412642for(j = fixstart; j < fixed.len; j++)2643if(!isspace(fixed.buf[j]))2644goto unmatch_exit;26452646 orig += oldlen;2647}26482649/*2650 * Yes, the preimage is based on an older version that still2651 * has whitespace breakages unfixed, and fixing them makes the2652 * hunk match. Update the context lines in the postimage.2653 */2654 fixed_buf =strbuf_detach(&fixed, &fixed_len);2655if(postlen < postimage->len)2656 postlen =0;2657update_pre_post_images(preimage, postimage,2658 fixed_buf, fixed_len, postlen);2659return1;26602661 unmatch_exit:2662strbuf_release(&fixed);2663return0;2664}26652666static intfind_pos(struct apply_state *state,2667struct image *img,2668struct image *preimage,2669struct image *postimage,2670int line,2671unsigned ws_rule,2672int match_beginning,int match_end)2673{2674int i;2675unsigned long backwards, forwards, current;2676int backwards_lno, forwards_lno, current_lno;26772678/*2679 * If match_beginning or match_end is specified, there is no2680 * point starting from a wrong line that will never match and2681 * wander around and wait for a match at the specified end.2682 */2683if(match_beginning)2684 line =0;2685else if(match_end)2686 line = img->nr - preimage->nr;26872688/*2689 * Because the comparison is unsigned, the following test2690 * will also take care of a negative line number that can2691 * result when match_end and preimage is larger than the target.2692 */2693if((size_t) line > img->nr)2694 line = img->nr;26952696 current =0;2697for(i =0; i < line; i++)2698 current += img->line[i].len;26992700/*2701 * There's probably some smart way to do this, but I'll leave2702 * that to the smart and beautiful people. I'm simple and stupid.2703 */2704 backwards = current;2705 backwards_lno = line;2706 forwards = current;2707 forwards_lno = line;2708 current_lno = line;27092710for(i =0; ; i++) {2711if(match_fragment(state, img, preimage, postimage,2712 current, current_lno, ws_rule,2713 match_beginning, match_end))2714return current_lno;27152716 again:2717if(backwards_lno ==0&& forwards_lno == img->nr)2718break;27192720if(i &1) {2721if(backwards_lno ==0) {2722 i++;2723goto again;2724}2725 backwards_lno--;2726 backwards -= img->line[backwards_lno].len;2727 current = backwards;2728 current_lno = backwards_lno;2729}else{2730if(forwards_lno == img->nr) {2731 i++;2732goto again;2733}2734 forwards += img->line[forwards_lno].len;2735 forwards_lno++;2736 current = forwards;2737 current_lno = forwards_lno;2738}27392740}2741return-1;2742}27432744static voidremove_first_line(struct image *img)2745{2746 img->buf += img->line[0].len;2747 img->len -= img->line[0].len;2748 img->line++;2749 img->nr--;2750}27512752static voidremove_last_line(struct image *img)2753{2754 img->len -= img->line[--img->nr].len;2755}27562757/*2758 * The change from "preimage" and "postimage" has been found to2759 * apply at applied_pos (counts in line numbers) in "img".2760 * Update "img" to remove "preimage" and replace it with "postimage".2761 */2762static voidupdate_image(struct apply_state *state,2763struct image *img,2764int applied_pos,2765struct image *preimage,2766struct image *postimage)2767{2768/*2769 * remove the copy of preimage at offset in img2770 * and replace it with postimage2771 */2772int i, nr;2773size_t remove_count, insert_count, applied_at =0;2774char*result;2775int preimage_limit;27762777/*2778 * If we are removing blank lines at the end of img,2779 * the preimage may extend beyond the end.2780 * If that is the case, we must be careful only to2781 * remove the part of the preimage that falls within2782 * the boundaries of img. Initialize preimage_limit2783 * to the number of lines in the preimage that falls2784 * within the boundaries.2785 */2786 preimage_limit = preimage->nr;2787if(preimage_limit > img->nr - applied_pos)2788 preimage_limit = img->nr - applied_pos;27892790for(i =0; i < applied_pos; i++)2791 applied_at += img->line[i].len;27922793 remove_count =0;2794for(i =0; i < preimage_limit; i++)2795 remove_count += img->line[applied_pos + i].len;2796 insert_count = postimage->len;27972798/* Adjust the contents */2799 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2800memcpy(result, img->buf, applied_at);2801memcpy(result + applied_at, postimage->buf, postimage->len);2802memcpy(result + applied_at + postimage->len,2803 img->buf + (applied_at + remove_count),2804 img->len - (applied_at + remove_count));2805free(img->buf);2806 img->buf = result;2807 img->len += insert_count - remove_count;2808 result[img->len] ='\0';28092810/* Adjust the line table */2811 nr = img->nr + postimage->nr - preimage_limit;2812if(preimage_limit < postimage->nr) {2813/*2814 * NOTE: this knows that we never call remove_first_line()2815 * on anything other than pre/post image.2816 */2817REALLOC_ARRAY(img->line, nr);2818 img->line_allocated = img->line;2819}2820if(preimage_limit != postimage->nr)2821MOVE_ARRAY(img->line + applied_pos + postimage->nr,2822 img->line + applied_pos + preimage_limit,2823 img->nr - (applied_pos + preimage_limit));2824COPY_ARRAY(img->line + applied_pos, postimage->line, postimage->nr);2825if(!state->allow_overlap)2826for(i =0; i < postimage->nr; i++)2827 img->line[applied_pos + i].flag |= LINE_PATCHED;2828 img->nr = nr;2829}28302831/*2832 * Use the patch-hunk text in "frag" to prepare two images (preimage and2833 * postimage) for the hunk. Find lines that match "preimage" in "img" and2834 * replace the part of "img" with "postimage" text.2835 */2836static intapply_one_fragment(struct apply_state *state,2837struct image *img,struct fragment *frag,2838int inaccurate_eof,unsigned ws_rule,2839int nth_fragment)2840{2841int match_beginning, match_end;2842const char*patch = frag->patch;2843int size = frag->size;2844char*old, *oldlines;2845struct strbuf newlines;2846int new_blank_lines_at_end =0;2847int found_new_blank_lines_at_end =0;2848int hunk_linenr = frag->linenr;2849unsigned long leading, trailing;2850int pos, applied_pos;2851struct image preimage;2852struct image postimage;28532854memset(&preimage,0,sizeof(preimage));2855memset(&postimage,0,sizeof(postimage));2856 oldlines =xmalloc(size);2857strbuf_init(&newlines, size);28582859 old = oldlines;2860while(size >0) {2861char first;2862int len =linelen(patch, size);2863int plen;2864int added_blank_line =0;2865int is_blank_context =0;2866size_t start;28672868if(!len)2869break;28702871/*2872 * "plen" is how much of the line we should use for2873 * the actual patch data. Normally we just remove the2874 * first character on the line, but if the line is2875 * followed by "\ No newline", then we also remove the2876 * last one (which is the newline, of course).2877 */2878 plen = len -1;2879if(len < size && patch[len] =='\\')2880 plen--;2881 first = *patch;2882if(state->apply_in_reverse) {2883if(first =='-')2884 first ='+';2885else if(first =='+')2886 first ='-';2887}28882889switch(first) {2890case'\n':2891/* Newer GNU diff, empty context line */2892if(plen <0)2893/* ... followed by '\No newline'; nothing */2894break;2895*old++ ='\n';2896strbuf_addch(&newlines,'\n');2897add_line_info(&preimage,"\n",1, LINE_COMMON);2898add_line_info(&postimage,"\n",1, LINE_COMMON);2899 is_blank_context =1;2900break;2901case' ':2902if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2903ws_blank_line(patch +1, plen, ws_rule))2904 is_blank_context =1;2905/* fallthrough */2906case'-':2907memcpy(old, patch +1, plen);2908add_line_info(&preimage, old, plen,2909(first ==' '? LINE_COMMON :0));2910 old += plen;2911if(first =='-')2912break;2913/* fallthrough */2914case'+':2915/* --no-add does not add new lines */2916if(first =='+'&& state->no_add)2917break;29182919 start = newlines.len;2920if(first !='+'||2921!state->whitespace_error ||2922 state->ws_error_action != correct_ws_error) {2923strbuf_add(&newlines, patch +1, plen);2924}2925else{2926ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2927}2928add_line_info(&postimage, newlines.buf + start, newlines.len - start,2929(first =='+'?0: LINE_COMMON));2930if(first =='+'&&2931(ws_rule & WS_BLANK_AT_EOF) &&2932ws_blank_line(patch +1, plen, ws_rule))2933 added_blank_line =1;2934break;2935case'@':case'\\':2936/* Ignore it, we already handled it */2937break;2938default:2939if(state->apply_verbosity > verbosity_normal)2940error(_("invalid start of line: '%c'"), first);2941 applied_pos = -1;2942goto out;2943}2944if(added_blank_line) {2945if(!new_blank_lines_at_end)2946 found_new_blank_lines_at_end = hunk_linenr;2947 new_blank_lines_at_end++;2948}2949else if(is_blank_context)2950;2951else2952 new_blank_lines_at_end =0;2953 patch += len;2954 size -= len;2955 hunk_linenr++;2956}2957if(inaccurate_eof &&2958 old > oldlines && old[-1] =='\n'&&2959 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2960 old--;2961strbuf_setlen(&newlines, newlines.len -1);2962 preimage.line_allocated[preimage.nr -1].len--;2963 postimage.line_allocated[postimage.nr -1].len--;2964}29652966 leading = frag->leading;2967 trailing = frag->trailing;29682969/*2970 * A hunk to change lines at the beginning would begin with2971 * @@ -1,L +N,M @@2972 * but we need to be careful. -U0 that inserts before the second2973 * line also has this pattern.2974 *2975 * And a hunk to add to an empty file would begin with2976 * @@ -0,0 +N,M @@2977 *2978 * In other words, a hunk that is (frag->oldpos <= 1) with or2979 * without leading context must match at the beginning.2980 */2981 match_beginning = (!frag->oldpos ||2982(frag->oldpos ==1&& !state->unidiff_zero));29832984/*2985 * A hunk without trailing lines must match at the end.2986 * However, we simply cannot tell if a hunk must match end2987 * from the lack of trailing lines if the patch was generated2988 * with unidiff without any context.2989 */2990 match_end = !state->unidiff_zero && !trailing;29912992 pos = frag->newpos ? (frag->newpos -1) :0;2993 preimage.buf = oldlines;2994 preimage.len = old - oldlines;2995 postimage.buf = newlines.buf;2996 postimage.len = newlines.len;2997 preimage.line = preimage.line_allocated;2998 postimage.line = postimage.line_allocated;29993000for(;;) {30013002 applied_pos =find_pos(state, img, &preimage, &postimage, pos,3003 ws_rule, match_beginning, match_end);30043005if(applied_pos >=0)3006break;30073008/* Am I at my context limits? */3009if((leading <= state->p_context) && (trailing <= state->p_context))3010break;3011if(match_beginning || match_end) {3012 match_beginning = match_end =0;3013continue;3014}30153016/*3017 * Reduce the number of context lines; reduce both3018 * leading and trailing if they are equal otherwise3019 * just reduce the larger context.3020 */3021if(leading >= trailing) {3022remove_first_line(&preimage);3023remove_first_line(&postimage);3024 pos--;3025 leading--;3026}3027if(trailing > leading) {3028remove_last_line(&preimage);3029remove_last_line(&postimage);3030 trailing--;3031}3032}30333034if(applied_pos >=0) {3035if(new_blank_lines_at_end &&3036 preimage.nr + applied_pos >= img->nr &&3037(ws_rule & WS_BLANK_AT_EOF) &&3038 state->ws_error_action != nowarn_ws_error) {3039record_ws_error(state, WS_BLANK_AT_EOF,"+",1,3040 found_new_blank_lines_at_end);3041if(state->ws_error_action == correct_ws_error) {3042while(new_blank_lines_at_end--)3043remove_last_line(&postimage);3044}3045/*3046 * We would want to prevent write_out_results()3047 * from taking place in apply_patch() that follows3048 * the callchain led us here, which is:3049 * apply_patch->check_patch_list->check_patch->3050 * apply_data->apply_fragments->apply_one_fragment3051 */3052if(state->ws_error_action == die_on_ws_error)3053 state->apply =0;3054}30553056if(state->apply_verbosity > verbosity_normal && applied_pos != pos) {3057int offset = applied_pos - pos;3058if(state->apply_in_reverse)3059 offset =0- offset;3060fprintf_ln(stderr,3061Q_("Hunk #%dsucceeded at%d(offset%dline).",3062"Hunk #%dsucceeded at%d(offset%dlines).",3063 offset),3064 nth_fragment, applied_pos +1, offset);3065}30663067/*3068 * Warn if it was necessary to reduce the number3069 * of context lines.3070 */3071if((leading != frag->leading ||3072 trailing != frag->trailing) && state->apply_verbosity > verbosity_silent)3073fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"3074" to apply fragment at%d"),3075 leading, trailing, applied_pos+1);3076update_image(state, img, applied_pos, &preimage, &postimage);3077}else{3078if(state->apply_verbosity > verbosity_normal)3079error(_("while searching for:\n%.*s"),3080(int)(old - oldlines), oldlines);3081}30823083out:3084free(oldlines);3085strbuf_release(&newlines);3086free(preimage.line_allocated);3087free(postimage.line_allocated);30883089return(applied_pos <0);3090}30913092static intapply_binary_fragment(struct apply_state *state,3093struct image *img,3094struct patch *patch)3095{3096struct fragment *fragment = patch->fragments;3097unsigned long len;3098void*dst;30993100if(!fragment)3101returnerror(_("missing binary patch data for '%s'"),3102 patch->new_name ?3103 patch->new_name :3104 patch->old_name);31053106/* Binary patch is irreversible without the optional second hunk */3107if(state->apply_in_reverse) {3108if(!fragment->next)3109returnerror(_("cannot reverse-apply a binary patch "3110"without the reverse hunk to '%s'"),3111 patch->new_name3112? patch->new_name : patch->old_name);3113 fragment = fragment->next;3114}3115switch(fragment->binary_patch_method) {3116case BINARY_DELTA_DEFLATED:3117 dst =patch_delta(img->buf, img->len, fragment->patch,3118 fragment->size, &len);3119if(!dst)3120return-1;3121clear_image(img);3122 img->buf = dst;3123 img->len = len;3124return0;3125case BINARY_LITERAL_DEFLATED:3126clear_image(img);3127 img->len = fragment->size;3128 img->buf =xmemdupz(fragment->patch, img->len);3129return0;3130}3131return-1;3132}31333134/*3135 * Replace "img" with the result of applying the binary patch.3136 * The binary patch data itself in patch->fragment is still kept3137 * but the preimage prepared by the caller in "img" is freed here3138 * or in the helper function apply_binary_fragment() this calls.3139 */3140static intapply_binary(struct apply_state *state,3141struct image *img,3142struct patch *patch)3143{3144const char*name = patch->old_name ? patch->old_name : patch->new_name;3145struct object_id oid;3146const unsigned hexsz = the_hash_algo->hexsz;31473148/*3149 * For safety, we require patch index line to contain3150 * full hex textual object ID for old and new, at least for now.3151 */3152if(strlen(patch->old_sha1_prefix) != hexsz ||3153strlen(patch->new_sha1_prefix) != hexsz ||3154get_oid_hex(patch->old_sha1_prefix, &oid) ||3155get_oid_hex(patch->new_sha1_prefix, &oid))3156returnerror(_("cannot apply binary patch to '%s' "3157"without full index line"), name);31583159if(patch->old_name) {3160/*3161 * See if the old one matches what the patch3162 * applies to.3163 */3164hash_object_file(img->buf, img->len, blob_type, &oid);3165if(strcmp(oid_to_hex(&oid), patch->old_sha1_prefix))3166returnerror(_("the patch applies to '%s' (%s), "3167"which does not match the "3168"current contents."),3169 name,oid_to_hex(&oid));3170}3171else{3172/* Otherwise, the old one must be empty. */3173if(img->len)3174returnerror(_("the patch applies to an empty "3175"'%s' but it is not empty"), name);3176}31773178get_oid_hex(patch->new_sha1_prefix, &oid);3179if(is_null_oid(&oid)) {3180clear_image(img);3181return0;/* deletion patch */3182}31833184if(has_sha1_file(oid.hash)) {3185/* We already have the postimage */3186enum object_type type;3187unsigned long size;3188char*result;31893190 result =read_object_file(&oid, &type, &size);3191if(!result)3192returnerror(_("the necessary postimage%sfor "3193"'%s' cannot be read"),3194 patch->new_sha1_prefix, name);3195clear_image(img);3196 img->buf = result;3197 img->len = size;3198}else{3199/*3200 * We have verified buf matches the preimage;3201 * apply the patch data to it, which is stored3202 * in the patch->fragments->{patch,size}.3203 */3204if(apply_binary_fragment(state, img, patch))3205returnerror(_("binary patch does not apply to '%s'"),3206 name);32073208/* verify that the result matches */3209hash_object_file(img->buf, img->len, blob_type, &oid);3210if(strcmp(oid_to_hex(&oid), patch->new_sha1_prefix))3211returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3212 name, patch->new_sha1_prefix,oid_to_hex(&oid));3213}32143215return0;3216}32173218static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3219{3220struct fragment *frag = patch->fragments;3221const char*name = patch->old_name ? patch->old_name : patch->new_name;3222unsigned ws_rule = patch->ws_rule;3223unsigned inaccurate_eof = patch->inaccurate_eof;3224int nth =0;32253226if(patch->is_binary)3227returnapply_binary(state, img, patch);32283229while(frag) {3230 nth++;3231if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3232error(_("patch failed:%s:%ld"), name, frag->oldpos);3233if(!state->apply_with_reject)3234return-1;3235 frag->rejected =1;3236}3237 frag = frag->next;3238}3239return0;3240}32413242static intread_blob_object(struct strbuf *buf,const struct object_id *oid,unsigned mode)3243{3244if(S_ISGITLINK(mode)) {3245strbuf_grow(buf,100);3246strbuf_addf(buf,"Subproject commit%s\n",oid_to_hex(oid));3247}else{3248enum object_type type;3249unsigned long sz;3250char*result;32513252 result =read_object_file(oid, &type, &sz);3253if(!result)3254return-1;3255/* XXX read_sha1_file NUL-terminates */3256strbuf_attach(buf, result, sz, sz +1);3257}3258return0;3259}32603261static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3262{3263if(!ce)3264return0;3265returnread_blob_object(buf, &ce->oid, ce->ce_mode);3266}32673268static struct patch *in_fn_table(struct apply_state *state,const char*name)3269{3270struct string_list_item *item;32713272if(name == NULL)3273return NULL;32743275 item =string_list_lookup(&state->fn_table, name);3276if(item != NULL)3277return(struct patch *)item->util;32783279return NULL;3280}32813282/*3283 * item->util in the filename table records the status of the path.3284 * Usually it points at a patch (whose result records the contents3285 * of it after applying it), but it could be PATH_WAS_DELETED for a3286 * path that a previously applied patch has already removed, or3287 * PATH_TO_BE_DELETED for a path that a later patch would remove.3288 *3289 * The latter is needed to deal with a case where two paths A and B3290 * are swapped by first renaming A to B and then renaming B to A;3291 * moving A to B should not be prevented due to presence of B as we3292 * will remove it in a later patch.3293 */3294#define PATH_TO_BE_DELETED ((struct patch *) -2)3295#define PATH_WAS_DELETED ((struct patch *) -1)32963297static intto_be_deleted(struct patch *patch)3298{3299return patch == PATH_TO_BE_DELETED;3300}33013302static intwas_deleted(struct patch *patch)3303{3304return patch == PATH_WAS_DELETED;3305}33063307static voidadd_to_fn_table(struct apply_state *state,struct patch *patch)3308{3309struct string_list_item *item;33103311/*3312 * Always add new_name unless patch is a deletion3313 * This should cover the cases for normal diffs,3314 * file creations and copies3315 */3316if(patch->new_name != NULL) {3317 item =string_list_insert(&state->fn_table, patch->new_name);3318 item->util = patch;3319}33203321/*3322 * store a failure on rename/deletion cases because3323 * later chunks shouldn't patch old names3324 */3325if((patch->new_name == NULL) || (patch->is_rename)) {3326 item =string_list_insert(&state->fn_table, patch->old_name);3327 item->util = PATH_WAS_DELETED;3328}3329}33303331static voidprepare_fn_table(struct apply_state *state,struct patch *patch)3332{3333/*3334 * store information about incoming file deletion3335 */3336while(patch) {3337if((patch->new_name == NULL) || (patch->is_rename)) {3338struct string_list_item *item;3339 item =string_list_insert(&state->fn_table, patch->old_name);3340 item->util = PATH_TO_BE_DELETED;3341}3342 patch = patch->next;3343}3344}33453346static intcheckout_target(struct index_state *istate,3347struct cache_entry *ce,struct stat *st)3348{3349struct checkout costate = CHECKOUT_INIT;33503351 costate.refresh_cache =1;3352 costate.istate = istate;3353if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3354returnerror(_("cannot checkout%s"), ce->name);3355return0;3356}33573358static struct patch *previous_patch(struct apply_state *state,3359struct patch *patch,3360int*gone)3361{3362struct patch *previous;33633364*gone =0;3365if(patch->is_copy || patch->is_rename)3366return NULL;/* "git" patches do not depend on the order */33673368 previous =in_fn_table(state, patch->old_name);3369if(!previous)3370return NULL;33713372if(to_be_deleted(previous))3373return NULL;/* the deletion hasn't happened yet */33743375if(was_deleted(previous))3376*gone =1;33773378return previous;3379}33803381static intverify_index_match(struct apply_state *state,3382const struct cache_entry *ce,3383struct stat *st)3384{3385if(S_ISGITLINK(ce->ce_mode)) {3386if(!S_ISDIR(st->st_mode))3387return-1;3388return0;3389}3390returnie_match_stat(state->repo->index, ce, st,3391 CE_MATCH_IGNORE_VALID | CE_MATCH_IGNORE_SKIP_WORKTREE);3392}33933394#define SUBMODULE_PATCH_WITHOUT_INDEX 133953396static intload_patch_target(struct apply_state *state,3397struct strbuf *buf,3398const struct cache_entry *ce,3399struct stat *st,3400struct patch *patch,3401const char*name,3402unsigned expected_mode)3403{3404if(state->cached || state->check_index) {3405if(read_file_or_gitlink(ce, buf))3406returnerror(_("failed to read%s"), name);3407}else if(name) {3408if(S_ISGITLINK(expected_mode)) {3409if(ce)3410returnread_file_or_gitlink(ce, buf);3411else3412return SUBMODULE_PATCH_WITHOUT_INDEX;3413}else if(has_symlink_leading_path(name,strlen(name))) {3414returnerror(_("reading from '%s' beyond a symbolic link"), name);3415}else{3416if(read_old_data(st, patch, name, buf))3417returnerror(_("failed to read%s"), name);3418}3419}3420return0;3421}34223423/*3424 * We are about to apply "patch"; populate the "image" with the3425 * current version we have, from the working tree or from the index,3426 * depending on the situation e.g. --cached/--index. If we are3427 * applying a non-git patch that incrementally updates the tree,3428 * we read from the result of a previous diff.3429 */3430static intload_preimage(struct apply_state *state,3431struct image *image,3432struct patch *patch,struct stat *st,3433const struct cache_entry *ce)3434{3435struct strbuf buf = STRBUF_INIT;3436size_t len;3437char*img;3438struct patch *previous;3439int status;34403441 previous =previous_patch(state, patch, &status);3442if(status)3443returnerror(_("path%shas been renamed/deleted"),3444 patch->old_name);3445if(previous) {3446/* We have a patched copy in memory; use that. */3447strbuf_add(&buf, previous->result, previous->resultsize);3448}else{3449 status =load_patch_target(state, &buf, ce, st, patch,3450 patch->old_name, patch->old_mode);3451if(status <0)3452return status;3453else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3454/*3455 * There is no way to apply subproject3456 * patch without looking at the index.3457 * NEEDSWORK: shouldn't this be flagged3458 * as an error???3459 */3460free_fragment_list(patch->fragments);3461 patch->fragments = NULL;3462}else if(status) {3463returnerror(_("failed to read%s"), patch->old_name);3464}3465}34663467 img =strbuf_detach(&buf, &len);3468prepare_image(image, img, len, !patch->is_binary);3469return0;3470}34713472static intthree_way_merge(struct image *image,3473char*path,3474const struct object_id *base,3475const struct object_id *ours,3476const struct object_id *theirs)3477{3478 mmfile_t base_file, our_file, their_file;3479 mmbuffer_t result = { NULL };3480int status;34813482read_mmblob(&base_file, base);3483read_mmblob(&our_file, ours);3484read_mmblob(&their_file, theirs);3485 status =ll_merge(&result, path,3486&base_file,"base",3487&our_file,"ours",3488&their_file,"theirs", NULL);3489free(base_file.ptr);3490free(our_file.ptr);3491free(their_file.ptr);3492if(status <0|| !result.ptr) {3493free(result.ptr);3494return-1;3495}3496clear_image(image);3497 image->buf = result.ptr;3498 image->len = result.size;34993500return status;3501}35023503/*3504 * When directly falling back to add/add three-way merge, we read from3505 * the current contents of the new_name. In no cases other than that3506 * this function will be called.3507 */3508static intload_current(struct apply_state *state,3509struct image *image,3510struct patch *patch)3511{3512struct strbuf buf = STRBUF_INIT;3513int status, pos;3514size_t len;3515char*img;3516struct stat st;3517struct cache_entry *ce;3518char*name = patch->new_name;3519unsigned mode = patch->new_mode;35203521if(!patch->is_new)3522BUG("patch to%sis not a creation", patch->old_name);35233524 pos =index_name_pos(state->repo->index, name,strlen(name));3525if(pos <0)3526returnerror(_("%s: does not exist in index"), name);3527 ce = state->repo->index->cache[pos];3528if(lstat(name, &st)) {3529if(errno != ENOENT)3530returnerror_errno("%s", name);3531if(checkout_target(state->repo->index, ce, &st))3532return-1;3533}3534if(verify_index_match(state, ce, &st))3535returnerror(_("%s: does not match index"), name);35363537 status =load_patch_target(state, &buf, ce, &st, patch, name, mode);3538if(status <0)3539return status;3540else if(status)3541return-1;3542 img =strbuf_detach(&buf, &len);3543prepare_image(image, img, len, !patch->is_binary);3544return0;3545}35463547static inttry_threeway(struct apply_state *state,3548struct image *image,3549struct patch *patch,3550struct stat *st,3551const struct cache_entry *ce)3552{3553struct object_id pre_oid, post_oid, our_oid;3554struct strbuf buf = STRBUF_INIT;3555size_t len;3556int status;3557char*img;3558struct image tmp_image;35593560/* No point falling back to 3-way merge in these cases */3561if(patch->is_delete ||3562S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3563return-1;35643565/* Preimage the patch was prepared for */3566if(patch->is_new)3567write_object_file("",0, blob_type, &pre_oid);3568else if(get_oid(patch->old_sha1_prefix, &pre_oid) ||3569read_blob_object(&buf, &pre_oid, patch->old_mode))3570returnerror(_("repository lacks the necessary blob to fall back on 3-way merge."));35713572if(state->apply_verbosity > verbosity_silent)3573fprintf(stderr,_("Falling back to three-way merge...\n"));35743575 img =strbuf_detach(&buf, &len);3576prepare_image(&tmp_image, img, len,1);3577/* Apply the patch to get the post image */3578if(apply_fragments(state, &tmp_image, patch) <0) {3579clear_image(&tmp_image);3580return-1;3581}3582/* post_oid is theirs */3583write_object_file(tmp_image.buf, tmp_image.len, blob_type, &post_oid);3584clear_image(&tmp_image);35853586/* our_oid is ours */3587if(patch->is_new) {3588if(load_current(state, &tmp_image, patch))3589returnerror(_("cannot read the current contents of '%s'"),3590 patch->new_name);3591}else{3592if(load_preimage(state, &tmp_image, patch, st, ce))3593returnerror(_("cannot read the current contents of '%s'"),3594 patch->old_name);3595}3596write_object_file(tmp_image.buf, tmp_image.len, blob_type, &our_oid);3597clear_image(&tmp_image);35983599/* in-core three-way merge between post and our using pre as base */3600 status =three_way_merge(image, patch->new_name,3601&pre_oid, &our_oid, &post_oid);3602if(status <0) {3603if(state->apply_verbosity > verbosity_silent)3604fprintf(stderr,3605_("Failed to fall back on three-way merge...\n"));3606return status;3607}36083609if(status) {3610 patch->conflicted_threeway =1;3611if(patch->is_new)3612oidclr(&patch->threeway_stage[0]);3613else3614oidcpy(&patch->threeway_stage[0], &pre_oid);3615oidcpy(&patch->threeway_stage[1], &our_oid);3616oidcpy(&patch->threeway_stage[2], &post_oid);3617if(state->apply_verbosity > verbosity_silent)3618fprintf(stderr,3619_("Applied patch to '%s' with conflicts.\n"),3620 patch->new_name);3621}else{3622if(state->apply_verbosity > verbosity_silent)3623fprintf(stderr,3624_("Applied patch to '%s' cleanly.\n"),3625 patch->new_name);3626}3627return0;3628}36293630static intapply_data(struct apply_state *state,struct patch *patch,3631struct stat *st,const struct cache_entry *ce)3632{3633struct image image;36343635if(load_preimage(state, &image, patch, st, ce) <0)3636return-1;36373638if(patch->direct_to_threeway ||3639apply_fragments(state, &image, patch) <0) {3640/* Note: with --reject, apply_fragments() returns 0 */3641if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3642return-1;3643}3644 patch->result = image.buf;3645 patch->resultsize = image.len;3646add_to_fn_table(state, patch);3647free(image.line_allocated);36483649if(0< patch->is_delete && patch->resultsize)3650returnerror(_("removal patch leaves file contents"));36513652return0;3653}36543655/*3656 * If "patch" that we are looking at modifies or deletes what we have,3657 * we would want it not to lose any local modification we have, either3658 * in the working tree or in the index.3659 *3660 * This also decides if a non-git patch is a creation patch or a3661 * modification to an existing empty file. We do not check the state3662 * of the current tree for a creation patch in this function; the caller3663 * check_patch() separately makes sure (and errors out otherwise) that3664 * the path the patch creates does not exist in the current tree.3665 */3666static intcheck_preimage(struct apply_state *state,3667struct patch *patch,3668struct cache_entry **ce,3669struct stat *st)3670{3671const char*old_name = patch->old_name;3672struct patch *previous = NULL;3673int stat_ret =0, status;3674unsigned st_mode =0;36753676if(!old_name)3677return0;36783679assert(patch->is_new <=0);3680 previous =previous_patch(state, patch, &status);36813682if(status)3683returnerror(_("path%shas been renamed/deleted"), old_name);3684if(previous) {3685 st_mode = previous->new_mode;3686}else if(!state->cached) {3687 stat_ret =lstat(old_name, st);3688if(stat_ret && errno != ENOENT)3689returnerror_errno("%s", old_name);3690}36913692if(state->check_index && !previous) {3693int pos =index_name_pos(state->repo->index, old_name,3694strlen(old_name));3695if(pos <0) {3696if(patch->is_new <0)3697goto is_new;3698returnerror(_("%s: does not exist in index"), old_name);3699}3700*ce = state->repo->index->cache[pos];3701if(stat_ret <0) {3702if(checkout_target(state->repo->index, *ce, st))3703return-1;3704}3705if(!state->cached &&verify_index_match(state, *ce, st))3706returnerror(_("%s: does not match index"), old_name);3707if(state->cached)3708 st_mode = (*ce)->ce_mode;3709}else if(stat_ret <0) {3710if(patch->is_new <0)3711goto is_new;3712returnerror_errno("%s", old_name);3713}37143715if(!state->cached && !previous)3716 st_mode =ce_mode_from_stat(*ce, st->st_mode);37173718if(patch->is_new <0)3719 patch->is_new =0;3720if(!patch->old_mode)3721 patch->old_mode = st_mode;3722if((st_mode ^ patch->old_mode) & S_IFMT)3723returnerror(_("%s: wrong type"), old_name);3724if(st_mode != patch->old_mode)3725warning(_("%shas type%o, expected%o"),3726 old_name, st_mode, patch->old_mode);3727if(!patch->new_mode && !patch->is_delete)3728 patch->new_mode = st_mode;3729return0;37303731 is_new:3732 patch->is_new =1;3733 patch->is_delete =0;3734FREE_AND_NULL(patch->old_name);3735return0;3736}373737383739#define EXISTS_IN_INDEX 13740#define EXISTS_IN_WORKTREE 237413742static intcheck_to_create(struct apply_state *state,3743const char*new_name,3744int ok_if_exists)3745{3746struct stat nst;37473748if(state->check_index &&3749index_name_pos(state->repo->index, new_name,strlen(new_name)) >=0&&3750!ok_if_exists)3751return EXISTS_IN_INDEX;3752if(state->cached)3753return0;37543755if(!lstat(new_name, &nst)) {3756if(S_ISDIR(nst.st_mode) || ok_if_exists)3757return0;3758/*3759 * A leading component of new_name might be a symlink3760 * that is going to be removed with this patch, but3761 * still pointing at somewhere that has the path.3762 * In such a case, path "new_name" does not exist as3763 * far as git is concerned.3764 */3765if(has_symlink_leading_path(new_name,strlen(new_name)))3766return0;37673768return EXISTS_IN_WORKTREE;3769}else if(!is_missing_file_error(errno)) {3770returnerror_errno("%s", new_name);3771}3772return0;3773}37743775static uintptr_tregister_symlink_changes(struct apply_state *state,3776const char*path,3777uintptr_t what)3778{3779struct string_list_item *ent;37803781 ent =string_list_lookup(&state->symlink_changes, path);3782if(!ent) {3783 ent =string_list_insert(&state->symlink_changes, path);3784 ent->util = (void*)0;3785}3786 ent->util = (void*)(what | ((uintptr_t)ent->util));3787return(uintptr_t)ent->util;3788}37893790static uintptr_tcheck_symlink_changes(struct apply_state *state,const char*path)3791{3792struct string_list_item *ent;37933794 ent =string_list_lookup(&state->symlink_changes, path);3795if(!ent)3796return0;3797return(uintptr_t)ent->util;3798}37993800static voidprepare_symlink_changes(struct apply_state *state,struct patch *patch)3801{3802for( ; patch; patch = patch->next) {3803if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3804(patch->is_rename || patch->is_delete))3805/* the symlink at patch->old_name is removed */3806register_symlink_changes(state, patch->old_name, APPLY_SYMLINK_GOES_AWAY);38073808if(patch->new_name &&S_ISLNK(patch->new_mode))3809/* the symlink at patch->new_name is created or remains */3810register_symlink_changes(state, patch->new_name, APPLY_SYMLINK_IN_RESULT);3811}3812}38133814static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3815{3816do{3817unsigned int change;38183819while(--name->len && name->buf[name->len] !='/')3820;/* scan backwards */3821if(!name->len)3822break;3823 name->buf[name->len] ='\0';3824 change =check_symlink_changes(state, name->buf);3825if(change & APPLY_SYMLINK_IN_RESULT)3826return1;3827if(change & APPLY_SYMLINK_GOES_AWAY)3828/*3829 * This cannot be "return 0", because we may3830 * see a new one created at a higher level.3831 */3832continue;38333834/* otherwise, check the preimage */3835if(state->check_index) {3836struct cache_entry *ce;38373838 ce =index_file_exists(state->repo->index, name->buf,3839 name->len, ignore_case);3840if(ce &&S_ISLNK(ce->ce_mode))3841return1;3842}else{3843struct stat st;3844if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3845return1;3846}3847}while(1);3848return0;3849}38503851static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3852{3853int ret;3854struct strbuf name = STRBUF_INIT;38553856assert(*name_ !='\0');3857strbuf_addstr(&name, name_);3858 ret =path_is_beyond_symlink_1(state, &name);3859strbuf_release(&name);38603861return ret;3862}38633864static intcheck_unsafe_path(struct patch *patch)3865{3866const char*old_name = NULL;3867const char*new_name = NULL;3868if(patch->is_delete)3869 old_name = patch->old_name;3870else if(!patch->is_new && !patch->is_copy)3871 old_name = patch->old_name;3872if(!patch->is_delete)3873 new_name = patch->new_name;38743875if(old_name && !verify_path(old_name, patch->old_mode))3876returnerror(_("invalid path '%s'"), old_name);3877if(new_name && !verify_path(new_name, patch->new_mode))3878returnerror(_("invalid path '%s'"), new_name);3879return0;3880}38813882/*3883 * Check and apply the patch in-core; leave the result in patch->result3884 * for the caller to write it out to the final destination.3885 */3886static intcheck_patch(struct apply_state *state,struct patch *patch)3887{3888struct stat st;3889const char*old_name = patch->old_name;3890const char*new_name = patch->new_name;3891const char*name = old_name ? old_name : new_name;3892struct cache_entry *ce = NULL;3893struct patch *tpatch;3894int ok_if_exists;3895int status;38963897 patch->rejected =1;/* we will drop this after we succeed */38983899 status =check_preimage(state, patch, &ce, &st);3900if(status)3901return status;3902 old_name = patch->old_name;39033904/*3905 * A type-change diff is always split into a patch to delete3906 * old, immediately followed by a patch to create new (see3907 * diff.c::run_diff()); in such a case it is Ok that the entry3908 * to be deleted by the previous patch is still in the working3909 * tree and in the index.3910 *3911 * A patch to swap-rename between A and B would first rename A3912 * to B and then rename B to A. While applying the first one,3913 * the presence of B should not stop A from getting renamed to3914 * B; ask to_be_deleted() about the later rename. Removal of3915 * B and rename from A to B is handled the same way by asking3916 * was_deleted().3917 */3918if((tpatch =in_fn_table(state, new_name)) &&3919(was_deleted(tpatch) ||to_be_deleted(tpatch)))3920 ok_if_exists =1;3921else3922 ok_if_exists =0;39233924if(new_name &&3925((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3926int err =check_to_create(state, new_name, ok_if_exists);39273928if(err && state->threeway) {3929 patch->direct_to_threeway =1;3930}else switch(err) {3931case0:3932break;/* happy */3933case EXISTS_IN_INDEX:3934returnerror(_("%s: already exists in index"), new_name);3935break;3936case EXISTS_IN_WORKTREE:3937returnerror(_("%s: already exists in working directory"),3938 new_name);3939default:3940return err;3941}39423943if(!patch->new_mode) {3944if(0< patch->is_new)3945 patch->new_mode = S_IFREG |0644;3946else3947 patch->new_mode = patch->old_mode;3948}3949}39503951if(new_name && old_name) {3952int same = !strcmp(old_name, new_name);3953if(!patch->new_mode)3954 patch->new_mode = patch->old_mode;3955if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3956if(same)3957returnerror(_("new mode (%o) of%sdoes not "3958"match old mode (%o)"),3959 patch->new_mode, new_name,3960 patch->old_mode);3961else3962returnerror(_("new mode (%o) of%sdoes not "3963"match old mode (%o) of%s"),3964 patch->new_mode, new_name,3965 patch->old_mode, old_name);3966}3967}39683969if(!state->unsafe_paths &&check_unsafe_path(patch))3970return-128;39713972/*3973 * An attempt to read from or delete a path that is beyond a3974 * symbolic link will be prevented by load_patch_target() that3975 * is called at the beginning of apply_data() so we do not3976 * have to worry about a patch marked with "is_delete" bit3977 * here. We however need to make sure that the patch result3978 * is not deposited to a path that is beyond a symbolic link3979 * here.3980 */3981if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3982returnerror(_("affected file '%s' is beyond a symbolic link"),3983 patch->new_name);39843985if(apply_data(state, patch, &st, ce) <0)3986returnerror(_("%s: patch does not apply"), name);3987 patch->rejected =0;3988return0;3989}39903991static intcheck_patch_list(struct apply_state *state,struct patch *patch)3992{3993int err =0;39943995prepare_symlink_changes(state, patch);3996prepare_fn_table(state, patch);3997while(patch) {3998int res;3999if(state->apply_verbosity > verbosity_normal)4000say_patch_name(stderr,4001_("Checking patch%s..."), patch);4002 res =check_patch(state, patch);4003if(res == -128)4004return-128;4005 err |= res;4006 patch = patch->next;4007}4008return err;4009}40104011static intread_apply_cache(struct apply_state *state)4012{4013if(state->index_file)4014returnread_index_from(state->repo->index, state->index_file,4015get_git_dir());4016else4017returnread_index(state->repo->index);4018}40194020/* This function tries to read the object name from the current index */4021static intget_current_oid(struct apply_state *state,const char*path,4022struct object_id *oid)4023{4024int pos;40254026if(read_apply_cache(state) <0)4027return-1;4028 pos =index_name_pos(state->repo->index, path,strlen(path));4029if(pos <0)4030return-1;4031oidcpy(oid, &state->repo->index->cache[pos]->oid);4032return0;4033}40344035static intpreimage_oid_in_gitlink_patch(struct patch *p,struct object_id *oid)4036{4037/*4038 * A usable gitlink patch has only one fragment (hunk) that looks like:4039 * @@ -1 +1 @@4040 * -Subproject commit <old sha1>4041 * +Subproject commit <new sha1>4042 * or4043 * @@ -1 +0,0 @@4044 * -Subproject commit <old sha1>4045 * for a removal patch.4046 */4047struct fragment *hunk = p->fragments;4048static const char heading[] ="-Subproject commit ";4049char*preimage;40504051if(/* does the patch have only one hunk? */4052 hunk && !hunk->next &&4053/* is its preimage one line? */4054 hunk->oldpos ==1&& hunk->oldlines ==1&&4055/* does preimage begin with the heading? */4056(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&4057starts_with(++preimage, heading) &&4058/* does it record full SHA-1? */4059!get_oid_hex(preimage +sizeof(heading) -1, oid) &&4060 preimage[sizeof(heading) + the_hash_algo->hexsz -1] =='\n'&&4061/* does the abbreviated name on the index line agree with it? */4062starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))4063return0;/* it all looks fine */40644065/* we may have full object name on the index line */4066returnget_oid_hex(p->old_sha1_prefix, oid);4067}40684069/* Build an index that contains just the files needed for a 3way merge */4070static intbuild_fake_ancestor(struct apply_state *state,struct patch *list)4071{4072struct patch *patch;4073struct index_state result = { NULL };4074struct lock_file lock = LOCK_INIT;4075int res;40764077/* Once we start supporting the reverse patch, it may be4078 * worth showing the new sha1 prefix, but until then...4079 */4080for(patch = list; patch; patch = patch->next) {4081struct object_id oid;4082struct cache_entry *ce;4083const char*name;40844085 name = patch->old_name ? patch->old_name : patch->new_name;4086if(0< patch->is_new)4087continue;40884089if(S_ISGITLINK(patch->old_mode)) {4090if(!preimage_oid_in_gitlink_patch(patch, &oid))4091;/* ok, the textual part looks sane */4092else4093returnerror(_("sha1 information is lacking or "4094"useless for submodule%s"), name);4095}else if(!get_oid_blob(patch->old_sha1_prefix, &oid)) {4096;/* ok */4097}else if(!patch->lines_added && !patch->lines_deleted) {4098/* mode-only change: update the current */4099if(get_current_oid(state, patch->old_name, &oid))4100returnerror(_("mode change for%s, which is not "4101"in current HEAD"), name);4102}else4103returnerror(_("sha1 information is lacking or useless "4104"(%s)."), name);41054106 ce =make_cache_entry(&result, patch->old_mode, &oid, name,0,0);4107if(!ce)4108returnerror(_("make_cache_entry failed for path '%s'"),4109 name);4110if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) {4111discard_cache_entry(ce);4112returnerror(_("could not add%sto temporary index"),4113 name);4114}4115}41164117hold_lock_file_for_update(&lock, state->fake_ancestor, LOCK_DIE_ON_ERROR);4118 res =write_locked_index(&result, &lock, COMMIT_LOCK);4119discard_index(&result);41204121if(res)4122returnerror(_("could not write temporary index to%s"),4123 state->fake_ancestor);41244125return0;4126}41274128static voidstat_patch_list(struct apply_state *state,struct patch *patch)4129{4130int files, adds, dels;41314132for(files = adds = dels =0; patch ; patch = patch->next) {4133 files++;4134 adds += patch->lines_added;4135 dels += patch->lines_deleted;4136show_stats(state, patch);4137}41384139print_stat_summary(stdout, files, adds, dels);4140}41414142static voidnumstat_patch_list(struct apply_state *state,4143struct patch *patch)4144{4145for( ; patch; patch = patch->next) {4146const char*name;4147 name = patch->new_name ? patch->new_name : patch->old_name;4148if(patch->is_binary)4149printf("-\t-\t");4150else4151printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4152write_name_quoted(name, stdout, state->line_termination);4153}4154}41554156static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4157{4158if(mode)4159printf("%smode%06o%s\n", newdelete, mode, name);4160else4161printf("%s %s\n", newdelete, name);4162}41634164static voidshow_mode_change(struct patch *p,int show_name)4165{4166if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4167if(show_name)4168printf(" mode change%06o =>%06o%s\n",4169 p->old_mode, p->new_mode, p->new_name);4170else4171printf(" mode change%06o =>%06o\n",4172 p->old_mode, p->new_mode);4173}4174}41754176static voidshow_rename_copy(struct patch *p)4177{4178const char*renamecopy = p->is_rename ?"rename":"copy";4179const char*old_name, *new_name;41804181/* Find common prefix */4182 old_name = p->old_name;4183 new_name = p->new_name;4184while(1) {4185const char*slash_old, *slash_new;4186 slash_old =strchr(old_name,'/');4187 slash_new =strchr(new_name,'/');4188if(!slash_old ||4189!slash_new ||4190 slash_old - old_name != slash_new - new_name ||4191memcmp(old_name, new_name, slash_new - new_name))4192break;4193 old_name = slash_old +1;4194 new_name = slash_new +1;4195}4196/* p->old_name thru old_name is the common prefix, and old_name and new_name4197 * through the end of names are renames4198 */4199if(old_name != p->old_name)4200printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4201(int)(old_name - p->old_name), p->old_name,4202 old_name, new_name, p->score);4203else4204printf("%s %s=>%s(%d%%)\n", renamecopy,4205 p->old_name, p->new_name, p->score);4206show_mode_change(p,0);4207}42084209static voidsummary_patch_list(struct patch *patch)4210{4211struct patch *p;42124213for(p = patch; p; p = p->next) {4214if(p->is_new)4215show_file_mode_name("create", p->new_mode, p->new_name);4216else if(p->is_delete)4217show_file_mode_name("delete", p->old_mode, p->old_name);4218else{4219if(p->is_rename || p->is_copy)4220show_rename_copy(p);4221else{4222if(p->score) {4223printf(" rewrite%s(%d%%)\n",4224 p->new_name, p->score);4225show_mode_change(p,0);4226}4227else4228show_mode_change(p,1);4229}4230}4231}4232}42334234static voidpatch_stats(struct apply_state *state,struct patch *patch)4235{4236int lines = patch->lines_added + patch->lines_deleted;42374238if(lines > state->max_change)4239 state->max_change = lines;4240if(patch->old_name) {4241int len =quote_c_style(patch->old_name, NULL, NULL,0);4242if(!len)4243 len =strlen(patch->old_name);4244if(len > state->max_len)4245 state->max_len = len;4246}4247if(patch->new_name) {4248int len =quote_c_style(patch->new_name, NULL, NULL,0);4249if(!len)4250 len =strlen(patch->new_name);4251if(len > state->max_len)4252 state->max_len = len;4253}4254}42554256static intremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4257{4258if(state->update_index && !state->ita_only) {4259if(remove_file_from_index(state->repo->index, patch->old_name) <0)4260returnerror(_("unable to remove%sfrom index"), patch->old_name);4261}4262if(!state->cached) {4263if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4264remove_path(patch->old_name);4265}4266}4267return0;4268}42694270static intadd_index_file(struct apply_state *state,4271const char*path,4272unsigned mode,4273void*buf,4274unsigned long size)4275{4276struct stat st;4277struct cache_entry *ce;4278int namelen =strlen(path);42794280 ce =make_empty_cache_entry(state->repo->index, namelen);4281memcpy(ce->name, path, namelen);4282 ce->ce_mode =create_ce_mode(mode);4283 ce->ce_flags =create_ce_flags(0);4284 ce->ce_namelen = namelen;4285if(state->ita_only) {4286 ce->ce_flags |= CE_INTENT_TO_ADD;4287set_object_name_for_intent_to_add_entry(ce);4288}else if(S_ISGITLINK(mode)) {4289const char*s;42904291if(!skip_prefix(buf,"Subproject commit ", &s) ||4292get_oid_hex(s, &ce->oid)) {4293discard_cache_entry(ce);4294returnerror(_("corrupt patch for submodule%s"), path);4295}4296}else{4297if(!state->cached) {4298if(lstat(path, &st) <0) {4299discard_cache_entry(ce);4300returnerror_errno(_("unable to stat newly "4301"created file '%s'"),4302 path);4303}4304fill_stat_cache_info(ce, &st);4305}4306if(write_object_file(buf, size, blob_type, &ce->oid) <0) {4307discard_cache_entry(ce);4308returnerror(_("unable to create backing store "4309"for newly created file%s"), path);4310}4311}4312if(add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) <0) {4313discard_cache_entry(ce);4314returnerror(_("unable to add cache entry for%s"), path);4315}43164317return0;4318}43194320/*4321 * Returns:4322 * -1 if an unrecoverable error happened4323 * 0 if everything went well4324 * 1 if a recoverable error happened4325 */4326static inttry_create_file(struct apply_state *state,const char*path,4327unsigned int mode,const char*buf,4328unsigned long size)4329{4330int fd, res;4331struct strbuf nbuf = STRBUF_INIT;43324333if(S_ISGITLINK(mode)) {4334struct stat st;4335if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4336return0;4337return!!mkdir(path,0777);4338}43394340if(has_symlinks &&S_ISLNK(mode))4341/* Although buf:size is counted string, it also is NUL4342 * terminated.4343 */4344return!!symlink(buf, path);43454346 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4347if(fd <0)4348return1;43494350if(convert_to_working_tree(state->repo->index, path, buf, size, &nbuf)) {4351 size = nbuf.len;4352 buf = nbuf.buf;4353}43544355 res =write_in_full(fd, buf, size) <0;4356if(res)4357error_errno(_("failed to write to '%s'"), path);4358strbuf_release(&nbuf);43594360if(close(fd) <0&& !res)4361returnerror_errno(_("closing file '%s'"), path);43624363return res ? -1:0;4364}43654366/*4367 * We optimistically assume that the directories exist,4368 * which is true 99% of the time anyway. If they don't,4369 * we create them and try again.4370 *4371 * Returns:4372 * -1 on error4373 * 0 otherwise4374 */4375static intcreate_one_file(struct apply_state *state,4376char*path,4377unsigned mode,4378const char*buf,4379unsigned long size)4380{4381int res;43824383if(state->cached)4384return0;43854386 res =try_create_file(state, path, mode, buf, size);4387if(res <0)4388return-1;4389if(!res)4390return0;43914392if(errno == ENOENT) {4393if(safe_create_leading_directories(path))4394return0;4395 res =try_create_file(state, path, mode, buf, size);4396if(res <0)4397return-1;4398if(!res)4399return0;4400}44014402if(errno == EEXIST || errno == EACCES) {4403/* We may be trying to create a file where a directory4404 * used to be.4405 */4406struct stat st;4407if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4408 errno = EEXIST;4409}44104411if(errno == EEXIST) {4412unsigned int nr =getpid();44134414for(;;) {4415char newpath[PATH_MAX];4416mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4417 res =try_create_file(state, newpath, mode, buf, size);4418if(res <0)4419return-1;4420if(!res) {4421if(!rename(newpath, path))4422return0;4423unlink_or_warn(newpath);4424break;4425}4426if(errno != EEXIST)4427break;4428++nr;4429}4430}4431returnerror_errno(_("unable to write file '%s' mode%o"),4432 path, mode);4433}44344435static intadd_conflicted_stages_file(struct apply_state *state,4436struct patch *patch)4437{4438int stage, namelen;4439unsigned mode;4440struct cache_entry *ce;44414442if(!state->update_index)4443return0;4444 namelen =strlen(patch->new_name);4445 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);44464447remove_file_from_index(state->repo->index, patch->new_name);4448for(stage =1; stage <4; stage++) {4449if(is_null_oid(&patch->threeway_stage[stage -1]))4450continue;4451 ce =make_empty_cache_entry(state->repo->index, namelen);4452memcpy(ce->name, patch->new_name, namelen);4453 ce->ce_mode =create_ce_mode(mode);4454 ce->ce_flags =create_ce_flags(stage);4455 ce->ce_namelen = namelen;4456oidcpy(&ce->oid, &patch->threeway_stage[stage -1]);4457if(add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) <0) {4458discard_cache_entry(ce);4459returnerror(_("unable to add cache entry for%s"),4460 patch->new_name);4461}4462}44634464return0;4465}44664467static intcreate_file(struct apply_state *state,struct patch *patch)4468{4469char*path = patch->new_name;4470unsigned mode = patch->new_mode;4471unsigned long size = patch->resultsize;4472char*buf = patch->result;44734474if(!mode)4475 mode = S_IFREG |0644;4476if(create_one_file(state, path, mode, buf, size))4477return-1;44784479if(patch->conflicted_threeway)4480returnadd_conflicted_stages_file(state, patch);4481else if(state->update_index)4482returnadd_index_file(state, path, mode, buf, size);4483return0;4484}44854486/* phase zero is to remove, phase one is to create */4487static intwrite_out_one_result(struct apply_state *state,4488struct patch *patch,4489int phase)4490{4491if(patch->is_delete >0) {4492if(phase ==0)4493returnremove_file(state, patch,1);4494return0;4495}4496if(patch->is_new >0|| patch->is_copy) {4497if(phase ==1)4498returncreate_file(state, patch);4499return0;4500}4501/*4502 * Rename or modification boils down to the same4503 * thing: remove the old, write the new4504 */4505if(phase ==0)4506returnremove_file(state, patch, patch->is_rename);4507if(phase ==1)4508returncreate_file(state, patch);4509return0;4510}45114512static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4513{4514FILE*rej;4515char namebuf[PATH_MAX];4516struct fragment *frag;4517int cnt =0;4518struct strbuf sb = STRBUF_INIT;45194520for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4521if(!frag->rejected)4522continue;4523 cnt++;4524}45254526if(!cnt) {4527if(state->apply_verbosity > verbosity_normal)4528say_patch_name(stderr,4529_("Applied patch%scleanly."), patch);4530return0;4531}45324533/* This should not happen, because a removal patch that leaves4534 * contents are marked "rejected" at the patch level.4535 */4536if(!patch->new_name)4537die(_("internal error"));45384539/* Say this even without --verbose */4540strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4541"Applying patch %%swith%drejects...",4542 cnt),4543 cnt);4544if(state->apply_verbosity > verbosity_silent)4545say_patch_name(stderr, sb.buf, patch);4546strbuf_release(&sb);45474548 cnt =strlen(patch->new_name);4549if(ARRAY_SIZE(namebuf) <= cnt +5) {4550 cnt =ARRAY_SIZE(namebuf) -5;4551warning(_("truncating .rej filename to %.*s.rej"),4552 cnt -1, patch->new_name);4553}4554memcpy(namebuf, patch->new_name, cnt);4555memcpy(namebuf + cnt,".rej",5);45564557 rej =fopen(namebuf,"w");4558if(!rej)4559returnerror_errno(_("cannot open%s"), namebuf);45604561/* Normal git tools never deal with .rej, so do not pretend4562 * this is a git patch by saying --git or giving extended4563 * headers. While at it, maybe please "kompare" that wants4564 * the trailing TAB and some garbage at the end of line ;-).4565 */4566fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4567 patch->new_name, patch->new_name);4568for(cnt =1, frag = patch->fragments;4569 frag;4570 cnt++, frag = frag->next) {4571if(!frag->rejected) {4572if(state->apply_verbosity > verbosity_silent)4573fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4574continue;4575}4576if(state->apply_verbosity > verbosity_silent)4577fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4578fprintf(rej,"%.*s", frag->size, frag->patch);4579if(frag->patch[frag->size-1] !='\n')4580fputc('\n', rej);4581}4582fclose(rej);4583return-1;4584}45854586/*4587 * Returns:4588 * -1 if an error happened4589 * 0 if the patch applied cleanly4590 * 1 if the patch did not apply cleanly4591 */4592static intwrite_out_results(struct apply_state *state,struct patch *list)4593{4594int phase;4595int errs =0;4596struct patch *l;4597struct string_list cpath = STRING_LIST_INIT_DUP;45984599for(phase =0; phase <2; phase++) {4600 l = list;4601while(l) {4602if(l->rejected)4603 errs =1;4604else{4605if(write_out_one_result(state, l, phase)) {4606string_list_clear(&cpath,0);4607return-1;4608}4609if(phase ==1) {4610if(write_out_one_reject(state, l))4611 errs =1;4612if(l->conflicted_threeway) {4613string_list_append(&cpath, l->new_name);4614 errs =1;4615}4616}4617}4618 l = l->next;4619}4620}46214622if(cpath.nr) {4623struct string_list_item *item;46244625string_list_sort(&cpath);4626if(state->apply_verbosity > verbosity_silent) {4627for_each_string_list_item(item, &cpath)4628fprintf(stderr,"U%s\n", item->string);4629}4630string_list_clear(&cpath,0);46314632rerere(0);4633}46344635return errs;4636}46374638/*4639 * Try to apply a patch.4640 *4641 * Returns:4642 * -128 if a bad error happened (like patch unreadable)4643 * -1 if patch did not apply and user cannot deal with it4644 * 0 if the patch applied4645 * 1 if the patch did not apply but user might fix it4646 */4647static intapply_patch(struct apply_state *state,4648int fd,4649const char*filename,4650int options)4651{4652size_t offset;4653struct strbuf buf = STRBUF_INIT;/* owns the patch text */4654struct patch *list = NULL, **listp = &list;4655int skipped_patch =0;4656int res =0;46574658 state->patch_input_file = filename;4659if(read_patch_file(&buf, fd) <0)4660return-128;4661 offset =0;4662while(offset < buf.len) {4663struct patch *patch;4664int nr;46654666 patch =xcalloc(1,sizeof(*patch));4667 patch->inaccurate_eof = !!(options & APPLY_OPT_INACCURATE_EOF);4668 patch->recount = !!(options & APPLY_OPT_RECOUNT);4669 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4670if(nr <0) {4671free_patch(patch);4672if(nr == -128) {4673 res = -128;4674goto end;4675}4676break;4677}4678if(state->apply_in_reverse)4679reverse_patches(patch);4680if(use_patch(state, patch)) {4681patch_stats(state, patch);4682*listp = patch;4683 listp = &patch->next;4684}4685else{4686if(state->apply_verbosity > verbosity_normal)4687say_patch_name(stderr,_("Skipped patch '%s'."), patch);4688free_patch(patch);4689 skipped_patch++;4690}4691 offset += nr;4692}46934694if(!list && !skipped_patch) {4695error(_("unrecognized input"));4696 res = -128;4697goto end;4698}46994700if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4701 state->apply =0;47024703 state->update_index = (state->check_index || state->ita_only) && state->apply;4704if(state->update_index && !is_lock_file_locked(&state->lock_file)) {4705if(state->index_file)4706hold_lock_file_for_update(&state->lock_file,4707 state->index_file,4708 LOCK_DIE_ON_ERROR);4709else4710hold_locked_index(&state->lock_file, LOCK_DIE_ON_ERROR);4711}47124713if(state->check_index &&read_apply_cache(state) <0) {4714error(_("unable to read index file"));4715 res = -128;4716goto end;4717}47184719if(state->check || state->apply) {4720int r =check_patch_list(state, list);4721if(r == -128) {4722 res = -128;4723goto end;4724}4725if(r <0&& !state->apply_with_reject) {4726 res = -1;4727goto end;4728}4729}47304731if(state->apply) {4732int write_res =write_out_results(state, list);4733if(write_res <0) {4734 res = -128;4735goto end;4736}4737if(write_res >0) {4738/* with --3way, we still need to write the index out */4739 res = state->apply_with_reject ? -1:1;4740goto end;4741}4742}47434744if(state->fake_ancestor &&4745build_fake_ancestor(state, list)) {4746 res = -128;4747goto end;4748}47494750if(state->diffstat && state->apply_verbosity > verbosity_silent)4751stat_patch_list(state, list);47524753if(state->numstat && state->apply_verbosity > verbosity_silent)4754numstat_patch_list(state, list);47554756if(state->summary && state->apply_verbosity > verbosity_silent)4757summary_patch_list(list);47584759end:4760free_patch_list(list);4761strbuf_release(&buf);4762string_list_clear(&state->fn_table,0);4763return res;4764}47654766static intapply_option_parse_exclude(const struct option *opt,4767const char*arg,int unset)4768{4769struct apply_state *state = opt->value;4770add_name_limit(state, arg,1);4771return0;4772}47734774static intapply_option_parse_include(const struct option *opt,4775const char*arg,int unset)4776{4777struct apply_state *state = opt->value;4778add_name_limit(state, arg,0);4779 state->has_include =1;4780return0;4781}47824783static intapply_option_parse_p(const struct option *opt,4784const char*arg,4785int unset)4786{4787struct apply_state *state = opt->value;4788 state->p_value =atoi(arg);4789 state->p_value_known =1;4790return0;4791}47924793static intapply_option_parse_space_change(const struct option *opt,4794const char*arg,int unset)4795{4796struct apply_state *state = opt->value;4797if(unset)4798 state->ws_ignore_action = ignore_ws_none;4799else4800 state->ws_ignore_action = ignore_ws_change;4801return0;4802}48034804static intapply_option_parse_whitespace(const struct option *opt,4805const char*arg,int unset)4806{4807struct apply_state *state = opt->value;4808 state->whitespace_option = arg;4809if(parse_whitespace_option(state, arg))4810exit(1);4811return0;4812}48134814static intapply_option_parse_directory(const struct option *opt,4815const char*arg,int unset)4816{4817struct apply_state *state = opt->value;4818strbuf_reset(&state->root);4819strbuf_addstr(&state->root, arg);4820strbuf_complete(&state->root,'/');4821return0;4822}48234824intapply_all_patches(struct apply_state *state,4825int argc,4826const char**argv,4827int options)4828{4829int i;4830int res;4831int errs =0;4832int read_stdin =1;48334834for(i =0; i < argc; i++) {4835const char*arg = argv[i];4836char*to_free = NULL;4837int fd;48384839if(!strcmp(arg,"-")) {4840 res =apply_patch(state,0,"<stdin>", options);4841if(res <0)4842goto end;4843 errs |= res;4844 read_stdin =0;4845continue;4846}else4847 arg = to_free =prefix_filename(state->prefix, arg);48484849 fd =open(arg, O_RDONLY);4850if(fd <0) {4851error(_("can't open patch '%s':%s"), arg,strerror(errno));4852 res = -128;4853free(to_free);4854goto end;4855}4856 read_stdin =0;4857set_default_whitespace_mode(state);4858 res =apply_patch(state, fd, arg, options);4859close(fd);4860free(to_free);4861if(res <0)4862goto end;4863 errs |= res;4864}4865set_default_whitespace_mode(state);4866if(read_stdin) {4867 res =apply_patch(state,0,"<stdin>", options);4868if(res <0)4869goto end;4870 errs |= res;4871}48724873if(state->whitespace_error) {4874if(state->squelch_whitespace_errors &&4875 state->squelch_whitespace_errors < state->whitespace_error) {4876int squelched =4877 state->whitespace_error - state->squelch_whitespace_errors;4878warning(Q_("squelched%dwhitespace error",4879"squelched%dwhitespace errors",4880 squelched),4881 squelched);4882}4883if(state->ws_error_action == die_on_ws_error) {4884error(Q_("%dline adds whitespace errors.",4885"%dlines add whitespace errors.",4886 state->whitespace_error),4887 state->whitespace_error);4888 res = -128;4889goto end;4890}4891if(state->applied_after_fixing_ws && state->apply)4892warning(Q_("%dline applied after"4893" fixing whitespace errors.",4894"%dlines applied after"4895" fixing whitespace errors.",4896 state->applied_after_fixing_ws),4897 state->applied_after_fixing_ws);4898else if(state->whitespace_error)4899warning(Q_("%dline adds whitespace errors.",4900"%dlines add whitespace errors.",4901 state->whitespace_error),4902 state->whitespace_error);4903}49044905if(state->update_index) {4906 res =write_locked_index(state->repo->index, &state->lock_file, COMMIT_LOCK);4907if(res) {4908error(_("Unable to write new index file"));4909 res = -128;4910goto end;4911}4912}49134914 res = !!errs;49154916end:4917rollback_lock_file(&state->lock_file);49184919if(state->apply_verbosity <= verbosity_silent) {4920set_error_routine(state->saved_error_routine);4921set_warn_routine(state->saved_warn_routine);4922}49234924if(res > -1)4925return res;4926return(res == -1?1:128);4927}49284929intapply_parse_options(int argc,const char**argv,4930struct apply_state *state,4931int*force_apply,int*options,4932const char*const*apply_usage)4933{4934struct option builtin_apply_options[] = {4935{ OPTION_CALLBACK,0,"exclude", state,N_("path"),4936N_("don't apply changes matching the given path"),49370, apply_option_parse_exclude },4938{ OPTION_CALLBACK,0,"include", state,N_("path"),4939N_("apply changes matching the given path"),49400, apply_option_parse_include },4941{ OPTION_CALLBACK,'p', NULL, state,N_("num"),4942N_("remove <num> leading slashes from traditional diff paths"),49430, apply_option_parse_p },4944OPT_BOOL(0,"no-add", &state->no_add,4945N_("ignore additions made by the patch")),4946OPT_BOOL(0,"stat", &state->diffstat,4947N_("instead of applying the patch, output diffstat for the input")),4948OPT_NOOP_NOARG(0,"allow-binary-replacement"),4949OPT_NOOP_NOARG(0,"binary"),4950OPT_BOOL(0,"numstat", &state->numstat,4951N_("show number of added and deleted lines in decimal notation")),4952OPT_BOOL(0,"summary", &state->summary,4953N_("instead of applying the patch, output a summary for the input")),4954OPT_BOOL(0,"check", &state->check,4955N_("instead of applying the patch, see if the patch is applicable")),4956OPT_BOOL(0,"index", &state->check_index,4957N_("make sure the patch is applicable to the current index")),4958OPT_BOOL('N',"intent-to-add", &state->ita_only,4959N_("mark new files with `git add --intent-to-add`")),4960OPT_BOOL(0,"cached", &state->cached,4961N_("apply a patch without touching the working tree")),4962OPT_BOOL_F(0,"unsafe-paths", &state->unsafe_paths,4963N_("accept a patch that touches outside the working area"),4964 PARSE_OPT_NOCOMPLETE),4965OPT_BOOL(0,"apply", force_apply,4966N_("also apply the patch (use with --stat/--summary/--check)")),4967OPT_BOOL('3',"3way", &state->threeway,4968N_("attempt three-way merge if a patch does not apply")),4969OPT_FILENAME(0,"build-fake-ancestor", &state->fake_ancestor,4970N_("build a temporary index based on embedded index information")),4971/* Think twice before adding "--nul" synonym to this */4972OPT_SET_INT('z', NULL, &state->line_termination,4973N_("paths are separated with NUL character"),'\0'),4974OPT_INTEGER('C', NULL, &state->p_context,4975N_("ensure at least <n> lines of context match")),4976{ OPTION_CALLBACK,0,"whitespace", state,N_("action"),4977N_("detect new or modified lines that have whitespace errors"),49780, apply_option_parse_whitespace },4979{ OPTION_CALLBACK,0,"ignore-space-change", state, NULL,4980N_("ignore changes in whitespace when finding context"),4981 PARSE_OPT_NOARG, apply_option_parse_space_change },4982{ OPTION_CALLBACK,0,"ignore-whitespace", state, NULL,4983N_("ignore changes in whitespace when finding context"),4984 PARSE_OPT_NOARG, apply_option_parse_space_change },4985OPT_BOOL('R',"reverse", &state->apply_in_reverse,4986N_("apply the patch in reverse")),4987OPT_BOOL(0,"unidiff-zero", &state->unidiff_zero,4988N_("don't expect at least one line of context")),4989OPT_BOOL(0,"reject", &state->apply_with_reject,4990N_("leave the rejected hunks in corresponding *.rej files")),4991OPT_BOOL(0,"allow-overlap", &state->allow_overlap,4992N_("allow overlapping hunks")),4993OPT__VERBOSE(&state->apply_verbosity,N_("be verbose")),4994OPT_BIT(0,"inaccurate-eof", options,4995N_("tolerate incorrectly detected missing new-line at the end of file"),4996 APPLY_OPT_INACCURATE_EOF),4997OPT_BIT(0,"recount", options,4998N_("do not trust the line counts in the hunk headers"),4999 APPLY_OPT_RECOUNT),5000{ OPTION_CALLBACK,0,"directory", state,N_("root"),5001N_("prepend <root> to all filenames"),50020, apply_option_parse_directory },5003OPT_END()5004};50055006returnparse_options(argc, argv, state->prefix, builtin_apply_options, apply_usage,0);5007}