1/* 2 * apply.c 3 * 4 * Copyright (C) Linus Torvalds, 2005 5 * 6 * This applies patches on top of some (arbitrary) version of the SCM. 7 * 8 */ 9 10#include"cache.h" 11#include"config.h" 12#include"object-store.h" 13#include"blob.h" 14#include"delta.h" 15#include"diff.h" 16#include"dir.h" 17#include"xdiff-interface.h" 18#include"ll-merge.h" 19#include"lockfile.h" 20#include"parse-options.h" 21#include"quote.h" 22#include"rerere.h" 23#include"apply.h" 24 25static voidgit_apply_config(void) 26{ 27git_config_get_string_const("apply.whitespace", &apply_default_whitespace); 28git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace); 29git_config(git_default_config, NULL); 30} 31 32static intparse_whitespace_option(struct apply_state *state,const char*option) 33{ 34if(!option) { 35 state->ws_error_action = warn_on_ws_error; 36return0; 37} 38if(!strcmp(option,"warn")) { 39 state->ws_error_action = warn_on_ws_error; 40return0; 41} 42if(!strcmp(option,"nowarn")) { 43 state->ws_error_action = nowarn_ws_error; 44return0; 45} 46if(!strcmp(option,"error")) { 47 state->ws_error_action = die_on_ws_error; 48return0; 49} 50if(!strcmp(option,"error-all")) { 51 state->ws_error_action = die_on_ws_error; 52 state->squelch_whitespace_errors =0; 53return0; 54} 55if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 56 state->ws_error_action = correct_ws_error; 57return0; 58} 59/* 60 * Please update $__git_whitespacelist in git-completion.bash 61 * when you add new options. 62 */ 63returnerror(_("unrecognized whitespace option '%s'"), option); 64} 65 66static intparse_ignorewhitespace_option(struct apply_state *state, 67const char*option) 68{ 69if(!option || !strcmp(option,"no") || 70!strcmp(option,"false") || !strcmp(option,"never") || 71!strcmp(option,"none")) { 72 state->ws_ignore_action = ignore_ws_none; 73return0; 74} 75if(!strcmp(option,"change")) { 76 state->ws_ignore_action = ignore_ws_change; 77return0; 78} 79returnerror(_("unrecognized whitespace ignore option '%s'"), option); 80} 81 82intinit_apply_state(struct apply_state *state, 83struct repository *repo, 84const char*prefix) 85{ 86memset(state,0,sizeof(*state)); 87 state->prefix = prefix; 88 state->repo = repo; 89 state->apply =1; 90 state->line_termination ='\n'; 91 state->p_value =1; 92 state->p_context = UINT_MAX; 93 state->squelch_whitespace_errors =5; 94 state->ws_error_action = warn_on_ws_error; 95 state->ws_ignore_action = ignore_ws_none; 96 state->linenr =1; 97string_list_init(&state->fn_table,0); 98string_list_init(&state->limit_by_name,0); 99string_list_init(&state->symlink_changes,0); 100strbuf_init(&state->root,0); 101 102git_apply_config(); 103if(apply_default_whitespace &&parse_whitespace_option(state, apply_default_whitespace)) 104return-1; 105if(apply_default_ignorewhitespace &&parse_ignorewhitespace_option(state, apply_default_ignorewhitespace)) 106return-1; 107return0; 108} 109 110voidclear_apply_state(struct apply_state *state) 111{ 112string_list_clear(&state->limit_by_name,0); 113string_list_clear(&state->symlink_changes,0); 114strbuf_release(&state->root); 115 116/* &state->fn_table is cleared at the end of apply_patch() */ 117} 118 119static voidmute_routine(const char*msg,va_list params) 120{ 121/* do nothing */ 122} 123 124intcheck_apply_state(struct apply_state *state,int force_apply) 125{ 126int is_not_gitdir = !startup_info->have_repository; 127 128if(state->apply_with_reject && state->threeway) 129returnerror(_("--reject and --3way cannot be used together.")); 130if(state->cached && state->threeway) 131returnerror(_("--cached and --3way cannot be used together.")); 132if(state->threeway) { 133if(is_not_gitdir) 134returnerror(_("--3way outside a repository")); 135 state->check_index =1; 136} 137if(state->apply_with_reject) { 138 state->apply =1; 139if(state->apply_verbosity == verbosity_normal) 140 state->apply_verbosity = verbosity_verbose; 141} 142if(!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor)) 143 state->apply =0; 144if(state->check_index && is_not_gitdir) 145returnerror(_("--index outside a repository")); 146if(state->cached) { 147if(is_not_gitdir) 148returnerror(_("--cached outside a repository")); 149 state->check_index =1; 150} 151if(state->ita_only && (state->check_index || is_not_gitdir)) 152 state->ita_only =0; 153if(state->check_index) 154 state->unsafe_paths =0; 155 156if(state->apply_verbosity <= verbosity_silent) { 157 state->saved_error_routine =get_error_routine(); 158 state->saved_warn_routine =get_warn_routine(); 159set_error_routine(mute_routine); 160set_warn_routine(mute_routine); 161} 162 163return0; 164} 165 166static voidset_default_whitespace_mode(struct apply_state *state) 167{ 168if(!state->whitespace_option && !apply_default_whitespace) 169 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 170} 171 172/* 173 * This represents one "hunk" from a patch, starting with 174 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 175 * patch text is pointed at by patch, and its byte length 176 * is stored in size. leading and trailing are the number 177 * of context lines. 178 */ 179struct fragment { 180unsigned long leading, trailing; 181unsigned long oldpos, oldlines; 182unsigned long newpos, newlines; 183/* 184 * 'patch' is usually borrowed from buf in apply_patch(), 185 * but some codepaths store an allocated buffer. 186 */ 187const char*patch; 188unsigned free_patch:1, 189 rejected:1; 190int size; 191int linenr; 192struct fragment *next; 193}; 194 195/* 196 * When dealing with a binary patch, we reuse "leading" field 197 * to store the type of the binary hunk, either deflated "delta" 198 * or deflated "literal". 199 */ 200#define binary_patch_method leading 201#define BINARY_DELTA_DEFLATED 1 202#define BINARY_LITERAL_DEFLATED 2 203 204/* 205 * This represents a "patch" to a file, both metainfo changes 206 * such as creation/deletion, filemode and content changes represented 207 * as a series of fragments. 208 */ 209struct patch { 210char*new_name, *old_name, *def_name; 211unsigned int old_mode, new_mode; 212int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 213int rejected; 214unsigned ws_rule; 215int lines_added, lines_deleted; 216int score; 217int extension_linenr;/* first line specifying delete/new/rename/copy */ 218unsigned int is_toplevel_relative:1; 219unsigned int inaccurate_eof:1; 220unsigned int is_binary:1; 221unsigned int is_copy:1; 222unsigned int is_rename:1; 223unsigned int recount:1; 224unsigned int conflicted_threeway:1; 225unsigned int direct_to_threeway:1; 226unsigned int crlf_in_old:1; 227struct fragment *fragments; 228char*result; 229size_t resultsize; 230char old_oid_prefix[GIT_MAX_HEXSZ +1]; 231char new_oid_prefix[GIT_MAX_HEXSZ +1]; 232struct patch *next; 233 234/* three-way fallback result */ 235struct object_id threeway_stage[3]; 236}; 237 238static voidfree_fragment_list(struct fragment *list) 239{ 240while(list) { 241struct fragment *next = list->next; 242if(list->free_patch) 243free((char*)list->patch); 244free(list); 245 list = next; 246} 247} 248 249static voidfree_patch(struct patch *patch) 250{ 251free_fragment_list(patch->fragments); 252free(patch->def_name); 253free(patch->old_name); 254free(patch->new_name); 255free(patch->result); 256free(patch); 257} 258 259static voidfree_patch_list(struct patch *list) 260{ 261while(list) { 262struct patch *next = list->next; 263free_patch(list); 264 list = next; 265} 266} 267 268/* 269 * A line in a file, len-bytes long (includes the terminating LF, 270 * except for an incomplete line at the end if the file ends with 271 * one), and its contents hashes to 'hash'. 272 */ 273struct line { 274size_t len; 275unsigned hash :24; 276unsigned flag :8; 277#define LINE_COMMON 1 278#define LINE_PATCHED 2 279}; 280 281/* 282 * This represents a "file", which is an array of "lines". 283 */ 284struct image { 285char*buf; 286size_t len; 287size_t nr; 288size_t alloc; 289struct line *line_allocated; 290struct line *line; 291}; 292 293static uint32_thash_line(const char*cp,size_t len) 294{ 295size_t i; 296uint32_t h; 297for(i =0, h =0; i < len; i++) { 298if(!isspace(cp[i])) { 299 h = h *3+ (cp[i] &0xff); 300} 301} 302return h; 303} 304 305/* 306 * Compare lines s1 of length n1 and s2 of length n2, ignoring 307 * whitespace difference. Returns 1 if they match, 0 otherwise 308 */ 309static intfuzzy_matchlines(const char*s1,size_t n1, 310const char*s2,size_t n2) 311{ 312const char*end1 = s1 + n1; 313const char*end2 = s2 + n2; 314 315/* ignore line endings */ 316while(s1 < end1 && (end1[-1] =='\r'|| end1[-1] =='\n')) 317 end1--; 318while(s2 < end2 && (end2[-1] =='\r'|| end2[-1] =='\n')) 319 end2--; 320 321while(s1 < end1 && s2 < end2) { 322if(isspace(*s1)) { 323/* 324 * Skip whitespace. We check on both buffers 325 * because we don't want "a b" to match "ab". 326 */ 327if(!isspace(*s2)) 328return0; 329while(s1 < end1 &&isspace(*s1)) 330 s1++; 331while(s2 < end2 &&isspace(*s2)) 332 s2++; 333}else if(*s1++ != *s2++) 334return0; 335} 336 337/* If we reached the end on one side only, lines don't match. */ 338return s1 == end1 && s2 == end2; 339} 340 341static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 342{ 343ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 344 img->line_allocated[img->nr].len = len; 345 img->line_allocated[img->nr].hash =hash_line(bol, len); 346 img->line_allocated[img->nr].flag = flag; 347 img->nr++; 348} 349 350/* 351 * "buf" has the file contents to be patched (read from various sources). 352 * attach it to "image" and add line-based index to it. 353 * "image" now owns the "buf". 354 */ 355static voidprepare_image(struct image *image,char*buf,size_t len, 356int prepare_linetable) 357{ 358const char*cp, *ep; 359 360memset(image,0,sizeof(*image)); 361 image->buf = buf; 362 image->len = len; 363 364if(!prepare_linetable) 365return; 366 367 ep = image->buf + image->len; 368 cp = image->buf; 369while(cp < ep) { 370const char*next; 371for(next = cp; next < ep && *next !='\n'; next++) 372; 373if(next < ep) 374 next++; 375add_line_info(image, cp, next - cp,0); 376 cp = next; 377} 378 image->line = image->line_allocated; 379} 380 381static voidclear_image(struct image *image) 382{ 383free(image->buf); 384free(image->line_allocated); 385memset(image,0,sizeof(*image)); 386} 387 388/* fmt must contain _one_ %s and no other substitution */ 389static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 390{ 391struct strbuf sb = STRBUF_INIT; 392 393if(patch->old_name && patch->new_name && 394strcmp(patch->old_name, patch->new_name)) { 395quote_c_style(patch->old_name, &sb, NULL,0); 396strbuf_addstr(&sb," => "); 397quote_c_style(patch->new_name, &sb, NULL,0); 398}else{ 399const char*n = patch->new_name; 400if(!n) 401 n = patch->old_name; 402quote_c_style(n, &sb, NULL,0); 403} 404fprintf(output, fmt, sb.buf); 405fputc('\n', output); 406strbuf_release(&sb); 407} 408 409#define SLOP (16) 410 411static intread_patch_file(struct strbuf *sb,int fd) 412{ 413if(strbuf_read(sb, fd,0) <0) 414returnerror_errno("git apply: failed to read"); 415 416/* 417 * Make sure that we have some slop in the buffer 418 * so that we can do speculative "memcmp" etc, and 419 * see to it that it is NUL-filled. 420 */ 421strbuf_grow(sb, SLOP); 422memset(sb->buf + sb->len,0, SLOP); 423return0; 424} 425 426static unsigned longlinelen(const char*buffer,unsigned long size) 427{ 428unsigned long len =0; 429while(size--) { 430 len++; 431if(*buffer++ =='\n') 432break; 433} 434return len; 435} 436 437static intis_dev_null(const char*str) 438{ 439returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 440} 441 442#define TERM_SPACE 1 443#define TERM_TAB 2 444 445static intname_terminate(int c,int terminate) 446{ 447if(c ==' '&& !(terminate & TERM_SPACE)) 448return0; 449if(c =='\t'&& !(terminate & TERM_TAB)) 450return0; 451 452return1; 453} 454 455/* remove double slashes to make --index work with such filenames */ 456static char*squash_slash(char*name) 457{ 458int i =0, j =0; 459 460if(!name) 461return NULL; 462 463while(name[i]) { 464if((name[j++] = name[i++]) =='/') 465while(name[i] =='/') 466 i++; 467} 468 name[j] ='\0'; 469return name; 470} 471 472static char*find_name_gnu(struct apply_state *state, 473const char*line, 474int p_value) 475{ 476struct strbuf name = STRBUF_INIT; 477char*cp; 478 479/* 480 * Proposed "new-style" GNU patch/diff format; see 481 * https://public-inbox.org/git/7vll0wvb2a.fsf@assigned-by-dhcp.cox.net/ 482 */ 483if(unquote_c_style(&name, line, NULL)) { 484strbuf_release(&name); 485return NULL; 486} 487 488for(cp = name.buf; p_value; p_value--) { 489 cp =strchr(cp,'/'); 490if(!cp) { 491strbuf_release(&name); 492return NULL; 493} 494 cp++; 495} 496 497strbuf_remove(&name,0, cp - name.buf); 498if(state->root.len) 499strbuf_insert(&name,0, state->root.buf, state->root.len); 500returnsquash_slash(strbuf_detach(&name, NULL)); 501} 502 503static size_tsane_tz_len(const char*line,size_t len) 504{ 505const char*tz, *p; 506 507if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 508return0; 509 tz = line + len -strlen(" +0500"); 510 511if(tz[1] !='+'&& tz[1] !='-') 512return0; 513 514for(p = tz +2; p != line + len; p++) 515if(!isdigit(*p)) 516return0; 517 518return line + len - tz; 519} 520 521static size_ttz_with_colon_len(const char*line,size_t len) 522{ 523const char*tz, *p; 524 525if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 526return0; 527 tz = line + len -strlen(" +08:00"); 528 529if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 530return0; 531 p = tz +2; 532if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 533!isdigit(*p++) || !isdigit(*p++)) 534return0; 535 536return line + len - tz; 537} 538 539static size_tdate_len(const char*line,size_t len) 540{ 541const char*date, *p; 542 543if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 544return0; 545 p = date = line + len -strlen("72-02-05"); 546 547if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 548!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 549!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 550return0; 551 552if(date - line >=strlen("19") && 553isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 554 date -=strlen("19"); 555 556return line + len - date; 557} 558 559static size_tshort_time_len(const char*line,size_t len) 560{ 561const char*time, *p; 562 563if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 564return0; 565 p = time = line + len -strlen(" 07:01:32"); 566 567/* Permit 1-digit hours? */ 568if(*p++ !=' '|| 569!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 570!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 571!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 572return0; 573 574return line + len - time; 575} 576 577static size_tfractional_time_len(const char*line,size_t len) 578{ 579const char*p; 580size_t n; 581 582/* Expected format: 19:41:17.620000023 */ 583if(!len || !isdigit(line[len -1])) 584return0; 585 p = line + len -1; 586 587/* Fractional seconds. */ 588while(p > line &&isdigit(*p)) 589 p--; 590if(*p !='.') 591return0; 592 593/* Hours, minutes, and whole seconds. */ 594 n =short_time_len(line, p - line); 595if(!n) 596return0; 597 598return line + len - p + n; 599} 600 601static size_ttrailing_spaces_len(const char*line,size_t len) 602{ 603const char*p; 604 605/* Expected format: ' ' x (1 or more) */ 606if(!len || line[len -1] !=' ') 607return0; 608 609 p = line + len; 610while(p != line) { 611 p--; 612if(*p !=' ') 613return line + len - (p +1); 614} 615 616/* All spaces! */ 617return len; 618} 619 620static size_tdiff_timestamp_len(const char*line,size_t len) 621{ 622const char*end = line + len; 623size_t n; 624 625/* 626 * Posix: 2010-07-05 19:41:17 627 * GNU: 2010-07-05 19:41:17.620000023 -0500 628 */ 629 630if(!isdigit(end[-1])) 631return0; 632 633 n =sane_tz_len(line, end - line); 634if(!n) 635 n =tz_with_colon_len(line, end - line); 636 end -= n; 637 638 n =short_time_len(line, end - line); 639if(!n) 640 n =fractional_time_len(line, end - line); 641 end -= n; 642 643 n =date_len(line, end - line); 644if(!n)/* No date. Too bad. */ 645return0; 646 end -= n; 647 648if(end == line)/* No space before date. */ 649return0; 650if(end[-1] =='\t') {/* Success! */ 651 end--; 652return line + len - end; 653} 654if(end[-1] !=' ')/* No space before date. */ 655return0; 656 657/* Whitespace damage. */ 658 end -=trailing_spaces_len(line, end - line); 659return line + len - end; 660} 661 662static char*find_name_common(struct apply_state *state, 663const char*line, 664const char*def, 665int p_value, 666const char*end, 667int terminate) 668{ 669int len; 670const char*start = NULL; 671 672if(p_value ==0) 673 start = line; 674while(line != end) { 675char c = *line; 676 677if(!end &&isspace(c)) { 678if(c =='\n') 679break; 680if(name_terminate(c, terminate)) 681break; 682} 683 line++; 684if(c =='/'&& !--p_value) 685 start = line; 686} 687if(!start) 688returnsquash_slash(xstrdup_or_null(def)); 689 len = line - start; 690if(!len) 691returnsquash_slash(xstrdup_or_null(def)); 692 693/* 694 * Generally we prefer the shorter name, especially 695 * if the other one is just a variation of that with 696 * something else tacked on to the end (ie "file.orig" 697 * or "file~"). 698 */ 699if(def) { 700int deflen =strlen(def); 701if(deflen < len && !strncmp(start, def, deflen)) 702returnsquash_slash(xstrdup(def)); 703} 704 705if(state->root.len) { 706char*ret =xstrfmt("%s%.*s", state->root.buf, len, start); 707returnsquash_slash(ret); 708} 709 710returnsquash_slash(xmemdupz(start, len)); 711} 712 713static char*find_name(struct apply_state *state, 714const char*line, 715char*def, 716int p_value, 717int terminate) 718{ 719if(*line =='"') { 720char*name =find_name_gnu(state, line, p_value); 721if(name) 722return name; 723} 724 725returnfind_name_common(state, line, def, p_value, NULL, terminate); 726} 727 728static char*find_name_traditional(struct apply_state *state, 729const char*line, 730char*def, 731int p_value) 732{ 733size_t len; 734size_t date_len; 735 736if(*line =='"') { 737char*name =find_name_gnu(state, line, p_value); 738if(name) 739return name; 740} 741 742 len =strchrnul(line,'\n') - line; 743 date_len =diff_timestamp_len(line, len); 744if(!date_len) 745returnfind_name_common(state, line, def, p_value, NULL, TERM_TAB); 746 len -= date_len; 747 748returnfind_name_common(state, line, def, p_value, line + len,0); 749} 750 751/* 752 * Given the string after "--- " or "+++ ", guess the appropriate 753 * p_value for the given patch. 754 */ 755static intguess_p_value(struct apply_state *state,const char*nameline) 756{ 757char*name, *cp; 758int val = -1; 759 760if(is_dev_null(nameline)) 761return-1; 762 name =find_name_traditional(state, nameline, NULL,0); 763if(!name) 764return-1; 765 cp =strchr(name,'/'); 766if(!cp) 767 val =0; 768else if(state->prefix) { 769/* 770 * Does it begin with "a/$our-prefix" and such? Then this is 771 * very likely to apply to our directory. 772 */ 773if(starts_with(name, state->prefix)) 774 val =count_slashes(state->prefix); 775else{ 776 cp++; 777if(starts_with(cp, state->prefix)) 778 val =count_slashes(state->prefix) +1; 779} 780} 781free(name); 782return val; 783} 784 785/* 786 * Does the ---/+++ line have the POSIX timestamp after the last HT? 787 * GNU diff puts epoch there to signal a creation/deletion event. Is 788 * this such a timestamp? 789 */ 790static inthas_epoch_timestamp(const char*nameline) 791{ 792/* 793 * We are only interested in epoch timestamp; any non-zero 794 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 795 * For the same reason, the date must be either 1969-12-31 or 796 * 1970-01-01, and the seconds part must be "00". 797 */ 798const char stamp_regexp[] = 799"^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?" 800" " 801"([-+][0-2][0-9]:?[0-5][0-9])\n"; 802const char*timestamp = NULL, *cp, *colon; 803static regex_t *stamp; 804 regmatch_t m[10]; 805int zoneoffset, epoch_hour, hour, minute; 806int status; 807 808for(cp = nameline; *cp !='\n'; cp++) { 809if(*cp =='\t') 810 timestamp = cp +1; 811} 812if(!timestamp) 813return0; 814 815/* 816 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 817 * (west of GMT) or 1970-01-01 (east of GMT) 818 */ 819if(skip_prefix(timestamp,"1969-12-31 ", ×tamp)) 820 epoch_hour =24; 821else if(skip_prefix(timestamp,"1970-01-01 ", ×tamp)) 822 epoch_hour =0; 823else 824return0; 825 826if(!stamp) { 827 stamp =xmalloc(sizeof(*stamp)); 828if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 829warning(_("Cannot prepare timestamp regexp%s"), 830 stamp_regexp); 831return0; 832} 833} 834 835 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 836if(status) { 837if(status != REG_NOMATCH) 838warning(_("regexec returned%dfor input:%s"), 839 status, timestamp); 840return0; 841} 842 843 hour =strtol(timestamp, NULL,10); 844 minute =strtol(timestamp + m[1].rm_so, NULL,10); 845 846 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 847if(*colon ==':') 848 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 849else 850 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 851if(timestamp[m[3].rm_so] =='-') 852 zoneoffset = -zoneoffset; 853 854return hour *60+ minute - zoneoffset == epoch_hour *60; 855} 856 857/* 858 * Get the name etc info from the ---/+++ lines of a traditional patch header 859 * 860 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 861 * files, we can happily check the index for a match, but for creating a 862 * new file we should try to match whatever "patch" does. I have no idea. 863 */ 864static intparse_traditional_patch(struct apply_state *state, 865const char*first, 866const char*second, 867struct patch *patch) 868{ 869char*name; 870 871 first +=4;/* skip "--- " */ 872 second +=4;/* skip "+++ " */ 873if(!state->p_value_known) { 874int p, q; 875 p =guess_p_value(state, first); 876 q =guess_p_value(state, second); 877if(p <0) p = q; 878if(0<= p && p == q) { 879 state->p_value = p; 880 state->p_value_known =1; 881} 882} 883if(is_dev_null(first)) { 884 patch->is_new =1; 885 patch->is_delete =0; 886 name =find_name_traditional(state, second, NULL, state->p_value); 887 patch->new_name = name; 888}else if(is_dev_null(second)) { 889 patch->is_new =0; 890 patch->is_delete =1; 891 name =find_name_traditional(state, first, NULL, state->p_value); 892 patch->old_name = name; 893}else{ 894char*first_name; 895 first_name =find_name_traditional(state, first, NULL, state->p_value); 896 name =find_name_traditional(state, second, first_name, state->p_value); 897free(first_name); 898if(has_epoch_timestamp(first)) { 899 patch->is_new =1; 900 patch->is_delete =0; 901 patch->new_name = name; 902}else if(has_epoch_timestamp(second)) { 903 patch->is_new =0; 904 patch->is_delete =1; 905 patch->old_name = name; 906}else{ 907 patch->old_name = name; 908 patch->new_name =xstrdup_or_null(name); 909} 910} 911if(!name) 912returnerror(_("unable to find filename in patch at line%d"), state->linenr); 913 914return0; 915} 916 917static intgitdiff_hdrend(struct apply_state *state, 918const char*line, 919struct patch *patch) 920{ 921return1; 922} 923 924/* 925 * We're anal about diff header consistency, to make 926 * sure that we don't end up having strange ambiguous 927 * patches floating around. 928 * 929 * As a result, gitdiff_{old|new}name() will check 930 * their names against any previous information, just 931 * to make sure.. 932 */ 933#define DIFF_OLD_NAME 0 934#define DIFF_NEW_NAME 1 935 936static intgitdiff_verify_name(struct apply_state *state, 937const char*line, 938int isnull, 939char**name, 940int side) 941{ 942if(!*name && !isnull) { 943*name =find_name(state, line, NULL, state->p_value, TERM_TAB); 944return0; 945} 946 947if(*name) { 948char*another; 949if(isnull) 950returnerror(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 951*name, state->linenr); 952 another =find_name(state, line, NULL, state->p_value, TERM_TAB); 953if(!another ||strcmp(another, *name)) { 954free(another); 955returnerror((side == DIFF_NEW_NAME) ? 956_("git apply: bad git-diff - inconsistent new filename on line%d") : 957_("git apply: bad git-diff - inconsistent old filename on line%d"), state->linenr); 958} 959free(another); 960}else{ 961if(!is_dev_null(line)) 962returnerror(_("git apply: bad git-diff - expected /dev/null on line%d"), state->linenr); 963} 964 965return0; 966} 967 968static intgitdiff_oldname(struct apply_state *state, 969const char*line, 970struct patch *patch) 971{ 972returngitdiff_verify_name(state, line, 973 patch->is_new, &patch->old_name, 974 DIFF_OLD_NAME); 975} 976 977static intgitdiff_newname(struct apply_state *state, 978const char*line, 979struct patch *patch) 980{ 981returngitdiff_verify_name(state, line, 982 patch->is_delete, &patch->new_name, 983 DIFF_NEW_NAME); 984} 985 986static intparse_mode_line(const char*line,int linenr,unsigned int*mode) 987{ 988char*end; 989*mode =strtoul(line, &end,8); 990if(end == line || !isspace(*end)) 991returnerror(_("invalid mode on line%d:%s"), linenr, line); 992return0; 993} 994 995static intgitdiff_oldmode(struct apply_state *state, 996const char*line, 997struct patch *patch) 998{ 999returnparse_mode_line(line, state->linenr, &patch->old_mode);1000}10011002static intgitdiff_newmode(struct apply_state *state,1003const char*line,1004struct patch *patch)1005{1006returnparse_mode_line(line, state->linenr, &patch->new_mode);1007}10081009static intgitdiff_delete(struct apply_state *state,1010const char*line,1011struct patch *patch)1012{1013 patch->is_delete =1;1014free(patch->old_name);1015 patch->old_name =xstrdup_or_null(patch->def_name);1016returngitdiff_oldmode(state, line, patch);1017}10181019static intgitdiff_newfile(struct apply_state *state,1020const char*line,1021struct patch *patch)1022{1023 patch->is_new =1;1024free(patch->new_name);1025 patch->new_name =xstrdup_or_null(patch->def_name);1026returngitdiff_newmode(state, line, patch);1027}10281029static intgitdiff_copysrc(struct apply_state *state,1030const char*line,1031struct patch *patch)1032{1033 patch->is_copy =1;1034free(patch->old_name);1035 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1036return0;1037}10381039static intgitdiff_copydst(struct apply_state *state,1040const char*line,1041struct patch *patch)1042{1043 patch->is_copy =1;1044free(patch->new_name);1045 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1046return0;1047}10481049static intgitdiff_renamesrc(struct apply_state *state,1050const char*line,1051struct patch *patch)1052{1053 patch->is_rename =1;1054free(patch->old_name);1055 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1056return0;1057}10581059static intgitdiff_renamedst(struct apply_state *state,1060const char*line,1061struct patch *patch)1062{1063 patch->is_rename =1;1064free(patch->new_name);1065 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1066return0;1067}10681069static intgitdiff_similarity(struct apply_state *state,1070const char*line,1071struct patch *patch)1072{1073unsigned long val =strtoul(line, NULL,10);1074if(val <=100)1075 patch->score = val;1076return0;1077}10781079static intgitdiff_dissimilarity(struct apply_state *state,1080const char*line,1081struct patch *patch)1082{1083unsigned long val =strtoul(line, NULL,10);1084if(val <=100)1085 patch->score = val;1086return0;1087}10881089static intgitdiff_index(struct apply_state *state,1090const char*line,1091struct patch *patch)1092{1093/*1094 * index line is N hexadecimal, "..", N hexadecimal,1095 * and optional space with octal mode.1096 */1097const char*ptr, *eol;1098int len;1099const unsigned hexsz = the_hash_algo->hexsz;11001101 ptr =strchr(line,'.');1102if(!ptr || ptr[1] !='.'|| hexsz < ptr - line)1103return0;1104 len = ptr - line;1105memcpy(patch->old_oid_prefix, line, len);1106 patch->old_oid_prefix[len] =0;11071108 line = ptr +2;1109 ptr =strchr(line,' ');1110 eol =strchrnul(line,'\n');11111112if(!ptr || eol < ptr)1113 ptr = eol;1114 len = ptr - line;11151116if(hexsz < len)1117return0;1118memcpy(patch->new_oid_prefix, line, len);1119 patch->new_oid_prefix[len] =0;1120if(*ptr ==' ')1121returngitdiff_oldmode(state, ptr +1, patch);1122return0;1123}11241125/*1126 * This is normal for a diff that doesn't change anything: we'll fall through1127 * into the next diff. Tell the parser to break out.1128 */1129static intgitdiff_unrecognized(struct apply_state *state,1130const char*line,1131struct patch *patch)1132{1133return1;1134}11351136/*1137 * Skip p_value leading components from "line"; as we do not accept1138 * absolute paths, return NULL in that case.1139 */1140static const char*skip_tree_prefix(int p_value,1141const char*line,1142int llen)1143{1144int nslash;1145int i;11461147if(!p_value)1148return(llen && line[0] =='/') ? NULL : line;11491150 nslash = p_value;1151for(i =0; i < llen; i++) {1152int ch = line[i];1153if(ch =='/'&& --nslash <=0)1154return(i ==0) ? NULL : &line[i +1];1155}1156return NULL;1157}11581159/*1160 * This is to extract the same name that appears on "diff --git"1161 * line. We do not find and return anything if it is a rename1162 * patch, and it is OK because we will find the name elsewhere.1163 * We need to reliably find name only when it is mode-change only,1164 * creation or deletion of an empty file. In any of these cases,1165 * both sides are the same name under a/ and b/ respectively.1166 */1167static char*git_header_name(struct apply_state *state,1168const char*line,1169int llen)1170{1171const char*name;1172const char*second = NULL;1173size_t len, line_len;11741175 line +=strlen("diff --git ");1176 llen -=strlen("diff --git ");11771178if(*line =='"') {1179const char*cp;1180struct strbuf first = STRBUF_INIT;1181struct strbuf sp = STRBUF_INIT;11821183if(unquote_c_style(&first, line, &second))1184goto free_and_fail1;11851186/* strip the a/b prefix including trailing slash */1187 cp =skip_tree_prefix(state->p_value, first.buf, first.len);1188if(!cp)1189goto free_and_fail1;1190strbuf_remove(&first,0, cp - first.buf);11911192/*1193 * second points at one past closing dq of name.1194 * find the second name.1195 */1196while((second < line + llen) &&isspace(*second))1197 second++;11981199if(line + llen <= second)1200goto free_and_fail1;1201if(*second =='"') {1202if(unquote_c_style(&sp, second, NULL))1203goto free_and_fail1;1204 cp =skip_tree_prefix(state->p_value, sp.buf, sp.len);1205if(!cp)1206goto free_and_fail1;1207/* They must match, otherwise ignore */1208if(strcmp(cp, first.buf))1209goto free_and_fail1;1210strbuf_release(&sp);1211returnstrbuf_detach(&first, NULL);1212}12131214/* unquoted second */1215 cp =skip_tree_prefix(state->p_value, second, line + llen - second);1216if(!cp)1217goto free_and_fail1;1218if(line + llen - cp != first.len ||1219memcmp(first.buf, cp, first.len))1220goto free_and_fail1;1221returnstrbuf_detach(&first, NULL);12221223 free_and_fail1:1224strbuf_release(&first);1225strbuf_release(&sp);1226return NULL;1227}12281229/* unquoted first name */1230 name =skip_tree_prefix(state->p_value, line, llen);1231if(!name)1232return NULL;12331234/*1235 * since the first name is unquoted, a dq if exists must be1236 * the beginning of the second name.1237 */1238for(second = name; second < line + llen; second++) {1239if(*second =='"') {1240struct strbuf sp = STRBUF_INIT;1241const char*np;12421243if(unquote_c_style(&sp, second, NULL))1244goto free_and_fail2;12451246 np =skip_tree_prefix(state->p_value, sp.buf, sp.len);1247if(!np)1248goto free_and_fail2;12491250 len = sp.buf + sp.len - np;1251if(len < second - name &&1252!strncmp(np, name, len) &&1253isspace(name[len])) {1254/* Good */1255strbuf_remove(&sp,0, np - sp.buf);1256returnstrbuf_detach(&sp, NULL);1257}12581259 free_and_fail2:1260strbuf_release(&sp);1261return NULL;1262}1263}12641265/*1266 * Accept a name only if it shows up twice, exactly the same1267 * form.1268 */1269 second =strchr(name,'\n');1270if(!second)1271return NULL;1272 line_len = second - name;1273for(len =0; ; len++) {1274switch(name[len]) {1275default:1276continue;1277case'\n':1278return NULL;1279case'\t':case' ':1280/*1281 * Is this the separator between the preimage1282 * and the postimage pathname? Again, we are1283 * only interested in the case where there is1284 * no rename, as this is only to set def_name1285 * and a rename patch has the names elsewhere1286 * in an unambiguous form.1287 */1288if(!name[len +1])1289return NULL;/* no postimage name */1290 second =skip_tree_prefix(state->p_value, name + len +1,1291 line_len - (len +1));1292if(!second)1293return NULL;1294/*1295 * Does len bytes starting at "name" and "second"1296 * (that are separated by one HT or SP we just1297 * found) exactly match?1298 */1299if(second[len] =='\n'&& !strncmp(name, second, len))1300returnxmemdupz(name, len);1301}1302}1303}13041305static intcheck_header_line(struct apply_state *state,struct patch *patch)1306{1307int extensions = (patch->is_delete ==1) + (patch->is_new ==1) +1308(patch->is_rename ==1) + (patch->is_copy ==1);1309if(extensions >1)1310returnerror(_("inconsistent header lines%dand%d"),1311 patch->extension_linenr, state->linenr);1312if(extensions && !patch->extension_linenr)1313 patch->extension_linenr = state->linenr;1314return0;1315}13161317/* Verify that we recognize the lines following a git header */1318static intparse_git_header(struct apply_state *state,1319const char*line,1320int len,1321unsigned int size,1322struct patch *patch)1323{1324unsigned long offset;13251326/* A git diff has explicit new/delete information, so we don't guess */1327 patch->is_new =0;1328 patch->is_delete =0;13291330/*1331 * Some things may not have the old name in the1332 * rest of the headers anywhere (pure mode changes,1333 * or removing or adding empty files), so we get1334 * the default name from the header.1335 */1336 patch->def_name =git_header_name(state, line, len);1337if(patch->def_name && state->root.len) {1338char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1339free(patch->def_name);1340 patch->def_name = s;1341}13421343 line += len;1344 size -= len;1345 state->linenr++;1346for(offset = len ; size >0; offset += len, size -= len, line += len, state->linenr++) {1347static const struct opentry {1348const char*str;1349int(*fn)(struct apply_state *,const char*,struct patch *);1350} optable[] = {1351{"@@ -", gitdiff_hdrend },1352{"--- ", gitdiff_oldname },1353{"+++ ", gitdiff_newname },1354{"old mode ", gitdiff_oldmode },1355{"new mode ", gitdiff_newmode },1356{"deleted file mode ", gitdiff_delete },1357{"new file mode ", gitdiff_newfile },1358{"copy from ", gitdiff_copysrc },1359{"copy to ", gitdiff_copydst },1360{"rename old ", gitdiff_renamesrc },1361{"rename new ", gitdiff_renamedst },1362{"rename from ", gitdiff_renamesrc },1363{"rename to ", gitdiff_renamedst },1364{"similarity index ", gitdiff_similarity },1365{"dissimilarity index ", gitdiff_dissimilarity },1366{"index ", gitdiff_index },1367{"", gitdiff_unrecognized },1368};1369int i;13701371 len =linelen(line, size);1372if(!len || line[len-1] !='\n')1373break;1374for(i =0; i <ARRAY_SIZE(optable); i++) {1375const struct opentry *p = optable + i;1376int oplen =strlen(p->str);1377int res;1378if(len < oplen ||memcmp(p->str, line, oplen))1379continue;1380 res = p->fn(state, line + oplen, patch);1381if(res <0)1382return-1;1383if(check_header_line(state, patch))1384return-1;1385if(res >0)1386return offset;1387break;1388}1389}13901391return offset;1392}13931394static intparse_num(const char*line,unsigned long*p)1395{1396char*ptr;13971398if(!isdigit(*line))1399return0;1400*p =strtoul(line, &ptr,10);1401return ptr - line;1402}14031404static intparse_range(const char*line,int len,int offset,const char*expect,1405unsigned long*p1,unsigned long*p2)1406{1407int digits, ex;14081409if(offset <0|| offset >= len)1410return-1;1411 line += offset;1412 len -= offset;14131414 digits =parse_num(line, p1);1415if(!digits)1416return-1;14171418 offset += digits;1419 line += digits;1420 len -= digits;14211422*p2 =1;1423if(*line ==',') {1424 digits =parse_num(line+1, p2);1425if(!digits)1426return-1;14271428 offset += digits+1;1429 line += digits+1;1430 len -= digits+1;1431}14321433 ex =strlen(expect);1434if(ex > len)1435return-1;1436if(memcmp(line, expect, ex))1437return-1;14381439return offset + ex;1440}14411442static voidrecount_diff(const char*line,int size,struct fragment *fragment)1443{1444int oldlines =0, newlines =0, ret =0;14451446if(size <1) {1447warning("recount: ignore empty hunk");1448return;1449}14501451for(;;) {1452int len =linelen(line, size);1453 size -= len;1454 line += len;14551456if(size <1)1457break;14581459switch(*line) {1460case' ':case'\n':1461 newlines++;1462/* fall through */1463case'-':1464 oldlines++;1465continue;1466case'+':1467 newlines++;1468continue;1469case'\\':1470continue;1471case'@':1472 ret = size <3|| !starts_with(line,"@@ ");1473break;1474case'd':1475 ret = size <5|| !starts_with(line,"diff ");1476break;1477default:1478 ret = -1;1479break;1480}1481if(ret) {1482warning(_("recount: unexpected line: %.*s"),1483(int)linelen(line, size), line);1484return;1485}1486break;1487}1488 fragment->oldlines = oldlines;1489 fragment->newlines = newlines;1490}14911492/*1493 * Parse a unified diff fragment header of the1494 * form "@@ -a,b +c,d @@"1495 */1496static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1497{1498int offset;14991500if(!len || line[len-1] !='\n')1501return-1;15021503/* Figure out the number of lines in a fragment */1504 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1505 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);15061507return offset;1508}15091510/*1511 * Find file diff header1512 *1513 * Returns:1514 * -1 if no header was found1515 * -128 in case of error1516 * the size of the header in bytes (called "offset") otherwise1517 */1518static intfind_header(struct apply_state *state,1519const char*line,1520unsigned long size,1521int*hdrsize,1522struct patch *patch)1523{1524unsigned long offset, len;15251526 patch->is_toplevel_relative =0;1527 patch->is_rename = patch->is_copy =0;1528 patch->is_new = patch->is_delete = -1;1529 patch->old_mode = patch->new_mode =0;1530 patch->old_name = patch->new_name = NULL;1531for(offset =0; size >0; offset += len, size -= len, line += len, state->linenr++) {1532unsigned long nextlen;15331534 len =linelen(line, size);1535if(!len)1536break;15371538/* Testing this early allows us to take a few shortcuts.. */1539if(len <6)1540continue;15411542/*1543 * Make sure we don't find any unconnected patch fragments.1544 * That's a sign that we didn't find a header, and that a1545 * patch has become corrupted/broken up.1546 */1547if(!memcmp("@@ -", line,4)) {1548struct fragment dummy;1549if(parse_fragment_header(line, len, &dummy) <0)1550continue;1551error(_("patch fragment without header at line%d: %.*s"),1552 state->linenr, (int)len-1, line);1553return-128;1554}15551556if(size < len +6)1557break;15581559/*1560 * Git patch? It might not have a real patch, just a rename1561 * or mode change, so we handle that specially1562 */1563if(!memcmp("diff --git ", line,11)) {1564int git_hdr_len =parse_git_header(state, line, len, size, patch);1565if(git_hdr_len <0)1566return-128;1567if(git_hdr_len <= len)1568continue;1569if(!patch->old_name && !patch->new_name) {1570if(!patch->def_name) {1571error(Q_("git diff header lacks filename information when removing "1572"%dleading pathname component (line%d)",1573"git diff header lacks filename information when removing "1574"%dleading pathname components (line%d)",1575 state->p_value),1576 state->p_value, state->linenr);1577return-128;1578}1579 patch->old_name =xstrdup(patch->def_name);1580 patch->new_name =xstrdup(patch->def_name);1581}1582if((!patch->new_name && !patch->is_delete) ||1583(!patch->old_name && !patch->is_new)) {1584error(_("git diff header lacks filename information "1585"(line%d)"), state->linenr);1586return-128;1587}1588 patch->is_toplevel_relative =1;1589*hdrsize = git_hdr_len;1590return offset;1591}15921593/* --- followed by +++ ? */1594if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1595continue;15961597/*1598 * We only accept unified patches, so we want it to1599 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1600 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1601 */1602 nextlen =linelen(line + len, size - len);1603if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1604continue;16051606/* Ok, we'll consider it a patch */1607if(parse_traditional_patch(state, line, line+len, patch))1608return-128;1609*hdrsize = len + nextlen;1610 state->linenr +=2;1611return offset;1612}1613return-1;1614}16151616static voidrecord_ws_error(struct apply_state *state,1617unsigned result,1618const char*line,1619int len,1620int linenr)1621{1622char*err;16231624if(!result)1625return;16261627 state->whitespace_error++;1628if(state->squelch_whitespace_errors &&1629 state->squelch_whitespace_errors < state->whitespace_error)1630return;16311632 err =whitespace_error_string(result);1633if(state->apply_verbosity > verbosity_silent)1634fprintf(stderr,"%s:%d:%s.\n%.*s\n",1635 state->patch_input_file, linenr, err, len, line);1636free(err);1637}16381639static voidcheck_whitespace(struct apply_state *state,1640const char*line,1641int len,1642unsigned ws_rule)1643{1644unsigned result =ws_check(line +1, len -1, ws_rule);16451646record_ws_error(state, result, line +1, len -2, state->linenr);1647}16481649/*1650 * Check if the patch has context lines with CRLF or1651 * the patch wants to remove lines with CRLF.1652 */1653static voidcheck_old_for_crlf(struct patch *patch,const char*line,int len)1654{1655if(len >=2&& line[len-1] =='\n'&& line[len-2] =='\r') {1656 patch->ws_rule |= WS_CR_AT_EOL;1657 patch->crlf_in_old =1;1658}1659}166016611662/*1663 * Parse a unified diff. Note that this really needs to parse each1664 * fragment separately, since the only way to know the difference1665 * between a "---" that is part of a patch, and a "---" that starts1666 * the next patch is to look at the line counts..1667 */1668static intparse_fragment(struct apply_state *state,1669const char*line,1670unsigned long size,1671struct patch *patch,1672struct fragment *fragment)1673{1674int added, deleted;1675int len =linelen(line, size), offset;1676unsigned long oldlines, newlines;1677unsigned long leading, trailing;16781679 offset =parse_fragment_header(line, len, fragment);1680if(offset <0)1681return-1;1682if(offset >0&& patch->recount)1683recount_diff(line + offset, size - offset, fragment);1684 oldlines = fragment->oldlines;1685 newlines = fragment->newlines;1686 leading =0;1687 trailing =0;16881689/* Parse the thing.. */1690 line += len;1691 size -= len;1692 state->linenr++;1693 added = deleted =0;1694for(offset = len;16950< size;1696 offset += len, size -= len, line += len, state->linenr++) {1697if(!oldlines && !newlines)1698break;1699 len =linelen(line, size);1700if(!len || line[len-1] !='\n')1701return-1;1702switch(*line) {1703default:1704return-1;1705case'\n':/* newer GNU diff, an empty context line */1706case' ':1707 oldlines--;1708 newlines--;1709if(!deleted && !added)1710 leading++;1711 trailing++;1712check_old_for_crlf(patch, line, len);1713if(!state->apply_in_reverse &&1714 state->ws_error_action == correct_ws_error)1715check_whitespace(state, line, len, patch->ws_rule);1716break;1717case'-':1718if(!state->apply_in_reverse)1719check_old_for_crlf(patch, line, len);1720if(state->apply_in_reverse &&1721 state->ws_error_action != nowarn_ws_error)1722check_whitespace(state, line, len, patch->ws_rule);1723 deleted++;1724 oldlines--;1725 trailing =0;1726break;1727case'+':1728if(state->apply_in_reverse)1729check_old_for_crlf(patch, line, len);1730if(!state->apply_in_reverse &&1731 state->ws_error_action != nowarn_ws_error)1732check_whitespace(state, line, len, patch->ws_rule);1733 added++;1734 newlines--;1735 trailing =0;1736break;17371738/*1739 * We allow "\ No newline at end of file". Depending1740 * on locale settings when the patch was produced we1741 * don't know what this line looks like. The only1742 * thing we do know is that it begins with "\ ".1743 * Checking for 12 is just for sanity check -- any1744 * l10n of "\ No newline..." is at least that long.1745 */1746case'\\':1747if(len <12||memcmp(line,"\\",2))1748return-1;1749break;1750}1751}1752if(oldlines || newlines)1753return-1;1754if(!patch->recount && !deleted && !added)1755return-1;17561757 fragment->leading = leading;1758 fragment->trailing = trailing;17591760/*1761 * If a fragment ends with an incomplete line, we failed to include1762 * it in the above loop because we hit oldlines == newlines == 01763 * before seeing it.1764 */1765if(12< size && !memcmp(line,"\\",2))1766 offset +=linelen(line, size);17671768 patch->lines_added += added;1769 patch->lines_deleted += deleted;17701771if(0< patch->is_new && oldlines)1772returnerror(_("new file depends on old contents"));1773if(0< patch->is_delete && newlines)1774returnerror(_("deleted file still has contents"));1775return offset;1776}17771778/*1779 * We have seen "diff --git a/... b/..." header (or a traditional patch1780 * header). Read hunks that belong to this patch into fragments and hang1781 * them to the given patch structure.1782 *1783 * The (fragment->patch, fragment->size) pair points into the memory given1784 * by the caller, not a copy, when we return.1785 *1786 * Returns:1787 * -1 in case of error,1788 * the number of bytes in the patch otherwise.1789 */1790static intparse_single_patch(struct apply_state *state,1791const char*line,1792unsigned long size,1793struct patch *patch)1794{1795unsigned long offset =0;1796unsigned long oldlines =0, newlines =0, context =0;1797struct fragment **fragp = &patch->fragments;17981799while(size >4&& !memcmp(line,"@@ -",4)) {1800struct fragment *fragment;1801int len;18021803 fragment =xcalloc(1,sizeof(*fragment));1804 fragment->linenr = state->linenr;1805 len =parse_fragment(state, line, size, patch, fragment);1806if(len <=0) {1807free(fragment);1808returnerror(_("corrupt patch at line%d"), state->linenr);1809}1810 fragment->patch = line;1811 fragment->size = len;1812 oldlines += fragment->oldlines;1813 newlines += fragment->newlines;1814 context += fragment->leading + fragment->trailing;18151816*fragp = fragment;1817 fragp = &fragment->next;18181819 offset += len;1820 line += len;1821 size -= len;1822}18231824/*1825 * If something was removed (i.e. we have old-lines) it cannot1826 * be creation, and if something was added it cannot be1827 * deletion. However, the reverse is not true; --unified=01828 * patches that only add are not necessarily creation even1829 * though they do not have any old lines, and ones that only1830 * delete are not necessarily deletion.1831 *1832 * Unfortunately, a real creation/deletion patch do _not_ have1833 * any context line by definition, so we cannot safely tell it1834 * apart with --unified=0 insanity. At least if the patch has1835 * more than one hunk it is not creation or deletion.1836 */1837if(patch->is_new <0&&1838(oldlines || (patch->fragments && patch->fragments->next)))1839 patch->is_new =0;1840if(patch->is_delete <0&&1841(newlines || (patch->fragments && patch->fragments->next)))1842 patch->is_delete =0;18431844if(0< patch->is_new && oldlines)1845returnerror(_("new file%sdepends on old contents"), patch->new_name);1846if(0< patch->is_delete && newlines)1847returnerror(_("deleted file%sstill has contents"), patch->old_name);1848if(!patch->is_delete && !newlines && context && state->apply_verbosity > verbosity_silent)1849fprintf_ln(stderr,1850_("** warning: "1851"file%sbecomes empty but is not deleted"),1852 patch->new_name);18531854return offset;1855}18561857staticinlineintmetadata_changes(struct patch *patch)1858{1859return patch->is_rename >0||1860 patch->is_copy >0||1861 patch->is_new >0||1862 patch->is_delete ||1863(patch->old_mode && patch->new_mode &&1864 patch->old_mode != patch->new_mode);1865}18661867static char*inflate_it(const void*data,unsigned long size,1868unsigned long inflated_size)1869{1870 git_zstream stream;1871void*out;1872int st;18731874memset(&stream,0,sizeof(stream));18751876 stream.next_in = (unsigned char*)data;1877 stream.avail_in = size;1878 stream.next_out = out =xmalloc(inflated_size);1879 stream.avail_out = inflated_size;1880git_inflate_init(&stream);1881 st =git_inflate(&stream, Z_FINISH);1882git_inflate_end(&stream);1883if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1884free(out);1885return NULL;1886}1887return out;1888}18891890/*1891 * Read a binary hunk and return a new fragment; fragment->patch1892 * points at an allocated memory that the caller must free, so1893 * it is marked as "->free_patch = 1".1894 */1895static struct fragment *parse_binary_hunk(struct apply_state *state,1896char**buf_p,1897unsigned long*sz_p,1898int*status_p,1899int*used_p)1900{1901/*1902 * Expect a line that begins with binary patch method ("literal"1903 * or "delta"), followed by the length of data before deflating.1904 * a sequence of 'length-byte' followed by base-85 encoded data1905 * should follow, terminated by a newline.1906 *1907 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1908 * and we would limit the patch line to 66 characters,1909 * so one line can fit up to 13 groups that would decode1910 * to 52 bytes max. The length byte 'A'-'Z' corresponds1911 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1912 */1913int llen, used;1914unsigned long size = *sz_p;1915char*buffer = *buf_p;1916int patch_method;1917unsigned long origlen;1918char*data = NULL;1919int hunk_size =0;1920struct fragment *frag;19211922 llen =linelen(buffer, size);1923 used = llen;19241925*status_p =0;19261927if(starts_with(buffer,"delta ")) {1928 patch_method = BINARY_DELTA_DEFLATED;1929 origlen =strtoul(buffer +6, NULL,10);1930}1931else if(starts_with(buffer,"literal ")) {1932 patch_method = BINARY_LITERAL_DEFLATED;1933 origlen =strtoul(buffer +8, NULL,10);1934}1935else1936return NULL;19371938 state->linenr++;1939 buffer += llen;1940while(1) {1941int byte_length, max_byte_length, newsize;1942 llen =linelen(buffer, size);1943 used += llen;1944 state->linenr++;1945if(llen ==1) {1946/* consume the blank line */1947 buffer++;1948 size--;1949break;1950}1951/*1952 * Minimum line is "A00000\n" which is 7-byte long,1953 * and the line length must be multiple of 5 plus 2.1954 */1955if((llen <7) || (llen-2) %5)1956goto corrupt;1957 max_byte_length = (llen -2) /5*4;1958 byte_length = *buffer;1959if('A'<= byte_length && byte_length <='Z')1960 byte_length = byte_length -'A'+1;1961else if('a'<= byte_length && byte_length <='z')1962 byte_length = byte_length -'a'+27;1963else1964goto corrupt;1965/* if the input length was not multiple of 4, we would1966 * have filler at the end but the filler should never1967 * exceed 3 bytes1968 */1969if(max_byte_length < byte_length ||1970 byte_length <= max_byte_length -4)1971goto corrupt;1972 newsize = hunk_size + byte_length;1973 data =xrealloc(data, newsize);1974if(decode_85(data + hunk_size, buffer +1, byte_length))1975goto corrupt;1976 hunk_size = newsize;1977 buffer += llen;1978 size -= llen;1979}19801981 frag =xcalloc(1,sizeof(*frag));1982 frag->patch =inflate_it(data, hunk_size, origlen);1983 frag->free_patch =1;1984if(!frag->patch)1985goto corrupt;1986free(data);1987 frag->size = origlen;1988*buf_p = buffer;1989*sz_p = size;1990*used_p = used;1991 frag->binary_patch_method = patch_method;1992return frag;19931994 corrupt:1995free(data);1996*status_p = -1;1997error(_("corrupt binary patch at line%d: %.*s"),1998 state->linenr-1, llen-1, buffer);1999return NULL;2000}20012002/*2003 * Returns:2004 * -1 in case of error,2005 * the length of the parsed binary patch otherwise2006 */2007static intparse_binary(struct apply_state *state,2008char*buffer,2009unsigned long size,2010struct patch *patch)2011{2012/*2013 * We have read "GIT binary patch\n"; what follows is a line2014 * that says the patch method (currently, either "literal" or2015 * "delta") and the length of data before deflating; a2016 * sequence of 'length-byte' followed by base-85 encoded data2017 * follows.2018 *2019 * When a binary patch is reversible, there is another binary2020 * hunk in the same format, starting with patch method (either2021 * "literal" or "delta") with the length of data, and a sequence2022 * of length-byte + base-85 encoded data, terminated with another2023 * empty line. This data, when applied to the postimage, produces2024 * the preimage.2025 */2026struct fragment *forward;2027struct fragment *reverse;2028int status;2029int used, used_1;20302031 forward =parse_binary_hunk(state, &buffer, &size, &status, &used);2032if(!forward && !status)2033/* there has to be one hunk (forward hunk) */2034returnerror(_("unrecognized binary patch at line%d"), state->linenr-1);2035if(status)2036/* otherwise we already gave an error message */2037return status;20382039 reverse =parse_binary_hunk(state, &buffer, &size, &status, &used_1);2040if(reverse)2041 used += used_1;2042else if(status) {2043/*2044 * Not having reverse hunk is not an error, but having2045 * a corrupt reverse hunk is.2046 */2047free((void*) forward->patch);2048free(forward);2049return status;2050}2051 forward->next = reverse;2052 patch->fragments = forward;2053 patch->is_binary =1;2054return used;2055}20562057static voidprefix_one(struct apply_state *state,char**name)2058{2059char*old_name = *name;2060if(!old_name)2061return;2062*name =prefix_filename(state->prefix, *name);2063free(old_name);2064}20652066static voidprefix_patch(struct apply_state *state,struct patch *p)2067{2068if(!state->prefix || p->is_toplevel_relative)2069return;2070prefix_one(state, &p->new_name);2071prefix_one(state, &p->old_name);2072}20732074/*2075 * include/exclude2076 */20772078static voidadd_name_limit(struct apply_state *state,2079const char*name,2080int exclude)2081{2082struct string_list_item *it;20832084 it =string_list_append(&state->limit_by_name, name);2085 it->util = exclude ? NULL : (void*)1;2086}20872088static intuse_patch(struct apply_state *state,struct patch *p)2089{2090const char*pathname = p->new_name ? p->new_name : p->old_name;2091int i;20922093/* Paths outside are not touched regardless of "--include" */2094if(state->prefix && *state->prefix) {2095const char*rest;2096if(!skip_prefix(pathname, state->prefix, &rest) || !*rest)2097return0;2098}20992100/* See if it matches any of exclude/include rule */2101for(i =0; i < state->limit_by_name.nr; i++) {2102struct string_list_item *it = &state->limit_by_name.items[i];2103if(!wildmatch(it->string, pathname,0))2104return(it->util != NULL);2105}21062107/*2108 * If we had any include, a path that does not match any rule is2109 * not used. Otherwise, we saw bunch of exclude rules (or none)2110 * and such a path is used.2111 */2112return!state->has_include;2113}21142115/*2116 * Read the patch text in "buffer" that extends for "size" bytes; stop2117 * reading after seeing a single patch (i.e. changes to a single file).2118 * Create fragments (i.e. patch hunks) and hang them to the given patch.2119 *2120 * Returns:2121 * -1 if no header was found or parse_binary() failed,2122 * -128 on another error,2123 * the number of bytes consumed otherwise,2124 * so that the caller can call us again for the next patch.2125 */2126static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2127{2128int hdrsize, patchsize;2129int offset =find_header(state, buffer, size, &hdrsize, patch);21302131if(offset <0)2132return offset;21332134prefix_patch(state, patch);21352136if(!use_patch(state, patch))2137 patch->ws_rule =0;2138else if(patch->new_name)2139 patch->ws_rule =whitespace_rule(state->repo->index,2140 patch->new_name);2141else2142 patch->ws_rule =whitespace_rule(state->repo->index,2143 patch->old_name);21442145 patchsize =parse_single_patch(state,2146 buffer + offset + hdrsize,2147 size - offset - hdrsize,2148 patch);21492150if(patchsize <0)2151return-128;21522153if(!patchsize) {2154static const char git_binary[] ="GIT binary patch\n";2155int hd = hdrsize + offset;2156unsigned long llen =linelen(buffer + hd, size - hd);21572158if(llen ==sizeof(git_binary) -1&&2159!memcmp(git_binary, buffer + hd, llen)) {2160int used;2161 state->linenr++;2162 used =parse_binary(state, buffer + hd + llen,2163 size - hd - llen, patch);2164if(used <0)2165return-1;2166if(used)2167 patchsize = used + llen;2168else2169 patchsize =0;2170}2171else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2172static const char*binhdr[] = {2173"Binary files ",2174"Files ",2175 NULL,2176};2177int i;2178for(i =0; binhdr[i]; i++) {2179int len =strlen(binhdr[i]);2180if(len < size - hd &&2181!memcmp(binhdr[i], buffer + hd, len)) {2182 state->linenr++;2183 patch->is_binary =1;2184 patchsize = llen;2185break;2186}2187}2188}21892190/* Empty patch cannot be applied if it is a text patch2191 * without metadata change. A binary patch appears2192 * empty to us here.2193 */2194if((state->apply || state->check) &&2195(!patch->is_binary && !metadata_changes(patch))) {2196error(_("patch with only garbage at line%d"), state->linenr);2197return-128;2198}2199}22002201return offset + hdrsize + patchsize;2202}22032204static voidreverse_patches(struct patch *p)2205{2206for(; p; p = p->next) {2207struct fragment *frag = p->fragments;22082209SWAP(p->new_name, p->old_name);2210SWAP(p->new_mode, p->old_mode);2211SWAP(p->is_new, p->is_delete);2212SWAP(p->lines_added, p->lines_deleted);2213SWAP(p->old_oid_prefix, p->new_oid_prefix);22142215for(; frag; frag = frag->next) {2216SWAP(frag->newpos, frag->oldpos);2217SWAP(frag->newlines, frag->oldlines);2218}2219}2220}22212222static const char pluses[] =2223"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2224static const char minuses[]=2225"----------------------------------------------------------------------";22262227static voidshow_stats(struct apply_state *state,struct patch *patch)2228{2229struct strbuf qname = STRBUF_INIT;2230char*cp = patch->new_name ? patch->new_name : patch->old_name;2231int max, add, del;22322233quote_c_style(cp, &qname, NULL,0);22342235/*2236 * "scale" the filename2237 */2238 max = state->max_len;2239if(max >50)2240 max =50;22412242if(qname.len > max) {2243 cp =strchr(qname.buf + qname.len +3- max,'/');2244if(!cp)2245 cp = qname.buf + qname.len +3- max;2246strbuf_splice(&qname,0, cp - qname.buf,"...",3);2247}22482249if(patch->is_binary) {2250printf(" %-*s | Bin\n", max, qname.buf);2251strbuf_release(&qname);2252return;2253}22542255printf(" %-*s |", max, qname.buf);2256strbuf_release(&qname);22572258/*2259 * scale the add/delete2260 */2261 max = max + state->max_change >70?70- max : state->max_change;2262 add = patch->lines_added;2263 del = patch->lines_deleted;22642265if(state->max_change >0) {2266int total = ((add + del) * max + state->max_change /2) / state->max_change;2267 add = (add * max + state->max_change /2) / state->max_change;2268 del = total - add;2269}2270printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2271 add, pluses, del, minuses);2272}22732274static intread_old_data(struct stat *st,struct patch *patch,2275const char*path,struct strbuf *buf)2276{2277int conv_flags = patch->crlf_in_old ?2278 CONV_EOL_KEEP_CRLF : CONV_EOL_RENORMALIZE;2279switch(st->st_mode & S_IFMT) {2280case S_IFLNK:2281if(strbuf_readlink(buf, path, st->st_size) <0)2282returnerror(_("unable to read symlink%s"), path);2283return0;2284case S_IFREG:2285if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2286returnerror(_("unable to open or read%s"), path);2287/*2288 * "git apply" without "--index/--cached" should never look2289 * at the index; the target file may not have been added to2290 * the index yet, and we may not even be in any Git repository.2291 * Pass NULL to convert_to_git() to stress this; the function2292 * should never look at the index when explicit crlf option2293 * is given.2294 */2295convert_to_git(NULL, path, buf->buf, buf->len, buf, conv_flags);2296return0;2297default:2298return-1;2299}2300}23012302/*2303 * Update the preimage, and the common lines in postimage,2304 * from buffer buf of length len. If postlen is 0 the postimage2305 * is updated in place, otherwise it's updated on a new buffer2306 * of length postlen2307 */23082309static voidupdate_pre_post_images(struct image *preimage,2310struct image *postimage,2311char*buf,2312size_t len,size_t postlen)2313{2314int i, ctx, reduced;2315char*new_buf, *old_buf, *fixed;2316struct image fixed_preimage;23172318/*2319 * Update the preimage with whitespace fixes. Note that we2320 * are not losing preimage->buf -- apply_one_fragment() will2321 * free "oldlines".2322 */2323prepare_image(&fixed_preimage, buf, len,1);2324assert(postlen2325? fixed_preimage.nr == preimage->nr2326: fixed_preimage.nr <= preimage->nr);2327for(i =0; i < fixed_preimage.nr; i++)2328 fixed_preimage.line[i].flag = preimage->line[i].flag;2329free(preimage->line_allocated);2330*preimage = fixed_preimage;23312332/*2333 * Adjust the common context lines in postimage. This can be2334 * done in-place when we are shrinking it with whitespace2335 * fixing, but needs a new buffer when ignoring whitespace or2336 * expanding leading tabs to spaces.2337 *2338 * We trust the caller to tell us if the update can be done2339 * in place (postlen==0) or not.2340 */2341 old_buf = postimage->buf;2342if(postlen)2343 new_buf = postimage->buf =xmalloc(postlen);2344else2345 new_buf = old_buf;2346 fixed = preimage->buf;23472348for(i = reduced = ctx =0; i < postimage->nr; i++) {2349size_t l_len = postimage->line[i].len;2350if(!(postimage->line[i].flag & LINE_COMMON)) {2351/* an added line -- no counterparts in preimage */2352memmove(new_buf, old_buf, l_len);2353 old_buf += l_len;2354 new_buf += l_len;2355continue;2356}23572358/* a common context -- skip it in the original postimage */2359 old_buf += l_len;23602361/* and find the corresponding one in the fixed preimage */2362while(ctx < preimage->nr &&2363!(preimage->line[ctx].flag & LINE_COMMON)) {2364 fixed += preimage->line[ctx].len;2365 ctx++;2366}23672368/*2369 * preimage is expected to run out, if the caller2370 * fixed addition of trailing blank lines.2371 */2372if(preimage->nr <= ctx) {2373 reduced++;2374continue;2375}23762377/* and copy it in, while fixing the line length */2378 l_len = preimage->line[ctx].len;2379memcpy(new_buf, fixed, l_len);2380 new_buf += l_len;2381 fixed += l_len;2382 postimage->line[i].len = l_len;2383 ctx++;2384}23852386if(postlen2387? postlen < new_buf - postimage->buf2388: postimage->len < new_buf - postimage->buf)2389BUG("caller miscounted postlen: asked%d, orig =%d, used =%d",2390(int)postlen, (int) postimage->len, (int)(new_buf - postimage->buf));23912392/* Fix the length of the whole thing */2393 postimage->len = new_buf - postimage->buf;2394 postimage->nr -= reduced;2395}23962397static intline_by_line_fuzzy_match(struct image *img,2398struct image *preimage,2399struct image *postimage,2400unsigned long current,2401int current_lno,2402int preimage_limit)2403{2404int i;2405size_t imgoff =0;2406size_t preoff =0;2407size_t postlen = postimage->len;2408size_t extra_chars;2409char*buf;2410char*preimage_eof;2411char*preimage_end;2412struct strbuf fixed;2413char*fixed_buf;2414size_t fixed_len;24152416for(i =0; i < preimage_limit; i++) {2417size_t prelen = preimage->line[i].len;2418size_t imglen = img->line[current_lno+i].len;24192420if(!fuzzy_matchlines(img->buf + current + imgoff, imglen,2421 preimage->buf + preoff, prelen))2422return0;2423if(preimage->line[i].flag & LINE_COMMON)2424 postlen += imglen - prelen;2425 imgoff += imglen;2426 preoff += prelen;2427}24282429/*2430 * Ok, the preimage matches with whitespace fuzz.2431 *2432 * imgoff now holds the true length of the target that2433 * matches the preimage before the end of the file.2434 *2435 * Count the number of characters in the preimage that fall2436 * beyond the end of the file and make sure that all of them2437 * are whitespace characters. (This can only happen if2438 * we are removing blank lines at the end of the file.)2439 */2440 buf = preimage_eof = preimage->buf + preoff;2441for( ; i < preimage->nr; i++)2442 preoff += preimage->line[i].len;2443 preimage_end = preimage->buf + preoff;2444for( ; buf < preimage_end; buf++)2445if(!isspace(*buf))2446return0;24472448/*2449 * Update the preimage and the common postimage context2450 * lines to use the same whitespace as the target.2451 * If whitespace is missing in the target (i.e.2452 * if the preimage extends beyond the end of the file),2453 * use the whitespace from the preimage.2454 */2455 extra_chars = preimage_end - preimage_eof;2456strbuf_init(&fixed, imgoff + extra_chars);2457strbuf_add(&fixed, img->buf + current, imgoff);2458strbuf_add(&fixed, preimage_eof, extra_chars);2459 fixed_buf =strbuf_detach(&fixed, &fixed_len);2460update_pre_post_images(preimage, postimage,2461 fixed_buf, fixed_len, postlen);2462return1;2463}24642465static intmatch_fragment(struct apply_state *state,2466struct image *img,2467struct image *preimage,2468struct image *postimage,2469unsigned long current,2470int current_lno,2471unsigned ws_rule,2472int match_beginning,int match_end)2473{2474int i;2475char*fixed_buf, *buf, *orig, *target;2476struct strbuf fixed;2477size_t fixed_len, postlen;2478int preimage_limit;24792480if(preimage->nr + current_lno <= img->nr) {2481/*2482 * The hunk falls within the boundaries of img.2483 */2484 preimage_limit = preimage->nr;2485if(match_end && (preimage->nr + current_lno != img->nr))2486return0;2487}else if(state->ws_error_action == correct_ws_error &&2488(ws_rule & WS_BLANK_AT_EOF)) {2489/*2490 * This hunk extends beyond the end of img, and we are2491 * removing blank lines at the end of the file. This2492 * many lines from the beginning of the preimage must2493 * match with img, and the remainder of the preimage2494 * must be blank.2495 */2496 preimage_limit = img->nr - current_lno;2497}else{2498/*2499 * The hunk extends beyond the end of the img and2500 * we are not removing blanks at the end, so we2501 * should reject the hunk at this position.2502 */2503return0;2504}25052506if(match_beginning && current_lno)2507return0;25082509/* Quick hash check */2510for(i =0; i < preimage_limit; i++)2511if((img->line[current_lno + i].flag & LINE_PATCHED) ||2512(preimage->line[i].hash != img->line[current_lno + i].hash))2513return0;25142515if(preimage_limit == preimage->nr) {2516/*2517 * Do we have an exact match? If we were told to match2518 * at the end, size must be exactly at current+fragsize,2519 * otherwise current+fragsize must be still within the preimage,2520 * and either case, the old piece should match the preimage2521 * exactly.2522 */2523if((match_end2524? (current + preimage->len == img->len)2525: (current + preimage->len <= img->len)) &&2526!memcmp(img->buf + current, preimage->buf, preimage->len))2527return1;2528}else{2529/*2530 * The preimage extends beyond the end of img, so2531 * there cannot be an exact match.2532 *2533 * There must be one non-blank context line that match2534 * a line before the end of img.2535 */2536char*buf_end;25372538 buf = preimage->buf;2539 buf_end = buf;2540for(i =0; i < preimage_limit; i++)2541 buf_end += preimage->line[i].len;25422543for( ; buf < buf_end; buf++)2544if(!isspace(*buf))2545break;2546if(buf == buf_end)2547return0;2548}25492550/*2551 * No exact match. If we are ignoring whitespace, run a line-by-line2552 * fuzzy matching. We collect all the line length information because2553 * we need it to adjust whitespace if we match.2554 */2555if(state->ws_ignore_action == ignore_ws_change)2556returnline_by_line_fuzzy_match(img, preimage, postimage,2557 current, current_lno, preimage_limit);25582559if(state->ws_error_action != correct_ws_error)2560return0;25612562/*2563 * The hunk does not apply byte-by-byte, but the hash says2564 * it might with whitespace fuzz. We weren't asked to2565 * ignore whitespace, we were asked to correct whitespace2566 * errors, so let's try matching after whitespace correction.2567 *2568 * While checking the preimage against the target, whitespace2569 * errors in both fixed, we count how large the corresponding2570 * postimage needs to be. The postimage prepared by2571 * apply_one_fragment() has whitespace errors fixed on added2572 * lines already, but the common lines were propagated as-is,2573 * which may become longer when their whitespace errors are2574 * fixed.2575 */25762577/* First count added lines in postimage */2578 postlen =0;2579for(i =0; i < postimage->nr; i++) {2580if(!(postimage->line[i].flag & LINE_COMMON))2581 postlen += postimage->line[i].len;2582}25832584/*2585 * The preimage may extend beyond the end of the file,2586 * but in this loop we will only handle the part of the2587 * preimage that falls within the file.2588 */2589strbuf_init(&fixed, preimage->len +1);2590 orig = preimage->buf;2591 target = img->buf + current;2592for(i =0; i < preimage_limit; i++) {2593size_t oldlen = preimage->line[i].len;2594size_t tgtlen = img->line[current_lno + i].len;2595size_t fixstart = fixed.len;2596struct strbuf tgtfix;2597int match;25982599/* Try fixing the line in the preimage */2600ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);26012602/* Try fixing the line in the target */2603strbuf_init(&tgtfix, tgtlen);2604ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);26052606/*2607 * If they match, either the preimage was based on2608 * a version before our tree fixed whitespace breakage,2609 * or we are lacking a whitespace-fix patch the tree2610 * the preimage was based on already had (i.e. target2611 * has whitespace breakage, the preimage doesn't).2612 * In either case, we are fixing the whitespace breakages2613 * so we might as well take the fix together with their2614 * real change.2615 */2616 match = (tgtfix.len == fixed.len - fixstart &&2617!memcmp(tgtfix.buf, fixed.buf + fixstart,2618 fixed.len - fixstart));26192620/* Add the length if this is common with the postimage */2621if(preimage->line[i].flag & LINE_COMMON)2622 postlen += tgtfix.len;26232624strbuf_release(&tgtfix);2625if(!match)2626goto unmatch_exit;26272628 orig += oldlen;2629 target += tgtlen;2630}263126322633/*2634 * Now handle the lines in the preimage that falls beyond the2635 * end of the file (if any). They will only match if they are2636 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2637 * false).2638 */2639for( ; i < preimage->nr; i++) {2640size_t fixstart = fixed.len;/* start of the fixed preimage */2641size_t oldlen = preimage->line[i].len;2642int j;26432644/* Try fixing the line in the preimage */2645ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);26462647for(j = fixstart; j < fixed.len; j++)2648if(!isspace(fixed.buf[j]))2649goto unmatch_exit;26502651 orig += oldlen;2652}26532654/*2655 * Yes, the preimage is based on an older version that still2656 * has whitespace breakages unfixed, and fixing them makes the2657 * hunk match. Update the context lines in the postimage.2658 */2659 fixed_buf =strbuf_detach(&fixed, &fixed_len);2660if(postlen < postimage->len)2661 postlen =0;2662update_pre_post_images(preimage, postimage,2663 fixed_buf, fixed_len, postlen);2664return1;26652666 unmatch_exit:2667strbuf_release(&fixed);2668return0;2669}26702671static intfind_pos(struct apply_state *state,2672struct image *img,2673struct image *preimage,2674struct image *postimage,2675int line,2676unsigned ws_rule,2677int match_beginning,int match_end)2678{2679int i;2680unsigned long backwards, forwards, current;2681int backwards_lno, forwards_lno, current_lno;26822683/*2684 * If match_beginning or match_end is specified, there is no2685 * point starting from a wrong line that will never match and2686 * wander around and wait for a match at the specified end.2687 */2688if(match_beginning)2689 line =0;2690else if(match_end)2691 line = img->nr - preimage->nr;26922693/*2694 * Because the comparison is unsigned, the following test2695 * will also take care of a negative line number that can2696 * result when match_end and preimage is larger than the target.2697 */2698if((size_t) line > img->nr)2699 line = img->nr;27002701 current =0;2702for(i =0; i < line; i++)2703 current += img->line[i].len;27042705/*2706 * There's probably some smart way to do this, but I'll leave2707 * that to the smart and beautiful people. I'm simple and stupid.2708 */2709 backwards = current;2710 backwards_lno = line;2711 forwards = current;2712 forwards_lno = line;2713 current_lno = line;27142715for(i =0; ; i++) {2716if(match_fragment(state, img, preimage, postimage,2717 current, current_lno, ws_rule,2718 match_beginning, match_end))2719return current_lno;27202721 again:2722if(backwards_lno ==0&& forwards_lno == img->nr)2723break;27242725if(i &1) {2726if(backwards_lno ==0) {2727 i++;2728goto again;2729}2730 backwards_lno--;2731 backwards -= img->line[backwards_lno].len;2732 current = backwards;2733 current_lno = backwards_lno;2734}else{2735if(forwards_lno == img->nr) {2736 i++;2737goto again;2738}2739 forwards += img->line[forwards_lno].len;2740 forwards_lno++;2741 current = forwards;2742 current_lno = forwards_lno;2743}27442745}2746return-1;2747}27482749static voidremove_first_line(struct image *img)2750{2751 img->buf += img->line[0].len;2752 img->len -= img->line[0].len;2753 img->line++;2754 img->nr--;2755}27562757static voidremove_last_line(struct image *img)2758{2759 img->len -= img->line[--img->nr].len;2760}27612762/*2763 * The change from "preimage" and "postimage" has been found to2764 * apply at applied_pos (counts in line numbers) in "img".2765 * Update "img" to remove "preimage" and replace it with "postimage".2766 */2767static voidupdate_image(struct apply_state *state,2768struct image *img,2769int applied_pos,2770struct image *preimage,2771struct image *postimage)2772{2773/*2774 * remove the copy of preimage at offset in img2775 * and replace it with postimage2776 */2777int i, nr;2778size_t remove_count, insert_count, applied_at =0;2779char*result;2780int preimage_limit;27812782/*2783 * If we are removing blank lines at the end of img,2784 * the preimage may extend beyond the end.2785 * If that is the case, we must be careful only to2786 * remove the part of the preimage that falls within2787 * the boundaries of img. Initialize preimage_limit2788 * to the number of lines in the preimage that falls2789 * within the boundaries.2790 */2791 preimage_limit = preimage->nr;2792if(preimage_limit > img->nr - applied_pos)2793 preimage_limit = img->nr - applied_pos;27942795for(i =0; i < applied_pos; i++)2796 applied_at += img->line[i].len;27972798 remove_count =0;2799for(i =0; i < preimage_limit; i++)2800 remove_count += img->line[applied_pos + i].len;2801 insert_count = postimage->len;28022803/* Adjust the contents */2804 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2805memcpy(result, img->buf, applied_at);2806memcpy(result + applied_at, postimage->buf, postimage->len);2807memcpy(result + applied_at + postimage->len,2808 img->buf + (applied_at + remove_count),2809 img->len - (applied_at + remove_count));2810free(img->buf);2811 img->buf = result;2812 img->len += insert_count - remove_count;2813 result[img->len] ='\0';28142815/* Adjust the line table */2816 nr = img->nr + postimage->nr - preimage_limit;2817if(preimage_limit < postimage->nr) {2818/*2819 * NOTE: this knows that we never call remove_first_line()2820 * on anything other than pre/post image.2821 */2822REALLOC_ARRAY(img->line, nr);2823 img->line_allocated = img->line;2824}2825if(preimage_limit != postimage->nr)2826MOVE_ARRAY(img->line + applied_pos + postimage->nr,2827 img->line + applied_pos + preimage_limit,2828 img->nr - (applied_pos + preimage_limit));2829COPY_ARRAY(img->line + applied_pos, postimage->line, postimage->nr);2830if(!state->allow_overlap)2831for(i =0; i < postimage->nr; i++)2832 img->line[applied_pos + i].flag |= LINE_PATCHED;2833 img->nr = nr;2834}28352836/*2837 * Use the patch-hunk text in "frag" to prepare two images (preimage and2838 * postimage) for the hunk. Find lines that match "preimage" in "img" and2839 * replace the part of "img" with "postimage" text.2840 */2841static intapply_one_fragment(struct apply_state *state,2842struct image *img,struct fragment *frag,2843int inaccurate_eof,unsigned ws_rule,2844int nth_fragment)2845{2846int match_beginning, match_end;2847const char*patch = frag->patch;2848int size = frag->size;2849char*old, *oldlines;2850struct strbuf newlines;2851int new_blank_lines_at_end =0;2852int found_new_blank_lines_at_end =0;2853int hunk_linenr = frag->linenr;2854unsigned long leading, trailing;2855int pos, applied_pos;2856struct image preimage;2857struct image postimage;28582859memset(&preimage,0,sizeof(preimage));2860memset(&postimage,0,sizeof(postimage));2861 oldlines =xmalloc(size);2862strbuf_init(&newlines, size);28632864 old = oldlines;2865while(size >0) {2866char first;2867int len =linelen(patch, size);2868int plen;2869int added_blank_line =0;2870int is_blank_context =0;2871size_t start;28722873if(!len)2874break;28752876/*2877 * "plen" is how much of the line we should use for2878 * the actual patch data. Normally we just remove the2879 * first character on the line, but if the line is2880 * followed by "\ No newline", then we also remove the2881 * last one (which is the newline, of course).2882 */2883 plen = len -1;2884if(len < size && patch[len] =='\\')2885 plen--;2886 first = *patch;2887if(state->apply_in_reverse) {2888if(first =='-')2889 first ='+';2890else if(first =='+')2891 first ='-';2892}28932894switch(first) {2895case'\n':2896/* Newer GNU diff, empty context line */2897if(plen <0)2898/* ... followed by '\No newline'; nothing */2899break;2900*old++ ='\n';2901strbuf_addch(&newlines,'\n');2902add_line_info(&preimage,"\n",1, LINE_COMMON);2903add_line_info(&postimage,"\n",1, LINE_COMMON);2904 is_blank_context =1;2905break;2906case' ':2907if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2908ws_blank_line(patch +1, plen, ws_rule))2909 is_blank_context =1;2910/* fallthrough */2911case'-':2912memcpy(old, patch +1, plen);2913add_line_info(&preimage, old, plen,2914(first ==' '? LINE_COMMON :0));2915 old += plen;2916if(first =='-')2917break;2918/* fallthrough */2919case'+':2920/* --no-add does not add new lines */2921if(first =='+'&& state->no_add)2922break;29232924 start = newlines.len;2925if(first !='+'||2926!state->whitespace_error ||2927 state->ws_error_action != correct_ws_error) {2928strbuf_add(&newlines, patch +1, plen);2929}2930else{2931ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2932}2933add_line_info(&postimage, newlines.buf + start, newlines.len - start,2934(first =='+'?0: LINE_COMMON));2935if(first =='+'&&2936(ws_rule & WS_BLANK_AT_EOF) &&2937ws_blank_line(patch +1, plen, ws_rule))2938 added_blank_line =1;2939break;2940case'@':case'\\':2941/* Ignore it, we already handled it */2942break;2943default:2944if(state->apply_verbosity > verbosity_normal)2945error(_("invalid start of line: '%c'"), first);2946 applied_pos = -1;2947goto out;2948}2949if(added_blank_line) {2950if(!new_blank_lines_at_end)2951 found_new_blank_lines_at_end = hunk_linenr;2952 new_blank_lines_at_end++;2953}2954else if(is_blank_context)2955;2956else2957 new_blank_lines_at_end =0;2958 patch += len;2959 size -= len;2960 hunk_linenr++;2961}2962if(inaccurate_eof &&2963 old > oldlines && old[-1] =='\n'&&2964 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2965 old--;2966strbuf_setlen(&newlines, newlines.len -1);2967 preimage.line_allocated[preimage.nr -1].len--;2968 postimage.line_allocated[postimage.nr -1].len--;2969}29702971 leading = frag->leading;2972 trailing = frag->trailing;29732974/*2975 * A hunk to change lines at the beginning would begin with2976 * @@ -1,L +N,M @@2977 * but we need to be careful. -U0 that inserts before the second2978 * line also has this pattern.2979 *2980 * And a hunk to add to an empty file would begin with2981 * @@ -0,0 +N,M @@2982 *2983 * In other words, a hunk that is (frag->oldpos <= 1) with or2984 * without leading context must match at the beginning.2985 */2986 match_beginning = (!frag->oldpos ||2987(frag->oldpos ==1&& !state->unidiff_zero));29882989/*2990 * A hunk without trailing lines must match at the end.2991 * However, we simply cannot tell if a hunk must match end2992 * from the lack of trailing lines if the patch was generated2993 * with unidiff without any context.2994 */2995 match_end = !state->unidiff_zero && !trailing;29962997 pos = frag->newpos ? (frag->newpos -1) :0;2998 preimage.buf = oldlines;2999 preimage.len = old - oldlines;3000 postimage.buf = newlines.buf;3001 postimage.len = newlines.len;3002 preimage.line = preimage.line_allocated;3003 postimage.line = postimage.line_allocated;30043005for(;;) {30063007 applied_pos =find_pos(state, img, &preimage, &postimage, pos,3008 ws_rule, match_beginning, match_end);30093010if(applied_pos >=0)3011break;30123013/* Am I at my context limits? */3014if((leading <= state->p_context) && (trailing <= state->p_context))3015break;3016if(match_beginning || match_end) {3017 match_beginning = match_end =0;3018continue;3019}30203021/*3022 * Reduce the number of context lines; reduce both3023 * leading and trailing if they are equal otherwise3024 * just reduce the larger context.3025 */3026if(leading >= trailing) {3027remove_first_line(&preimage);3028remove_first_line(&postimage);3029 pos--;3030 leading--;3031}3032if(trailing > leading) {3033remove_last_line(&preimage);3034remove_last_line(&postimage);3035 trailing--;3036}3037}30383039if(applied_pos >=0) {3040if(new_blank_lines_at_end &&3041 preimage.nr + applied_pos >= img->nr &&3042(ws_rule & WS_BLANK_AT_EOF) &&3043 state->ws_error_action != nowarn_ws_error) {3044record_ws_error(state, WS_BLANK_AT_EOF,"+",1,3045 found_new_blank_lines_at_end);3046if(state->ws_error_action == correct_ws_error) {3047while(new_blank_lines_at_end--)3048remove_last_line(&postimage);3049}3050/*3051 * We would want to prevent write_out_results()3052 * from taking place in apply_patch() that follows3053 * the callchain led us here, which is:3054 * apply_patch->check_patch_list->check_patch->3055 * apply_data->apply_fragments->apply_one_fragment3056 */3057if(state->ws_error_action == die_on_ws_error)3058 state->apply =0;3059}30603061if(state->apply_verbosity > verbosity_normal && applied_pos != pos) {3062int offset = applied_pos - pos;3063if(state->apply_in_reverse)3064 offset =0- offset;3065fprintf_ln(stderr,3066Q_("Hunk #%dsucceeded at%d(offset%dline).",3067"Hunk #%dsucceeded at%d(offset%dlines).",3068 offset),3069 nth_fragment, applied_pos +1, offset);3070}30713072/*3073 * Warn if it was necessary to reduce the number3074 * of context lines.3075 */3076if((leading != frag->leading ||3077 trailing != frag->trailing) && state->apply_verbosity > verbosity_silent)3078fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"3079" to apply fragment at%d"),3080 leading, trailing, applied_pos+1);3081update_image(state, img, applied_pos, &preimage, &postimage);3082}else{3083if(state->apply_verbosity > verbosity_normal)3084error(_("while searching for:\n%.*s"),3085(int)(old - oldlines), oldlines);3086}30873088out:3089free(oldlines);3090strbuf_release(&newlines);3091free(preimage.line_allocated);3092free(postimage.line_allocated);30933094return(applied_pos <0);3095}30963097static intapply_binary_fragment(struct apply_state *state,3098struct image *img,3099struct patch *patch)3100{3101struct fragment *fragment = patch->fragments;3102unsigned long len;3103void*dst;31043105if(!fragment)3106returnerror(_("missing binary patch data for '%s'"),3107 patch->new_name ?3108 patch->new_name :3109 patch->old_name);31103111/* Binary patch is irreversible without the optional second hunk */3112if(state->apply_in_reverse) {3113if(!fragment->next)3114returnerror(_("cannot reverse-apply a binary patch "3115"without the reverse hunk to '%s'"),3116 patch->new_name3117? patch->new_name : patch->old_name);3118 fragment = fragment->next;3119}3120switch(fragment->binary_patch_method) {3121case BINARY_DELTA_DEFLATED:3122 dst =patch_delta(img->buf, img->len, fragment->patch,3123 fragment->size, &len);3124if(!dst)3125return-1;3126clear_image(img);3127 img->buf = dst;3128 img->len = len;3129return0;3130case BINARY_LITERAL_DEFLATED:3131clear_image(img);3132 img->len = fragment->size;3133 img->buf =xmemdupz(fragment->patch, img->len);3134return0;3135}3136return-1;3137}31383139/*3140 * Replace "img" with the result of applying the binary patch.3141 * The binary patch data itself in patch->fragment is still kept3142 * but the preimage prepared by the caller in "img" is freed here3143 * or in the helper function apply_binary_fragment() this calls.3144 */3145static intapply_binary(struct apply_state *state,3146struct image *img,3147struct patch *patch)3148{3149const char*name = patch->old_name ? patch->old_name : patch->new_name;3150struct object_id oid;3151const unsigned hexsz = the_hash_algo->hexsz;31523153/*3154 * For safety, we require patch index line to contain3155 * full hex textual object ID for old and new, at least for now.3156 */3157if(strlen(patch->old_oid_prefix) != hexsz ||3158strlen(patch->new_oid_prefix) != hexsz ||3159get_oid_hex(patch->old_oid_prefix, &oid) ||3160get_oid_hex(patch->new_oid_prefix, &oid))3161returnerror(_("cannot apply binary patch to '%s' "3162"without full index line"), name);31633164if(patch->old_name) {3165/*3166 * See if the old one matches what the patch3167 * applies to.3168 */3169hash_object_file(img->buf, img->len, blob_type, &oid);3170if(strcmp(oid_to_hex(&oid), patch->old_oid_prefix))3171returnerror(_("the patch applies to '%s' (%s), "3172"which does not match the "3173"current contents."),3174 name,oid_to_hex(&oid));3175}3176else{3177/* Otherwise, the old one must be empty. */3178if(img->len)3179returnerror(_("the patch applies to an empty "3180"'%s' but it is not empty"), name);3181}31823183get_oid_hex(patch->new_oid_prefix, &oid);3184if(is_null_oid(&oid)) {3185clear_image(img);3186return0;/* deletion patch */3187}31883189if(has_object_file(&oid)) {3190/* We already have the postimage */3191enum object_type type;3192unsigned long size;3193char*result;31943195 result =read_object_file(&oid, &type, &size);3196if(!result)3197returnerror(_("the necessary postimage%sfor "3198"'%s' cannot be read"),3199 patch->new_oid_prefix, name);3200clear_image(img);3201 img->buf = result;3202 img->len = size;3203}else{3204/*3205 * We have verified buf matches the preimage;3206 * apply the patch data to it, which is stored3207 * in the patch->fragments->{patch,size}.3208 */3209if(apply_binary_fragment(state, img, patch))3210returnerror(_("binary patch does not apply to '%s'"),3211 name);32123213/* verify that the result matches */3214hash_object_file(img->buf, img->len, blob_type, &oid);3215if(strcmp(oid_to_hex(&oid), patch->new_oid_prefix))3216returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3217 name, patch->new_oid_prefix,oid_to_hex(&oid));3218}32193220return0;3221}32223223static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3224{3225struct fragment *frag = patch->fragments;3226const char*name = patch->old_name ? patch->old_name : patch->new_name;3227unsigned ws_rule = patch->ws_rule;3228unsigned inaccurate_eof = patch->inaccurate_eof;3229int nth =0;32303231if(patch->is_binary)3232returnapply_binary(state, img, patch);32333234while(frag) {3235 nth++;3236if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3237error(_("patch failed:%s:%ld"), name, frag->oldpos);3238if(!state->apply_with_reject)3239return-1;3240 frag->rejected =1;3241}3242 frag = frag->next;3243}3244return0;3245}32463247static intread_blob_object(struct strbuf *buf,const struct object_id *oid,unsigned mode)3248{3249if(S_ISGITLINK(mode)) {3250strbuf_grow(buf,100);3251strbuf_addf(buf,"Subproject commit%s\n",oid_to_hex(oid));3252}else{3253enum object_type type;3254unsigned long sz;3255char*result;32563257 result =read_object_file(oid, &type, &sz);3258if(!result)3259return-1;3260/* XXX read_sha1_file NUL-terminates */3261strbuf_attach(buf, result, sz, sz +1);3262}3263return0;3264}32653266static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3267{3268if(!ce)3269return0;3270returnread_blob_object(buf, &ce->oid, ce->ce_mode);3271}32723273static struct patch *in_fn_table(struct apply_state *state,const char*name)3274{3275struct string_list_item *item;32763277if(name == NULL)3278return NULL;32793280 item =string_list_lookup(&state->fn_table, name);3281if(item != NULL)3282return(struct patch *)item->util;32833284return NULL;3285}32863287/*3288 * item->util in the filename table records the status of the path.3289 * Usually it points at a patch (whose result records the contents3290 * of it after applying it), but it could be PATH_WAS_DELETED for a3291 * path that a previously applied patch has already removed, or3292 * PATH_TO_BE_DELETED for a path that a later patch would remove.3293 *3294 * The latter is needed to deal with a case where two paths A and B3295 * are swapped by first renaming A to B and then renaming B to A;3296 * moving A to B should not be prevented due to presence of B as we3297 * will remove it in a later patch.3298 */3299#define PATH_TO_BE_DELETED ((struct patch *) -2)3300#define PATH_WAS_DELETED ((struct patch *) -1)33013302static intto_be_deleted(struct patch *patch)3303{3304return patch == PATH_TO_BE_DELETED;3305}33063307static intwas_deleted(struct patch *patch)3308{3309return patch == PATH_WAS_DELETED;3310}33113312static voidadd_to_fn_table(struct apply_state *state,struct patch *patch)3313{3314struct string_list_item *item;33153316/*3317 * Always add new_name unless patch is a deletion3318 * This should cover the cases for normal diffs,3319 * file creations and copies3320 */3321if(patch->new_name != NULL) {3322 item =string_list_insert(&state->fn_table, patch->new_name);3323 item->util = patch;3324}33253326/*3327 * store a failure on rename/deletion cases because3328 * later chunks shouldn't patch old names3329 */3330if((patch->new_name == NULL) || (patch->is_rename)) {3331 item =string_list_insert(&state->fn_table, patch->old_name);3332 item->util = PATH_WAS_DELETED;3333}3334}33353336static voidprepare_fn_table(struct apply_state *state,struct patch *patch)3337{3338/*3339 * store information about incoming file deletion3340 */3341while(patch) {3342if((patch->new_name == NULL) || (patch->is_rename)) {3343struct string_list_item *item;3344 item =string_list_insert(&state->fn_table, patch->old_name);3345 item->util = PATH_TO_BE_DELETED;3346}3347 patch = patch->next;3348}3349}33503351static intcheckout_target(struct index_state *istate,3352struct cache_entry *ce,struct stat *st)3353{3354struct checkout costate = CHECKOUT_INIT;33553356 costate.refresh_cache =1;3357 costate.istate = istate;3358if(checkout_entry(ce, &costate, NULL, NULL) ||3359lstat(ce->name, st))3360returnerror(_("cannot checkout%s"), ce->name);3361return0;3362}33633364static struct patch *previous_patch(struct apply_state *state,3365struct patch *patch,3366int*gone)3367{3368struct patch *previous;33693370*gone =0;3371if(patch->is_copy || patch->is_rename)3372return NULL;/* "git" patches do not depend on the order */33733374 previous =in_fn_table(state, patch->old_name);3375if(!previous)3376return NULL;33773378if(to_be_deleted(previous))3379return NULL;/* the deletion hasn't happened yet */33803381if(was_deleted(previous))3382*gone =1;33833384return previous;3385}33863387static intverify_index_match(struct apply_state *state,3388const struct cache_entry *ce,3389struct stat *st)3390{3391if(S_ISGITLINK(ce->ce_mode)) {3392if(!S_ISDIR(st->st_mode))3393return-1;3394return0;3395}3396returnie_match_stat(state->repo->index, ce, st,3397 CE_MATCH_IGNORE_VALID | CE_MATCH_IGNORE_SKIP_WORKTREE);3398}33993400#define SUBMODULE_PATCH_WITHOUT_INDEX 134013402static intload_patch_target(struct apply_state *state,3403struct strbuf *buf,3404const struct cache_entry *ce,3405struct stat *st,3406struct patch *patch,3407const char*name,3408unsigned expected_mode)3409{3410if(state->cached || state->check_index) {3411if(read_file_or_gitlink(ce, buf))3412returnerror(_("failed to read%s"), name);3413}else if(name) {3414if(S_ISGITLINK(expected_mode)) {3415if(ce)3416returnread_file_or_gitlink(ce, buf);3417else3418return SUBMODULE_PATCH_WITHOUT_INDEX;3419}else if(has_symlink_leading_path(name,strlen(name))) {3420returnerror(_("reading from '%s' beyond a symbolic link"), name);3421}else{3422if(read_old_data(st, patch, name, buf))3423returnerror(_("failed to read%s"), name);3424}3425}3426return0;3427}34283429/*3430 * We are about to apply "patch"; populate the "image" with the3431 * current version we have, from the working tree or from the index,3432 * depending on the situation e.g. --cached/--index. If we are3433 * applying a non-git patch that incrementally updates the tree,3434 * we read from the result of a previous diff.3435 */3436static intload_preimage(struct apply_state *state,3437struct image *image,3438struct patch *patch,struct stat *st,3439const struct cache_entry *ce)3440{3441struct strbuf buf = STRBUF_INIT;3442size_t len;3443char*img;3444struct patch *previous;3445int status;34463447 previous =previous_patch(state, patch, &status);3448if(status)3449returnerror(_("path%shas been renamed/deleted"),3450 patch->old_name);3451if(previous) {3452/* We have a patched copy in memory; use that. */3453strbuf_add(&buf, previous->result, previous->resultsize);3454}else{3455 status =load_patch_target(state, &buf, ce, st, patch,3456 patch->old_name, patch->old_mode);3457if(status <0)3458return status;3459else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3460/*3461 * There is no way to apply subproject3462 * patch without looking at the index.3463 * NEEDSWORK: shouldn't this be flagged3464 * as an error???3465 */3466free_fragment_list(patch->fragments);3467 patch->fragments = NULL;3468}else if(status) {3469returnerror(_("failed to read%s"), patch->old_name);3470}3471}34723473 img =strbuf_detach(&buf, &len);3474prepare_image(image, img, len, !patch->is_binary);3475return0;3476}34773478static intthree_way_merge(struct apply_state *state,3479struct image *image,3480char*path,3481const struct object_id *base,3482const struct object_id *ours,3483const struct object_id *theirs)3484{3485 mmfile_t base_file, our_file, their_file;3486 mmbuffer_t result = { NULL };3487int status;34883489read_mmblob(&base_file, base);3490read_mmblob(&our_file, ours);3491read_mmblob(&their_file, theirs);3492 status =ll_merge(&result, path,3493&base_file,"base",3494&our_file,"ours",3495&their_file,"theirs",3496 state->repo->index,3497 NULL);3498free(base_file.ptr);3499free(our_file.ptr);3500free(their_file.ptr);3501if(status <0|| !result.ptr) {3502free(result.ptr);3503return-1;3504}3505clear_image(image);3506 image->buf = result.ptr;3507 image->len = result.size;35083509return status;3510}35113512/*3513 * When directly falling back to add/add three-way merge, we read from3514 * the current contents of the new_name. In no cases other than that3515 * this function will be called.3516 */3517static intload_current(struct apply_state *state,3518struct image *image,3519struct patch *patch)3520{3521struct strbuf buf = STRBUF_INIT;3522int status, pos;3523size_t len;3524char*img;3525struct stat st;3526struct cache_entry *ce;3527char*name = patch->new_name;3528unsigned mode = patch->new_mode;35293530if(!patch->is_new)3531BUG("patch to%sis not a creation", patch->old_name);35323533 pos =index_name_pos(state->repo->index, name,strlen(name));3534if(pos <0)3535returnerror(_("%s: does not exist in index"), name);3536 ce = state->repo->index->cache[pos];3537if(lstat(name, &st)) {3538if(errno != ENOENT)3539returnerror_errno("%s", name);3540if(checkout_target(state->repo->index, ce, &st))3541return-1;3542}3543if(verify_index_match(state, ce, &st))3544returnerror(_("%s: does not match index"), name);35453546 status =load_patch_target(state, &buf, ce, &st, patch, name, mode);3547if(status <0)3548return status;3549else if(status)3550return-1;3551 img =strbuf_detach(&buf, &len);3552prepare_image(image, img, len, !patch->is_binary);3553return0;3554}35553556static inttry_threeway(struct apply_state *state,3557struct image *image,3558struct patch *patch,3559struct stat *st,3560const struct cache_entry *ce)3561{3562struct object_id pre_oid, post_oid, our_oid;3563struct strbuf buf = STRBUF_INIT;3564size_t len;3565int status;3566char*img;3567struct image tmp_image;35683569/* No point falling back to 3-way merge in these cases */3570if(patch->is_delete ||3571S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3572return-1;35733574/* Preimage the patch was prepared for */3575if(patch->is_new)3576write_object_file("",0, blob_type, &pre_oid);3577else if(get_oid(patch->old_oid_prefix, &pre_oid) ||3578read_blob_object(&buf, &pre_oid, patch->old_mode))3579returnerror(_("repository lacks the necessary blob to fall back on 3-way merge."));35803581if(state->apply_verbosity > verbosity_silent)3582fprintf(stderr,_("Falling back to three-way merge...\n"));35833584 img =strbuf_detach(&buf, &len);3585prepare_image(&tmp_image, img, len,1);3586/* Apply the patch to get the post image */3587if(apply_fragments(state, &tmp_image, patch) <0) {3588clear_image(&tmp_image);3589return-1;3590}3591/* post_oid is theirs */3592write_object_file(tmp_image.buf, tmp_image.len, blob_type, &post_oid);3593clear_image(&tmp_image);35943595/* our_oid is ours */3596if(patch->is_new) {3597if(load_current(state, &tmp_image, patch))3598returnerror(_("cannot read the current contents of '%s'"),3599 patch->new_name);3600}else{3601if(load_preimage(state, &tmp_image, patch, st, ce))3602returnerror(_("cannot read the current contents of '%s'"),3603 patch->old_name);3604}3605write_object_file(tmp_image.buf, tmp_image.len, blob_type, &our_oid);3606clear_image(&tmp_image);36073608/* in-core three-way merge between post and our using pre as base */3609 status =three_way_merge(state, image, patch->new_name,3610&pre_oid, &our_oid, &post_oid);3611if(status <0) {3612if(state->apply_verbosity > verbosity_silent)3613fprintf(stderr,3614_("Failed to fall back on three-way merge...\n"));3615return status;3616}36173618if(status) {3619 patch->conflicted_threeway =1;3620if(patch->is_new)3621oidclr(&patch->threeway_stage[0]);3622else3623oidcpy(&patch->threeway_stage[0], &pre_oid);3624oidcpy(&patch->threeway_stage[1], &our_oid);3625oidcpy(&patch->threeway_stage[2], &post_oid);3626if(state->apply_verbosity > verbosity_silent)3627fprintf(stderr,3628_("Applied patch to '%s' with conflicts.\n"),3629 patch->new_name);3630}else{3631if(state->apply_verbosity > verbosity_silent)3632fprintf(stderr,3633_("Applied patch to '%s' cleanly.\n"),3634 patch->new_name);3635}3636return0;3637}36383639static intapply_data(struct apply_state *state,struct patch *patch,3640struct stat *st,const struct cache_entry *ce)3641{3642struct image image;36433644if(load_preimage(state, &image, patch, st, ce) <0)3645return-1;36463647if(patch->direct_to_threeway ||3648apply_fragments(state, &image, patch) <0) {3649/* Note: with --reject, apply_fragments() returns 0 */3650if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3651return-1;3652}3653 patch->result = image.buf;3654 patch->resultsize = image.len;3655add_to_fn_table(state, patch);3656free(image.line_allocated);36573658if(0< patch->is_delete && patch->resultsize)3659returnerror(_("removal patch leaves file contents"));36603661return0;3662}36633664/*3665 * If "patch" that we are looking at modifies or deletes what we have,3666 * we would want it not to lose any local modification we have, either3667 * in the working tree or in the index.3668 *3669 * This also decides if a non-git patch is a creation patch or a3670 * modification to an existing empty file. We do not check the state3671 * of the current tree for a creation patch in this function; the caller3672 * check_patch() separately makes sure (and errors out otherwise) that3673 * the path the patch creates does not exist in the current tree.3674 */3675static intcheck_preimage(struct apply_state *state,3676struct patch *patch,3677struct cache_entry **ce,3678struct stat *st)3679{3680const char*old_name = patch->old_name;3681struct patch *previous = NULL;3682int stat_ret =0, status;3683unsigned st_mode =0;36843685if(!old_name)3686return0;36873688assert(patch->is_new <=0);3689 previous =previous_patch(state, patch, &status);36903691if(status)3692returnerror(_("path%shas been renamed/deleted"), old_name);3693if(previous) {3694 st_mode = previous->new_mode;3695}else if(!state->cached) {3696 stat_ret =lstat(old_name, st);3697if(stat_ret && errno != ENOENT)3698returnerror_errno("%s", old_name);3699}37003701if(state->check_index && !previous) {3702int pos =index_name_pos(state->repo->index, old_name,3703strlen(old_name));3704if(pos <0) {3705if(patch->is_new <0)3706goto is_new;3707returnerror(_("%s: does not exist in index"), old_name);3708}3709*ce = state->repo->index->cache[pos];3710if(stat_ret <0) {3711if(checkout_target(state->repo->index, *ce, st))3712return-1;3713}3714if(!state->cached &&verify_index_match(state, *ce, st))3715returnerror(_("%s: does not match index"), old_name);3716if(state->cached)3717 st_mode = (*ce)->ce_mode;3718}else if(stat_ret <0) {3719if(patch->is_new <0)3720goto is_new;3721returnerror_errno("%s", old_name);3722}37233724if(!state->cached && !previous)3725 st_mode =ce_mode_from_stat(*ce, st->st_mode);37263727if(patch->is_new <0)3728 patch->is_new =0;3729if(!patch->old_mode)3730 patch->old_mode = st_mode;3731if((st_mode ^ patch->old_mode) & S_IFMT)3732returnerror(_("%s: wrong type"), old_name);3733if(st_mode != patch->old_mode)3734warning(_("%shas type%o, expected%o"),3735 old_name, st_mode, patch->old_mode);3736if(!patch->new_mode && !patch->is_delete)3737 patch->new_mode = st_mode;3738return0;37393740 is_new:3741 patch->is_new =1;3742 patch->is_delete =0;3743FREE_AND_NULL(patch->old_name);3744return0;3745}374637473748#define EXISTS_IN_INDEX 13749#define EXISTS_IN_WORKTREE 237503751static intcheck_to_create(struct apply_state *state,3752const char*new_name,3753int ok_if_exists)3754{3755struct stat nst;37563757if(state->check_index &&3758index_name_pos(state->repo->index, new_name,strlen(new_name)) >=0&&3759!ok_if_exists)3760return EXISTS_IN_INDEX;3761if(state->cached)3762return0;37633764if(!lstat(new_name, &nst)) {3765if(S_ISDIR(nst.st_mode) || ok_if_exists)3766return0;3767/*3768 * A leading component of new_name might be a symlink3769 * that is going to be removed with this patch, but3770 * still pointing at somewhere that has the path.3771 * In such a case, path "new_name" does not exist as3772 * far as git is concerned.3773 */3774if(has_symlink_leading_path(new_name,strlen(new_name)))3775return0;37763777return EXISTS_IN_WORKTREE;3778}else if(!is_missing_file_error(errno)) {3779returnerror_errno("%s", new_name);3780}3781return0;3782}37833784static uintptr_tregister_symlink_changes(struct apply_state *state,3785const char*path,3786uintptr_t what)3787{3788struct string_list_item *ent;37893790 ent =string_list_lookup(&state->symlink_changes, path);3791if(!ent) {3792 ent =string_list_insert(&state->symlink_changes, path);3793 ent->util = (void*)0;3794}3795 ent->util = (void*)(what | ((uintptr_t)ent->util));3796return(uintptr_t)ent->util;3797}37983799static uintptr_tcheck_symlink_changes(struct apply_state *state,const char*path)3800{3801struct string_list_item *ent;38023803 ent =string_list_lookup(&state->symlink_changes, path);3804if(!ent)3805return0;3806return(uintptr_t)ent->util;3807}38083809static voidprepare_symlink_changes(struct apply_state *state,struct patch *patch)3810{3811for( ; patch; patch = patch->next) {3812if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3813(patch->is_rename || patch->is_delete))3814/* the symlink at patch->old_name is removed */3815register_symlink_changes(state, patch->old_name, APPLY_SYMLINK_GOES_AWAY);38163817if(patch->new_name &&S_ISLNK(patch->new_mode))3818/* the symlink at patch->new_name is created or remains */3819register_symlink_changes(state, patch->new_name, APPLY_SYMLINK_IN_RESULT);3820}3821}38223823static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3824{3825do{3826unsigned int change;38273828while(--name->len && name->buf[name->len] !='/')3829;/* scan backwards */3830if(!name->len)3831break;3832 name->buf[name->len] ='\0';3833 change =check_symlink_changes(state, name->buf);3834if(change & APPLY_SYMLINK_IN_RESULT)3835return1;3836if(change & APPLY_SYMLINK_GOES_AWAY)3837/*3838 * This cannot be "return 0", because we may3839 * see a new one created at a higher level.3840 */3841continue;38423843/* otherwise, check the preimage */3844if(state->check_index) {3845struct cache_entry *ce;38463847 ce =index_file_exists(state->repo->index, name->buf,3848 name->len, ignore_case);3849if(ce &&S_ISLNK(ce->ce_mode))3850return1;3851}else{3852struct stat st;3853if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3854return1;3855}3856}while(1);3857return0;3858}38593860static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3861{3862int ret;3863struct strbuf name = STRBUF_INIT;38643865assert(*name_ !='\0');3866strbuf_addstr(&name, name_);3867 ret =path_is_beyond_symlink_1(state, &name);3868strbuf_release(&name);38693870return ret;3871}38723873static intcheck_unsafe_path(struct patch *patch)3874{3875const char*old_name = NULL;3876const char*new_name = NULL;3877if(patch->is_delete)3878 old_name = patch->old_name;3879else if(!patch->is_new && !patch->is_copy)3880 old_name = patch->old_name;3881if(!patch->is_delete)3882 new_name = patch->new_name;38833884if(old_name && !verify_path(old_name, patch->old_mode))3885returnerror(_("invalid path '%s'"), old_name);3886if(new_name && !verify_path(new_name, patch->new_mode))3887returnerror(_("invalid path '%s'"), new_name);3888return0;3889}38903891/*3892 * Check and apply the patch in-core; leave the result in patch->result3893 * for the caller to write it out to the final destination.3894 */3895static intcheck_patch(struct apply_state *state,struct patch *patch)3896{3897struct stat st;3898const char*old_name = patch->old_name;3899const char*new_name = patch->new_name;3900const char*name = old_name ? old_name : new_name;3901struct cache_entry *ce = NULL;3902struct patch *tpatch;3903int ok_if_exists;3904int status;39053906 patch->rejected =1;/* we will drop this after we succeed */39073908 status =check_preimage(state, patch, &ce, &st);3909if(status)3910return status;3911 old_name = patch->old_name;39123913/*3914 * A type-change diff is always split into a patch to delete3915 * old, immediately followed by a patch to create new (see3916 * diff.c::run_diff()); in such a case it is Ok that the entry3917 * to be deleted by the previous patch is still in the working3918 * tree and in the index.3919 *3920 * A patch to swap-rename between A and B would first rename A3921 * to B and then rename B to A. While applying the first one,3922 * the presence of B should not stop A from getting renamed to3923 * B; ask to_be_deleted() about the later rename. Removal of3924 * B and rename from A to B is handled the same way by asking3925 * was_deleted().3926 */3927if((tpatch =in_fn_table(state, new_name)) &&3928(was_deleted(tpatch) ||to_be_deleted(tpatch)))3929 ok_if_exists =1;3930else3931 ok_if_exists =0;39323933if(new_name &&3934((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3935int err =check_to_create(state, new_name, ok_if_exists);39363937if(err && state->threeway) {3938 patch->direct_to_threeway =1;3939}else switch(err) {3940case0:3941break;/* happy */3942case EXISTS_IN_INDEX:3943returnerror(_("%s: already exists in index"), new_name);3944break;3945case EXISTS_IN_WORKTREE:3946returnerror(_("%s: already exists in working directory"),3947 new_name);3948default:3949return err;3950}39513952if(!patch->new_mode) {3953if(0< patch->is_new)3954 patch->new_mode = S_IFREG |0644;3955else3956 patch->new_mode = patch->old_mode;3957}3958}39593960if(new_name && old_name) {3961int same = !strcmp(old_name, new_name);3962if(!patch->new_mode)3963 patch->new_mode = patch->old_mode;3964if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3965if(same)3966returnerror(_("new mode (%o) of%sdoes not "3967"match old mode (%o)"),3968 patch->new_mode, new_name,3969 patch->old_mode);3970else3971returnerror(_("new mode (%o) of%sdoes not "3972"match old mode (%o) of%s"),3973 patch->new_mode, new_name,3974 patch->old_mode, old_name);3975}3976}39773978if(!state->unsafe_paths &&check_unsafe_path(patch))3979return-128;39803981/*3982 * An attempt to read from or delete a path that is beyond a3983 * symbolic link will be prevented by load_patch_target() that3984 * is called at the beginning of apply_data() so we do not3985 * have to worry about a patch marked with "is_delete" bit3986 * here. We however need to make sure that the patch result3987 * is not deposited to a path that is beyond a symbolic link3988 * here.3989 */3990if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3991returnerror(_("affected file '%s' is beyond a symbolic link"),3992 patch->new_name);39933994if(apply_data(state, patch, &st, ce) <0)3995returnerror(_("%s: patch does not apply"), name);3996 patch->rejected =0;3997return0;3998}39994000static intcheck_patch_list(struct apply_state *state,struct patch *patch)4001{4002int err =0;40034004prepare_symlink_changes(state, patch);4005prepare_fn_table(state, patch);4006while(patch) {4007int res;4008if(state->apply_verbosity > verbosity_normal)4009say_patch_name(stderr,4010_("Checking patch%s..."), patch);4011 res =check_patch(state, patch);4012if(res == -128)4013return-128;4014 err |= res;4015 patch = patch->next;4016}4017return err;4018}40194020static intread_apply_cache(struct apply_state *state)4021{4022if(state->index_file)4023returnread_index_from(state->repo->index, state->index_file,4024get_git_dir());4025else4026returnrepo_read_index(state->repo);4027}40284029/* This function tries to read the object name from the current index */4030static intget_current_oid(struct apply_state *state,const char*path,4031struct object_id *oid)4032{4033int pos;40344035if(read_apply_cache(state) <0)4036return-1;4037 pos =index_name_pos(state->repo->index, path,strlen(path));4038if(pos <0)4039return-1;4040oidcpy(oid, &state->repo->index->cache[pos]->oid);4041return0;4042}40434044static intpreimage_oid_in_gitlink_patch(struct patch *p,struct object_id *oid)4045{4046/*4047 * A usable gitlink patch has only one fragment (hunk) that looks like:4048 * @@ -1 +1 @@4049 * -Subproject commit <old sha1>4050 * +Subproject commit <new sha1>4051 * or4052 * @@ -1 +0,0 @@4053 * -Subproject commit <old sha1>4054 * for a removal patch.4055 */4056struct fragment *hunk = p->fragments;4057static const char heading[] ="-Subproject commit ";4058char*preimage;40594060if(/* does the patch have only one hunk? */4061 hunk && !hunk->next &&4062/* is its preimage one line? */4063 hunk->oldpos ==1&& hunk->oldlines ==1&&4064/* does preimage begin with the heading? */4065(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&4066starts_with(++preimage, heading) &&4067/* does it record full SHA-1? */4068!get_oid_hex(preimage +sizeof(heading) -1, oid) &&4069 preimage[sizeof(heading) + the_hash_algo->hexsz -1] =='\n'&&4070/* does the abbreviated name on the index line agree with it? */4071starts_with(preimage +sizeof(heading) -1, p->old_oid_prefix))4072return0;/* it all looks fine */40734074/* we may have full object name on the index line */4075returnget_oid_hex(p->old_oid_prefix, oid);4076}40774078/* Build an index that contains just the files needed for a 3way merge */4079static intbuild_fake_ancestor(struct apply_state *state,struct patch *list)4080{4081struct patch *patch;4082struct index_state result = { NULL };4083struct lock_file lock = LOCK_INIT;4084int res;40854086/* Once we start supporting the reverse patch, it may be4087 * worth showing the new sha1 prefix, but until then...4088 */4089for(patch = list; patch; patch = patch->next) {4090struct object_id oid;4091struct cache_entry *ce;4092const char*name;40934094 name = patch->old_name ? patch->old_name : patch->new_name;4095if(0< patch->is_new)4096continue;40974098if(S_ISGITLINK(patch->old_mode)) {4099if(!preimage_oid_in_gitlink_patch(patch, &oid))4100;/* ok, the textual part looks sane */4101else4102returnerror(_("sha1 information is lacking or "4103"useless for submodule%s"), name);4104}else if(!get_oid_blob(patch->old_oid_prefix, &oid)) {4105;/* ok */4106}else if(!patch->lines_added && !patch->lines_deleted) {4107/* mode-only change: update the current */4108if(get_current_oid(state, patch->old_name, &oid))4109returnerror(_("mode change for%s, which is not "4110"in current HEAD"), name);4111}else4112returnerror(_("sha1 information is lacking or useless "4113"(%s)."), name);41144115 ce =make_cache_entry(&result, patch->old_mode, &oid, name,0,0);4116if(!ce)4117returnerror(_("make_cache_entry failed for path '%s'"),4118 name);4119if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) {4120discard_cache_entry(ce);4121returnerror(_("could not add%sto temporary index"),4122 name);4123}4124}41254126hold_lock_file_for_update(&lock, state->fake_ancestor, LOCK_DIE_ON_ERROR);4127 res =write_locked_index(&result, &lock, COMMIT_LOCK);4128discard_index(&result);41294130if(res)4131returnerror(_("could not write temporary index to%s"),4132 state->fake_ancestor);41334134return0;4135}41364137static voidstat_patch_list(struct apply_state *state,struct patch *patch)4138{4139int files, adds, dels;41404141for(files = adds = dels =0; patch ; patch = patch->next) {4142 files++;4143 adds += patch->lines_added;4144 dels += patch->lines_deleted;4145show_stats(state, patch);4146}41474148print_stat_summary(stdout, files, adds, dels);4149}41504151static voidnumstat_patch_list(struct apply_state *state,4152struct patch *patch)4153{4154for( ; patch; patch = patch->next) {4155const char*name;4156 name = patch->new_name ? patch->new_name : patch->old_name;4157if(patch->is_binary)4158printf("-\t-\t");4159else4160printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4161write_name_quoted(name, stdout, state->line_termination);4162}4163}41644165static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4166{4167if(mode)4168printf("%smode%06o%s\n", newdelete, mode, name);4169else4170printf("%s %s\n", newdelete, name);4171}41724173static voidshow_mode_change(struct patch *p,int show_name)4174{4175if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4176if(show_name)4177printf(" mode change%06o =>%06o%s\n",4178 p->old_mode, p->new_mode, p->new_name);4179else4180printf(" mode change%06o =>%06o\n",4181 p->old_mode, p->new_mode);4182}4183}41844185static voidshow_rename_copy(struct patch *p)4186{4187const char*renamecopy = p->is_rename ?"rename":"copy";4188const char*old_name, *new_name;41894190/* Find common prefix */4191 old_name = p->old_name;4192 new_name = p->new_name;4193while(1) {4194const char*slash_old, *slash_new;4195 slash_old =strchr(old_name,'/');4196 slash_new =strchr(new_name,'/');4197if(!slash_old ||4198!slash_new ||4199 slash_old - old_name != slash_new - new_name ||4200memcmp(old_name, new_name, slash_new - new_name))4201break;4202 old_name = slash_old +1;4203 new_name = slash_new +1;4204}4205/* p->old_name thru old_name is the common prefix, and old_name and new_name4206 * through the end of names are renames4207 */4208if(old_name != p->old_name)4209printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4210(int)(old_name - p->old_name), p->old_name,4211 old_name, new_name, p->score);4212else4213printf("%s %s=>%s(%d%%)\n", renamecopy,4214 p->old_name, p->new_name, p->score);4215show_mode_change(p,0);4216}42174218static voidsummary_patch_list(struct patch *patch)4219{4220struct patch *p;42214222for(p = patch; p; p = p->next) {4223if(p->is_new)4224show_file_mode_name("create", p->new_mode, p->new_name);4225else if(p->is_delete)4226show_file_mode_name("delete", p->old_mode, p->old_name);4227else{4228if(p->is_rename || p->is_copy)4229show_rename_copy(p);4230else{4231if(p->score) {4232printf(" rewrite%s(%d%%)\n",4233 p->new_name, p->score);4234show_mode_change(p,0);4235}4236else4237show_mode_change(p,1);4238}4239}4240}4241}42424243static voidpatch_stats(struct apply_state *state,struct patch *patch)4244{4245int lines = patch->lines_added + patch->lines_deleted;42464247if(lines > state->max_change)4248 state->max_change = lines;4249if(patch->old_name) {4250int len =quote_c_style(patch->old_name, NULL, NULL,0);4251if(!len)4252 len =strlen(patch->old_name);4253if(len > state->max_len)4254 state->max_len = len;4255}4256if(patch->new_name) {4257int len =quote_c_style(patch->new_name, NULL, NULL,0);4258if(!len)4259 len =strlen(patch->new_name);4260if(len > state->max_len)4261 state->max_len = len;4262}4263}42644265static intremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4266{4267if(state->update_index && !state->ita_only) {4268if(remove_file_from_index(state->repo->index, patch->old_name) <0)4269returnerror(_("unable to remove%sfrom index"), patch->old_name);4270}4271if(!state->cached) {4272if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4273remove_path(patch->old_name);4274}4275}4276return0;4277}42784279static intadd_index_file(struct apply_state *state,4280const char*path,4281unsigned mode,4282void*buf,4283unsigned long size)4284{4285struct stat st;4286struct cache_entry *ce;4287int namelen =strlen(path);42884289 ce =make_empty_cache_entry(state->repo->index, namelen);4290memcpy(ce->name, path, namelen);4291 ce->ce_mode =create_ce_mode(mode);4292 ce->ce_flags =create_ce_flags(0);4293 ce->ce_namelen = namelen;4294if(state->ita_only) {4295 ce->ce_flags |= CE_INTENT_TO_ADD;4296set_object_name_for_intent_to_add_entry(ce);4297}else if(S_ISGITLINK(mode)) {4298const char*s;42994300if(!skip_prefix(buf,"Subproject commit ", &s) ||4301get_oid_hex(s, &ce->oid)) {4302discard_cache_entry(ce);4303returnerror(_("corrupt patch for submodule%s"), path);4304}4305}else{4306if(!state->cached) {4307if(lstat(path, &st) <0) {4308discard_cache_entry(ce);4309returnerror_errno(_("unable to stat newly "4310"created file '%s'"),4311 path);4312}4313fill_stat_cache_info(state->repo->index, ce, &st);4314}4315if(write_object_file(buf, size, blob_type, &ce->oid) <0) {4316discard_cache_entry(ce);4317returnerror(_("unable to create backing store "4318"for newly created file%s"), path);4319}4320}4321if(add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) <0) {4322discard_cache_entry(ce);4323returnerror(_("unable to add cache entry for%s"), path);4324}43254326return0;4327}43284329/*4330 * Returns:4331 * -1 if an unrecoverable error happened4332 * 0 if everything went well4333 * 1 if a recoverable error happened4334 */4335static inttry_create_file(struct apply_state *state,const char*path,4336unsigned int mode,const char*buf,4337unsigned long size)4338{4339int fd, res;4340struct strbuf nbuf = STRBUF_INIT;43414342if(S_ISGITLINK(mode)) {4343struct stat st;4344if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4345return0;4346return!!mkdir(path,0777);4347}43484349if(has_symlinks &&S_ISLNK(mode))4350/* Although buf:size is counted string, it also is NUL4351 * terminated.4352 */4353return!!symlink(buf, path);43544355 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4356if(fd <0)4357return1;43584359if(convert_to_working_tree(state->repo->index, path, buf, size, &nbuf)) {4360 size = nbuf.len;4361 buf = nbuf.buf;4362}43634364 res =write_in_full(fd, buf, size) <0;4365if(res)4366error_errno(_("failed to write to '%s'"), path);4367strbuf_release(&nbuf);43684369if(close(fd) <0&& !res)4370returnerror_errno(_("closing file '%s'"), path);43714372return res ? -1:0;4373}43744375/*4376 * We optimistically assume that the directories exist,4377 * which is true 99% of the time anyway. If they don't,4378 * we create them and try again.4379 *4380 * Returns:4381 * -1 on error4382 * 0 otherwise4383 */4384static intcreate_one_file(struct apply_state *state,4385char*path,4386unsigned mode,4387const char*buf,4388unsigned long size)4389{4390int res;43914392if(state->cached)4393return0;43944395 res =try_create_file(state, path, mode, buf, size);4396if(res <0)4397return-1;4398if(!res)4399return0;44004401if(errno == ENOENT) {4402if(safe_create_leading_directories(path))4403return0;4404 res =try_create_file(state, path, mode, buf, size);4405if(res <0)4406return-1;4407if(!res)4408return0;4409}44104411if(errno == EEXIST || errno == EACCES) {4412/* We may be trying to create a file where a directory4413 * used to be.4414 */4415struct stat st;4416if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4417 errno = EEXIST;4418}44194420if(errno == EEXIST) {4421unsigned int nr =getpid();44224423for(;;) {4424char newpath[PATH_MAX];4425mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4426 res =try_create_file(state, newpath, mode, buf, size);4427if(res <0)4428return-1;4429if(!res) {4430if(!rename(newpath, path))4431return0;4432unlink_or_warn(newpath);4433break;4434}4435if(errno != EEXIST)4436break;4437++nr;4438}4439}4440returnerror_errno(_("unable to write file '%s' mode%o"),4441 path, mode);4442}44434444static intadd_conflicted_stages_file(struct apply_state *state,4445struct patch *patch)4446{4447int stage, namelen;4448unsigned mode;4449struct cache_entry *ce;44504451if(!state->update_index)4452return0;4453 namelen =strlen(patch->new_name);4454 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);44554456remove_file_from_index(state->repo->index, patch->new_name);4457for(stage =1; stage <4; stage++) {4458if(is_null_oid(&patch->threeway_stage[stage -1]))4459continue;4460 ce =make_empty_cache_entry(state->repo->index, namelen);4461memcpy(ce->name, patch->new_name, namelen);4462 ce->ce_mode =create_ce_mode(mode);4463 ce->ce_flags =create_ce_flags(stage);4464 ce->ce_namelen = namelen;4465oidcpy(&ce->oid, &patch->threeway_stage[stage -1]);4466if(add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) <0) {4467discard_cache_entry(ce);4468returnerror(_("unable to add cache entry for%s"),4469 patch->new_name);4470}4471}44724473return0;4474}44754476static intcreate_file(struct apply_state *state,struct patch *patch)4477{4478char*path = patch->new_name;4479unsigned mode = patch->new_mode;4480unsigned long size = patch->resultsize;4481char*buf = patch->result;44824483if(!mode)4484 mode = S_IFREG |0644;4485if(create_one_file(state, path, mode, buf, size))4486return-1;44874488if(patch->conflicted_threeway)4489returnadd_conflicted_stages_file(state, patch);4490else if(state->update_index)4491returnadd_index_file(state, path, mode, buf, size);4492return0;4493}44944495/* phase zero is to remove, phase one is to create */4496static intwrite_out_one_result(struct apply_state *state,4497struct patch *patch,4498int phase)4499{4500if(patch->is_delete >0) {4501if(phase ==0)4502returnremove_file(state, patch,1);4503return0;4504}4505if(patch->is_new >0|| patch->is_copy) {4506if(phase ==1)4507returncreate_file(state, patch);4508return0;4509}4510/*4511 * Rename or modification boils down to the same4512 * thing: remove the old, write the new4513 */4514if(phase ==0)4515returnremove_file(state, patch, patch->is_rename);4516if(phase ==1)4517returncreate_file(state, patch);4518return0;4519}45204521static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4522{4523FILE*rej;4524char namebuf[PATH_MAX];4525struct fragment *frag;4526int cnt =0;4527struct strbuf sb = STRBUF_INIT;45284529for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4530if(!frag->rejected)4531continue;4532 cnt++;4533}45344535if(!cnt) {4536if(state->apply_verbosity > verbosity_normal)4537say_patch_name(stderr,4538_("Applied patch%scleanly."), patch);4539return0;4540}45414542/* This should not happen, because a removal patch that leaves4543 * contents are marked "rejected" at the patch level.4544 */4545if(!patch->new_name)4546die(_("internal error"));45474548/* Say this even without --verbose */4549strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4550"Applying patch %%swith%drejects...",4551 cnt),4552 cnt);4553if(state->apply_verbosity > verbosity_silent)4554say_patch_name(stderr, sb.buf, patch);4555strbuf_release(&sb);45564557 cnt =strlen(patch->new_name);4558if(ARRAY_SIZE(namebuf) <= cnt +5) {4559 cnt =ARRAY_SIZE(namebuf) -5;4560warning(_("truncating .rej filename to %.*s.rej"),4561 cnt -1, patch->new_name);4562}4563memcpy(namebuf, patch->new_name, cnt);4564memcpy(namebuf + cnt,".rej",5);45654566 rej =fopen(namebuf,"w");4567if(!rej)4568returnerror_errno(_("cannot open%s"), namebuf);45694570/* Normal git tools never deal with .rej, so do not pretend4571 * this is a git patch by saying --git or giving extended4572 * headers. While at it, maybe please "kompare" that wants4573 * the trailing TAB and some garbage at the end of line ;-).4574 */4575fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4576 patch->new_name, patch->new_name);4577for(cnt =1, frag = patch->fragments;4578 frag;4579 cnt++, frag = frag->next) {4580if(!frag->rejected) {4581if(state->apply_verbosity > verbosity_silent)4582fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4583continue;4584}4585if(state->apply_verbosity > verbosity_silent)4586fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4587fprintf(rej,"%.*s", frag->size, frag->patch);4588if(frag->patch[frag->size-1] !='\n')4589fputc('\n', rej);4590}4591fclose(rej);4592return-1;4593}45944595/*4596 * Returns:4597 * -1 if an error happened4598 * 0 if the patch applied cleanly4599 * 1 if the patch did not apply cleanly4600 */4601static intwrite_out_results(struct apply_state *state,struct patch *list)4602{4603int phase;4604int errs =0;4605struct patch *l;4606struct string_list cpath = STRING_LIST_INIT_DUP;46074608for(phase =0; phase <2; phase++) {4609 l = list;4610while(l) {4611if(l->rejected)4612 errs =1;4613else{4614if(write_out_one_result(state, l, phase)) {4615string_list_clear(&cpath,0);4616return-1;4617}4618if(phase ==1) {4619if(write_out_one_reject(state, l))4620 errs =1;4621if(l->conflicted_threeway) {4622string_list_append(&cpath, l->new_name);4623 errs =1;4624}4625}4626}4627 l = l->next;4628}4629}46304631if(cpath.nr) {4632struct string_list_item *item;46334634string_list_sort(&cpath);4635if(state->apply_verbosity > verbosity_silent) {4636for_each_string_list_item(item, &cpath)4637fprintf(stderr,"U%s\n", item->string);4638}4639string_list_clear(&cpath,0);46404641repo_rerere(state->repo,0);4642}46434644return errs;4645}46464647/*4648 * Try to apply a patch.4649 *4650 * Returns:4651 * -128 if a bad error happened (like patch unreadable)4652 * -1 if patch did not apply and user cannot deal with it4653 * 0 if the patch applied4654 * 1 if the patch did not apply but user might fix it4655 */4656static intapply_patch(struct apply_state *state,4657int fd,4658const char*filename,4659int options)4660{4661size_t offset;4662struct strbuf buf = STRBUF_INIT;/* owns the patch text */4663struct patch *list = NULL, **listp = &list;4664int skipped_patch =0;4665int res =0;46664667 state->patch_input_file = filename;4668if(read_patch_file(&buf, fd) <0)4669return-128;4670 offset =0;4671while(offset < buf.len) {4672struct patch *patch;4673int nr;46744675 patch =xcalloc(1,sizeof(*patch));4676 patch->inaccurate_eof = !!(options & APPLY_OPT_INACCURATE_EOF);4677 patch->recount = !!(options & APPLY_OPT_RECOUNT);4678 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4679if(nr <0) {4680free_patch(patch);4681if(nr == -128) {4682 res = -128;4683goto end;4684}4685break;4686}4687if(state->apply_in_reverse)4688reverse_patches(patch);4689if(use_patch(state, patch)) {4690patch_stats(state, patch);4691*listp = patch;4692 listp = &patch->next;4693}4694else{4695if(state->apply_verbosity > verbosity_normal)4696say_patch_name(stderr,_("Skipped patch '%s'."), patch);4697free_patch(patch);4698 skipped_patch++;4699}4700 offset += nr;4701}47024703if(!list && !skipped_patch) {4704error(_("unrecognized input"));4705 res = -128;4706goto end;4707}47084709if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4710 state->apply =0;47114712 state->update_index = (state->check_index || state->ita_only) && state->apply;4713if(state->update_index && !is_lock_file_locked(&state->lock_file)) {4714if(state->index_file)4715hold_lock_file_for_update(&state->lock_file,4716 state->index_file,4717 LOCK_DIE_ON_ERROR);4718else4719repo_hold_locked_index(state->repo, &state->lock_file,4720 LOCK_DIE_ON_ERROR);4721}47224723if(state->check_index &&read_apply_cache(state) <0) {4724error(_("unable to read index file"));4725 res = -128;4726goto end;4727}47284729if(state->check || state->apply) {4730int r =check_patch_list(state, list);4731if(r == -128) {4732 res = -128;4733goto end;4734}4735if(r <0&& !state->apply_with_reject) {4736 res = -1;4737goto end;4738}4739}47404741if(state->apply) {4742int write_res =write_out_results(state, list);4743if(write_res <0) {4744 res = -128;4745goto end;4746}4747if(write_res >0) {4748/* with --3way, we still need to write the index out */4749 res = state->apply_with_reject ? -1:1;4750goto end;4751}4752}47534754if(state->fake_ancestor &&4755build_fake_ancestor(state, list)) {4756 res = -128;4757goto end;4758}47594760if(state->diffstat && state->apply_verbosity > verbosity_silent)4761stat_patch_list(state, list);47624763if(state->numstat && state->apply_verbosity > verbosity_silent)4764numstat_patch_list(state, list);47654766if(state->summary && state->apply_verbosity > verbosity_silent)4767summary_patch_list(list);47684769end:4770free_patch_list(list);4771strbuf_release(&buf);4772string_list_clear(&state->fn_table,0);4773return res;4774}47754776static intapply_option_parse_exclude(const struct option *opt,4777const char*arg,int unset)4778{4779struct apply_state *state = opt->value;47804781BUG_ON_OPT_NEG(unset);47824783add_name_limit(state, arg,1);4784return0;4785}47864787static intapply_option_parse_include(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,0);4795 state->has_include =1;4796return0;4797}47984799static intapply_option_parse_p(const struct option *opt,4800const char*arg,4801int unset)4802{4803struct apply_state *state = opt->value;48044805BUG_ON_OPT_NEG(unset);48064807 state->p_value =atoi(arg);4808 state->p_value_known =1;4809return0;4810}48114812static intapply_option_parse_space_change(const struct option *opt,4813const char*arg,int unset)4814{4815struct apply_state *state = opt->value;48164817BUG_ON_OPT_ARG(arg);48184819if(unset)4820 state->ws_ignore_action = ignore_ws_none;4821else4822 state->ws_ignore_action = ignore_ws_change;4823return0;4824}48254826static intapply_option_parse_whitespace(const struct option *opt,4827const char*arg,int unset)4828{4829struct apply_state *state = opt->value;48304831BUG_ON_OPT_NEG(unset);48324833 state->whitespace_option = arg;4834if(parse_whitespace_option(state, arg))4835return-1;4836return0;4837}48384839static intapply_option_parse_directory(const struct option *opt,4840const char*arg,int unset)4841{4842struct apply_state *state = opt->value;48434844BUG_ON_OPT_NEG(unset);48454846strbuf_reset(&state->root);4847strbuf_addstr(&state->root, arg);4848strbuf_complete(&state->root,'/');4849return0;4850}48514852intapply_all_patches(struct apply_state *state,4853int argc,4854const char**argv,4855int options)4856{4857int i;4858int res;4859int errs =0;4860int read_stdin =1;48614862for(i =0; i < argc; i++) {4863const char*arg = argv[i];4864char*to_free = NULL;4865int fd;48664867if(!strcmp(arg,"-")) {4868 res =apply_patch(state,0,"<stdin>", options);4869if(res <0)4870goto end;4871 errs |= res;4872 read_stdin =0;4873continue;4874}else4875 arg = to_free =prefix_filename(state->prefix, arg);48764877 fd =open(arg, O_RDONLY);4878if(fd <0) {4879error(_("can't open patch '%s':%s"), arg,strerror(errno));4880 res = -128;4881free(to_free);4882goto end;4883}4884 read_stdin =0;4885set_default_whitespace_mode(state);4886 res =apply_patch(state, fd, arg, options);4887close(fd);4888free(to_free);4889if(res <0)4890goto end;4891 errs |= res;4892}4893set_default_whitespace_mode(state);4894if(read_stdin) {4895 res =apply_patch(state,0,"<stdin>", options);4896if(res <0)4897goto end;4898 errs |= res;4899}49004901if(state->whitespace_error) {4902if(state->squelch_whitespace_errors &&4903 state->squelch_whitespace_errors < state->whitespace_error) {4904int squelched =4905 state->whitespace_error - state->squelch_whitespace_errors;4906warning(Q_("squelched%dwhitespace error",4907"squelched%dwhitespace errors",4908 squelched),4909 squelched);4910}4911if(state->ws_error_action == die_on_ws_error) {4912error(Q_("%dline adds whitespace errors.",4913"%dlines add whitespace errors.",4914 state->whitespace_error),4915 state->whitespace_error);4916 res = -128;4917goto end;4918}4919if(state->applied_after_fixing_ws && state->apply)4920warning(Q_("%dline applied after"4921" fixing whitespace errors.",4922"%dlines applied after"4923" fixing whitespace errors.",4924 state->applied_after_fixing_ws),4925 state->applied_after_fixing_ws);4926else if(state->whitespace_error)4927warning(Q_("%dline adds whitespace errors.",4928"%dlines add whitespace errors.",4929 state->whitespace_error),4930 state->whitespace_error);4931}49324933if(state->update_index) {4934 res =write_locked_index(state->repo->index, &state->lock_file, COMMIT_LOCK);4935if(res) {4936error(_("Unable to write new index file"));4937 res = -128;4938goto end;4939}4940}49414942 res = !!errs;49434944end:4945rollback_lock_file(&state->lock_file);49464947if(state->apply_verbosity <= verbosity_silent) {4948set_error_routine(state->saved_error_routine);4949set_warn_routine(state->saved_warn_routine);4950}49514952if(res > -1)4953return res;4954return(res == -1?1:128);4955}49564957intapply_parse_options(int argc,const char**argv,4958struct apply_state *state,4959int*force_apply,int*options,4960const char*const*apply_usage)4961{4962struct option builtin_apply_options[] = {4963{ OPTION_CALLBACK,0,"exclude", state,N_("path"),4964N_("don't apply changes matching the given path"),4965 PARSE_OPT_NONEG, apply_option_parse_exclude },4966{ OPTION_CALLBACK,0,"include", state,N_("path"),4967N_("apply changes matching the given path"),4968 PARSE_OPT_NONEG, apply_option_parse_include },4969{ OPTION_CALLBACK,'p', NULL, state,N_("num"),4970N_("remove <num> leading slashes from traditional diff paths"),49710, apply_option_parse_p },4972OPT_BOOL(0,"no-add", &state->no_add,4973N_("ignore additions made by the patch")),4974OPT_BOOL(0,"stat", &state->diffstat,4975N_("instead of applying the patch, output diffstat for the input")),4976OPT_NOOP_NOARG(0,"allow-binary-replacement"),4977OPT_NOOP_NOARG(0,"binary"),4978OPT_BOOL(0,"numstat", &state->numstat,4979N_("show number of added and deleted lines in decimal notation")),4980OPT_BOOL(0,"summary", &state->summary,4981N_("instead of applying the patch, output a summary for the input")),4982OPT_BOOL(0,"check", &state->check,4983N_("instead of applying the patch, see if the patch is applicable")),4984OPT_BOOL(0,"index", &state->check_index,4985N_("make sure the patch is applicable to the current index")),4986OPT_BOOL('N',"intent-to-add", &state->ita_only,4987N_("mark new files with `git add --intent-to-add`")),4988OPT_BOOL(0,"cached", &state->cached,4989N_("apply a patch without touching the working tree")),4990OPT_BOOL_F(0,"unsafe-paths", &state->unsafe_paths,4991N_("accept a patch that touches outside the working area"),4992 PARSE_OPT_NOCOMPLETE),4993OPT_BOOL(0,"apply", force_apply,4994N_("also apply the patch (use with --stat/--summary/--check)")),4995OPT_BOOL('3',"3way", &state->threeway,4996N_("attempt three-way merge if a patch does not apply")),4997OPT_FILENAME(0,"build-fake-ancestor", &state->fake_ancestor,4998N_("build a temporary index based on embedded index information")),4999/* Think twice before adding "--nul" synonym to this */5000OPT_SET_INT('z', NULL, &state->line_termination,5001N_("paths are separated with NUL character"),'\0'),5002OPT_INTEGER('C', NULL, &state->p_context,5003N_("ensure at least <n> lines of context match")),5004{ OPTION_CALLBACK,0,"whitespace", state,N_("action"),5005N_("detect new or modified lines that have whitespace errors"),50060, apply_option_parse_whitespace },5007{ OPTION_CALLBACK,0,"ignore-space-change", state, NULL,5008N_("ignore changes in whitespace when finding context"),5009 PARSE_OPT_NOARG, apply_option_parse_space_change },5010{ OPTION_CALLBACK,0,"ignore-whitespace", state, NULL,5011N_("ignore changes in whitespace when finding context"),5012 PARSE_OPT_NOARG, apply_option_parse_space_change },5013OPT_BOOL('R',"reverse", &state->apply_in_reverse,5014N_("apply the patch in reverse")),5015OPT_BOOL(0,"unidiff-zero", &state->unidiff_zero,5016N_("don't expect at least one line of context")),5017OPT_BOOL(0,"reject", &state->apply_with_reject,5018N_("leave the rejected hunks in corresponding *.rej files")),5019OPT_BOOL(0,"allow-overlap", &state->allow_overlap,5020N_("allow overlapping hunks")),5021OPT__VERBOSE(&state->apply_verbosity,N_("be verbose")),5022OPT_BIT(0,"inaccurate-eof", options,5023N_("tolerate incorrectly detected missing new-line at the end of file"),5024 APPLY_OPT_INACCURATE_EOF),5025OPT_BIT(0,"recount", options,5026N_("do not trust the line counts in the hunk headers"),5027 APPLY_OPT_RECOUNT),5028{ OPTION_CALLBACK,0,"directory", state,N_("root"),5029N_("prepend <root> to all filenames"),50300, apply_option_parse_directory },5031OPT_END()5032};50335034returnparse_options(argc, argv, state->prefix, builtin_apply_options, apply_usage,0);5035}