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 25struct gitdiff_data { 26struct strbuf *root; 27int linenr; 28int p_value; 29}; 30 31static voidgit_apply_config(void) 32{ 33git_config_get_string_const("apply.whitespace", &apply_default_whitespace); 34git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace); 35git_config(git_default_config, NULL); 36} 37 38static intparse_whitespace_option(struct apply_state *state,const char*option) 39{ 40if(!option) { 41 state->ws_error_action = warn_on_ws_error; 42return0; 43} 44if(!strcmp(option,"warn")) { 45 state->ws_error_action = warn_on_ws_error; 46return0; 47} 48if(!strcmp(option,"nowarn")) { 49 state->ws_error_action = nowarn_ws_error; 50return0; 51} 52if(!strcmp(option,"error")) { 53 state->ws_error_action = die_on_ws_error; 54return0; 55} 56if(!strcmp(option,"error-all")) { 57 state->ws_error_action = die_on_ws_error; 58 state->squelch_whitespace_errors =0; 59return0; 60} 61if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 62 state->ws_error_action = correct_ws_error; 63return0; 64} 65/* 66 * Please update $__git_whitespacelist in git-completion.bash 67 * when you add new options. 68 */ 69returnerror(_("unrecognized whitespace option '%s'"), option); 70} 71 72static intparse_ignorewhitespace_option(struct apply_state *state, 73const char*option) 74{ 75if(!option || !strcmp(option,"no") || 76!strcmp(option,"false") || !strcmp(option,"never") || 77!strcmp(option,"none")) { 78 state->ws_ignore_action = ignore_ws_none; 79return0; 80} 81if(!strcmp(option,"change")) { 82 state->ws_ignore_action = ignore_ws_change; 83return0; 84} 85returnerror(_("unrecognized whitespace ignore option '%s'"), option); 86} 87 88intinit_apply_state(struct apply_state *state, 89struct repository *repo, 90const char*prefix) 91{ 92memset(state,0,sizeof(*state)); 93 state->prefix = prefix; 94 state->repo = repo; 95 state->apply =1; 96 state->line_termination ='\n'; 97 state->p_value =1; 98 state->p_context = UINT_MAX; 99 state->squelch_whitespace_errors =5; 100 state->ws_error_action = warn_on_ws_error; 101 state->ws_ignore_action = ignore_ws_none; 102 state->linenr =1; 103string_list_init(&state->fn_table,0); 104string_list_init(&state->limit_by_name,0); 105string_list_init(&state->symlink_changes,0); 106strbuf_init(&state->root,0); 107 108git_apply_config(); 109if(apply_default_whitespace &&parse_whitespace_option(state, apply_default_whitespace)) 110return-1; 111if(apply_default_ignorewhitespace &&parse_ignorewhitespace_option(state, apply_default_ignorewhitespace)) 112return-1; 113return0; 114} 115 116voidclear_apply_state(struct apply_state *state) 117{ 118string_list_clear(&state->limit_by_name,0); 119string_list_clear(&state->symlink_changes,0); 120strbuf_release(&state->root); 121 122/* &state->fn_table is cleared at the end of apply_patch() */ 123} 124 125static voidmute_routine(const char*msg,va_list params) 126{ 127/* do nothing */ 128} 129 130intcheck_apply_state(struct apply_state *state,int force_apply) 131{ 132int is_not_gitdir = !startup_info->have_repository; 133 134if(state->apply_with_reject && state->threeway) 135returnerror(_("--reject and --3way cannot be used together.")); 136if(state->cached && state->threeway) 137returnerror(_("--cached and --3way cannot be used together.")); 138if(state->threeway) { 139if(is_not_gitdir) 140returnerror(_("--3way outside a repository")); 141 state->check_index =1; 142} 143if(state->apply_with_reject) { 144 state->apply =1; 145if(state->apply_verbosity == verbosity_normal) 146 state->apply_verbosity = verbosity_verbose; 147} 148if(!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor)) 149 state->apply =0; 150if(state->check_index && is_not_gitdir) 151returnerror(_("--index outside a repository")); 152if(state->cached) { 153if(is_not_gitdir) 154returnerror(_("--cached outside a repository")); 155 state->check_index =1; 156} 157if(state->ita_only && (state->check_index || is_not_gitdir)) 158 state->ita_only =0; 159if(state->check_index) 160 state->unsafe_paths =0; 161 162if(state->apply_verbosity <= verbosity_silent) { 163 state->saved_error_routine =get_error_routine(); 164 state->saved_warn_routine =get_warn_routine(); 165set_error_routine(mute_routine); 166set_warn_routine(mute_routine); 167} 168 169return0; 170} 171 172static voidset_default_whitespace_mode(struct apply_state *state) 173{ 174if(!state->whitespace_option && !apply_default_whitespace) 175 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 176} 177 178/* 179 * This represents one "hunk" from a patch, starting with 180 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 181 * patch text is pointed at by patch, and its byte length 182 * is stored in size. leading and trailing are the number 183 * of context lines. 184 */ 185struct fragment { 186unsigned long leading, trailing; 187unsigned long oldpos, oldlines; 188unsigned long newpos, newlines; 189/* 190 * 'patch' is usually borrowed from buf in apply_patch(), 191 * but some codepaths store an allocated buffer. 192 */ 193const char*patch; 194unsigned free_patch:1, 195 rejected:1; 196int size; 197int linenr; 198struct fragment *next; 199}; 200 201/* 202 * When dealing with a binary patch, we reuse "leading" field 203 * to store the type of the binary hunk, either deflated "delta" 204 * or deflated "literal". 205 */ 206#define binary_patch_method leading 207#define BINARY_DELTA_DEFLATED 1 208#define BINARY_LITERAL_DEFLATED 2 209 210/* 211 * This represents a "patch" to a file, both metainfo changes 212 * such as creation/deletion, filemode and content changes represented 213 * as a series of fragments. 214 */ 215struct patch { 216char*new_name, *old_name, *def_name; 217unsigned int old_mode, new_mode; 218int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 219int rejected; 220unsigned ws_rule; 221int lines_added, lines_deleted; 222int score; 223int extension_linenr;/* first line specifying delete/new/rename/copy */ 224unsigned int is_toplevel_relative:1; 225unsigned int inaccurate_eof:1; 226unsigned int is_binary:1; 227unsigned int is_copy:1; 228unsigned int is_rename:1; 229unsigned int recount:1; 230unsigned int conflicted_threeway:1; 231unsigned int direct_to_threeway:1; 232unsigned int crlf_in_old:1; 233struct fragment *fragments; 234char*result; 235size_t resultsize; 236char old_oid_prefix[GIT_MAX_HEXSZ +1]; 237char new_oid_prefix[GIT_MAX_HEXSZ +1]; 238struct patch *next; 239 240/* three-way fallback result */ 241struct object_id threeway_stage[3]; 242}; 243 244static voidfree_fragment_list(struct fragment *list) 245{ 246while(list) { 247struct fragment *next = list->next; 248if(list->free_patch) 249free((char*)list->patch); 250free(list); 251 list = next; 252} 253} 254 255static voidfree_patch(struct patch *patch) 256{ 257free_fragment_list(patch->fragments); 258free(patch->def_name); 259free(patch->old_name); 260free(patch->new_name); 261free(patch->result); 262free(patch); 263} 264 265static voidfree_patch_list(struct patch *list) 266{ 267while(list) { 268struct patch *next = list->next; 269free_patch(list); 270 list = next; 271} 272} 273 274/* 275 * A line in a file, len-bytes long (includes the terminating LF, 276 * except for an incomplete line at the end if the file ends with 277 * one), and its contents hashes to 'hash'. 278 */ 279struct line { 280size_t len; 281unsigned hash :24; 282unsigned flag :8; 283#define LINE_COMMON 1 284#define LINE_PATCHED 2 285}; 286 287/* 288 * This represents a "file", which is an array of "lines". 289 */ 290struct image { 291char*buf; 292size_t len; 293size_t nr; 294size_t alloc; 295struct line *line_allocated; 296struct line *line; 297}; 298 299static uint32_thash_line(const char*cp,size_t len) 300{ 301size_t i; 302uint32_t h; 303for(i =0, h =0; i < len; i++) { 304if(!isspace(cp[i])) { 305 h = h *3+ (cp[i] &0xff); 306} 307} 308return h; 309} 310 311/* 312 * Compare lines s1 of length n1 and s2 of length n2, ignoring 313 * whitespace difference. Returns 1 if they match, 0 otherwise 314 */ 315static intfuzzy_matchlines(const char*s1,size_t n1, 316const char*s2,size_t n2) 317{ 318const char*end1 = s1 + n1; 319const char*end2 = s2 + n2; 320 321/* ignore line endings */ 322while(s1 < end1 && (end1[-1] =='\r'|| end1[-1] =='\n')) 323 end1--; 324while(s2 < end2 && (end2[-1] =='\r'|| end2[-1] =='\n')) 325 end2--; 326 327while(s1 < end1 && s2 < end2) { 328if(isspace(*s1)) { 329/* 330 * Skip whitespace. We check on both buffers 331 * because we don't want "a b" to match "ab". 332 */ 333if(!isspace(*s2)) 334return0; 335while(s1 < end1 &&isspace(*s1)) 336 s1++; 337while(s2 < end2 &&isspace(*s2)) 338 s2++; 339}else if(*s1++ != *s2++) 340return0; 341} 342 343/* If we reached the end on one side only, lines don't match. */ 344return s1 == end1 && s2 == end2; 345} 346 347static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 348{ 349ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 350 img->line_allocated[img->nr].len = len; 351 img->line_allocated[img->nr].hash =hash_line(bol, len); 352 img->line_allocated[img->nr].flag = flag; 353 img->nr++; 354} 355 356/* 357 * "buf" has the file contents to be patched (read from various sources). 358 * attach it to "image" and add line-based index to it. 359 * "image" now owns the "buf". 360 */ 361static voidprepare_image(struct image *image,char*buf,size_t len, 362int prepare_linetable) 363{ 364const char*cp, *ep; 365 366memset(image,0,sizeof(*image)); 367 image->buf = buf; 368 image->len = len; 369 370if(!prepare_linetable) 371return; 372 373 ep = image->buf + image->len; 374 cp = image->buf; 375while(cp < ep) { 376const char*next; 377for(next = cp; next < ep && *next !='\n'; next++) 378; 379if(next < ep) 380 next++; 381add_line_info(image, cp, next - cp,0); 382 cp = next; 383} 384 image->line = image->line_allocated; 385} 386 387static voidclear_image(struct image *image) 388{ 389free(image->buf); 390free(image->line_allocated); 391memset(image,0,sizeof(*image)); 392} 393 394/* fmt must contain _one_ %s and no other substitution */ 395static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 396{ 397struct strbuf sb = STRBUF_INIT; 398 399if(patch->old_name && patch->new_name && 400strcmp(patch->old_name, patch->new_name)) { 401quote_c_style(patch->old_name, &sb, NULL,0); 402strbuf_addstr(&sb," => "); 403quote_c_style(patch->new_name, &sb, NULL,0); 404}else{ 405const char*n = patch->new_name; 406if(!n) 407 n = patch->old_name; 408quote_c_style(n, &sb, NULL,0); 409} 410fprintf(output, fmt, sb.buf); 411fputc('\n', output); 412strbuf_release(&sb); 413} 414 415#define SLOP (16) 416 417static intread_patch_file(struct strbuf *sb,int fd) 418{ 419if(strbuf_read(sb, fd,0) <0) 420returnerror_errno("git apply: failed to read"); 421 422/* 423 * Make sure that we have some slop in the buffer 424 * so that we can do speculative "memcmp" etc, and 425 * see to it that it is NUL-filled. 426 */ 427strbuf_grow(sb, SLOP); 428memset(sb->buf + sb->len,0, SLOP); 429return0; 430} 431 432static unsigned longlinelen(const char*buffer,unsigned long size) 433{ 434unsigned long len =0; 435while(size--) { 436 len++; 437if(*buffer++ =='\n') 438break; 439} 440return len; 441} 442 443static intis_dev_null(const char*str) 444{ 445returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 446} 447 448#define TERM_SPACE 1 449#define TERM_TAB 2 450 451static intname_terminate(int c,int terminate) 452{ 453if(c ==' '&& !(terminate & TERM_SPACE)) 454return0; 455if(c =='\t'&& !(terminate & TERM_TAB)) 456return0; 457 458return1; 459} 460 461/* remove double slashes to make --index work with such filenames */ 462static char*squash_slash(char*name) 463{ 464int i =0, j =0; 465 466if(!name) 467return NULL; 468 469while(name[i]) { 470if((name[j++] = name[i++]) =='/') 471while(name[i] =='/') 472 i++; 473} 474 name[j] ='\0'; 475return name; 476} 477 478static char*find_name_gnu(struct strbuf *root, 479const char*line, 480int p_value) 481{ 482struct strbuf name = STRBUF_INIT; 483char*cp; 484 485/* 486 * Proposed "new-style" GNU patch/diff format; see 487 * https://public-inbox.org/git/7vll0wvb2a.fsf@assigned-by-dhcp.cox.net/ 488 */ 489if(unquote_c_style(&name, line, NULL)) { 490strbuf_release(&name); 491return NULL; 492} 493 494for(cp = name.buf; p_value; p_value--) { 495 cp =strchr(cp,'/'); 496if(!cp) { 497strbuf_release(&name); 498return NULL; 499} 500 cp++; 501} 502 503strbuf_remove(&name,0, cp - name.buf); 504if(root->len) 505strbuf_insert(&name,0, root->buf, root->len); 506returnsquash_slash(strbuf_detach(&name, NULL)); 507} 508 509static size_tsane_tz_len(const char*line,size_t len) 510{ 511const char*tz, *p; 512 513if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 514return0; 515 tz = line + len -strlen(" +0500"); 516 517if(tz[1] !='+'&& tz[1] !='-') 518return0; 519 520for(p = tz +2; p != line + len; p++) 521if(!isdigit(*p)) 522return0; 523 524return line + len - tz; 525} 526 527static size_ttz_with_colon_len(const char*line,size_t len) 528{ 529const char*tz, *p; 530 531if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 532return0; 533 tz = line + len -strlen(" +08:00"); 534 535if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 536return0; 537 p = tz +2; 538if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 539!isdigit(*p++) || !isdigit(*p++)) 540return0; 541 542return line + len - tz; 543} 544 545static size_tdate_len(const char*line,size_t len) 546{ 547const char*date, *p; 548 549if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 550return0; 551 p = date = line + len -strlen("72-02-05"); 552 553if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 554!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 555!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 556return0; 557 558if(date - line >=strlen("19") && 559isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 560 date -=strlen("19"); 561 562return line + len - date; 563} 564 565static size_tshort_time_len(const char*line,size_t len) 566{ 567const char*time, *p; 568 569if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 570return0; 571 p = time = line + len -strlen(" 07:01:32"); 572 573/* Permit 1-digit hours? */ 574if(*p++ !=' '|| 575!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 576!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 577!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 578return0; 579 580return line + len - time; 581} 582 583static size_tfractional_time_len(const char*line,size_t len) 584{ 585const char*p; 586size_t n; 587 588/* Expected format: 19:41:17.620000023 */ 589if(!len || !isdigit(line[len -1])) 590return0; 591 p = line + len -1; 592 593/* Fractional seconds. */ 594while(p > line &&isdigit(*p)) 595 p--; 596if(*p !='.') 597return0; 598 599/* Hours, minutes, and whole seconds. */ 600 n =short_time_len(line, p - line); 601if(!n) 602return0; 603 604return line + len - p + n; 605} 606 607static size_ttrailing_spaces_len(const char*line,size_t len) 608{ 609const char*p; 610 611/* Expected format: ' ' x (1 or more) */ 612if(!len || line[len -1] !=' ') 613return0; 614 615 p = line + len; 616while(p != line) { 617 p--; 618if(*p !=' ') 619return line + len - (p +1); 620} 621 622/* All spaces! */ 623return len; 624} 625 626static size_tdiff_timestamp_len(const char*line,size_t len) 627{ 628const char*end = line + len; 629size_t n; 630 631/* 632 * Posix: 2010-07-05 19:41:17 633 * GNU: 2010-07-05 19:41:17.620000023 -0500 634 */ 635 636if(!isdigit(end[-1])) 637return0; 638 639 n =sane_tz_len(line, end - line); 640if(!n) 641 n =tz_with_colon_len(line, end - line); 642 end -= n; 643 644 n =short_time_len(line, end - line); 645if(!n) 646 n =fractional_time_len(line, end - line); 647 end -= n; 648 649 n =date_len(line, end - line); 650if(!n)/* No date. Too bad. */ 651return0; 652 end -= n; 653 654if(end == line)/* No space before date. */ 655return0; 656if(end[-1] =='\t') {/* Success! */ 657 end--; 658return line + len - end; 659} 660if(end[-1] !=' ')/* No space before date. */ 661return0; 662 663/* Whitespace damage. */ 664 end -=trailing_spaces_len(line, end - line); 665return line + len - end; 666} 667 668static char*find_name_common(struct strbuf *root, 669const char*line, 670const char*def, 671int p_value, 672const char*end, 673int terminate) 674{ 675int len; 676const char*start = NULL; 677 678if(p_value ==0) 679 start = line; 680while(line != end) { 681char c = *line; 682 683if(!end &&isspace(c)) { 684if(c =='\n') 685break; 686if(name_terminate(c, terminate)) 687break; 688} 689 line++; 690if(c =='/'&& !--p_value) 691 start = line; 692} 693if(!start) 694returnsquash_slash(xstrdup_or_null(def)); 695 len = line - start; 696if(!len) 697returnsquash_slash(xstrdup_or_null(def)); 698 699/* 700 * Generally we prefer the shorter name, especially 701 * if the other one is just a variation of that with 702 * something else tacked on to the end (ie "file.orig" 703 * or "file~"). 704 */ 705if(def) { 706int deflen =strlen(def); 707if(deflen < len && !strncmp(start, def, deflen)) 708returnsquash_slash(xstrdup(def)); 709} 710 711if(root->len) { 712char*ret =xstrfmt("%s%.*s", root->buf, len, start); 713returnsquash_slash(ret); 714} 715 716returnsquash_slash(xmemdupz(start, len)); 717} 718 719static char*find_name(struct strbuf *root, 720const char*line, 721char*def, 722int p_value, 723int terminate) 724{ 725if(*line =='"') { 726char*name =find_name_gnu(root, line, p_value); 727if(name) 728return name; 729} 730 731returnfind_name_common(root, line, def, p_value, NULL, terminate); 732} 733 734static char*find_name_traditional(struct strbuf *root, 735const char*line, 736char*def, 737int p_value) 738{ 739size_t len; 740size_t date_len; 741 742if(*line =='"') { 743char*name =find_name_gnu(root, line, p_value); 744if(name) 745return name; 746} 747 748 len =strchrnul(line,'\n') - line; 749 date_len =diff_timestamp_len(line, len); 750if(!date_len) 751returnfind_name_common(root, line, def, p_value, NULL, TERM_TAB); 752 len -= date_len; 753 754returnfind_name_common(root, line, def, p_value, line + len,0); 755} 756 757/* 758 * Given the string after "--- " or "+++ ", guess the appropriate 759 * p_value for the given patch. 760 */ 761static intguess_p_value(struct apply_state *state,const char*nameline) 762{ 763char*name, *cp; 764int val = -1; 765 766if(is_dev_null(nameline)) 767return-1; 768 name =find_name_traditional(&state->root, nameline, NULL,0); 769if(!name) 770return-1; 771 cp =strchr(name,'/'); 772if(!cp) 773 val =0; 774else if(state->prefix) { 775/* 776 * Does it begin with "a/$our-prefix" and such? Then this is 777 * very likely to apply to our directory. 778 */ 779if(starts_with(name, state->prefix)) 780 val =count_slashes(state->prefix); 781else{ 782 cp++; 783if(starts_with(cp, state->prefix)) 784 val =count_slashes(state->prefix) +1; 785} 786} 787free(name); 788return val; 789} 790 791/* 792 * Does the ---/+++ line have the POSIX timestamp after the last HT? 793 * GNU diff puts epoch there to signal a creation/deletion event. Is 794 * this such a timestamp? 795 */ 796static inthas_epoch_timestamp(const char*nameline) 797{ 798/* 799 * We are only interested in epoch timestamp; any non-zero 800 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 801 * For the same reason, the date must be either 1969-12-31 or 802 * 1970-01-01, and the seconds part must be "00". 803 */ 804const char stamp_regexp[] = 805"^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?" 806" " 807"([-+][0-2][0-9]:?[0-5][0-9])\n"; 808const char*timestamp = NULL, *cp, *colon; 809static regex_t *stamp; 810 regmatch_t m[10]; 811int zoneoffset, epoch_hour, hour, minute; 812int status; 813 814for(cp = nameline; *cp !='\n'; cp++) { 815if(*cp =='\t') 816 timestamp = cp +1; 817} 818if(!timestamp) 819return0; 820 821/* 822 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 823 * (west of GMT) or 1970-01-01 (east of GMT) 824 */ 825if(skip_prefix(timestamp,"1969-12-31 ", ×tamp)) 826 epoch_hour =24; 827else if(skip_prefix(timestamp,"1970-01-01 ", ×tamp)) 828 epoch_hour =0; 829else 830return0; 831 832if(!stamp) { 833 stamp =xmalloc(sizeof(*stamp)); 834if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 835warning(_("Cannot prepare timestamp regexp%s"), 836 stamp_regexp); 837return0; 838} 839} 840 841 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 842if(status) { 843if(status != REG_NOMATCH) 844warning(_("regexec returned%dfor input:%s"), 845 status, timestamp); 846return0; 847} 848 849 hour =strtol(timestamp, NULL,10); 850 minute =strtol(timestamp + m[1].rm_so, NULL,10); 851 852 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 853if(*colon ==':') 854 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 855else 856 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 857if(timestamp[m[3].rm_so] =='-') 858 zoneoffset = -zoneoffset; 859 860return hour *60+ minute - zoneoffset == epoch_hour *60; 861} 862 863/* 864 * Get the name etc info from the ---/+++ lines of a traditional patch header 865 * 866 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 867 * files, we can happily check the index for a match, but for creating a 868 * new file we should try to match whatever "patch" does. I have no idea. 869 */ 870static intparse_traditional_patch(struct apply_state *state, 871const char*first, 872const char*second, 873struct patch *patch) 874{ 875char*name; 876 877 first +=4;/* skip "--- " */ 878 second +=4;/* skip "+++ " */ 879if(!state->p_value_known) { 880int p, q; 881 p =guess_p_value(state, first); 882 q =guess_p_value(state, second); 883if(p <0) p = q; 884if(0<= p && p == q) { 885 state->p_value = p; 886 state->p_value_known =1; 887} 888} 889if(is_dev_null(first)) { 890 patch->is_new =1; 891 patch->is_delete =0; 892 name =find_name_traditional(&state->root, second, NULL, state->p_value); 893 patch->new_name = name; 894}else if(is_dev_null(second)) { 895 patch->is_new =0; 896 patch->is_delete =1; 897 name =find_name_traditional(&state->root, first, NULL, state->p_value); 898 patch->old_name = name; 899}else{ 900char*first_name; 901 first_name =find_name_traditional(&state->root, first, NULL, state->p_value); 902 name =find_name_traditional(&state->root, second, first_name, state->p_value); 903free(first_name); 904if(has_epoch_timestamp(first)) { 905 patch->is_new =1; 906 patch->is_delete =0; 907 patch->new_name = name; 908}else if(has_epoch_timestamp(second)) { 909 patch->is_new =0; 910 patch->is_delete =1; 911 patch->old_name = name; 912}else{ 913 patch->old_name = name; 914 patch->new_name =xstrdup_or_null(name); 915} 916} 917if(!name) 918returnerror(_("unable to find filename in patch at line%d"), state->linenr); 919 920return0; 921} 922 923static intgitdiff_hdrend(struct gitdiff_data *state, 924const char*line, 925struct patch *patch) 926{ 927return1; 928} 929 930/* 931 * We're anal about diff header consistency, to make 932 * sure that we don't end up having strange ambiguous 933 * patches floating around. 934 * 935 * As a result, gitdiff_{old|new}name() will check 936 * their names against any previous information, just 937 * to make sure.. 938 */ 939#define DIFF_OLD_NAME 0 940#define DIFF_NEW_NAME 1 941 942static intgitdiff_verify_name(struct gitdiff_data *state, 943const char*line, 944int isnull, 945char**name, 946int side) 947{ 948if(!*name && !isnull) { 949*name =find_name(state->root, line, NULL, state->p_value, TERM_TAB); 950return0; 951} 952 953if(*name) { 954char*another; 955if(isnull) 956returnerror(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 957*name, state->linenr); 958 another =find_name(state->root, line, NULL, state->p_value, TERM_TAB); 959if(!another ||strcmp(another, *name)) { 960free(another); 961returnerror((side == DIFF_NEW_NAME) ? 962_("git apply: bad git-diff - inconsistent new filename on line%d") : 963_("git apply: bad git-diff - inconsistent old filename on line%d"), state->linenr); 964} 965free(another); 966}else{ 967if(!is_dev_null(line)) 968returnerror(_("git apply: bad git-diff - expected /dev/null on line%d"), state->linenr); 969} 970 971return0; 972} 973 974static intgitdiff_oldname(struct gitdiff_data *state, 975const char*line, 976struct patch *patch) 977{ 978returngitdiff_verify_name(state, line, 979 patch->is_new, &patch->old_name, 980 DIFF_OLD_NAME); 981} 982 983static intgitdiff_newname(struct gitdiff_data *state, 984const char*line, 985struct patch *patch) 986{ 987returngitdiff_verify_name(state, line, 988 patch->is_delete, &patch->new_name, 989 DIFF_NEW_NAME); 990} 991 992static intparse_mode_line(const char*line,int linenr,unsigned int*mode) 993{ 994char*end; 995*mode =strtoul(line, &end,8); 996if(end == line || !isspace(*end)) 997returnerror(_("invalid mode on line%d:%s"), linenr, line); 998return0; 999}10001001static intgitdiff_oldmode(struct gitdiff_data *state,1002const char*line,1003struct patch *patch)1004{1005returnparse_mode_line(line, state->linenr, &patch->old_mode);1006}10071008static intgitdiff_newmode(struct gitdiff_data *state,1009const char*line,1010struct patch *patch)1011{1012returnparse_mode_line(line, state->linenr, &patch->new_mode);1013}10141015static intgitdiff_delete(struct gitdiff_data *state,1016const char*line,1017struct patch *patch)1018{1019 patch->is_delete =1;1020free(patch->old_name);1021 patch->old_name =xstrdup_or_null(patch->def_name);1022returngitdiff_oldmode(state, line, patch);1023}10241025static intgitdiff_newfile(struct gitdiff_data *state,1026const char*line,1027struct patch *patch)1028{1029 patch->is_new =1;1030free(patch->new_name);1031 patch->new_name =xstrdup_or_null(patch->def_name);1032returngitdiff_newmode(state, line, patch);1033}10341035static intgitdiff_copysrc(struct gitdiff_data *state,1036const char*line,1037struct patch *patch)1038{1039 patch->is_copy =1;1040free(patch->old_name);1041 patch->old_name =find_name(state->root, line, NULL, state->p_value ? state->p_value -1:0,0);1042return0;1043}10441045static intgitdiff_copydst(struct gitdiff_data *state,1046const char*line,1047struct patch *patch)1048{1049 patch->is_copy =1;1050free(patch->new_name);1051 patch->new_name =find_name(state->root, line, NULL, state->p_value ? state->p_value -1:0,0);1052return0;1053}10541055static intgitdiff_renamesrc(struct gitdiff_data *state,1056const char*line,1057struct patch *patch)1058{1059 patch->is_rename =1;1060free(patch->old_name);1061 patch->old_name =find_name(state->root, line, NULL, state->p_value ? state->p_value -1:0,0);1062return0;1063}10641065static intgitdiff_renamedst(struct gitdiff_data *state,1066const char*line,1067struct patch *patch)1068{1069 patch->is_rename =1;1070free(patch->new_name);1071 patch->new_name =find_name(state->root, line, NULL, state->p_value ? state->p_value -1:0,0);1072return0;1073}10741075static intgitdiff_similarity(struct gitdiff_data *state,1076const char*line,1077struct patch *patch)1078{1079unsigned long val =strtoul(line, NULL,10);1080if(val <=100)1081 patch->score = val;1082return0;1083}10841085static intgitdiff_dissimilarity(struct gitdiff_data *state,1086const char*line,1087struct patch *patch)1088{1089unsigned long val =strtoul(line, NULL,10);1090if(val <=100)1091 patch->score = val;1092return0;1093}10941095static intgitdiff_index(struct gitdiff_data *state,1096const char*line,1097struct patch *patch)1098{1099/*1100 * index line is N hexadecimal, "..", N hexadecimal,1101 * and optional space with octal mode.1102 */1103const char*ptr, *eol;1104int len;1105const unsigned hexsz = the_hash_algo->hexsz;11061107 ptr =strchr(line,'.');1108if(!ptr || ptr[1] !='.'|| hexsz < ptr - line)1109return0;1110 len = ptr - line;1111memcpy(patch->old_oid_prefix, line, len);1112 patch->old_oid_prefix[len] =0;11131114 line = ptr +2;1115 ptr =strchr(line,' ');1116 eol =strchrnul(line,'\n');11171118if(!ptr || eol < ptr)1119 ptr = eol;1120 len = ptr - line;11211122if(hexsz < len)1123return0;1124memcpy(patch->new_oid_prefix, line, len);1125 patch->new_oid_prefix[len] =0;1126if(*ptr ==' ')1127returngitdiff_oldmode(state, ptr +1, patch);1128return0;1129}11301131/*1132 * This is normal for a diff that doesn't change anything: we'll fall through1133 * into the next diff. Tell the parser to break out.1134 */1135static intgitdiff_unrecognized(struct gitdiff_data *state,1136const char*line,1137struct patch *patch)1138{1139return1;1140}11411142/*1143 * Skip p_value leading components from "line"; as we do not accept1144 * absolute paths, return NULL in that case.1145 */1146static const char*skip_tree_prefix(int p_value,1147const char*line,1148int llen)1149{1150int nslash;1151int i;11521153if(!p_value)1154return(llen && line[0] =='/') ? NULL : line;11551156 nslash = p_value;1157for(i =0; i < llen; i++) {1158int ch = line[i];1159if(ch =='/'&& --nslash <=0)1160return(i ==0) ? NULL : &line[i +1];1161}1162return NULL;1163}11641165/*1166 * This is to extract the same name that appears on "diff --git"1167 * line. We do not find and return anything if it is a rename1168 * patch, and it is OK because we will find the name elsewhere.1169 * We need to reliably find name only when it is mode-change only,1170 * creation or deletion of an empty file. In any of these cases,1171 * both sides are the same name under a/ and b/ respectively.1172 */1173static char*git_header_name(int p_value,1174const char*line,1175int llen)1176{1177const char*name;1178const char*second = NULL;1179size_t len, line_len;11801181 line +=strlen("diff --git ");1182 llen -=strlen("diff --git ");11831184if(*line =='"') {1185const char*cp;1186struct strbuf first = STRBUF_INIT;1187struct strbuf sp = STRBUF_INIT;11881189if(unquote_c_style(&first, line, &second))1190goto free_and_fail1;11911192/* strip the a/b prefix including trailing slash */1193 cp =skip_tree_prefix(p_value, first.buf, first.len);1194if(!cp)1195goto free_and_fail1;1196strbuf_remove(&first,0, cp - first.buf);11971198/*1199 * second points at one past closing dq of name.1200 * find the second name.1201 */1202while((second < line + llen) &&isspace(*second))1203 second++;12041205if(line + llen <= second)1206goto free_and_fail1;1207if(*second =='"') {1208if(unquote_c_style(&sp, second, NULL))1209goto free_and_fail1;1210 cp =skip_tree_prefix(p_value, sp.buf, sp.len);1211if(!cp)1212goto free_and_fail1;1213/* They must match, otherwise ignore */1214if(strcmp(cp, first.buf))1215goto free_and_fail1;1216strbuf_release(&sp);1217returnstrbuf_detach(&first, NULL);1218}12191220/* unquoted second */1221 cp =skip_tree_prefix(p_value, second, line + llen - second);1222if(!cp)1223goto free_and_fail1;1224if(line + llen - cp != first.len ||1225memcmp(first.buf, cp, first.len))1226goto free_and_fail1;1227returnstrbuf_detach(&first, NULL);12281229 free_and_fail1:1230strbuf_release(&first);1231strbuf_release(&sp);1232return NULL;1233}12341235/* unquoted first name */1236 name =skip_tree_prefix(p_value, line, llen);1237if(!name)1238return NULL;12391240/*1241 * since the first name is unquoted, a dq if exists must be1242 * the beginning of the second name.1243 */1244for(second = name; second < line + llen; second++) {1245if(*second =='"') {1246struct strbuf sp = STRBUF_INIT;1247const char*np;12481249if(unquote_c_style(&sp, second, NULL))1250goto free_and_fail2;12511252 np =skip_tree_prefix(p_value, sp.buf, sp.len);1253if(!np)1254goto free_and_fail2;12551256 len = sp.buf + sp.len - np;1257if(len < second - name &&1258!strncmp(np, name, len) &&1259isspace(name[len])) {1260/* Good */1261strbuf_remove(&sp,0, np - sp.buf);1262returnstrbuf_detach(&sp, NULL);1263}12641265 free_and_fail2:1266strbuf_release(&sp);1267return NULL;1268}1269}12701271/*1272 * Accept a name only if it shows up twice, exactly the same1273 * form.1274 */1275 second =strchr(name,'\n');1276if(!second)1277return NULL;1278 line_len = second - name;1279for(len =0; ; len++) {1280switch(name[len]) {1281default:1282continue;1283case'\n':1284return NULL;1285case'\t':case' ':1286/*1287 * Is this the separator between the preimage1288 * and the postimage pathname? Again, we are1289 * only interested in the case where there is1290 * no rename, as this is only to set def_name1291 * and a rename patch has the names elsewhere1292 * in an unambiguous form.1293 */1294if(!name[len +1])1295return NULL;/* no postimage name */1296 second =skip_tree_prefix(p_value, name + len +1,1297 line_len - (len +1));1298if(!second)1299return NULL;1300/*1301 * Does len bytes starting at "name" and "second"1302 * (that are separated by one HT or SP we just1303 * found) exactly match?1304 */1305if(second[len] =='\n'&& !strncmp(name, second, len))1306returnxmemdupz(name, len);1307}1308}1309}13101311static intcheck_header_line(int linenr,struct patch *patch)1312{1313int extensions = (patch->is_delete ==1) + (patch->is_new ==1) +1314(patch->is_rename ==1) + (patch->is_copy ==1);1315if(extensions >1)1316returnerror(_("inconsistent header lines%dand%d"),1317 patch->extension_linenr, linenr);1318if(extensions && !patch->extension_linenr)1319 patch->extension_linenr = linenr;1320return0;1321}13221323/* Verify that we recognize the lines following a git header */1324static intparse_git_header(struct apply_state *state,1325const char*line,1326int len,1327unsigned int size,1328struct patch *patch)1329{1330unsigned long offset;1331struct gitdiff_data parse_hdr_state;13321333/* A git diff has explicit new/delete information, so we don't guess */1334 patch->is_new =0;1335 patch->is_delete =0;13361337/*1338 * Some things may not have the old name in the1339 * rest of the headers anywhere (pure mode changes,1340 * or removing or adding empty files), so we get1341 * the default name from the header.1342 */1343 patch->def_name =git_header_name(state->p_value, line, len);1344if(patch->def_name && state->root.len) {1345char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1346free(patch->def_name);1347 patch->def_name = s;1348}13491350 line += len;1351 size -= len;1352 state->linenr++;1353 parse_hdr_state.root = &state->root;1354 parse_hdr_state.linenr = state->linenr;1355 parse_hdr_state.p_value = state->p_value;13561357for(offset = len ; size >0; offset += len, size -= len, line += len, state->linenr++) {1358static const struct opentry {1359const char*str;1360int(*fn)(struct gitdiff_data *,const char*,struct patch *);1361} optable[] = {1362{"@@ -", gitdiff_hdrend },1363{"--- ", gitdiff_oldname },1364{"+++ ", gitdiff_newname },1365{"old mode ", gitdiff_oldmode },1366{"new mode ", gitdiff_newmode },1367{"deleted file mode ", gitdiff_delete },1368{"new file mode ", gitdiff_newfile },1369{"copy from ", gitdiff_copysrc },1370{"copy to ", gitdiff_copydst },1371{"rename old ", gitdiff_renamesrc },1372{"rename new ", gitdiff_renamedst },1373{"rename from ", gitdiff_renamesrc },1374{"rename to ", gitdiff_renamedst },1375{"similarity index ", gitdiff_similarity },1376{"dissimilarity index ", gitdiff_dissimilarity },1377{"index ", gitdiff_index },1378{"", gitdiff_unrecognized },1379};1380int i;13811382 len =linelen(line, size);1383if(!len || line[len-1] !='\n')1384break;1385for(i =0; i <ARRAY_SIZE(optable); i++) {1386const struct opentry *p = optable + i;1387int oplen =strlen(p->str);1388int res;1389if(len < oplen ||memcmp(p->str, line, oplen))1390continue;1391 res = p->fn(&parse_hdr_state, line + oplen, patch);1392if(res <0)1393return-1;1394if(check_header_line(state->linenr, patch))1395return-1;1396if(res >0)1397return offset;1398break;1399}1400}14011402return offset;1403}14041405static intparse_num(const char*line,unsigned long*p)1406{1407char*ptr;14081409if(!isdigit(*line))1410return0;1411*p =strtoul(line, &ptr,10);1412return ptr - line;1413}14141415static intparse_range(const char*line,int len,int offset,const char*expect,1416unsigned long*p1,unsigned long*p2)1417{1418int digits, ex;14191420if(offset <0|| offset >= len)1421return-1;1422 line += offset;1423 len -= offset;14241425 digits =parse_num(line, p1);1426if(!digits)1427return-1;14281429 offset += digits;1430 line += digits;1431 len -= digits;14321433*p2 =1;1434if(*line ==',') {1435 digits =parse_num(line+1, p2);1436if(!digits)1437return-1;14381439 offset += digits+1;1440 line += digits+1;1441 len -= digits+1;1442}14431444 ex =strlen(expect);1445if(ex > len)1446return-1;1447if(memcmp(line, expect, ex))1448return-1;14491450return offset + ex;1451}14521453static voidrecount_diff(const char*line,int size,struct fragment *fragment)1454{1455int oldlines =0, newlines =0, ret =0;14561457if(size <1) {1458warning("recount: ignore empty hunk");1459return;1460}14611462for(;;) {1463int len =linelen(line, size);1464 size -= len;1465 line += len;14661467if(size <1)1468break;14691470switch(*line) {1471case' ':case'\n':1472 newlines++;1473/* fall through */1474case'-':1475 oldlines++;1476continue;1477case'+':1478 newlines++;1479continue;1480case'\\':1481continue;1482case'@':1483 ret = size <3|| !starts_with(line,"@@ ");1484break;1485case'd':1486 ret = size <5|| !starts_with(line,"diff ");1487break;1488default:1489 ret = -1;1490break;1491}1492if(ret) {1493warning(_("recount: unexpected line: %.*s"),1494(int)linelen(line, size), line);1495return;1496}1497break;1498}1499 fragment->oldlines = oldlines;1500 fragment->newlines = newlines;1501}15021503/*1504 * Parse a unified diff fragment header of the1505 * form "@@ -a,b +c,d @@"1506 */1507static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1508{1509int offset;15101511if(!len || line[len-1] !='\n')1512return-1;15131514/* Figure out the number of lines in a fragment */1515 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1516 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);15171518return offset;1519}15201521/*1522 * Find file diff header1523 *1524 * Returns:1525 * -1 if no header was found1526 * -128 in case of error1527 * the size of the header in bytes (called "offset") otherwise1528 */1529static intfind_header(struct apply_state *state,1530const char*line,1531unsigned long size,1532int*hdrsize,1533struct patch *patch)1534{1535unsigned long offset, len;15361537 patch->is_toplevel_relative =0;1538 patch->is_rename = patch->is_copy =0;1539 patch->is_new = patch->is_delete = -1;1540 patch->old_mode = patch->new_mode =0;1541 patch->old_name = patch->new_name = NULL;1542for(offset =0; size >0; offset += len, size -= len, line += len, state->linenr++) {1543unsigned long nextlen;15441545 len =linelen(line, size);1546if(!len)1547break;15481549/* Testing this early allows us to take a few shortcuts.. */1550if(len <6)1551continue;15521553/*1554 * Make sure we don't find any unconnected patch fragments.1555 * That's a sign that we didn't find a header, and that a1556 * patch has become corrupted/broken up.1557 */1558if(!memcmp("@@ -", line,4)) {1559struct fragment dummy;1560if(parse_fragment_header(line, len, &dummy) <0)1561continue;1562error(_("patch fragment without header at line%d: %.*s"),1563 state->linenr, (int)len-1, line);1564return-128;1565}15661567if(size < len +6)1568break;15691570/*1571 * Git patch? It might not have a real patch, just a rename1572 * or mode change, so we handle that specially1573 */1574if(!memcmp("diff --git ", line,11)) {1575int git_hdr_len =parse_git_header(state, line, len, size, patch);1576if(git_hdr_len <0)1577return-128;1578if(git_hdr_len <= len)1579continue;1580if(!patch->old_name && !patch->new_name) {1581if(!patch->def_name) {1582error(Q_("git diff header lacks filename information when removing "1583"%dleading pathname component (line%d)",1584"git diff header lacks filename information when removing "1585"%dleading pathname components (line%d)",1586 state->p_value),1587 state->p_value, state->linenr);1588return-128;1589}1590 patch->old_name =xstrdup(patch->def_name);1591 patch->new_name =xstrdup(patch->def_name);1592}1593if((!patch->new_name && !patch->is_delete) ||1594(!patch->old_name && !patch->is_new)) {1595error(_("git diff header lacks filename information "1596"(line%d)"), state->linenr);1597return-128;1598}1599 patch->is_toplevel_relative =1;1600*hdrsize = git_hdr_len;1601return offset;1602}16031604/* --- followed by +++ ? */1605if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1606continue;16071608/*1609 * We only accept unified patches, so we want it to1610 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1611 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1612 */1613 nextlen =linelen(line + len, size - len);1614if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1615continue;16161617/* Ok, we'll consider it a patch */1618if(parse_traditional_patch(state, line, line+len, patch))1619return-128;1620*hdrsize = len + nextlen;1621 state->linenr +=2;1622return offset;1623}1624return-1;1625}16261627static voidrecord_ws_error(struct apply_state *state,1628unsigned result,1629const char*line,1630int len,1631int linenr)1632{1633char*err;16341635if(!result)1636return;16371638 state->whitespace_error++;1639if(state->squelch_whitespace_errors &&1640 state->squelch_whitespace_errors < state->whitespace_error)1641return;16421643 err =whitespace_error_string(result);1644if(state->apply_verbosity > verbosity_silent)1645fprintf(stderr,"%s:%d:%s.\n%.*s\n",1646 state->patch_input_file, linenr, err, len, line);1647free(err);1648}16491650static voidcheck_whitespace(struct apply_state *state,1651const char*line,1652int len,1653unsigned ws_rule)1654{1655unsigned result =ws_check(line +1, len -1, ws_rule);16561657record_ws_error(state, result, line +1, len -2, state->linenr);1658}16591660/*1661 * Check if the patch has context lines with CRLF or1662 * the patch wants to remove lines with CRLF.1663 */1664static voidcheck_old_for_crlf(struct patch *patch,const char*line,int len)1665{1666if(len >=2&& line[len-1] =='\n'&& line[len-2] =='\r') {1667 patch->ws_rule |= WS_CR_AT_EOL;1668 patch->crlf_in_old =1;1669}1670}167116721673/*1674 * Parse a unified diff. Note that this really needs to parse each1675 * fragment separately, since the only way to know the difference1676 * between a "---" that is part of a patch, and a "---" that starts1677 * the next patch is to look at the line counts..1678 */1679static intparse_fragment(struct apply_state *state,1680const char*line,1681unsigned long size,1682struct patch *patch,1683struct fragment *fragment)1684{1685int added, deleted;1686int len =linelen(line, size), offset;1687unsigned long oldlines, newlines;1688unsigned long leading, trailing;16891690 offset =parse_fragment_header(line, len, fragment);1691if(offset <0)1692return-1;1693if(offset >0&& patch->recount)1694recount_diff(line + offset, size - offset, fragment);1695 oldlines = fragment->oldlines;1696 newlines = fragment->newlines;1697 leading =0;1698 trailing =0;16991700/* Parse the thing.. */1701 line += len;1702 size -= len;1703 state->linenr++;1704 added = deleted =0;1705for(offset = len;17060< size;1707 offset += len, size -= len, line += len, state->linenr++) {1708if(!oldlines && !newlines)1709break;1710 len =linelen(line, size);1711if(!len || line[len-1] !='\n')1712return-1;1713switch(*line) {1714default:1715return-1;1716case'\n':/* newer GNU diff, an empty context line */1717case' ':1718 oldlines--;1719 newlines--;1720if(!deleted && !added)1721 leading++;1722 trailing++;1723check_old_for_crlf(patch, line, len);1724if(!state->apply_in_reverse &&1725 state->ws_error_action == correct_ws_error)1726check_whitespace(state, line, len, patch->ws_rule);1727break;1728case'-':1729if(!state->apply_in_reverse)1730check_old_for_crlf(patch, line, len);1731if(state->apply_in_reverse &&1732 state->ws_error_action != nowarn_ws_error)1733check_whitespace(state, line, len, patch->ws_rule);1734 deleted++;1735 oldlines--;1736 trailing =0;1737break;1738case'+':1739if(state->apply_in_reverse)1740check_old_for_crlf(patch, line, len);1741if(!state->apply_in_reverse &&1742 state->ws_error_action != nowarn_ws_error)1743check_whitespace(state, line, len, patch->ws_rule);1744 added++;1745 newlines--;1746 trailing =0;1747break;17481749/*1750 * We allow "\ No newline at end of file". Depending1751 * on locale settings when the patch was produced we1752 * don't know what this line looks like. The only1753 * thing we do know is that it begins with "\ ".1754 * Checking for 12 is just for sanity check -- any1755 * l10n of "\ No newline..." is at least that long.1756 */1757case'\\':1758if(len <12||memcmp(line,"\\",2))1759return-1;1760break;1761}1762}1763if(oldlines || newlines)1764return-1;1765if(!patch->recount && !deleted && !added)1766return-1;17671768 fragment->leading = leading;1769 fragment->trailing = trailing;17701771/*1772 * If a fragment ends with an incomplete line, we failed to include1773 * it in the above loop because we hit oldlines == newlines == 01774 * before seeing it.1775 */1776if(12< size && !memcmp(line,"\\",2))1777 offset +=linelen(line, size);17781779 patch->lines_added += added;1780 patch->lines_deleted += deleted;17811782if(0< patch->is_new && oldlines)1783returnerror(_("new file depends on old contents"));1784if(0< patch->is_delete && newlines)1785returnerror(_("deleted file still has contents"));1786return offset;1787}17881789/*1790 * We have seen "diff --git a/... b/..." header (or a traditional patch1791 * header). Read hunks that belong to this patch into fragments and hang1792 * them to the given patch structure.1793 *1794 * The (fragment->patch, fragment->size) pair points into the memory given1795 * by the caller, not a copy, when we return.1796 *1797 * Returns:1798 * -1 in case of error,1799 * the number of bytes in the patch otherwise.1800 */1801static intparse_single_patch(struct apply_state *state,1802const char*line,1803unsigned long size,1804struct patch *patch)1805{1806unsigned long offset =0;1807unsigned long oldlines =0, newlines =0, context =0;1808struct fragment **fragp = &patch->fragments;18091810while(size >4&& !memcmp(line,"@@ -",4)) {1811struct fragment *fragment;1812int len;18131814 fragment =xcalloc(1,sizeof(*fragment));1815 fragment->linenr = state->linenr;1816 len =parse_fragment(state, line, size, patch, fragment);1817if(len <=0) {1818free(fragment);1819returnerror(_("corrupt patch at line%d"), state->linenr);1820}1821 fragment->patch = line;1822 fragment->size = len;1823 oldlines += fragment->oldlines;1824 newlines += fragment->newlines;1825 context += fragment->leading + fragment->trailing;18261827*fragp = fragment;1828 fragp = &fragment->next;18291830 offset += len;1831 line += len;1832 size -= len;1833}18341835/*1836 * If something was removed (i.e. we have old-lines) it cannot1837 * be creation, and if something was added it cannot be1838 * deletion. However, the reverse is not true; --unified=01839 * patches that only add are not necessarily creation even1840 * though they do not have any old lines, and ones that only1841 * delete are not necessarily deletion.1842 *1843 * Unfortunately, a real creation/deletion patch do _not_ have1844 * any context line by definition, so we cannot safely tell it1845 * apart with --unified=0 insanity. At least if the patch has1846 * more than one hunk it is not creation or deletion.1847 */1848if(patch->is_new <0&&1849(oldlines || (patch->fragments && patch->fragments->next)))1850 patch->is_new =0;1851if(patch->is_delete <0&&1852(newlines || (patch->fragments && patch->fragments->next)))1853 patch->is_delete =0;18541855if(0< patch->is_new && oldlines)1856returnerror(_("new file%sdepends on old contents"), patch->new_name);1857if(0< patch->is_delete && newlines)1858returnerror(_("deleted file%sstill has contents"), patch->old_name);1859if(!patch->is_delete && !newlines && context && state->apply_verbosity > verbosity_silent)1860fprintf_ln(stderr,1861_("** warning: "1862"file%sbecomes empty but is not deleted"),1863 patch->new_name);18641865return offset;1866}18671868staticinlineintmetadata_changes(struct patch *patch)1869{1870return patch->is_rename >0||1871 patch->is_copy >0||1872 patch->is_new >0||1873 patch->is_delete ||1874(patch->old_mode && patch->new_mode &&1875 patch->old_mode != patch->new_mode);1876}18771878static char*inflate_it(const void*data,unsigned long size,1879unsigned long inflated_size)1880{1881 git_zstream stream;1882void*out;1883int st;18841885memset(&stream,0,sizeof(stream));18861887 stream.next_in = (unsigned char*)data;1888 stream.avail_in = size;1889 stream.next_out = out =xmalloc(inflated_size);1890 stream.avail_out = inflated_size;1891git_inflate_init(&stream);1892 st =git_inflate(&stream, Z_FINISH);1893git_inflate_end(&stream);1894if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1895free(out);1896return NULL;1897}1898return out;1899}19001901/*1902 * Read a binary hunk and return a new fragment; fragment->patch1903 * points at an allocated memory that the caller must free, so1904 * it is marked as "->free_patch = 1".1905 */1906static struct fragment *parse_binary_hunk(struct apply_state *state,1907char**buf_p,1908unsigned long*sz_p,1909int*status_p,1910int*used_p)1911{1912/*1913 * Expect a line that begins with binary patch method ("literal"1914 * or "delta"), followed by the length of data before deflating.1915 * a sequence of 'length-byte' followed by base-85 encoded data1916 * should follow, terminated by a newline.1917 *1918 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1919 * and we would limit the patch line to 66 characters,1920 * so one line can fit up to 13 groups that would decode1921 * to 52 bytes max. The length byte 'A'-'Z' corresponds1922 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1923 */1924int llen, used;1925unsigned long size = *sz_p;1926char*buffer = *buf_p;1927int patch_method;1928unsigned long origlen;1929char*data = NULL;1930int hunk_size =0;1931struct fragment *frag;19321933 llen =linelen(buffer, size);1934 used = llen;19351936*status_p =0;19371938if(starts_with(buffer,"delta ")) {1939 patch_method = BINARY_DELTA_DEFLATED;1940 origlen =strtoul(buffer +6, NULL,10);1941}1942else if(starts_with(buffer,"literal ")) {1943 patch_method = BINARY_LITERAL_DEFLATED;1944 origlen =strtoul(buffer +8, NULL,10);1945}1946else1947return NULL;19481949 state->linenr++;1950 buffer += llen;1951while(1) {1952int byte_length, max_byte_length, newsize;1953 llen =linelen(buffer, size);1954 used += llen;1955 state->linenr++;1956if(llen ==1) {1957/* consume the blank line */1958 buffer++;1959 size--;1960break;1961}1962/*1963 * Minimum line is "A00000\n" which is 7-byte long,1964 * and the line length must be multiple of 5 plus 2.1965 */1966if((llen <7) || (llen-2) %5)1967goto corrupt;1968 max_byte_length = (llen -2) /5*4;1969 byte_length = *buffer;1970if('A'<= byte_length && byte_length <='Z')1971 byte_length = byte_length -'A'+1;1972else if('a'<= byte_length && byte_length <='z')1973 byte_length = byte_length -'a'+27;1974else1975goto corrupt;1976/* if the input length was not multiple of 4, we would1977 * have filler at the end but the filler should never1978 * exceed 3 bytes1979 */1980if(max_byte_length < byte_length ||1981 byte_length <= max_byte_length -4)1982goto corrupt;1983 newsize = hunk_size + byte_length;1984 data =xrealloc(data, newsize);1985if(decode_85(data + hunk_size, buffer +1, byte_length))1986goto corrupt;1987 hunk_size = newsize;1988 buffer += llen;1989 size -= llen;1990}19911992 frag =xcalloc(1,sizeof(*frag));1993 frag->patch =inflate_it(data, hunk_size, origlen);1994 frag->free_patch =1;1995if(!frag->patch)1996goto corrupt;1997free(data);1998 frag->size = origlen;1999*buf_p = buffer;2000*sz_p = size;2001*used_p = used;2002 frag->binary_patch_method = patch_method;2003return frag;20042005 corrupt:2006free(data);2007*status_p = -1;2008error(_("corrupt binary patch at line%d: %.*s"),2009 state->linenr-1, llen-1, buffer);2010return NULL;2011}20122013/*2014 * Returns:2015 * -1 in case of error,2016 * the length of the parsed binary patch otherwise2017 */2018static intparse_binary(struct apply_state *state,2019char*buffer,2020unsigned long size,2021struct patch *patch)2022{2023/*2024 * We have read "GIT binary patch\n"; what follows is a line2025 * that says the patch method (currently, either "literal" or2026 * "delta") and the length of data before deflating; a2027 * sequence of 'length-byte' followed by base-85 encoded data2028 * follows.2029 *2030 * When a binary patch is reversible, there is another binary2031 * hunk in the same format, starting with patch method (either2032 * "literal" or "delta") with the length of data, and a sequence2033 * of length-byte + base-85 encoded data, terminated with another2034 * empty line. This data, when applied to the postimage, produces2035 * the preimage.2036 */2037struct fragment *forward;2038struct fragment *reverse;2039int status;2040int used, used_1;20412042 forward =parse_binary_hunk(state, &buffer, &size, &status, &used);2043if(!forward && !status)2044/* there has to be one hunk (forward hunk) */2045returnerror(_("unrecognized binary patch at line%d"), state->linenr-1);2046if(status)2047/* otherwise we already gave an error message */2048return status;20492050 reverse =parse_binary_hunk(state, &buffer, &size, &status, &used_1);2051if(reverse)2052 used += used_1;2053else if(status) {2054/*2055 * Not having reverse hunk is not an error, but having2056 * a corrupt reverse hunk is.2057 */2058free((void*) forward->patch);2059free(forward);2060return status;2061}2062 forward->next = reverse;2063 patch->fragments = forward;2064 patch->is_binary =1;2065return used;2066}20672068static voidprefix_one(struct apply_state *state,char**name)2069{2070char*old_name = *name;2071if(!old_name)2072return;2073*name =prefix_filename(state->prefix, *name);2074free(old_name);2075}20762077static voidprefix_patch(struct apply_state *state,struct patch *p)2078{2079if(!state->prefix || p->is_toplevel_relative)2080return;2081prefix_one(state, &p->new_name);2082prefix_one(state, &p->old_name);2083}20842085/*2086 * include/exclude2087 */20882089static voidadd_name_limit(struct apply_state *state,2090const char*name,2091int exclude)2092{2093struct string_list_item *it;20942095 it =string_list_append(&state->limit_by_name, name);2096 it->util = exclude ? NULL : (void*)1;2097}20982099static intuse_patch(struct apply_state *state,struct patch *p)2100{2101const char*pathname = p->new_name ? p->new_name : p->old_name;2102int i;21032104/* Paths outside are not touched regardless of "--include" */2105if(state->prefix && *state->prefix) {2106const char*rest;2107if(!skip_prefix(pathname, state->prefix, &rest) || !*rest)2108return0;2109}21102111/* See if it matches any of exclude/include rule */2112for(i =0; i < state->limit_by_name.nr; i++) {2113struct string_list_item *it = &state->limit_by_name.items[i];2114if(!wildmatch(it->string, pathname,0))2115return(it->util != NULL);2116}21172118/*2119 * If we had any include, a path that does not match any rule is2120 * not used. Otherwise, we saw bunch of exclude rules (or none)2121 * and such a path is used.2122 */2123return!state->has_include;2124}21252126/*2127 * Read the patch text in "buffer" that extends for "size" bytes; stop2128 * reading after seeing a single patch (i.e. changes to a single file).2129 * Create fragments (i.e. patch hunks) and hang them to the given patch.2130 *2131 * Returns:2132 * -1 if no header was found or parse_binary() failed,2133 * -128 on another error,2134 * the number of bytes consumed otherwise,2135 * so that the caller can call us again for the next patch.2136 */2137static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2138{2139int hdrsize, patchsize;2140int offset =find_header(state, buffer, size, &hdrsize, patch);21412142if(offset <0)2143return offset;21442145prefix_patch(state, patch);21462147if(!use_patch(state, patch))2148 patch->ws_rule =0;2149else if(patch->new_name)2150 patch->ws_rule =whitespace_rule(state->repo->index,2151 patch->new_name);2152else2153 patch->ws_rule =whitespace_rule(state->repo->index,2154 patch->old_name);21552156 patchsize =parse_single_patch(state,2157 buffer + offset + hdrsize,2158 size - offset - hdrsize,2159 patch);21602161if(patchsize <0)2162return-128;21632164if(!patchsize) {2165static const char git_binary[] ="GIT binary patch\n";2166int hd = hdrsize + offset;2167unsigned long llen =linelen(buffer + hd, size - hd);21682169if(llen ==sizeof(git_binary) -1&&2170!memcmp(git_binary, buffer + hd, llen)) {2171int used;2172 state->linenr++;2173 used =parse_binary(state, buffer + hd + llen,2174 size - hd - llen, patch);2175if(used <0)2176return-1;2177if(used)2178 patchsize = used + llen;2179else2180 patchsize =0;2181}2182else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2183static const char*binhdr[] = {2184"Binary files ",2185"Files ",2186 NULL,2187};2188int i;2189for(i =0; binhdr[i]; i++) {2190int len =strlen(binhdr[i]);2191if(len < size - hd &&2192!memcmp(binhdr[i], buffer + hd, len)) {2193 state->linenr++;2194 patch->is_binary =1;2195 patchsize = llen;2196break;2197}2198}2199}22002201/* Empty patch cannot be applied if it is a text patch2202 * without metadata change. A binary patch appears2203 * empty to us here.2204 */2205if((state->apply || state->check) &&2206(!patch->is_binary && !metadata_changes(patch))) {2207error(_("patch with only garbage at line%d"), state->linenr);2208return-128;2209}2210}22112212return offset + hdrsize + patchsize;2213}22142215static voidreverse_patches(struct patch *p)2216{2217for(; p; p = p->next) {2218struct fragment *frag = p->fragments;22192220SWAP(p->new_name, p->old_name);2221SWAP(p->new_mode, p->old_mode);2222SWAP(p->is_new, p->is_delete);2223SWAP(p->lines_added, p->lines_deleted);2224SWAP(p->old_oid_prefix, p->new_oid_prefix);22252226for(; frag; frag = frag->next) {2227SWAP(frag->newpos, frag->oldpos);2228SWAP(frag->newlines, frag->oldlines);2229}2230}2231}22322233static const char pluses[] =2234"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2235static const char minuses[]=2236"----------------------------------------------------------------------";22372238static voidshow_stats(struct apply_state *state,struct patch *patch)2239{2240struct strbuf qname = STRBUF_INIT;2241char*cp = patch->new_name ? patch->new_name : patch->old_name;2242int max, add, del;22432244quote_c_style(cp, &qname, NULL,0);22452246/*2247 * "scale" the filename2248 */2249 max = state->max_len;2250if(max >50)2251 max =50;22522253if(qname.len > max) {2254 cp =strchr(qname.buf + qname.len +3- max,'/');2255if(!cp)2256 cp = qname.buf + qname.len +3- max;2257strbuf_splice(&qname,0, cp - qname.buf,"...",3);2258}22592260if(patch->is_binary) {2261printf(" %-*s | Bin\n", max, qname.buf);2262strbuf_release(&qname);2263return;2264}22652266printf(" %-*s |", max, qname.buf);2267strbuf_release(&qname);22682269/*2270 * scale the add/delete2271 */2272 max = max + state->max_change >70?70- max : state->max_change;2273 add = patch->lines_added;2274 del = patch->lines_deleted;22752276if(state->max_change >0) {2277int total = ((add + del) * max + state->max_change /2) / state->max_change;2278 add = (add * max + state->max_change /2) / state->max_change;2279 del = total - add;2280}2281printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2282 add, pluses, del, minuses);2283}22842285static intread_old_data(struct stat *st,struct patch *patch,2286const char*path,struct strbuf *buf)2287{2288int conv_flags = patch->crlf_in_old ?2289 CONV_EOL_KEEP_CRLF : CONV_EOL_RENORMALIZE;2290switch(st->st_mode & S_IFMT) {2291case S_IFLNK:2292if(strbuf_readlink(buf, path, st->st_size) <0)2293returnerror(_("unable to read symlink%s"), path);2294return0;2295case S_IFREG:2296if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2297returnerror(_("unable to open or read%s"), path);2298/*2299 * "git apply" without "--index/--cached" should never look2300 * at the index; the target file may not have been added to2301 * the index yet, and we may not even be in any Git repository.2302 * Pass NULL to convert_to_git() to stress this; the function2303 * should never look at the index when explicit crlf option2304 * is given.2305 */2306convert_to_git(NULL, path, buf->buf, buf->len, buf, conv_flags);2307return0;2308default:2309return-1;2310}2311}23122313/*2314 * Update the preimage, and the common lines in postimage,2315 * from buffer buf of length len. If postlen is 0 the postimage2316 * is updated in place, otherwise it's updated on a new buffer2317 * of length postlen2318 */23192320static voidupdate_pre_post_images(struct image *preimage,2321struct image *postimage,2322char*buf,2323size_t len,size_t postlen)2324{2325int i, ctx, reduced;2326char*new_buf, *old_buf, *fixed;2327struct image fixed_preimage;23282329/*2330 * Update the preimage with whitespace fixes. Note that we2331 * are not losing preimage->buf -- apply_one_fragment() will2332 * free "oldlines".2333 */2334prepare_image(&fixed_preimage, buf, len,1);2335assert(postlen2336? fixed_preimage.nr == preimage->nr2337: fixed_preimage.nr <= preimage->nr);2338for(i =0; i < fixed_preimage.nr; i++)2339 fixed_preimage.line[i].flag = preimage->line[i].flag;2340free(preimage->line_allocated);2341*preimage = fixed_preimage;23422343/*2344 * Adjust the common context lines in postimage. This can be2345 * done in-place when we are shrinking it with whitespace2346 * fixing, but needs a new buffer when ignoring whitespace or2347 * expanding leading tabs to spaces.2348 *2349 * We trust the caller to tell us if the update can be done2350 * in place (postlen==0) or not.2351 */2352 old_buf = postimage->buf;2353if(postlen)2354 new_buf = postimage->buf =xmalloc(postlen);2355else2356 new_buf = old_buf;2357 fixed = preimage->buf;23582359for(i = reduced = ctx =0; i < postimage->nr; i++) {2360size_t l_len = postimage->line[i].len;2361if(!(postimage->line[i].flag & LINE_COMMON)) {2362/* an added line -- no counterparts in preimage */2363memmove(new_buf, old_buf, l_len);2364 old_buf += l_len;2365 new_buf += l_len;2366continue;2367}23682369/* a common context -- skip it in the original postimage */2370 old_buf += l_len;23712372/* and find the corresponding one in the fixed preimage */2373while(ctx < preimage->nr &&2374!(preimage->line[ctx].flag & LINE_COMMON)) {2375 fixed += preimage->line[ctx].len;2376 ctx++;2377}23782379/*2380 * preimage is expected to run out, if the caller2381 * fixed addition of trailing blank lines.2382 */2383if(preimage->nr <= ctx) {2384 reduced++;2385continue;2386}23872388/* and copy it in, while fixing the line length */2389 l_len = preimage->line[ctx].len;2390memcpy(new_buf, fixed, l_len);2391 new_buf += l_len;2392 fixed += l_len;2393 postimage->line[i].len = l_len;2394 ctx++;2395}23962397if(postlen2398? postlen < new_buf - postimage->buf2399: postimage->len < new_buf - postimage->buf)2400BUG("caller miscounted postlen: asked%d, orig =%d, used =%d",2401(int)postlen, (int) postimage->len, (int)(new_buf - postimage->buf));24022403/* Fix the length of the whole thing */2404 postimage->len = new_buf - postimage->buf;2405 postimage->nr -= reduced;2406}24072408static intline_by_line_fuzzy_match(struct image *img,2409struct image *preimage,2410struct image *postimage,2411unsigned long current,2412int current_lno,2413int preimage_limit)2414{2415int i;2416size_t imgoff =0;2417size_t preoff =0;2418size_t postlen = postimage->len;2419size_t extra_chars;2420char*buf;2421char*preimage_eof;2422char*preimage_end;2423struct strbuf fixed;2424char*fixed_buf;2425size_t fixed_len;24262427for(i =0; i < preimage_limit; i++) {2428size_t prelen = preimage->line[i].len;2429size_t imglen = img->line[current_lno+i].len;24302431if(!fuzzy_matchlines(img->buf + current + imgoff, imglen,2432 preimage->buf + preoff, prelen))2433return0;2434if(preimage->line[i].flag & LINE_COMMON)2435 postlen += imglen - prelen;2436 imgoff += imglen;2437 preoff += prelen;2438}24392440/*2441 * Ok, the preimage matches with whitespace fuzz.2442 *2443 * imgoff now holds the true length of the target that2444 * matches the preimage before the end of the file.2445 *2446 * Count the number of characters in the preimage that fall2447 * beyond the end of the file and make sure that all of them2448 * are whitespace characters. (This can only happen if2449 * we are removing blank lines at the end of the file.)2450 */2451 buf = preimage_eof = preimage->buf + preoff;2452for( ; i < preimage->nr; i++)2453 preoff += preimage->line[i].len;2454 preimage_end = preimage->buf + preoff;2455for( ; buf < preimage_end; buf++)2456if(!isspace(*buf))2457return0;24582459/*2460 * Update the preimage and the common postimage context2461 * lines to use the same whitespace as the target.2462 * If whitespace is missing in the target (i.e.2463 * if the preimage extends beyond the end of the file),2464 * use the whitespace from the preimage.2465 */2466 extra_chars = preimage_end - preimage_eof;2467strbuf_init(&fixed, imgoff + extra_chars);2468strbuf_add(&fixed, img->buf + current, imgoff);2469strbuf_add(&fixed, preimage_eof, extra_chars);2470 fixed_buf =strbuf_detach(&fixed, &fixed_len);2471update_pre_post_images(preimage, postimage,2472 fixed_buf, fixed_len, postlen);2473return1;2474}24752476static intmatch_fragment(struct apply_state *state,2477struct image *img,2478struct image *preimage,2479struct image *postimage,2480unsigned long current,2481int current_lno,2482unsigned ws_rule,2483int match_beginning,int match_end)2484{2485int i;2486char*fixed_buf, *buf, *orig, *target;2487struct strbuf fixed;2488size_t fixed_len, postlen;2489int preimage_limit;24902491if(preimage->nr + current_lno <= img->nr) {2492/*2493 * The hunk falls within the boundaries of img.2494 */2495 preimage_limit = preimage->nr;2496if(match_end && (preimage->nr + current_lno != img->nr))2497return0;2498}else if(state->ws_error_action == correct_ws_error &&2499(ws_rule & WS_BLANK_AT_EOF)) {2500/*2501 * This hunk extends beyond the end of img, and we are2502 * removing blank lines at the end of the file. This2503 * many lines from the beginning of the preimage must2504 * match with img, and the remainder of the preimage2505 * must be blank.2506 */2507 preimage_limit = img->nr - current_lno;2508}else{2509/*2510 * The hunk extends beyond the end of the img and2511 * we are not removing blanks at the end, so we2512 * should reject the hunk at this position.2513 */2514return0;2515}25162517if(match_beginning && current_lno)2518return0;25192520/* Quick hash check */2521for(i =0; i < preimage_limit; i++)2522if((img->line[current_lno + i].flag & LINE_PATCHED) ||2523(preimage->line[i].hash != img->line[current_lno + i].hash))2524return0;25252526if(preimage_limit == preimage->nr) {2527/*2528 * Do we have an exact match? If we were told to match2529 * at the end, size must be exactly at current+fragsize,2530 * otherwise current+fragsize must be still within the preimage,2531 * and either case, the old piece should match the preimage2532 * exactly.2533 */2534if((match_end2535? (current + preimage->len == img->len)2536: (current + preimage->len <= img->len)) &&2537!memcmp(img->buf + current, preimage->buf, preimage->len))2538return1;2539}else{2540/*2541 * The preimage extends beyond the end of img, so2542 * there cannot be an exact match.2543 *2544 * There must be one non-blank context line that match2545 * a line before the end of img.2546 */2547char*buf_end;25482549 buf = preimage->buf;2550 buf_end = buf;2551for(i =0; i < preimage_limit; i++)2552 buf_end += preimage->line[i].len;25532554for( ; buf < buf_end; buf++)2555if(!isspace(*buf))2556break;2557if(buf == buf_end)2558return0;2559}25602561/*2562 * No exact match. If we are ignoring whitespace, run a line-by-line2563 * fuzzy matching. We collect all the line length information because2564 * we need it to adjust whitespace if we match.2565 */2566if(state->ws_ignore_action == ignore_ws_change)2567returnline_by_line_fuzzy_match(img, preimage, postimage,2568 current, current_lno, preimage_limit);25692570if(state->ws_error_action != correct_ws_error)2571return0;25722573/*2574 * The hunk does not apply byte-by-byte, but the hash says2575 * it might with whitespace fuzz. We weren't asked to2576 * ignore whitespace, we were asked to correct whitespace2577 * errors, so let's try matching after whitespace correction.2578 *2579 * While checking the preimage against the target, whitespace2580 * errors in both fixed, we count how large the corresponding2581 * postimage needs to be. The postimage prepared by2582 * apply_one_fragment() has whitespace errors fixed on added2583 * lines already, but the common lines were propagated as-is,2584 * which may become longer when their whitespace errors are2585 * fixed.2586 */25872588/* First count added lines in postimage */2589 postlen =0;2590for(i =0; i < postimage->nr; i++) {2591if(!(postimage->line[i].flag & LINE_COMMON))2592 postlen += postimage->line[i].len;2593}25942595/*2596 * The preimage may extend beyond the end of the file,2597 * but in this loop we will only handle the part of the2598 * preimage that falls within the file.2599 */2600strbuf_init(&fixed, preimage->len +1);2601 orig = preimage->buf;2602 target = img->buf + current;2603for(i =0; i < preimage_limit; i++) {2604size_t oldlen = preimage->line[i].len;2605size_t tgtlen = img->line[current_lno + i].len;2606size_t fixstart = fixed.len;2607struct strbuf tgtfix;2608int match;26092610/* Try fixing the line in the preimage */2611ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);26122613/* Try fixing the line in the target */2614strbuf_init(&tgtfix, tgtlen);2615ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);26162617/*2618 * If they match, either the preimage was based on2619 * a version before our tree fixed whitespace breakage,2620 * or we are lacking a whitespace-fix patch the tree2621 * the preimage was based on already had (i.e. target2622 * has whitespace breakage, the preimage doesn't).2623 * In either case, we are fixing the whitespace breakages2624 * so we might as well take the fix together with their2625 * real change.2626 */2627 match = (tgtfix.len == fixed.len - fixstart &&2628!memcmp(tgtfix.buf, fixed.buf + fixstart,2629 fixed.len - fixstart));26302631/* Add the length if this is common with the postimage */2632if(preimage->line[i].flag & LINE_COMMON)2633 postlen += tgtfix.len;26342635strbuf_release(&tgtfix);2636if(!match)2637goto unmatch_exit;26382639 orig += oldlen;2640 target += tgtlen;2641}264226432644/*2645 * Now handle the lines in the preimage that falls beyond the2646 * end of the file (if any). They will only match if they are2647 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2648 * false).2649 */2650for( ; i < preimage->nr; i++) {2651size_t fixstart = fixed.len;/* start of the fixed preimage */2652size_t oldlen = preimage->line[i].len;2653int j;26542655/* Try fixing the line in the preimage */2656ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);26572658for(j = fixstart; j < fixed.len; j++)2659if(!isspace(fixed.buf[j]))2660goto unmatch_exit;26612662 orig += oldlen;2663}26642665/*2666 * Yes, the preimage is based on an older version that still2667 * has whitespace breakages unfixed, and fixing them makes the2668 * hunk match. Update the context lines in the postimage.2669 */2670 fixed_buf =strbuf_detach(&fixed, &fixed_len);2671if(postlen < postimage->len)2672 postlen =0;2673update_pre_post_images(preimage, postimage,2674 fixed_buf, fixed_len, postlen);2675return1;26762677 unmatch_exit:2678strbuf_release(&fixed);2679return0;2680}26812682static intfind_pos(struct apply_state *state,2683struct image *img,2684struct image *preimage,2685struct image *postimage,2686int line,2687unsigned ws_rule,2688int match_beginning,int match_end)2689{2690int i;2691unsigned long backwards, forwards, current;2692int backwards_lno, forwards_lno, current_lno;26932694/*2695 * If match_beginning or match_end is specified, there is no2696 * point starting from a wrong line that will never match and2697 * wander around and wait for a match at the specified end.2698 */2699if(match_beginning)2700 line =0;2701else if(match_end)2702 line = img->nr - preimage->nr;27032704/*2705 * Because the comparison is unsigned, the following test2706 * will also take care of a negative line number that can2707 * result when match_end and preimage is larger than the target.2708 */2709if((size_t) line > img->nr)2710 line = img->nr;27112712 current =0;2713for(i =0; i < line; i++)2714 current += img->line[i].len;27152716/*2717 * There's probably some smart way to do this, but I'll leave2718 * that to the smart and beautiful people. I'm simple and stupid.2719 */2720 backwards = current;2721 backwards_lno = line;2722 forwards = current;2723 forwards_lno = line;2724 current_lno = line;27252726for(i =0; ; i++) {2727if(match_fragment(state, img, preimage, postimage,2728 current, current_lno, ws_rule,2729 match_beginning, match_end))2730return current_lno;27312732 again:2733if(backwards_lno ==0&& forwards_lno == img->nr)2734break;27352736if(i &1) {2737if(backwards_lno ==0) {2738 i++;2739goto again;2740}2741 backwards_lno--;2742 backwards -= img->line[backwards_lno].len;2743 current = backwards;2744 current_lno = backwards_lno;2745}else{2746if(forwards_lno == img->nr) {2747 i++;2748goto again;2749}2750 forwards += img->line[forwards_lno].len;2751 forwards_lno++;2752 current = forwards;2753 current_lno = forwards_lno;2754}27552756}2757return-1;2758}27592760static voidremove_first_line(struct image *img)2761{2762 img->buf += img->line[0].len;2763 img->len -= img->line[0].len;2764 img->line++;2765 img->nr--;2766}27672768static voidremove_last_line(struct image *img)2769{2770 img->len -= img->line[--img->nr].len;2771}27722773/*2774 * The change from "preimage" and "postimage" has been found to2775 * apply at applied_pos (counts in line numbers) in "img".2776 * Update "img" to remove "preimage" and replace it with "postimage".2777 */2778static voidupdate_image(struct apply_state *state,2779struct image *img,2780int applied_pos,2781struct image *preimage,2782struct image *postimage)2783{2784/*2785 * remove the copy of preimage at offset in img2786 * and replace it with postimage2787 */2788int i, nr;2789size_t remove_count, insert_count, applied_at =0;2790char*result;2791int preimage_limit;27922793/*2794 * If we are removing blank lines at the end of img,2795 * the preimage may extend beyond the end.2796 * If that is the case, we must be careful only to2797 * remove the part of the preimage that falls within2798 * the boundaries of img. Initialize preimage_limit2799 * to the number of lines in the preimage that falls2800 * within the boundaries.2801 */2802 preimage_limit = preimage->nr;2803if(preimage_limit > img->nr - applied_pos)2804 preimage_limit = img->nr - applied_pos;28052806for(i =0; i < applied_pos; i++)2807 applied_at += img->line[i].len;28082809 remove_count =0;2810for(i =0; i < preimage_limit; i++)2811 remove_count += img->line[applied_pos + i].len;2812 insert_count = postimage->len;28132814/* Adjust the contents */2815 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2816memcpy(result, img->buf, applied_at);2817memcpy(result + applied_at, postimage->buf, postimage->len);2818memcpy(result + applied_at + postimage->len,2819 img->buf + (applied_at + remove_count),2820 img->len - (applied_at + remove_count));2821free(img->buf);2822 img->buf = result;2823 img->len += insert_count - remove_count;2824 result[img->len] ='\0';28252826/* Adjust the line table */2827 nr = img->nr + postimage->nr - preimage_limit;2828if(preimage_limit < postimage->nr) {2829/*2830 * NOTE: this knows that we never call remove_first_line()2831 * on anything other than pre/post image.2832 */2833REALLOC_ARRAY(img->line, nr);2834 img->line_allocated = img->line;2835}2836if(preimage_limit != postimage->nr)2837MOVE_ARRAY(img->line + applied_pos + postimage->nr,2838 img->line + applied_pos + preimage_limit,2839 img->nr - (applied_pos + preimage_limit));2840COPY_ARRAY(img->line + applied_pos, postimage->line, postimage->nr);2841if(!state->allow_overlap)2842for(i =0; i < postimage->nr; i++)2843 img->line[applied_pos + i].flag |= LINE_PATCHED;2844 img->nr = nr;2845}28462847/*2848 * Use the patch-hunk text in "frag" to prepare two images (preimage and2849 * postimage) for the hunk. Find lines that match "preimage" in "img" and2850 * replace the part of "img" with "postimage" text.2851 */2852static intapply_one_fragment(struct apply_state *state,2853struct image *img,struct fragment *frag,2854int inaccurate_eof,unsigned ws_rule,2855int nth_fragment)2856{2857int match_beginning, match_end;2858const char*patch = frag->patch;2859int size = frag->size;2860char*old, *oldlines;2861struct strbuf newlines;2862int new_blank_lines_at_end =0;2863int found_new_blank_lines_at_end =0;2864int hunk_linenr = frag->linenr;2865unsigned long leading, trailing;2866int pos, applied_pos;2867struct image preimage;2868struct image postimage;28692870memset(&preimage,0,sizeof(preimage));2871memset(&postimage,0,sizeof(postimage));2872 oldlines =xmalloc(size);2873strbuf_init(&newlines, size);28742875 old = oldlines;2876while(size >0) {2877char first;2878int len =linelen(patch, size);2879int plen;2880int added_blank_line =0;2881int is_blank_context =0;2882size_t start;28832884if(!len)2885break;28862887/*2888 * "plen" is how much of the line we should use for2889 * the actual patch data. Normally we just remove the2890 * first character on the line, but if the line is2891 * followed by "\ No newline", then we also remove the2892 * last one (which is the newline, of course).2893 */2894 plen = len -1;2895if(len < size && patch[len] =='\\')2896 plen--;2897 first = *patch;2898if(state->apply_in_reverse) {2899if(first =='-')2900 first ='+';2901else if(first =='+')2902 first ='-';2903}29042905switch(first) {2906case'\n':2907/* Newer GNU diff, empty context line */2908if(plen <0)2909/* ... followed by '\No newline'; nothing */2910break;2911*old++ ='\n';2912strbuf_addch(&newlines,'\n');2913add_line_info(&preimage,"\n",1, LINE_COMMON);2914add_line_info(&postimage,"\n",1, LINE_COMMON);2915 is_blank_context =1;2916break;2917case' ':2918if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2919ws_blank_line(patch +1, plen, ws_rule))2920 is_blank_context =1;2921/* fallthrough */2922case'-':2923memcpy(old, patch +1, plen);2924add_line_info(&preimage, old, plen,2925(first ==' '? LINE_COMMON :0));2926 old += plen;2927if(first =='-')2928break;2929/* fallthrough */2930case'+':2931/* --no-add does not add new lines */2932if(first =='+'&& state->no_add)2933break;29342935 start = newlines.len;2936if(first !='+'||2937!state->whitespace_error ||2938 state->ws_error_action != correct_ws_error) {2939strbuf_add(&newlines, patch +1, plen);2940}2941else{2942ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2943}2944add_line_info(&postimage, newlines.buf + start, newlines.len - start,2945(first =='+'?0: LINE_COMMON));2946if(first =='+'&&2947(ws_rule & WS_BLANK_AT_EOF) &&2948ws_blank_line(patch +1, plen, ws_rule))2949 added_blank_line =1;2950break;2951case'@':case'\\':2952/* Ignore it, we already handled it */2953break;2954default:2955if(state->apply_verbosity > verbosity_normal)2956error(_("invalid start of line: '%c'"), first);2957 applied_pos = -1;2958goto out;2959}2960if(added_blank_line) {2961if(!new_blank_lines_at_end)2962 found_new_blank_lines_at_end = hunk_linenr;2963 new_blank_lines_at_end++;2964}2965else if(is_blank_context)2966;2967else2968 new_blank_lines_at_end =0;2969 patch += len;2970 size -= len;2971 hunk_linenr++;2972}2973if(inaccurate_eof &&2974 old > oldlines && old[-1] =='\n'&&2975 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2976 old--;2977strbuf_setlen(&newlines, newlines.len -1);2978 preimage.line_allocated[preimage.nr -1].len--;2979 postimage.line_allocated[postimage.nr -1].len--;2980}29812982 leading = frag->leading;2983 trailing = frag->trailing;29842985/*2986 * A hunk to change lines at the beginning would begin with2987 * @@ -1,L +N,M @@2988 * but we need to be careful. -U0 that inserts before the second2989 * line also has this pattern.2990 *2991 * And a hunk to add to an empty file would begin with2992 * @@ -0,0 +N,M @@2993 *2994 * In other words, a hunk that is (frag->oldpos <= 1) with or2995 * without leading context must match at the beginning.2996 */2997 match_beginning = (!frag->oldpos ||2998(frag->oldpos ==1&& !state->unidiff_zero));29993000/*3001 * A hunk without trailing lines must match at the end.3002 * However, we simply cannot tell if a hunk must match end3003 * from the lack of trailing lines if the patch was generated3004 * with unidiff without any context.3005 */3006 match_end = !state->unidiff_zero && !trailing;30073008 pos = frag->newpos ? (frag->newpos -1) :0;3009 preimage.buf = oldlines;3010 preimage.len = old - oldlines;3011 postimage.buf = newlines.buf;3012 postimage.len = newlines.len;3013 preimage.line = preimage.line_allocated;3014 postimage.line = postimage.line_allocated;30153016for(;;) {30173018 applied_pos =find_pos(state, img, &preimage, &postimage, pos,3019 ws_rule, match_beginning, match_end);30203021if(applied_pos >=0)3022break;30233024/* Am I at my context limits? */3025if((leading <= state->p_context) && (trailing <= state->p_context))3026break;3027if(match_beginning || match_end) {3028 match_beginning = match_end =0;3029continue;3030}30313032/*3033 * Reduce the number of context lines; reduce both3034 * leading and trailing if they are equal otherwise3035 * just reduce the larger context.3036 */3037if(leading >= trailing) {3038remove_first_line(&preimage);3039remove_first_line(&postimage);3040 pos--;3041 leading--;3042}3043if(trailing > leading) {3044remove_last_line(&preimage);3045remove_last_line(&postimage);3046 trailing--;3047}3048}30493050if(applied_pos >=0) {3051if(new_blank_lines_at_end &&3052 preimage.nr + applied_pos >= img->nr &&3053(ws_rule & WS_BLANK_AT_EOF) &&3054 state->ws_error_action != nowarn_ws_error) {3055record_ws_error(state, WS_BLANK_AT_EOF,"+",1,3056 found_new_blank_lines_at_end);3057if(state->ws_error_action == correct_ws_error) {3058while(new_blank_lines_at_end--)3059remove_last_line(&postimage);3060}3061/*3062 * We would want to prevent write_out_results()3063 * from taking place in apply_patch() that follows3064 * the callchain led us here, which is:3065 * apply_patch->check_patch_list->check_patch->3066 * apply_data->apply_fragments->apply_one_fragment3067 */3068if(state->ws_error_action == die_on_ws_error)3069 state->apply =0;3070}30713072if(state->apply_verbosity > verbosity_normal && applied_pos != pos) {3073int offset = applied_pos - pos;3074if(state->apply_in_reverse)3075 offset =0- offset;3076fprintf_ln(stderr,3077Q_("Hunk #%dsucceeded at%d(offset%dline).",3078"Hunk #%dsucceeded at%d(offset%dlines).",3079 offset),3080 nth_fragment, applied_pos +1, offset);3081}30823083/*3084 * Warn if it was necessary to reduce the number3085 * of context lines.3086 */3087if((leading != frag->leading ||3088 trailing != frag->trailing) && state->apply_verbosity > verbosity_silent)3089fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"3090" to apply fragment at%d"),3091 leading, trailing, applied_pos+1);3092update_image(state, img, applied_pos, &preimage, &postimage);3093}else{3094if(state->apply_verbosity > verbosity_normal)3095error(_("while searching for:\n%.*s"),3096(int)(old - oldlines), oldlines);3097}30983099out:3100free(oldlines);3101strbuf_release(&newlines);3102free(preimage.line_allocated);3103free(postimage.line_allocated);31043105return(applied_pos <0);3106}31073108static intapply_binary_fragment(struct apply_state *state,3109struct image *img,3110struct patch *patch)3111{3112struct fragment *fragment = patch->fragments;3113unsigned long len;3114void*dst;31153116if(!fragment)3117returnerror(_("missing binary patch data for '%s'"),3118 patch->new_name ?3119 patch->new_name :3120 patch->old_name);31213122/* Binary patch is irreversible without the optional second hunk */3123if(state->apply_in_reverse) {3124if(!fragment->next)3125returnerror(_("cannot reverse-apply a binary patch "3126"without the reverse hunk to '%s'"),3127 patch->new_name3128? patch->new_name : patch->old_name);3129 fragment = fragment->next;3130}3131switch(fragment->binary_patch_method) {3132case BINARY_DELTA_DEFLATED:3133 dst =patch_delta(img->buf, img->len, fragment->patch,3134 fragment->size, &len);3135if(!dst)3136return-1;3137clear_image(img);3138 img->buf = dst;3139 img->len = len;3140return0;3141case BINARY_LITERAL_DEFLATED:3142clear_image(img);3143 img->len = fragment->size;3144 img->buf =xmemdupz(fragment->patch, img->len);3145return0;3146}3147return-1;3148}31493150/*3151 * Replace "img" with the result of applying the binary patch.3152 * The binary patch data itself in patch->fragment is still kept3153 * but the preimage prepared by the caller in "img" is freed here3154 * or in the helper function apply_binary_fragment() this calls.3155 */3156static intapply_binary(struct apply_state *state,3157struct image *img,3158struct patch *patch)3159{3160const char*name = patch->old_name ? patch->old_name : patch->new_name;3161struct object_id oid;3162const unsigned hexsz = the_hash_algo->hexsz;31633164/*3165 * For safety, we require patch index line to contain3166 * full hex textual object ID for old and new, at least for now.3167 */3168if(strlen(patch->old_oid_prefix) != hexsz ||3169strlen(patch->new_oid_prefix) != hexsz ||3170get_oid_hex(patch->old_oid_prefix, &oid) ||3171get_oid_hex(patch->new_oid_prefix, &oid))3172returnerror(_("cannot apply binary patch to '%s' "3173"without full index line"), name);31743175if(patch->old_name) {3176/*3177 * See if the old one matches what the patch3178 * applies to.3179 */3180hash_object_file(img->buf, img->len, blob_type, &oid);3181if(strcmp(oid_to_hex(&oid), patch->old_oid_prefix))3182returnerror(_("the patch applies to '%s' (%s), "3183"which does not match the "3184"current contents."),3185 name,oid_to_hex(&oid));3186}3187else{3188/* Otherwise, the old one must be empty. */3189if(img->len)3190returnerror(_("the patch applies to an empty "3191"'%s' but it is not empty"), name);3192}31933194get_oid_hex(patch->new_oid_prefix, &oid);3195if(is_null_oid(&oid)) {3196clear_image(img);3197return0;/* deletion patch */3198}31993200if(has_object_file(&oid)) {3201/* We already have the postimage */3202enum object_type type;3203unsigned long size;3204char*result;32053206 result =read_object_file(&oid, &type, &size);3207if(!result)3208returnerror(_("the necessary postimage%sfor "3209"'%s' cannot be read"),3210 patch->new_oid_prefix, name);3211clear_image(img);3212 img->buf = result;3213 img->len = size;3214}else{3215/*3216 * We have verified buf matches the preimage;3217 * apply the patch data to it, which is stored3218 * in the patch->fragments->{patch,size}.3219 */3220if(apply_binary_fragment(state, img, patch))3221returnerror(_("binary patch does not apply to '%s'"),3222 name);32233224/* verify that the result matches */3225hash_object_file(img->buf, img->len, blob_type, &oid);3226if(strcmp(oid_to_hex(&oid), patch->new_oid_prefix))3227returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3228 name, patch->new_oid_prefix,oid_to_hex(&oid));3229}32303231return0;3232}32333234static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3235{3236struct fragment *frag = patch->fragments;3237const char*name = patch->old_name ? patch->old_name : patch->new_name;3238unsigned ws_rule = patch->ws_rule;3239unsigned inaccurate_eof = patch->inaccurate_eof;3240int nth =0;32413242if(patch->is_binary)3243returnapply_binary(state, img, patch);32443245while(frag) {3246 nth++;3247if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3248error(_("patch failed:%s:%ld"), name, frag->oldpos);3249if(!state->apply_with_reject)3250return-1;3251 frag->rejected =1;3252}3253 frag = frag->next;3254}3255return0;3256}32573258static intread_blob_object(struct strbuf *buf,const struct object_id *oid,unsigned mode)3259{3260if(S_ISGITLINK(mode)) {3261strbuf_grow(buf,100);3262strbuf_addf(buf,"Subproject commit%s\n",oid_to_hex(oid));3263}else{3264enum object_type type;3265unsigned long sz;3266char*result;32673268 result =read_object_file(oid, &type, &sz);3269if(!result)3270return-1;3271/* XXX read_sha1_file NUL-terminates */3272strbuf_attach(buf, result, sz, sz +1);3273}3274return0;3275}32763277static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3278{3279if(!ce)3280return0;3281returnread_blob_object(buf, &ce->oid, ce->ce_mode);3282}32833284static struct patch *in_fn_table(struct apply_state *state,const char*name)3285{3286struct string_list_item *item;32873288if(name == NULL)3289return NULL;32903291 item =string_list_lookup(&state->fn_table, name);3292if(item != NULL)3293return(struct patch *)item->util;32943295return NULL;3296}32973298/*3299 * item->util in the filename table records the status of the path.3300 * Usually it points at a patch (whose result records the contents3301 * of it after applying it), but it could be PATH_WAS_DELETED for a3302 * path that a previously applied patch has already removed, or3303 * PATH_TO_BE_DELETED for a path that a later patch would remove.3304 *3305 * The latter is needed to deal with a case where two paths A and B3306 * are swapped by first renaming A to B and then renaming B to A;3307 * moving A to B should not be prevented due to presence of B as we3308 * will remove it in a later patch.3309 */3310#define PATH_TO_BE_DELETED ((struct patch *) -2)3311#define PATH_WAS_DELETED ((struct patch *) -1)33123313static intto_be_deleted(struct patch *patch)3314{3315return patch == PATH_TO_BE_DELETED;3316}33173318static intwas_deleted(struct patch *patch)3319{3320return patch == PATH_WAS_DELETED;3321}33223323static voidadd_to_fn_table(struct apply_state *state,struct patch *patch)3324{3325struct string_list_item *item;33263327/*3328 * Always add new_name unless patch is a deletion3329 * This should cover the cases for normal diffs,3330 * file creations and copies3331 */3332if(patch->new_name != NULL) {3333 item =string_list_insert(&state->fn_table, patch->new_name);3334 item->util = patch;3335}33363337/*3338 * store a failure on rename/deletion cases because3339 * later chunks shouldn't patch old names3340 */3341if((patch->new_name == NULL) || (patch->is_rename)) {3342 item =string_list_insert(&state->fn_table, patch->old_name);3343 item->util = PATH_WAS_DELETED;3344}3345}33463347static voidprepare_fn_table(struct apply_state *state,struct patch *patch)3348{3349/*3350 * store information about incoming file deletion3351 */3352while(patch) {3353if((patch->new_name == NULL) || (patch->is_rename)) {3354struct string_list_item *item;3355 item =string_list_insert(&state->fn_table, patch->old_name);3356 item->util = PATH_TO_BE_DELETED;3357}3358 patch = patch->next;3359}3360}33613362static intcheckout_target(struct index_state *istate,3363struct cache_entry *ce,struct stat *st)3364{3365struct checkout costate = CHECKOUT_INIT;33663367 costate.refresh_cache =1;3368 costate.istate = istate;3369if(checkout_entry(ce, &costate, NULL, NULL) ||3370lstat(ce->name, st))3371returnerror(_("cannot checkout%s"), ce->name);3372return0;3373}33743375static struct patch *previous_patch(struct apply_state *state,3376struct patch *patch,3377int*gone)3378{3379struct patch *previous;33803381*gone =0;3382if(patch->is_copy || patch->is_rename)3383return NULL;/* "git" patches do not depend on the order */33843385 previous =in_fn_table(state, patch->old_name);3386if(!previous)3387return NULL;33883389if(to_be_deleted(previous))3390return NULL;/* the deletion hasn't happened yet */33913392if(was_deleted(previous))3393*gone =1;33943395return previous;3396}33973398static intverify_index_match(struct apply_state *state,3399const struct cache_entry *ce,3400struct stat *st)3401{3402if(S_ISGITLINK(ce->ce_mode)) {3403if(!S_ISDIR(st->st_mode))3404return-1;3405return0;3406}3407returnie_match_stat(state->repo->index, ce, st,3408 CE_MATCH_IGNORE_VALID | CE_MATCH_IGNORE_SKIP_WORKTREE);3409}34103411#define SUBMODULE_PATCH_WITHOUT_INDEX 134123413static intload_patch_target(struct apply_state *state,3414struct strbuf *buf,3415const struct cache_entry *ce,3416struct stat *st,3417struct patch *patch,3418const char*name,3419unsigned expected_mode)3420{3421if(state->cached || state->check_index) {3422if(read_file_or_gitlink(ce, buf))3423returnerror(_("failed to read%s"), name);3424}else if(name) {3425if(S_ISGITLINK(expected_mode)) {3426if(ce)3427returnread_file_or_gitlink(ce, buf);3428else3429return SUBMODULE_PATCH_WITHOUT_INDEX;3430}else if(has_symlink_leading_path(name,strlen(name))) {3431returnerror(_("reading from '%s' beyond a symbolic link"), name);3432}else{3433if(read_old_data(st, patch, name, buf))3434returnerror(_("failed to read%s"), name);3435}3436}3437return0;3438}34393440/*3441 * We are about to apply "patch"; populate the "image" with the3442 * current version we have, from the working tree or from the index,3443 * depending on the situation e.g. --cached/--index. If we are3444 * applying a non-git patch that incrementally updates the tree,3445 * we read from the result of a previous diff.3446 */3447static intload_preimage(struct apply_state *state,3448struct image *image,3449struct patch *patch,struct stat *st,3450const struct cache_entry *ce)3451{3452struct strbuf buf = STRBUF_INIT;3453size_t len;3454char*img;3455struct patch *previous;3456int status;34573458 previous =previous_patch(state, patch, &status);3459if(status)3460returnerror(_("path%shas been renamed/deleted"),3461 patch->old_name);3462if(previous) {3463/* We have a patched copy in memory; use that. */3464strbuf_add(&buf, previous->result, previous->resultsize);3465}else{3466 status =load_patch_target(state, &buf, ce, st, patch,3467 patch->old_name, patch->old_mode);3468if(status <0)3469return status;3470else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3471/*3472 * There is no way to apply subproject3473 * patch without looking at the index.3474 * NEEDSWORK: shouldn't this be flagged3475 * as an error???3476 */3477free_fragment_list(patch->fragments);3478 patch->fragments = NULL;3479}else if(status) {3480returnerror(_("failed to read%s"), patch->old_name);3481}3482}34833484 img =strbuf_detach(&buf, &len);3485prepare_image(image, img, len, !patch->is_binary);3486return0;3487}34883489static intthree_way_merge(struct apply_state *state,3490struct image *image,3491char*path,3492const struct object_id *base,3493const struct object_id *ours,3494const struct object_id *theirs)3495{3496 mmfile_t base_file, our_file, their_file;3497 mmbuffer_t result = { NULL };3498int status;34993500read_mmblob(&base_file, base);3501read_mmblob(&our_file, ours);3502read_mmblob(&their_file, theirs);3503 status =ll_merge(&result, path,3504&base_file,"base",3505&our_file,"ours",3506&their_file,"theirs",3507 state->repo->index,3508 NULL);3509free(base_file.ptr);3510free(our_file.ptr);3511free(their_file.ptr);3512if(status <0|| !result.ptr) {3513free(result.ptr);3514return-1;3515}3516clear_image(image);3517 image->buf = result.ptr;3518 image->len = result.size;35193520return status;3521}35223523/*3524 * When directly falling back to add/add three-way merge, we read from3525 * the current contents of the new_name. In no cases other than that3526 * this function will be called.3527 */3528static intload_current(struct apply_state *state,3529struct image *image,3530struct patch *patch)3531{3532struct strbuf buf = STRBUF_INIT;3533int status, pos;3534size_t len;3535char*img;3536struct stat st;3537struct cache_entry *ce;3538char*name = patch->new_name;3539unsigned mode = patch->new_mode;35403541if(!patch->is_new)3542BUG("patch to%sis not a creation", patch->old_name);35433544 pos =index_name_pos(state->repo->index, name,strlen(name));3545if(pos <0)3546returnerror(_("%s: does not exist in index"), name);3547 ce = state->repo->index->cache[pos];3548if(lstat(name, &st)) {3549if(errno != ENOENT)3550returnerror_errno("%s", name);3551if(checkout_target(state->repo->index, ce, &st))3552return-1;3553}3554if(verify_index_match(state, ce, &st))3555returnerror(_("%s: does not match index"), name);35563557 status =load_patch_target(state, &buf, ce, &st, patch, name, mode);3558if(status <0)3559return status;3560else if(status)3561return-1;3562 img =strbuf_detach(&buf, &len);3563prepare_image(image, img, len, !patch->is_binary);3564return0;3565}35663567static inttry_threeway(struct apply_state *state,3568struct image *image,3569struct patch *patch,3570struct stat *st,3571const struct cache_entry *ce)3572{3573struct object_id pre_oid, post_oid, our_oid;3574struct strbuf buf = STRBUF_INIT;3575size_t len;3576int status;3577char*img;3578struct image tmp_image;35793580/* No point falling back to 3-way merge in these cases */3581if(patch->is_delete ||3582S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3583return-1;35843585/* Preimage the patch was prepared for */3586if(patch->is_new)3587write_object_file("",0, blob_type, &pre_oid);3588else if(get_oid(patch->old_oid_prefix, &pre_oid) ||3589read_blob_object(&buf, &pre_oid, patch->old_mode))3590returnerror(_("repository lacks the necessary blob to fall back on 3-way merge."));35913592if(state->apply_verbosity > verbosity_silent)3593fprintf(stderr,_("Falling back to three-way merge...\n"));35943595 img =strbuf_detach(&buf, &len);3596prepare_image(&tmp_image, img, len,1);3597/* Apply the patch to get the post image */3598if(apply_fragments(state, &tmp_image, patch) <0) {3599clear_image(&tmp_image);3600return-1;3601}3602/* post_oid is theirs */3603write_object_file(tmp_image.buf, tmp_image.len, blob_type, &post_oid);3604clear_image(&tmp_image);36053606/* our_oid is ours */3607if(patch->is_new) {3608if(load_current(state, &tmp_image, patch))3609returnerror(_("cannot read the current contents of '%s'"),3610 patch->new_name);3611}else{3612if(load_preimage(state, &tmp_image, patch, st, ce))3613returnerror(_("cannot read the current contents of '%s'"),3614 patch->old_name);3615}3616write_object_file(tmp_image.buf, tmp_image.len, blob_type, &our_oid);3617clear_image(&tmp_image);36183619/* in-core three-way merge between post and our using pre as base */3620 status =three_way_merge(state, image, patch->new_name,3621&pre_oid, &our_oid, &post_oid);3622if(status <0) {3623if(state->apply_verbosity > verbosity_silent)3624fprintf(stderr,3625_("Failed to fall back on three-way merge...\n"));3626return status;3627}36283629if(status) {3630 patch->conflicted_threeway =1;3631if(patch->is_new)3632oidclr(&patch->threeway_stage[0]);3633else3634oidcpy(&patch->threeway_stage[0], &pre_oid);3635oidcpy(&patch->threeway_stage[1], &our_oid);3636oidcpy(&patch->threeway_stage[2], &post_oid);3637if(state->apply_verbosity > verbosity_silent)3638fprintf(stderr,3639_("Applied patch to '%s' with conflicts.\n"),3640 patch->new_name);3641}else{3642if(state->apply_verbosity > verbosity_silent)3643fprintf(stderr,3644_("Applied patch to '%s' cleanly.\n"),3645 patch->new_name);3646}3647return0;3648}36493650static intapply_data(struct apply_state *state,struct patch *patch,3651struct stat *st,const struct cache_entry *ce)3652{3653struct image image;36543655if(load_preimage(state, &image, patch, st, ce) <0)3656return-1;36573658if(patch->direct_to_threeway ||3659apply_fragments(state, &image, patch) <0) {3660/* Note: with --reject, apply_fragments() returns 0 */3661if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3662return-1;3663}3664 patch->result = image.buf;3665 patch->resultsize = image.len;3666add_to_fn_table(state, patch);3667free(image.line_allocated);36683669if(0< patch->is_delete && patch->resultsize)3670returnerror(_("removal patch leaves file contents"));36713672return0;3673}36743675/*3676 * If "patch" that we are looking at modifies or deletes what we have,3677 * we would want it not to lose any local modification we have, either3678 * in the working tree or in the index.3679 *3680 * This also decides if a non-git patch is a creation patch or a3681 * modification to an existing empty file. We do not check the state3682 * of the current tree for a creation patch in this function; the caller3683 * check_patch() separately makes sure (and errors out otherwise) that3684 * the path the patch creates does not exist in the current tree.3685 */3686static intcheck_preimage(struct apply_state *state,3687struct patch *patch,3688struct cache_entry **ce,3689struct stat *st)3690{3691const char*old_name = patch->old_name;3692struct patch *previous = NULL;3693int stat_ret =0, status;3694unsigned st_mode =0;36953696if(!old_name)3697return0;36983699assert(patch->is_new <=0);3700 previous =previous_patch(state, patch, &status);37013702if(status)3703returnerror(_("path%shas been renamed/deleted"), old_name);3704if(previous) {3705 st_mode = previous->new_mode;3706}else if(!state->cached) {3707 stat_ret =lstat(old_name, st);3708if(stat_ret && errno != ENOENT)3709returnerror_errno("%s", old_name);3710}37113712if(state->check_index && !previous) {3713int pos =index_name_pos(state->repo->index, old_name,3714strlen(old_name));3715if(pos <0) {3716if(patch->is_new <0)3717goto is_new;3718returnerror(_("%s: does not exist in index"), old_name);3719}3720*ce = state->repo->index->cache[pos];3721if(stat_ret <0) {3722if(checkout_target(state->repo->index, *ce, st))3723return-1;3724}3725if(!state->cached &&verify_index_match(state, *ce, st))3726returnerror(_("%s: does not match index"), old_name);3727if(state->cached)3728 st_mode = (*ce)->ce_mode;3729}else if(stat_ret <0) {3730if(patch->is_new <0)3731goto is_new;3732returnerror_errno("%s", old_name);3733}37343735if(!state->cached && !previous)3736 st_mode =ce_mode_from_stat(*ce, st->st_mode);37373738if(patch->is_new <0)3739 patch->is_new =0;3740if(!patch->old_mode)3741 patch->old_mode = st_mode;3742if((st_mode ^ patch->old_mode) & S_IFMT)3743returnerror(_("%s: wrong type"), old_name);3744if(st_mode != patch->old_mode)3745warning(_("%shas type%o, expected%o"),3746 old_name, st_mode, patch->old_mode);3747if(!patch->new_mode && !patch->is_delete)3748 patch->new_mode = st_mode;3749return0;37503751 is_new:3752 patch->is_new =1;3753 patch->is_delete =0;3754FREE_AND_NULL(patch->old_name);3755return0;3756}375737583759#define EXISTS_IN_INDEX 13760#define EXISTS_IN_WORKTREE 237613762static intcheck_to_create(struct apply_state *state,3763const char*new_name,3764int ok_if_exists)3765{3766struct stat nst;37673768if(state->check_index &&3769index_name_pos(state->repo->index, new_name,strlen(new_name)) >=0&&3770!ok_if_exists)3771return EXISTS_IN_INDEX;3772if(state->cached)3773return0;37743775if(!lstat(new_name, &nst)) {3776if(S_ISDIR(nst.st_mode) || ok_if_exists)3777return0;3778/*3779 * A leading component of new_name might be a symlink3780 * that is going to be removed with this patch, but3781 * still pointing at somewhere that has the path.3782 * In such a case, path "new_name" does not exist as3783 * far as git is concerned.3784 */3785if(has_symlink_leading_path(new_name,strlen(new_name)))3786return0;37873788return EXISTS_IN_WORKTREE;3789}else if(!is_missing_file_error(errno)) {3790returnerror_errno("%s", new_name);3791}3792return0;3793}37943795static uintptr_tregister_symlink_changes(struct apply_state *state,3796const char*path,3797uintptr_t what)3798{3799struct string_list_item *ent;38003801 ent =string_list_lookup(&state->symlink_changes, path);3802if(!ent) {3803 ent =string_list_insert(&state->symlink_changes, path);3804 ent->util = (void*)0;3805}3806 ent->util = (void*)(what | ((uintptr_t)ent->util));3807return(uintptr_t)ent->util;3808}38093810static uintptr_tcheck_symlink_changes(struct apply_state *state,const char*path)3811{3812struct string_list_item *ent;38133814 ent =string_list_lookup(&state->symlink_changes, path);3815if(!ent)3816return0;3817return(uintptr_t)ent->util;3818}38193820static voidprepare_symlink_changes(struct apply_state *state,struct patch *patch)3821{3822for( ; patch; patch = patch->next) {3823if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3824(patch->is_rename || patch->is_delete))3825/* the symlink at patch->old_name is removed */3826register_symlink_changes(state, patch->old_name, APPLY_SYMLINK_GOES_AWAY);38273828if(patch->new_name &&S_ISLNK(patch->new_mode))3829/* the symlink at patch->new_name is created or remains */3830register_symlink_changes(state, patch->new_name, APPLY_SYMLINK_IN_RESULT);3831}3832}38333834static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3835{3836do{3837unsigned int change;38383839while(--name->len && name->buf[name->len] !='/')3840;/* scan backwards */3841if(!name->len)3842break;3843 name->buf[name->len] ='\0';3844 change =check_symlink_changes(state, name->buf);3845if(change & APPLY_SYMLINK_IN_RESULT)3846return1;3847if(change & APPLY_SYMLINK_GOES_AWAY)3848/*3849 * This cannot be "return 0", because we may3850 * see a new one created at a higher level.3851 */3852continue;38533854/* otherwise, check the preimage */3855if(state->check_index) {3856struct cache_entry *ce;38573858 ce =index_file_exists(state->repo->index, name->buf,3859 name->len, ignore_case);3860if(ce &&S_ISLNK(ce->ce_mode))3861return1;3862}else{3863struct stat st;3864if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3865return1;3866}3867}while(1);3868return0;3869}38703871static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3872{3873int ret;3874struct strbuf name = STRBUF_INIT;38753876assert(*name_ !='\0');3877strbuf_addstr(&name, name_);3878 ret =path_is_beyond_symlink_1(state, &name);3879strbuf_release(&name);38803881return ret;3882}38833884static intcheck_unsafe_path(struct patch *patch)3885{3886const char*old_name = NULL;3887const char*new_name = NULL;3888if(patch->is_delete)3889 old_name = patch->old_name;3890else if(!patch->is_new && !patch->is_copy)3891 old_name = patch->old_name;3892if(!patch->is_delete)3893 new_name = patch->new_name;38943895if(old_name && !verify_path(old_name, patch->old_mode))3896returnerror(_("invalid path '%s'"), old_name);3897if(new_name && !verify_path(new_name, patch->new_mode))3898returnerror(_("invalid path '%s'"), new_name);3899return0;3900}39013902/*3903 * Check and apply the patch in-core; leave the result in patch->result3904 * for the caller to write it out to the final destination.3905 */3906static intcheck_patch(struct apply_state *state,struct patch *patch)3907{3908struct stat st;3909const char*old_name = patch->old_name;3910const char*new_name = patch->new_name;3911const char*name = old_name ? old_name : new_name;3912struct cache_entry *ce = NULL;3913struct patch *tpatch;3914int ok_if_exists;3915int status;39163917 patch->rejected =1;/* we will drop this after we succeed */39183919 status =check_preimage(state, patch, &ce, &st);3920if(status)3921return status;3922 old_name = patch->old_name;39233924/*3925 * A type-change diff is always split into a patch to delete3926 * old, immediately followed by a patch to create new (see3927 * diff.c::run_diff()); in such a case it is Ok that the entry3928 * to be deleted by the previous patch is still in the working3929 * tree and in the index.3930 *3931 * A patch to swap-rename between A and B would first rename A3932 * to B and then rename B to A. While applying the first one,3933 * the presence of B should not stop A from getting renamed to3934 * B; ask to_be_deleted() about the later rename. Removal of3935 * B and rename from A to B is handled the same way by asking3936 * was_deleted().3937 */3938if((tpatch =in_fn_table(state, new_name)) &&3939(was_deleted(tpatch) ||to_be_deleted(tpatch)))3940 ok_if_exists =1;3941else3942 ok_if_exists =0;39433944if(new_name &&3945((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3946int err =check_to_create(state, new_name, ok_if_exists);39473948if(err && state->threeway) {3949 patch->direct_to_threeway =1;3950}else switch(err) {3951case0:3952break;/* happy */3953case EXISTS_IN_INDEX:3954returnerror(_("%s: already exists in index"), new_name);3955break;3956case EXISTS_IN_WORKTREE:3957returnerror(_("%s: already exists in working directory"),3958 new_name);3959default:3960return err;3961}39623963if(!patch->new_mode) {3964if(0< patch->is_new)3965 patch->new_mode = S_IFREG |0644;3966else3967 patch->new_mode = patch->old_mode;3968}3969}39703971if(new_name && old_name) {3972int same = !strcmp(old_name, new_name);3973if(!patch->new_mode)3974 patch->new_mode = patch->old_mode;3975if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3976if(same)3977returnerror(_("new mode (%o) of%sdoes not "3978"match old mode (%o)"),3979 patch->new_mode, new_name,3980 patch->old_mode);3981else3982returnerror(_("new mode (%o) of%sdoes not "3983"match old mode (%o) of%s"),3984 patch->new_mode, new_name,3985 patch->old_mode, old_name);3986}3987}39883989if(!state->unsafe_paths &&check_unsafe_path(patch))3990return-128;39913992/*3993 * An attempt to read from or delete a path that is beyond a3994 * symbolic link will be prevented by load_patch_target() that3995 * is called at the beginning of apply_data() so we do not3996 * have to worry about a patch marked with "is_delete" bit3997 * here. We however need to make sure that the patch result3998 * is not deposited to a path that is beyond a symbolic link3999 * here.4000 */4001if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))4002returnerror(_("affected file '%s' is beyond a symbolic link"),4003 patch->new_name);40044005if(apply_data(state, patch, &st, ce) <0)4006returnerror(_("%s: patch does not apply"), name);4007 patch->rejected =0;4008return0;4009}40104011static intcheck_patch_list(struct apply_state *state,struct patch *patch)4012{4013int err =0;40144015prepare_symlink_changes(state, patch);4016prepare_fn_table(state, patch);4017while(patch) {4018int res;4019if(state->apply_verbosity > verbosity_normal)4020say_patch_name(stderr,4021_("Checking patch%s..."), patch);4022 res =check_patch(state, patch);4023if(res == -128)4024return-128;4025 err |= res;4026 patch = patch->next;4027}4028return err;4029}40304031static intread_apply_cache(struct apply_state *state)4032{4033if(state->index_file)4034returnread_index_from(state->repo->index, state->index_file,4035get_git_dir());4036else4037returnrepo_read_index(state->repo);4038}40394040/* This function tries to read the object name from the current index */4041static intget_current_oid(struct apply_state *state,const char*path,4042struct object_id *oid)4043{4044int pos;40454046if(read_apply_cache(state) <0)4047return-1;4048 pos =index_name_pos(state->repo->index, path,strlen(path));4049if(pos <0)4050return-1;4051oidcpy(oid, &state->repo->index->cache[pos]->oid);4052return0;4053}40544055static intpreimage_oid_in_gitlink_patch(struct patch *p,struct object_id *oid)4056{4057/*4058 * A usable gitlink patch has only one fragment (hunk) that looks like:4059 * @@ -1 +1 @@4060 * -Subproject commit <old sha1>4061 * +Subproject commit <new sha1>4062 * or4063 * @@ -1 +0,0 @@4064 * -Subproject commit <old sha1>4065 * for a removal patch.4066 */4067struct fragment *hunk = p->fragments;4068static const char heading[] ="-Subproject commit ";4069char*preimage;40704071if(/* does the patch have only one hunk? */4072 hunk && !hunk->next &&4073/* is its preimage one line? */4074 hunk->oldpos ==1&& hunk->oldlines ==1&&4075/* does preimage begin with the heading? */4076(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&4077starts_with(++preimage, heading) &&4078/* does it record full SHA-1? */4079!get_oid_hex(preimage +sizeof(heading) -1, oid) &&4080 preimage[sizeof(heading) + the_hash_algo->hexsz -1] =='\n'&&4081/* does the abbreviated name on the index line agree with it? */4082starts_with(preimage +sizeof(heading) -1, p->old_oid_prefix))4083return0;/* it all looks fine */40844085/* we may have full object name on the index line */4086returnget_oid_hex(p->old_oid_prefix, oid);4087}40884089/* Build an index that contains just the files needed for a 3way merge */4090static intbuild_fake_ancestor(struct apply_state *state,struct patch *list)4091{4092struct patch *patch;4093struct index_state result = { NULL };4094struct lock_file lock = LOCK_INIT;4095int res;40964097/* Once we start supporting the reverse patch, it may be4098 * worth showing the new sha1 prefix, but until then...4099 */4100for(patch = list; patch; patch = patch->next) {4101struct object_id oid;4102struct cache_entry *ce;4103const char*name;41044105 name = patch->old_name ? patch->old_name : patch->new_name;4106if(0< patch->is_new)4107continue;41084109if(S_ISGITLINK(patch->old_mode)) {4110if(!preimage_oid_in_gitlink_patch(patch, &oid))4111;/* ok, the textual part looks sane */4112else4113returnerror(_("sha1 information is lacking or "4114"useless for submodule%s"), name);4115}else if(!get_oid_blob(patch->old_oid_prefix, &oid)) {4116;/* ok */4117}else if(!patch->lines_added && !patch->lines_deleted) {4118/* mode-only change: update the current */4119if(get_current_oid(state, patch->old_name, &oid))4120returnerror(_("mode change for%s, which is not "4121"in current HEAD"), name);4122}else4123returnerror(_("sha1 information is lacking or useless "4124"(%s)."), name);41254126 ce =make_cache_entry(&result, patch->old_mode, &oid, name,0,0);4127if(!ce)4128returnerror(_("make_cache_entry failed for path '%s'"),4129 name);4130if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) {4131discard_cache_entry(ce);4132returnerror(_("could not add%sto temporary index"),4133 name);4134}4135}41364137hold_lock_file_for_update(&lock, state->fake_ancestor, LOCK_DIE_ON_ERROR);4138 res =write_locked_index(&result, &lock, COMMIT_LOCK);4139discard_index(&result);41404141if(res)4142returnerror(_("could not write temporary index to%s"),4143 state->fake_ancestor);41444145return0;4146}41474148static voidstat_patch_list(struct apply_state *state,struct patch *patch)4149{4150int files, adds, dels;41514152for(files = adds = dels =0; patch ; patch = patch->next) {4153 files++;4154 adds += patch->lines_added;4155 dels += patch->lines_deleted;4156show_stats(state, patch);4157}41584159print_stat_summary(stdout, files, adds, dels);4160}41614162static voidnumstat_patch_list(struct apply_state *state,4163struct patch *patch)4164{4165for( ; patch; patch = patch->next) {4166const char*name;4167 name = patch->new_name ? patch->new_name : patch->old_name;4168if(patch->is_binary)4169printf("-\t-\t");4170else4171printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4172write_name_quoted(name, stdout, state->line_termination);4173}4174}41754176static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4177{4178if(mode)4179printf("%smode%06o%s\n", newdelete, mode, name);4180else4181printf("%s %s\n", newdelete, name);4182}41834184static voidshow_mode_change(struct patch *p,int show_name)4185{4186if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4187if(show_name)4188printf(" mode change%06o =>%06o%s\n",4189 p->old_mode, p->new_mode, p->new_name);4190else4191printf(" mode change%06o =>%06o\n",4192 p->old_mode, p->new_mode);4193}4194}41954196static voidshow_rename_copy(struct patch *p)4197{4198const char*renamecopy = p->is_rename ?"rename":"copy";4199const char*old_name, *new_name;42004201/* Find common prefix */4202 old_name = p->old_name;4203 new_name = p->new_name;4204while(1) {4205const char*slash_old, *slash_new;4206 slash_old =strchr(old_name,'/');4207 slash_new =strchr(new_name,'/');4208if(!slash_old ||4209!slash_new ||4210 slash_old - old_name != slash_new - new_name ||4211memcmp(old_name, new_name, slash_new - new_name))4212break;4213 old_name = slash_old +1;4214 new_name = slash_new +1;4215}4216/* p->old_name thru old_name is the common prefix, and old_name and new_name4217 * through the end of names are renames4218 */4219if(old_name != p->old_name)4220printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4221(int)(old_name - p->old_name), p->old_name,4222 old_name, new_name, p->score);4223else4224printf("%s %s=>%s(%d%%)\n", renamecopy,4225 p->old_name, p->new_name, p->score);4226show_mode_change(p,0);4227}42284229static voidsummary_patch_list(struct patch *patch)4230{4231struct patch *p;42324233for(p = patch; p; p = p->next) {4234if(p->is_new)4235show_file_mode_name("create", p->new_mode, p->new_name);4236else if(p->is_delete)4237show_file_mode_name("delete", p->old_mode, p->old_name);4238else{4239if(p->is_rename || p->is_copy)4240show_rename_copy(p);4241else{4242if(p->score) {4243printf(" rewrite%s(%d%%)\n",4244 p->new_name, p->score);4245show_mode_change(p,0);4246}4247else4248show_mode_change(p,1);4249}4250}4251}4252}42534254static voidpatch_stats(struct apply_state *state,struct patch *patch)4255{4256int lines = patch->lines_added + patch->lines_deleted;42574258if(lines > state->max_change)4259 state->max_change = lines;4260if(patch->old_name) {4261int len =quote_c_style(patch->old_name, NULL, NULL,0);4262if(!len)4263 len =strlen(patch->old_name);4264if(len > state->max_len)4265 state->max_len = len;4266}4267if(patch->new_name) {4268int len =quote_c_style(patch->new_name, NULL, NULL,0);4269if(!len)4270 len =strlen(patch->new_name);4271if(len > state->max_len)4272 state->max_len = len;4273}4274}42754276static intremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4277{4278if(state->update_index && !state->ita_only) {4279if(remove_file_from_index(state->repo->index, patch->old_name) <0)4280returnerror(_("unable to remove%sfrom index"), patch->old_name);4281}4282if(!state->cached) {4283if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4284remove_path(patch->old_name);4285}4286}4287return0;4288}42894290static intadd_index_file(struct apply_state *state,4291const char*path,4292unsigned mode,4293void*buf,4294unsigned long size)4295{4296struct stat st;4297struct cache_entry *ce;4298int namelen =strlen(path);42994300 ce =make_empty_cache_entry(state->repo->index, namelen);4301memcpy(ce->name, path, namelen);4302 ce->ce_mode =create_ce_mode(mode);4303 ce->ce_flags =create_ce_flags(0);4304 ce->ce_namelen = namelen;4305if(state->ita_only) {4306 ce->ce_flags |= CE_INTENT_TO_ADD;4307set_object_name_for_intent_to_add_entry(ce);4308}else if(S_ISGITLINK(mode)) {4309const char*s;43104311if(!skip_prefix(buf,"Subproject commit ", &s) ||4312get_oid_hex(s, &ce->oid)) {4313discard_cache_entry(ce);4314returnerror(_("corrupt patch for submodule%s"), path);4315}4316}else{4317if(!state->cached) {4318if(lstat(path, &st) <0) {4319discard_cache_entry(ce);4320returnerror_errno(_("unable to stat newly "4321"created file '%s'"),4322 path);4323}4324fill_stat_cache_info(state->repo->index, ce, &st);4325}4326if(write_object_file(buf, size, blob_type, &ce->oid) <0) {4327discard_cache_entry(ce);4328returnerror(_("unable to create backing store "4329"for newly created file%s"), path);4330}4331}4332if(add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) <0) {4333discard_cache_entry(ce);4334returnerror(_("unable to add cache entry for%s"), path);4335}43364337return0;4338}43394340/*4341 * Returns:4342 * -1 if an unrecoverable error happened4343 * 0 if everything went well4344 * 1 if a recoverable error happened4345 */4346static inttry_create_file(struct apply_state *state,const char*path,4347unsigned int mode,const char*buf,4348unsigned long size)4349{4350int fd, res;4351struct strbuf nbuf = STRBUF_INIT;43524353if(S_ISGITLINK(mode)) {4354struct stat st;4355if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4356return0;4357return!!mkdir(path,0777);4358}43594360if(has_symlinks &&S_ISLNK(mode))4361/* Although buf:size is counted string, it also is NUL4362 * terminated.4363 */4364return!!symlink(buf, path);43654366 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4367if(fd <0)4368return1;43694370if(convert_to_working_tree(state->repo->index, path, buf, size, &nbuf)) {4371 size = nbuf.len;4372 buf = nbuf.buf;4373}43744375 res =write_in_full(fd, buf, size) <0;4376if(res)4377error_errno(_("failed to write to '%s'"), path);4378strbuf_release(&nbuf);43794380if(close(fd) <0&& !res)4381returnerror_errno(_("closing file '%s'"), path);43824383return res ? -1:0;4384}43854386/*4387 * We optimistically assume that the directories exist,4388 * which is true 99% of the time anyway. If they don't,4389 * we create them and try again.4390 *4391 * Returns:4392 * -1 on error4393 * 0 otherwise4394 */4395static intcreate_one_file(struct apply_state *state,4396char*path,4397unsigned mode,4398const char*buf,4399unsigned long size)4400{4401int res;44024403if(state->cached)4404return0;44054406 res =try_create_file(state, path, mode, buf, size);4407if(res <0)4408return-1;4409if(!res)4410return0;44114412if(errno == ENOENT) {4413if(safe_create_leading_directories(path))4414return0;4415 res =try_create_file(state, path, mode, buf, size);4416if(res <0)4417return-1;4418if(!res)4419return0;4420}44214422if(errno == EEXIST || errno == EACCES) {4423/* We may be trying to create a file where a directory4424 * used to be.4425 */4426struct stat st;4427if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4428 errno = EEXIST;4429}44304431if(errno == EEXIST) {4432unsigned int nr =getpid();44334434for(;;) {4435char newpath[PATH_MAX];4436mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4437 res =try_create_file(state, newpath, mode, buf, size);4438if(res <0)4439return-1;4440if(!res) {4441if(!rename(newpath, path))4442return0;4443unlink_or_warn(newpath);4444break;4445}4446if(errno != EEXIST)4447break;4448++nr;4449}4450}4451returnerror_errno(_("unable to write file '%s' mode%o"),4452 path, mode);4453}44544455static intadd_conflicted_stages_file(struct apply_state *state,4456struct patch *patch)4457{4458int stage, namelen;4459unsigned mode;4460struct cache_entry *ce;44614462if(!state->update_index)4463return0;4464 namelen =strlen(patch->new_name);4465 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);44664467remove_file_from_index(state->repo->index, patch->new_name);4468for(stage =1; stage <4; stage++) {4469if(is_null_oid(&patch->threeway_stage[stage -1]))4470continue;4471 ce =make_empty_cache_entry(state->repo->index, namelen);4472memcpy(ce->name, patch->new_name, namelen);4473 ce->ce_mode =create_ce_mode(mode);4474 ce->ce_flags =create_ce_flags(stage);4475 ce->ce_namelen = namelen;4476oidcpy(&ce->oid, &patch->threeway_stage[stage -1]);4477if(add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) <0) {4478discard_cache_entry(ce);4479returnerror(_("unable to add cache entry for%s"),4480 patch->new_name);4481}4482}44834484return0;4485}44864487static intcreate_file(struct apply_state *state,struct patch *patch)4488{4489char*path = patch->new_name;4490unsigned mode = patch->new_mode;4491unsigned long size = patch->resultsize;4492char*buf = patch->result;44934494if(!mode)4495 mode = S_IFREG |0644;4496if(create_one_file(state, path, mode, buf, size))4497return-1;44984499if(patch->conflicted_threeway)4500returnadd_conflicted_stages_file(state, patch);4501else if(state->update_index)4502returnadd_index_file(state, path, mode, buf, size);4503return0;4504}45054506/* phase zero is to remove, phase one is to create */4507static intwrite_out_one_result(struct apply_state *state,4508struct patch *patch,4509int phase)4510{4511if(patch->is_delete >0) {4512if(phase ==0)4513returnremove_file(state, patch,1);4514return0;4515}4516if(patch->is_new >0|| patch->is_copy) {4517if(phase ==1)4518returncreate_file(state, patch);4519return0;4520}4521/*4522 * Rename or modification boils down to the same4523 * thing: remove the old, write the new4524 */4525if(phase ==0)4526returnremove_file(state, patch, patch->is_rename);4527if(phase ==1)4528returncreate_file(state, patch);4529return0;4530}45314532static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4533{4534FILE*rej;4535char namebuf[PATH_MAX];4536struct fragment *frag;4537int cnt =0;4538struct strbuf sb = STRBUF_INIT;45394540for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4541if(!frag->rejected)4542continue;4543 cnt++;4544}45454546if(!cnt) {4547if(state->apply_verbosity > verbosity_normal)4548say_patch_name(stderr,4549_("Applied patch%scleanly."), patch);4550return0;4551}45524553/* This should not happen, because a removal patch that leaves4554 * contents are marked "rejected" at the patch level.4555 */4556if(!patch->new_name)4557die(_("internal error"));45584559/* Say this even without --verbose */4560strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4561"Applying patch %%swith%drejects...",4562 cnt),4563 cnt);4564if(state->apply_verbosity > verbosity_silent)4565say_patch_name(stderr, sb.buf, patch);4566strbuf_release(&sb);45674568 cnt =strlen(patch->new_name);4569if(ARRAY_SIZE(namebuf) <= cnt +5) {4570 cnt =ARRAY_SIZE(namebuf) -5;4571warning(_("truncating .rej filename to %.*s.rej"),4572 cnt -1, patch->new_name);4573}4574memcpy(namebuf, patch->new_name, cnt);4575memcpy(namebuf + cnt,".rej",5);45764577 rej =fopen(namebuf,"w");4578if(!rej)4579returnerror_errno(_("cannot open%s"), namebuf);45804581/* Normal git tools never deal with .rej, so do not pretend4582 * this is a git patch by saying --git or giving extended4583 * headers. While at it, maybe please "kompare" that wants4584 * the trailing TAB and some garbage at the end of line ;-).4585 */4586fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4587 patch->new_name, patch->new_name);4588for(cnt =1, frag = patch->fragments;4589 frag;4590 cnt++, frag = frag->next) {4591if(!frag->rejected) {4592if(state->apply_verbosity > verbosity_silent)4593fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4594continue;4595}4596if(state->apply_verbosity > verbosity_silent)4597fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4598fprintf(rej,"%.*s", frag->size, frag->patch);4599if(frag->patch[frag->size-1] !='\n')4600fputc('\n', rej);4601}4602fclose(rej);4603return-1;4604}46054606/*4607 * Returns:4608 * -1 if an error happened4609 * 0 if the patch applied cleanly4610 * 1 if the patch did not apply cleanly4611 */4612static intwrite_out_results(struct apply_state *state,struct patch *list)4613{4614int phase;4615int errs =0;4616struct patch *l;4617struct string_list cpath = STRING_LIST_INIT_DUP;46184619for(phase =0; phase <2; phase++) {4620 l = list;4621while(l) {4622if(l->rejected)4623 errs =1;4624else{4625if(write_out_one_result(state, l, phase)) {4626string_list_clear(&cpath,0);4627return-1;4628}4629if(phase ==1) {4630if(write_out_one_reject(state, l))4631 errs =1;4632if(l->conflicted_threeway) {4633string_list_append(&cpath, l->new_name);4634 errs =1;4635}4636}4637}4638 l = l->next;4639}4640}46414642if(cpath.nr) {4643struct string_list_item *item;46444645string_list_sort(&cpath);4646if(state->apply_verbosity > verbosity_silent) {4647for_each_string_list_item(item, &cpath)4648fprintf(stderr,"U%s\n", item->string);4649}4650string_list_clear(&cpath,0);46514652repo_rerere(state->repo,0);4653}46544655return errs;4656}46574658/*4659 * Try to apply a patch.4660 *4661 * Returns:4662 * -128 if a bad error happened (like patch unreadable)4663 * -1 if patch did not apply and user cannot deal with it4664 * 0 if the patch applied4665 * 1 if the patch did not apply but user might fix it4666 */4667static intapply_patch(struct apply_state *state,4668int fd,4669const char*filename,4670int options)4671{4672size_t offset;4673struct strbuf buf = STRBUF_INIT;/* owns the patch text */4674struct patch *list = NULL, **listp = &list;4675int skipped_patch =0;4676int res =0;46774678 state->patch_input_file = filename;4679if(read_patch_file(&buf, fd) <0)4680return-128;4681 offset =0;4682while(offset < buf.len) {4683struct patch *patch;4684int nr;46854686 patch =xcalloc(1,sizeof(*patch));4687 patch->inaccurate_eof = !!(options & APPLY_OPT_INACCURATE_EOF);4688 patch->recount = !!(options & APPLY_OPT_RECOUNT);4689 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4690if(nr <0) {4691free_patch(patch);4692if(nr == -128) {4693 res = -128;4694goto end;4695}4696break;4697}4698if(state->apply_in_reverse)4699reverse_patches(patch);4700if(use_patch(state, patch)) {4701patch_stats(state, patch);4702*listp = patch;4703 listp = &patch->next;4704}4705else{4706if(state->apply_verbosity > verbosity_normal)4707say_patch_name(stderr,_("Skipped patch '%s'."), patch);4708free_patch(patch);4709 skipped_patch++;4710}4711 offset += nr;4712}47134714if(!list && !skipped_patch) {4715error(_("unrecognized input"));4716 res = -128;4717goto end;4718}47194720if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4721 state->apply =0;47224723 state->update_index = (state->check_index || state->ita_only) && state->apply;4724if(state->update_index && !is_lock_file_locked(&state->lock_file)) {4725if(state->index_file)4726hold_lock_file_for_update(&state->lock_file,4727 state->index_file,4728 LOCK_DIE_ON_ERROR);4729else4730repo_hold_locked_index(state->repo, &state->lock_file,4731 LOCK_DIE_ON_ERROR);4732}47334734if(state->check_index &&read_apply_cache(state) <0) {4735error(_("unable to read index file"));4736 res = -128;4737goto end;4738}47394740if(state->check || state->apply) {4741int r =check_patch_list(state, list);4742if(r == -128) {4743 res = -128;4744goto end;4745}4746if(r <0&& !state->apply_with_reject) {4747 res = -1;4748goto end;4749}4750}47514752if(state->apply) {4753int write_res =write_out_results(state, list);4754if(write_res <0) {4755 res = -128;4756goto end;4757}4758if(write_res >0) {4759/* with --3way, we still need to write the index out */4760 res = state->apply_with_reject ? -1:1;4761goto end;4762}4763}47644765if(state->fake_ancestor &&4766build_fake_ancestor(state, list)) {4767 res = -128;4768goto end;4769}47704771if(state->diffstat && state->apply_verbosity > verbosity_silent)4772stat_patch_list(state, list);47734774if(state->numstat && state->apply_verbosity > verbosity_silent)4775numstat_patch_list(state, list);47764777if(state->summary && state->apply_verbosity > verbosity_silent)4778summary_patch_list(list);47794780end:4781free_patch_list(list);4782strbuf_release(&buf);4783string_list_clear(&state->fn_table,0);4784return res;4785}47864787static intapply_option_parse_exclude(const struct option *opt,4788const char*arg,int unset)4789{4790struct apply_state *state = opt->value;47914792BUG_ON_OPT_NEG(unset);47934794add_name_limit(state, arg,1);4795return0;4796}47974798static intapply_option_parse_include(const struct option *opt,4799const char*arg,int unset)4800{4801struct apply_state *state = opt->value;48024803BUG_ON_OPT_NEG(unset);48044805add_name_limit(state, arg,0);4806 state->has_include =1;4807return0;4808}48094810static intapply_option_parse_p(const struct option *opt,4811const char*arg,4812int unset)4813{4814struct apply_state *state = opt->value;48154816BUG_ON_OPT_NEG(unset);48174818 state->p_value =atoi(arg);4819 state->p_value_known =1;4820return0;4821}48224823static intapply_option_parse_space_change(const struct option *opt,4824const char*arg,int unset)4825{4826struct apply_state *state = opt->value;48274828BUG_ON_OPT_ARG(arg);48294830if(unset)4831 state->ws_ignore_action = ignore_ws_none;4832else4833 state->ws_ignore_action = ignore_ws_change;4834return0;4835}48364837static intapply_option_parse_whitespace(const struct option *opt,4838const char*arg,int unset)4839{4840struct apply_state *state = opt->value;48414842BUG_ON_OPT_NEG(unset);48434844 state->whitespace_option = arg;4845if(parse_whitespace_option(state, arg))4846return-1;4847return0;4848}48494850static intapply_option_parse_directory(const struct option *opt,4851const char*arg,int unset)4852{4853struct apply_state *state = opt->value;48544855BUG_ON_OPT_NEG(unset);48564857strbuf_reset(&state->root);4858strbuf_addstr(&state->root, arg);4859strbuf_complete(&state->root,'/');4860return0;4861}48624863intapply_all_patches(struct apply_state *state,4864int argc,4865const char**argv,4866int options)4867{4868int i;4869int res;4870int errs =0;4871int read_stdin =1;48724873for(i =0; i < argc; i++) {4874const char*arg = argv[i];4875char*to_free = NULL;4876int fd;48774878if(!strcmp(arg,"-")) {4879 res =apply_patch(state,0,"<stdin>", options);4880if(res <0)4881goto end;4882 errs |= res;4883 read_stdin =0;4884continue;4885}else4886 arg = to_free =prefix_filename(state->prefix, arg);48874888 fd =open(arg, O_RDONLY);4889if(fd <0) {4890error(_("can't open patch '%s':%s"), arg,strerror(errno));4891 res = -128;4892free(to_free);4893goto end;4894}4895 read_stdin =0;4896set_default_whitespace_mode(state);4897 res =apply_patch(state, fd, arg, options);4898close(fd);4899free(to_free);4900if(res <0)4901goto end;4902 errs |= res;4903}4904set_default_whitespace_mode(state);4905if(read_stdin) {4906 res =apply_patch(state,0,"<stdin>", options);4907if(res <0)4908goto end;4909 errs |= res;4910}49114912if(state->whitespace_error) {4913if(state->squelch_whitespace_errors &&4914 state->squelch_whitespace_errors < state->whitespace_error) {4915int squelched =4916 state->whitespace_error - state->squelch_whitespace_errors;4917warning(Q_("squelched%dwhitespace error",4918"squelched%dwhitespace errors",4919 squelched),4920 squelched);4921}4922if(state->ws_error_action == die_on_ws_error) {4923error(Q_("%dline adds whitespace errors.",4924"%dlines add whitespace errors.",4925 state->whitespace_error),4926 state->whitespace_error);4927 res = -128;4928goto end;4929}4930if(state->applied_after_fixing_ws && state->apply)4931warning(Q_("%dline applied after"4932" fixing whitespace errors.",4933"%dlines applied after"4934" fixing whitespace errors.",4935 state->applied_after_fixing_ws),4936 state->applied_after_fixing_ws);4937else if(state->whitespace_error)4938warning(Q_("%dline adds whitespace errors.",4939"%dlines add whitespace errors.",4940 state->whitespace_error),4941 state->whitespace_error);4942}49434944if(state->update_index) {4945 res =write_locked_index(state->repo->index, &state->lock_file, COMMIT_LOCK);4946if(res) {4947error(_("Unable to write new index file"));4948 res = -128;4949goto end;4950}4951}49524953 res = !!errs;49544955end:4956rollback_lock_file(&state->lock_file);49574958if(state->apply_verbosity <= verbosity_silent) {4959set_error_routine(state->saved_error_routine);4960set_warn_routine(state->saved_warn_routine);4961}49624963if(res > -1)4964return res;4965return(res == -1?1:128);4966}49674968intapply_parse_options(int argc,const char**argv,4969struct apply_state *state,4970int*force_apply,int*options,4971const char*const*apply_usage)4972{4973struct option builtin_apply_options[] = {4974{ OPTION_CALLBACK,0,"exclude", state,N_("path"),4975N_("don't apply changes matching the given path"),4976 PARSE_OPT_NONEG, apply_option_parse_exclude },4977{ OPTION_CALLBACK,0,"include", state,N_("path"),4978N_("apply changes matching the given path"),4979 PARSE_OPT_NONEG, apply_option_parse_include },4980{ OPTION_CALLBACK,'p', NULL, state,N_("num"),4981N_("remove <num> leading slashes from traditional diff paths"),49820, apply_option_parse_p },4983OPT_BOOL(0,"no-add", &state->no_add,4984N_("ignore additions made by the patch")),4985OPT_BOOL(0,"stat", &state->diffstat,4986N_("instead of applying the patch, output diffstat for the input")),4987OPT_NOOP_NOARG(0,"allow-binary-replacement"),4988OPT_NOOP_NOARG(0,"binary"),4989OPT_BOOL(0,"numstat", &state->numstat,4990N_("show number of added and deleted lines in decimal notation")),4991OPT_BOOL(0,"summary", &state->summary,4992N_("instead of applying the patch, output a summary for the input")),4993OPT_BOOL(0,"check", &state->check,4994N_("instead of applying the patch, see if the patch is applicable")),4995OPT_BOOL(0,"index", &state->check_index,4996N_("make sure the patch is applicable to the current index")),4997OPT_BOOL('N',"intent-to-add", &state->ita_only,4998N_("mark new files with `git add --intent-to-add`")),4999OPT_BOOL(0,"cached", &state->cached,5000N_("apply a patch without touching the working tree")),5001OPT_BOOL_F(0,"unsafe-paths", &state->unsafe_paths,5002N_("accept a patch that touches outside the working area"),5003 PARSE_OPT_NOCOMPLETE),5004OPT_BOOL(0,"apply", force_apply,5005N_("also apply the patch (use with --stat/--summary/--check)")),5006OPT_BOOL('3',"3way", &state->threeway,5007N_("attempt three-way merge if a patch does not apply")),5008OPT_FILENAME(0,"build-fake-ancestor", &state->fake_ancestor,5009N_("build a temporary index based on embedded index information")),5010/* Think twice before adding "--nul" synonym to this */5011OPT_SET_INT('z', NULL, &state->line_termination,5012N_("paths are separated with NUL character"),'\0'),5013OPT_INTEGER('C', NULL, &state->p_context,5014N_("ensure at least <n> lines of context match")),5015{ OPTION_CALLBACK,0,"whitespace", state,N_("action"),5016N_("detect new or modified lines that have whitespace errors"),50170, apply_option_parse_whitespace },5018{ OPTION_CALLBACK,0,"ignore-space-change", state, NULL,5019N_("ignore changes in whitespace when finding context"),5020 PARSE_OPT_NOARG, apply_option_parse_space_change },5021{ OPTION_CALLBACK,0,"ignore-whitespace", state, NULL,5022N_("ignore changes in whitespace when finding context"),5023 PARSE_OPT_NOARG, apply_option_parse_space_change },5024OPT_BOOL('R',"reverse", &state->apply_in_reverse,5025N_("apply the patch in reverse")),5026OPT_BOOL(0,"unidiff-zero", &state->unidiff_zero,5027N_("don't expect at least one line of context")),5028OPT_BOOL(0,"reject", &state->apply_with_reject,5029N_("leave the rejected hunks in corresponding *.rej files")),5030OPT_BOOL(0,"allow-overlap", &state->allow_overlap,5031N_("allow overlapping hunks")),5032OPT__VERBOSE(&state->apply_verbosity,N_("be verbose")),5033OPT_BIT(0,"inaccurate-eof", options,5034N_("tolerate incorrectly detected missing new-line at the end of file"),5035 APPLY_OPT_INACCURATE_EOF),5036OPT_BIT(0,"recount", options,5037N_("do not trust the line counts in the hunk headers"),5038 APPLY_OPT_RECOUNT),5039{ OPTION_CALLBACK,0,"directory", state,N_("root"),5040N_("prepend <root> to all filenames"),50410, apply_option_parse_directory },5042OPT_END()5043};50445045returnparse_options(argc, argv, state->prefix, builtin_apply_options, apply_usage,0);5046}