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"blob.h" 13#include"delta.h" 14#include"diff.h" 15#include"dir.h" 16#include"xdiff-interface.h" 17#include"ll-merge.h" 18#include"lockfile.h" 19#include"parse-options.h" 20#include"quote.h" 21#include"rerere.h" 22#include"apply.h" 23 24static voidgit_apply_config(void) 25{ 26git_config_get_string_const("apply.whitespace", &apply_default_whitespace); 27git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace); 28git_config(git_default_config, NULL); 29} 30 31static intparse_whitespace_option(struct apply_state *state,const char*option) 32{ 33if(!option) { 34 state->ws_error_action = warn_on_ws_error; 35return0; 36} 37if(!strcmp(option,"warn")) { 38 state->ws_error_action = warn_on_ws_error; 39return0; 40} 41if(!strcmp(option,"nowarn")) { 42 state->ws_error_action = nowarn_ws_error; 43return0; 44} 45if(!strcmp(option,"error")) { 46 state->ws_error_action = die_on_ws_error; 47return0; 48} 49if(!strcmp(option,"error-all")) { 50 state->ws_error_action = die_on_ws_error; 51 state->squelch_whitespace_errors =0; 52return0; 53} 54if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 55 state->ws_error_action = correct_ws_error; 56return0; 57} 58returnerror(_("unrecognized whitespace option '%s'"), option); 59} 60 61static intparse_ignorewhitespace_option(struct apply_state *state, 62const char*option) 63{ 64if(!option || !strcmp(option,"no") || 65!strcmp(option,"false") || !strcmp(option,"never") || 66!strcmp(option,"none")) { 67 state->ws_ignore_action = ignore_ws_none; 68return0; 69} 70if(!strcmp(option,"change")) { 71 state->ws_ignore_action = ignore_ws_change; 72return0; 73} 74returnerror(_("unrecognized whitespace ignore option '%s'"), option); 75} 76 77intinit_apply_state(struct apply_state *state, 78const char*prefix) 79{ 80memset(state,0,sizeof(*state)); 81 state->prefix = prefix; 82 state->apply =1; 83 state->line_termination ='\n'; 84 state->p_value =1; 85 state->p_context = UINT_MAX; 86 state->squelch_whitespace_errors =5; 87 state->ws_error_action = warn_on_ws_error; 88 state->ws_ignore_action = ignore_ws_none; 89 state->linenr =1; 90string_list_init(&state->fn_table,0); 91string_list_init(&state->limit_by_name,0); 92string_list_init(&state->symlink_changes,0); 93strbuf_init(&state->root,0); 94 95git_apply_config(); 96if(apply_default_whitespace &&parse_whitespace_option(state, apply_default_whitespace)) 97return-1; 98if(apply_default_ignorewhitespace &&parse_ignorewhitespace_option(state, apply_default_ignorewhitespace)) 99return-1; 100return0; 101} 102 103voidclear_apply_state(struct apply_state *state) 104{ 105string_list_clear(&state->limit_by_name,0); 106string_list_clear(&state->symlink_changes,0); 107strbuf_release(&state->root); 108 109/* &state->fn_table is cleared at the end of apply_patch() */ 110} 111 112static voidmute_routine(const char*msg,va_list params) 113{ 114/* do nothing */ 115} 116 117intcheck_apply_state(struct apply_state *state,int force_apply) 118{ 119int is_not_gitdir = !startup_info->have_repository; 120 121if(state->apply_with_reject && state->threeway) 122returnerror(_("--reject and --3way cannot be used together.")); 123if(state->cached && state->threeway) 124returnerror(_("--cached and --3way cannot be used together.")); 125if(state->threeway) { 126if(is_not_gitdir) 127returnerror(_("--3way outside a repository")); 128 state->check_index =1; 129} 130if(state->apply_with_reject) { 131 state->apply =1; 132if(state->apply_verbosity == verbosity_normal) 133 state->apply_verbosity = verbosity_verbose; 134} 135if(!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor)) 136 state->apply =0; 137if(state->check_index && is_not_gitdir) 138returnerror(_("--index outside a repository")); 139if(state->cached) { 140if(is_not_gitdir) 141returnerror(_("--cached outside a repository")); 142 state->check_index =1; 143} 144if(state->ita_only && (state->check_index || is_not_gitdir)) 145 state->ita_only =0; 146if(state->check_index) 147 state->unsafe_paths =0; 148 149if(state->apply_verbosity <= verbosity_silent) { 150 state->saved_error_routine =get_error_routine(); 151 state->saved_warn_routine =get_warn_routine(); 152set_error_routine(mute_routine); 153set_warn_routine(mute_routine); 154} 155 156return0; 157} 158 159static voidset_default_whitespace_mode(struct apply_state *state) 160{ 161if(!state->whitespace_option && !apply_default_whitespace) 162 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 163} 164 165/* 166 * This represents one "hunk" from a patch, starting with 167 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 168 * patch text is pointed at by patch, and its byte length 169 * is stored in size. leading and trailing are the number 170 * of context lines. 171 */ 172struct fragment { 173unsigned long leading, trailing; 174unsigned long oldpos, oldlines; 175unsigned long newpos, newlines; 176/* 177 * 'patch' is usually borrowed from buf in apply_patch(), 178 * but some codepaths store an allocated buffer. 179 */ 180const char*patch; 181unsigned free_patch:1, 182 rejected:1; 183int size; 184int linenr; 185struct fragment *next; 186}; 187 188/* 189 * When dealing with a binary patch, we reuse "leading" field 190 * to store the type of the binary hunk, either deflated "delta" 191 * or deflated "literal". 192 */ 193#define binary_patch_method leading 194#define BINARY_DELTA_DEFLATED 1 195#define BINARY_LITERAL_DEFLATED 2 196 197/* 198 * This represents a "patch" to a file, both metainfo changes 199 * such as creation/deletion, filemode and content changes represented 200 * as a series of fragments. 201 */ 202struct patch { 203char*new_name, *old_name, *def_name; 204unsigned int old_mode, new_mode; 205int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 206int rejected; 207unsigned ws_rule; 208int lines_added, lines_deleted; 209int score; 210int extension_linenr;/* first line specifying delete/new/rename/copy */ 211unsigned int is_toplevel_relative:1; 212unsigned int inaccurate_eof:1; 213unsigned int is_binary:1; 214unsigned int is_copy:1; 215unsigned int is_rename:1; 216unsigned int recount:1; 217unsigned int conflicted_threeway:1; 218unsigned int direct_to_threeway:1; 219unsigned int crlf_in_old:1; 220struct fragment *fragments; 221char*result; 222size_t resultsize; 223char old_sha1_prefix[41]; 224char new_sha1_prefix[41]; 225struct patch *next; 226 227/* three-way fallback result */ 228struct object_id threeway_stage[3]; 229}; 230 231static voidfree_fragment_list(struct fragment *list) 232{ 233while(list) { 234struct fragment *next = list->next; 235if(list->free_patch) 236free((char*)list->patch); 237free(list); 238 list = next; 239} 240} 241 242static voidfree_patch(struct patch *patch) 243{ 244free_fragment_list(patch->fragments); 245free(patch->def_name); 246free(patch->old_name); 247free(patch->new_name); 248free(patch->result); 249free(patch); 250} 251 252static voidfree_patch_list(struct patch *list) 253{ 254while(list) { 255struct patch *next = list->next; 256free_patch(list); 257 list = next; 258} 259} 260 261/* 262 * A line in a file, len-bytes long (includes the terminating LF, 263 * except for an incomplete line at the end if the file ends with 264 * one), and its contents hashes to 'hash'. 265 */ 266struct line { 267size_t len; 268unsigned hash :24; 269unsigned flag :8; 270#define LINE_COMMON 1 271#define LINE_PATCHED 2 272}; 273 274/* 275 * This represents a "file", which is an array of "lines". 276 */ 277struct image { 278char*buf; 279size_t len; 280size_t nr; 281size_t alloc; 282struct line *line_allocated; 283struct line *line; 284}; 285 286static uint32_thash_line(const char*cp,size_t len) 287{ 288size_t i; 289uint32_t h; 290for(i =0, h =0; i < len; i++) { 291if(!isspace(cp[i])) { 292 h = h *3+ (cp[i] &0xff); 293} 294} 295return h; 296} 297 298/* 299 * Compare lines s1 of length n1 and s2 of length n2, ignoring 300 * whitespace difference. Returns 1 if they match, 0 otherwise 301 */ 302static intfuzzy_matchlines(const char*s1,size_t n1, 303const char*s2,size_t n2) 304{ 305const char*end1 = s1 + n1; 306const char*end2 = s2 + n2; 307 308/* ignore line endings */ 309while(s1 < end1 && (end1[-1] =='\r'|| end1[-1] =='\n')) 310 end1--; 311while(s2 < end2 && (end2[-1] =='\r'|| end2[-1] =='\n')) 312 end2--; 313 314while(s1 < end1 && s2 < end2) { 315if(isspace(*s1)) { 316/* 317 * Skip whitespace. We check on both buffers 318 * because we don't want "a b" to match "ab". 319 */ 320if(!isspace(*s2)) 321return0; 322while(s1 < end1 &&isspace(*s1)) 323 s1++; 324while(s2 < end2 &&isspace(*s2)) 325 s2++; 326}else if(*s1++ != *s2++) 327return0; 328} 329 330/* If we reached the end on one side only, lines don't match. */ 331return s1 == end1 && s2 == end2; 332} 333 334static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 335{ 336ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 337 img->line_allocated[img->nr].len = len; 338 img->line_allocated[img->nr].hash =hash_line(bol, len); 339 img->line_allocated[img->nr].flag = flag; 340 img->nr++; 341} 342 343/* 344 * "buf" has the file contents to be patched (read from various sources). 345 * attach it to "image" and add line-based index to it. 346 * "image" now owns the "buf". 347 */ 348static voidprepare_image(struct image *image,char*buf,size_t len, 349int prepare_linetable) 350{ 351const char*cp, *ep; 352 353memset(image,0,sizeof(*image)); 354 image->buf = buf; 355 image->len = len; 356 357if(!prepare_linetable) 358return; 359 360 ep = image->buf + image->len; 361 cp = image->buf; 362while(cp < ep) { 363const char*next; 364for(next = cp; next < ep && *next !='\n'; next++) 365; 366if(next < ep) 367 next++; 368add_line_info(image, cp, next - cp,0); 369 cp = next; 370} 371 image->line = image->line_allocated; 372} 373 374static voidclear_image(struct image *image) 375{ 376free(image->buf); 377free(image->line_allocated); 378memset(image,0,sizeof(*image)); 379} 380 381/* fmt must contain _one_ %s and no other substitution */ 382static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 383{ 384struct strbuf sb = STRBUF_INIT; 385 386if(patch->old_name && patch->new_name && 387strcmp(patch->old_name, patch->new_name)) { 388quote_c_style(patch->old_name, &sb, NULL,0); 389strbuf_addstr(&sb," => "); 390quote_c_style(patch->new_name, &sb, NULL,0); 391}else{ 392const char*n = patch->new_name; 393if(!n) 394 n = patch->old_name; 395quote_c_style(n, &sb, NULL,0); 396} 397fprintf(output, fmt, sb.buf); 398fputc('\n', output); 399strbuf_release(&sb); 400} 401 402#define SLOP (16) 403 404static intread_patch_file(struct strbuf *sb,int fd) 405{ 406if(strbuf_read(sb, fd,0) <0) 407returnerror_errno("git apply: failed to read"); 408 409/* 410 * Make sure that we have some slop in the buffer 411 * so that we can do speculative "memcmp" etc, and 412 * see to it that it is NUL-filled. 413 */ 414strbuf_grow(sb, SLOP); 415memset(sb->buf + sb->len,0, SLOP); 416return0; 417} 418 419static unsigned longlinelen(const char*buffer,unsigned long size) 420{ 421unsigned long len =0; 422while(size--) { 423 len++; 424if(*buffer++ =='\n') 425break; 426} 427return len; 428} 429 430static intis_dev_null(const char*str) 431{ 432returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 433} 434 435#define TERM_SPACE 1 436#define TERM_TAB 2 437 438static intname_terminate(int c,int terminate) 439{ 440if(c ==' '&& !(terminate & TERM_SPACE)) 441return0; 442if(c =='\t'&& !(terminate & TERM_TAB)) 443return0; 444 445return1; 446} 447 448/* remove double slashes to make --index work with such filenames */ 449static char*squash_slash(char*name) 450{ 451int i =0, j =0; 452 453if(!name) 454return NULL; 455 456while(name[i]) { 457if((name[j++] = name[i++]) =='/') 458while(name[i] =='/') 459 i++; 460} 461 name[j] ='\0'; 462return name; 463} 464 465static char*find_name_gnu(struct apply_state *state, 466const char*line, 467const char*def, 468int p_value) 469{ 470struct strbuf name = STRBUF_INIT; 471char*cp; 472 473/* 474 * Proposed "new-style" GNU patch/diff format; see 475 * http://marc.info/?l=git&m=112927316408690&w=2 476 */ 477if(unquote_c_style(&name, line, NULL)) { 478strbuf_release(&name); 479return NULL; 480} 481 482for(cp = name.buf; p_value; p_value--) { 483 cp =strchr(cp,'/'); 484if(!cp) { 485strbuf_release(&name); 486return NULL; 487} 488 cp++; 489} 490 491strbuf_remove(&name,0, cp - name.buf); 492if(state->root.len) 493strbuf_insert(&name,0, state->root.buf, state->root.len); 494returnsquash_slash(strbuf_detach(&name, NULL)); 495} 496 497static size_tsane_tz_len(const char*line,size_t len) 498{ 499const char*tz, *p; 500 501if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 502return0; 503 tz = line + len -strlen(" +0500"); 504 505if(tz[1] !='+'&& tz[1] !='-') 506return0; 507 508for(p = tz +2; p != line + len; p++) 509if(!isdigit(*p)) 510return0; 511 512return line + len - tz; 513} 514 515static size_ttz_with_colon_len(const char*line,size_t len) 516{ 517const char*tz, *p; 518 519if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 520return0; 521 tz = line + len -strlen(" +08:00"); 522 523if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 524return0; 525 p = tz +2; 526if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 527!isdigit(*p++) || !isdigit(*p++)) 528return0; 529 530return line + len - tz; 531} 532 533static size_tdate_len(const char*line,size_t len) 534{ 535const char*date, *p; 536 537if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 538return0; 539 p = date = line + len -strlen("72-02-05"); 540 541if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 542!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 543!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 544return0; 545 546if(date - line >=strlen("19") && 547isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 548 date -=strlen("19"); 549 550return line + len - date; 551} 552 553static size_tshort_time_len(const char*line,size_t len) 554{ 555const char*time, *p; 556 557if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 558return0; 559 p = time = line + len -strlen(" 07:01:32"); 560 561/* Permit 1-digit hours? */ 562if(*p++ !=' '|| 563!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 564!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 565!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 566return0; 567 568return line + len - time; 569} 570 571static size_tfractional_time_len(const char*line,size_t len) 572{ 573const char*p; 574size_t n; 575 576/* Expected format: 19:41:17.620000023 */ 577if(!len || !isdigit(line[len -1])) 578return0; 579 p = line + len -1; 580 581/* Fractional seconds. */ 582while(p > line &&isdigit(*p)) 583 p--; 584if(*p !='.') 585return0; 586 587/* Hours, minutes, and whole seconds. */ 588 n =short_time_len(line, p - line); 589if(!n) 590return0; 591 592return line + len - p + n; 593} 594 595static size_ttrailing_spaces_len(const char*line,size_t len) 596{ 597const char*p; 598 599/* Expected format: ' ' x (1 or more) */ 600if(!len || line[len -1] !=' ') 601return0; 602 603 p = line + len; 604while(p != line) { 605 p--; 606if(*p !=' ') 607return line + len - (p +1); 608} 609 610/* All spaces! */ 611return len; 612} 613 614static size_tdiff_timestamp_len(const char*line,size_t len) 615{ 616const char*end = line + len; 617size_t n; 618 619/* 620 * Posix: 2010-07-05 19:41:17 621 * GNU: 2010-07-05 19:41:17.620000023 -0500 622 */ 623 624if(!isdigit(end[-1])) 625return0; 626 627 n =sane_tz_len(line, end - line); 628if(!n) 629 n =tz_with_colon_len(line, end - line); 630 end -= n; 631 632 n =short_time_len(line, end - line); 633if(!n) 634 n =fractional_time_len(line, end - line); 635 end -= n; 636 637 n =date_len(line, end - line); 638if(!n)/* No date. Too bad. */ 639return0; 640 end -= n; 641 642if(end == line)/* No space before date. */ 643return0; 644if(end[-1] =='\t') {/* Success! */ 645 end--; 646return line + len - end; 647} 648if(end[-1] !=' ')/* No space before date. */ 649return0; 650 651/* Whitespace damage. */ 652 end -=trailing_spaces_len(line, end - line); 653return line + len - end; 654} 655 656static char*find_name_common(struct apply_state *state, 657const char*line, 658const char*def, 659int p_value, 660const char*end, 661int terminate) 662{ 663int len; 664const char*start = NULL; 665 666if(p_value ==0) 667 start = line; 668while(line != end) { 669char c = *line; 670 671if(!end &&isspace(c)) { 672if(c =='\n') 673break; 674if(name_terminate(c, terminate)) 675break; 676} 677 line++; 678if(c =='/'&& !--p_value) 679 start = line; 680} 681if(!start) 682returnsquash_slash(xstrdup_or_null(def)); 683 len = line - start; 684if(!len) 685returnsquash_slash(xstrdup_or_null(def)); 686 687/* 688 * Generally we prefer the shorter name, especially 689 * if the other one is just a variation of that with 690 * something else tacked on to the end (ie "file.orig" 691 * or "file~"). 692 */ 693if(def) { 694int deflen =strlen(def); 695if(deflen < len && !strncmp(start, def, deflen)) 696returnsquash_slash(xstrdup(def)); 697} 698 699if(state->root.len) { 700char*ret =xstrfmt("%s%.*s", state->root.buf, len, start); 701returnsquash_slash(ret); 702} 703 704returnsquash_slash(xmemdupz(start, len)); 705} 706 707static char*find_name(struct apply_state *state, 708const char*line, 709char*def, 710int p_value, 711int terminate) 712{ 713if(*line =='"') { 714char*name =find_name_gnu(state, line, def, p_value); 715if(name) 716return name; 717} 718 719returnfind_name_common(state, line, def, p_value, NULL, terminate); 720} 721 722static char*find_name_traditional(struct apply_state *state, 723const char*line, 724char*def, 725int p_value) 726{ 727size_t len; 728size_t date_len; 729 730if(*line =='"') { 731char*name =find_name_gnu(state, line, def, p_value); 732if(name) 733return name; 734} 735 736 len =strchrnul(line,'\n') - line; 737 date_len =diff_timestamp_len(line, len); 738if(!date_len) 739returnfind_name_common(state, line, def, p_value, NULL, TERM_TAB); 740 len -= date_len; 741 742returnfind_name_common(state, line, def, p_value, line + len,0); 743} 744 745/* 746 * Given the string after "--- " or "+++ ", guess the appropriate 747 * p_value for the given patch. 748 */ 749static intguess_p_value(struct apply_state *state,const char*nameline) 750{ 751char*name, *cp; 752int val = -1; 753 754if(is_dev_null(nameline)) 755return-1; 756 name =find_name_traditional(state, nameline, NULL,0); 757if(!name) 758return-1; 759 cp =strchr(name,'/'); 760if(!cp) 761 val =0; 762else if(state->prefix) { 763/* 764 * Does it begin with "a/$our-prefix" and such? Then this is 765 * very likely to apply to our directory. 766 */ 767if(starts_with(name, state->prefix)) 768 val =count_slashes(state->prefix); 769else{ 770 cp++; 771if(starts_with(cp, state->prefix)) 772 val =count_slashes(state->prefix) +1; 773} 774} 775free(name); 776return val; 777} 778 779/* 780 * Does the ---/+++ line have the POSIX timestamp after the last HT? 781 * GNU diff puts epoch there to signal a creation/deletion event. Is 782 * this such a timestamp? 783 */ 784static inthas_epoch_timestamp(const char*nameline) 785{ 786/* 787 * We are only interested in epoch timestamp; any non-zero 788 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 789 * For the same reason, the date must be either 1969-12-31 or 790 * 1970-01-01, and the seconds part must be "00". 791 */ 792const char stamp_regexp[] = 793"^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?" 794" " 795"([-+][0-2][0-9]:?[0-5][0-9])\n"; 796const char*timestamp = NULL, *cp, *colon; 797static regex_t *stamp; 798 regmatch_t m[10]; 799int zoneoffset, epoch_hour, hour, minute; 800int status; 801 802for(cp = nameline; *cp !='\n'; cp++) { 803if(*cp =='\t') 804 timestamp = cp +1; 805} 806if(!timestamp) 807return0; 808 809/* 810 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 811 * (west of GMT) or 1970-01-01 (east of GMT) 812 */ 813if(skip_prefix(timestamp,"1969-12-31 ", ×tamp)) 814 epoch_hour =24; 815else if(skip_prefix(timestamp,"1970-01-01 ", ×tamp)) 816 epoch_hour =0; 817else 818return0; 819 820if(!stamp) { 821 stamp =xmalloc(sizeof(*stamp)); 822if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 823warning(_("Cannot prepare timestamp regexp%s"), 824 stamp_regexp); 825return0; 826} 827} 828 829 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 830if(status) { 831if(status != REG_NOMATCH) 832warning(_("regexec returned%dfor input:%s"), 833 status, timestamp); 834return0; 835} 836 837 hour =strtol(timestamp, NULL,10); 838 minute =strtol(timestamp + m[1].rm_so, NULL,10); 839 840 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 841if(*colon ==':') 842 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 843else 844 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 845if(timestamp[m[3].rm_so] =='-') 846 zoneoffset = -zoneoffset; 847 848return hour *60+ minute - zoneoffset == epoch_hour *60; 849} 850 851/* 852 * Get the name etc info from the ---/+++ lines of a traditional patch header 853 * 854 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 855 * files, we can happily check the index for a match, but for creating a 856 * new file we should try to match whatever "patch" does. I have no idea. 857 */ 858static intparse_traditional_patch(struct apply_state *state, 859const char*first, 860const char*second, 861struct patch *patch) 862{ 863char*name; 864 865 first +=4;/* skip "--- " */ 866 second +=4;/* skip "+++ " */ 867if(!state->p_value_known) { 868int p, q; 869 p =guess_p_value(state, first); 870 q =guess_p_value(state, second); 871if(p <0) p = q; 872if(0<= p && p == q) { 873 state->p_value = p; 874 state->p_value_known =1; 875} 876} 877if(is_dev_null(first)) { 878 patch->is_new =1; 879 patch->is_delete =0; 880 name =find_name_traditional(state, second, NULL, state->p_value); 881 patch->new_name = name; 882}else if(is_dev_null(second)) { 883 patch->is_new =0; 884 patch->is_delete =1; 885 name =find_name_traditional(state, first, NULL, state->p_value); 886 patch->old_name = name; 887}else{ 888char*first_name; 889 first_name =find_name_traditional(state, first, NULL, state->p_value); 890 name =find_name_traditional(state, second, first_name, state->p_value); 891free(first_name); 892if(has_epoch_timestamp(first)) { 893 patch->is_new =1; 894 patch->is_delete =0; 895 patch->new_name = name; 896}else if(has_epoch_timestamp(second)) { 897 patch->is_new =0; 898 patch->is_delete =1; 899 patch->old_name = name; 900}else{ 901 patch->old_name = name; 902 patch->new_name =xstrdup_or_null(name); 903} 904} 905if(!name) 906returnerror(_("unable to find filename in patch at line%d"), state->linenr); 907 908return0; 909} 910 911static intgitdiff_hdrend(struct apply_state *state, 912const char*line, 913struct patch *patch) 914{ 915return1; 916} 917 918/* 919 * We're anal about diff header consistency, to make 920 * sure that we don't end up having strange ambiguous 921 * patches floating around. 922 * 923 * As a result, gitdiff_{old|new}name() will check 924 * their names against any previous information, just 925 * to make sure.. 926 */ 927#define DIFF_OLD_NAME 0 928#define DIFF_NEW_NAME 1 929 930static intgitdiff_verify_name(struct apply_state *state, 931const char*line, 932int isnull, 933char**name, 934int side) 935{ 936if(!*name && !isnull) { 937*name =find_name(state, line, NULL, state->p_value, TERM_TAB); 938return0; 939} 940 941if(*name) { 942char*another; 943if(isnull) 944returnerror(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 945*name, state->linenr); 946 another =find_name(state, line, NULL, state->p_value, TERM_TAB); 947if(!another ||strcmp(another, *name)) { 948free(another); 949returnerror((side == DIFF_NEW_NAME) ? 950_("git apply: bad git-diff - inconsistent new filename on line%d") : 951_("git apply: bad git-diff - inconsistent old filename on line%d"), state->linenr); 952} 953free(another); 954}else{ 955if(!is_dev_null(line)) 956returnerror(_("git apply: bad git-diff - expected /dev/null on line%d"), state->linenr); 957} 958 959return0; 960} 961 962static intgitdiff_oldname(struct apply_state *state, 963const char*line, 964struct patch *patch) 965{ 966returngitdiff_verify_name(state, line, 967 patch->is_new, &patch->old_name, 968 DIFF_OLD_NAME); 969} 970 971static intgitdiff_newname(struct apply_state *state, 972const char*line, 973struct patch *patch) 974{ 975returngitdiff_verify_name(state, line, 976 patch->is_delete, &patch->new_name, 977 DIFF_NEW_NAME); 978} 979 980static intparse_mode_line(const char*line,int linenr,unsigned int*mode) 981{ 982char*end; 983*mode =strtoul(line, &end,8); 984if(end == line || !isspace(*end)) 985returnerror(_("invalid mode on line%d:%s"), linenr, line); 986return0; 987} 988 989static intgitdiff_oldmode(struct apply_state *state, 990const char*line, 991struct patch *patch) 992{ 993returnparse_mode_line(line, state->linenr, &patch->old_mode); 994} 995 996static intgitdiff_newmode(struct apply_state *state, 997const char*line, 998struct patch *patch) 999{1000returnparse_mode_line(line, state->linenr, &patch->new_mode);1001}10021003static intgitdiff_delete(struct apply_state *state,1004const char*line,1005struct patch *patch)1006{1007 patch->is_delete =1;1008free(patch->old_name);1009 patch->old_name =xstrdup_or_null(patch->def_name);1010returngitdiff_oldmode(state, line, patch);1011}10121013static intgitdiff_newfile(struct apply_state *state,1014const char*line,1015struct patch *patch)1016{1017 patch->is_new =1;1018free(patch->new_name);1019 patch->new_name =xstrdup_or_null(patch->def_name);1020returngitdiff_newmode(state, line, patch);1021}10221023static intgitdiff_copysrc(struct apply_state *state,1024const char*line,1025struct patch *patch)1026{1027 patch->is_copy =1;1028free(patch->old_name);1029 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1030return0;1031}10321033static intgitdiff_copydst(struct apply_state *state,1034const char*line,1035struct patch *patch)1036{1037 patch->is_copy =1;1038free(patch->new_name);1039 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1040return0;1041}10421043static intgitdiff_renamesrc(struct apply_state *state,1044const char*line,1045struct patch *patch)1046{1047 patch->is_rename =1;1048free(patch->old_name);1049 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1050return0;1051}10521053static intgitdiff_renamedst(struct apply_state *state,1054const char*line,1055struct patch *patch)1056{1057 patch->is_rename =1;1058free(patch->new_name);1059 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1060return0;1061}10621063static intgitdiff_similarity(struct apply_state *state,1064const char*line,1065struct patch *patch)1066{1067unsigned long val =strtoul(line, NULL,10);1068if(val <=100)1069 patch->score = val;1070return0;1071}10721073static intgitdiff_dissimilarity(struct apply_state *state,1074const char*line,1075struct patch *patch)1076{1077unsigned long val =strtoul(line, NULL,10);1078if(val <=100)1079 patch->score = val;1080return0;1081}10821083static intgitdiff_index(struct apply_state *state,1084const char*line,1085struct patch *patch)1086{1087/*1088 * index line is N hexadecimal, "..", N hexadecimal,1089 * and optional space with octal mode.1090 */1091const char*ptr, *eol;1092int len;10931094 ptr =strchr(line,'.');1095if(!ptr || ptr[1] !='.'||40< ptr - line)1096return0;1097 len = ptr - line;1098memcpy(patch->old_sha1_prefix, line, len);1099 patch->old_sha1_prefix[len] =0;11001101 line = ptr +2;1102 ptr =strchr(line,' ');1103 eol =strchrnul(line,'\n');11041105if(!ptr || eol < ptr)1106 ptr = eol;1107 len = ptr - line;11081109if(40< len)1110return0;1111memcpy(patch->new_sha1_prefix, line, len);1112 patch->new_sha1_prefix[len] =0;1113if(*ptr ==' ')1114returngitdiff_oldmode(state, ptr +1, patch);1115return0;1116}11171118/*1119 * This is normal for a diff that doesn't change anything: we'll fall through1120 * into the next diff. Tell the parser to break out.1121 */1122static intgitdiff_unrecognized(struct apply_state *state,1123const char*line,1124struct patch *patch)1125{1126return1;1127}11281129/*1130 * Skip p_value leading components from "line"; as we do not accept1131 * absolute paths, return NULL in that case.1132 */1133static const char*skip_tree_prefix(struct apply_state *state,1134const char*line,1135int llen)1136{1137int nslash;1138int i;11391140if(!state->p_value)1141return(llen && line[0] =='/') ? NULL : line;11421143 nslash = state->p_value;1144for(i =0; i < llen; i++) {1145int ch = line[i];1146if(ch =='/'&& --nslash <=0)1147return(i ==0) ? NULL : &line[i +1];1148}1149return NULL;1150}11511152/*1153 * This is to extract the same name that appears on "diff --git"1154 * line. We do not find and return anything if it is a rename1155 * patch, and it is OK because we will find the name elsewhere.1156 * We need to reliably find name only when it is mode-change only,1157 * creation or deletion of an empty file. In any of these cases,1158 * both sides are the same name under a/ and b/ respectively.1159 */1160static char*git_header_name(struct apply_state *state,1161const char*line,1162int llen)1163{1164const char*name;1165const char*second = NULL;1166size_t len, line_len;11671168 line +=strlen("diff --git ");1169 llen -=strlen("diff --git ");11701171if(*line =='"') {1172const char*cp;1173struct strbuf first = STRBUF_INIT;1174struct strbuf sp = STRBUF_INIT;11751176if(unquote_c_style(&first, line, &second))1177goto free_and_fail1;11781179/* strip the a/b prefix including trailing slash */1180 cp =skip_tree_prefix(state, first.buf, first.len);1181if(!cp)1182goto free_and_fail1;1183strbuf_remove(&first,0, cp - first.buf);11841185/*1186 * second points at one past closing dq of name.1187 * find the second name.1188 */1189while((second < line + llen) &&isspace(*second))1190 second++;11911192if(line + llen <= second)1193goto free_and_fail1;1194if(*second =='"') {1195if(unquote_c_style(&sp, second, NULL))1196goto free_and_fail1;1197 cp =skip_tree_prefix(state, sp.buf, sp.len);1198if(!cp)1199goto free_and_fail1;1200/* They must match, otherwise ignore */1201if(strcmp(cp, first.buf))1202goto free_and_fail1;1203strbuf_release(&sp);1204returnstrbuf_detach(&first, NULL);1205}12061207/* unquoted second */1208 cp =skip_tree_prefix(state, second, line + llen - second);1209if(!cp)1210goto free_and_fail1;1211if(line + llen - cp != first.len ||1212memcmp(first.buf, cp, first.len))1213goto free_and_fail1;1214returnstrbuf_detach(&first, NULL);12151216 free_and_fail1:1217strbuf_release(&first);1218strbuf_release(&sp);1219return NULL;1220}12211222/* unquoted first name */1223 name =skip_tree_prefix(state, line, llen);1224if(!name)1225return NULL;12261227/*1228 * since the first name is unquoted, a dq if exists must be1229 * the beginning of the second name.1230 */1231for(second = name; second < line + llen; second++) {1232if(*second =='"') {1233struct strbuf sp = STRBUF_INIT;1234const char*np;12351236if(unquote_c_style(&sp, second, NULL))1237goto free_and_fail2;12381239 np =skip_tree_prefix(state, sp.buf, sp.len);1240if(!np)1241goto free_and_fail2;12421243 len = sp.buf + sp.len - np;1244if(len < second - name &&1245!strncmp(np, name, len) &&1246isspace(name[len])) {1247/* Good */1248strbuf_remove(&sp,0, np - sp.buf);1249returnstrbuf_detach(&sp, NULL);1250}12511252 free_and_fail2:1253strbuf_release(&sp);1254return NULL;1255}1256}12571258/*1259 * Accept a name only if it shows up twice, exactly the same1260 * form.1261 */1262 second =strchr(name,'\n');1263if(!second)1264return NULL;1265 line_len = second - name;1266for(len =0; ; len++) {1267switch(name[len]) {1268default:1269continue;1270case'\n':1271return NULL;1272case'\t':case' ':1273/*1274 * Is this the separator between the preimage1275 * and the postimage pathname? Again, we are1276 * only interested in the case where there is1277 * no rename, as this is only to set def_name1278 * and a rename patch has the names elsewhere1279 * in an unambiguous form.1280 */1281if(!name[len +1])1282return NULL;/* no postimage name */1283 second =skip_tree_prefix(state, name + len +1,1284 line_len - (len +1));1285if(!second)1286return NULL;1287/*1288 * Does len bytes starting at "name" and "second"1289 * (that are separated by one HT or SP we just1290 * found) exactly match?1291 */1292if(second[len] =='\n'&& !strncmp(name, second, len))1293returnxmemdupz(name, len);1294}1295}1296}12971298static intcheck_header_line(struct apply_state *state,struct patch *patch)1299{1300int extensions = (patch->is_delete ==1) + (patch->is_new ==1) +1301(patch->is_rename ==1) + (patch->is_copy ==1);1302if(extensions >1)1303returnerror(_("inconsistent header lines%dand%d"),1304 patch->extension_linenr, state->linenr);1305if(extensions && !patch->extension_linenr)1306 patch->extension_linenr = state->linenr;1307return0;1308}13091310/* Verify that we recognize the lines following a git header */1311static intparse_git_header(struct apply_state *state,1312const char*line,1313int len,1314unsigned int size,1315struct patch *patch)1316{1317unsigned long offset;13181319/* A git diff has explicit new/delete information, so we don't guess */1320 patch->is_new =0;1321 patch->is_delete =0;13221323/*1324 * Some things may not have the old name in the1325 * rest of the headers anywhere (pure mode changes,1326 * or removing or adding empty files), so we get1327 * the default name from the header.1328 */1329 patch->def_name =git_header_name(state, line, len);1330if(patch->def_name && state->root.len) {1331char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1332free(patch->def_name);1333 patch->def_name = s;1334}13351336 line += len;1337 size -= len;1338 state->linenr++;1339for(offset = len ; size >0; offset += len, size -= len, line += len, state->linenr++) {1340static const struct opentry {1341const char*str;1342int(*fn)(struct apply_state *,const char*,struct patch *);1343} optable[] = {1344{"@@ -", gitdiff_hdrend },1345{"--- ", gitdiff_oldname },1346{"+++ ", gitdiff_newname },1347{"old mode ", gitdiff_oldmode },1348{"new mode ", gitdiff_newmode },1349{"deleted file mode ", gitdiff_delete },1350{"new file mode ", gitdiff_newfile },1351{"copy from ", gitdiff_copysrc },1352{"copy to ", gitdiff_copydst },1353{"rename old ", gitdiff_renamesrc },1354{"rename new ", gitdiff_renamedst },1355{"rename from ", gitdiff_renamesrc },1356{"rename to ", gitdiff_renamedst },1357{"similarity index ", gitdiff_similarity },1358{"dissimilarity index ", gitdiff_dissimilarity },1359{"index ", gitdiff_index },1360{"", gitdiff_unrecognized },1361};1362int i;13631364 len =linelen(line, size);1365if(!len || line[len-1] !='\n')1366break;1367for(i =0; i <ARRAY_SIZE(optable); i++) {1368const struct opentry *p = optable + i;1369int oplen =strlen(p->str);1370int res;1371if(len < oplen ||memcmp(p->str, line, oplen))1372continue;1373 res = p->fn(state, line + oplen, patch);1374if(res <0)1375return-1;1376if(check_header_line(state, patch))1377return-1;1378if(res >0)1379return offset;1380break;1381}1382}13831384return offset;1385}13861387static intparse_num(const char*line,unsigned long*p)1388{1389char*ptr;13901391if(!isdigit(*line))1392return0;1393*p =strtoul(line, &ptr,10);1394return ptr - line;1395}13961397static intparse_range(const char*line,int len,int offset,const char*expect,1398unsigned long*p1,unsigned long*p2)1399{1400int digits, ex;14011402if(offset <0|| offset >= len)1403return-1;1404 line += offset;1405 len -= offset;14061407 digits =parse_num(line, p1);1408if(!digits)1409return-1;14101411 offset += digits;1412 line += digits;1413 len -= digits;14141415*p2 =1;1416if(*line ==',') {1417 digits =parse_num(line+1, p2);1418if(!digits)1419return-1;14201421 offset += digits+1;1422 line += digits+1;1423 len -= digits+1;1424}14251426 ex =strlen(expect);1427if(ex > len)1428return-1;1429if(memcmp(line, expect, ex))1430return-1;14311432return offset + ex;1433}14341435static voidrecount_diff(const char*line,int size,struct fragment *fragment)1436{1437int oldlines =0, newlines =0, ret =0;14381439if(size <1) {1440warning("recount: ignore empty hunk");1441return;1442}14431444for(;;) {1445int len =linelen(line, size);1446 size -= len;1447 line += len;14481449if(size <1)1450break;14511452switch(*line) {1453case' ':case'\n':1454 newlines++;1455/* fall through */1456case'-':1457 oldlines++;1458continue;1459case'+':1460 newlines++;1461continue;1462case'\\':1463continue;1464case'@':1465 ret = size <3|| !starts_with(line,"@@ ");1466break;1467case'd':1468 ret = size <5|| !starts_with(line,"diff ");1469break;1470default:1471 ret = -1;1472break;1473}1474if(ret) {1475warning(_("recount: unexpected line: %.*s"),1476(int)linelen(line, size), line);1477return;1478}1479break;1480}1481 fragment->oldlines = oldlines;1482 fragment->newlines = newlines;1483}14841485/*1486 * Parse a unified diff fragment header of the1487 * form "@@ -a,b +c,d @@"1488 */1489static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1490{1491int offset;14921493if(!len || line[len-1] !='\n')1494return-1;14951496/* Figure out the number of lines in a fragment */1497 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1498 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14991500return offset;1501}15021503/*1504 * Find file diff header1505 *1506 * Returns:1507 * -1 if no header was found1508 * -128 in case of error1509 * the size of the header in bytes (called "offset") otherwise1510 */1511static intfind_header(struct apply_state *state,1512const char*line,1513unsigned long size,1514int*hdrsize,1515struct patch *patch)1516{1517unsigned long offset, len;15181519 patch->is_toplevel_relative =0;1520 patch->is_rename = patch->is_copy =0;1521 patch->is_new = patch->is_delete = -1;1522 patch->old_mode = patch->new_mode =0;1523 patch->old_name = patch->new_name = NULL;1524for(offset =0; size >0; offset += len, size -= len, line += len, state->linenr++) {1525unsigned long nextlen;15261527 len =linelen(line, size);1528if(!len)1529break;15301531/* Testing this early allows us to take a few shortcuts.. */1532if(len <6)1533continue;15341535/*1536 * Make sure we don't find any unconnected patch fragments.1537 * That's a sign that we didn't find a header, and that a1538 * patch has become corrupted/broken up.1539 */1540if(!memcmp("@@ -", line,4)) {1541struct fragment dummy;1542if(parse_fragment_header(line, len, &dummy) <0)1543continue;1544error(_("patch fragment without header at line%d: %.*s"),1545 state->linenr, (int)len-1, line);1546return-128;1547}15481549if(size < len +6)1550break;15511552/*1553 * Git patch? It might not have a real patch, just a rename1554 * or mode change, so we handle that specially1555 */1556if(!memcmp("diff --git ", line,11)) {1557int git_hdr_len =parse_git_header(state, line, len, size, patch);1558if(git_hdr_len <0)1559return-128;1560if(git_hdr_len <= len)1561continue;1562if(!patch->old_name && !patch->new_name) {1563if(!patch->def_name) {1564error(Q_("git diff header lacks filename information when removing "1565"%dleading pathname component (line%d)",1566"git diff header lacks filename information when removing "1567"%dleading pathname components (line%d)",1568 state->p_value),1569 state->p_value, state->linenr);1570return-128;1571}1572 patch->old_name =xstrdup(patch->def_name);1573 patch->new_name =xstrdup(patch->def_name);1574}1575if((!patch->new_name && !patch->is_delete) ||1576(!patch->old_name && !patch->is_new)) {1577error(_("git diff header lacks filename information "1578"(line%d)"), state->linenr);1579return-128;1580}1581 patch->is_toplevel_relative =1;1582*hdrsize = git_hdr_len;1583return offset;1584}15851586/* --- followed by +++ ? */1587if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1588continue;15891590/*1591 * We only accept unified patches, so we want it to1592 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1593 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1594 */1595 nextlen =linelen(line + len, size - len);1596if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1597continue;15981599/* Ok, we'll consider it a patch */1600if(parse_traditional_patch(state, line, line+len, patch))1601return-128;1602*hdrsize = len + nextlen;1603 state->linenr +=2;1604return offset;1605}1606return-1;1607}16081609static voidrecord_ws_error(struct apply_state *state,1610unsigned result,1611const char*line,1612int len,1613int linenr)1614{1615char*err;16161617if(!result)1618return;16191620 state->whitespace_error++;1621if(state->squelch_whitespace_errors &&1622 state->squelch_whitespace_errors < state->whitespace_error)1623return;16241625 err =whitespace_error_string(result);1626if(state->apply_verbosity > verbosity_silent)1627fprintf(stderr,"%s:%d:%s.\n%.*s\n",1628 state->patch_input_file, linenr, err, len, line);1629free(err);1630}16311632static voidcheck_whitespace(struct apply_state *state,1633const char*line,1634int len,1635unsigned ws_rule)1636{1637unsigned result =ws_check(line +1, len -1, ws_rule);16381639record_ws_error(state, result, line +1, len -2, state->linenr);1640}16411642/*1643 * Check if the patch has context lines with CRLF or1644 * the patch wants to remove lines with CRLF.1645 */1646static voidcheck_old_for_crlf(struct patch *patch,const char*line,int len)1647{1648if(len >=2&& line[len-1] =='\n'&& line[len-2] =='\r') {1649 patch->ws_rule |= WS_CR_AT_EOL;1650 patch->crlf_in_old =1;1651}1652}165316541655/*1656 * Parse a unified diff. Note that this really needs to parse each1657 * fragment separately, since the only way to know the difference1658 * between a "---" that is part of a patch, and a "---" that starts1659 * the next patch is to look at the line counts..1660 */1661static intparse_fragment(struct apply_state *state,1662const char*line,1663unsigned long size,1664struct patch *patch,1665struct fragment *fragment)1666{1667int added, deleted;1668int len =linelen(line, size), offset;1669unsigned long oldlines, newlines;1670unsigned long leading, trailing;16711672 offset =parse_fragment_header(line, len, fragment);1673if(offset <0)1674return-1;1675if(offset >0&& patch->recount)1676recount_diff(line + offset, size - offset, fragment);1677 oldlines = fragment->oldlines;1678 newlines = fragment->newlines;1679 leading =0;1680 trailing =0;16811682/* Parse the thing.. */1683 line += len;1684 size -= len;1685 state->linenr++;1686 added = deleted =0;1687for(offset = len;16880< size;1689 offset += len, size -= len, line += len, state->linenr++) {1690if(!oldlines && !newlines)1691break;1692 len =linelen(line, size);1693if(!len || line[len-1] !='\n')1694return-1;1695switch(*line) {1696default:1697return-1;1698case'\n':/* newer GNU diff, an empty context line */1699case' ':1700 oldlines--;1701 newlines--;1702if(!deleted && !added)1703 leading++;1704 trailing++;1705check_old_for_crlf(patch, line, len);1706if(!state->apply_in_reverse &&1707 state->ws_error_action == correct_ws_error)1708check_whitespace(state, line, len, patch->ws_rule);1709break;1710case'-':1711if(!state->apply_in_reverse)1712check_old_for_crlf(patch, line, len);1713if(state->apply_in_reverse &&1714 state->ws_error_action != nowarn_ws_error)1715check_whitespace(state, line, len, patch->ws_rule);1716 deleted++;1717 oldlines--;1718 trailing =0;1719break;1720case'+':1721if(state->apply_in_reverse)1722check_old_for_crlf(patch, line, len);1723if(!state->apply_in_reverse &&1724 state->ws_error_action != nowarn_ws_error)1725check_whitespace(state, line, len, patch->ws_rule);1726 added++;1727 newlines--;1728 trailing =0;1729break;17301731/*1732 * We allow "\ No newline at end of file". Depending1733 * on locale settings when the patch was produced we1734 * don't know what this line looks like. The only1735 * thing we do know is that it begins with "\ ".1736 * Checking for 12 is just for sanity check -- any1737 * l10n of "\ No newline..." is at least that long.1738 */1739case'\\':1740if(len <12||memcmp(line,"\\",2))1741return-1;1742break;1743}1744}1745if(oldlines || newlines)1746return-1;1747if(!deleted && !added)1748return-1;17491750 fragment->leading = leading;1751 fragment->trailing = trailing;17521753/*1754 * If a fragment ends with an incomplete line, we failed to include1755 * it in the above loop because we hit oldlines == newlines == 01756 * before seeing it.1757 */1758if(12< size && !memcmp(line,"\\",2))1759 offset +=linelen(line, size);17601761 patch->lines_added += added;1762 patch->lines_deleted += deleted;17631764if(0< patch->is_new && oldlines)1765returnerror(_("new file depends on old contents"));1766if(0< patch->is_delete && newlines)1767returnerror(_("deleted file still has contents"));1768return offset;1769}17701771/*1772 * We have seen "diff --git a/... b/..." header (or a traditional patch1773 * header). Read hunks that belong to this patch into fragments and hang1774 * them to the given patch structure.1775 *1776 * The (fragment->patch, fragment->size) pair points into the memory given1777 * by the caller, not a copy, when we return.1778 *1779 * Returns:1780 * -1 in case of error,1781 * the number of bytes in the patch otherwise.1782 */1783static intparse_single_patch(struct apply_state *state,1784const char*line,1785unsigned long size,1786struct patch *patch)1787{1788unsigned long offset =0;1789unsigned long oldlines =0, newlines =0, context =0;1790struct fragment **fragp = &patch->fragments;17911792while(size >4&& !memcmp(line,"@@ -",4)) {1793struct fragment *fragment;1794int len;17951796 fragment =xcalloc(1,sizeof(*fragment));1797 fragment->linenr = state->linenr;1798 len =parse_fragment(state, line, size, patch, fragment);1799if(len <=0) {1800free(fragment);1801returnerror(_("corrupt patch at line%d"), state->linenr);1802}1803 fragment->patch = line;1804 fragment->size = len;1805 oldlines += fragment->oldlines;1806 newlines += fragment->newlines;1807 context += fragment->leading + fragment->trailing;18081809*fragp = fragment;1810 fragp = &fragment->next;18111812 offset += len;1813 line += len;1814 size -= len;1815}18161817/*1818 * If something was removed (i.e. we have old-lines) it cannot1819 * be creation, and if something was added it cannot be1820 * deletion. However, the reverse is not true; --unified=01821 * patches that only add are not necessarily creation even1822 * though they do not have any old lines, and ones that only1823 * delete are not necessarily deletion.1824 *1825 * Unfortunately, a real creation/deletion patch do _not_ have1826 * any context line by definition, so we cannot safely tell it1827 * apart with --unified=0 insanity. At least if the patch has1828 * more than one hunk it is not creation or deletion.1829 */1830if(patch->is_new <0&&1831(oldlines || (patch->fragments && patch->fragments->next)))1832 patch->is_new =0;1833if(patch->is_delete <0&&1834(newlines || (patch->fragments && patch->fragments->next)))1835 patch->is_delete =0;18361837if(0< patch->is_new && oldlines)1838returnerror(_("new file%sdepends on old contents"), patch->new_name);1839if(0< patch->is_delete && newlines)1840returnerror(_("deleted file%sstill has contents"), patch->old_name);1841if(!patch->is_delete && !newlines && context && state->apply_verbosity > verbosity_silent)1842fprintf_ln(stderr,1843_("** warning: "1844"file%sbecomes empty but is not deleted"),1845 patch->new_name);18461847return offset;1848}18491850staticinlineintmetadata_changes(struct patch *patch)1851{1852return patch->is_rename >0||1853 patch->is_copy >0||1854 patch->is_new >0||1855 patch->is_delete ||1856(patch->old_mode && patch->new_mode &&1857 patch->old_mode != patch->new_mode);1858}18591860static char*inflate_it(const void*data,unsigned long size,1861unsigned long inflated_size)1862{1863 git_zstream stream;1864void*out;1865int st;18661867memset(&stream,0,sizeof(stream));18681869 stream.next_in = (unsigned char*)data;1870 stream.avail_in = size;1871 stream.next_out = out =xmalloc(inflated_size);1872 stream.avail_out = inflated_size;1873git_inflate_init(&stream);1874 st =git_inflate(&stream, Z_FINISH);1875git_inflate_end(&stream);1876if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1877free(out);1878return NULL;1879}1880return out;1881}18821883/*1884 * Read a binary hunk and return a new fragment; fragment->patch1885 * points at an allocated memory that the caller must free, so1886 * it is marked as "->free_patch = 1".1887 */1888static struct fragment *parse_binary_hunk(struct apply_state *state,1889char**buf_p,1890unsigned long*sz_p,1891int*status_p,1892int*used_p)1893{1894/*1895 * Expect a line that begins with binary patch method ("literal"1896 * or "delta"), followed by the length of data before deflating.1897 * a sequence of 'length-byte' followed by base-85 encoded data1898 * should follow, terminated by a newline.1899 *1900 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1901 * and we would limit the patch line to 66 characters,1902 * so one line can fit up to 13 groups that would decode1903 * to 52 bytes max. The length byte 'A'-'Z' corresponds1904 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1905 */1906int llen, used;1907unsigned long size = *sz_p;1908char*buffer = *buf_p;1909int patch_method;1910unsigned long origlen;1911char*data = NULL;1912int hunk_size =0;1913struct fragment *frag;19141915 llen =linelen(buffer, size);1916 used = llen;19171918*status_p =0;19191920if(starts_with(buffer,"delta ")) {1921 patch_method = BINARY_DELTA_DEFLATED;1922 origlen =strtoul(buffer +6, NULL,10);1923}1924else if(starts_with(buffer,"literal ")) {1925 patch_method = BINARY_LITERAL_DEFLATED;1926 origlen =strtoul(buffer +8, NULL,10);1927}1928else1929return NULL;19301931 state->linenr++;1932 buffer += llen;1933while(1) {1934int byte_length, max_byte_length, newsize;1935 llen =linelen(buffer, size);1936 used += llen;1937 state->linenr++;1938if(llen ==1) {1939/* consume the blank line */1940 buffer++;1941 size--;1942break;1943}1944/*1945 * Minimum line is "A00000\n" which is 7-byte long,1946 * and the line length must be multiple of 5 plus 2.1947 */1948if((llen <7) || (llen-2) %5)1949goto corrupt;1950 max_byte_length = (llen -2) /5*4;1951 byte_length = *buffer;1952if('A'<= byte_length && byte_length <='Z')1953 byte_length = byte_length -'A'+1;1954else if('a'<= byte_length && byte_length <='z')1955 byte_length = byte_length -'a'+27;1956else1957goto corrupt;1958/* if the input length was not multiple of 4, we would1959 * have filler at the end but the filler should never1960 * exceed 3 bytes1961 */1962if(max_byte_length < byte_length ||1963 byte_length <= max_byte_length -4)1964goto corrupt;1965 newsize = hunk_size + byte_length;1966 data =xrealloc(data, newsize);1967if(decode_85(data + hunk_size, buffer +1, byte_length))1968goto corrupt;1969 hunk_size = newsize;1970 buffer += llen;1971 size -= llen;1972}19731974 frag =xcalloc(1,sizeof(*frag));1975 frag->patch =inflate_it(data, hunk_size, origlen);1976 frag->free_patch =1;1977if(!frag->patch)1978goto corrupt;1979free(data);1980 frag->size = origlen;1981*buf_p = buffer;1982*sz_p = size;1983*used_p = used;1984 frag->binary_patch_method = patch_method;1985return frag;19861987 corrupt:1988free(data);1989*status_p = -1;1990error(_("corrupt binary patch at line%d: %.*s"),1991 state->linenr-1, llen-1, buffer);1992return NULL;1993}19941995/*1996 * Returns:1997 * -1 in case of error,1998 * the length of the parsed binary patch otherwise1999 */2000static intparse_binary(struct apply_state *state,2001char*buffer,2002unsigned long size,2003struct patch *patch)2004{2005/*2006 * We have read "GIT binary patch\n"; what follows is a line2007 * that says the patch method (currently, either "literal" or2008 * "delta") and the length of data before deflating; a2009 * sequence of 'length-byte' followed by base-85 encoded data2010 * follows.2011 *2012 * When a binary patch is reversible, there is another binary2013 * hunk in the same format, starting with patch method (either2014 * "literal" or "delta") with the length of data, and a sequence2015 * of length-byte + base-85 encoded data, terminated with another2016 * empty line. This data, when applied to the postimage, produces2017 * the preimage.2018 */2019struct fragment *forward;2020struct fragment *reverse;2021int status;2022int used, used_1;20232024 forward =parse_binary_hunk(state, &buffer, &size, &status, &used);2025if(!forward && !status)2026/* there has to be one hunk (forward hunk) */2027returnerror(_("unrecognized binary patch at line%d"), state->linenr-1);2028if(status)2029/* otherwise we already gave an error message */2030return status;20312032 reverse =parse_binary_hunk(state, &buffer, &size, &status, &used_1);2033if(reverse)2034 used += used_1;2035else if(status) {2036/*2037 * Not having reverse hunk is not an error, but having2038 * a corrupt reverse hunk is.2039 */2040free((void*) forward->patch);2041free(forward);2042return status;2043}2044 forward->next = reverse;2045 patch->fragments = forward;2046 patch->is_binary =1;2047return used;2048}20492050static voidprefix_one(struct apply_state *state,char**name)2051{2052char*old_name = *name;2053if(!old_name)2054return;2055*name =prefix_filename(state->prefix, *name);2056free(old_name);2057}20582059static voidprefix_patch(struct apply_state *state,struct patch *p)2060{2061if(!state->prefix || p->is_toplevel_relative)2062return;2063prefix_one(state, &p->new_name);2064prefix_one(state, &p->old_name);2065}20662067/*2068 * include/exclude2069 */20702071static voidadd_name_limit(struct apply_state *state,2072const char*name,2073int exclude)2074{2075struct string_list_item *it;20762077 it =string_list_append(&state->limit_by_name, name);2078 it->util = exclude ? NULL : (void*)1;2079}20802081static intuse_patch(struct apply_state *state,struct patch *p)2082{2083const char*pathname = p->new_name ? p->new_name : p->old_name;2084int i;20852086/* Paths outside are not touched regardless of "--include" */2087if(state->prefix && *state->prefix) {2088const char*rest;2089if(!skip_prefix(pathname, state->prefix, &rest) || !*rest)2090return0;2091}20922093/* See if it matches any of exclude/include rule */2094for(i =0; i < state->limit_by_name.nr; i++) {2095struct string_list_item *it = &state->limit_by_name.items[i];2096if(!wildmatch(it->string, pathname,0))2097return(it->util != NULL);2098}20992100/*2101 * If we had any include, a path that does not match any rule is2102 * not used. Otherwise, we saw bunch of exclude rules (or none)2103 * and such a path is used.2104 */2105return!state->has_include;2106}21072108/*2109 * Read the patch text in "buffer" that extends for "size" bytes; stop2110 * reading after seeing a single patch (i.e. changes to a single file).2111 * Create fragments (i.e. patch hunks) and hang them to the given patch.2112 *2113 * Returns:2114 * -1 if no header was found or parse_binary() failed,2115 * -128 on another error,2116 * the number of bytes consumed otherwise,2117 * so that the caller can call us again for the next patch.2118 */2119static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2120{2121int hdrsize, patchsize;2122int offset =find_header(state, buffer, size, &hdrsize, patch);21232124if(offset <0)2125return offset;21262127prefix_patch(state, patch);21282129if(!use_patch(state, patch))2130 patch->ws_rule =0;2131else2132 patch->ws_rule =whitespace_rule(patch->new_name2133? patch->new_name2134: patch->old_name);21352136 patchsize =parse_single_patch(state,2137 buffer + offset + hdrsize,2138 size - offset - hdrsize,2139 patch);21402141if(patchsize <0)2142return-128;21432144if(!patchsize) {2145static const char git_binary[] ="GIT binary patch\n";2146int hd = hdrsize + offset;2147unsigned long llen =linelen(buffer + hd, size - hd);21482149if(llen ==sizeof(git_binary) -1&&2150!memcmp(git_binary, buffer + hd, llen)) {2151int used;2152 state->linenr++;2153 used =parse_binary(state, buffer + hd + llen,2154 size - hd - llen, patch);2155if(used <0)2156return-1;2157if(used)2158 patchsize = used + llen;2159else2160 patchsize =0;2161}2162else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2163static const char*binhdr[] = {2164"Binary files ",2165"Files ",2166 NULL,2167};2168int i;2169for(i =0; binhdr[i]; i++) {2170int len =strlen(binhdr[i]);2171if(len < size - hd &&2172!memcmp(binhdr[i], buffer + hd, len)) {2173 state->linenr++;2174 patch->is_binary =1;2175 patchsize = llen;2176break;2177}2178}2179}21802181/* Empty patch cannot be applied if it is a text patch2182 * without metadata change. A binary patch appears2183 * empty to us here.2184 */2185if((state->apply || state->check) &&2186(!patch->is_binary && !metadata_changes(patch))) {2187error(_("patch with only garbage at line%d"), state->linenr);2188return-128;2189}2190}21912192return offset + hdrsize + patchsize;2193}21942195static voidreverse_patches(struct patch *p)2196{2197for(; p; p = p->next) {2198struct fragment *frag = p->fragments;21992200SWAP(p->new_name, p->old_name);2201SWAP(p->new_mode, p->old_mode);2202SWAP(p->is_new, p->is_delete);2203SWAP(p->lines_added, p->lines_deleted);2204SWAP(p->old_sha1_prefix, p->new_sha1_prefix);22052206for(; frag; frag = frag->next) {2207SWAP(frag->newpos, frag->oldpos);2208SWAP(frag->newlines, frag->oldlines);2209}2210}2211}22122213static const char pluses[] =2214"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2215static const char minuses[]=2216"----------------------------------------------------------------------";22172218static voidshow_stats(struct apply_state *state,struct patch *patch)2219{2220struct strbuf qname = STRBUF_INIT;2221char*cp = patch->new_name ? patch->new_name : patch->old_name;2222int max, add, del;22232224quote_c_style(cp, &qname, NULL,0);22252226/*2227 * "scale" the filename2228 */2229 max = state->max_len;2230if(max >50)2231 max =50;22322233if(qname.len > max) {2234 cp =strchr(qname.buf + qname.len +3- max,'/');2235if(!cp)2236 cp = qname.buf + qname.len +3- max;2237strbuf_splice(&qname,0, cp - qname.buf,"...",3);2238}22392240if(patch->is_binary) {2241printf(" %-*s | Bin\n", max, qname.buf);2242strbuf_release(&qname);2243return;2244}22452246printf(" %-*s |", max, qname.buf);2247strbuf_release(&qname);22482249/*2250 * scale the add/delete2251 */2252 max = max + state->max_change >70?70- max : state->max_change;2253 add = patch->lines_added;2254 del = patch->lines_deleted;22552256if(state->max_change >0) {2257int total = ((add + del) * max + state->max_change /2) / state->max_change;2258 add = (add * max + state->max_change /2) / state->max_change;2259 del = total - add;2260}2261printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2262 add, pluses, del, minuses);2263}22642265static intread_old_data(struct stat *st,struct patch *patch,2266const char*path,struct strbuf *buf)2267{2268int conv_flags = patch->crlf_in_old ?2269 CONV_EOL_KEEP_CRLF : CONV_EOL_RENORMALIZE;2270switch(st->st_mode & S_IFMT) {2271case S_IFLNK:2272if(strbuf_readlink(buf, path, st->st_size) <0)2273returnerror(_("unable to read symlink%s"), path);2274return0;2275case S_IFREG:2276if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2277returnerror(_("unable to open or read%s"), path);2278/*2279 * "git apply" without "--index/--cached" should never look2280 * at the index; the target file may not have been added to2281 * the index yet, and we may not even be in any Git repository.2282 * Pass NULL to convert_to_git() to stress this; the function2283 * should never look at the index when explicit crlf option2284 * is given.2285 */2286convert_to_git(NULL, path, buf->buf, buf->len, buf, conv_flags);2287return0;2288default:2289return-1;2290}2291}22922293/*2294 * Update the preimage, and the common lines in postimage,2295 * from buffer buf of length len. If postlen is 0 the postimage2296 * is updated in place, otherwise it's updated on a new buffer2297 * of length postlen2298 */22992300static voidupdate_pre_post_images(struct image *preimage,2301struct image *postimage,2302char*buf,2303size_t len,size_t postlen)2304{2305int i, ctx, reduced;2306char*new_buf, *old_buf, *fixed;2307struct image fixed_preimage;23082309/*2310 * Update the preimage with whitespace fixes. Note that we2311 * are not losing preimage->buf -- apply_one_fragment() will2312 * free "oldlines".2313 */2314prepare_image(&fixed_preimage, buf, len,1);2315assert(postlen2316? fixed_preimage.nr == preimage->nr2317: fixed_preimage.nr <= preimage->nr);2318for(i =0; i < fixed_preimage.nr; i++)2319 fixed_preimage.line[i].flag = preimage->line[i].flag;2320free(preimage->line_allocated);2321*preimage = fixed_preimage;23222323/*2324 * Adjust the common context lines in postimage. This can be2325 * done in-place when we are shrinking it with whitespace2326 * fixing, but needs a new buffer when ignoring whitespace or2327 * expanding leading tabs to spaces.2328 *2329 * We trust the caller to tell us if the update can be done2330 * in place (postlen==0) or not.2331 */2332 old_buf = postimage->buf;2333if(postlen)2334 new_buf = postimage->buf =xmalloc(postlen);2335else2336 new_buf = old_buf;2337 fixed = preimage->buf;23382339for(i = reduced = ctx =0; i < postimage->nr; i++) {2340size_t l_len = postimage->line[i].len;2341if(!(postimage->line[i].flag & LINE_COMMON)) {2342/* an added line -- no counterparts in preimage */2343memmove(new_buf, old_buf, l_len);2344 old_buf += l_len;2345 new_buf += l_len;2346continue;2347}23482349/* a common context -- skip it in the original postimage */2350 old_buf += l_len;23512352/* and find the corresponding one in the fixed preimage */2353while(ctx < preimage->nr &&2354!(preimage->line[ctx].flag & LINE_COMMON)) {2355 fixed += preimage->line[ctx].len;2356 ctx++;2357}23582359/*2360 * preimage is expected to run out, if the caller2361 * fixed addition of trailing blank lines.2362 */2363if(preimage->nr <= ctx) {2364 reduced++;2365continue;2366}23672368/* and copy it in, while fixing the line length */2369 l_len = preimage->line[ctx].len;2370memcpy(new_buf, fixed, l_len);2371 new_buf += l_len;2372 fixed += l_len;2373 postimage->line[i].len = l_len;2374 ctx++;2375}23762377if(postlen2378? postlen < new_buf - postimage->buf2379: postimage->len < new_buf - postimage->buf)2380BUG("caller miscounted postlen: asked%d, orig =%d, used =%d",2381(int)postlen, (int) postimage->len, (int)(new_buf - postimage->buf));23822383/* Fix the length of the whole thing */2384 postimage->len = new_buf - postimage->buf;2385 postimage->nr -= reduced;2386}23872388static intline_by_line_fuzzy_match(struct image *img,2389struct image *preimage,2390struct image *postimage,2391unsigned long current,2392int current_lno,2393int preimage_limit)2394{2395int i;2396size_t imgoff =0;2397size_t preoff =0;2398size_t postlen = postimage->len;2399size_t extra_chars;2400char*buf;2401char*preimage_eof;2402char*preimage_end;2403struct strbuf fixed;2404char*fixed_buf;2405size_t fixed_len;24062407for(i =0; i < preimage_limit; i++) {2408size_t prelen = preimage->line[i].len;2409size_t imglen = img->line[current_lno+i].len;24102411if(!fuzzy_matchlines(img->buf + current + imgoff, imglen,2412 preimage->buf + preoff, prelen))2413return0;2414if(preimage->line[i].flag & LINE_COMMON)2415 postlen += imglen - prelen;2416 imgoff += imglen;2417 preoff += prelen;2418}24192420/*2421 * Ok, the preimage matches with whitespace fuzz.2422 *2423 * imgoff now holds the true length of the target that2424 * matches the preimage before the end of the file.2425 *2426 * Count the number of characters in the preimage that fall2427 * beyond the end of the file and make sure that all of them2428 * are whitespace characters. (This can only happen if2429 * we are removing blank lines at the end of the file.)2430 */2431 buf = preimage_eof = preimage->buf + preoff;2432for( ; i < preimage->nr; i++)2433 preoff += preimage->line[i].len;2434 preimage_end = preimage->buf + preoff;2435for( ; buf < preimage_end; buf++)2436if(!isspace(*buf))2437return0;24382439/*2440 * Update the preimage and the common postimage context2441 * lines to use the same whitespace as the target.2442 * If whitespace is missing in the target (i.e.2443 * if the preimage extends beyond the end of the file),2444 * use the whitespace from the preimage.2445 */2446 extra_chars = preimage_end - preimage_eof;2447strbuf_init(&fixed, imgoff + extra_chars);2448strbuf_add(&fixed, img->buf + current, imgoff);2449strbuf_add(&fixed, preimage_eof, extra_chars);2450 fixed_buf =strbuf_detach(&fixed, &fixed_len);2451update_pre_post_images(preimage, postimage,2452 fixed_buf, fixed_len, postlen);2453return1;2454}24552456static intmatch_fragment(struct apply_state *state,2457struct image *img,2458struct image *preimage,2459struct image *postimage,2460unsigned long current,2461int current_lno,2462unsigned ws_rule,2463int match_beginning,int match_end)2464{2465int i;2466char*fixed_buf, *buf, *orig, *target;2467struct strbuf fixed;2468size_t fixed_len, postlen;2469int preimage_limit;24702471if(preimage->nr + current_lno <= img->nr) {2472/*2473 * The hunk falls within the boundaries of img.2474 */2475 preimage_limit = preimage->nr;2476if(match_end && (preimage->nr + current_lno != img->nr))2477return0;2478}else if(state->ws_error_action == correct_ws_error &&2479(ws_rule & WS_BLANK_AT_EOF)) {2480/*2481 * This hunk extends beyond the end of img, and we are2482 * removing blank lines at the end of the file. This2483 * many lines from the beginning of the preimage must2484 * match with img, and the remainder of the preimage2485 * must be blank.2486 */2487 preimage_limit = img->nr - current_lno;2488}else{2489/*2490 * The hunk extends beyond the end of the img and2491 * we are not removing blanks at the end, so we2492 * should reject the hunk at this position.2493 */2494return0;2495}24962497if(match_beginning && current_lno)2498return0;24992500/* Quick hash check */2501for(i =0; i < preimage_limit; i++)2502if((img->line[current_lno + i].flag & LINE_PATCHED) ||2503(preimage->line[i].hash != img->line[current_lno + i].hash))2504return0;25052506if(preimage_limit == preimage->nr) {2507/*2508 * Do we have an exact match? If we were told to match2509 * at the end, size must be exactly at current+fragsize,2510 * otherwise current+fragsize must be still within the preimage,2511 * and either case, the old piece should match the preimage2512 * exactly.2513 */2514if((match_end2515? (current + preimage->len == img->len)2516: (current + preimage->len <= img->len)) &&2517!memcmp(img->buf + current, preimage->buf, preimage->len))2518return1;2519}else{2520/*2521 * The preimage extends beyond the end of img, so2522 * there cannot be an exact match.2523 *2524 * There must be one non-blank context line that match2525 * a line before the end of img.2526 */2527char*buf_end;25282529 buf = preimage->buf;2530 buf_end = buf;2531for(i =0; i < preimage_limit; i++)2532 buf_end += preimage->line[i].len;25332534for( ; buf < buf_end; buf++)2535if(!isspace(*buf))2536break;2537if(buf == buf_end)2538return0;2539}25402541/*2542 * No exact match. If we are ignoring whitespace, run a line-by-line2543 * fuzzy matching. We collect all the line length information because2544 * we need it to adjust whitespace if we match.2545 */2546if(state->ws_ignore_action == ignore_ws_change)2547returnline_by_line_fuzzy_match(img, preimage, postimage,2548 current, current_lno, preimage_limit);25492550if(state->ws_error_action != correct_ws_error)2551return0;25522553/*2554 * The hunk does not apply byte-by-byte, but the hash says2555 * it might with whitespace fuzz. We weren't asked to2556 * ignore whitespace, we were asked to correct whitespace2557 * errors, so let's try matching after whitespace correction.2558 *2559 * While checking the preimage against the target, whitespace2560 * errors in both fixed, we count how large the corresponding2561 * postimage needs to be. The postimage prepared by2562 * apply_one_fragment() has whitespace errors fixed on added2563 * lines already, but the common lines were propagated as-is,2564 * which may become longer when their whitespace errors are2565 * fixed.2566 */25672568/* First count added lines in postimage */2569 postlen =0;2570for(i =0; i < postimage->nr; i++) {2571if(!(postimage->line[i].flag & LINE_COMMON))2572 postlen += postimage->line[i].len;2573}25742575/*2576 * The preimage may extend beyond the end of the file,2577 * but in this loop we will only handle the part of the2578 * preimage that falls within the file.2579 */2580strbuf_init(&fixed, preimage->len +1);2581 orig = preimage->buf;2582 target = img->buf + current;2583for(i =0; i < preimage_limit; i++) {2584size_t oldlen = preimage->line[i].len;2585size_t tgtlen = img->line[current_lno + i].len;2586size_t fixstart = fixed.len;2587struct strbuf tgtfix;2588int match;25892590/* Try fixing the line in the preimage */2591ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25922593/* Try fixing the line in the target */2594strbuf_init(&tgtfix, tgtlen);2595ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);25962597/*2598 * If they match, either the preimage was based on2599 * a version before our tree fixed whitespace breakage,2600 * or we are lacking a whitespace-fix patch the tree2601 * the preimage was based on already had (i.e. target2602 * has whitespace breakage, the preimage doesn't).2603 * In either case, we are fixing the whitespace breakages2604 * so we might as well take the fix together with their2605 * real change.2606 */2607 match = (tgtfix.len == fixed.len - fixstart &&2608!memcmp(tgtfix.buf, fixed.buf + fixstart,2609 fixed.len - fixstart));26102611/* Add the length if this is common with the postimage */2612if(preimage->line[i].flag & LINE_COMMON)2613 postlen += tgtfix.len;26142615strbuf_release(&tgtfix);2616if(!match)2617goto unmatch_exit;26182619 orig += oldlen;2620 target += tgtlen;2621}262226232624/*2625 * Now handle the lines in the preimage that falls beyond the2626 * end of the file (if any). They will only match if they are2627 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2628 * false).2629 */2630for( ; i < preimage->nr; i++) {2631size_t fixstart = fixed.len;/* start of the fixed preimage */2632size_t oldlen = preimage->line[i].len;2633int j;26342635/* Try fixing the line in the preimage */2636ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);26372638for(j = fixstart; j < fixed.len; j++)2639if(!isspace(fixed.buf[j]))2640goto unmatch_exit;26412642 orig += oldlen;2643}26442645/*2646 * Yes, the preimage is based on an older version that still2647 * has whitespace breakages unfixed, and fixing them makes the2648 * hunk match. Update the context lines in the postimage.2649 */2650 fixed_buf =strbuf_detach(&fixed, &fixed_len);2651if(postlen < postimage->len)2652 postlen =0;2653update_pre_post_images(preimage, postimage,2654 fixed_buf, fixed_len, postlen);2655return1;26562657 unmatch_exit:2658strbuf_release(&fixed);2659return0;2660}26612662static intfind_pos(struct apply_state *state,2663struct image *img,2664struct image *preimage,2665struct image *postimage,2666int line,2667unsigned ws_rule,2668int match_beginning,int match_end)2669{2670int i;2671unsigned long backwards, forwards, current;2672int backwards_lno, forwards_lno, current_lno;26732674/*2675 * If match_beginning or match_end is specified, there is no2676 * point starting from a wrong line that will never match and2677 * wander around and wait for a match at the specified end.2678 */2679if(match_beginning)2680 line =0;2681else if(match_end)2682 line = img->nr - preimage->nr;26832684/*2685 * Because the comparison is unsigned, the following test2686 * will also take care of a negative line number that can2687 * result when match_end and preimage is larger than the target.2688 */2689if((size_t) line > img->nr)2690 line = img->nr;26912692 current =0;2693for(i =0; i < line; i++)2694 current += img->line[i].len;26952696/*2697 * There's probably some smart way to do this, but I'll leave2698 * that to the smart and beautiful people. I'm simple and stupid.2699 */2700 backwards = current;2701 backwards_lno = line;2702 forwards = current;2703 forwards_lno = line;2704 current_lno = line;27052706for(i =0; ; i++) {2707if(match_fragment(state, img, preimage, postimage,2708 current, current_lno, ws_rule,2709 match_beginning, match_end))2710return current_lno;27112712 again:2713if(backwards_lno ==0&& forwards_lno == img->nr)2714break;27152716if(i &1) {2717if(backwards_lno ==0) {2718 i++;2719goto again;2720}2721 backwards_lno--;2722 backwards -= img->line[backwards_lno].len;2723 current = backwards;2724 current_lno = backwards_lno;2725}else{2726if(forwards_lno == img->nr) {2727 i++;2728goto again;2729}2730 forwards += img->line[forwards_lno].len;2731 forwards_lno++;2732 current = forwards;2733 current_lno = forwards_lno;2734}27352736}2737return-1;2738}27392740static voidremove_first_line(struct image *img)2741{2742 img->buf += img->line[0].len;2743 img->len -= img->line[0].len;2744 img->line++;2745 img->nr--;2746}27472748static voidremove_last_line(struct image *img)2749{2750 img->len -= img->line[--img->nr].len;2751}27522753/*2754 * The change from "preimage" and "postimage" has been found to2755 * apply at applied_pos (counts in line numbers) in "img".2756 * Update "img" to remove "preimage" and replace it with "postimage".2757 */2758static voidupdate_image(struct apply_state *state,2759struct image *img,2760int applied_pos,2761struct image *preimage,2762struct image *postimage)2763{2764/*2765 * remove the copy of preimage at offset in img2766 * and replace it with postimage2767 */2768int i, nr;2769size_t remove_count, insert_count, applied_at =0;2770char*result;2771int preimage_limit;27722773/*2774 * If we are removing blank lines at the end of img,2775 * the preimage may extend beyond the end.2776 * If that is the case, we must be careful only to2777 * remove the part of the preimage that falls within2778 * the boundaries of img. Initialize preimage_limit2779 * to the number of lines in the preimage that falls2780 * within the boundaries.2781 */2782 preimage_limit = preimage->nr;2783if(preimage_limit > img->nr - applied_pos)2784 preimage_limit = img->nr - applied_pos;27852786for(i =0; i < applied_pos; i++)2787 applied_at += img->line[i].len;27882789 remove_count =0;2790for(i =0; i < preimage_limit; i++)2791 remove_count += img->line[applied_pos + i].len;2792 insert_count = postimage->len;27932794/* Adjust the contents */2795 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2796memcpy(result, img->buf, applied_at);2797memcpy(result + applied_at, postimage->buf, postimage->len);2798memcpy(result + applied_at + postimage->len,2799 img->buf + (applied_at + remove_count),2800 img->len - (applied_at + remove_count));2801free(img->buf);2802 img->buf = result;2803 img->len += insert_count - remove_count;2804 result[img->len] ='\0';28052806/* Adjust the line table */2807 nr = img->nr + postimage->nr - preimage_limit;2808if(preimage_limit < postimage->nr) {2809/*2810 * NOTE: this knows that we never call remove_first_line()2811 * on anything other than pre/post image.2812 */2813REALLOC_ARRAY(img->line, nr);2814 img->line_allocated = img->line;2815}2816if(preimage_limit != postimage->nr)2817MOVE_ARRAY(img->line + applied_pos + postimage->nr,2818 img->line + applied_pos + preimage_limit,2819 img->nr - (applied_pos + preimage_limit));2820COPY_ARRAY(img->line + applied_pos, postimage->line, postimage->nr);2821if(!state->allow_overlap)2822for(i =0; i < postimage->nr; i++)2823 img->line[applied_pos + i].flag |= LINE_PATCHED;2824 img->nr = nr;2825}28262827/*2828 * Use the patch-hunk text in "frag" to prepare two images (preimage and2829 * postimage) for the hunk. Find lines that match "preimage" in "img" and2830 * replace the part of "img" with "postimage" text.2831 */2832static intapply_one_fragment(struct apply_state *state,2833struct image *img,struct fragment *frag,2834int inaccurate_eof,unsigned ws_rule,2835int nth_fragment)2836{2837int match_beginning, match_end;2838const char*patch = frag->patch;2839int size = frag->size;2840char*old, *oldlines;2841struct strbuf newlines;2842int new_blank_lines_at_end =0;2843int found_new_blank_lines_at_end =0;2844int hunk_linenr = frag->linenr;2845unsigned long leading, trailing;2846int pos, applied_pos;2847struct image preimage;2848struct image postimage;28492850memset(&preimage,0,sizeof(preimage));2851memset(&postimage,0,sizeof(postimage));2852 oldlines =xmalloc(size);2853strbuf_init(&newlines, size);28542855 old = oldlines;2856while(size >0) {2857char first;2858int len =linelen(patch, size);2859int plen;2860int added_blank_line =0;2861int is_blank_context =0;2862size_t start;28632864if(!len)2865break;28662867/*2868 * "plen" is how much of the line we should use for2869 * the actual patch data. Normally we just remove the2870 * first character on the line, but if the line is2871 * followed by "\ No newline", then we also remove the2872 * last one (which is the newline, of course).2873 */2874 plen = len -1;2875if(len < size && patch[len] =='\\')2876 plen--;2877 first = *patch;2878if(state->apply_in_reverse) {2879if(first =='-')2880 first ='+';2881else if(first =='+')2882 first ='-';2883}28842885switch(first) {2886case'\n':2887/* Newer GNU diff, empty context line */2888if(plen <0)2889/* ... followed by '\No newline'; nothing */2890break;2891*old++ ='\n';2892strbuf_addch(&newlines,'\n');2893add_line_info(&preimage,"\n",1, LINE_COMMON);2894add_line_info(&postimage,"\n",1, LINE_COMMON);2895 is_blank_context =1;2896break;2897case' ':2898if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2899ws_blank_line(patch +1, plen, ws_rule))2900 is_blank_context =1;2901/* fallthrough */2902case'-':2903memcpy(old, patch +1, plen);2904add_line_info(&preimage, old, plen,2905(first ==' '? LINE_COMMON :0));2906 old += plen;2907if(first =='-')2908break;2909/* fallthrough */2910case'+':2911/* --no-add does not add new lines */2912if(first =='+'&& state->no_add)2913break;29142915 start = newlines.len;2916if(first !='+'||2917!state->whitespace_error ||2918 state->ws_error_action != correct_ws_error) {2919strbuf_add(&newlines, patch +1, plen);2920}2921else{2922ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2923}2924add_line_info(&postimage, newlines.buf + start, newlines.len - start,2925(first =='+'?0: LINE_COMMON));2926if(first =='+'&&2927(ws_rule & WS_BLANK_AT_EOF) &&2928ws_blank_line(patch +1, plen, ws_rule))2929 added_blank_line =1;2930break;2931case'@':case'\\':2932/* Ignore it, we already handled it */2933break;2934default:2935if(state->apply_verbosity > verbosity_normal)2936error(_("invalid start of line: '%c'"), first);2937 applied_pos = -1;2938goto out;2939}2940if(added_blank_line) {2941if(!new_blank_lines_at_end)2942 found_new_blank_lines_at_end = hunk_linenr;2943 new_blank_lines_at_end++;2944}2945else if(is_blank_context)2946;2947else2948 new_blank_lines_at_end =0;2949 patch += len;2950 size -= len;2951 hunk_linenr++;2952}2953if(inaccurate_eof &&2954 old > oldlines && old[-1] =='\n'&&2955 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2956 old--;2957strbuf_setlen(&newlines, newlines.len -1);2958 preimage.line_allocated[preimage.nr -1].len--;2959 postimage.line_allocated[postimage.nr -1].len--;2960}29612962 leading = frag->leading;2963 trailing = frag->trailing;29642965/*2966 * A hunk to change lines at the beginning would begin with2967 * @@ -1,L +N,M @@2968 * but we need to be careful. -U0 that inserts before the second2969 * line also has this pattern.2970 *2971 * And a hunk to add to an empty file would begin with2972 * @@ -0,0 +N,M @@2973 *2974 * In other words, a hunk that is (frag->oldpos <= 1) with or2975 * without leading context must match at the beginning.2976 */2977 match_beginning = (!frag->oldpos ||2978(frag->oldpos ==1&& !state->unidiff_zero));29792980/*2981 * A hunk without trailing lines must match at the end.2982 * However, we simply cannot tell if a hunk must match end2983 * from the lack of trailing lines if the patch was generated2984 * with unidiff without any context.2985 */2986 match_end = !state->unidiff_zero && !trailing;29872988 pos = frag->newpos ? (frag->newpos -1) :0;2989 preimage.buf = oldlines;2990 preimage.len = old - oldlines;2991 postimage.buf = newlines.buf;2992 postimage.len = newlines.len;2993 preimage.line = preimage.line_allocated;2994 postimage.line = postimage.line_allocated;29952996for(;;) {29972998 applied_pos =find_pos(state, img, &preimage, &postimage, pos,2999 ws_rule, match_beginning, match_end);30003001if(applied_pos >=0)3002break;30033004/* Am I at my context limits? */3005if((leading <= state->p_context) && (trailing <= state->p_context))3006break;3007if(match_beginning || match_end) {3008 match_beginning = match_end =0;3009continue;3010}30113012/*3013 * Reduce the number of context lines; reduce both3014 * leading and trailing if they are equal otherwise3015 * just reduce the larger context.3016 */3017if(leading >= trailing) {3018remove_first_line(&preimage);3019remove_first_line(&postimage);3020 pos--;3021 leading--;3022}3023if(trailing > leading) {3024remove_last_line(&preimage);3025remove_last_line(&postimage);3026 trailing--;3027}3028}30293030if(applied_pos >=0) {3031if(new_blank_lines_at_end &&3032 preimage.nr + applied_pos >= img->nr &&3033(ws_rule & WS_BLANK_AT_EOF) &&3034 state->ws_error_action != nowarn_ws_error) {3035record_ws_error(state, WS_BLANK_AT_EOF,"+",1,3036 found_new_blank_lines_at_end);3037if(state->ws_error_action == correct_ws_error) {3038while(new_blank_lines_at_end--)3039remove_last_line(&postimage);3040}3041/*3042 * We would want to prevent write_out_results()3043 * from taking place in apply_patch() that follows3044 * the callchain led us here, which is:3045 * apply_patch->check_patch_list->check_patch->3046 * apply_data->apply_fragments->apply_one_fragment3047 */3048if(state->ws_error_action == die_on_ws_error)3049 state->apply =0;3050}30513052if(state->apply_verbosity > verbosity_normal && applied_pos != pos) {3053int offset = applied_pos - pos;3054if(state->apply_in_reverse)3055 offset =0- offset;3056fprintf_ln(stderr,3057Q_("Hunk #%dsucceeded at%d(offset%dline).",3058"Hunk #%dsucceeded at%d(offset%dlines).",3059 offset),3060 nth_fragment, applied_pos +1, offset);3061}30623063/*3064 * Warn if it was necessary to reduce the number3065 * of context lines.3066 */3067if((leading != frag->leading ||3068 trailing != frag->trailing) && state->apply_verbosity > verbosity_silent)3069fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"3070" to apply fragment at%d"),3071 leading, trailing, applied_pos+1);3072update_image(state, img, applied_pos, &preimage, &postimage);3073}else{3074if(state->apply_verbosity > verbosity_normal)3075error(_("while searching for:\n%.*s"),3076(int)(old - oldlines), oldlines);3077}30783079out:3080free(oldlines);3081strbuf_release(&newlines);3082free(preimage.line_allocated);3083free(postimage.line_allocated);30843085return(applied_pos <0);3086}30873088static intapply_binary_fragment(struct apply_state *state,3089struct image *img,3090struct patch *patch)3091{3092struct fragment *fragment = patch->fragments;3093unsigned long len;3094void*dst;30953096if(!fragment)3097returnerror(_("missing binary patch data for '%s'"),3098 patch->new_name ?3099 patch->new_name :3100 patch->old_name);31013102/* Binary patch is irreversible without the optional second hunk */3103if(state->apply_in_reverse) {3104if(!fragment->next)3105returnerror(_("cannot reverse-apply a binary patch "3106"without the reverse hunk to '%s'"),3107 patch->new_name3108? patch->new_name : patch->old_name);3109 fragment = fragment->next;3110}3111switch(fragment->binary_patch_method) {3112case BINARY_DELTA_DEFLATED:3113 dst =patch_delta(img->buf, img->len, fragment->patch,3114 fragment->size, &len);3115if(!dst)3116return-1;3117clear_image(img);3118 img->buf = dst;3119 img->len = len;3120return0;3121case BINARY_LITERAL_DEFLATED:3122clear_image(img);3123 img->len = fragment->size;3124 img->buf =xmemdupz(fragment->patch, img->len);3125return0;3126}3127return-1;3128}31293130/*3131 * Replace "img" with the result of applying the binary patch.3132 * The binary patch data itself in patch->fragment is still kept3133 * but the preimage prepared by the caller in "img" is freed here3134 * or in the helper function apply_binary_fragment() this calls.3135 */3136static intapply_binary(struct apply_state *state,3137struct image *img,3138struct patch *patch)3139{3140const char*name = patch->old_name ? patch->old_name : patch->new_name;3141struct object_id oid;31423143/*3144 * For safety, we require patch index line to contain3145 * full 40-byte textual SHA1 for old and new, at least for now.3146 */3147if(strlen(patch->old_sha1_prefix) !=40||3148strlen(patch->new_sha1_prefix) !=40||3149get_oid_hex(patch->old_sha1_prefix, &oid) ||3150get_oid_hex(patch->new_sha1_prefix, &oid))3151returnerror(_("cannot apply binary patch to '%s' "3152"without full index line"), name);31533154if(patch->old_name) {3155/*3156 * See if the old one matches what the patch3157 * applies to.3158 */3159hash_object_file(img->buf, img->len, blob_type, &oid);3160if(strcmp(oid_to_hex(&oid), patch->old_sha1_prefix))3161returnerror(_("the patch applies to '%s' (%s), "3162"which does not match the "3163"current contents."),3164 name,oid_to_hex(&oid));3165}3166else{3167/* Otherwise, the old one must be empty. */3168if(img->len)3169returnerror(_("the patch applies to an empty "3170"'%s' but it is not empty"), name);3171}31723173get_oid_hex(patch->new_sha1_prefix, &oid);3174if(is_null_oid(&oid)) {3175clear_image(img);3176return0;/* deletion patch */3177}31783179if(has_sha1_file(oid.hash)) {3180/* We already have the postimage */3181enum object_type type;3182unsigned long size;3183char*result;31843185 result =read_object_file(&oid, &type, &size);3186if(!result)3187returnerror(_("the necessary postimage%sfor "3188"'%s' cannot be read"),3189 patch->new_sha1_prefix, name);3190clear_image(img);3191 img->buf = result;3192 img->len = size;3193}else{3194/*3195 * We have verified buf matches the preimage;3196 * apply the patch data to it, which is stored3197 * in the patch->fragments->{patch,size}.3198 */3199if(apply_binary_fragment(state, img, patch))3200returnerror(_("binary patch does not apply to '%s'"),3201 name);32023203/* verify that the result matches */3204hash_object_file(img->buf, img->len, blob_type, &oid);3205if(strcmp(oid_to_hex(&oid), patch->new_sha1_prefix))3206returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3207 name, patch->new_sha1_prefix,oid_to_hex(&oid));3208}32093210return0;3211}32123213static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3214{3215struct fragment *frag = patch->fragments;3216const char*name = patch->old_name ? patch->old_name : patch->new_name;3217unsigned ws_rule = patch->ws_rule;3218unsigned inaccurate_eof = patch->inaccurate_eof;3219int nth =0;32203221if(patch->is_binary)3222returnapply_binary(state, img, patch);32233224while(frag) {3225 nth++;3226if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3227error(_("patch failed:%s:%ld"), name, frag->oldpos);3228if(!state->apply_with_reject)3229return-1;3230 frag->rejected =1;3231}3232 frag = frag->next;3233}3234return0;3235}32363237static intread_blob_object(struct strbuf *buf,const struct object_id *oid,unsigned mode)3238{3239if(S_ISGITLINK(mode)) {3240strbuf_grow(buf,100);3241strbuf_addf(buf,"Subproject commit%s\n",oid_to_hex(oid));3242}else{3243enum object_type type;3244unsigned long sz;3245char*result;32463247 result =read_object_file(oid, &type, &sz);3248if(!result)3249return-1;3250/* XXX read_sha1_file NUL-terminates */3251strbuf_attach(buf, result, sz, sz +1);3252}3253return0;3254}32553256static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3257{3258if(!ce)3259return0;3260returnread_blob_object(buf, &ce->oid, ce->ce_mode);3261}32623263static struct patch *in_fn_table(struct apply_state *state,const char*name)3264{3265struct string_list_item *item;32663267if(name == NULL)3268return NULL;32693270 item =string_list_lookup(&state->fn_table, name);3271if(item != NULL)3272return(struct patch *)item->util;32733274return NULL;3275}32763277/*3278 * item->util in the filename table records the status of the path.3279 * Usually it points at a patch (whose result records the contents3280 * of it after applying it), but it could be PATH_WAS_DELETED for a3281 * path that a previously applied patch has already removed, or3282 * PATH_TO_BE_DELETED for a path that a later patch would remove.3283 *3284 * The latter is needed to deal with a case where two paths A and B3285 * are swapped by first renaming A to B and then renaming B to A;3286 * moving A to B should not be prevented due to presence of B as we3287 * will remove it in a later patch.3288 */3289#define PATH_TO_BE_DELETED ((struct patch *) -2)3290#define PATH_WAS_DELETED ((struct patch *) -1)32913292static intto_be_deleted(struct patch *patch)3293{3294return patch == PATH_TO_BE_DELETED;3295}32963297static intwas_deleted(struct patch *patch)3298{3299return patch == PATH_WAS_DELETED;3300}33013302static voidadd_to_fn_table(struct apply_state *state,struct patch *patch)3303{3304struct string_list_item *item;33053306/*3307 * Always add new_name unless patch is a deletion3308 * This should cover the cases for normal diffs,3309 * file creations and copies3310 */3311if(patch->new_name != NULL) {3312 item =string_list_insert(&state->fn_table, patch->new_name);3313 item->util = patch;3314}33153316/*3317 * store a failure on rename/deletion cases because3318 * later chunks shouldn't patch old names3319 */3320if((patch->new_name == NULL) || (patch->is_rename)) {3321 item =string_list_insert(&state->fn_table, patch->old_name);3322 item->util = PATH_WAS_DELETED;3323}3324}33253326static voidprepare_fn_table(struct apply_state *state,struct patch *patch)3327{3328/*3329 * store information about incoming file deletion3330 */3331while(patch) {3332if((patch->new_name == NULL) || (patch->is_rename)) {3333struct string_list_item *item;3334 item =string_list_insert(&state->fn_table, patch->old_name);3335 item->util = PATH_TO_BE_DELETED;3336}3337 patch = patch->next;3338}3339}33403341static intcheckout_target(struct index_state *istate,3342struct cache_entry *ce,struct stat *st)3343{3344struct checkout costate = CHECKOUT_INIT;33453346 costate.refresh_cache =1;3347 costate.istate = istate;3348if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3349returnerror(_("cannot checkout%s"), ce->name);3350return0;3351}33523353static struct patch *previous_patch(struct apply_state *state,3354struct patch *patch,3355int*gone)3356{3357struct patch *previous;33583359*gone =0;3360if(patch->is_copy || patch->is_rename)3361return NULL;/* "git" patches do not depend on the order */33623363 previous =in_fn_table(state, patch->old_name);3364if(!previous)3365return NULL;33663367if(to_be_deleted(previous))3368return NULL;/* the deletion hasn't happened yet */33693370if(was_deleted(previous))3371*gone =1;33723373return previous;3374}33753376static intverify_index_match(const struct cache_entry *ce,struct stat *st)3377{3378if(S_ISGITLINK(ce->ce_mode)) {3379if(!S_ISDIR(st->st_mode))3380return-1;3381return0;3382}3383returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3384}33853386#define SUBMODULE_PATCH_WITHOUT_INDEX 133873388static intload_patch_target(struct apply_state *state,3389struct strbuf *buf,3390const struct cache_entry *ce,3391struct stat *st,3392struct patch *patch,3393const char*name,3394unsigned expected_mode)3395{3396if(state->cached || state->check_index) {3397if(read_file_or_gitlink(ce, buf))3398returnerror(_("failed to read%s"), name);3399}else if(name) {3400if(S_ISGITLINK(expected_mode)) {3401if(ce)3402returnread_file_or_gitlink(ce, buf);3403else3404return SUBMODULE_PATCH_WITHOUT_INDEX;3405}else if(has_symlink_leading_path(name,strlen(name))) {3406returnerror(_("reading from '%s' beyond a symbolic link"), name);3407}else{3408if(read_old_data(st, patch, name, buf))3409returnerror(_("failed to read%s"), name);3410}3411}3412return0;3413}34143415/*3416 * We are about to apply "patch"; populate the "image" with the3417 * current version we have, from the working tree or from the index,3418 * depending on the situation e.g. --cached/--index. If we are3419 * applying a non-git patch that incrementally updates the tree,3420 * we read from the result of a previous diff.3421 */3422static intload_preimage(struct apply_state *state,3423struct image *image,3424struct patch *patch,struct stat *st,3425const struct cache_entry *ce)3426{3427struct strbuf buf = STRBUF_INIT;3428size_t len;3429char*img;3430struct patch *previous;3431int status;34323433 previous =previous_patch(state, patch, &status);3434if(status)3435returnerror(_("path%shas been renamed/deleted"),3436 patch->old_name);3437if(previous) {3438/* We have a patched copy in memory; use that. */3439strbuf_add(&buf, previous->result, previous->resultsize);3440}else{3441 status =load_patch_target(state, &buf, ce, st, patch,3442 patch->old_name, patch->old_mode);3443if(status <0)3444return status;3445else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3446/*3447 * There is no way to apply subproject3448 * patch without looking at the index.3449 * NEEDSWORK: shouldn't this be flagged3450 * as an error???3451 */3452free_fragment_list(patch->fragments);3453 patch->fragments = NULL;3454}else if(status) {3455returnerror(_("failed to read%s"), patch->old_name);3456}3457}34583459 img =strbuf_detach(&buf, &len);3460prepare_image(image, img, len, !patch->is_binary);3461return0;3462}34633464static intthree_way_merge(struct image *image,3465char*path,3466const struct object_id *base,3467const struct object_id *ours,3468const struct object_id *theirs)3469{3470 mmfile_t base_file, our_file, their_file;3471 mmbuffer_t result = { NULL };3472int status;34733474read_mmblob(&base_file, base);3475read_mmblob(&our_file, ours);3476read_mmblob(&their_file, theirs);3477 status =ll_merge(&result, path,3478&base_file,"base",3479&our_file,"ours",3480&their_file,"theirs", NULL);3481free(base_file.ptr);3482free(our_file.ptr);3483free(their_file.ptr);3484if(status <0|| !result.ptr) {3485free(result.ptr);3486return-1;3487}3488clear_image(image);3489 image->buf = result.ptr;3490 image->len = result.size;34913492return status;3493}34943495/*3496 * When directly falling back to add/add three-way merge, we read from3497 * the current contents of the new_name. In no cases other than that3498 * this function will be called.3499 */3500static intload_current(struct apply_state *state,3501struct image *image,3502struct patch *patch)3503{3504struct strbuf buf = STRBUF_INIT;3505int status, pos;3506size_t len;3507char*img;3508struct stat st;3509struct cache_entry *ce;3510char*name = patch->new_name;3511unsigned mode = patch->new_mode;35123513if(!patch->is_new)3514BUG("patch to%sis not a creation", patch->old_name);35153516 pos =cache_name_pos(name,strlen(name));3517if(pos <0)3518returnerror(_("%s: does not exist in index"), name);3519 ce = active_cache[pos];3520if(lstat(name, &st)) {3521if(errno != ENOENT)3522returnerror_errno("%s", name);3523if(checkout_target(&the_index, ce, &st))3524return-1;3525}3526if(verify_index_match(ce, &st))3527returnerror(_("%s: does not match index"), name);35283529 status =load_patch_target(state, &buf, ce, &st, patch, name, mode);3530if(status <0)3531return status;3532else if(status)3533return-1;3534 img =strbuf_detach(&buf, &len);3535prepare_image(image, img, len, !patch->is_binary);3536return0;3537}35383539static inttry_threeway(struct apply_state *state,3540struct image *image,3541struct patch *patch,3542struct stat *st,3543const struct cache_entry *ce)3544{3545struct object_id pre_oid, post_oid, our_oid;3546struct strbuf buf = STRBUF_INIT;3547size_t len;3548int status;3549char*img;3550struct image tmp_image;35513552/* No point falling back to 3-way merge in these cases */3553if(patch->is_delete ||3554S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3555return-1;35563557/* Preimage the patch was prepared for */3558if(patch->is_new)3559write_object_file("",0, blob_type, &pre_oid);3560else if(get_oid(patch->old_sha1_prefix, &pre_oid) ||3561read_blob_object(&buf, &pre_oid, patch->old_mode))3562returnerror(_("repository lacks the necessary blob to fall back on 3-way merge."));35633564if(state->apply_verbosity > verbosity_silent)3565fprintf(stderr,_("Falling back to three-way merge...\n"));35663567 img =strbuf_detach(&buf, &len);3568prepare_image(&tmp_image, img, len,1);3569/* Apply the patch to get the post image */3570if(apply_fragments(state, &tmp_image, patch) <0) {3571clear_image(&tmp_image);3572return-1;3573}3574/* post_oid is theirs */3575write_object_file(tmp_image.buf, tmp_image.len, blob_type, &post_oid);3576clear_image(&tmp_image);35773578/* our_oid is ours */3579if(patch->is_new) {3580if(load_current(state, &tmp_image, patch))3581returnerror(_("cannot read the current contents of '%s'"),3582 patch->new_name);3583}else{3584if(load_preimage(state, &tmp_image, patch, st, ce))3585returnerror(_("cannot read the current contents of '%s'"),3586 patch->old_name);3587}3588write_object_file(tmp_image.buf, tmp_image.len, blob_type, &our_oid);3589clear_image(&tmp_image);35903591/* in-core three-way merge between post and our using pre as base */3592 status =three_way_merge(image, patch->new_name,3593&pre_oid, &our_oid, &post_oid);3594if(status <0) {3595if(state->apply_verbosity > verbosity_silent)3596fprintf(stderr,3597_("Failed to fall back on three-way merge...\n"));3598return status;3599}36003601if(status) {3602 patch->conflicted_threeway =1;3603if(patch->is_new)3604oidclr(&patch->threeway_stage[0]);3605else3606oidcpy(&patch->threeway_stage[0], &pre_oid);3607oidcpy(&patch->threeway_stage[1], &our_oid);3608oidcpy(&patch->threeway_stage[2], &post_oid);3609if(state->apply_verbosity > verbosity_silent)3610fprintf(stderr,3611_("Applied patch to '%s' with conflicts.\n"),3612 patch->new_name);3613}else{3614if(state->apply_verbosity > verbosity_silent)3615fprintf(stderr,3616_("Applied patch to '%s' cleanly.\n"),3617 patch->new_name);3618}3619return0;3620}36213622static intapply_data(struct apply_state *state,struct patch *patch,3623struct stat *st,const struct cache_entry *ce)3624{3625struct image image;36263627if(load_preimage(state, &image, patch, st, ce) <0)3628return-1;36293630if(patch->direct_to_threeway ||3631apply_fragments(state, &image, patch) <0) {3632/* Note: with --reject, apply_fragments() returns 0 */3633if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3634return-1;3635}3636 patch->result = image.buf;3637 patch->resultsize = image.len;3638add_to_fn_table(state, patch);3639free(image.line_allocated);36403641if(0< patch->is_delete && patch->resultsize)3642returnerror(_("removal patch leaves file contents"));36433644return0;3645}36463647/*3648 * If "patch" that we are looking at modifies or deletes what we have,3649 * we would want it not to lose any local modification we have, either3650 * in the working tree or in the index.3651 *3652 * This also decides if a non-git patch is a creation patch or a3653 * modification to an existing empty file. We do not check the state3654 * of the current tree for a creation patch in this function; the caller3655 * check_patch() separately makes sure (and errors out otherwise) that3656 * the path the patch creates does not exist in the current tree.3657 */3658static intcheck_preimage(struct apply_state *state,3659struct patch *patch,3660struct cache_entry **ce,3661struct stat *st)3662{3663const char*old_name = patch->old_name;3664struct patch *previous = NULL;3665int stat_ret =0, status;3666unsigned st_mode =0;36673668if(!old_name)3669return0;36703671assert(patch->is_new <=0);3672 previous =previous_patch(state, patch, &status);36733674if(status)3675returnerror(_("path%shas been renamed/deleted"), old_name);3676if(previous) {3677 st_mode = previous->new_mode;3678}else if(!state->cached) {3679 stat_ret =lstat(old_name, st);3680if(stat_ret && errno != ENOENT)3681returnerror_errno("%s", old_name);3682}36833684if(state->check_index && !previous) {3685int pos =cache_name_pos(old_name,strlen(old_name));3686if(pos <0) {3687if(patch->is_new <0)3688goto is_new;3689returnerror(_("%s: does not exist in index"), old_name);3690}3691*ce = active_cache[pos];3692if(stat_ret <0) {3693if(checkout_target(&the_index, *ce, st))3694return-1;3695}3696if(!state->cached &&verify_index_match(*ce, st))3697returnerror(_("%s: does not match index"), old_name);3698if(state->cached)3699 st_mode = (*ce)->ce_mode;3700}else if(stat_ret <0) {3701if(patch->is_new <0)3702goto is_new;3703returnerror_errno("%s", old_name);3704}37053706if(!state->cached && !previous)3707 st_mode =ce_mode_from_stat(*ce, st->st_mode);37083709if(patch->is_new <0)3710 patch->is_new =0;3711if(!patch->old_mode)3712 patch->old_mode = st_mode;3713if((st_mode ^ patch->old_mode) & S_IFMT)3714returnerror(_("%s: wrong type"), old_name);3715if(st_mode != patch->old_mode)3716warning(_("%shas type%o, expected%o"),3717 old_name, st_mode, patch->old_mode);3718if(!patch->new_mode && !patch->is_delete)3719 patch->new_mode = st_mode;3720return0;37213722 is_new:3723 patch->is_new =1;3724 patch->is_delete =0;3725FREE_AND_NULL(patch->old_name);3726return0;3727}372837293730#define EXISTS_IN_INDEX 13731#define EXISTS_IN_WORKTREE 237323733static intcheck_to_create(struct apply_state *state,3734const char*new_name,3735int ok_if_exists)3736{3737struct stat nst;37383739if(state->check_index &&3740cache_name_pos(new_name,strlen(new_name)) >=0&&3741!ok_if_exists)3742return EXISTS_IN_INDEX;3743if(state->cached)3744return0;37453746if(!lstat(new_name, &nst)) {3747if(S_ISDIR(nst.st_mode) || ok_if_exists)3748return0;3749/*3750 * A leading component of new_name might be a symlink3751 * that is going to be removed with this patch, but3752 * still pointing at somewhere that has the path.3753 * In such a case, path "new_name" does not exist as3754 * far as git is concerned.3755 */3756if(has_symlink_leading_path(new_name,strlen(new_name)))3757return0;37583759return EXISTS_IN_WORKTREE;3760}else if(!is_missing_file_error(errno)) {3761returnerror_errno("%s", new_name);3762}3763return0;3764}37653766static uintptr_tregister_symlink_changes(struct apply_state *state,3767const char*path,3768uintptr_t what)3769{3770struct string_list_item *ent;37713772 ent =string_list_lookup(&state->symlink_changes, path);3773if(!ent) {3774 ent =string_list_insert(&state->symlink_changes, path);3775 ent->util = (void*)0;3776}3777 ent->util = (void*)(what | ((uintptr_t)ent->util));3778return(uintptr_t)ent->util;3779}37803781static uintptr_tcheck_symlink_changes(struct apply_state *state,const char*path)3782{3783struct string_list_item *ent;37843785 ent =string_list_lookup(&state->symlink_changes, path);3786if(!ent)3787return0;3788return(uintptr_t)ent->util;3789}37903791static voidprepare_symlink_changes(struct apply_state *state,struct patch *patch)3792{3793for( ; patch; patch = patch->next) {3794if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3795(patch->is_rename || patch->is_delete))3796/* the symlink at patch->old_name is removed */3797register_symlink_changes(state, patch->old_name, APPLY_SYMLINK_GOES_AWAY);37983799if(patch->new_name &&S_ISLNK(patch->new_mode))3800/* the symlink at patch->new_name is created or remains */3801register_symlink_changes(state, patch->new_name, APPLY_SYMLINK_IN_RESULT);3802}3803}38043805static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3806{3807do{3808unsigned int change;38093810while(--name->len && name->buf[name->len] !='/')3811;/* scan backwards */3812if(!name->len)3813break;3814 name->buf[name->len] ='\0';3815 change =check_symlink_changes(state, name->buf);3816if(change & APPLY_SYMLINK_IN_RESULT)3817return1;3818if(change & APPLY_SYMLINK_GOES_AWAY)3819/*3820 * This cannot be "return 0", because we may3821 * see a new one created at a higher level.3822 */3823continue;38243825/* otherwise, check the preimage */3826if(state->check_index) {3827struct cache_entry *ce;38283829 ce =cache_file_exists(name->buf, name->len, ignore_case);3830if(ce &&S_ISLNK(ce->ce_mode))3831return1;3832}else{3833struct stat st;3834if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3835return1;3836}3837}while(1);3838return0;3839}38403841static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3842{3843int ret;3844struct strbuf name = STRBUF_INIT;38453846assert(*name_ !='\0');3847strbuf_addstr(&name, name_);3848 ret =path_is_beyond_symlink_1(state, &name);3849strbuf_release(&name);38503851return ret;3852}38533854static intcheck_unsafe_path(struct patch *patch)3855{3856const char*old_name = NULL;3857const char*new_name = NULL;3858if(patch->is_delete)3859 old_name = patch->old_name;3860else if(!patch->is_new && !patch->is_copy)3861 old_name = patch->old_name;3862if(!patch->is_delete)3863 new_name = patch->new_name;38643865if(old_name && !verify_path(old_name, patch->old_mode))3866returnerror(_("invalid path '%s'"), old_name);3867if(new_name && !verify_path(new_name, patch->new_mode))3868returnerror(_("invalid path '%s'"), new_name);3869return0;3870}38713872/*3873 * Check and apply the patch in-core; leave the result in patch->result3874 * for the caller to write it out to the final destination.3875 */3876static intcheck_patch(struct apply_state *state,struct patch *patch)3877{3878struct stat st;3879const char*old_name = patch->old_name;3880const char*new_name = patch->new_name;3881const char*name = old_name ? old_name : new_name;3882struct cache_entry *ce = NULL;3883struct patch *tpatch;3884int ok_if_exists;3885int status;38863887 patch->rejected =1;/* we will drop this after we succeed */38883889 status =check_preimage(state, patch, &ce, &st);3890if(status)3891return status;3892 old_name = patch->old_name;38933894/*3895 * A type-change diff is always split into a patch to delete3896 * old, immediately followed by a patch to create new (see3897 * diff.c::run_diff()); in such a case it is Ok that the entry3898 * to be deleted by the previous patch is still in the working3899 * tree and in the index.3900 *3901 * A patch to swap-rename between A and B would first rename A3902 * to B and then rename B to A. While applying the first one,3903 * the presence of B should not stop A from getting renamed to3904 * B; ask to_be_deleted() about the later rename. Removal of3905 * B and rename from A to B is handled the same way by asking3906 * was_deleted().3907 */3908if((tpatch =in_fn_table(state, new_name)) &&3909(was_deleted(tpatch) ||to_be_deleted(tpatch)))3910 ok_if_exists =1;3911else3912 ok_if_exists =0;39133914if(new_name &&3915((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3916int err =check_to_create(state, new_name, ok_if_exists);39173918if(err && state->threeway) {3919 patch->direct_to_threeway =1;3920}else switch(err) {3921case0:3922break;/* happy */3923case EXISTS_IN_INDEX:3924returnerror(_("%s: already exists in index"), new_name);3925break;3926case EXISTS_IN_WORKTREE:3927returnerror(_("%s: already exists in working directory"),3928 new_name);3929default:3930return err;3931}39323933if(!patch->new_mode) {3934if(0< patch->is_new)3935 patch->new_mode = S_IFREG |0644;3936else3937 patch->new_mode = patch->old_mode;3938}3939}39403941if(new_name && old_name) {3942int same = !strcmp(old_name, new_name);3943if(!patch->new_mode)3944 patch->new_mode = patch->old_mode;3945if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3946if(same)3947returnerror(_("new mode (%o) of%sdoes not "3948"match old mode (%o)"),3949 patch->new_mode, new_name,3950 patch->old_mode);3951else3952returnerror(_("new mode (%o) of%sdoes not "3953"match old mode (%o) of%s"),3954 patch->new_mode, new_name,3955 patch->old_mode, old_name);3956}3957}39583959if(!state->unsafe_paths &&check_unsafe_path(patch))3960return-128;39613962/*3963 * An attempt to read from or delete a path that is beyond a3964 * symbolic link will be prevented by load_patch_target() that3965 * is called at the beginning of apply_data() so we do not3966 * have to worry about a patch marked with "is_delete" bit3967 * here. We however need to make sure that the patch result3968 * is not deposited to a path that is beyond a symbolic link3969 * here.3970 */3971if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3972returnerror(_("affected file '%s' is beyond a symbolic link"),3973 patch->new_name);39743975if(apply_data(state, patch, &st, ce) <0)3976returnerror(_("%s: patch does not apply"), name);3977 patch->rejected =0;3978return0;3979}39803981static intcheck_patch_list(struct apply_state *state,struct patch *patch)3982{3983int err =0;39843985prepare_symlink_changes(state, patch);3986prepare_fn_table(state, patch);3987while(patch) {3988int res;3989if(state->apply_verbosity > verbosity_normal)3990say_patch_name(stderr,3991_("Checking patch%s..."), patch);3992 res =check_patch(state, patch);3993if(res == -128)3994return-128;3995 err |= res;3996 patch = patch->next;3997}3998return err;3999}40004001static intread_apply_cache(struct apply_state *state)4002{4003if(state->index_file)4004returnread_cache_from(state->index_file);4005else4006returnread_cache();4007}40084009/* This function tries to read the object name from the current index */4010static intget_current_oid(struct apply_state *state,const char*path,4011struct object_id *oid)4012{4013int pos;40144015if(read_apply_cache(state) <0)4016return-1;4017 pos =cache_name_pos(path,strlen(path));4018if(pos <0)4019return-1;4020oidcpy(oid, &active_cache[pos]->oid);4021return0;4022}40234024static intpreimage_oid_in_gitlink_patch(struct patch *p,struct object_id *oid)4025{4026/*4027 * A usable gitlink patch has only one fragment (hunk) that looks like:4028 * @@ -1 +1 @@4029 * -Subproject commit <old sha1>4030 * +Subproject commit <new sha1>4031 * or4032 * @@ -1 +0,0 @@4033 * -Subproject commit <old sha1>4034 * for a removal patch.4035 */4036struct fragment *hunk = p->fragments;4037static const char heading[] ="-Subproject commit ";4038char*preimage;40394040if(/* does the patch have only one hunk? */4041 hunk && !hunk->next &&4042/* is its preimage one line? */4043 hunk->oldpos ==1&& hunk->oldlines ==1&&4044/* does preimage begin with the heading? */4045(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&4046starts_with(++preimage, heading) &&4047/* does it record full SHA-1? */4048!get_oid_hex(preimage +sizeof(heading) -1, oid) &&4049 preimage[sizeof(heading) + GIT_SHA1_HEXSZ -1] =='\n'&&4050/* does the abbreviated name on the index line agree with it? */4051starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))4052return0;/* it all looks fine */40534054/* we may have full object name on the index line */4055returnget_oid_hex(p->old_sha1_prefix, oid);4056}40574058/* Build an index that contains the just the files needed for a 3way merge */4059static intbuild_fake_ancestor(struct apply_state *state,struct patch *list)4060{4061struct patch *patch;4062struct index_state result = { NULL };4063struct lock_file lock = LOCK_INIT;4064int res;40654066/* Once we start supporting the reverse patch, it may be4067 * worth showing the new sha1 prefix, but until then...4068 */4069for(patch = list; patch; patch = patch->next) {4070struct object_id oid;4071struct cache_entry *ce;4072const char*name;40734074 name = patch->old_name ? patch->old_name : patch->new_name;4075if(0< patch->is_new)4076continue;40774078if(S_ISGITLINK(patch->old_mode)) {4079if(!preimage_oid_in_gitlink_patch(patch, &oid))4080;/* ok, the textual part looks sane */4081else4082returnerror(_("sha1 information is lacking or "4083"useless for submodule%s"), name);4084}else if(!get_oid_blob(patch->old_sha1_prefix, &oid)) {4085;/* ok */4086}else if(!patch->lines_added && !patch->lines_deleted) {4087/* mode-only change: update the current */4088if(get_current_oid(state, patch->old_name, &oid))4089returnerror(_("mode change for%s, which is not "4090"in current HEAD"), name);4091}else4092returnerror(_("sha1 information is lacking or useless "4093"(%s)."), name);40944095 ce =make_cache_entry(patch->old_mode, oid.hash, name,0,0);4096if(!ce)4097returnerror(_("make_cache_entry failed for path '%s'"),4098 name);4099if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) {4100free(ce);4101returnerror(_("could not add%sto temporary index"),4102 name);4103}4104}41054106hold_lock_file_for_update(&lock, state->fake_ancestor, LOCK_DIE_ON_ERROR);4107 res =write_locked_index(&result, &lock, COMMIT_LOCK);4108discard_index(&result);41094110if(res)4111returnerror(_("could not write temporary index to%s"),4112 state->fake_ancestor);41134114return0;4115}41164117static voidstat_patch_list(struct apply_state *state,struct patch *patch)4118{4119int files, adds, dels;41204121for(files = adds = dels =0; patch ; patch = patch->next) {4122 files++;4123 adds += patch->lines_added;4124 dels += patch->lines_deleted;4125show_stats(state, patch);4126}41274128print_stat_summary(stdout, files, adds, dels);4129}41304131static voidnumstat_patch_list(struct apply_state *state,4132struct patch *patch)4133{4134for( ; patch; patch = patch->next) {4135const char*name;4136 name = patch->new_name ? patch->new_name : patch->old_name;4137if(patch->is_binary)4138printf("-\t-\t");4139else4140printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4141write_name_quoted(name, stdout, state->line_termination);4142}4143}41444145static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4146{4147if(mode)4148printf("%smode%06o%s\n", newdelete, mode, name);4149else4150printf("%s %s\n", newdelete, name);4151}41524153static voidshow_mode_change(struct patch *p,int show_name)4154{4155if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4156if(show_name)4157printf(" mode change%06o =>%06o%s\n",4158 p->old_mode, p->new_mode, p->new_name);4159else4160printf(" mode change%06o =>%06o\n",4161 p->old_mode, p->new_mode);4162}4163}41644165static voidshow_rename_copy(struct patch *p)4166{4167const char*renamecopy = p->is_rename ?"rename":"copy";4168const char*old_name, *new_name;41694170/* Find common prefix */4171 old_name = p->old_name;4172 new_name = p->new_name;4173while(1) {4174const char*slash_old, *slash_new;4175 slash_old =strchr(old_name,'/');4176 slash_new =strchr(new_name,'/');4177if(!slash_old ||4178!slash_new ||4179 slash_old - old_name != slash_new - new_name ||4180memcmp(old_name, new_name, slash_new - new_name))4181break;4182 old_name = slash_old +1;4183 new_name = slash_new +1;4184}4185/* p->old_name thru old_name is the common prefix, and old_name and new_name4186 * through the end of names are renames4187 */4188if(old_name != p->old_name)4189printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4190(int)(old_name - p->old_name), p->old_name,4191 old_name, new_name, p->score);4192else4193printf("%s %s=>%s(%d%%)\n", renamecopy,4194 p->old_name, p->new_name, p->score);4195show_mode_change(p,0);4196}41974198static voidsummary_patch_list(struct patch *patch)4199{4200struct patch *p;42014202for(p = patch; p; p = p->next) {4203if(p->is_new)4204show_file_mode_name("create", p->new_mode, p->new_name);4205else if(p->is_delete)4206show_file_mode_name("delete", p->old_mode, p->old_name);4207else{4208if(p->is_rename || p->is_copy)4209show_rename_copy(p);4210else{4211if(p->score) {4212printf(" rewrite%s(%d%%)\n",4213 p->new_name, p->score);4214show_mode_change(p,0);4215}4216else4217show_mode_change(p,1);4218}4219}4220}4221}42224223static voidpatch_stats(struct apply_state *state,struct patch *patch)4224{4225int lines = patch->lines_added + patch->lines_deleted;42264227if(lines > state->max_change)4228 state->max_change = lines;4229if(patch->old_name) {4230int len =quote_c_style(patch->old_name, NULL, NULL,0);4231if(!len)4232 len =strlen(patch->old_name);4233if(len > state->max_len)4234 state->max_len = len;4235}4236if(patch->new_name) {4237int len =quote_c_style(patch->new_name, NULL, NULL,0);4238if(!len)4239 len =strlen(patch->new_name);4240if(len > state->max_len)4241 state->max_len = len;4242}4243}42444245static intremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4246{4247if(state->update_index && !state->ita_only) {4248if(remove_file_from_cache(patch->old_name) <0)4249returnerror(_("unable to remove%sfrom index"), patch->old_name);4250}4251if(!state->cached) {4252if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4253remove_path(patch->old_name);4254}4255}4256return0;4257}42584259static intadd_index_file(struct apply_state *state,4260const char*path,4261unsigned mode,4262void*buf,4263unsigned long size)4264{4265struct stat st;4266struct cache_entry *ce;4267int namelen =strlen(path);4268unsigned ce_size =cache_entry_size(namelen);42694270 ce =xcalloc(1, ce_size);4271memcpy(ce->name, path, namelen);4272 ce->ce_mode =create_ce_mode(mode);4273 ce->ce_flags =create_ce_flags(0);4274 ce->ce_namelen = namelen;4275if(state->ita_only) {4276 ce->ce_flags |= CE_INTENT_TO_ADD;4277set_object_name_for_intent_to_add_entry(ce);4278}else if(S_ISGITLINK(mode)) {4279const char*s;42804281if(!skip_prefix(buf,"Subproject commit ", &s) ||4282get_oid_hex(s, &ce->oid)) {4283free(ce);4284returnerror(_("corrupt patch for submodule%s"), path);4285}4286}else{4287if(!state->cached) {4288if(lstat(path, &st) <0) {4289free(ce);4290returnerror_errno(_("unable to stat newly "4291"created file '%s'"),4292 path);4293}4294fill_stat_cache_info(ce, &st);4295}4296if(write_object_file(buf, size, blob_type, &ce->oid) <0) {4297free(ce);4298returnerror(_("unable to create backing store "4299"for newly created file%s"), path);4300}4301}4302if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0) {4303free(ce);4304returnerror(_("unable to add cache entry for%s"), path);4305}43064307return0;4308}43094310/*4311 * Returns:4312 * -1 if an unrecoverable error happened4313 * 0 if everything went well4314 * 1 if a recoverable error happened4315 */4316static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4317{4318int fd, res;4319struct strbuf nbuf = STRBUF_INIT;43204321if(S_ISGITLINK(mode)) {4322struct stat st;4323if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4324return0;4325return!!mkdir(path,0777);4326}43274328if(has_symlinks &&S_ISLNK(mode))4329/* Although buf:size is counted string, it also is NUL4330 * terminated.4331 */4332return!!symlink(buf, path);43334334 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4335if(fd <0)4336return1;43374338if(convert_to_working_tree(path, buf, size, &nbuf)) {4339 size = nbuf.len;4340 buf = nbuf.buf;4341}43424343 res =write_in_full(fd, buf, size) <0;4344if(res)4345error_errno(_("failed to write to '%s'"), path);4346strbuf_release(&nbuf);43474348if(close(fd) <0&& !res)4349returnerror_errno(_("closing file '%s'"), path);43504351return res ? -1:0;4352}43534354/*4355 * We optimistically assume that the directories exist,4356 * which is true 99% of the time anyway. If they don't,4357 * we create them and try again.4358 *4359 * Returns:4360 * -1 on error4361 * 0 otherwise4362 */4363static intcreate_one_file(struct apply_state *state,4364char*path,4365unsigned mode,4366const char*buf,4367unsigned long size)4368{4369int res;43704371if(state->cached)4372return0;43734374 res =try_create_file(path, mode, buf, size);4375if(res <0)4376return-1;4377if(!res)4378return0;43794380if(errno == ENOENT) {4381if(safe_create_leading_directories(path))4382return0;4383 res =try_create_file(path, mode, buf, size);4384if(res <0)4385return-1;4386if(!res)4387return0;4388}43894390if(errno == EEXIST || errno == EACCES) {4391/* We may be trying to create a file where a directory4392 * used to be.4393 */4394struct stat st;4395if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4396 errno = EEXIST;4397}43984399if(errno == EEXIST) {4400unsigned int nr =getpid();44014402for(;;) {4403char newpath[PATH_MAX];4404mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4405 res =try_create_file(newpath, mode, buf, size);4406if(res <0)4407return-1;4408if(!res) {4409if(!rename(newpath, path))4410return0;4411unlink_or_warn(newpath);4412break;4413}4414if(errno != EEXIST)4415break;4416++nr;4417}4418}4419returnerror_errno(_("unable to write file '%s' mode%o"),4420 path, mode);4421}44224423static intadd_conflicted_stages_file(struct apply_state *state,4424struct patch *patch)4425{4426int stage, namelen;4427unsigned ce_size, mode;4428struct cache_entry *ce;44294430if(!state->update_index)4431return0;4432 namelen =strlen(patch->new_name);4433 ce_size =cache_entry_size(namelen);4434 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);44354436remove_file_from_cache(patch->new_name);4437for(stage =1; stage <4; stage++) {4438if(is_null_oid(&patch->threeway_stage[stage -1]))4439continue;4440 ce =xcalloc(1, ce_size);4441memcpy(ce->name, patch->new_name, namelen);4442 ce->ce_mode =create_ce_mode(mode);4443 ce->ce_flags =create_ce_flags(stage);4444 ce->ce_namelen = namelen;4445oidcpy(&ce->oid, &patch->threeway_stage[stage -1]);4446if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0) {4447free(ce);4448returnerror(_("unable to add cache entry for%s"),4449 patch->new_name);4450}4451}44524453return0;4454}44554456static intcreate_file(struct apply_state *state,struct patch *patch)4457{4458char*path = patch->new_name;4459unsigned mode = patch->new_mode;4460unsigned long size = patch->resultsize;4461char*buf = patch->result;44624463if(!mode)4464 mode = S_IFREG |0644;4465if(create_one_file(state, path, mode, buf, size))4466return-1;44674468if(patch->conflicted_threeway)4469returnadd_conflicted_stages_file(state, patch);4470else if(state->update_index)4471returnadd_index_file(state, path, mode, buf, size);4472return0;4473}44744475/* phase zero is to remove, phase one is to create */4476static intwrite_out_one_result(struct apply_state *state,4477struct patch *patch,4478int phase)4479{4480if(patch->is_delete >0) {4481if(phase ==0)4482returnremove_file(state, patch,1);4483return0;4484}4485if(patch->is_new >0|| patch->is_copy) {4486if(phase ==1)4487returncreate_file(state, patch);4488return0;4489}4490/*4491 * Rename or modification boils down to the same4492 * thing: remove the old, write the new4493 */4494if(phase ==0)4495returnremove_file(state, patch, patch->is_rename);4496if(phase ==1)4497returncreate_file(state, patch);4498return0;4499}45004501static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4502{4503FILE*rej;4504char namebuf[PATH_MAX];4505struct fragment *frag;4506int cnt =0;4507struct strbuf sb = STRBUF_INIT;45084509for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4510if(!frag->rejected)4511continue;4512 cnt++;4513}45144515if(!cnt) {4516if(state->apply_verbosity > verbosity_normal)4517say_patch_name(stderr,4518_("Applied patch%scleanly."), patch);4519return0;4520}45214522/* This should not happen, because a removal patch that leaves4523 * contents are marked "rejected" at the patch level.4524 */4525if(!patch->new_name)4526die(_("internal error"));45274528/* Say this even without --verbose */4529strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4530"Applying patch %%swith%drejects...",4531 cnt),4532 cnt);4533if(state->apply_verbosity > verbosity_silent)4534say_patch_name(stderr, sb.buf, patch);4535strbuf_release(&sb);45364537 cnt =strlen(patch->new_name);4538if(ARRAY_SIZE(namebuf) <= cnt +5) {4539 cnt =ARRAY_SIZE(namebuf) -5;4540warning(_("truncating .rej filename to %.*s.rej"),4541 cnt -1, patch->new_name);4542}4543memcpy(namebuf, patch->new_name, cnt);4544memcpy(namebuf + cnt,".rej",5);45454546 rej =fopen(namebuf,"w");4547if(!rej)4548returnerror_errno(_("cannot open%s"), namebuf);45494550/* Normal git tools never deal with .rej, so do not pretend4551 * this is a git patch by saying --git or giving extended4552 * headers. While at it, maybe please "kompare" that wants4553 * the trailing TAB and some garbage at the end of line ;-).4554 */4555fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4556 patch->new_name, patch->new_name);4557for(cnt =1, frag = patch->fragments;4558 frag;4559 cnt++, frag = frag->next) {4560if(!frag->rejected) {4561if(state->apply_verbosity > verbosity_silent)4562fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4563continue;4564}4565if(state->apply_verbosity > verbosity_silent)4566fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4567fprintf(rej,"%.*s", frag->size, frag->patch);4568if(frag->patch[frag->size-1] !='\n')4569fputc('\n', rej);4570}4571fclose(rej);4572return-1;4573}45744575/*4576 * Returns:4577 * -1 if an error happened4578 * 0 if the patch applied cleanly4579 * 1 if the patch did not apply cleanly4580 */4581static intwrite_out_results(struct apply_state *state,struct patch *list)4582{4583int phase;4584int errs =0;4585struct patch *l;4586struct string_list cpath = STRING_LIST_INIT_DUP;45874588for(phase =0; phase <2; phase++) {4589 l = list;4590while(l) {4591if(l->rejected)4592 errs =1;4593else{4594if(write_out_one_result(state, l, phase)) {4595string_list_clear(&cpath,0);4596return-1;4597}4598if(phase ==1) {4599if(write_out_one_reject(state, l))4600 errs =1;4601if(l->conflicted_threeway) {4602string_list_append(&cpath, l->new_name);4603 errs =1;4604}4605}4606}4607 l = l->next;4608}4609}46104611if(cpath.nr) {4612struct string_list_item *item;46134614string_list_sort(&cpath);4615if(state->apply_verbosity > verbosity_silent) {4616for_each_string_list_item(item, &cpath)4617fprintf(stderr,"U%s\n", item->string);4618}4619string_list_clear(&cpath,0);46204621rerere(0);4622}46234624return errs;4625}46264627/*4628 * Try to apply a patch.4629 *4630 * Returns:4631 * -128 if a bad error happened (like patch unreadable)4632 * -1 if patch did not apply and user cannot deal with it4633 * 0 if the patch applied4634 * 1 if the patch did not apply but user might fix it4635 */4636static intapply_patch(struct apply_state *state,4637int fd,4638const char*filename,4639int options)4640{4641size_t offset;4642struct strbuf buf = STRBUF_INIT;/* owns the patch text */4643struct patch *list = NULL, **listp = &list;4644int skipped_patch =0;4645int res =0;46464647 state->patch_input_file = filename;4648if(read_patch_file(&buf, fd) <0)4649return-128;4650 offset =0;4651while(offset < buf.len) {4652struct patch *patch;4653int nr;46544655 patch =xcalloc(1,sizeof(*patch));4656 patch->inaccurate_eof = !!(options & APPLY_OPT_INACCURATE_EOF);4657 patch->recount = !!(options & APPLY_OPT_RECOUNT);4658 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4659if(nr <0) {4660free_patch(patch);4661if(nr == -128) {4662 res = -128;4663goto end;4664}4665break;4666}4667if(state->apply_in_reverse)4668reverse_patches(patch);4669if(use_patch(state, patch)) {4670patch_stats(state, patch);4671*listp = patch;4672 listp = &patch->next;4673}4674else{4675if(state->apply_verbosity > verbosity_normal)4676say_patch_name(stderr,_("Skipped patch '%s'."), patch);4677free_patch(patch);4678 skipped_patch++;4679}4680 offset += nr;4681}46824683if(!list && !skipped_patch) {4684error(_("unrecognized input"));4685 res = -128;4686goto end;4687}46884689if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4690 state->apply =0;46914692 state->update_index = (state->check_index || state->ita_only) && state->apply;4693if(state->update_index && !is_lock_file_locked(&state->lock_file)) {4694if(state->index_file)4695hold_lock_file_for_update(&state->lock_file,4696 state->index_file,4697 LOCK_DIE_ON_ERROR);4698else4699hold_locked_index(&state->lock_file, LOCK_DIE_ON_ERROR);4700}47014702if(state->check_index &&read_apply_cache(state) <0) {4703error(_("unable to read index file"));4704 res = -128;4705goto end;4706}47074708if(state->check || state->apply) {4709int r =check_patch_list(state, list);4710if(r == -128) {4711 res = -128;4712goto end;4713}4714if(r <0&& !state->apply_with_reject) {4715 res = -1;4716goto end;4717}4718}47194720if(state->apply) {4721int write_res =write_out_results(state, list);4722if(write_res <0) {4723 res = -128;4724goto end;4725}4726if(write_res >0) {4727/* with --3way, we still need to write the index out */4728 res = state->apply_with_reject ? -1:1;4729goto end;4730}4731}47324733if(state->fake_ancestor &&4734build_fake_ancestor(state, list)) {4735 res = -128;4736goto end;4737}47384739if(state->diffstat && state->apply_verbosity > verbosity_silent)4740stat_patch_list(state, list);47414742if(state->numstat && state->apply_verbosity > verbosity_silent)4743numstat_patch_list(state, list);47444745if(state->summary && state->apply_verbosity > verbosity_silent)4746summary_patch_list(list);47474748end:4749free_patch_list(list);4750strbuf_release(&buf);4751string_list_clear(&state->fn_table,0);4752return res;4753}47544755static intapply_option_parse_exclude(const struct option *opt,4756const char*arg,int unset)4757{4758struct apply_state *state = opt->value;4759add_name_limit(state, arg,1);4760return0;4761}47624763static intapply_option_parse_include(const struct option *opt,4764const char*arg,int unset)4765{4766struct apply_state *state = opt->value;4767add_name_limit(state, arg,0);4768 state->has_include =1;4769return0;4770}47714772static intapply_option_parse_p(const struct option *opt,4773const char*arg,4774int unset)4775{4776struct apply_state *state = opt->value;4777 state->p_value =atoi(arg);4778 state->p_value_known =1;4779return0;4780}47814782static intapply_option_parse_space_change(const struct option *opt,4783const char*arg,int unset)4784{4785struct apply_state *state = opt->value;4786if(unset)4787 state->ws_ignore_action = ignore_ws_none;4788else4789 state->ws_ignore_action = ignore_ws_change;4790return0;4791}47924793static intapply_option_parse_whitespace(const struct option *opt,4794const char*arg,int unset)4795{4796struct apply_state *state = opt->value;4797 state->whitespace_option = arg;4798if(parse_whitespace_option(state, arg))4799exit(1);4800return0;4801}48024803static intapply_option_parse_directory(const struct option *opt,4804const char*arg,int unset)4805{4806struct apply_state *state = opt->value;4807strbuf_reset(&state->root);4808strbuf_addstr(&state->root, arg);4809strbuf_complete(&state->root,'/');4810return0;4811}48124813intapply_all_patches(struct apply_state *state,4814int argc,4815const char**argv,4816int options)4817{4818int i;4819int res;4820int errs =0;4821int read_stdin =1;48224823for(i =0; i < argc; i++) {4824const char*arg = argv[i];4825char*to_free = NULL;4826int fd;48274828if(!strcmp(arg,"-")) {4829 res =apply_patch(state,0,"<stdin>", options);4830if(res <0)4831goto end;4832 errs |= res;4833 read_stdin =0;4834continue;4835}else4836 arg = to_free =prefix_filename(state->prefix, arg);48374838 fd =open(arg, O_RDONLY);4839if(fd <0) {4840error(_("can't open patch '%s':%s"), arg,strerror(errno));4841 res = -128;4842free(to_free);4843goto end;4844}4845 read_stdin =0;4846set_default_whitespace_mode(state);4847 res =apply_patch(state, fd, arg, options);4848close(fd);4849free(to_free);4850if(res <0)4851goto end;4852 errs |= res;4853}4854set_default_whitespace_mode(state);4855if(read_stdin) {4856 res =apply_patch(state,0,"<stdin>", options);4857if(res <0)4858goto end;4859 errs |= res;4860}48614862if(state->whitespace_error) {4863if(state->squelch_whitespace_errors &&4864 state->squelch_whitespace_errors < state->whitespace_error) {4865int squelched =4866 state->whitespace_error - state->squelch_whitespace_errors;4867warning(Q_("squelched%dwhitespace error",4868"squelched%dwhitespace errors",4869 squelched),4870 squelched);4871}4872if(state->ws_error_action == die_on_ws_error) {4873error(Q_("%dline adds whitespace errors.",4874"%dlines add whitespace errors.",4875 state->whitespace_error),4876 state->whitespace_error);4877 res = -128;4878goto end;4879}4880if(state->applied_after_fixing_ws && state->apply)4881warning(Q_("%dline applied after"4882" fixing whitespace errors.",4883"%dlines applied after"4884" fixing whitespace errors.",4885 state->applied_after_fixing_ws),4886 state->applied_after_fixing_ws);4887else if(state->whitespace_error)4888warning(Q_("%dline adds whitespace errors.",4889"%dlines add whitespace errors.",4890 state->whitespace_error),4891 state->whitespace_error);4892}48934894if(state->update_index) {4895 res =write_locked_index(&the_index, &state->lock_file, COMMIT_LOCK);4896if(res) {4897error(_("Unable to write new index file"));4898 res = -128;4899goto end;4900}4901}49024903 res = !!errs;49044905end:4906rollback_lock_file(&state->lock_file);49074908if(state->apply_verbosity <= verbosity_silent) {4909set_error_routine(state->saved_error_routine);4910set_warn_routine(state->saved_warn_routine);4911}49124913if(res > -1)4914return res;4915return(res == -1?1:128);4916}49174918intapply_parse_options(int argc,const char**argv,4919struct apply_state *state,4920int*force_apply,int*options,4921const char*const*apply_usage)4922{4923struct option builtin_apply_options[] = {4924{ OPTION_CALLBACK,0,"exclude", state,N_("path"),4925N_("don't apply changes matching the given path"),49260, apply_option_parse_exclude },4927{ OPTION_CALLBACK,0,"include", state,N_("path"),4928N_("apply changes matching the given path"),49290, apply_option_parse_include },4930{ OPTION_CALLBACK,'p', NULL, state,N_("num"),4931N_("remove <num> leading slashes from traditional diff paths"),49320, apply_option_parse_p },4933OPT_BOOL(0,"no-add", &state->no_add,4934N_("ignore additions made by the patch")),4935OPT_BOOL(0,"stat", &state->diffstat,4936N_("instead of applying the patch, output diffstat for the input")),4937OPT_NOOP_NOARG(0,"allow-binary-replacement"),4938OPT_NOOP_NOARG(0,"binary"),4939OPT_BOOL(0,"numstat", &state->numstat,4940N_("show number of added and deleted lines in decimal notation")),4941OPT_BOOL(0,"summary", &state->summary,4942N_("instead of applying the patch, output a summary for the input")),4943OPT_BOOL(0,"check", &state->check,4944N_("instead of applying the patch, see if the patch is applicable")),4945OPT_BOOL(0,"index", &state->check_index,4946N_("make sure the patch is applicable to the current index")),4947OPT_BOOL('N',"intent-to-add", &state->ita_only,4948N_("mark new files with `git add --intent-to-add`")),4949OPT_BOOL(0,"cached", &state->cached,4950N_("apply a patch without touching the working tree")),4951OPT_BOOL_F(0,"unsafe-paths", &state->unsafe_paths,4952N_("accept a patch that touches outside the working area"),4953 PARSE_OPT_NOCOMPLETE),4954OPT_BOOL(0,"apply", force_apply,4955N_("also apply the patch (use with --stat/--summary/--check)")),4956OPT_BOOL('3',"3way", &state->threeway,4957N_("attempt three-way merge if a patch does not apply")),4958OPT_FILENAME(0,"build-fake-ancestor", &state->fake_ancestor,4959N_("build a temporary index based on embedded index information")),4960/* Think twice before adding "--nul" synonym to this */4961OPT_SET_INT('z', NULL, &state->line_termination,4962N_("paths are separated with NUL character"),'\0'),4963OPT_INTEGER('C', NULL, &state->p_context,4964N_("ensure at least <n> lines of context match")),4965{ OPTION_CALLBACK,0,"whitespace", state,N_("action"),4966N_("detect new or modified lines that have whitespace errors"),49670, apply_option_parse_whitespace },4968{ OPTION_CALLBACK,0,"ignore-space-change", state, NULL,4969N_("ignore changes in whitespace when finding context"),4970 PARSE_OPT_NOARG, apply_option_parse_space_change },4971{ OPTION_CALLBACK,0,"ignore-whitespace", state, NULL,4972N_("ignore changes in whitespace when finding context"),4973 PARSE_OPT_NOARG, apply_option_parse_space_change },4974OPT_BOOL('R',"reverse", &state->apply_in_reverse,4975N_("apply the patch in reverse")),4976OPT_BOOL(0,"unidiff-zero", &state->unidiff_zero,4977N_("don't expect at least one line of context")),4978OPT_BOOL(0,"reject", &state->apply_with_reject,4979N_("leave the rejected hunks in corresponding *.rej files")),4980OPT_BOOL(0,"allow-overlap", &state->allow_overlap,4981N_("allow overlapping hunks")),4982OPT__VERBOSE(&state->apply_verbosity,N_("be verbose")),4983OPT_BIT(0,"inaccurate-eof", options,4984N_("tolerate incorrectly detected missing new-line at the end of file"),4985 APPLY_OPT_INACCURATE_EOF),4986OPT_BIT(0,"recount", options,4987N_("do not trust the line counts in the hunk headers"),4988 APPLY_OPT_RECOUNT),4989{ OPTION_CALLBACK,0,"directory", state,N_("root"),4990N_("prepend <root> to all filenames"),49910, apply_option_parse_directory },4992OPT_END()4993};49944995returnparse_options(argc, argv, state->prefix, builtin_apply_options, apply_usage,0);4996}