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[41]; 227char new_sha1_prefix[41]; 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;10961097 ptr =strchr(line,'.');1098if(!ptr || ptr[1] !='.'||40< ptr - line)1099return0;1100 len = ptr - line;1101memcpy(patch->old_sha1_prefix, line, len);1102 patch->old_sha1_prefix[len] =0;11031104 line = ptr +2;1105 ptr =strchr(line,' ');1106 eol =strchrnul(line,'\n');11071108if(!ptr || eol < ptr)1109 ptr = eol;1110 len = ptr - line;11111112if(40< len)1113return0;1114memcpy(patch->new_sha1_prefix, line, len);1115 patch->new_sha1_prefix[len] =0;1116if(*ptr ==' ')1117returngitdiff_oldmode(state, ptr +1, patch);1118return0;1119}11201121/*1122 * This is normal for a diff that doesn't change anything: we'll fall through1123 * into the next diff. Tell the parser to break out.1124 */1125static intgitdiff_unrecognized(struct apply_state *state,1126const char*line,1127struct patch *patch)1128{1129return1;1130}11311132/*1133 * Skip p_value leading components from "line"; as we do not accept1134 * absolute paths, return NULL in that case.1135 */1136static const char*skip_tree_prefix(struct apply_state *state,1137const char*line,1138int llen)1139{1140int nslash;1141int i;11421143if(!state->p_value)1144return(llen && line[0] =='/') ? NULL : line;11451146 nslash = state->p_value;1147for(i =0; i < llen; i++) {1148int ch = line[i];1149if(ch =='/'&& --nslash <=0)1150return(i ==0) ? NULL : &line[i +1];1151}1152return NULL;1153}11541155/*1156 * This is to extract the same name that appears on "diff --git"1157 * line. We do not find and return anything if it is a rename1158 * patch, and it is OK because we will find the name elsewhere.1159 * We need to reliably find name only when it is mode-change only,1160 * creation or deletion of an empty file. In any of these cases,1161 * both sides are the same name under a/ and b/ respectively.1162 */1163static char*git_header_name(struct apply_state *state,1164const char*line,1165int llen)1166{1167const char*name;1168const char*second = NULL;1169size_t len, line_len;11701171 line +=strlen("diff --git ");1172 llen -=strlen("diff --git ");11731174if(*line =='"') {1175const char*cp;1176struct strbuf first = STRBUF_INIT;1177struct strbuf sp = STRBUF_INIT;11781179if(unquote_c_style(&first, line, &second))1180goto free_and_fail1;11811182/* strip the a/b prefix including trailing slash */1183 cp =skip_tree_prefix(state, first.buf, first.len);1184if(!cp)1185goto free_and_fail1;1186strbuf_remove(&first,0, cp - first.buf);11871188/*1189 * second points at one past closing dq of name.1190 * find the second name.1191 */1192while((second < line + llen) &&isspace(*second))1193 second++;11941195if(line + llen <= second)1196goto free_and_fail1;1197if(*second =='"') {1198if(unquote_c_style(&sp, second, NULL))1199goto free_and_fail1;1200 cp =skip_tree_prefix(state, sp.buf, sp.len);1201if(!cp)1202goto free_and_fail1;1203/* They must match, otherwise ignore */1204if(strcmp(cp, first.buf))1205goto free_and_fail1;1206strbuf_release(&sp);1207returnstrbuf_detach(&first, NULL);1208}12091210/* unquoted second */1211 cp =skip_tree_prefix(state, second, line + llen - second);1212if(!cp)1213goto free_and_fail1;1214if(line + llen - cp != first.len ||1215memcmp(first.buf, cp, first.len))1216goto free_and_fail1;1217returnstrbuf_detach(&first, NULL);12181219 free_and_fail1:1220strbuf_release(&first);1221strbuf_release(&sp);1222return NULL;1223}12241225/* unquoted first name */1226 name =skip_tree_prefix(state, line, llen);1227if(!name)1228return NULL;12291230/*1231 * since the first name is unquoted, a dq if exists must be1232 * the beginning of the second name.1233 */1234for(second = name; second < line + llen; second++) {1235if(*second =='"') {1236struct strbuf sp = STRBUF_INIT;1237const char*np;12381239if(unquote_c_style(&sp, second, NULL))1240goto free_and_fail2;12411242 np =skip_tree_prefix(state, sp.buf, sp.len);1243if(!np)1244goto free_and_fail2;12451246 len = sp.buf + sp.len - np;1247if(len < second - name &&1248!strncmp(np, name, len) &&1249isspace(name[len])) {1250/* Good */1251strbuf_remove(&sp,0, np - sp.buf);1252returnstrbuf_detach(&sp, NULL);1253}12541255 free_and_fail2:1256strbuf_release(&sp);1257return NULL;1258}1259}12601261/*1262 * Accept a name only if it shows up twice, exactly the same1263 * form.1264 */1265 second =strchr(name,'\n');1266if(!second)1267return NULL;1268 line_len = second - name;1269for(len =0; ; len++) {1270switch(name[len]) {1271default:1272continue;1273case'\n':1274return NULL;1275case'\t':case' ':1276/*1277 * Is this the separator between the preimage1278 * and the postimage pathname? Again, we are1279 * only interested in the case where there is1280 * no rename, as this is only to set def_name1281 * and a rename patch has the names elsewhere1282 * in an unambiguous form.1283 */1284if(!name[len +1])1285return NULL;/* no postimage name */1286 second =skip_tree_prefix(state, name + len +1,1287 line_len - (len +1));1288if(!second)1289return NULL;1290/*1291 * Does len bytes starting at "name" and "second"1292 * (that are separated by one HT or SP we just1293 * found) exactly match?1294 */1295if(second[len] =='\n'&& !strncmp(name, second, len))1296returnxmemdupz(name, len);1297}1298}1299}13001301static intcheck_header_line(struct apply_state *state,struct patch *patch)1302{1303int extensions = (patch->is_delete ==1) + (patch->is_new ==1) +1304(patch->is_rename ==1) + (patch->is_copy ==1);1305if(extensions >1)1306returnerror(_("inconsistent header lines%dand%d"),1307 patch->extension_linenr, state->linenr);1308if(extensions && !patch->extension_linenr)1309 patch->extension_linenr = state->linenr;1310return0;1311}13121313/* Verify that we recognize the lines following a git header */1314static intparse_git_header(struct apply_state *state,1315const char*line,1316int len,1317unsigned int size,1318struct patch *patch)1319{1320unsigned long offset;13211322/* A git diff has explicit new/delete information, so we don't guess */1323 patch->is_new =0;1324 patch->is_delete =0;13251326/*1327 * Some things may not have the old name in the1328 * rest of the headers anywhere (pure mode changes,1329 * or removing or adding empty files), so we get1330 * the default name from the header.1331 */1332 patch->def_name =git_header_name(state, line, len);1333if(patch->def_name && state->root.len) {1334char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1335free(patch->def_name);1336 patch->def_name = s;1337}13381339 line += len;1340 size -= len;1341 state->linenr++;1342for(offset = len ; size >0; offset += len, size -= len, line += len, state->linenr++) {1343static const struct opentry {1344const char*str;1345int(*fn)(struct apply_state *,const char*,struct patch *);1346} optable[] = {1347{"@@ -", gitdiff_hdrend },1348{"--- ", gitdiff_oldname },1349{"+++ ", gitdiff_newname },1350{"old mode ", gitdiff_oldmode },1351{"new mode ", gitdiff_newmode },1352{"deleted file mode ", gitdiff_delete },1353{"new file mode ", gitdiff_newfile },1354{"copy from ", gitdiff_copysrc },1355{"copy to ", gitdiff_copydst },1356{"rename old ", gitdiff_renamesrc },1357{"rename new ", gitdiff_renamedst },1358{"rename from ", gitdiff_renamesrc },1359{"rename to ", gitdiff_renamedst },1360{"similarity index ", gitdiff_similarity },1361{"dissimilarity index ", gitdiff_dissimilarity },1362{"index ", gitdiff_index },1363{"", gitdiff_unrecognized },1364};1365int i;13661367 len =linelen(line, size);1368if(!len || line[len-1] !='\n')1369break;1370for(i =0; i <ARRAY_SIZE(optable); i++) {1371const struct opentry *p = optable + i;1372int oplen =strlen(p->str);1373int res;1374if(len < oplen ||memcmp(p->str, line, oplen))1375continue;1376 res = p->fn(state, line + oplen, patch);1377if(res <0)1378return-1;1379if(check_header_line(state, patch))1380return-1;1381if(res >0)1382return offset;1383break;1384}1385}13861387return offset;1388}13891390static intparse_num(const char*line,unsigned long*p)1391{1392char*ptr;13931394if(!isdigit(*line))1395return0;1396*p =strtoul(line, &ptr,10);1397return ptr - line;1398}13991400static intparse_range(const char*line,int len,int offset,const char*expect,1401unsigned long*p1,unsigned long*p2)1402{1403int digits, ex;14041405if(offset <0|| offset >= len)1406return-1;1407 line += offset;1408 len -= offset;14091410 digits =parse_num(line, p1);1411if(!digits)1412return-1;14131414 offset += digits;1415 line += digits;1416 len -= digits;14171418*p2 =1;1419if(*line ==',') {1420 digits =parse_num(line+1, p2);1421if(!digits)1422return-1;14231424 offset += digits+1;1425 line += digits+1;1426 len -= digits+1;1427}14281429 ex =strlen(expect);1430if(ex > len)1431return-1;1432if(memcmp(line, expect, ex))1433return-1;14341435return offset + ex;1436}14371438static voidrecount_diff(const char*line,int size,struct fragment *fragment)1439{1440int oldlines =0, newlines =0, ret =0;14411442if(size <1) {1443warning("recount: ignore empty hunk");1444return;1445}14461447for(;;) {1448int len =linelen(line, size);1449 size -= len;1450 line += len;14511452if(size <1)1453break;14541455switch(*line) {1456case' ':case'\n':1457 newlines++;1458/* fall through */1459case'-':1460 oldlines++;1461continue;1462case'+':1463 newlines++;1464continue;1465case'\\':1466continue;1467case'@':1468 ret = size <3|| !starts_with(line,"@@ ");1469break;1470case'd':1471 ret = size <5|| !starts_with(line,"diff ");1472break;1473default:1474 ret = -1;1475break;1476}1477if(ret) {1478warning(_("recount: unexpected line: %.*s"),1479(int)linelen(line, size), line);1480return;1481}1482break;1483}1484 fragment->oldlines = oldlines;1485 fragment->newlines = newlines;1486}14871488/*1489 * Parse a unified diff fragment header of the1490 * form "@@ -a,b +c,d @@"1491 */1492static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1493{1494int offset;14951496if(!len || line[len-1] !='\n')1497return-1;14981499/* Figure out the number of lines in a fragment */1500 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1501 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);15021503return offset;1504}15051506/*1507 * Find file diff header1508 *1509 * Returns:1510 * -1 if no header was found1511 * -128 in case of error1512 * the size of the header in bytes (called "offset") otherwise1513 */1514static intfind_header(struct apply_state *state,1515const char*line,1516unsigned long size,1517int*hdrsize,1518struct patch *patch)1519{1520unsigned long offset, len;15211522 patch->is_toplevel_relative =0;1523 patch->is_rename = patch->is_copy =0;1524 patch->is_new = patch->is_delete = -1;1525 patch->old_mode = patch->new_mode =0;1526 patch->old_name = patch->new_name = NULL;1527for(offset =0; size >0; offset += len, size -= len, line += len, state->linenr++) {1528unsigned long nextlen;15291530 len =linelen(line, size);1531if(!len)1532break;15331534/* Testing this early allows us to take a few shortcuts.. */1535if(len <6)1536continue;15371538/*1539 * Make sure we don't find any unconnected patch fragments.1540 * That's a sign that we didn't find a header, and that a1541 * patch has become corrupted/broken up.1542 */1543if(!memcmp("@@ -", line,4)) {1544struct fragment dummy;1545if(parse_fragment_header(line, len, &dummy) <0)1546continue;1547error(_("patch fragment without header at line%d: %.*s"),1548 state->linenr, (int)len-1, line);1549return-128;1550}15511552if(size < len +6)1553break;15541555/*1556 * Git patch? It might not have a real patch, just a rename1557 * or mode change, so we handle that specially1558 */1559if(!memcmp("diff --git ", line,11)) {1560int git_hdr_len =parse_git_header(state, line, len, size, patch);1561if(git_hdr_len <0)1562return-128;1563if(git_hdr_len <= len)1564continue;1565if(!patch->old_name && !patch->new_name) {1566if(!patch->def_name) {1567error(Q_("git diff header lacks filename information when removing "1568"%dleading pathname component (line%d)",1569"git diff header lacks filename information when removing "1570"%dleading pathname components (line%d)",1571 state->p_value),1572 state->p_value, state->linenr);1573return-128;1574}1575 patch->old_name =xstrdup(patch->def_name);1576 patch->new_name =xstrdup(patch->def_name);1577}1578if((!patch->new_name && !patch->is_delete) ||1579(!patch->old_name && !patch->is_new)) {1580error(_("git diff header lacks filename information "1581"(line%d)"), state->linenr);1582return-128;1583}1584 patch->is_toplevel_relative =1;1585*hdrsize = git_hdr_len;1586return offset;1587}15881589/* --- followed by +++ ? */1590if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1591continue;15921593/*1594 * We only accept unified patches, so we want it to1595 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1596 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1597 */1598 nextlen =linelen(line + len, size - len);1599if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1600continue;16011602/* Ok, we'll consider it a patch */1603if(parse_traditional_patch(state, line, line+len, patch))1604return-128;1605*hdrsize = len + nextlen;1606 state->linenr +=2;1607return offset;1608}1609return-1;1610}16111612static voidrecord_ws_error(struct apply_state *state,1613unsigned result,1614const char*line,1615int len,1616int linenr)1617{1618char*err;16191620if(!result)1621return;16221623 state->whitespace_error++;1624if(state->squelch_whitespace_errors &&1625 state->squelch_whitespace_errors < state->whitespace_error)1626return;16271628 err =whitespace_error_string(result);1629if(state->apply_verbosity > verbosity_silent)1630fprintf(stderr,"%s:%d:%s.\n%.*s\n",1631 state->patch_input_file, linenr, err, len, line);1632free(err);1633}16341635static voidcheck_whitespace(struct apply_state *state,1636const char*line,1637int len,1638unsigned ws_rule)1639{1640unsigned result =ws_check(line +1, len -1, ws_rule);16411642record_ws_error(state, result, line +1, len -2, state->linenr);1643}16441645/*1646 * Check if the patch has context lines with CRLF or1647 * the patch wants to remove lines with CRLF.1648 */1649static voidcheck_old_for_crlf(struct patch *patch,const char*line,int len)1650{1651if(len >=2&& line[len-1] =='\n'&& line[len-2] =='\r') {1652 patch->ws_rule |= WS_CR_AT_EOL;1653 patch->crlf_in_old =1;1654}1655}165616571658/*1659 * Parse a unified diff. Note that this really needs to parse each1660 * fragment separately, since the only way to know the difference1661 * between a "---" that is part of a patch, and a "---" that starts1662 * the next patch is to look at the line counts..1663 */1664static intparse_fragment(struct apply_state *state,1665const char*line,1666unsigned long size,1667struct patch *patch,1668struct fragment *fragment)1669{1670int added, deleted;1671int len =linelen(line, size), offset;1672unsigned long oldlines, newlines;1673unsigned long leading, trailing;16741675 offset =parse_fragment_header(line, len, fragment);1676if(offset <0)1677return-1;1678if(offset >0&& patch->recount)1679recount_diff(line + offset, size - offset, fragment);1680 oldlines = fragment->oldlines;1681 newlines = fragment->newlines;1682 leading =0;1683 trailing =0;16841685/* Parse the thing.. */1686 line += len;1687 size -= len;1688 state->linenr++;1689 added = deleted =0;1690for(offset = len;16910< size;1692 offset += len, size -= len, line += len, state->linenr++) {1693if(!oldlines && !newlines)1694break;1695 len =linelen(line, size);1696if(!len || line[len-1] !='\n')1697return-1;1698switch(*line) {1699default:1700return-1;1701case'\n':/* newer GNU diff, an empty context line */1702case' ':1703 oldlines--;1704 newlines--;1705if(!deleted && !added)1706 leading++;1707 trailing++;1708check_old_for_crlf(patch, line, len);1709if(!state->apply_in_reverse &&1710 state->ws_error_action == correct_ws_error)1711check_whitespace(state, line, len, patch->ws_rule);1712break;1713case'-':1714if(!state->apply_in_reverse)1715check_old_for_crlf(patch, line, len);1716if(state->apply_in_reverse &&1717 state->ws_error_action != nowarn_ws_error)1718check_whitespace(state, line, len, patch->ws_rule);1719 deleted++;1720 oldlines--;1721 trailing =0;1722break;1723case'+':1724if(state->apply_in_reverse)1725check_old_for_crlf(patch, line, len);1726if(!state->apply_in_reverse &&1727 state->ws_error_action != nowarn_ws_error)1728check_whitespace(state, line, len, patch->ws_rule);1729 added++;1730 newlines--;1731 trailing =0;1732break;17331734/*1735 * We allow "\ No newline at end of file". Depending1736 * on locale settings when the patch was produced we1737 * don't know what this line looks like. The only1738 * thing we do know is that it begins with "\ ".1739 * Checking for 12 is just for sanity check -- any1740 * l10n of "\ No newline..." is at least that long.1741 */1742case'\\':1743if(len <12||memcmp(line,"\\",2))1744return-1;1745break;1746}1747}1748if(oldlines || newlines)1749return-1;1750if(!deleted && !added)1751return-1;17521753 fragment->leading = leading;1754 fragment->trailing = trailing;17551756/*1757 * If a fragment ends with an incomplete line, we failed to include1758 * it in the above loop because we hit oldlines == newlines == 01759 * before seeing it.1760 */1761if(12< size && !memcmp(line,"\\",2))1762 offset +=linelen(line, size);17631764 patch->lines_added += added;1765 patch->lines_deleted += deleted;17661767if(0< patch->is_new && oldlines)1768returnerror(_("new file depends on old contents"));1769if(0< patch->is_delete && newlines)1770returnerror(_("deleted file still has contents"));1771return offset;1772}17731774/*1775 * We have seen "diff --git a/... b/..." header (or a traditional patch1776 * header). Read hunks that belong to this patch into fragments and hang1777 * them to the given patch structure.1778 *1779 * The (fragment->patch, fragment->size) pair points into the memory given1780 * by the caller, not a copy, when we return.1781 *1782 * Returns:1783 * -1 in case of error,1784 * the number of bytes in the patch otherwise.1785 */1786static intparse_single_patch(struct apply_state *state,1787const char*line,1788unsigned long size,1789struct patch *patch)1790{1791unsigned long offset =0;1792unsigned long oldlines =0, newlines =0, context =0;1793struct fragment **fragp = &patch->fragments;17941795while(size >4&& !memcmp(line,"@@ -",4)) {1796struct fragment *fragment;1797int len;17981799 fragment =xcalloc(1,sizeof(*fragment));1800 fragment->linenr = state->linenr;1801 len =parse_fragment(state, line, size, patch, fragment);1802if(len <=0) {1803free(fragment);1804returnerror(_("corrupt patch at line%d"), state->linenr);1805}1806 fragment->patch = line;1807 fragment->size = len;1808 oldlines += fragment->oldlines;1809 newlines += fragment->newlines;1810 context += fragment->leading + fragment->trailing;18111812*fragp = fragment;1813 fragp = &fragment->next;18141815 offset += len;1816 line += len;1817 size -= len;1818}18191820/*1821 * If something was removed (i.e. we have old-lines) it cannot1822 * be creation, and if something was added it cannot be1823 * deletion. However, the reverse is not true; --unified=01824 * patches that only add are not necessarily creation even1825 * though they do not have any old lines, and ones that only1826 * delete are not necessarily deletion.1827 *1828 * Unfortunately, a real creation/deletion patch do _not_ have1829 * any context line by definition, so we cannot safely tell it1830 * apart with --unified=0 insanity. At least if the patch has1831 * more than one hunk it is not creation or deletion.1832 */1833if(patch->is_new <0&&1834(oldlines || (patch->fragments && patch->fragments->next)))1835 patch->is_new =0;1836if(patch->is_delete <0&&1837(newlines || (patch->fragments && patch->fragments->next)))1838 patch->is_delete =0;18391840if(0< patch->is_new && oldlines)1841returnerror(_("new file%sdepends on old contents"), patch->new_name);1842if(0< patch->is_delete && newlines)1843returnerror(_("deleted file%sstill has contents"), patch->old_name);1844if(!patch->is_delete && !newlines && context && state->apply_verbosity > verbosity_silent)1845fprintf_ln(stderr,1846_("** warning: "1847"file%sbecomes empty but is not deleted"),1848 patch->new_name);18491850return offset;1851}18521853staticinlineintmetadata_changes(struct patch *patch)1854{1855return patch->is_rename >0||1856 patch->is_copy >0||1857 patch->is_new >0||1858 patch->is_delete ||1859(patch->old_mode && patch->new_mode &&1860 patch->old_mode != patch->new_mode);1861}18621863static char*inflate_it(const void*data,unsigned long size,1864unsigned long inflated_size)1865{1866 git_zstream stream;1867void*out;1868int st;18691870memset(&stream,0,sizeof(stream));18711872 stream.next_in = (unsigned char*)data;1873 stream.avail_in = size;1874 stream.next_out = out =xmalloc(inflated_size);1875 stream.avail_out = inflated_size;1876git_inflate_init(&stream);1877 st =git_inflate(&stream, Z_FINISH);1878git_inflate_end(&stream);1879if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1880free(out);1881return NULL;1882}1883return out;1884}18851886/*1887 * Read a binary hunk and return a new fragment; fragment->patch1888 * points at an allocated memory that the caller must free, so1889 * it is marked as "->free_patch = 1".1890 */1891static struct fragment *parse_binary_hunk(struct apply_state *state,1892char**buf_p,1893unsigned long*sz_p,1894int*status_p,1895int*used_p)1896{1897/*1898 * Expect a line that begins with binary patch method ("literal"1899 * or "delta"), followed by the length of data before deflating.1900 * a sequence of 'length-byte' followed by base-85 encoded data1901 * should follow, terminated by a newline.1902 *1903 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1904 * and we would limit the patch line to 66 characters,1905 * so one line can fit up to 13 groups that would decode1906 * to 52 bytes max. The length byte 'A'-'Z' corresponds1907 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1908 */1909int llen, used;1910unsigned long size = *sz_p;1911char*buffer = *buf_p;1912int patch_method;1913unsigned long origlen;1914char*data = NULL;1915int hunk_size =0;1916struct fragment *frag;19171918 llen =linelen(buffer, size);1919 used = llen;19201921*status_p =0;19221923if(starts_with(buffer,"delta ")) {1924 patch_method = BINARY_DELTA_DEFLATED;1925 origlen =strtoul(buffer +6, NULL,10);1926}1927else if(starts_with(buffer,"literal ")) {1928 patch_method = BINARY_LITERAL_DEFLATED;1929 origlen =strtoul(buffer +8, NULL,10);1930}1931else1932return NULL;19331934 state->linenr++;1935 buffer += llen;1936while(1) {1937int byte_length, max_byte_length, newsize;1938 llen =linelen(buffer, size);1939 used += llen;1940 state->linenr++;1941if(llen ==1) {1942/* consume the blank line */1943 buffer++;1944 size--;1945break;1946}1947/*1948 * Minimum line is "A00000\n" which is 7-byte long,1949 * and the line length must be multiple of 5 plus 2.1950 */1951if((llen <7) || (llen-2) %5)1952goto corrupt;1953 max_byte_length = (llen -2) /5*4;1954 byte_length = *buffer;1955if('A'<= byte_length && byte_length <='Z')1956 byte_length = byte_length -'A'+1;1957else if('a'<= byte_length && byte_length <='z')1958 byte_length = byte_length -'a'+27;1959else1960goto corrupt;1961/* if the input length was not multiple of 4, we would1962 * have filler at the end but the filler should never1963 * exceed 3 bytes1964 */1965if(max_byte_length < byte_length ||1966 byte_length <= max_byte_length -4)1967goto corrupt;1968 newsize = hunk_size + byte_length;1969 data =xrealloc(data, newsize);1970if(decode_85(data + hunk_size, buffer +1, byte_length))1971goto corrupt;1972 hunk_size = newsize;1973 buffer += llen;1974 size -= llen;1975}19761977 frag =xcalloc(1,sizeof(*frag));1978 frag->patch =inflate_it(data, hunk_size, origlen);1979 frag->free_patch =1;1980if(!frag->patch)1981goto corrupt;1982free(data);1983 frag->size = origlen;1984*buf_p = buffer;1985*sz_p = size;1986*used_p = used;1987 frag->binary_patch_method = patch_method;1988return frag;19891990 corrupt:1991free(data);1992*status_p = -1;1993error(_("corrupt binary patch at line%d: %.*s"),1994 state->linenr-1, llen-1, buffer);1995return NULL;1996}19971998/*1999 * Returns:2000 * -1 in case of error,2001 * the length of the parsed binary patch otherwise2002 */2003static intparse_binary(struct apply_state *state,2004char*buffer,2005unsigned long size,2006struct patch *patch)2007{2008/*2009 * We have read "GIT binary patch\n"; what follows is a line2010 * that says the patch method (currently, either "literal" or2011 * "delta") and the length of data before deflating; a2012 * sequence of 'length-byte' followed by base-85 encoded data2013 * follows.2014 *2015 * When a binary patch is reversible, there is another binary2016 * hunk in the same format, starting with patch method (either2017 * "literal" or "delta") with the length of data, and a sequence2018 * of length-byte + base-85 encoded data, terminated with another2019 * empty line. This data, when applied to the postimage, produces2020 * the preimage.2021 */2022struct fragment *forward;2023struct fragment *reverse;2024int status;2025int used, used_1;20262027 forward =parse_binary_hunk(state, &buffer, &size, &status, &used);2028if(!forward && !status)2029/* there has to be one hunk (forward hunk) */2030returnerror(_("unrecognized binary patch at line%d"), state->linenr-1);2031if(status)2032/* otherwise we already gave an error message */2033return status;20342035 reverse =parse_binary_hunk(state, &buffer, &size, &status, &used_1);2036if(reverse)2037 used += used_1;2038else if(status) {2039/*2040 * Not having reverse hunk is not an error, but having2041 * a corrupt reverse hunk is.2042 */2043free((void*) forward->patch);2044free(forward);2045return status;2046}2047 forward->next = reverse;2048 patch->fragments = forward;2049 patch->is_binary =1;2050return used;2051}20522053static voidprefix_one(struct apply_state *state,char**name)2054{2055char*old_name = *name;2056if(!old_name)2057return;2058*name =prefix_filename(state->prefix, *name);2059free(old_name);2060}20612062static voidprefix_patch(struct apply_state *state,struct patch *p)2063{2064if(!state->prefix || p->is_toplevel_relative)2065return;2066prefix_one(state, &p->new_name);2067prefix_one(state, &p->old_name);2068}20692070/*2071 * include/exclude2072 */20732074static voidadd_name_limit(struct apply_state *state,2075const char*name,2076int exclude)2077{2078struct string_list_item *it;20792080 it =string_list_append(&state->limit_by_name, name);2081 it->util = exclude ? NULL : (void*)1;2082}20832084static intuse_patch(struct apply_state *state,struct patch *p)2085{2086const char*pathname = p->new_name ? p->new_name : p->old_name;2087int i;20882089/* Paths outside are not touched regardless of "--include" */2090if(state->prefix && *state->prefix) {2091const char*rest;2092if(!skip_prefix(pathname, state->prefix, &rest) || !*rest)2093return0;2094}20952096/* See if it matches any of exclude/include rule */2097for(i =0; i < state->limit_by_name.nr; i++) {2098struct string_list_item *it = &state->limit_by_name.items[i];2099if(!wildmatch(it->string, pathname,0))2100return(it->util != NULL);2101}21022103/*2104 * If we had any include, a path that does not match any rule is2105 * not used. Otherwise, we saw bunch of exclude rules (or none)2106 * and such a path is used.2107 */2108return!state->has_include;2109}21102111/*2112 * Read the patch text in "buffer" that extends for "size" bytes; stop2113 * reading after seeing a single patch (i.e. changes to a single file).2114 * Create fragments (i.e. patch hunks) and hang them to the given patch.2115 *2116 * Returns:2117 * -1 if no header was found or parse_binary() failed,2118 * -128 on another error,2119 * the number of bytes consumed otherwise,2120 * so that the caller can call us again for the next patch.2121 */2122static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2123{2124int hdrsize, patchsize;2125int offset =find_header(state, buffer, size, &hdrsize, patch);21262127if(offset <0)2128return offset;21292130prefix_patch(state, patch);21312132if(!use_patch(state, patch))2133 patch->ws_rule =0;2134else if(patch->new_name)2135 patch->ws_rule =whitespace_rule(state->repo->index,2136 patch->new_name);2137else2138 patch->ws_rule =whitespace_rule(state->repo->index,2139 patch->old_name);21402141 patchsize =parse_single_patch(state,2142 buffer + offset + hdrsize,2143 size - offset - hdrsize,2144 patch);21452146if(patchsize <0)2147return-128;21482149if(!patchsize) {2150static const char git_binary[] ="GIT binary patch\n";2151int hd = hdrsize + offset;2152unsigned long llen =linelen(buffer + hd, size - hd);21532154if(llen ==sizeof(git_binary) -1&&2155!memcmp(git_binary, buffer + hd, llen)) {2156int used;2157 state->linenr++;2158 used =parse_binary(state, buffer + hd + llen,2159 size - hd - llen, patch);2160if(used <0)2161return-1;2162if(used)2163 patchsize = used + llen;2164else2165 patchsize =0;2166}2167else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2168static const char*binhdr[] = {2169"Binary files ",2170"Files ",2171 NULL,2172};2173int i;2174for(i =0; binhdr[i]; i++) {2175int len =strlen(binhdr[i]);2176if(len < size - hd &&2177!memcmp(binhdr[i], buffer + hd, len)) {2178 state->linenr++;2179 patch->is_binary =1;2180 patchsize = llen;2181break;2182}2183}2184}21852186/* Empty patch cannot be applied if it is a text patch2187 * without metadata change. A binary patch appears2188 * empty to us here.2189 */2190if((state->apply || state->check) &&2191(!patch->is_binary && !metadata_changes(patch))) {2192error(_("patch with only garbage at line%d"), state->linenr);2193return-128;2194}2195}21962197return offset + hdrsize + patchsize;2198}21992200static voidreverse_patches(struct patch *p)2201{2202for(; p; p = p->next) {2203struct fragment *frag = p->fragments;22042205SWAP(p->new_name, p->old_name);2206SWAP(p->new_mode, p->old_mode);2207SWAP(p->is_new, p->is_delete);2208SWAP(p->lines_added, p->lines_deleted);2209SWAP(p->old_sha1_prefix, p->new_sha1_prefix);22102211for(; frag; frag = frag->next) {2212SWAP(frag->newpos, frag->oldpos);2213SWAP(frag->newlines, frag->oldlines);2214}2215}2216}22172218static const char pluses[] =2219"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2220static const char minuses[]=2221"----------------------------------------------------------------------";22222223static voidshow_stats(struct apply_state *state,struct patch *patch)2224{2225struct strbuf qname = STRBUF_INIT;2226char*cp = patch->new_name ? patch->new_name : patch->old_name;2227int max, add, del;22282229quote_c_style(cp, &qname, NULL,0);22302231/*2232 * "scale" the filename2233 */2234 max = state->max_len;2235if(max >50)2236 max =50;22372238if(qname.len > max) {2239 cp =strchr(qname.buf + qname.len +3- max,'/');2240if(!cp)2241 cp = qname.buf + qname.len +3- max;2242strbuf_splice(&qname,0, cp - qname.buf,"...",3);2243}22442245if(patch->is_binary) {2246printf(" %-*s | Bin\n", max, qname.buf);2247strbuf_release(&qname);2248return;2249}22502251printf(" %-*s |", max, qname.buf);2252strbuf_release(&qname);22532254/*2255 * scale the add/delete2256 */2257 max = max + state->max_change >70?70- max : state->max_change;2258 add = patch->lines_added;2259 del = patch->lines_deleted;22602261if(state->max_change >0) {2262int total = ((add + del) * max + state->max_change /2) / state->max_change;2263 add = (add * max + state->max_change /2) / state->max_change;2264 del = total - add;2265}2266printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2267 add, pluses, del, minuses);2268}22692270static intread_old_data(struct stat *st,struct patch *patch,2271const char*path,struct strbuf *buf)2272{2273int conv_flags = patch->crlf_in_old ?2274 CONV_EOL_KEEP_CRLF : CONV_EOL_RENORMALIZE;2275switch(st->st_mode & S_IFMT) {2276case S_IFLNK:2277if(strbuf_readlink(buf, path, st->st_size) <0)2278returnerror(_("unable to read symlink%s"), path);2279return0;2280case S_IFREG:2281if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2282returnerror(_("unable to open or read%s"), path);2283/*2284 * "git apply" without "--index/--cached" should never look2285 * at the index; the target file may not have been added to2286 * the index yet, and we may not even be in any Git repository.2287 * Pass NULL to convert_to_git() to stress this; the function2288 * should never look at the index when explicit crlf option2289 * is given.2290 */2291convert_to_git(NULL, path, buf->buf, buf->len, buf, conv_flags);2292return0;2293default:2294return-1;2295}2296}22972298/*2299 * Update the preimage, and the common lines in postimage,2300 * from buffer buf of length len. If postlen is 0 the postimage2301 * is updated in place, otherwise it's updated on a new buffer2302 * of length postlen2303 */23042305static voidupdate_pre_post_images(struct image *preimage,2306struct image *postimage,2307char*buf,2308size_t len,size_t postlen)2309{2310int i, ctx, reduced;2311char*new_buf, *old_buf, *fixed;2312struct image fixed_preimage;23132314/*2315 * Update the preimage with whitespace fixes. Note that we2316 * are not losing preimage->buf -- apply_one_fragment() will2317 * free "oldlines".2318 */2319prepare_image(&fixed_preimage, buf, len,1);2320assert(postlen2321? fixed_preimage.nr == preimage->nr2322: fixed_preimage.nr <= preimage->nr);2323for(i =0; i < fixed_preimage.nr; i++)2324 fixed_preimage.line[i].flag = preimage->line[i].flag;2325free(preimage->line_allocated);2326*preimage = fixed_preimage;23272328/*2329 * Adjust the common context lines in postimage. This can be2330 * done in-place when we are shrinking it with whitespace2331 * fixing, but needs a new buffer when ignoring whitespace or2332 * expanding leading tabs to spaces.2333 *2334 * We trust the caller to tell us if the update can be done2335 * in place (postlen==0) or not.2336 */2337 old_buf = postimage->buf;2338if(postlen)2339 new_buf = postimage->buf =xmalloc(postlen);2340else2341 new_buf = old_buf;2342 fixed = preimage->buf;23432344for(i = reduced = ctx =0; i < postimage->nr; i++) {2345size_t l_len = postimage->line[i].len;2346if(!(postimage->line[i].flag & LINE_COMMON)) {2347/* an added line -- no counterparts in preimage */2348memmove(new_buf, old_buf, l_len);2349 old_buf += l_len;2350 new_buf += l_len;2351continue;2352}23532354/* a common context -- skip it in the original postimage */2355 old_buf += l_len;23562357/* and find the corresponding one in the fixed preimage */2358while(ctx < preimage->nr &&2359!(preimage->line[ctx].flag & LINE_COMMON)) {2360 fixed += preimage->line[ctx].len;2361 ctx++;2362}23632364/*2365 * preimage is expected to run out, if the caller2366 * fixed addition of trailing blank lines.2367 */2368if(preimage->nr <= ctx) {2369 reduced++;2370continue;2371}23722373/* and copy it in, while fixing the line length */2374 l_len = preimage->line[ctx].len;2375memcpy(new_buf, fixed, l_len);2376 new_buf += l_len;2377 fixed += l_len;2378 postimage->line[i].len = l_len;2379 ctx++;2380}23812382if(postlen2383? postlen < new_buf - postimage->buf2384: postimage->len < new_buf - postimage->buf)2385BUG("caller miscounted postlen: asked%d, orig =%d, used =%d",2386(int)postlen, (int) postimage->len, (int)(new_buf - postimage->buf));23872388/* Fix the length of the whole thing */2389 postimage->len = new_buf - postimage->buf;2390 postimage->nr -= reduced;2391}23922393static intline_by_line_fuzzy_match(struct image *img,2394struct image *preimage,2395struct image *postimage,2396unsigned long current,2397int current_lno,2398int preimage_limit)2399{2400int i;2401size_t imgoff =0;2402size_t preoff =0;2403size_t postlen = postimage->len;2404size_t extra_chars;2405char*buf;2406char*preimage_eof;2407char*preimage_end;2408struct strbuf fixed;2409char*fixed_buf;2410size_t fixed_len;24112412for(i =0; i < preimage_limit; i++) {2413size_t prelen = preimage->line[i].len;2414size_t imglen = img->line[current_lno+i].len;24152416if(!fuzzy_matchlines(img->buf + current + imgoff, imglen,2417 preimage->buf + preoff, prelen))2418return0;2419if(preimage->line[i].flag & LINE_COMMON)2420 postlen += imglen - prelen;2421 imgoff += imglen;2422 preoff += prelen;2423}24242425/*2426 * Ok, the preimage matches with whitespace fuzz.2427 *2428 * imgoff now holds the true length of the target that2429 * matches the preimage before the end of the file.2430 *2431 * Count the number of characters in the preimage that fall2432 * beyond the end of the file and make sure that all of them2433 * are whitespace characters. (This can only happen if2434 * we are removing blank lines at the end of the file.)2435 */2436 buf = preimage_eof = preimage->buf + preoff;2437for( ; i < preimage->nr; i++)2438 preoff += preimage->line[i].len;2439 preimage_end = preimage->buf + preoff;2440for( ; buf < preimage_end; buf++)2441if(!isspace(*buf))2442return0;24432444/*2445 * Update the preimage and the common postimage context2446 * lines to use the same whitespace as the target.2447 * If whitespace is missing in the target (i.e.2448 * if the preimage extends beyond the end of the file),2449 * use the whitespace from the preimage.2450 */2451 extra_chars = preimage_end - preimage_eof;2452strbuf_init(&fixed, imgoff + extra_chars);2453strbuf_add(&fixed, img->buf + current, imgoff);2454strbuf_add(&fixed, preimage_eof, extra_chars);2455 fixed_buf =strbuf_detach(&fixed, &fixed_len);2456update_pre_post_images(preimage, postimage,2457 fixed_buf, fixed_len, postlen);2458return1;2459}24602461static intmatch_fragment(struct apply_state *state,2462struct image *img,2463struct image *preimage,2464struct image *postimage,2465unsigned long current,2466int current_lno,2467unsigned ws_rule,2468int match_beginning,int match_end)2469{2470int i;2471char*fixed_buf, *buf, *orig, *target;2472struct strbuf fixed;2473size_t fixed_len, postlen;2474int preimage_limit;24752476if(preimage->nr + current_lno <= img->nr) {2477/*2478 * The hunk falls within the boundaries of img.2479 */2480 preimage_limit = preimage->nr;2481if(match_end && (preimage->nr + current_lno != img->nr))2482return0;2483}else if(state->ws_error_action == correct_ws_error &&2484(ws_rule & WS_BLANK_AT_EOF)) {2485/*2486 * This hunk extends beyond the end of img, and we are2487 * removing blank lines at the end of the file. This2488 * many lines from the beginning of the preimage must2489 * match with img, and the remainder of the preimage2490 * must be blank.2491 */2492 preimage_limit = img->nr - current_lno;2493}else{2494/*2495 * The hunk extends beyond the end of the img and2496 * we are not removing blanks at the end, so we2497 * should reject the hunk at this position.2498 */2499return0;2500}25012502if(match_beginning && current_lno)2503return0;25042505/* Quick hash check */2506for(i =0; i < preimage_limit; i++)2507if((img->line[current_lno + i].flag & LINE_PATCHED) ||2508(preimage->line[i].hash != img->line[current_lno + i].hash))2509return0;25102511if(preimage_limit == preimage->nr) {2512/*2513 * Do we have an exact match? If we were told to match2514 * at the end, size must be exactly at current+fragsize,2515 * otherwise current+fragsize must be still within the preimage,2516 * and either case, the old piece should match the preimage2517 * exactly.2518 */2519if((match_end2520? (current + preimage->len == img->len)2521: (current + preimage->len <= img->len)) &&2522!memcmp(img->buf + current, preimage->buf, preimage->len))2523return1;2524}else{2525/*2526 * The preimage extends beyond the end of img, so2527 * there cannot be an exact match.2528 *2529 * There must be one non-blank context line that match2530 * a line before the end of img.2531 */2532char*buf_end;25332534 buf = preimage->buf;2535 buf_end = buf;2536for(i =0; i < preimage_limit; i++)2537 buf_end += preimage->line[i].len;25382539for( ; buf < buf_end; buf++)2540if(!isspace(*buf))2541break;2542if(buf == buf_end)2543return0;2544}25452546/*2547 * No exact match. If we are ignoring whitespace, run a line-by-line2548 * fuzzy matching. We collect all the line length information because2549 * we need it to adjust whitespace if we match.2550 */2551if(state->ws_ignore_action == ignore_ws_change)2552returnline_by_line_fuzzy_match(img, preimage, postimage,2553 current, current_lno, preimage_limit);25542555if(state->ws_error_action != correct_ws_error)2556return0;25572558/*2559 * The hunk does not apply byte-by-byte, but the hash says2560 * it might with whitespace fuzz. We weren't asked to2561 * ignore whitespace, we were asked to correct whitespace2562 * errors, so let's try matching after whitespace correction.2563 *2564 * While checking the preimage against the target, whitespace2565 * errors in both fixed, we count how large the corresponding2566 * postimage needs to be. The postimage prepared by2567 * apply_one_fragment() has whitespace errors fixed on added2568 * lines already, but the common lines were propagated as-is,2569 * which may become longer when their whitespace errors are2570 * fixed.2571 */25722573/* First count added lines in postimage */2574 postlen =0;2575for(i =0; i < postimage->nr; i++) {2576if(!(postimage->line[i].flag & LINE_COMMON))2577 postlen += postimage->line[i].len;2578}25792580/*2581 * The preimage may extend beyond the end of the file,2582 * but in this loop we will only handle the part of the2583 * preimage that falls within the file.2584 */2585strbuf_init(&fixed, preimage->len +1);2586 orig = preimage->buf;2587 target = img->buf + current;2588for(i =0; i < preimage_limit; i++) {2589size_t oldlen = preimage->line[i].len;2590size_t tgtlen = img->line[current_lno + i].len;2591size_t fixstart = fixed.len;2592struct strbuf tgtfix;2593int match;25942595/* Try fixing the line in the preimage */2596ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25972598/* Try fixing the line in the target */2599strbuf_init(&tgtfix, tgtlen);2600ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);26012602/*2603 * If they match, either the preimage was based on2604 * a version before our tree fixed whitespace breakage,2605 * or we are lacking a whitespace-fix patch the tree2606 * the preimage was based on already had (i.e. target2607 * has whitespace breakage, the preimage doesn't).2608 * In either case, we are fixing the whitespace breakages2609 * so we might as well take the fix together with their2610 * real change.2611 */2612 match = (tgtfix.len == fixed.len - fixstart &&2613!memcmp(tgtfix.buf, fixed.buf + fixstart,2614 fixed.len - fixstart));26152616/* Add the length if this is common with the postimage */2617if(preimage->line[i].flag & LINE_COMMON)2618 postlen += tgtfix.len;26192620strbuf_release(&tgtfix);2621if(!match)2622goto unmatch_exit;26232624 orig += oldlen;2625 target += tgtlen;2626}262726282629/*2630 * Now handle the lines in the preimage that falls beyond the2631 * end of the file (if any). They will only match if they are2632 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2633 * false).2634 */2635for( ; i < preimage->nr; i++) {2636size_t fixstart = fixed.len;/* start of the fixed preimage */2637size_t oldlen = preimage->line[i].len;2638int j;26392640/* Try fixing the line in the preimage */2641ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);26422643for(j = fixstart; j < fixed.len; j++)2644if(!isspace(fixed.buf[j]))2645goto unmatch_exit;26462647 orig += oldlen;2648}26492650/*2651 * Yes, the preimage is based on an older version that still2652 * has whitespace breakages unfixed, and fixing them makes the2653 * hunk match. Update the context lines in the postimage.2654 */2655 fixed_buf =strbuf_detach(&fixed, &fixed_len);2656if(postlen < postimage->len)2657 postlen =0;2658update_pre_post_images(preimage, postimage,2659 fixed_buf, fixed_len, postlen);2660return1;26612662 unmatch_exit:2663strbuf_release(&fixed);2664return0;2665}26662667static intfind_pos(struct apply_state *state,2668struct image *img,2669struct image *preimage,2670struct image *postimage,2671int line,2672unsigned ws_rule,2673int match_beginning,int match_end)2674{2675int i;2676unsigned long backwards, forwards, current;2677int backwards_lno, forwards_lno, current_lno;26782679/*2680 * If match_beginning or match_end is specified, there is no2681 * point starting from a wrong line that will never match and2682 * wander around and wait for a match at the specified end.2683 */2684if(match_beginning)2685 line =0;2686else if(match_end)2687 line = img->nr - preimage->nr;26882689/*2690 * Because the comparison is unsigned, the following test2691 * will also take care of a negative line number that can2692 * result when match_end and preimage is larger than the target.2693 */2694if((size_t) line > img->nr)2695 line = img->nr;26962697 current =0;2698for(i =0; i < line; i++)2699 current += img->line[i].len;27002701/*2702 * There's probably some smart way to do this, but I'll leave2703 * that to the smart and beautiful people. I'm simple and stupid.2704 */2705 backwards = current;2706 backwards_lno = line;2707 forwards = current;2708 forwards_lno = line;2709 current_lno = line;27102711for(i =0; ; i++) {2712if(match_fragment(state, img, preimage, postimage,2713 current, current_lno, ws_rule,2714 match_beginning, match_end))2715return current_lno;27162717 again:2718if(backwards_lno ==0&& forwards_lno == img->nr)2719break;27202721if(i &1) {2722if(backwards_lno ==0) {2723 i++;2724goto again;2725}2726 backwards_lno--;2727 backwards -= img->line[backwards_lno].len;2728 current = backwards;2729 current_lno = backwards_lno;2730}else{2731if(forwards_lno == img->nr) {2732 i++;2733goto again;2734}2735 forwards += img->line[forwards_lno].len;2736 forwards_lno++;2737 current = forwards;2738 current_lno = forwards_lno;2739}27402741}2742return-1;2743}27442745static voidremove_first_line(struct image *img)2746{2747 img->buf += img->line[0].len;2748 img->len -= img->line[0].len;2749 img->line++;2750 img->nr--;2751}27522753static voidremove_last_line(struct image *img)2754{2755 img->len -= img->line[--img->nr].len;2756}27572758/*2759 * The change from "preimage" and "postimage" has been found to2760 * apply at applied_pos (counts in line numbers) in "img".2761 * Update "img" to remove "preimage" and replace it with "postimage".2762 */2763static voidupdate_image(struct apply_state *state,2764struct image *img,2765int applied_pos,2766struct image *preimage,2767struct image *postimage)2768{2769/*2770 * remove the copy of preimage at offset in img2771 * and replace it with postimage2772 */2773int i, nr;2774size_t remove_count, insert_count, applied_at =0;2775char*result;2776int preimage_limit;27772778/*2779 * If we are removing blank lines at the end of img,2780 * the preimage may extend beyond the end.2781 * If that is the case, we must be careful only to2782 * remove the part of the preimage that falls within2783 * the boundaries of img. Initialize preimage_limit2784 * to the number of lines in the preimage that falls2785 * within the boundaries.2786 */2787 preimage_limit = preimage->nr;2788if(preimage_limit > img->nr - applied_pos)2789 preimage_limit = img->nr - applied_pos;27902791for(i =0; i < applied_pos; i++)2792 applied_at += img->line[i].len;27932794 remove_count =0;2795for(i =0; i < preimage_limit; i++)2796 remove_count += img->line[applied_pos + i].len;2797 insert_count = postimage->len;27982799/* Adjust the contents */2800 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2801memcpy(result, img->buf, applied_at);2802memcpy(result + applied_at, postimage->buf, postimage->len);2803memcpy(result + applied_at + postimage->len,2804 img->buf + (applied_at + remove_count),2805 img->len - (applied_at + remove_count));2806free(img->buf);2807 img->buf = result;2808 img->len += insert_count - remove_count;2809 result[img->len] ='\0';28102811/* Adjust the line table */2812 nr = img->nr + postimage->nr - preimage_limit;2813if(preimage_limit < postimage->nr) {2814/*2815 * NOTE: this knows that we never call remove_first_line()2816 * on anything other than pre/post image.2817 */2818REALLOC_ARRAY(img->line, nr);2819 img->line_allocated = img->line;2820}2821if(preimage_limit != postimage->nr)2822MOVE_ARRAY(img->line + applied_pos + postimage->nr,2823 img->line + applied_pos + preimage_limit,2824 img->nr - (applied_pos + preimage_limit));2825COPY_ARRAY(img->line + applied_pos, postimage->line, postimage->nr);2826if(!state->allow_overlap)2827for(i =0; i < postimage->nr; i++)2828 img->line[applied_pos + i].flag |= LINE_PATCHED;2829 img->nr = nr;2830}28312832/*2833 * Use the patch-hunk text in "frag" to prepare two images (preimage and2834 * postimage) for the hunk. Find lines that match "preimage" in "img" and2835 * replace the part of "img" with "postimage" text.2836 */2837static intapply_one_fragment(struct apply_state *state,2838struct image *img,struct fragment *frag,2839int inaccurate_eof,unsigned ws_rule,2840int nth_fragment)2841{2842int match_beginning, match_end;2843const char*patch = frag->patch;2844int size = frag->size;2845char*old, *oldlines;2846struct strbuf newlines;2847int new_blank_lines_at_end =0;2848int found_new_blank_lines_at_end =0;2849int hunk_linenr = frag->linenr;2850unsigned long leading, trailing;2851int pos, applied_pos;2852struct image preimage;2853struct image postimage;28542855memset(&preimage,0,sizeof(preimage));2856memset(&postimage,0,sizeof(postimage));2857 oldlines =xmalloc(size);2858strbuf_init(&newlines, size);28592860 old = oldlines;2861while(size >0) {2862char first;2863int len =linelen(patch, size);2864int plen;2865int added_blank_line =0;2866int is_blank_context =0;2867size_t start;28682869if(!len)2870break;28712872/*2873 * "plen" is how much of the line we should use for2874 * the actual patch data. Normally we just remove the2875 * first character on the line, but if the line is2876 * followed by "\ No newline", then we also remove the2877 * last one (which is the newline, of course).2878 */2879 plen = len -1;2880if(len < size && patch[len] =='\\')2881 plen--;2882 first = *patch;2883if(state->apply_in_reverse) {2884if(first =='-')2885 first ='+';2886else if(first =='+')2887 first ='-';2888}28892890switch(first) {2891case'\n':2892/* Newer GNU diff, empty context line */2893if(plen <0)2894/* ... followed by '\No newline'; nothing */2895break;2896*old++ ='\n';2897strbuf_addch(&newlines,'\n');2898add_line_info(&preimage,"\n",1, LINE_COMMON);2899add_line_info(&postimage,"\n",1, LINE_COMMON);2900 is_blank_context =1;2901break;2902case' ':2903if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2904ws_blank_line(patch +1, plen, ws_rule))2905 is_blank_context =1;2906/* fallthrough */2907case'-':2908memcpy(old, patch +1, plen);2909add_line_info(&preimage, old, plen,2910(first ==' '? LINE_COMMON :0));2911 old += plen;2912if(first =='-')2913break;2914/* fallthrough */2915case'+':2916/* --no-add does not add new lines */2917if(first =='+'&& state->no_add)2918break;29192920 start = newlines.len;2921if(first !='+'||2922!state->whitespace_error ||2923 state->ws_error_action != correct_ws_error) {2924strbuf_add(&newlines, patch +1, plen);2925}2926else{2927ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2928}2929add_line_info(&postimage, newlines.buf + start, newlines.len - start,2930(first =='+'?0: LINE_COMMON));2931if(first =='+'&&2932(ws_rule & WS_BLANK_AT_EOF) &&2933ws_blank_line(patch +1, plen, ws_rule))2934 added_blank_line =1;2935break;2936case'@':case'\\':2937/* Ignore it, we already handled it */2938break;2939default:2940if(state->apply_verbosity > verbosity_normal)2941error(_("invalid start of line: '%c'"), first);2942 applied_pos = -1;2943goto out;2944}2945if(added_blank_line) {2946if(!new_blank_lines_at_end)2947 found_new_blank_lines_at_end = hunk_linenr;2948 new_blank_lines_at_end++;2949}2950else if(is_blank_context)2951;2952else2953 new_blank_lines_at_end =0;2954 patch += len;2955 size -= len;2956 hunk_linenr++;2957}2958if(inaccurate_eof &&2959 old > oldlines && old[-1] =='\n'&&2960 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2961 old--;2962strbuf_setlen(&newlines, newlines.len -1);2963 preimage.line_allocated[preimage.nr -1].len--;2964 postimage.line_allocated[postimage.nr -1].len--;2965}29662967 leading = frag->leading;2968 trailing = frag->trailing;29692970/*2971 * A hunk to change lines at the beginning would begin with2972 * @@ -1,L +N,M @@2973 * but we need to be careful. -U0 that inserts before the second2974 * line also has this pattern.2975 *2976 * And a hunk to add to an empty file would begin with2977 * @@ -0,0 +N,M @@2978 *2979 * In other words, a hunk that is (frag->oldpos <= 1) with or2980 * without leading context must match at the beginning.2981 */2982 match_beginning = (!frag->oldpos ||2983(frag->oldpos ==1&& !state->unidiff_zero));29842985/*2986 * A hunk without trailing lines must match at the end.2987 * However, we simply cannot tell if a hunk must match end2988 * from the lack of trailing lines if the patch was generated2989 * with unidiff without any context.2990 */2991 match_end = !state->unidiff_zero && !trailing;29922993 pos = frag->newpos ? (frag->newpos -1) :0;2994 preimage.buf = oldlines;2995 preimage.len = old - oldlines;2996 postimage.buf = newlines.buf;2997 postimage.len = newlines.len;2998 preimage.line = preimage.line_allocated;2999 postimage.line = postimage.line_allocated;30003001for(;;) {30023003 applied_pos =find_pos(state, img, &preimage, &postimage, pos,3004 ws_rule, match_beginning, match_end);30053006if(applied_pos >=0)3007break;30083009/* Am I at my context limits? */3010if((leading <= state->p_context) && (trailing <= state->p_context))3011break;3012if(match_beginning || match_end) {3013 match_beginning = match_end =0;3014continue;3015}30163017/*3018 * Reduce the number of context lines; reduce both3019 * leading and trailing if they are equal otherwise3020 * just reduce the larger context.3021 */3022if(leading >= trailing) {3023remove_first_line(&preimage);3024remove_first_line(&postimage);3025 pos--;3026 leading--;3027}3028if(trailing > leading) {3029remove_last_line(&preimage);3030remove_last_line(&postimage);3031 trailing--;3032}3033}30343035if(applied_pos >=0) {3036if(new_blank_lines_at_end &&3037 preimage.nr + applied_pos >= img->nr &&3038(ws_rule & WS_BLANK_AT_EOF) &&3039 state->ws_error_action != nowarn_ws_error) {3040record_ws_error(state, WS_BLANK_AT_EOF,"+",1,3041 found_new_blank_lines_at_end);3042if(state->ws_error_action == correct_ws_error) {3043while(new_blank_lines_at_end--)3044remove_last_line(&postimage);3045}3046/*3047 * We would want to prevent write_out_results()3048 * from taking place in apply_patch() that follows3049 * the callchain led us here, which is:3050 * apply_patch->check_patch_list->check_patch->3051 * apply_data->apply_fragments->apply_one_fragment3052 */3053if(state->ws_error_action == die_on_ws_error)3054 state->apply =0;3055}30563057if(state->apply_verbosity > verbosity_normal && applied_pos != pos) {3058int offset = applied_pos - pos;3059if(state->apply_in_reverse)3060 offset =0- offset;3061fprintf_ln(stderr,3062Q_("Hunk #%dsucceeded at%d(offset%dline).",3063"Hunk #%dsucceeded at%d(offset%dlines).",3064 offset),3065 nth_fragment, applied_pos +1, offset);3066}30673068/*3069 * Warn if it was necessary to reduce the number3070 * of context lines.3071 */3072if((leading != frag->leading ||3073 trailing != frag->trailing) && state->apply_verbosity > verbosity_silent)3074fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"3075" to apply fragment at%d"),3076 leading, trailing, applied_pos+1);3077update_image(state, img, applied_pos, &preimage, &postimage);3078}else{3079if(state->apply_verbosity > verbosity_normal)3080error(_("while searching for:\n%.*s"),3081(int)(old - oldlines), oldlines);3082}30833084out:3085free(oldlines);3086strbuf_release(&newlines);3087free(preimage.line_allocated);3088free(postimage.line_allocated);30893090return(applied_pos <0);3091}30923093static intapply_binary_fragment(struct apply_state *state,3094struct image *img,3095struct patch *patch)3096{3097struct fragment *fragment = patch->fragments;3098unsigned long len;3099void*dst;31003101if(!fragment)3102returnerror(_("missing binary patch data for '%s'"),3103 patch->new_name ?3104 patch->new_name :3105 patch->old_name);31063107/* Binary patch is irreversible without the optional second hunk */3108if(state->apply_in_reverse) {3109if(!fragment->next)3110returnerror(_("cannot reverse-apply a binary patch "3111"without the reverse hunk to '%s'"),3112 patch->new_name3113? patch->new_name : patch->old_name);3114 fragment = fragment->next;3115}3116switch(fragment->binary_patch_method) {3117case BINARY_DELTA_DEFLATED:3118 dst =patch_delta(img->buf, img->len, fragment->patch,3119 fragment->size, &len);3120if(!dst)3121return-1;3122clear_image(img);3123 img->buf = dst;3124 img->len = len;3125return0;3126case BINARY_LITERAL_DEFLATED:3127clear_image(img);3128 img->len = fragment->size;3129 img->buf =xmemdupz(fragment->patch, img->len);3130return0;3131}3132return-1;3133}31343135/*3136 * Replace "img" with the result of applying the binary patch.3137 * The binary patch data itself in patch->fragment is still kept3138 * but the preimage prepared by the caller in "img" is freed here3139 * or in the helper function apply_binary_fragment() this calls.3140 */3141static intapply_binary(struct apply_state *state,3142struct image *img,3143struct patch *patch)3144{3145const char*name = patch->old_name ? patch->old_name : patch->new_name;3146struct object_id oid;31473148/*3149 * For safety, we require patch index line to contain3150 * full 40-byte textual SHA1 for old and new, at least for now.3151 */3152if(strlen(patch->old_sha1_prefix) !=40||3153strlen(patch->new_sha1_prefix) !=40||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 apply_state *state,3473struct image *image,3474char*path,3475const struct object_id *base,3476const struct object_id *ours,3477const struct object_id *theirs)3478{3479 mmfile_t base_file, our_file, their_file;3480 mmbuffer_t result = { NULL };3481int status;34823483read_mmblob(&base_file, base);3484read_mmblob(&our_file, ours);3485read_mmblob(&their_file, theirs);3486 status =ll_merge(&result, path,3487&base_file,"base",3488&our_file,"ours",3489&their_file,"theirs",3490 state->repo->index,3491 NULL);3492free(base_file.ptr);3493free(our_file.ptr);3494free(their_file.ptr);3495if(status <0|| !result.ptr) {3496free(result.ptr);3497return-1;3498}3499clear_image(image);3500 image->buf = result.ptr;3501 image->len = result.size;35023503return status;3504}35053506/*3507 * When directly falling back to add/add three-way merge, we read from3508 * the current contents of the new_name. In no cases other than that3509 * this function will be called.3510 */3511static intload_current(struct apply_state *state,3512struct image *image,3513struct patch *patch)3514{3515struct strbuf buf = STRBUF_INIT;3516int status, pos;3517size_t len;3518char*img;3519struct stat st;3520struct cache_entry *ce;3521char*name = patch->new_name;3522unsigned mode = patch->new_mode;35233524if(!patch->is_new)3525BUG("patch to%sis not a creation", patch->old_name);35263527 pos =index_name_pos(state->repo->index, name,strlen(name));3528if(pos <0)3529returnerror(_("%s: does not exist in index"), name);3530 ce = state->repo->index->cache[pos];3531if(lstat(name, &st)) {3532if(errno != ENOENT)3533returnerror_errno("%s", name);3534if(checkout_target(state->repo->index, ce, &st))3535return-1;3536}3537if(verify_index_match(state, ce, &st))3538returnerror(_("%s: does not match index"), name);35393540 status =load_patch_target(state, &buf, ce, &st, patch, name, mode);3541if(status <0)3542return status;3543else if(status)3544return-1;3545 img =strbuf_detach(&buf, &len);3546prepare_image(image, img, len, !patch->is_binary);3547return0;3548}35493550static inttry_threeway(struct apply_state *state,3551struct image *image,3552struct patch *patch,3553struct stat *st,3554const struct cache_entry *ce)3555{3556struct object_id pre_oid, post_oid, our_oid;3557struct strbuf buf = STRBUF_INIT;3558size_t len;3559int status;3560char*img;3561struct image tmp_image;35623563/* No point falling back to 3-way merge in these cases */3564if(patch->is_delete ||3565S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3566return-1;35673568/* Preimage the patch was prepared for */3569if(patch->is_new)3570write_object_file("",0, blob_type, &pre_oid);3571else if(get_oid(patch->old_sha1_prefix, &pre_oid) ||3572read_blob_object(&buf, &pre_oid, patch->old_mode))3573returnerror(_("repository lacks the necessary blob to fall back on 3-way merge."));35743575if(state->apply_verbosity > verbosity_silent)3576fprintf(stderr,_("Falling back to three-way merge...\n"));35773578 img =strbuf_detach(&buf, &len);3579prepare_image(&tmp_image, img, len,1);3580/* Apply the patch to get the post image */3581if(apply_fragments(state, &tmp_image, patch) <0) {3582clear_image(&tmp_image);3583return-1;3584}3585/* post_oid is theirs */3586write_object_file(tmp_image.buf, tmp_image.len, blob_type, &post_oid);3587clear_image(&tmp_image);35883589/* our_oid is ours */3590if(patch->is_new) {3591if(load_current(state, &tmp_image, patch))3592returnerror(_("cannot read the current contents of '%s'"),3593 patch->new_name);3594}else{3595if(load_preimage(state, &tmp_image, patch, st, ce))3596returnerror(_("cannot read the current contents of '%s'"),3597 patch->old_name);3598}3599write_object_file(tmp_image.buf, tmp_image.len, blob_type, &our_oid);3600clear_image(&tmp_image);36013602/* in-core three-way merge between post and our using pre as base */3603 status =three_way_merge(state, image, patch->new_name,3604&pre_oid, &our_oid, &post_oid);3605if(status <0) {3606if(state->apply_verbosity > verbosity_silent)3607fprintf(stderr,3608_("Failed to fall back on three-way merge...\n"));3609return status;3610}36113612if(status) {3613 patch->conflicted_threeway =1;3614if(patch->is_new)3615oidclr(&patch->threeway_stage[0]);3616else3617oidcpy(&patch->threeway_stage[0], &pre_oid);3618oidcpy(&patch->threeway_stage[1], &our_oid);3619oidcpy(&patch->threeway_stage[2], &post_oid);3620if(state->apply_verbosity > verbosity_silent)3621fprintf(stderr,3622_("Applied patch to '%s' with conflicts.\n"),3623 patch->new_name);3624}else{3625if(state->apply_verbosity > verbosity_silent)3626fprintf(stderr,3627_("Applied patch to '%s' cleanly.\n"),3628 patch->new_name);3629}3630return0;3631}36323633static intapply_data(struct apply_state *state,struct patch *patch,3634struct stat *st,const struct cache_entry *ce)3635{3636struct image image;36373638if(load_preimage(state, &image, patch, st, ce) <0)3639return-1;36403641if(patch->direct_to_threeway ||3642apply_fragments(state, &image, patch) <0) {3643/* Note: with --reject, apply_fragments() returns 0 */3644if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3645return-1;3646}3647 patch->result = image.buf;3648 patch->resultsize = image.len;3649add_to_fn_table(state, patch);3650free(image.line_allocated);36513652if(0< patch->is_delete && patch->resultsize)3653returnerror(_("removal patch leaves file contents"));36543655return0;3656}36573658/*3659 * If "patch" that we are looking at modifies or deletes what we have,3660 * we would want it not to lose any local modification we have, either3661 * in the working tree or in the index.3662 *3663 * This also decides if a non-git patch is a creation patch or a3664 * modification to an existing empty file. We do not check the state3665 * of the current tree for a creation patch in this function; the caller3666 * check_patch() separately makes sure (and errors out otherwise) that3667 * the path the patch creates does not exist in the current tree.3668 */3669static intcheck_preimage(struct apply_state *state,3670struct patch *patch,3671struct cache_entry **ce,3672struct stat *st)3673{3674const char*old_name = patch->old_name;3675struct patch *previous = NULL;3676int stat_ret =0, status;3677unsigned st_mode =0;36783679if(!old_name)3680return0;36813682assert(patch->is_new <=0);3683 previous =previous_patch(state, patch, &status);36843685if(status)3686returnerror(_("path%shas been renamed/deleted"), old_name);3687if(previous) {3688 st_mode = previous->new_mode;3689}else if(!state->cached) {3690 stat_ret =lstat(old_name, st);3691if(stat_ret && errno != ENOENT)3692returnerror_errno("%s", old_name);3693}36943695if(state->check_index && !previous) {3696int pos =index_name_pos(state->repo->index, old_name,3697strlen(old_name));3698if(pos <0) {3699if(patch->is_new <0)3700goto is_new;3701returnerror(_("%s: does not exist in index"), old_name);3702}3703*ce = state->repo->index->cache[pos];3704if(stat_ret <0) {3705if(checkout_target(state->repo->index, *ce, st))3706return-1;3707}3708if(!state->cached &&verify_index_match(state, *ce, st))3709returnerror(_("%s: does not match index"), old_name);3710if(state->cached)3711 st_mode = (*ce)->ce_mode;3712}else if(stat_ret <0) {3713if(patch->is_new <0)3714goto is_new;3715returnerror_errno("%s", old_name);3716}37173718if(!state->cached && !previous)3719 st_mode =ce_mode_from_stat(*ce, st->st_mode);37203721if(patch->is_new <0)3722 patch->is_new =0;3723if(!patch->old_mode)3724 patch->old_mode = st_mode;3725if((st_mode ^ patch->old_mode) & S_IFMT)3726returnerror(_("%s: wrong type"), old_name);3727if(st_mode != patch->old_mode)3728warning(_("%shas type%o, expected%o"),3729 old_name, st_mode, patch->old_mode);3730if(!patch->new_mode && !patch->is_delete)3731 patch->new_mode = st_mode;3732return0;37333734 is_new:3735 patch->is_new =1;3736 patch->is_delete =0;3737FREE_AND_NULL(patch->old_name);3738return0;3739}374037413742#define EXISTS_IN_INDEX 13743#define EXISTS_IN_WORKTREE 237443745static intcheck_to_create(struct apply_state *state,3746const char*new_name,3747int ok_if_exists)3748{3749struct stat nst;37503751if(state->check_index &&3752index_name_pos(state->repo->index, new_name,strlen(new_name)) >=0&&3753!ok_if_exists)3754return EXISTS_IN_INDEX;3755if(state->cached)3756return0;37573758if(!lstat(new_name, &nst)) {3759if(S_ISDIR(nst.st_mode) || ok_if_exists)3760return0;3761/*3762 * A leading component of new_name might be a symlink3763 * that is going to be removed with this patch, but3764 * still pointing at somewhere that has the path.3765 * In such a case, path "new_name" does not exist as3766 * far as git is concerned.3767 */3768if(has_symlink_leading_path(new_name,strlen(new_name)))3769return0;37703771return EXISTS_IN_WORKTREE;3772}else if(!is_missing_file_error(errno)) {3773returnerror_errno("%s", new_name);3774}3775return0;3776}37773778static uintptr_tregister_symlink_changes(struct apply_state *state,3779const char*path,3780uintptr_t what)3781{3782struct string_list_item *ent;37833784 ent =string_list_lookup(&state->symlink_changes, path);3785if(!ent) {3786 ent =string_list_insert(&state->symlink_changes, path);3787 ent->util = (void*)0;3788}3789 ent->util = (void*)(what | ((uintptr_t)ent->util));3790return(uintptr_t)ent->util;3791}37923793static uintptr_tcheck_symlink_changes(struct apply_state *state,const char*path)3794{3795struct string_list_item *ent;37963797 ent =string_list_lookup(&state->symlink_changes, path);3798if(!ent)3799return0;3800return(uintptr_t)ent->util;3801}38023803static voidprepare_symlink_changes(struct apply_state *state,struct patch *patch)3804{3805for( ; patch; patch = patch->next) {3806if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3807(patch->is_rename || patch->is_delete))3808/* the symlink at patch->old_name is removed */3809register_symlink_changes(state, patch->old_name, APPLY_SYMLINK_GOES_AWAY);38103811if(patch->new_name &&S_ISLNK(patch->new_mode))3812/* the symlink at patch->new_name is created or remains */3813register_symlink_changes(state, patch->new_name, APPLY_SYMLINK_IN_RESULT);3814}3815}38163817static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3818{3819do{3820unsigned int change;38213822while(--name->len && name->buf[name->len] !='/')3823;/* scan backwards */3824if(!name->len)3825break;3826 name->buf[name->len] ='\0';3827 change =check_symlink_changes(state, name->buf);3828if(change & APPLY_SYMLINK_IN_RESULT)3829return1;3830if(change & APPLY_SYMLINK_GOES_AWAY)3831/*3832 * This cannot be "return 0", because we may3833 * see a new one created at a higher level.3834 */3835continue;38363837/* otherwise, check the preimage */3838if(state->check_index) {3839struct cache_entry *ce;38403841 ce =index_file_exists(state->repo->index, name->buf,3842 name->len, ignore_case);3843if(ce &&S_ISLNK(ce->ce_mode))3844return1;3845}else{3846struct stat st;3847if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3848return1;3849}3850}while(1);3851return0;3852}38533854static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3855{3856int ret;3857struct strbuf name = STRBUF_INIT;38583859assert(*name_ !='\0');3860strbuf_addstr(&name, name_);3861 ret =path_is_beyond_symlink_1(state, &name);3862strbuf_release(&name);38633864return ret;3865}38663867static intcheck_unsafe_path(struct patch *patch)3868{3869const char*old_name = NULL;3870const char*new_name = NULL;3871if(patch->is_delete)3872 old_name = patch->old_name;3873else if(!patch->is_new && !patch->is_copy)3874 old_name = patch->old_name;3875if(!patch->is_delete)3876 new_name = patch->new_name;38773878if(old_name && !verify_path(old_name, patch->old_mode))3879returnerror(_("invalid path '%s'"), old_name);3880if(new_name && !verify_path(new_name, patch->new_mode))3881returnerror(_("invalid path '%s'"), new_name);3882return0;3883}38843885/*3886 * Check and apply the patch in-core; leave the result in patch->result3887 * for the caller to write it out to the final destination.3888 */3889static intcheck_patch(struct apply_state *state,struct patch *patch)3890{3891struct stat st;3892const char*old_name = patch->old_name;3893const char*new_name = patch->new_name;3894const char*name = old_name ? old_name : new_name;3895struct cache_entry *ce = NULL;3896struct patch *tpatch;3897int ok_if_exists;3898int status;38993900 patch->rejected =1;/* we will drop this after we succeed */39013902 status =check_preimage(state, patch, &ce, &st);3903if(status)3904return status;3905 old_name = patch->old_name;39063907/*3908 * A type-change diff is always split into a patch to delete3909 * old, immediately followed by a patch to create new (see3910 * diff.c::run_diff()); in such a case it is Ok that the entry3911 * to be deleted by the previous patch is still in the working3912 * tree and in the index.3913 *3914 * A patch to swap-rename between A and B would first rename A3915 * to B and then rename B to A. While applying the first one,3916 * the presence of B should not stop A from getting renamed to3917 * B; ask to_be_deleted() about the later rename. Removal of3918 * B and rename from A to B is handled the same way by asking3919 * was_deleted().3920 */3921if((tpatch =in_fn_table(state, new_name)) &&3922(was_deleted(tpatch) ||to_be_deleted(tpatch)))3923 ok_if_exists =1;3924else3925 ok_if_exists =0;39263927if(new_name &&3928((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3929int err =check_to_create(state, new_name, ok_if_exists);39303931if(err && state->threeway) {3932 patch->direct_to_threeway =1;3933}else switch(err) {3934case0:3935break;/* happy */3936case EXISTS_IN_INDEX:3937returnerror(_("%s: already exists in index"), new_name);3938break;3939case EXISTS_IN_WORKTREE:3940returnerror(_("%s: already exists in working directory"),3941 new_name);3942default:3943return err;3944}39453946if(!patch->new_mode) {3947if(0< patch->is_new)3948 patch->new_mode = S_IFREG |0644;3949else3950 patch->new_mode = patch->old_mode;3951}3952}39533954if(new_name && old_name) {3955int same = !strcmp(old_name, new_name);3956if(!patch->new_mode)3957 patch->new_mode = patch->old_mode;3958if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3959if(same)3960returnerror(_("new mode (%o) of%sdoes not "3961"match old mode (%o)"),3962 patch->new_mode, new_name,3963 patch->old_mode);3964else3965returnerror(_("new mode (%o) of%sdoes not "3966"match old mode (%o) of%s"),3967 patch->new_mode, new_name,3968 patch->old_mode, old_name);3969}3970}39713972if(!state->unsafe_paths &&check_unsafe_path(patch))3973return-128;39743975/*3976 * An attempt to read from or delete a path that is beyond a3977 * symbolic link will be prevented by load_patch_target() that3978 * is called at the beginning of apply_data() so we do not3979 * have to worry about a patch marked with "is_delete" bit3980 * here. We however need to make sure that the patch result3981 * is not deposited to a path that is beyond a symbolic link3982 * here.3983 */3984if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3985returnerror(_("affected file '%s' is beyond a symbolic link"),3986 patch->new_name);39873988if(apply_data(state, patch, &st, ce) <0)3989returnerror(_("%s: patch does not apply"), name);3990 patch->rejected =0;3991return0;3992}39933994static intcheck_patch_list(struct apply_state *state,struct patch *patch)3995{3996int err =0;39973998prepare_symlink_changes(state, patch);3999prepare_fn_table(state, patch);4000while(patch) {4001int res;4002if(state->apply_verbosity > verbosity_normal)4003say_patch_name(stderr,4004_("Checking patch%s..."), patch);4005 res =check_patch(state, patch);4006if(res == -128)4007return-128;4008 err |= res;4009 patch = patch->next;4010}4011return err;4012}40134014static intread_apply_cache(struct apply_state *state)4015{4016if(state->index_file)4017returnread_index_from(state->repo->index, state->index_file,4018get_git_dir());4019else4020returnread_index(state->repo->index);4021}40224023/* This function tries to read the object name from the current index */4024static intget_current_oid(struct apply_state *state,const char*path,4025struct object_id *oid)4026{4027int pos;40284029if(read_apply_cache(state) <0)4030return-1;4031 pos =index_name_pos(state->repo->index, path,strlen(path));4032if(pos <0)4033return-1;4034oidcpy(oid, &state->repo->index->cache[pos]->oid);4035return0;4036}40374038static intpreimage_oid_in_gitlink_patch(struct patch *p,struct object_id *oid)4039{4040/*4041 * A usable gitlink patch has only one fragment (hunk) that looks like:4042 * @@ -1 +1 @@4043 * -Subproject commit <old sha1>4044 * +Subproject commit <new sha1>4045 * or4046 * @@ -1 +0,0 @@4047 * -Subproject commit <old sha1>4048 * for a removal patch.4049 */4050struct fragment *hunk = p->fragments;4051static const char heading[] ="-Subproject commit ";4052char*preimage;40534054if(/* does the patch have only one hunk? */4055 hunk && !hunk->next &&4056/* is its preimage one line? */4057 hunk->oldpos ==1&& hunk->oldlines ==1&&4058/* does preimage begin with the heading? */4059(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&4060starts_with(++preimage, heading) &&4061/* does it record full SHA-1? */4062!get_oid_hex(preimage +sizeof(heading) -1, oid) &&4063 preimage[sizeof(heading) + GIT_SHA1_HEXSZ -1] =='\n'&&4064/* does the abbreviated name on the index line agree with it? */4065starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))4066return0;/* it all looks fine */40674068/* we may have full object name on the index line */4069returnget_oid_hex(p->old_sha1_prefix, oid);4070}40714072/* Build an index that contains just the files needed for a 3way merge */4073static intbuild_fake_ancestor(struct apply_state *state,struct patch *list)4074{4075struct patch *patch;4076struct index_state result = { NULL };4077struct lock_file lock = LOCK_INIT;4078int res;40794080/* Once we start supporting the reverse patch, it may be4081 * worth showing the new sha1 prefix, but until then...4082 */4083for(patch = list; patch; patch = patch->next) {4084struct object_id oid;4085struct cache_entry *ce;4086const char*name;40874088 name = patch->old_name ? patch->old_name : patch->new_name;4089if(0< patch->is_new)4090continue;40914092if(S_ISGITLINK(patch->old_mode)) {4093if(!preimage_oid_in_gitlink_patch(patch, &oid))4094;/* ok, the textual part looks sane */4095else4096returnerror(_("sha1 information is lacking or "4097"useless for submodule%s"), name);4098}else if(!get_oid_blob(patch->old_sha1_prefix, &oid)) {4099;/* ok */4100}else if(!patch->lines_added && !patch->lines_deleted) {4101/* mode-only change: update the current */4102if(get_current_oid(state, patch->old_name, &oid))4103returnerror(_("mode change for%s, which is not "4104"in current HEAD"), name);4105}else4106returnerror(_("sha1 information is lacking or useless "4107"(%s)."), name);41084109 ce =make_cache_entry(&result, patch->old_mode, &oid, name,0,0);4110if(!ce)4111returnerror(_("make_cache_entry failed for path '%s'"),4112 name);4113if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) {4114discard_cache_entry(ce);4115returnerror(_("could not add%sto temporary index"),4116 name);4117}4118}41194120hold_lock_file_for_update(&lock, state->fake_ancestor, LOCK_DIE_ON_ERROR);4121 res =write_locked_index(&result, &lock, COMMIT_LOCK);4122discard_index(&result);41234124if(res)4125returnerror(_("could not write temporary index to%s"),4126 state->fake_ancestor);41274128return0;4129}41304131static voidstat_patch_list(struct apply_state *state,struct patch *patch)4132{4133int files, adds, dels;41344135for(files = adds = dels =0; patch ; patch = patch->next) {4136 files++;4137 adds += patch->lines_added;4138 dels += patch->lines_deleted;4139show_stats(state, patch);4140}41414142print_stat_summary(stdout, files, adds, dels);4143}41444145static voidnumstat_patch_list(struct apply_state *state,4146struct patch *patch)4147{4148for( ; patch; patch = patch->next) {4149const char*name;4150 name = patch->new_name ? patch->new_name : patch->old_name;4151if(patch->is_binary)4152printf("-\t-\t");4153else4154printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4155write_name_quoted(name, stdout, state->line_termination);4156}4157}41584159static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4160{4161if(mode)4162printf("%smode%06o%s\n", newdelete, mode, name);4163else4164printf("%s %s\n", newdelete, name);4165}41664167static voidshow_mode_change(struct patch *p,int show_name)4168{4169if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4170if(show_name)4171printf(" mode change%06o =>%06o%s\n",4172 p->old_mode, p->new_mode, p->new_name);4173else4174printf(" mode change%06o =>%06o\n",4175 p->old_mode, p->new_mode);4176}4177}41784179static voidshow_rename_copy(struct patch *p)4180{4181const char*renamecopy = p->is_rename ?"rename":"copy";4182const char*old_name, *new_name;41834184/* Find common prefix */4185 old_name = p->old_name;4186 new_name = p->new_name;4187while(1) {4188const char*slash_old, *slash_new;4189 slash_old =strchr(old_name,'/');4190 slash_new =strchr(new_name,'/');4191if(!slash_old ||4192!slash_new ||4193 slash_old - old_name != slash_new - new_name ||4194memcmp(old_name, new_name, slash_new - new_name))4195break;4196 old_name = slash_old +1;4197 new_name = slash_new +1;4198}4199/* p->old_name thru old_name is the common prefix, and old_name and new_name4200 * through the end of names are renames4201 */4202if(old_name != p->old_name)4203printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4204(int)(old_name - p->old_name), p->old_name,4205 old_name, new_name, p->score);4206else4207printf("%s %s=>%s(%d%%)\n", renamecopy,4208 p->old_name, p->new_name, p->score);4209show_mode_change(p,0);4210}42114212static voidsummary_patch_list(struct patch *patch)4213{4214struct patch *p;42154216for(p = patch; p; p = p->next) {4217if(p->is_new)4218show_file_mode_name("create", p->new_mode, p->new_name);4219else if(p->is_delete)4220show_file_mode_name("delete", p->old_mode, p->old_name);4221else{4222if(p->is_rename || p->is_copy)4223show_rename_copy(p);4224else{4225if(p->score) {4226printf(" rewrite%s(%d%%)\n",4227 p->new_name, p->score);4228show_mode_change(p,0);4229}4230else4231show_mode_change(p,1);4232}4233}4234}4235}42364237static voidpatch_stats(struct apply_state *state,struct patch *patch)4238{4239int lines = patch->lines_added + patch->lines_deleted;42404241if(lines > state->max_change)4242 state->max_change = lines;4243if(patch->old_name) {4244int len =quote_c_style(patch->old_name, NULL, NULL,0);4245if(!len)4246 len =strlen(patch->old_name);4247if(len > state->max_len)4248 state->max_len = len;4249}4250if(patch->new_name) {4251int len =quote_c_style(patch->new_name, NULL, NULL,0);4252if(!len)4253 len =strlen(patch->new_name);4254if(len > state->max_len)4255 state->max_len = len;4256}4257}42584259static intremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4260{4261if(state->update_index && !state->ita_only) {4262if(remove_file_from_index(state->repo->index, patch->old_name) <0)4263returnerror(_("unable to remove%sfrom index"), patch->old_name);4264}4265if(!state->cached) {4266if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4267remove_path(patch->old_name);4268}4269}4270return0;4271}42724273static intadd_index_file(struct apply_state *state,4274const char*path,4275unsigned mode,4276void*buf,4277unsigned long size)4278{4279struct stat st;4280struct cache_entry *ce;4281int namelen =strlen(path);42824283 ce =make_empty_cache_entry(state->repo->index, namelen);4284memcpy(ce->name, path, namelen);4285 ce->ce_mode =create_ce_mode(mode);4286 ce->ce_flags =create_ce_flags(0);4287 ce->ce_namelen = namelen;4288if(state->ita_only) {4289 ce->ce_flags |= CE_INTENT_TO_ADD;4290set_object_name_for_intent_to_add_entry(ce);4291}else if(S_ISGITLINK(mode)) {4292const char*s;42934294if(!skip_prefix(buf,"Subproject commit ", &s) ||4295get_oid_hex(s, &ce->oid)) {4296discard_cache_entry(ce);4297returnerror(_("corrupt patch for submodule%s"), path);4298}4299}else{4300if(!state->cached) {4301if(lstat(path, &st) <0) {4302discard_cache_entry(ce);4303returnerror_errno(_("unable to stat newly "4304"created file '%s'"),4305 path);4306}4307fill_stat_cache_info(ce, &st);4308}4309if(write_object_file(buf, size, blob_type, &ce->oid) <0) {4310discard_cache_entry(ce);4311returnerror(_("unable to create backing store "4312"for newly created file%s"), path);4313}4314}4315if(add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) <0) {4316discard_cache_entry(ce);4317returnerror(_("unable to add cache entry for%s"), path);4318}43194320return0;4321}43224323/*4324 * Returns:4325 * -1 if an unrecoverable error happened4326 * 0 if everything went well4327 * 1 if a recoverable error happened4328 */4329static inttry_create_file(struct apply_state *state,const char*path,4330unsigned int mode,const char*buf,4331unsigned long size)4332{4333int fd, res;4334struct strbuf nbuf = STRBUF_INIT;43354336if(S_ISGITLINK(mode)) {4337struct stat st;4338if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4339return0;4340return!!mkdir(path,0777);4341}43424343if(has_symlinks &&S_ISLNK(mode))4344/* Although buf:size is counted string, it also is NUL4345 * terminated.4346 */4347return!!symlink(buf, path);43484349 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4350if(fd <0)4351return1;43524353if(convert_to_working_tree(state->repo->index, path, buf, size, &nbuf)) {4354 size = nbuf.len;4355 buf = nbuf.buf;4356}43574358 res =write_in_full(fd, buf, size) <0;4359if(res)4360error_errno(_("failed to write to '%s'"), path);4361strbuf_release(&nbuf);43624363if(close(fd) <0&& !res)4364returnerror_errno(_("closing file '%s'"), path);43654366return res ? -1:0;4367}43684369/*4370 * We optimistically assume that the directories exist,4371 * which is true 99% of the time anyway. If they don't,4372 * we create them and try again.4373 *4374 * Returns:4375 * -1 on error4376 * 0 otherwise4377 */4378static intcreate_one_file(struct apply_state *state,4379char*path,4380unsigned mode,4381const char*buf,4382unsigned long size)4383{4384int res;43854386if(state->cached)4387return0;43884389 res =try_create_file(state, path, mode, buf, size);4390if(res <0)4391return-1;4392if(!res)4393return0;43944395if(errno == ENOENT) {4396if(safe_create_leading_directories(path))4397return0;4398 res =try_create_file(state, path, mode, buf, size);4399if(res <0)4400return-1;4401if(!res)4402return0;4403}44044405if(errno == EEXIST || errno == EACCES) {4406/* We may be trying to create a file where a directory4407 * used to be.4408 */4409struct stat st;4410if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4411 errno = EEXIST;4412}44134414if(errno == EEXIST) {4415unsigned int nr =getpid();44164417for(;;) {4418char newpath[PATH_MAX];4419mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4420 res =try_create_file(state, newpath, mode, buf, size);4421if(res <0)4422return-1;4423if(!res) {4424if(!rename(newpath, path))4425return0;4426unlink_or_warn(newpath);4427break;4428}4429if(errno != EEXIST)4430break;4431++nr;4432}4433}4434returnerror_errno(_("unable to write file '%s' mode%o"),4435 path, mode);4436}44374438static intadd_conflicted_stages_file(struct apply_state *state,4439struct patch *patch)4440{4441int stage, namelen;4442unsigned mode;4443struct cache_entry *ce;44444445if(!state->update_index)4446return0;4447 namelen =strlen(patch->new_name);4448 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);44494450remove_file_from_index(state->repo->index, patch->new_name);4451for(stage =1; stage <4; stage++) {4452if(is_null_oid(&patch->threeway_stage[stage -1]))4453continue;4454 ce =make_empty_cache_entry(state->repo->index, namelen);4455memcpy(ce->name, patch->new_name, namelen);4456 ce->ce_mode =create_ce_mode(mode);4457 ce->ce_flags =create_ce_flags(stage);4458 ce->ce_namelen = namelen;4459oidcpy(&ce->oid, &patch->threeway_stage[stage -1]);4460if(add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) <0) {4461discard_cache_entry(ce);4462returnerror(_("unable to add cache entry for%s"),4463 patch->new_name);4464}4465}44664467return0;4468}44694470static intcreate_file(struct apply_state *state,struct patch *patch)4471{4472char*path = patch->new_name;4473unsigned mode = patch->new_mode;4474unsigned long size = patch->resultsize;4475char*buf = patch->result;44764477if(!mode)4478 mode = S_IFREG |0644;4479if(create_one_file(state, path, mode, buf, size))4480return-1;44814482if(patch->conflicted_threeway)4483returnadd_conflicted_stages_file(state, patch);4484else if(state->update_index)4485returnadd_index_file(state, path, mode, buf, size);4486return0;4487}44884489/* phase zero is to remove, phase one is to create */4490static intwrite_out_one_result(struct apply_state *state,4491struct patch *patch,4492int phase)4493{4494if(patch->is_delete >0) {4495if(phase ==0)4496returnremove_file(state, patch,1);4497return0;4498}4499if(patch->is_new >0|| patch->is_copy) {4500if(phase ==1)4501returncreate_file(state, patch);4502return0;4503}4504/*4505 * Rename or modification boils down to the same4506 * thing: remove the old, write the new4507 */4508if(phase ==0)4509returnremove_file(state, patch, patch->is_rename);4510if(phase ==1)4511returncreate_file(state, patch);4512return0;4513}45144515static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4516{4517FILE*rej;4518char namebuf[PATH_MAX];4519struct fragment *frag;4520int cnt =0;4521struct strbuf sb = STRBUF_INIT;45224523for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4524if(!frag->rejected)4525continue;4526 cnt++;4527}45284529if(!cnt) {4530if(state->apply_verbosity > verbosity_normal)4531say_patch_name(stderr,4532_("Applied patch%scleanly."), patch);4533return0;4534}45354536/* This should not happen, because a removal patch that leaves4537 * contents are marked "rejected" at the patch level.4538 */4539if(!patch->new_name)4540die(_("internal error"));45414542/* Say this even without --verbose */4543strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4544"Applying patch %%swith%drejects...",4545 cnt),4546 cnt);4547if(state->apply_verbosity > verbosity_silent)4548say_patch_name(stderr, sb.buf, patch);4549strbuf_release(&sb);45504551 cnt =strlen(patch->new_name);4552if(ARRAY_SIZE(namebuf) <= cnt +5) {4553 cnt =ARRAY_SIZE(namebuf) -5;4554warning(_("truncating .rej filename to %.*s.rej"),4555 cnt -1, patch->new_name);4556}4557memcpy(namebuf, patch->new_name, cnt);4558memcpy(namebuf + cnt,".rej",5);45594560 rej =fopen(namebuf,"w");4561if(!rej)4562returnerror_errno(_("cannot open%s"), namebuf);45634564/* Normal git tools never deal with .rej, so do not pretend4565 * this is a git patch by saying --git or giving extended4566 * headers. While at it, maybe please "kompare" that wants4567 * the trailing TAB and some garbage at the end of line ;-).4568 */4569fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4570 patch->new_name, patch->new_name);4571for(cnt =1, frag = patch->fragments;4572 frag;4573 cnt++, frag = frag->next) {4574if(!frag->rejected) {4575if(state->apply_verbosity > verbosity_silent)4576fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4577continue;4578}4579if(state->apply_verbosity > verbosity_silent)4580fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4581fprintf(rej,"%.*s", frag->size, frag->patch);4582if(frag->patch[frag->size-1] !='\n')4583fputc('\n', rej);4584}4585fclose(rej);4586return-1;4587}45884589/*4590 * Returns:4591 * -1 if an error happened4592 * 0 if the patch applied cleanly4593 * 1 if the patch did not apply cleanly4594 */4595static intwrite_out_results(struct apply_state *state,struct patch *list)4596{4597int phase;4598int errs =0;4599struct patch *l;4600struct string_list cpath = STRING_LIST_INIT_DUP;46014602for(phase =0; phase <2; phase++) {4603 l = list;4604while(l) {4605if(l->rejected)4606 errs =1;4607else{4608if(write_out_one_result(state, l, phase)) {4609string_list_clear(&cpath,0);4610return-1;4611}4612if(phase ==1) {4613if(write_out_one_reject(state, l))4614 errs =1;4615if(l->conflicted_threeway) {4616string_list_append(&cpath, l->new_name);4617 errs =1;4618}4619}4620}4621 l = l->next;4622}4623}46244625if(cpath.nr) {4626struct string_list_item *item;46274628string_list_sort(&cpath);4629if(state->apply_verbosity > verbosity_silent) {4630for_each_string_list_item(item, &cpath)4631fprintf(stderr,"U%s\n", item->string);4632}4633string_list_clear(&cpath,0);46344635repo_rerere(state->repo,0);4636}46374638return errs;4639}46404641/*4642 * Try to apply a patch.4643 *4644 * Returns:4645 * -128 if a bad error happened (like patch unreadable)4646 * -1 if patch did not apply and user cannot deal with it4647 * 0 if the patch applied4648 * 1 if the patch did not apply but user might fix it4649 */4650static intapply_patch(struct apply_state *state,4651int fd,4652const char*filename,4653int options)4654{4655size_t offset;4656struct strbuf buf = STRBUF_INIT;/* owns the patch text */4657struct patch *list = NULL, **listp = &list;4658int skipped_patch =0;4659int res =0;46604661 state->patch_input_file = filename;4662if(read_patch_file(&buf, fd) <0)4663return-128;4664 offset =0;4665while(offset < buf.len) {4666struct patch *patch;4667int nr;46684669 patch =xcalloc(1,sizeof(*patch));4670 patch->inaccurate_eof = !!(options & APPLY_OPT_INACCURATE_EOF);4671 patch->recount = !!(options & APPLY_OPT_RECOUNT);4672 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4673if(nr <0) {4674free_patch(patch);4675if(nr == -128) {4676 res = -128;4677goto end;4678}4679break;4680}4681if(state->apply_in_reverse)4682reverse_patches(patch);4683if(use_patch(state, patch)) {4684patch_stats(state, patch);4685*listp = patch;4686 listp = &patch->next;4687}4688else{4689if(state->apply_verbosity > verbosity_normal)4690say_patch_name(stderr,_("Skipped patch '%s'."), patch);4691free_patch(patch);4692 skipped_patch++;4693}4694 offset += nr;4695}46964697if(!list && !skipped_patch) {4698error(_("unrecognized input"));4699 res = -128;4700goto end;4701}47024703if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4704 state->apply =0;47054706 state->update_index = (state->check_index || state->ita_only) && state->apply;4707if(state->update_index && !is_lock_file_locked(&state->lock_file)) {4708if(state->index_file)4709hold_lock_file_for_update(&state->lock_file,4710 state->index_file,4711 LOCK_DIE_ON_ERROR);4712else4713hold_locked_index(&state->lock_file, LOCK_DIE_ON_ERROR);4714}47154716if(state->check_index &&read_apply_cache(state) <0) {4717error(_("unable to read index file"));4718 res = -128;4719goto end;4720}47214722if(state->check || state->apply) {4723int r =check_patch_list(state, list);4724if(r == -128) {4725 res = -128;4726goto end;4727}4728if(r <0&& !state->apply_with_reject) {4729 res = -1;4730goto end;4731}4732}47334734if(state->apply) {4735int write_res =write_out_results(state, list);4736if(write_res <0) {4737 res = -128;4738goto end;4739}4740if(write_res >0) {4741/* with --3way, we still need to write the index out */4742 res = state->apply_with_reject ? -1:1;4743goto end;4744}4745}47464747if(state->fake_ancestor &&4748build_fake_ancestor(state, list)) {4749 res = -128;4750goto end;4751}47524753if(state->diffstat && state->apply_verbosity > verbosity_silent)4754stat_patch_list(state, list);47554756if(state->numstat && state->apply_verbosity > verbosity_silent)4757numstat_patch_list(state, list);47584759if(state->summary && state->apply_verbosity > verbosity_silent)4760summary_patch_list(list);47614762end:4763free_patch_list(list);4764strbuf_release(&buf);4765string_list_clear(&state->fn_table,0);4766return res;4767}47684769static intapply_option_parse_exclude(const struct option *opt,4770const char*arg,int unset)4771{4772struct apply_state *state = opt->value;4773add_name_limit(state, arg,1);4774return0;4775}47764777static intapply_option_parse_include(const struct option *opt,4778const char*arg,int unset)4779{4780struct apply_state *state = opt->value;4781add_name_limit(state, arg,0);4782 state->has_include =1;4783return0;4784}47854786static intapply_option_parse_p(const struct option *opt,4787const char*arg,4788int unset)4789{4790struct apply_state *state = opt->value;4791 state->p_value =atoi(arg);4792 state->p_value_known =1;4793return0;4794}47954796static intapply_option_parse_space_change(const struct option *opt,4797const char*arg,int unset)4798{4799struct apply_state *state = opt->value;4800if(unset)4801 state->ws_ignore_action = ignore_ws_none;4802else4803 state->ws_ignore_action = ignore_ws_change;4804return0;4805}48064807static intapply_option_parse_whitespace(const struct option *opt,4808const char*arg,int unset)4809{4810struct apply_state *state = opt->value;4811 state->whitespace_option = arg;4812if(parse_whitespace_option(state, arg))4813exit(1);4814return0;4815}48164817static intapply_option_parse_directory(const struct option *opt,4818const char*arg,int unset)4819{4820struct apply_state *state = opt->value;4821strbuf_reset(&state->root);4822strbuf_addstr(&state->root, arg);4823strbuf_complete(&state->root,'/');4824return0;4825}48264827intapply_all_patches(struct apply_state *state,4828int argc,4829const char**argv,4830int options)4831{4832int i;4833int res;4834int errs =0;4835int read_stdin =1;48364837for(i =0; i < argc; i++) {4838const char*arg = argv[i];4839char*to_free = NULL;4840int fd;48414842if(!strcmp(arg,"-")) {4843 res =apply_patch(state,0,"<stdin>", options);4844if(res <0)4845goto end;4846 errs |= res;4847 read_stdin =0;4848continue;4849}else4850 arg = to_free =prefix_filename(state->prefix, arg);48514852 fd =open(arg, O_RDONLY);4853if(fd <0) {4854error(_("can't open patch '%s':%s"), arg,strerror(errno));4855 res = -128;4856free(to_free);4857goto end;4858}4859 read_stdin =0;4860set_default_whitespace_mode(state);4861 res =apply_patch(state, fd, arg, options);4862close(fd);4863free(to_free);4864if(res <0)4865goto end;4866 errs |= res;4867}4868set_default_whitespace_mode(state);4869if(read_stdin) {4870 res =apply_patch(state,0,"<stdin>", options);4871if(res <0)4872goto end;4873 errs |= res;4874}48754876if(state->whitespace_error) {4877if(state->squelch_whitespace_errors &&4878 state->squelch_whitespace_errors < state->whitespace_error) {4879int squelched =4880 state->whitespace_error - state->squelch_whitespace_errors;4881warning(Q_("squelched%dwhitespace error",4882"squelched%dwhitespace errors",4883 squelched),4884 squelched);4885}4886if(state->ws_error_action == die_on_ws_error) {4887error(Q_("%dline adds whitespace errors.",4888"%dlines add whitespace errors.",4889 state->whitespace_error),4890 state->whitespace_error);4891 res = -128;4892goto end;4893}4894if(state->applied_after_fixing_ws && state->apply)4895warning(Q_("%dline applied after"4896" fixing whitespace errors.",4897"%dlines applied after"4898" fixing whitespace errors.",4899 state->applied_after_fixing_ws),4900 state->applied_after_fixing_ws);4901else if(state->whitespace_error)4902warning(Q_("%dline adds whitespace errors.",4903"%dlines add whitespace errors.",4904 state->whitespace_error),4905 state->whitespace_error);4906}49074908if(state->update_index) {4909 res =write_locked_index(state->repo->index, &state->lock_file, COMMIT_LOCK);4910if(res) {4911error(_("Unable to write new index file"));4912 res = -128;4913goto end;4914}4915}49164917 res = !!errs;49184919end:4920rollback_lock_file(&state->lock_file);49214922if(state->apply_verbosity <= verbosity_silent) {4923set_error_routine(state->saved_error_routine);4924set_warn_routine(state->saved_warn_routine);4925}49264927if(res > -1)4928return res;4929return(res == -1?1:128);4930}49314932intapply_parse_options(int argc,const char**argv,4933struct apply_state *state,4934int*force_apply,int*options,4935const char*const*apply_usage)4936{4937struct option builtin_apply_options[] = {4938{ OPTION_CALLBACK,0,"exclude", state,N_("path"),4939N_("don't apply changes matching the given path"),49400, apply_option_parse_exclude },4941{ OPTION_CALLBACK,0,"include", state,N_("path"),4942N_("apply changes matching the given path"),49430, apply_option_parse_include },4944{ OPTION_CALLBACK,'p', NULL, state,N_("num"),4945N_("remove <num> leading slashes from traditional diff paths"),49460, apply_option_parse_p },4947OPT_BOOL(0,"no-add", &state->no_add,4948N_("ignore additions made by the patch")),4949OPT_BOOL(0,"stat", &state->diffstat,4950N_("instead of applying the patch, output diffstat for the input")),4951OPT_NOOP_NOARG(0,"allow-binary-replacement"),4952OPT_NOOP_NOARG(0,"binary"),4953OPT_BOOL(0,"numstat", &state->numstat,4954N_("show number of added and deleted lines in decimal notation")),4955OPT_BOOL(0,"summary", &state->summary,4956N_("instead of applying the patch, output a summary for the input")),4957OPT_BOOL(0,"check", &state->check,4958N_("instead of applying the patch, see if the patch is applicable")),4959OPT_BOOL(0,"index", &state->check_index,4960N_("make sure the patch is applicable to the current index")),4961OPT_BOOL('N',"intent-to-add", &state->ita_only,4962N_("mark new files with `git add --intent-to-add`")),4963OPT_BOOL(0,"cached", &state->cached,4964N_("apply a patch without touching the working tree")),4965OPT_BOOL_F(0,"unsafe-paths", &state->unsafe_paths,4966N_("accept a patch that touches outside the working area"),4967 PARSE_OPT_NOCOMPLETE),4968OPT_BOOL(0,"apply", force_apply,4969N_("also apply the patch (use with --stat/--summary/--check)")),4970OPT_BOOL('3',"3way", &state->threeway,4971N_("attempt three-way merge if a patch does not apply")),4972OPT_FILENAME(0,"build-fake-ancestor", &state->fake_ancestor,4973N_("build a temporary index based on embedded index information")),4974/* Think twice before adding "--nul" synonym to this */4975OPT_SET_INT('z', NULL, &state->line_termination,4976N_("paths are separated with NUL character"),'\0'),4977OPT_INTEGER('C', NULL, &state->p_context,4978N_("ensure at least <n> lines of context match")),4979{ OPTION_CALLBACK,0,"whitespace", state,N_("action"),4980N_("detect new or modified lines that have whitespace errors"),49810, apply_option_parse_whitespace },4982{ OPTION_CALLBACK,0,"ignore-space-change", state, NULL,4983N_("ignore changes in whitespace when finding context"),4984 PARSE_OPT_NOARG, apply_option_parse_space_change },4985{ OPTION_CALLBACK,0,"ignore-whitespace", state, NULL,4986N_("ignore changes in whitespace when finding context"),4987 PARSE_OPT_NOARG, apply_option_parse_space_change },4988OPT_BOOL('R',"reverse", &state->apply_in_reverse,4989N_("apply the patch in reverse")),4990OPT_BOOL(0,"unidiff-zero", &state->unidiff_zero,4991N_("don't expect at least one line of context")),4992OPT_BOOL(0,"reject", &state->apply_with_reject,4993N_("leave the rejected hunks in corresponding *.rej files")),4994OPT_BOOL(0,"allow-overlap", &state->allow_overlap,4995N_("allow overlapping hunks")),4996OPT__VERBOSE(&state->apply_verbosity,N_("be verbose")),4997OPT_BIT(0,"inaccurate-eof", options,4998N_("tolerate incorrectly detected missing new-line at the end of file"),4999 APPLY_OPT_INACCURATE_EOF),5000OPT_BIT(0,"recount", options,5001N_("do not trust the line counts in the hunk headers"),5002 APPLY_OPT_RECOUNT),5003{ OPTION_CALLBACK,0,"directory", state,N_("root"),5004N_("prepend <root> to all filenames"),50050, apply_option_parse_directory },5006OPT_END()5007};50085009returnparse_options(argc, argv, state->prefix, builtin_apply_options, apply_usage,0);5010}