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->check_index) 145 state->unsafe_paths =0; 146 147if(state->apply_verbosity <= verbosity_silent) { 148 state->saved_error_routine =get_error_routine(); 149 state->saved_warn_routine =get_warn_routine(); 150set_error_routine(mute_routine); 151set_warn_routine(mute_routine); 152} 153 154return0; 155} 156 157static voidset_default_whitespace_mode(struct apply_state *state) 158{ 159if(!state->whitespace_option && !apply_default_whitespace) 160 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 161} 162 163/* 164 * This represents one "hunk" from a patch, starting with 165 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 166 * patch text is pointed at by patch, and its byte length 167 * is stored in size. leading and trailing are the number 168 * of context lines. 169 */ 170struct fragment { 171unsigned long leading, trailing; 172unsigned long oldpos, oldlines; 173unsigned long newpos, newlines; 174/* 175 * 'patch' is usually borrowed from buf in apply_patch(), 176 * but some codepaths store an allocated buffer. 177 */ 178const char*patch; 179unsigned free_patch:1, 180 rejected:1; 181int size; 182int linenr; 183struct fragment *next; 184}; 185 186/* 187 * When dealing with a binary patch, we reuse "leading" field 188 * to store the type of the binary hunk, either deflated "delta" 189 * or deflated "literal". 190 */ 191#define binary_patch_method leading 192#define BINARY_DELTA_DEFLATED 1 193#define BINARY_LITERAL_DEFLATED 2 194 195/* 196 * This represents a "patch" to a file, both metainfo changes 197 * such as creation/deletion, filemode and content changes represented 198 * as a series of fragments. 199 */ 200struct patch { 201char*new_name, *old_name, *def_name; 202unsigned int old_mode, new_mode; 203int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 204int rejected; 205unsigned ws_rule; 206int lines_added, lines_deleted; 207int score; 208int extension_linenr;/* first line specifying delete/new/rename/copy */ 209unsigned int is_toplevel_relative:1; 210unsigned int inaccurate_eof:1; 211unsigned int is_binary:1; 212unsigned int is_copy:1; 213unsigned int is_rename:1; 214unsigned int recount:1; 215unsigned int conflicted_threeway:1; 216unsigned int direct_to_threeway:1; 217unsigned int crlf_in_old:1; 218struct fragment *fragments; 219char*result; 220size_t resultsize; 221char old_sha1_prefix[41]; 222char new_sha1_prefix[41]; 223struct patch *next; 224 225/* three-way fallback result */ 226struct object_id threeway_stage[3]; 227}; 228 229static voidfree_fragment_list(struct fragment *list) 230{ 231while(list) { 232struct fragment *next = list->next; 233if(list->free_patch) 234free((char*)list->patch); 235free(list); 236 list = next; 237} 238} 239 240static voidfree_patch(struct patch *patch) 241{ 242free_fragment_list(patch->fragments); 243free(patch->def_name); 244free(patch->old_name); 245free(patch->new_name); 246free(patch->result); 247free(patch); 248} 249 250static voidfree_patch_list(struct patch *list) 251{ 252while(list) { 253struct patch *next = list->next; 254free_patch(list); 255 list = next; 256} 257} 258 259/* 260 * A line in a file, len-bytes long (includes the terminating LF, 261 * except for an incomplete line at the end if the file ends with 262 * one), and its contents hashes to 'hash'. 263 */ 264struct line { 265size_t len; 266unsigned hash :24; 267unsigned flag :8; 268#define LINE_COMMON 1 269#define LINE_PATCHED 2 270}; 271 272/* 273 * This represents a "file", which is an array of "lines". 274 */ 275struct image { 276char*buf; 277size_t len; 278size_t nr; 279size_t alloc; 280struct line *line_allocated; 281struct line *line; 282}; 283 284static uint32_thash_line(const char*cp,size_t len) 285{ 286size_t i; 287uint32_t h; 288for(i =0, h =0; i < len; i++) { 289if(!isspace(cp[i])) { 290 h = h *3+ (cp[i] &0xff); 291} 292} 293return h; 294} 295 296/* 297 * Compare lines s1 of length n1 and s2 of length n2, ignoring 298 * whitespace difference. Returns 1 if they match, 0 otherwise 299 */ 300static intfuzzy_matchlines(const char*s1,size_t n1, 301const char*s2,size_t n2) 302{ 303const char*last1 = s1 + n1 -1; 304const char*last2 = s2 + n2 -1; 305int result =0; 306 307/* ignore line endings */ 308while((*last1 =='\r') || (*last1 =='\n')) 309 last1--; 310while((*last2 =='\r') || (*last2 =='\n')) 311 last2--; 312 313/* skip leading whitespaces, if both begin with whitespace */ 314if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 315while(isspace(*s1) && (s1 <= last1)) 316 s1++; 317while(isspace(*s2) && (s2 <= last2)) 318 s2++; 319} 320/* early return if both lines are empty */ 321if((s1 > last1) && (s2 > last2)) 322return1; 323while(!result) { 324 result = *s1++ - *s2++; 325/* 326 * Skip whitespace inside. We check for whitespace on 327 * both buffers because we don't want "a b" to match 328 * "ab" 329 */ 330if(isspace(*s1) &&isspace(*s2)) { 331while(isspace(*s1) && s1 <= last1) 332 s1++; 333while(isspace(*s2) && s2 <= last2) 334 s2++; 335} 336/* 337 * If we reached the end on one side only, 338 * lines don't match 339 */ 340if( 341((s2 > last2) && (s1 <= last1)) || 342((s1 > last1) && (s2 <= last2))) 343return0; 344if((s1 > last1) && (s2 > last2)) 345break; 346} 347 348return!result; 349} 350 351static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 352{ 353ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 354 img->line_allocated[img->nr].len = len; 355 img->line_allocated[img->nr].hash =hash_line(bol, len); 356 img->line_allocated[img->nr].flag = flag; 357 img->nr++; 358} 359 360/* 361 * "buf" has the file contents to be patched (read from various sources). 362 * attach it to "image" and add line-based index to it. 363 * "image" now owns the "buf". 364 */ 365static voidprepare_image(struct image *image,char*buf,size_t len, 366int prepare_linetable) 367{ 368const char*cp, *ep; 369 370memset(image,0,sizeof(*image)); 371 image->buf = buf; 372 image->len = len; 373 374if(!prepare_linetable) 375return; 376 377 ep = image->buf + image->len; 378 cp = image->buf; 379while(cp < ep) { 380const char*next; 381for(next = cp; next < ep && *next !='\n'; next++) 382; 383if(next < ep) 384 next++; 385add_line_info(image, cp, next - cp,0); 386 cp = next; 387} 388 image->line = image->line_allocated; 389} 390 391static voidclear_image(struct image *image) 392{ 393free(image->buf); 394free(image->line_allocated); 395memset(image,0,sizeof(*image)); 396} 397 398/* fmt must contain _one_ %s and no other substitution */ 399static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 400{ 401struct strbuf sb = STRBUF_INIT; 402 403if(patch->old_name && patch->new_name && 404strcmp(patch->old_name, patch->new_name)) { 405quote_c_style(patch->old_name, &sb, NULL,0); 406strbuf_addstr(&sb," => "); 407quote_c_style(patch->new_name, &sb, NULL,0); 408}else{ 409const char*n = patch->new_name; 410if(!n) 411 n = patch->old_name; 412quote_c_style(n, &sb, NULL,0); 413} 414fprintf(output, fmt, sb.buf); 415fputc('\n', output); 416strbuf_release(&sb); 417} 418 419#define SLOP (16) 420 421static intread_patch_file(struct strbuf *sb,int fd) 422{ 423if(strbuf_read(sb, fd,0) <0) 424returnerror_errno("git apply: failed to read"); 425 426/* 427 * Make sure that we have some slop in the buffer 428 * so that we can do speculative "memcmp" etc, and 429 * see to it that it is NUL-filled. 430 */ 431strbuf_grow(sb, SLOP); 432memset(sb->buf + sb->len,0, SLOP); 433return0; 434} 435 436static unsigned longlinelen(const char*buffer,unsigned long size) 437{ 438unsigned long len =0; 439while(size--) { 440 len++; 441if(*buffer++ =='\n') 442break; 443} 444return len; 445} 446 447static intis_dev_null(const char*str) 448{ 449returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 450} 451 452#define TERM_SPACE 1 453#define TERM_TAB 2 454 455static intname_terminate(int c,int terminate) 456{ 457if(c ==' '&& !(terminate & TERM_SPACE)) 458return0; 459if(c =='\t'&& !(terminate & TERM_TAB)) 460return0; 461 462return1; 463} 464 465/* remove double slashes to make --index work with such filenames */ 466static char*squash_slash(char*name) 467{ 468int i =0, j =0; 469 470if(!name) 471return NULL; 472 473while(name[i]) { 474if((name[j++] = name[i++]) =='/') 475while(name[i] =='/') 476 i++; 477} 478 name[j] ='\0'; 479return name; 480} 481 482static char*find_name_gnu(struct apply_state *state, 483const char*line, 484const char*def, 485int p_value) 486{ 487struct strbuf name = STRBUF_INIT; 488char*cp; 489 490/* 491 * Proposed "new-style" GNU patch/diff format; see 492 * http://marc.info/?l=git&m=112927316408690&w=2 493 */ 494if(unquote_c_style(&name, line, NULL)) { 495strbuf_release(&name); 496return NULL; 497} 498 499for(cp = name.buf; p_value; p_value--) { 500 cp =strchr(cp,'/'); 501if(!cp) { 502strbuf_release(&name); 503return NULL; 504} 505 cp++; 506} 507 508strbuf_remove(&name,0, cp - name.buf); 509if(state->root.len) 510strbuf_insert(&name,0, state->root.buf, state->root.len); 511returnsquash_slash(strbuf_detach(&name, NULL)); 512} 513 514static size_tsane_tz_len(const char*line,size_t len) 515{ 516const char*tz, *p; 517 518if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 519return0; 520 tz = line + len -strlen(" +0500"); 521 522if(tz[1] !='+'&& tz[1] !='-') 523return0; 524 525for(p = tz +2; p != line + len; p++) 526if(!isdigit(*p)) 527return0; 528 529return line + len - tz; 530} 531 532static size_ttz_with_colon_len(const char*line,size_t len) 533{ 534const char*tz, *p; 535 536if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 537return0; 538 tz = line + len -strlen(" +08:00"); 539 540if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 541return0; 542 p = tz +2; 543if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 544!isdigit(*p++) || !isdigit(*p++)) 545return0; 546 547return line + len - tz; 548} 549 550static size_tdate_len(const char*line,size_t len) 551{ 552const char*date, *p; 553 554if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 555return0; 556 p = date = line + len -strlen("72-02-05"); 557 558if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 559!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 560!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 561return0; 562 563if(date - line >=strlen("19") && 564isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 565 date -=strlen("19"); 566 567return line + len - date; 568} 569 570static size_tshort_time_len(const char*line,size_t len) 571{ 572const char*time, *p; 573 574if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 575return0; 576 p = time = line + len -strlen(" 07:01:32"); 577 578/* Permit 1-digit hours? */ 579if(*p++ !=' '|| 580!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 581!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 582!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 583return0; 584 585return line + len - time; 586} 587 588static size_tfractional_time_len(const char*line,size_t len) 589{ 590const char*p; 591size_t n; 592 593/* Expected format: 19:41:17.620000023 */ 594if(!len || !isdigit(line[len -1])) 595return0; 596 p = line + len -1; 597 598/* Fractional seconds. */ 599while(p > line &&isdigit(*p)) 600 p--; 601if(*p !='.') 602return0; 603 604/* Hours, minutes, and whole seconds. */ 605 n =short_time_len(line, p - line); 606if(!n) 607return0; 608 609return line + len - p + n; 610} 611 612static size_ttrailing_spaces_len(const char*line,size_t len) 613{ 614const char*p; 615 616/* Expected format: ' ' x (1 or more) */ 617if(!len || line[len -1] !=' ') 618return0; 619 620 p = line + len; 621while(p != line) { 622 p--; 623if(*p !=' ') 624return line + len - (p +1); 625} 626 627/* All spaces! */ 628return len; 629} 630 631static size_tdiff_timestamp_len(const char*line,size_t len) 632{ 633const char*end = line + len; 634size_t n; 635 636/* 637 * Posix: 2010-07-05 19:41:17 638 * GNU: 2010-07-05 19:41:17.620000023 -0500 639 */ 640 641if(!isdigit(end[-1])) 642return0; 643 644 n =sane_tz_len(line, end - line); 645if(!n) 646 n =tz_with_colon_len(line, end - line); 647 end -= n; 648 649 n =short_time_len(line, end - line); 650if(!n) 651 n =fractional_time_len(line, end - line); 652 end -= n; 653 654 n =date_len(line, end - line); 655if(!n)/* No date. Too bad. */ 656return0; 657 end -= n; 658 659if(end == line)/* No space before date. */ 660return0; 661if(end[-1] =='\t') {/* Success! */ 662 end--; 663return line + len - end; 664} 665if(end[-1] !=' ')/* No space before date. */ 666return0; 667 668/* Whitespace damage. */ 669 end -=trailing_spaces_len(line, end - line); 670return line + len - end; 671} 672 673static char*find_name_common(struct apply_state *state, 674const char*line, 675const char*def, 676int p_value, 677const char*end, 678int terminate) 679{ 680int len; 681const char*start = NULL; 682 683if(p_value ==0) 684 start = line; 685while(line != end) { 686char c = *line; 687 688if(!end &&isspace(c)) { 689if(c =='\n') 690break; 691if(name_terminate(c, terminate)) 692break; 693} 694 line++; 695if(c =='/'&& !--p_value) 696 start = line; 697} 698if(!start) 699returnsquash_slash(xstrdup_or_null(def)); 700 len = line - start; 701if(!len) 702returnsquash_slash(xstrdup_or_null(def)); 703 704/* 705 * Generally we prefer the shorter name, especially 706 * if the other one is just a variation of that with 707 * something else tacked on to the end (ie "file.orig" 708 * or "file~"). 709 */ 710if(def) { 711int deflen =strlen(def); 712if(deflen < len && !strncmp(start, def, deflen)) 713returnsquash_slash(xstrdup(def)); 714} 715 716if(state->root.len) { 717char*ret =xstrfmt("%s%.*s", state->root.buf, len, start); 718returnsquash_slash(ret); 719} 720 721returnsquash_slash(xmemdupz(start, len)); 722} 723 724static char*find_name(struct apply_state *state, 725const char*line, 726char*def, 727int p_value, 728int terminate) 729{ 730if(*line =='"') { 731char*name =find_name_gnu(state, line, def, p_value); 732if(name) 733return name; 734} 735 736returnfind_name_common(state, line, def, p_value, NULL, terminate); 737} 738 739static char*find_name_traditional(struct apply_state *state, 740const char*line, 741char*def, 742int p_value) 743{ 744size_t len; 745size_t date_len; 746 747if(*line =='"') { 748char*name =find_name_gnu(state, line, def, p_value); 749if(name) 750return name; 751} 752 753 len =strchrnul(line,'\n') - line; 754 date_len =diff_timestamp_len(line, len); 755if(!date_len) 756returnfind_name_common(state, line, def, p_value, NULL, TERM_TAB); 757 len -= date_len; 758 759returnfind_name_common(state, line, def, p_value, line + len,0); 760} 761 762/* 763 * Given the string after "--- " or "+++ ", guess the appropriate 764 * p_value for the given patch. 765 */ 766static intguess_p_value(struct apply_state *state,const char*nameline) 767{ 768char*name, *cp; 769int val = -1; 770 771if(is_dev_null(nameline)) 772return-1; 773 name =find_name_traditional(state, nameline, NULL,0); 774if(!name) 775return-1; 776 cp =strchr(name,'/'); 777if(!cp) 778 val =0; 779else if(state->prefix) { 780/* 781 * Does it begin with "a/$our-prefix" and such? Then this is 782 * very likely to apply to our directory. 783 */ 784if(starts_with(name, state->prefix)) 785 val =count_slashes(state->prefix); 786else{ 787 cp++; 788if(starts_with(cp, state->prefix)) 789 val =count_slashes(state->prefix) +1; 790} 791} 792free(name); 793return val; 794} 795 796/* 797 * Does the ---/+++ line have the POSIX timestamp after the last HT? 798 * GNU diff puts epoch there to signal a creation/deletion event. Is 799 * this such a timestamp? 800 */ 801static inthas_epoch_timestamp(const char*nameline) 802{ 803/* 804 * We are only interested in epoch timestamp; any non-zero 805 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 806 * For the same reason, the date must be either 1969-12-31 or 807 * 1970-01-01, and the seconds part must be "00". 808 */ 809const char stamp_regexp[] = 810"^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?" 811" " 812"([-+][0-2][0-9]:?[0-5][0-9])\n"; 813const char*timestamp = NULL, *cp, *colon; 814static regex_t *stamp; 815 regmatch_t m[10]; 816int zoneoffset, epoch_hour, hour, minute; 817int status; 818 819for(cp = nameline; *cp !='\n'; cp++) { 820if(*cp =='\t') 821 timestamp = cp +1; 822} 823if(!timestamp) 824return0; 825 826/* 827 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 828 * (west of GMT) or 1970-01-01 (east of GMT) 829 */ 830if(skip_prefix(timestamp,"1969-12-31 ", ×tamp)) 831 epoch_hour =24; 832else if(skip_prefix(timestamp,"1970-01-01 ", ×tamp)) 833 epoch_hour =0; 834else 835return0; 836 837if(!stamp) { 838 stamp =xmalloc(sizeof(*stamp)); 839if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 840warning(_("Cannot prepare timestamp regexp%s"), 841 stamp_regexp); 842return0; 843} 844} 845 846 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 847if(status) { 848if(status != REG_NOMATCH) 849warning(_("regexec returned%dfor input:%s"), 850 status, timestamp); 851return0; 852} 853 854 hour =strtol(timestamp, NULL,10); 855 minute =strtol(timestamp + m[1].rm_so, NULL,10); 856 857 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 858if(*colon ==':') 859 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 860else 861 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 862if(timestamp[m[3].rm_so] =='-') 863 zoneoffset = -zoneoffset; 864 865return hour *60+ minute - zoneoffset == epoch_hour *60; 866} 867 868/* 869 * Get the name etc info from the ---/+++ lines of a traditional patch header 870 * 871 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 872 * files, we can happily check the index for a match, but for creating a 873 * new file we should try to match whatever "patch" does. I have no idea. 874 */ 875static intparse_traditional_patch(struct apply_state *state, 876const char*first, 877const char*second, 878struct patch *patch) 879{ 880char*name; 881 882 first +=4;/* skip "--- " */ 883 second +=4;/* skip "+++ " */ 884if(!state->p_value_known) { 885int p, q; 886 p =guess_p_value(state, first); 887 q =guess_p_value(state, second); 888if(p <0) p = q; 889if(0<= p && p == q) { 890 state->p_value = p; 891 state->p_value_known =1; 892} 893} 894if(is_dev_null(first)) { 895 patch->is_new =1; 896 patch->is_delete =0; 897 name =find_name_traditional(state, second, NULL, state->p_value); 898 patch->new_name = name; 899}else if(is_dev_null(second)) { 900 patch->is_new =0; 901 patch->is_delete =1; 902 name =find_name_traditional(state, first, NULL, state->p_value); 903 patch->old_name = name; 904}else{ 905char*first_name; 906 first_name =find_name_traditional(state, first, NULL, state->p_value); 907 name =find_name_traditional(state, second, first_name, state->p_value); 908free(first_name); 909if(has_epoch_timestamp(first)) { 910 patch->is_new =1; 911 patch->is_delete =0; 912 patch->new_name = name; 913}else if(has_epoch_timestamp(second)) { 914 patch->is_new =0; 915 patch->is_delete =1; 916 patch->old_name = name; 917}else{ 918 patch->old_name = name; 919 patch->new_name =xstrdup_or_null(name); 920} 921} 922if(!name) 923returnerror(_("unable to find filename in patch at line%d"), state->linenr); 924 925return0; 926} 927 928static intgitdiff_hdrend(struct apply_state *state, 929const char*line, 930struct patch *patch) 931{ 932return1; 933} 934 935/* 936 * We're anal about diff header consistency, to make 937 * sure that we don't end up having strange ambiguous 938 * patches floating around. 939 * 940 * As a result, gitdiff_{old|new}name() will check 941 * their names against any previous information, just 942 * to make sure.. 943 */ 944#define DIFF_OLD_NAME 0 945#define DIFF_NEW_NAME 1 946 947static intgitdiff_verify_name(struct apply_state *state, 948const char*line, 949int isnull, 950char**name, 951int side) 952{ 953if(!*name && !isnull) { 954*name =find_name(state, line, NULL, state->p_value, TERM_TAB); 955return0; 956} 957 958if(*name) { 959char*another; 960if(isnull) 961returnerror(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 962*name, state->linenr); 963 another =find_name(state, line, NULL, state->p_value, TERM_TAB); 964if(!another ||strcmp(another, *name)) { 965free(another); 966returnerror((side == DIFF_NEW_NAME) ? 967_("git apply: bad git-diff - inconsistent new filename on line%d") : 968_("git apply: bad git-diff - inconsistent old filename on line%d"), state->linenr); 969} 970free(another); 971}else{ 972if(!starts_with(line,"/dev/null\n")) 973returnerror(_("git apply: bad git-diff - expected /dev/null on line%d"), state->linenr); 974} 975 976return0; 977} 978 979static intgitdiff_oldname(struct apply_state *state, 980const char*line, 981struct patch *patch) 982{ 983returngitdiff_verify_name(state, line, 984 patch->is_new, &patch->old_name, 985 DIFF_OLD_NAME); 986} 987 988static intgitdiff_newname(struct apply_state *state, 989const char*line, 990struct patch *patch) 991{ 992returngitdiff_verify_name(state, line, 993 patch->is_delete, &patch->new_name, 994 DIFF_NEW_NAME); 995} 996 997static intparse_mode_line(const char*line,int linenr,unsigned int*mode) 998{ 999char*end;1000*mode =strtoul(line, &end,8);1001if(end == line || !isspace(*end))1002returnerror(_("invalid mode on line%d:%s"), linenr, line);1003return0;1004}10051006static intgitdiff_oldmode(struct apply_state *state,1007const char*line,1008struct patch *patch)1009{1010returnparse_mode_line(line, state->linenr, &patch->old_mode);1011}10121013static intgitdiff_newmode(struct apply_state *state,1014const char*line,1015struct patch *patch)1016{1017returnparse_mode_line(line, state->linenr, &patch->new_mode);1018}10191020static intgitdiff_delete(struct apply_state *state,1021const char*line,1022struct patch *patch)1023{1024 patch->is_delete =1;1025free(patch->old_name);1026 patch->old_name =xstrdup_or_null(patch->def_name);1027returngitdiff_oldmode(state, line, patch);1028}10291030static intgitdiff_newfile(struct apply_state *state,1031const char*line,1032struct patch *patch)1033{1034 patch->is_new =1;1035free(patch->new_name);1036 patch->new_name =xstrdup_or_null(patch->def_name);1037returngitdiff_newmode(state, line, patch);1038}10391040static intgitdiff_copysrc(struct apply_state *state,1041const char*line,1042struct patch *patch)1043{1044 patch->is_copy =1;1045free(patch->old_name);1046 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1047return0;1048}10491050static intgitdiff_copydst(struct apply_state *state,1051const char*line,1052struct patch *patch)1053{1054 patch->is_copy =1;1055free(patch->new_name);1056 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1057return0;1058}10591060static intgitdiff_renamesrc(struct apply_state *state,1061const char*line,1062struct patch *patch)1063{1064 patch->is_rename =1;1065free(patch->old_name);1066 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1067return0;1068}10691070static intgitdiff_renamedst(struct apply_state *state,1071const char*line,1072struct patch *patch)1073{1074 patch->is_rename =1;1075free(patch->new_name);1076 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1077return0;1078}10791080static intgitdiff_similarity(struct apply_state *state,1081const char*line,1082struct patch *patch)1083{1084unsigned long val =strtoul(line, NULL,10);1085if(val <=100)1086 patch->score = val;1087return0;1088}10891090static intgitdiff_dissimilarity(struct apply_state *state,1091const char*line,1092struct patch *patch)1093{1094unsigned long val =strtoul(line, NULL,10);1095if(val <=100)1096 patch->score = val;1097return0;1098}10991100static intgitdiff_index(struct apply_state *state,1101const char*line,1102struct patch *patch)1103{1104/*1105 * index line is N hexadecimal, "..", N hexadecimal,1106 * and optional space with octal mode.1107 */1108const char*ptr, *eol;1109int len;11101111 ptr =strchr(line,'.');1112if(!ptr || ptr[1] !='.'||40< ptr - line)1113return0;1114 len = ptr - line;1115memcpy(patch->old_sha1_prefix, line, len);1116 patch->old_sha1_prefix[len] =0;11171118 line = ptr +2;1119 ptr =strchr(line,' ');1120 eol =strchrnul(line,'\n');11211122if(!ptr || eol < ptr)1123 ptr = eol;1124 len = ptr - line;11251126if(40< len)1127return0;1128memcpy(patch->new_sha1_prefix, line, len);1129 patch->new_sha1_prefix[len] =0;1130if(*ptr ==' ')1131returngitdiff_oldmode(state, ptr +1, patch);1132return0;1133}11341135/*1136 * This is normal for a diff that doesn't change anything: we'll fall through1137 * into the next diff. Tell the parser to break out.1138 */1139static intgitdiff_unrecognized(struct apply_state *state,1140const char*line,1141struct patch *patch)1142{1143return1;1144}11451146/*1147 * Skip p_value leading components from "line"; as we do not accept1148 * absolute paths, return NULL in that case.1149 */1150static const char*skip_tree_prefix(struct apply_state *state,1151const char*line,1152int llen)1153{1154int nslash;1155int i;11561157if(!state->p_value)1158return(llen && line[0] =='/') ? NULL : line;11591160 nslash = state->p_value;1161for(i =0; i < llen; i++) {1162int ch = line[i];1163if(ch =='/'&& --nslash <=0)1164return(i ==0) ? NULL : &line[i +1];1165}1166return NULL;1167}11681169/*1170 * This is to extract the same name that appears on "diff --git"1171 * line. We do not find and return anything if it is a rename1172 * patch, and it is OK because we will find the name elsewhere.1173 * We need to reliably find name only when it is mode-change only,1174 * creation or deletion of an empty file. In any of these cases,1175 * both sides are the same name under a/ and b/ respectively.1176 */1177static char*git_header_name(struct apply_state *state,1178const char*line,1179int llen)1180{1181const char*name;1182const char*second = NULL;1183size_t len, line_len;11841185 line +=strlen("diff --git ");1186 llen -=strlen("diff --git ");11871188if(*line =='"') {1189const char*cp;1190struct strbuf first = STRBUF_INIT;1191struct strbuf sp = STRBUF_INIT;11921193if(unquote_c_style(&first, line, &second))1194goto free_and_fail1;11951196/* strip the a/b prefix including trailing slash */1197 cp =skip_tree_prefix(state, first.buf, first.len);1198if(!cp)1199goto free_and_fail1;1200strbuf_remove(&first,0, cp - first.buf);12011202/*1203 * second points at one past closing dq of name.1204 * find the second name.1205 */1206while((second < line + llen) &&isspace(*second))1207 second++;12081209if(line + llen <= second)1210goto free_and_fail1;1211if(*second =='"') {1212if(unquote_c_style(&sp, second, NULL))1213goto free_and_fail1;1214 cp =skip_tree_prefix(state, sp.buf, sp.len);1215if(!cp)1216goto free_and_fail1;1217/* They must match, otherwise ignore */1218if(strcmp(cp, first.buf))1219goto free_and_fail1;1220strbuf_release(&sp);1221returnstrbuf_detach(&first, NULL);1222}12231224/* unquoted second */1225 cp =skip_tree_prefix(state, second, line + llen - second);1226if(!cp)1227goto free_and_fail1;1228if(line + llen - cp != first.len ||1229memcmp(first.buf, cp, first.len))1230goto free_and_fail1;1231returnstrbuf_detach(&first, NULL);12321233 free_and_fail1:1234strbuf_release(&first);1235strbuf_release(&sp);1236return NULL;1237}12381239/* unquoted first name */1240 name =skip_tree_prefix(state, line, llen);1241if(!name)1242return NULL;12431244/*1245 * since the first name is unquoted, a dq if exists must be1246 * the beginning of the second name.1247 */1248for(second = name; second < line + llen; second++) {1249if(*second =='"') {1250struct strbuf sp = STRBUF_INIT;1251const char*np;12521253if(unquote_c_style(&sp, second, NULL))1254goto free_and_fail2;12551256 np =skip_tree_prefix(state, sp.buf, sp.len);1257if(!np)1258goto free_and_fail2;12591260 len = sp.buf + sp.len - np;1261if(len < second - name &&1262!strncmp(np, name, len) &&1263isspace(name[len])) {1264/* Good */1265strbuf_remove(&sp,0, np - sp.buf);1266returnstrbuf_detach(&sp, NULL);1267}12681269 free_and_fail2:1270strbuf_release(&sp);1271return NULL;1272}1273}12741275/*1276 * Accept a name only if it shows up twice, exactly the same1277 * form.1278 */1279 second =strchr(name,'\n');1280if(!second)1281return NULL;1282 line_len = second - name;1283for(len =0; ; len++) {1284switch(name[len]) {1285default:1286continue;1287case'\n':1288return NULL;1289case'\t':case' ':1290/*1291 * Is this the separator between the preimage1292 * and the postimage pathname? Again, we are1293 * only interested in the case where there is1294 * no rename, as this is only to set def_name1295 * and a rename patch has the names elsewhere1296 * in an unambiguous form.1297 */1298if(!name[len +1])1299return NULL;/* no postimage name */1300 second =skip_tree_prefix(state, name + len +1,1301 line_len - (len +1));1302if(!second)1303return NULL;1304/*1305 * Does len bytes starting at "name" and "second"1306 * (that are separated by one HT or SP we just1307 * found) exactly match?1308 */1309if(second[len] =='\n'&& !strncmp(name, second, len))1310returnxmemdupz(name, len);1311}1312}1313}13141315static intcheck_header_line(struct apply_state *state,struct patch *patch)1316{1317int extensions = (patch->is_delete ==1) + (patch->is_new ==1) +1318(patch->is_rename ==1) + (patch->is_copy ==1);1319if(extensions >1)1320returnerror(_("inconsistent header lines%dand%d"),1321 patch->extension_linenr, state->linenr);1322if(extensions && !patch->extension_linenr)1323 patch->extension_linenr = state->linenr;1324return0;1325}13261327/* Verify that we recognize the lines following a git header */1328static intparse_git_header(struct apply_state *state,1329const char*line,1330int len,1331unsigned int size,1332struct patch *patch)1333{1334unsigned long offset;13351336/* A git diff has explicit new/delete information, so we don't guess */1337 patch->is_new =0;1338 patch->is_delete =0;13391340/*1341 * Some things may not have the old name in the1342 * rest of the headers anywhere (pure mode changes,1343 * or removing or adding empty files), so we get1344 * the default name from the header.1345 */1346 patch->def_name =git_header_name(state, line, len);1347if(patch->def_name && state->root.len) {1348char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1349free(patch->def_name);1350 patch->def_name = s;1351}13521353 line += len;1354 size -= len;1355 state->linenr++;1356for(offset = len ; size >0; offset += len, size -= len, line += len, state->linenr++) {1357static const struct opentry {1358const char*str;1359int(*fn)(struct apply_state *,const char*,struct patch *);1360} optable[] = {1361{"@@ -", gitdiff_hdrend },1362{"--- ", gitdiff_oldname },1363{"+++ ", gitdiff_newname },1364{"old mode ", gitdiff_oldmode },1365{"new mode ", gitdiff_newmode },1366{"deleted file mode ", gitdiff_delete },1367{"new file mode ", gitdiff_newfile },1368{"copy from ", gitdiff_copysrc },1369{"copy to ", gitdiff_copydst },1370{"rename old ", gitdiff_renamesrc },1371{"rename new ", gitdiff_renamedst },1372{"rename from ", gitdiff_renamesrc },1373{"rename to ", gitdiff_renamedst },1374{"similarity index ", gitdiff_similarity },1375{"dissimilarity index ", gitdiff_dissimilarity },1376{"index ", gitdiff_index },1377{"", gitdiff_unrecognized },1378};1379int i;13801381 len =linelen(line, size);1382if(!len || line[len-1] !='\n')1383break;1384for(i =0; i <ARRAY_SIZE(optable); i++) {1385const struct opentry *p = optable + i;1386int oplen =strlen(p->str);1387int res;1388if(len < oplen ||memcmp(p->str, line, oplen))1389continue;1390 res = p->fn(state, line + oplen, patch);1391if(res <0)1392return-1;1393if(check_header_line(state, patch))1394return-1;1395if(res >0)1396return offset;1397break;1398}1399}14001401return offset;1402}14031404static intparse_num(const char*line,unsigned long*p)1405{1406char*ptr;14071408if(!isdigit(*line))1409return0;1410*p =strtoul(line, &ptr,10);1411return ptr - line;1412}14131414static intparse_range(const char*line,int len,int offset,const char*expect,1415unsigned long*p1,unsigned long*p2)1416{1417int digits, ex;14181419if(offset <0|| offset >= len)1420return-1;1421 line += offset;1422 len -= offset;14231424 digits =parse_num(line, p1);1425if(!digits)1426return-1;14271428 offset += digits;1429 line += digits;1430 len -= digits;14311432*p2 =1;1433if(*line ==',') {1434 digits =parse_num(line+1, p2);1435if(!digits)1436return-1;14371438 offset += digits+1;1439 line += digits+1;1440 len -= digits+1;1441}14421443 ex =strlen(expect);1444if(ex > len)1445return-1;1446if(memcmp(line, expect, ex))1447return-1;14481449return offset + ex;1450}14511452static voidrecount_diff(const char*line,int size,struct fragment *fragment)1453{1454int oldlines =0, newlines =0, ret =0;14551456if(size <1) {1457warning("recount: ignore empty hunk");1458return;1459}14601461for(;;) {1462int len =linelen(line, size);1463 size -= len;1464 line += len;14651466if(size <1)1467break;14681469switch(*line) {1470case' ':case'\n':1471 newlines++;1472/* fall through */1473case'-':1474 oldlines++;1475continue;1476case'+':1477 newlines++;1478continue;1479case'\\':1480continue;1481case'@':1482 ret = size <3|| !starts_with(line,"@@ ");1483break;1484case'd':1485 ret = size <5|| !starts_with(line,"diff ");1486break;1487default:1488 ret = -1;1489break;1490}1491if(ret) {1492warning(_("recount: unexpected line: %.*s"),1493(int)linelen(line, size), line);1494return;1495}1496break;1497}1498 fragment->oldlines = oldlines;1499 fragment->newlines = newlines;1500}15011502/*1503 * Parse a unified diff fragment header of the1504 * form "@@ -a,b +c,d @@"1505 */1506static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1507{1508int offset;15091510if(!len || line[len-1] !='\n')1511return-1;15121513/* Figure out the number of lines in a fragment */1514 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1515 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);15161517return offset;1518}15191520/*1521 * Find file diff header1522 *1523 * Returns:1524 * -1 if no header was found1525 * -128 in case of error1526 * the size of the header in bytes (called "offset") otherwise1527 */1528static intfind_header(struct apply_state *state,1529const char*line,1530unsigned long size,1531int*hdrsize,1532struct patch *patch)1533{1534unsigned long offset, len;15351536 patch->is_toplevel_relative =0;1537 patch->is_rename = patch->is_copy =0;1538 patch->is_new = patch->is_delete = -1;1539 patch->old_mode = patch->new_mode =0;1540 patch->old_name = patch->new_name = NULL;1541for(offset =0; size >0; offset += len, size -= len, line += len, state->linenr++) {1542unsigned long nextlen;15431544 len =linelen(line, size);1545if(!len)1546break;15471548/* Testing this early allows us to take a few shortcuts.. */1549if(len <6)1550continue;15511552/*1553 * Make sure we don't find any unconnected patch fragments.1554 * That's a sign that we didn't find a header, and that a1555 * patch has become corrupted/broken up.1556 */1557if(!memcmp("@@ -", line,4)) {1558struct fragment dummy;1559if(parse_fragment_header(line, len, &dummy) <0)1560continue;1561error(_("patch fragment without header at line%d: %.*s"),1562 state->linenr, (int)len-1, line);1563return-128;1564}15651566if(size < len +6)1567break;15681569/*1570 * Git patch? It might not have a real patch, just a rename1571 * or mode change, so we handle that specially1572 */1573if(!memcmp("diff --git ", line,11)) {1574int git_hdr_len =parse_git_header(state, line, len, size, patch);1575if(git_hdr_len <0)1576return-128;1577if(git_hdr_len <= len)1578continue;1579if(!patch->old_name && !patch->new_name) {1580if(!patch->def_name) {1581error(Q_("git diff header lacks filename information when removing "1582"%dleading pathname component (line%d)",1583"git diff header lacks filename information when removing "1584"%dleading pathname components (line%d)",1585 state->p_value),1586 state->p_value, state->linenr);1587return-128;1588}1589 patch->old_name =xstrdup(patch->def_name);1590 patch->new_name =xstrdup(patch->def_name);1591}1592if((!patch->new_name && !patch->is_delete) ||1593(!patch->old_name && !patch->is_new)) {1594error(_("git diff header lacks filename information "1595"(line%d)"), state->linenr);1596return-128;1597}1598 patch->is_toplevel_relative =1;1599*hdrsize = git_hdr_len;1600return offset;1601}16021603/* --- followed by +++ ? */1604if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1605continue;16061607/*1608 * We only accept unified patches, so we want it to1609 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1610 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1611 */1612 nextlen =linelen(line + len, size - len);1613if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1614continue;16151616/* Ok, we'll consider it a patch */1617if(parse_traditional_patch(state, line, line+len, patch))1618return-128;1619*hdrsize = len + nextlen;1620 state->linenr +=2;1621return offset;1622}1623return-1;1624}16251626static voidrecord_ws_error(struct apply_state *state,1627unsigned result,1628const char*line,1629int len,1630int linenr)1631{1632char*err;16331634if(!result)1635return;16361637 state->whitespace_error++;1638if(state->squelch_whitespace_errors &&1639 state->squelch_whitespace_errors < state->whitespace_error)1640return;16411642 err =whitespace_error_string(result);1643if(state->apply_verbosity > verbosity_silent)1644fprintf(stderr,"%s:%d:%s.\n%.*s\n",1645 state->patch_input_file, linenr, err, len, line);1646free(err);1647}16481649static voidcheck_whitespace(struct apply_state *state,1650const char*line,1651int len,1652unsigned ws_rule)1653{1654unsigned result =ws_check(line +1, len -1, ws_rule);16551656record_ws_error(state, result, line +1, len -2, state->linenr);1657}16581659/*1660 * Check if the patch has context lines with CRLF or1661 * the patch wants to remove lines with CRLF.1662 */1663static voidcheck_old_for_crlf(struct patch *patch,const char*line,int len)1664{1665if(len >=2&& line[len-1] =='\n'&& line[len-2] =='\r') {1666 patch->ws_rule |= WS_CR_AT_EOL;1667 patch->crlf_in_old =1;1668}1669}167016711672/*1673 * Parse a unified diff. Note that this really needs to parse each1674 * fragment separately, since the only way to know the difference1675 * between a "---" that is part of a patch, and a "---" that starts1676 * the next patch is to look at the line counts..1677 */1678static intparse_fragment(struct apply_state *state,1679const char*line,1680unsigned long size,1681struct patch *patch,1682struct fragment *fragment)1683{1684int added, deleted;1685int len =linelen(line, size), offset;1686unsigned long oldlines, newlines;1687unsigned long leading, trailing;16881689 offset =parse_fragment_header(line, len, fragment);1690if(offset <0)1691return-1;1692if(offset >0&& patch->recount)1693recount_diff(line + offset, size - offset, fragment);1694 oldlines = fragment->oldlines;1695 newlines = fragment->newlines;1696 leading =0;1697 trailing =0;16981699/* Parse the thing.. */1700 line += len;1701 size -= len;1702 state->linenr++;1703 added = deleted =0;1704for(offset = len;17050< size;1706 offset += len, size -= len, line += len, state->linenr++) {1707if(!oldlines && !newlines)1708break;1709 len =linelen(line, size);1710if(!len || line[len-1] !='\n')1711return-1;1712switch(*line) {1713default:1714return-1;1715case'\n':/* newer GNU diff, an empty context line */1716case' ':1717 oldlines--;1718 newlines--;1719if(!deleted && !added)1720 leading++;1721 trailing++;1722check_old_for_crlf(patch, line, len);1723if(!state->apply_in_reverse &&1724 state->ws_error_action == correct_ws_error)1725check_whitespace(state, line, len, patch->ws_rule);1726break;1727case'-':1728if(!state->apply_in_reverse)1729check_old_for_crlf(patch, line, len);1730if(state->apply_in_reverse &&1731 state->ws_error_action != nowarn_ws_error)1732check_whitespace(state, line, len, patch->ws_rule);1733 deleted++;1734 oldlines--;1735 trailing =0;1736break;1737case'+':1738if(state->apply_in_reverse)1739check_old_for_crlf(patch, line, len);1740if(!state->apply_in_reverse &&1741 state->ws_error_action != nowarn_ws_error)1742check_whitespace(state, line, len, patch->ws_rule);1743 added++;1744 newlines--;1745 trailing =0;1746break;17471748/*1749 * We allow "\ No newline at end of file". Depending1750 * on locale settings when the patch was produced we1751 * don't know what this line looks like. The only1752 * thing we do know is that it begins with "\ ".1753 * Checking for 12 is just for sanity check -- any1754 * l10n of "\ No newline..." is at least that long.1755 */1756case'\\':1757if(len <12||memcmp(line,"\\",2))1758return-1;1759break;1760}1761}1762if(oldlines || newlines)1763return-1;1764if(!deleted && !added)1765return-1;17661767 fragment->leading = leading;1768 fragment->trailing = trailing;17691770/*1771 * If a fragment ends with an incomplete line, we failed to include1772 * it in the above loop because we hit oldlines == newlines == 01773 * before seeing it.1774 */1775if(12< size && !memcmp(line,"\\",2))1776 offset +=linelen(line, size);17771778 patch->lines_added += added;1779 patch->lines_deleted += deleted;17801781if(0< patch->is_new && oldlines)1782returnerror(_("new file depends on old contents"));1783if(0< patch->is_delete && newlines)1784returnerror(_("deleted file still has contents"));1785return offset;1786}17871788/*1789 * We have seen "diff --git a/... b/..." header (or a traditional patch1790 * header). Read hunks that belong to this patch into fragments and hang1791 * them to the given patch structure.1792 *1793 * The (fragment->patch, fragment->size) pair points into the memory given1794 * by the caller, not a copy, when we return.1795 *1796 * Returns:1797 * -1 in case of error,1798 * the number of bytes in the patch otherwise.1799 */1800static intparse_single_patch(struct apply_state *state,1801const char*line,1802unsigned long size,1803struct patch *patch)1804{1805unsigned long offset =0;1806unsigned long oldlines =0, newlines =0, context =0;1807struct fragment **fragp = &patch->fragments;18081809while(size >4&& !memcmp(line,"@@ -",4)) {1810struct fragment *fragment;1811int len;18121813 fragment =xcalloc(1,sizeof(*fragment));1814 fragment->linenr = state->linenr;1815 len =parse_fragment(state, line, size, patch, fragment);1816if(len <=0) {1817free(fragment);1818returnerror(_("corrupt patch at line%d"), state->linenr);1819}1820 fragment->patch = line;1821 fragment->size = len;1822 oldlines += fragment->oldlines;1823 newlines += fragment->newlines;1824 context += fragment->leading + fragment->trailing;18251826*fragp = fragment;1827 fragp = &fragment->next;18281829 offset += len;1830 line += len;1831 size -= len;1832}18331834/*1835 * If something was removed (i.e. we have old-lines) it cannot1836 * be creation, and if something was added it cannot be1837 * deletion. However, the reverse is not true; --unified=01838 * patches that only add are not necessarily creation even1839 * though they do not have any old lines, and ones that only1840 * delete are not necessarily deletion.1841 *1842 * Unfortunately, a real creation/deletion patch do _not_ have1843 * any context line by definition, so we cannot safely tell it1844 * apart with --unified=0 insanity. At least if the patch has1845 * more than one hunk it is not creation or deletion.1846 */1847if(patch->is_new <0&&1848(oldlines || (patch->fragments && patch->fragments->next)))1849 patch->is_new =0;1850if(patch->is_delete <0&&1851(newlines || (patch->fragments && patch->fragments->next)))1852 patch->is_delete =0;18531854if(0< patch->is_new && oldlines)1855returnerror(_("new file%sdepends on old contents"), patch->new_name);1856if(0< patch->is_delete && newlines)1857returnerror(_("deleted file%sstill has contents"), patch->old_name);1858if(!patch->is_delete && !newlines && context && state->apply_verbosity > verbosity_silent)1859fprintf_ln(stderr,1860_("** warning: "1861"file%sbecomes empty but is not deleted"),1862 patch->new_name);18631864return offset;1865}18661867staticinlineintmetadata_changes(struct patch *patch)1868{1869return patch->is_rename >0||1870 patch->is_copy >0||1871 patch->is_new >0||1872 patch->is_delete ||1873(patch->old_mode && patch->new_mode &&1874 patch->old_mode != patch->new_mode);1875}18761877static char*inflate_it(const void*data,unsigned long size,1878unsigned long inflated_size)1879{1880 git_zstream stream;1881void*out;1882int st;18831884memset(&stream,0,sizeof(stream));18851886 stream.next_in = (unsigned char*)data;1887 stream.avail_in = size;1888 stream.next_out = out =xmalloc(inflated_size);1889 stream.avail_out = inflated_size;1890git_inflate_init(&stream);1891 st =git_inflate(&stream, Z_FINISH);1892git_inflate_end(&stream);1893if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1894free(out);1895return NULL;1896}1897return out;1898}18991900/*1901 * Read a binary hunk and return a new fragment; fragment->patch1902 * points at an allocated memory that the caller must free, so1903 * it is marked as "->free_patch = 1".1904 */1905static struct fragment *parse_binary_hunk(struct apply_state *state,1906char**buf_p,1907unsigned long*sz_p,1908int*status_p,1909int*used_p)1910{1911/*1912 * Expect a line that begins with binary patch method ("literal"1913 * or "delta"), followed by the length of data before deflating.1914 * a sequence of 'length-byte' followed by base-85 encoded data1915 * should follow, terminated by a newline.1916 *1917 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1918 * and we would limit the patch line to 66 characters,1919 * so one line can fit up to 13 groups that would decode1920 * to 52 bytes max. The length byte 'A'-'Z' corresponds1921 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1922 */1923int llen, used;1924unsigned long size = *sz_p;1925char*buffer = *buf_p;1926int patch_method;1927unsigned long origlen;1928char*data = NULL;1929int hunk_size =0;1930struct fragment *frag;19311932 llen =linelen(buffer, size);1933 used = llen;19341935*status_p =0;19361937if(starts_with(buffer,"delta ")) {1938 patch_method = BINARY_DELTA_DEFLATED;1939 origlen =strtoul(buffer +6, NULL,10);1940}1941else if(starts_with(buffer,"literal ")) {1942 patch_method = BINARY_LITERAL_DEFLATED;1943 origlen =strtoul(buffer +8, NULL,10);1944}1945else1946return NULL;19471948 state->linenr++;1949 buffer += llen;1950while(1) {1951int byte_length, max_byte_length, newsize;1952 llen =linelen(buffer, size);1953 used += llen;1954 state->linenr++;1955if(llen ==1) {1956/* consume the blank line */1957 buffer++;1958 size--;1959break;1960}1961/*1962 * Minimum line is "A00000\n" which is 7-byte long,1963 * and the line length must be multiple of 5 plus 2.1964 */1965if((llen <7) || (llen-2) %5)1966goto corrupt;1967 max_byte_length = (llen -2) /5*4;1968 byte_length = *buffer;1969if('A'<= byte_length && byte_length <='Z')1970 byte_length = byte_length -'A'+1;1971else if('a'<= byte_length && byte_length <='z')1972 byte_length = byte_length -'a'+27;1973else1974goto corrupt;1975/* if the input length was not multiple of 4, we would1976 * have filler at the end but the filler should never1977 * exceed 3 bytes1978 */1979if(max_byte_length < byte_length ||1980 byte_length <= max_byte_length -4)1981goto corrupt;1982 newsize = hunk_size + byte_length;1983 data =xrealloc(data, newsize);1984if(decode_85(data + hunk_size, buffer +1, byte_length))1985goto corrupt;1986 hunk_size = newsize;1987 buffer += llen;1988 size -= llen;1989}19901991 frag =xcalloc(1,sizeof(*frag));1992 frag->patch =inflate_it(data, hunk_size, origlen);1993 frag->free_patch =1;1994if(!frag->patch)1995goto corrupt;1996free(data);1997 frag->size = origlen;1998*buf_p = buffer;1999*sz_p = size;2000*used_p = used;2001 frag->binary_patch_method = patch_method;2002return frag;20032004 corrupt:2005free(data);2006*status_p = -1;2007error(_("corrupt binary patch at line%d: %.*s"),2008 state->linenr-1, llen-1, buffer);2009return NULL;2010}20112012/*2013 * Returns:2014 * -1 in case of error,2015 * the length of the parsed binary patch otherwise2016 */2017static intparse_binary(struct apply_state *state,2018char*buffer,2019unsigned long size,2020struct patch *patch)2021{2022/*2023 * We have read "GIT binary patch\n"; what follows is a line2024 * that says the patch method (currently, either "literal" or2025 * "delta") and the length of data before deflating; a2026 * sequence of 'length-byte' followed by base-85 encoded data2027 * follows.2028 *2029 * When a binary patch is reversible, there is another binary2030 * hunk in the same format, starting with patch method (either2031 * "literal" or "delta") with the length of data, and a sequence2032 * of length-byte + base-85 encoded data, terminated with another2033 * empty line. This data, when applied to the postimage, produces2034 * the preimage.2035 */2036struct fragment *forward;2037struct fragment *reverse;2038int status;2039int used, used_1;20402041 forward =parse_binary_hunk(state, &buffer, &size, &status, &used);2042if(!forward && !status)2043/* there has to be one hunk (forward hunk) */2044returnerror(_("unrecognized binary patch at line%d"), state->linenr-1);2045if(status)2046/* otherwise we already gave an error message */2047return status;20482049 reverse =parse_binary_hunk(state, &buffer, &size, &status, &used_1);2050if(reverse)2051 used += used_1;2052else if(status) {2053/*2054 * Not having reverse hunk is not an error, but having2055 * a corrupt reverse hunk is.2056 */2057free((void*) forward->patch);2058free(forward);2059return status;2060}2061 forward->next = reverse;2062 patch->fragments = forward;2063 patch->is_binary =1;2064return used;2065}20662067static voidprefix_one(struct apply_state *state,char**name)2068{2069char*old_name = *name;2070if(!old_name)2071return;2072*name =prefix_filename(state->prefix, *name);2073free(old_name);2074}20752076static voidprefix_patch(struct apply_state *state,struct patch *p)2077{2078if(!state->prefix || p->is_toplevel_relative)2079return;2080prefix_one(state, &p->new_name);2081prefix_one(state, &p->old_name);2082}20832084/*2085 * include/exclude2086 */20872088static voidadd_name_limit(struct apply_state *state,2089const char*name,2090int exclude)2091{2092struct string_list_item *it;20932094 it =string_list_append(&state->limit_by_name, name);2095 it->util = exclude ? NULL : (void*)1;2096}20972098static intuse_patch(struct apply_state *state,struct patch *p)2099{2100const char*pathname = p->new_name ? p->new_name : p->old_name;2101int i;21022103/* Paths outside are not touched regardless of "--include" */2104if(state->prefix && *state->prefix) {2105const char*rest;2106if(!skip_prefix(pathname, state->prefix, &rest) || !*rest)2107return0;2108}21092110/* See if it matches any of exclude/include rule */2111for(i =0; i < state->limit_by_name.nr; i++) {2112struct string_list_item *it = &state->limit_by_name.items[i];2113if(!wildmatch(it->string, pathname,0))2114return(it->util != NULL);2115}21162117/*2118 * If we had any include, a path that does not match any rule is2119 * not used. Otherwise, we saw bunch of exclude rules (or none)2120 * and such a path is used.2121 */2122return!state->has_include;2123}21242125/*2126 * Read the patch text in "buffer" that extends for "size" bytes; stop2127 * reading after seeing a single patch (i.e. changes to a single file).2128 * Create fragments (i.e. patch hunks) and hang them to the given patch.2129 *2130 * Returns:2131 * -1 if no header was found or parse_binary() failed,2132 * -128 on another error,2133 * the number of bytes consumed otherwise,2134 * so that the caller can call us again for the next patch.2135 */2136static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2137{2138int hdrsize, patchsize;2139int offset =find_header(state, buffer, size, &hdrsize, patch);21402141if(offset <0)2142return offset;21432144prefix_patch(state, patch);21452146if(!use_patch(state, patch))2147 patch->ws_rule =0;2148else2149 patch->ws_rule =whitespace_rule(patch->new_name2150? patch->new_name2151: patch->old_name);21522153 patchsize =parse_single_patch(state,2154 buffer + offset + hdrsize,2155 size - offset - hdrsize,2156 patch);21572158if(patchsize <0)2159return-128;21602161if(!patchsize) {2162static const char git_binary[] ="GIT binary patch\n";2163int hd = hdrsize + offset;2164unsigned long llen =linelen(buffer + hd, size - hd);21652166if(llen ==sizeof(git_binary) -1&&2167!memcmp(git_binary, buffer + hd, llen)) {2168int used;2169 state->linenr++;2170 used =parse_binary(state, buffer + hd + llen,2171 size - hd - llen, patch);2172if(used <0)2173return-1;2174if(used)2175 patchsize = used + llen;2176else2177 patchsize =0;2178}2179else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2180static const char*binhdr[] = {2181"Binary files ",2182"Files ",2183 NULL,2184};2185int i;2186for(i =0; binhdr[i]; i++) {2187int len =strlen(binhdr[i]);2188if(len < size - hd &&2189!memcmp(binhdr[i], buffer + hd, len)) {2190 state->linenr++;2191 patch->is_binary =1;2192 patchsize = llen;2193break;2194}2195}2196}21972198/* Empty patch cannot be applied if it is a text patch2199 * without metadata change. A binary patch appears2200 * empty to us here.2201 */2202if((state->apply || state->check) &&2203(!patch->is_binary && !metadata_changes(patch))) {2204error(_("patch with only garbage at line%d"), state->linenr);2205return-128;2206}2207}22082209return offset + hdrsize + patchsize;2210}22112212static voidreverse_patches(struct patch *p)2213{2214for(; p; p = p->next) {2215struct fragment *frag = p->fragments;22162217SWAP(p->new_name, p->old_name);2218SWAP(p->new_mode, p->old_mode);2219SWAP(p->is_new, p->is_delete);2220SWAP(p->lines_added, p->lines_deleted);2221SWAP(p->old_sha1_prefix, p->new_sha1_prefix);22222223for(; frag; frag = frag->next) {2224SWAP(frag->newpos, frag->oldpos);2225SWAP(frag->newlines, frag->oldlines);2226}2227}2228}22292230static const char pluses[] =2231"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2232static const char minuses[]=2233"----------------------------------------------------------------------";22342235static voidshow_stats(struct apply_state *state,struct patch *patch)2236{2237struct strbuf qname = STRBUF_INIT;2238char*cp = patch->new_name ? patch->new_name : patch->old_name;2239int max, add, del;22402241quote_c_style(cp, &qname, NULL,0);22422243/*2244 * "scale" the filename2245 */2246 max = state->max_len;2247if(max >50)2248 max =50;22492250if(qname.len > max) {2251 cp =strchr(qname.buf + qname.len +3- max,'/');2252if(!cp)2253 cp = qname.buf + qname.len +3- max;2254strbuf_splice(&qname,0, cp - qname.buf,"...",3);2255}22562257if(patch->is_binary) {2258printf(" %-*s | Bin\n", max, qname.buf);2259strbuf_release(&qname);2260return;2261}22622263printf(" %-*s |", max, qname.buf);2264strbuf_release(&qname);22652266/*2267 * scale the add/delete2268 */2269 max = max + state->max_change >70?70- max : state->max_change;2270 add = patch->lines_added;2271 del = patch->lines_deleted;22722273if(state->max_change >0) {2274int total = ((add + del) * max + state->max_change /2) / state->max_change;2275 add = (add * max + state->max_change /2) / state->max_change;2276 del = total - add;2277}2278printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2279 add, pluses, del, minuses);2280}22812282static intread_old_data(struct stat *st,struct patch *patch,2283const char*path,struct strbuf *buf)2284{2285enum safe_crlf safe_crlf = patch->crlf_in_old ?2286 SAFE_CRLF_KEEP_CRLF : SAFE_CRLF_RENORMALIZE;2287switch(st->st_mode & S_IFMT) {2288case S_IFLNK:2289if(strbuf_readlink(buf, path, st->st_size) <0)2290returnerror(_("unable to read symlink%s"), path);2291return0;2292case S_IFREG:2293if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2294returnerror(_("unable to open or read%s"), path);2295/*2296 * "git apply" without "--index/--cached" should never look2297 * at the index; the target file may not have been added to2298 * the index yet, and we may not even be in any Git repository.2299 * Pass NULL to convert_to_git() to stress this; the function2300 * should never look at the index when explicit crlf option2301 * is given.2302 */2303convert_to_git(NULL, path, buf->buf, buf->len, buf, safe_crlf);2304return0;2305default:2306return-1;2307}2308}23092310/*2311 * Update the preimage, and the common lines in postimage,2312 * from buffer buf of length len. If postlen is 0 the postimage2313 * is updated in place, otherwise it's updated on a new buffer2314 * of length postlen2315 */23162317static voidupdate_pre_post_images(struct image *preimage,2318struct image *postimage,2319char*buf,2320size_t len,size_t postlen)2321{2322int i, ctx, reduced;2323char*new, *old, *fixed;2324struct image fixed_preimage;23252326/*2327 * Update the preimage with whitespace fixes. Note that we2328 * are not losing preimage->buf -- apply_one_fragment() will2329 * free "oldlines".2330 */2331prepare_image(&fixed_preimage, buf, len,1);2332assert(postlen2333? fixed_preimage.nr == preimage->nr2334: fixed_preimage.nr <= preimage->nr);2335for(i =0; i < fixed_preimage.nr; i++)2336 fixed_preimage.line[i].flag = preimage->line[i].flag;2337free(preimage->line_allocated);2338*preimage = fixed_preimage;23392340/*2341 * Adjust the common context lines in postimage. This can be2342 * done in-place when we are shrinking it with whitespace2343 * fixing, but needs a new buffer when ignoring whitespace or2344 * expanding leading tabs to spaces.2345 *2346 * We trust the caller to tell us if the update can be done2347 * in place (postlen==0) or not.2348 */2349 old = postimage->buf;2350if(postlen)2351new= postimage->buf =xmalloc(postlen);2352else2353new= old;2354 fixed = preimage->buf;23552356for(i = reduced = ctx =0; i < postimage->nr; i++) {2357size_t l_len = postimage->line[i].len;2358if(!(postimage->line[i].flag & LINE_COMMON)) {2359/* an added line -- no counterparts in preimage */2360memmove(new, old, l_len);2361 old += l_len;2362new+= l_len;2363continue;2364}23652366/* a common context -- skip it in the original postimage */2367 old += l_len;23682369/* and find the corresponding one in the fixed preimage */2370while(ctx < preimage->nr &&2371!(preimage->line[ctx].flag & LINE_COMMON)) {2372 fixed += preimage->line[ctx].len;2373 ctx++;2374}23752376/*2377 * preimage is expected to run out, if the caller2378 * fixed addition of trailing blank lines.2379 */2380if(preimage->nr <= ctx) {2381 reduced++;2382continue;2383}23842385/* and copy it in, while fixing the line length */2386 l_len = preimage->line[ctx].len;2387memcpy(new, fixed, l_len);2388new+= l_len;2389 fixed += l_len;2390 postimage->line[i].len = l_len;2391 ctx++;2392}23932394if(postlen2395? postlen <new- postimage->buf2396: postimage->len <new- postimage->buf)2397die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2398(int)postlen, (int) postimage->len, (int)(new- postimage->buf));23992400/* Fix the length of the whole thing */2401 postimage->len =new- postimage->buf;2402 postimage->nr -= reduced;2403}24042405static intline_by_line_fuzzy_match(struct image *img,2406struct image *preimage,2407struct image *postimage,2408unsigned longtry,2409int try_lno,2410int preimage_limit)2411{2412int i;2413size_t imgoff =0;2414size_t preoff =0;2415size_t postlen = postimage->len;2416size_t extra_chars;2417char*buf;2418char*preimage_eof;2419char*preimage_end;2420struct strbuf fixed;2421char*fixed_buf;2422size_t fixed_len;24232424for(i =0; i < preimage_limit; i++) {2425size_t prelen = preimage->line[i].len;2426size_t imglen = img->line[try_lno+i].len;24272428if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2429 preimage->buf + preoff, prelen))2430return0;2431if(preimage->line[i].flag & LINE_COMMON)2432 postlen += imglen - prelen;2433 imgoff += imglen;2434 preoff += prelen;2435}24362437/*2438 * Ok, the preimage matches with whitespace fuzz.2439 *2440 * imgoff now holds the true length of the target that2441 * matches the preimage before the end of the file.2442 *2443 * Count the number of characters in the preimage that fall2444 * beyond the end of the file and make sure that all of them2445 * are whitespace characters. (This can only happen if2446 * we are removing blank lines at the end of the file.)2447 */2448 buf = preimage_eof = preimage->buf + preoff;2449for( ; i < preimage->nr; i++)2450 preoff += preimage->line[i].len;2451 preimage_end = preimage->buf + preoff;2452for( ; buf < preimage_end; buf++)2453if(!isspace(*buf))2454return0;24552456/*2457 * Update the preimage and the common postimage context2458 * lines to use the same whitespace as the target.2459 * If whitespace is missing in the target (i.e.2460 * if the preimage extends beyond the end of the file),2461 * use the whitespace from the preimage.2462 */2463 extra_chars = preimage_end - preimage_eof;2464strbuf_init(&fixed, imgoff + extra_chars);2465strbuf_add(&fixed, img->buf +try, imgoff);2466strbuf_add(&fixed, preimage_eof, extra_chars);2467 fixed_buf =strbuf_detach(&fixed, &fixed_len);2468update_pre_post_images(preimage, postimage,2469 fixed_buf, fixed_len, postlen);2470return1;2471}24722473static intmatch_fragment(struct apply_state *state,2474struct image *img,2475struct image *preimage,2476struct image *postimage,2477unsigned longtry,2478int try_lno,2479unsigned ws_rule,2480int match_beginning,int match_end)2481{2482int i;2483char*fixed_buf, *buf, *orig, *target;2484struct strbuf fixed;2485size_t fixed_len, postlen;2486int preimage_limit;24872488if(preimage->nr + try_lno <= img->nr) {2489/*2490 * The hunk falls within the boundaries of img.2491 */2492 preimage_limit = preimage->nr;2493if(match_end && (preimage->nr + try_lno != img->nr))2494return0;2495}else if(state->ws_error_action == correct_ws_error &&2496(ws_rule & WS_BLANK_AT_EOF)) {2497/*2498 * This hunk extends beyond the end of img, and we are2499 * removing blank lines at the end of the file. This2500 * many lines from the beginning of the preimage must2501 * match with img, and the remainder of the preimage2502 * must be blank.2503 */2504 preimage_limit = img->nr - try_lno;2505}else{2506/*2507 * The hunk extends beyond the end of the img and2508 * we are not removing blanks at the end, so we2509 * should reject the hunk at this position.2510 */2511return0;2512}25132514if(match_beginning && try_lno)2515return0;25162517/* Quick hash check */2518for(i =0; i < preimage_limit; i++)2519if((img->line[try_lno + i].flag & LINE_PATCHED) ||2520(preimage->line[i].hash != img->line[try_lno + i].hash))2521return0;25222523if(preimage_limit == preimage->nr) {2524/*2525 * Do we have an exact match? If we were told to match2526 * at the end, size must be exactly at try+fragsize,2527 * otherwise try+fragsize must be still within the preimage,2528 * and either case, the old piece should match the preimage2529 * exactly.2530 */2531if((match_end2532? (try+ preimage->len == img->len)2533: (try+ preimage->len <= img->len)) &&2534!memcmp(img->buf +try, preimage->buf, preimage->len))2535return1;2536}else{2537/*2538 * The preimage extends beyond the end of img, so2539 * there cannot be an exact match.2540 *2541 * There must be one non-blank context line that match2542 * a line before the end of img.2543 */2544char*buf_end;25452546 buf = preimage->buf;2547 buf_end = buf;2548for(i =0; i < preimage_limit; i++)2549 buf_end += preimage->line[i].len;25502551for( ; buf < buf_end; buf++)2552if(!isspace(*buf))2553break;2554if(buf == buf_end)2555return0;2556}25572558/*2559 * No exact match. If we are ignoring whitespace, run a line-by-line2560 * fuzzy matching. We collect all the line length information because2561 * we need it to adjust whitespace if we match.2562 */2563if(state->ws_ignore_action == ignore_ws_change)2564returnline_by_line_fuzzy_match(img, preimage, postimage,2565try, try_lno, preimage_limit);25662567if(state->ws_error_action != correct_ws_error)2568return0;25692570/*2571 * The hunk does not apply byte-by-byte, but the hash says2572 * it might with whitespace fuzz. We weren't asked to2573 * ignore whitespace, we were asked to correct whitespace2574 * errors, so let's try matching after whitespace correction.2575 *2576 * While checking the preimage against the target, whitespace2577 * errors in both fixed, we count how large the corresponding2578 * postimage needs to be. The postimage prepared by2579 * apply_one_fragment() has whitespace errors fixed on added2580 * lines already, but the common lines were propagated as-is,2581 * which may become longer when their whitespace errors are2582 * fixed.2583 */25842585/* First count added lines in postimage */2586 postlen =0;2587for(i =0; i < postimage->nr; i++) {2588if(!(postimage->line[i].flag & LINE_COMMON))2589 postlen += postimage->line[i].len;2590}25912592/*2593 * The preimage may extend beyond the end of the file,2594 * but in this loop we will only handle the part of the2595 * preimage that falls within the file.2596 */2597strbuf_init(&fixed, preimage->len +1);2598 orig = preimage->buf;2599 target = img->buf +try;2600for(i =0; i < preimage_limit; i++) {2601size_t oldlen = preimage->line[i].len;2602size_t tgtlen = img->line[try_lno + i].len;2603size_t fixstart = fixed.len;2604struct strbuf tgtfix;2605int match;26062607/* Try fixing the line in the preimage */2608ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);26092610/* Try fixing the line in the target */2611strbuf_init(&tgtfix, tgtlen);2612ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);26132614/*2615 * If they match, either the preimage was based on2616 * a version before our tree fixed whitespace breakage,2617 * or we are lacking a whitespace-fix patch the tree2618 * the preimage was based on already had (i.e. target2619 * has whitespace breakage, the preimage doesn't).2620 * In either case, we are fixing the whitespace breakages2621 * so we might as well take the fix together with their2622 * real change.2623 */2624 match = (tgtfix.len == fixed.len - fixstart &&2625!memcmp(tgtfix.buf, fixed.buf + fixstart,2626 fixed.len - fixstart));26272628/* Add the length if this is common with the postimage */2629if(preimage->line[i].flag & LINE_COMMON)2630 postlen += tgtfix.len;26312632strbuf_release(&tgtfix);2633if(!match)2634goto unmatch_exit;26352636 orig += oldlen;2637 target += tgtlen;2638}263926402641/*2642 * Now handle the lines in the preimage that falls beyond the2643 * end of the file (if any). They will only match if they are2644 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2645 * false).2646 */2647for( ; i < preimage->nr; i++) {2648size_t fixstart = fixed.len;/* start of the fixed preimage */2649size_t oldlen = preimage->line[i].len;2650int j;26512652/* Try fixing the line in the preimage */2653ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);26542655for(j = fixstart; j < fixed.len; j++)2656if(!isspace(fixed.buf[j]))2657goto unmatch_exit;26582659 orig += oldlen;2660}26612662/*2663 * Yes, the preimage is based on an older version that still2664 * has whitespace breakages unfixed, and fixing them makes the2665 * hunk match. Update the context lines in the postimage.2666 */2667 fixed_buf =strbuf_detach(&fixed, &fixed_len);2668if(postlen < postimage->len)2669 postlen =0;2670update_pre_post_images(preimage, postimage,2671 fixed_buf, fixed_len, postlen);2672return1;26732674 unmatch_exit:2675strbuf_release(&fixed);2676return0;2677}26782679static intfind_pos(struct apply_state *state,2680struct image *img,2681struct image *preimage,2682struct image *postimage,2683int line,2684unsigned ws_rule,2685int match_beginning,int match_end)2686{2687int i;2688unsigned long backwards, forwards,try;2689int backwards_lno, forwards_lno, try_lno;26902691/*2692 * If match_beginning or match_end is specified, there is no2693 * point starting from a wrong line that will never match and2694 * wander around and wait for a match at the specified end.2695 */2696if(match_beginning)2697 line =0;2698else if(match_end)2699 line = img->nr - preimage->nr;27002701/*2702 * Because the comparison is unsigned, the following test2703 * will also take care of a negative line number that can2704 * result when match_end and preimage is larger than the target.2705 */2706if((size_t) line > img->nr)2707 line = img->nr;27082709try=0;2710for(i =0; i < line; i++)2711try+= img->line[i].len;27122713/*2714 * There's probably some smart way to do this, but I'll leave2715 * that to the smart and beautiful people. I'm simple and stupid.2716 */2717 backwards =try;2718 backwards_lno = line;2719 forwards =try;2720 forwards_lno = line;2721 try_lno = line;27222723for(i =0; ; i++) {2724if(match_fragment(state, img, preimage, postimage,2725try, try_lno, ws_rule,2726 match_beginning, match_end))2727return try_lno;27282729 again:2730if(backwards_lno ==0&& forwards_lno == img->nr)2731break;27322733if(i &1) {2734if(backwards_lno ==0) {2735 i++;2736goto again;2737}2738 backwards_lno--;2739 backwards -= img->line[backwards_lno].len;2740try= backwards;2741 try_lno = backwards_lno;2742}else{2743if(forwards_lno == img->nr) {2744 i++;2745goto again;2746}2747 forwards += img->line[forwards_lno].len;2748 forwards_lno++;2749try= forwards;2750 try_lno = forwards_lno;2751}27522753}2754return-1;2755}27562757static voidremove_first_line(struct image *img)2758{2759 img->buf += img->line[0].len;2760 img->len -= img->line[0].len;2761 img->line++;2762 img->nr--;2763}27642765static voidremove_last_line(struct image *img)2766{2767 img->len -= img->line[--img->nr].len;2768}27692770/*2771 * The change from "preimage" and "postimage" has been found to2772 * apply at applied_pos (counts in line numbers) in "img".2773 * Update "img" to remove "preimage" and replace it with "postimage".2774 */2775static voidupdate_image(struct apply_state *state,2776struct image *img,2777int applied_pos,2778struct image *preimage,2779struct image *postimage)2780{2781/*2782 * remove the copy of preimage at offset in img2783 * and replace it with postimage2784 */2785int i, nr;2786size_t remove_count, insert_count, applied_at =0;2787char*result;2788int preimage_limit;27892790/*2791 * If we are removing blank lines at the end of img,2792 * the preimage may extend beyond the end.2793 * If that is the case, we must be careful only to2794 * remove the part of the preimage that falls within2795 * the boundaries of img. Initialize preimage_limit2796 * to the number of lines in the preimage that falls2797 * within the boundaries.2798 */2799 preimage_limit = preimage->nr;2800if(preimage_limit > img->nr - applied_pos)2801 preimage_limit = img->nr - applied_pos;28022803for(i =0; i < applied_pos; i++)2804 applied_at += img->line[i].len;28052806 remove_count =0;2807for(i =0; i < preimage_limit; i++)2808 remove_count += img->line[applied_pos + i].len;2809 insert_count = postimage->len;28102811/* Adjust the contents */2812 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2813memcpy(result, img->buf, applied_at);2814memcpy(result + applied_at, postimage->buf, postimage->len);2815memcpy(result + applied_at + postimage->len,2816 img->buf + (applied_at + remove_count),2817 img->len - (applied_at + remove_count));2818free(img->buf);2819 img->buf = result;2820 img->len += insert_count - remove_count;2821 result[img->len] ='\0';28222823/* Adjust the line table */2824 nr = img->nr + postimage->nr - preimage_limit;2825if(preimage_limit < postimage->nr) {2826/*2827 * NOTE: this knows that we never call remove_first_line()2828 * on anything other than pre/post image.2829 */2830REALLOC_ARRAY(img->line, nr);2831 img->line_allocated = img->line;2832}2833if(preimage_limit != postimage->nr)2834MOVE_ARRAY(img->line + applied_pos + postimage->nr,2835 img->line + applied_pos + preimage_limit,2836 img->nr - (applied_pos + preimage_limit));2837COPY_ARRAY(img->line + applied_pos, postimage->line, postimage->nr);2838if(!state->allow_overlap)2839for(i =0; i < postimage->nr; i++)2840 img->line[applied_pos + i].flag |= LINE_PATCHED;2841 img->nr = nr;2842}28432844/*2845 * Use the patch-hunk text in "frag" to prepare two images (preimage and2846 * postimage) for the hunk. Find lines that match "preimage" in "img" and2847 * replace the part of "img" with "postimage" text.2848 */2849static intapply_one_fragment(struct apply_state *state,2850struct image *img,struct fragment *frag,2851int inaccurate_eof,unsigned ws_rule,2852int nth_fragment)2853{2854int match_beginning, match_end;2855const char*patch = frag->patch;2856int size = frag->size;2857char*old, *oldlines;2858struct strbuf newlines;2859int new_blank_lines_at_end =0;2860int found_new_blank_lines_at_end =0;2861int hunk_linenr = frag->linenr;2862unsigned long leading, trailing;2863int pos, applied_pos;2864struct image preimage;2865struct image postimage;28662867memset(&preimage,0,sizeof(preimage));2868memset(&postimage,0,sizeof(postimage));2869 oldlines =xmalloc(size);2870strbuf_init(&newlines, size);28712872 old = oldlines;2873while(size >0) {2874char first;2875int len =linelen(patch, size);2876int plen;2877int added_blank_line =0;2878int is_blank_context =0;2879size_t start;28802881if(!len)2882break;28832884/*2885 * "plen" is how much of the line we should use for2886 * the actual patch data. Normally we just remove the2887 * first character on the line, but if the line is2888 * followed by "\ No newline", then we also remove the2889 * last one (which is the newline, of course).2890 */2891 plen = len -1;2892if(len < size && patch[len] =='\\')2893 plen--;2894 first = *patch;2895if(state->apply_in_reverse) {2896if(first =='-')2897 first ='+';2898else if(first =='+')2899 first ='-';2900}29012902switch(first) {2903case'\n':2904/* Newer GNU diff, empty context line */2905if(plen <0)2906/* ... followed by '\No newline'; nothing */2907break;2908*old++ ='\n';2909strbuf_addch(&newlines,'\n');2910add_line_info(&preimage,"\n",1, LINE_COMMON);2911add_line_info(&postimage,"\n",1, LINE_COMMON);2912 is_blank_context =1;2913break;2914case' ':2915if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2916ws_blank_line(patch +1, plen, ws_rule))2917 is_blank_context =1;2918/* fallthrough */2919case'-':2920memcpy(old, patch +1, plen);2921add_line_info(&preimage, old, plen,2922(first ==' '? LINE_COMMON :0));2923 old += plen;2924if(first =='-')2925break;2926/* fallthrough */2927case'+':2928/* --no-add does not add new lines */2929if(first =='+'&& state->no_add)2930break;29312932 start = newlines.len;2933if(first !='+'||2934!state->whitespace_error ||2935 state->ws_error_action != correct_ws_error) {2936strbuf_add(&newlines, patch +1, plen);2937}2938else{2939ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2940}2941add_line_info(&postimage, newlines.buf + start, newlines.len - start,2942(first =='+'?0: LINE_COMMON));2943if(first =='+'&&2944(ws_rule & WS_BLANK_AT_EOF) &&2945ws_blank_line(patch +1, plen, ws_rule))2946 added_blank_line =1;2947break;2948case'@':case'\\':2949/* Ignore it, we already handled it */2950break;2951default:2952if(state->apply_verbosity > verbosity_normal)2953error(_("invalid start of line: '%c'"), first);2954 applied_pos = -1;2955goto out;2956}2957if(added_blank_line) {2958if(!new_blank_lines_at_end)2959 found_new_blank_lines_at_end = hunk_linenr;2960 new_blank_lines_at_end++;2961}2962else if(is_blank_context)2963;2964else2965 new_blank_lines_at_end =0;2966 patch += len;2967 size -= len;2968 hunk_linenr++;2969}2970if(inaccurate_eof &&2971 old > oldlines && old[-1] =='\n'&&2972 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2973 old--;2974strbuf_setlen(&newlines, newlines.len -1);2975}29762977 leading = frag->leading;2978 trailing = frag->trailing;29792980/*2981 * A hunk to change lines at the beginning would begin with2982 * @@ -1,L +N,M @@2983 * but we need to be careful. -U0 that inserts before the second2984 * line also has this pattern.2985 *2986 * And a hunk to add to an empty file would begin with2987 * @@ -0,0 +N,M @@2988 *2989 * In other words, a hunk that is (frag->oldpos <= 1) with or2990 * without leading context must match at the beginning.2991 */2992 match_beginning = (!frag->oldpos ||2993(frag->oldpos ==1&& !state->unidiff_zero));29942995/*2996 * A hunk without trailing lines must match at the end.2997 * However, we simply cannot tell if a hunk must match end2998 * from the lack of trailing lines if the patch was generated2999 * with unidiff without any context.3000 */3001 match_end = !state->unidiff_zero && !trailing;30023003 pos = frag->newpos ? (frag->newpos -1) :0;3004 preimage.buf = oldlines;3005 preimage.len = old - oldlines;3006 postimage.buf = newlines.buf;3007 postimage.len = newlines.len;3008 preimage.line = preimage.line_allocated;3009 postimage.line = postimage.line_allocated;30103011for(;;) {30123013 applied_pos =find_pos(state, img, &preimage, &postimage, pos,3014 ws_rule, match_beginning, match_end);30153016if(applied_pos >=0)3017break;30183019/* Am I at my context limits? */3020if((leading <= state->p_context) && (trailing <= state->p_context))3021break;3022if(match_beginning || match_end) {3023 match_beginning = match_end =0;3024continue;3025}30263027/*3028 * Reduce the number of context lines; reduce both3029 * leading and trailing if they are equal otherwise3030 * just reduce the larger context.3031 */3032if(leading >= trailing) {3033remove_first_line(&preimage);3034remove_first_line(&postimage);3035 pos--;3036 leading--;3037}3038if(trailing > leading) {3039remove_last_line(&preimage);3040remove_last_line(&postimage);3041 trailing--;3042}3043}30443045if(applied_pos >=0) {3046if(new_blank_lines_at_end &&3047 preimage.nr + applied_pos >= img->nr &&3048(ws_rule & WS_BLANK_AT_EOF) &&3049 state->ws_error_action != nowarn_ws_error) {3050record_ws_error(state, WS_BLANK_AT_EOF,"+",1,3051 found_new_blank_lines_at_end);3052if(state->ws_error_action == correct_ws_error) {3053while(new_blank_lines_at_end--)3054remove_last_line(&postimage);3055}3056/*3057 * We would want to prevent write_out_results()3058 * from taking place in apply_patch() that follows3059 * the callchain led us here, which is:3060 * apply_patch->check_patch_list->check_patch->3061 * apply_data->apply_fragments->apply_one_fragment3062 */3063if(state->ws_error_action == die_on_ws_error)3064 state->apply =0;3065}30663067if(state->apply_verbosity > verbosity_normal && applied_pos != pos) {3068int offset = applied_pos - pos;3069if(state->apply_in_reverse)3070 offset =0- offset;3071fprintf_ln(stderr,3072Q_("Hunk #%dsucceeded at%d(offset%dline).",3073"Hunk #%dsucceeded at%d(offset%dlines).",3074 offset),3075 nth_fragment, applied_pos +1, offset);3076}30773078/*3079 * Warn if it was necessary to reduce the number3080 * of context lines.3081 */3082if((leading != frag->leading ||3083 trailing != frag->trailing) && state->apply_verbosity > verbosity_silent)3084fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"3085" to apply fragment at%d"),3086 leading, trailing, applied_pos+1);3087update_image(state, img, applied_pos, &preimage, &postimage);3088}else{3089if(state->apply_verbosity > verbosity_normal)3090error(_("while searching for:\n%.*s"),3091(int)(old - oldlines), oldlines);3092}30933094out:3095free(oldlines);3096strbuf_release(&newlines);3097free(preimage.line_allocated);3098free(postimage.line_allocated);30993100return(applied_pos <0);3101}31023103static intapply_binary_fragment(struct apply_state *state,3104struct image *img,3105struct patch *patch)3106{3107struct fragment *fragment = patch->fragments;3108unsigned long len;3109void*dst;31103111if(!fragment)3112returnerror(_("missing binary patch data for '%s'"),3113 patch->new_name ?3114 patch->new_name :3115 patch->old_name);31163117/* Binary patch is irreversible without the optional second hunk */3118if(state->apply_in_reverse) {3119if(!fragment->next)3120returnerror(_("cannot reverse-apply a binary patch "3121"without the reverse hunk to '%s'"),3122 patch->new_name3123? patch->new_name : patch->old_name);3124 fragment = fragment->next;3125}3126switch(fragment->binary_patch_method) {3127case BINARY_DELTA_DEFLATED:3128 dst =patch_delta(img->buf, img->len, fragment->patch,3129 fragment->size, &len);3130if(!dst)3131return-1;3132clear_image(img);3133 img->buf = dst;3134 img->len = len;3135return0;3136case BINARY_LITERAL_DEFLATED:3137clear_image(img);3138 img->len = fragment->size;3139 img->buf =xmemdupz(fragment->patch, img->len);3140return0;3141}3142return-1;3143}31443145/*3146 * Replace "img" with the result of applying the binary patch.3147 * The binary patch data itself in patch->fragment is still kept3148 * but the preimage prepared by the caller in "img" is freed here3149 * or in the helper function apply_binary_fragment() this calls.3150 */3151static intapply_binary(struct apply_state *state,3152struct image *img,3153struct patch *patch)3154{3155const char*name = patch->old_name ? patch->old_name : patch->new_name;3156struct object_id oid;31573158/*3159 * For safety, we require patch index line to contain3160 * full 40-byte textual SHA1 for old and new, at least for now.3161 */3162if(strlen(patch->old_sha1_prefix) !=40||3163strlen(patch->new_sha1_prefix) !=40||3164get_oid_hex(patch->old_sha1_prefix, &oid) ||3165get_oid_hex(patch->new_sha1_prefix, &oid))3166returnerror(_("cannot apply binary patch to '%s' "3167"without full index line"), name);31683169if(patch->old_name) {3170/*3171 * See if the old one matches what the patch3172 * applies to.3173 */3174hash_sha1_file(img->buf, img->len, blob_type, oid.hash);3175if(strcmp(oid_to_hex(&oid), patch->old_sha1_prefix))3176returnerror(_("the patch applies to '%s' (%s), "3177"which does not match the "3178"current contents."),3179 name,oid_to_hex(&oid));3180}3181else{3182/* Otherwise, the old one must be empty. */3183if(img->len)3184returnerror(_("the patch applies to an empty "3185"'%s' but it is not empty"), name);3186}31873188get_oid_hex(patch->new_sha1_prefix, &oid);3189if(is_null_oid(&oid)) {3190clear_image(img);3191return0;/* deletion patch */3192}31933194if(has_sha1_file(oid.hash)) {3195/* We already have the postimage */3196enum object_type type;3197unsigned long size;3198char*result;31993200 result =read_sha1_file(oid.hash, &type, &size);3201if(!result)3202returnerror(_("the necessary postimage%sfor "3203"'%s' cannot be read"),3204 patch->new_sha1_prefix, name);3205clear_image(img);3206 img->buf = result;3207 img->len = size;3208}else{3209/*3210 * We have verified buf matches the preimage;3211 * apply the patch data to it, which is stored3212 * in the patch->fragments->{patch,size}.3213 */3214if(apply_binary_fragment(state, img, patch))3215returnerror(_("binary patch does not apply to '%s'"),3216 name);32173218/* verify that the result matches */3219hash_sha1_file(img->buf, img->len, blob_type, oid.hash);3220if(strcmp(oid_to_hex(&oid), patch->new_sha1_prefix))3221returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3222 name, patch->new_sha1_prefix,oid_to_hex(&oid));3223}32243225return0;3226}32273228static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3229{3230struct fragment *frag = patch->fragments;3231const char*name = patch->old_name ? patch->old_name : patch->new_name;3232unsigned ws_rule = patch->ws_rule;3233unsigned inaccurate_eof = patch->inaccurate_eof;3234int nth =0;32353236if(patch->is_binary)3237returnapply_binary(state, img, patch);32383239while(frag) {3240 nth++;3241if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3242error(_("patch failed:%s:%ld"), name, frag->oldpos);3243if(!state->apply_with_reject)3244return-1;3245 frag->rejected =1;3246}3247 frag = frag->next;3248}3249return0;3250}32513252static intread_blob_object(struct strbuf *buf,const struct object_id *oid,unsigned mode)3253{3254if(S_ISGITLINK(mode)) {3255strbuf_grow(buf,100);3256strbuf_addf(buf,"Subproject commit%s\n",oid_to_hex(oid));3257}else{3258enum object_type type;3259unsigned long sz;3260char*result;32613262 result =read_sha1_file(oid->hash, &type, &sz);3263if(!result)3264return-1;3265/* XXX read_sha1_file NUL-terminates */3266strbuf_attach(buf, result, sz, sz +1);3267}3268return0;3269}32703271static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3272{3273if(!ce)3274return0;3275returnread_blob_object(buf, &ce->oid, ce->ce_mode);3276}32773278static struct patch *in_fn_table(struct apply_state *state,const char*name)3279{3280struct string_list_item *item;32813282if(name == NULL)3283return NULL;32843285 item =string_list_lookup(&state->fn_table, name);3286if(item != NULL)3287return(struct patch *)item->util;32883289return NULL;3290}32913292/*3293 * item->util in the filename table records the status of the path.3294 * Usually it points at a patch (whose result records the contents3295 * of it after applying it), but it could be PATH_WAS_DELETED for a3296 * path that a previously applied patch has already removed, or3297 * PATH_TO_BE_DELETED for a path that a later patch would remove.3298 *3299 * The latter is needed to deal with a case where two paths A and B3300 * are swapped by first renaming A to B and then renaming B to A;3301 * moving A to B should not be prevented due to presence of B as we3302 * will remove it in a later patch.3303 */3304#define PATH_TO_BE_DELETED ((struct patch *) -2)3305#define PATH_WAS_DELETED ((struct patch *) -1)33063307static intto_be_deleted(struct patch *patch)3308{3309return patch == PATH_TO_BE_DELETED;3310}33113312static intwas_deleted(struct patch *patch)3313{3314return patch == PATH_WAS_DELETED;3315}33163317static voidadd_to_fn_table(struct apply_state *state,struct patch *patch)3318{3319struct string_list_item *item;33203321/*3322 * Always add new_name unless patch is a deletion3323 * This should cover the cases for normal diffs,3324 * file creations and copies3325 */3326if(patch->new_name != NULL) {3327 item =string_list_insert(&state->fn_table, patch->new_name);3328 item->util = patch;3329}33303331/*3332 * store a failure on rename/deletion cases because3333 * later chunks shouldn't patch old names3334 */3335if((patch->new_name == NULL) || (patch->is_rename)) {3336 item =string_list_insert(&state->fn_table, patch->old_name);3337 item->util = PATH_WAS_DELETED;3338}3339}33403341static voidprepare_fn_table(struct apply_state *state,struct patch *patch)3342{3343/*3344 * store information about incoming file deletion3345 */3346while(patch) {3347if((patch->new_name == NULL) || (patch->is_rename)) {3348struct string_list_item *item;3349 item =string_list_insert(&state->fn_table, patch->old_name);3350 item->util = PATH_TO_BE_DELETED;3351}3352 patch = patch->next;3353}3354}33553356static intcheckout_target(struct index_state *istate,3357struct cache_entry *ce,struct stat *st)3358{3359struct checkout costate = CHECKOUT_INIT;33603361 costate.refresh_cache =1;3362 costate.istate = istate;3363if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3364returnerror(_("cannot checkout%s"), ce->name);3365return0;3366}33673368static struct patch *previous_patch(struct apply_state *state,3369struct patch *patch,3370int*gone)3371{3372struct patch *previous;33733374*gone =0;3375if(patch->is_copy || patch->is_rename)3376return NULL;/* "git" patches do not depend on the order */33773378 previous =in_fn_table(state, patch->old_name);3379if(!previous)3380return NULL;33813382if(to_be_deleted(previous))3383return NULL;/* the deletion hasn't happened yet */33843385if(was_deleted(previous))3386*gone =1;33873388return previous;3389}33903391static intverify_index_match(const struct cache_entry *ce,struct stat *st)3392{3393if(S_ISGITLINK(ce->ce_mode)) {3394if(!S_ISDIR(st->st_mode))3395return-1;3396return0;3397}3398returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3399}34003401#define SUBMODULE_PATCH_WITHOUT_INDEX 134023403static intload_patch_target(struct apply_state *state,3404struct strbuf *buf,3405const struct cache_entry *ce,3406struct stat *st,3407struct patch *patch,3408const char*name,3409unsigned expected_mode)3410{3411if(state->cached || state->check_index) {3412if(read_file_or_gitlink(ce, buf))3413returnerror(_("failed to read%s"), name);3414}else if(name) {3415if(S_ISGITLINK(expected_mode)) {3416if(ce)3417returnread_file_or_gitlink(ce, buf);3418else3419return SUBMODULE_PATCH_WITHOUT_INDEX;3420}else if(has_symlink_leading_path(name,strlen(name))) {3421returnerror(_("reading from '%s' beyond a symbolic link"), name);3422}else{3423if(read_old_data(st, patch, name, buf))3424returnerror(_("failed to read%s"), name);3425}3426}3427return0;3428}34293430/*3431 * We are about to apply "patch"; populate the "image" with the3432 * current version we have, from the working tree or from the index,3433 * depending on the situation e.g. --cached/--index. If we are3434 * applying a non-git patch that incrementally updates the tree,3435 * we read from the result of a previous diff.3436 */3437static intload_preimage(struct apply_state *state,3438struct image *image,3439struct patch *patch,struct stat *st,3440const struct cache_entry *ce)3441{3442struct strbuf buf = STRBUF_INIT;3443size_t len;3444char*img;3445struct patch *previous;3446int status;34473448 previous =previous_patch(state, patch, &status);3449if(status)3450returnerror(_("path%shas been renamed/deleted"),3451 patch->old_name);3452if(previous) {3453/* We have a patched copy in memory; use that. */3454strbuf_add(&buf, previous->result, previous->resultsize);3455}else{3456 status =load_patch_target(state, &buf, ce, st, patch,3457 patch->old_name, patch->old_mode);3458if(status <0)3459return status;3460else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3461/*3462 * There is no way to apply subproject3463 * patch without looking at the index.3464 * NEEDSWORK: shouldn't this be flagged3465 * as an error???3466 */3467free_fragment_list(patch->fragments);3468 patch->fragments = NULL;3469}else if(status) {3470returnerror(_("failed to read%s"), patch->old_name);3471}3472}34733474 img =strbuf_detach(&buf, &len);3475prepare_image(image, img, len, !patch->is_binary);3476return0;3477}34783479static intthree_way_merge(struct image *image,3480char*path,3481const struct object_id *base,3482const struct object_id *ours,3483const struct object_id *theirs)3484{3485 mmfile_t base_file, our_file, their_file;3486 mmbuffer_t result = { NULL };3487int status;34883489read_mmblob(&base_file, base);3490read_mmblob(&our_file, ours);3491read_mmblob(&their_file, theirs);3492 status =ll_merge(&result, path,3493&base_file,"base",3494&our_file,"ours",3495&their_file,"theirs", NULL);3496free(base_file.ptr);3497free(our_file.ptr);3498free(their_file.ptr);3499if(status <0|| !result.ptr) {3500free(result.ptr);3501return-1;3502}3503clear_image(image);3504 image->buf = result.ptr;3505 image->len = result.size;35063507return status;3508}35093510/*3511 * When directly falling back to add/add three-way merge, we read from3512 * the current contents of the new_name. In no cases other than that3513 * this function will be called.3514 */3515static intload_current(struct apply_state *state,3516struct image *image,3517struct patch *patch)3518{3519struct strbuf buf = STRBUF_INIT;3520int status, pos;3521size_t len;3522char*img;3523struct stat st;3524struct cache_entry *ce;3525char*name = patch->new_name;3526unsigned mode = patch->new_mode;35273528if(!patch->is_new)3529die("BUG: patch to%sis not a creation", patch->old_name);35303531 pos =cache_name_pos(name,strlen(name));3532if(pos <0)3533returnerror(_("%s: does not exist in index"), name);3534 ce = active_cache[pos];3535if(lstat(name, &st)) {3536if(errno != ENOENT)3537returnerror_errno("%s", name);3538if(checkout_target(&the_index, ce, &st))3539return-1;3540}3541if(verify_index_match(ce, &st))3542returnerror(_("%s: does not match index"), name);35433544 status =load_patch_target(state, &buf, ce, &st, patch, name, mode);3545if(status <0)3546return status;3547else if(status)3548return-1;3549 img =strbuf_detach(&buf, &len);3550prepare_image(image, img, len, !patch->is_binary);3551return0;3552}35533554static inttry_threeway(struct apply_state *state,3555struct image *image,3556struct patch *patch,3557struct stat *st,3558const struct cache_entry *ce)3559{3560struct object_id pre_oid, post_oid, our_oid;3561struct strbuf buf = STRBUF_INIT;3562size_t len;3563int status;3564char*img;3565struct image tmp_image;35663567/* No point falling back to 3-way merge in these cases */3568if(patch->is_delete ||3569S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3570return-1;35713572/* Preimage the patch was prepared for */3573if(patch->is_new)3574write_sha1_file("",0, blob_type, pre_oid.hash);3575else if(get_oid(patch->old_sha1_prefix, &pre_oid) ||3576read_blob_object(&buf, &pre_oid, patch->old_mode))3577returnerror(_("repository lacks the necessary blob to fall back on 3-way merge."));35783579if(state->apply_verbosity > verbosity_silent)3580fprintf(stderr,_("Falling back to three-way merge...\n"));35813582 img =strbuf_detach(&buf, &len);3583prepare_image(&tmp_image, img, len,1);3584/* Apply the patch to get the post image */3585if(apply_fragments(state, &tmp_image, patch) <0) {3586clear_image(&tmp_image);3587return-1;3588}3589/* post_oid is theirs */3590write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_oid.hash);3591clear_image(&tmp_image);35923593/* our_oid is ours */3594if(patch->is_new) {3595if(load_current(state, &tmp_image, patch))3596returnerror(_("cannot read the current contents of '%s'"),3597 patch->new_name);3598}else{3599if(load_preimage(state, &tmp_image, patch, st, ce))3600returnerror(_("cannot read the current contents of '%s'"),3601 patch->old_name);3602}3603write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_oid.hash);3604clear_image(&tmp_image);36053606/* in-core three-way merge between post and our using pre as base */3607 status =three_way_merge(image, patch->new_name,3608&pre_oid, &our_oid, &post_oid);3609if(status <0) {3610if(state->apply_verbosity > verbosity_silent)3611fprintf(stderr,3612_("Failed to fall back on three-way merge...\n"));3613return status;3614}36153616if(status) {3617 patch->conflicted_threeway =1;3618if(patch->is_new)3619oidclr(&patch->threeway_stage[0]);3620else3621oidcpy(&patch->threeway_stage[0], &pre_oid);3622oidcpy(&patch->threeway_stage[1], &our_oid);3623oidcpy(&patch->threeway_stage[2], &post_oid);3624if(state->apply_verbosity > verbosity_silent)3625fprintf(stderr,3626_("Applied patch to '%s' with conflicts.\n"),3627 patch->new_name);3628}else{3629if(state->apply_verbosity > verbosity_silent)3630fprintf(stderr,3631_("Applied patch to '%s' cleanly.\n"),3632 patch->new_name);3633}3634return0;3635}36363637static intapply_data(struct apply_state *state,struct patch *patch,3638struct stat *st,const struct cache_entry *ce)3639{3640struct image image;36413642if(load_preimage(state, &image, patch, st, ce) <0)3643return-1;36443645if(patch->direct_to_threeway ||3646apply_fragments(state, &image, patch) <0) {3647/* Note: with --reject, apply_fragments() returns 0 */3648if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3649return-1;3650}3651 patch->result = image.buf;3652 patch->resultsize = image.len;3653add_to_fn_table(state, patch);3654free(image.line_allocated);36553656if(0< patch->is_delete && patch->resultsize)3657returnerror(_("removal patch leaves file contents"));36583659return0;3660}36613662/*3663 * If "patch" that we are looking at modifies or deletes what we have,3664 * we would want it not to lose any local modification we have, either3665 * in the working tree or in the index.3666 *3667 * This also decides if a non-git patch is a creation patch or a3668 * modification to an existing empty file. We do not check the state3669 * of the current tree for a creation patch in this function; the caller3670 * check_patch() separately makes sure (and errors out otherwise) that3671 * the path the patch creates does not exist in the current tree.3672 */3673static intcheck_preimage(struct apply_state *state,3674struct patch *patch,3675struct cache_entry **ce,3676struct stat *st)3677{3678const char*old_name = patch->old_name;3679struct patch *previous = NULL;3680int stat_ret =0, status;3681unsigned st_mode =0;36823683if(!old_name)3684return0;36853686assert(patch->is_new <=0);3687 previous =previous_patch(state, patch, &status);36883689if(status)3690returnerror(_("path%shas been renamed/deleted"), old_name);3691if(previous) {3692 st_mode = previous->new_mode;3693}else if(!state->cached) {3694 stat_ret =lstat(old_name, st);3695if(stat_ret && errno != ENOENT)3696returnerror_errno("%s", old_name);3697}36983699if(state->check_index && !previous) {3700int pos =cache_name_pos(old_name,strlen(old_name));3701if(pos <0) {3702if(patch->is_new <0)3703goto is_new;3704returnerror(_("%s: does not exist in index"), old_name);3705}3706*ce = active_cache[pos];3707if(stat_ret <0) {3708if(checkout_target(&the_index, *ce, st))3709return-1;3710}3711if(!state->cached &&verify_index_match(*ce, st))3712returnerror(_("%s: does not match index"), old_name);3713if(state->cached)3714 st_mode = (*ce)->ce_mode;3715}else if(stat_ret <0) {3716if(patch->is_new <0)3717goto is_new;3718returnerror_errno("%s", old_name);3719}37203721if(!state->cached && !previous)3722 st_mode =ce_mode_from_stat(*ce, st->st_mode);37233724if(patch->is_new <0)3725 patch->is_new =0;3726if(!patch->old_mode)3727 patch->old_mode = st_mode;3728if((st_mode ^ patch->old_mode) & S_IFMT)3729returnerror(_("%s: wrong type"), old_name);3730if(st_mode != patch->old_mode)3731warning(_("%shas type%o, expected%o"),3732 old_name, st_mode, patch->old_mode);3733if(!patch->new_mode && !patch->is_delete)3734 patch->new_mode = st_mode;3735return0;37363737 is_new:3738 patch->is_new =1;3739 patch->is_delete =0;3740FREE_AND_NULL(patch->old_name);3741return0;3742}374337443745#define EXISTS_IN_INDEX 13746#define EXISTS_IN_WORKTREE 237473748static intcheck_to_create(struct apply_state *state,3749const char*new_name,3750int ok_if_exists)3751{3752struct stat nst;37533754if(state->check_index &&3755cache_name_pos(new_name,strlen(new_name)) >=0&&3756!ok_if_exists)3757return EXISTS_IN_INDEX;3758if(state->cached)3759return0;37603761if(!lstat(new_name, &nst)) {3762if(S_ISDIR(nst.st_mode) || ok_if_exists)3763return0;3764/*3765 * A leading component of new_name might be a symlink3766 * that is going to be removed with this patch, but3767 * still pointing at somewhere that has the path.3768 * In such a case, path "new_name" does not exist as3769 * far as git is concerned.3770 */3771if(has_symlink_leading_path(new_name,strlen(new_name)))3772return0;37733774return EXISTS_IN_WORKTREE;3775}else if(!is_missing_file_error(errno)) {3776returnerror_errno("%s", new_name);3777}3778return0;3779}37803781static uintptr_tregister_symlink_changes(struct apply_state *state,3782const char*path,3783uintptr_t what)3784{3785struct string_list_item *ent;37863787 ent =string_list_lookup(&state->symlink_changes, path);3788if(!ent) {3789 ent =string_list_insert(&state->symlink_changes, path);3790 ent->util = (void*)0;3791}3792 ent->util = (void*)(what | ((uintptr_t)ent->util));3793return(uintptr_t)ent->util;3794}37953796static uintptr_tcheck_symlink_changes(struct apply_state *state,const char*path)3797{3798struct string_list_item *ent;37993800 ent =string_list_lookup(&state->symlink_changes, path);3801if(!ent)3802return0;3803return(uintptr_t)ent->util;3804}38053806static voidprepare_symlink_changes(struct apply_state *state,struct patch *patch)3807{3808for( ; patch; patch = patch->next) {3809if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3810(patch->is_rename || patch->is_delete))3811/* the symlink at patch->old_name is removed */3812register_symlink_changes(state, patch->old_name, APPLY_SYMLINK_GOES_AWAY);38133814if(patch->new_name &&S_ISLNK(patch->new_mode))3815/* the symlink at patch->new_name is created or remains */3816register_symlink_changes(state, patch->new_name, APPLY_SYMLINK_IN_RESULT);3817}3818}38193820static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3821{3822do{3823unsigned int change;38243825while(--name->len && name->buf[name->len] !='/')3826;/* scan backwards */3827if(!name->len)3828break;3829 name->buf[name->len] ='\0';3830 change =check_symlink_changes(state, name->buf);3831if(change & APPLY_SYMLINK_IN_RESULT)3832return1;3833if(change & APPLY_SYMLINK_GOES_AWAY)3834/*3835 * This cannot be "return 0", because we may3836 * see a new one created at a higher level.3837 */3838continue;38393840/* otherwise, check the preimage */3841if(state->check_index) {3842struct cache_entry *ce;38433844 ce =cache_file_exists(name->buf, name->len, ignore_case);3845if(ce &&S_ISLNK(ce->ce_mode))3846return1;3847}else{3848struct stat st;3849if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3850return1;3851}3852}while(1);3853return0;3854}38553856static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3857{3858int ret;3859struct strbuf name = STRBUF_INIT;38603861assert(*name_ !='\0');3862strbuf_addstr(&name, name_);3863 ret =path_is_beyond_symlink_1(state, &name);3864strbuf_release(&name);38653866return ret;3867}38683869static intcheck_unsafe_path(struct patch *patch)3870{3871const char*old_name = NULL;3872const char*new_name = NULL;3873if(patch->is_delete)3874 old_name = patch->old_name;3875else if(!patch->is_new && !patch->is_copy)3876 old_name = patch->old_name;3877if(!patch->is_delete)3878 new_name = patch->new_name;38793880if(old_name && !verify_path(old_name))3881returnerror(_("invalid path '%s'"), old_name);3882if(new_name && !verify_path(new_name))3883returnerror(_("invalid path '%s'"), new_name);3884return0;3885}38863887/*3888 * Check and apply the patch in-core; leave the result in patch->result3889 * for the caller to write it out to the final destination.3890 */3891static intcheck_patch(struct apply_state *state,struct patch *patch)3892{3893struct stat st;3894const char*old_name = patch->old_name;3895const char*new_name = patch->new_name;3896const char*name = old_name ? old_name : new_name;3897struct cache_entry *ce = NULL;3898struct patch *tpatch;3899int ok_if_exists;3900int status;39013902 patch->rejected =1;/* we will drop this after we succeed */39033904 status =check_preimage(state, patch, &ce, &st);3905if(status)3906return status;3907 old_name = patch->old_name;39083909/*3910 * A type-change diff is always split into a patch to delete3911 * old, immediately followed by a patch to create new (see3912 * diff.c::run_diff()); in such a case it is Ok that the entry3913 * to be deleted by the previous patch is still in the working3914 * tree and in the index.3915 *3916 * A patch to swap-rename between A and B would first rename A3917 * to B and then rename B to A. While applying the first one,3918 * the presence of B should not stop A from getting renamed to3919 * B; ask to_be_deleted() about the later rename. Removal of3920 * B and rename from A to B is handled the same way by asking3921 * was_deleted().3922 */3923if((tpatch =in_fn_table(state, new_name)) &&3924(was_deleted(tpatch) ||to_be_deleted(tpatch)))3925 ok_if_exists =1;3926else3927 ok_if_exists =0;39283929if(new_name &&3930((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3931int err =check_to_create(state, new_name, ok_if_exists);39323933if(err && state->threeway) {3934 patch->direct_to_threeway =1;3935}else switch(err) {3936case0:3937break;/* happy */3938case EXISTS_IN_INDEX:3939returnerror(_("%s: already exists in index"), new_name);3940break;3941case EXISTS_IN_WORKTREE:3942returnerror(_("%s: already exists in working directory"),3943 new_name);3944default:3945return err;3946}39473948if(!patch->new_mode) {3949if(0< patch->is_new)3950 patch->new_mode = S_IFREG |0644;3951else3952 patch->new_mode = patch->old_mode;3953}3954}39553956if(new_name && old_name) {3957int same = !strcmp(old_name, new_name);3958if(!patch->new_mode)3959 patch->new_mode = patch->old_mode;3960if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3961if(same)3962returnerror(_("new mode (%o) of%sdoes not "3963"match old mode (%o)"),3964 patch->new_mode, new_name,3965 patch->old_mode);3966else3967returnerror(_("new mode (%o) of%sdoes not "3968"match old mode (%o) of%s"),3969 patch->new_mode, new_name,3970 patch->old_mode, old_name);3971}3972}39733974if(!state->unsafe_paths &&check_unsafe_path(patch))3975return-128;39763977/*3978 * An attempt to read from or delete a path that is beyond a3979 * symbolic link will be prevented by load_patch_target() that3980 * is called at the beginning of apply_data() so we do not3981 * have to worry about a patch marked with "is_delete" bit3982 * here. We however need to make sure that the patch result3983 * is not deposited to a path that is beyond a symbolic link3984 * here.3985 */3986if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3987returnerror(_("affected file '%s' is beyond a symbolic link"),3988 patch->new_name);39893990if(apply_data(state, patch, &st, ce) <0)3991returnerror(_("%s: patch does not apply"), name);3992 patch->rejected =0;3993return0;3994}39953996static intcheck_patch_list(struct apply_state *state,struct patch *patch)3997{3998int err =0;39994000prepare_symlink_changes(state, patch);4001prepare_fn_table(state, patch);4002while(patch) {4003int res;4004if(state->apply_verbosity > verbosity_normal)4005say_patch_name(stderr,4006_("Checking patch%s..."), patch);4007 res =check_patch(state, patch);4008if(res == -128)4009return-128;4010 err |= res;4011 patch = patch->next;4012}4013return err;4014}40154016static intread_apply_cache(struct apply_state *state)4017{4018if(state->index_file)4019returnread_cache_from(state->index_file);4020else4021returnread_cache();4022}40234024/* This function tries to read the object name from the current index */4025static intget_current_oid(struct apply_state *state,const char*path,4026struct object_id *oid)4027{4028int pos;40294030if(read_apply_cache(state) <0)4031return-1;4032 pos =cache_name_pos(path,strlen(path));4033if(pos <0)4034return-1;4035oidcpy(oid, &active_cache[pos]->oid);4036return0;4037}40384039static intpreimage_oid_in_gitlink_patch(struct patch *p,struct object_id *oid)4040{4041/*4042 * A usable gitlink patch has only one fragment (hunk) that looks like:4043 * @@ -1 +1 @@4044 * -Subproject commit <old sha1>4045 * +Subproject commit <new sha1>4046 * or4047 * @@ -1 +0,0 @@4048 * -Subproject commit <old sha1>4049 * for a removal patch.4050 */4051struct fragment *hunk = p->fragments;4052static const char heading[] ="-Subproject commit ";4053char*preimage;40544055if(/* does the patch have only one hunk? */4056 hunk && !hunk->next &&4057/* is its preimage one line? */4058 hunk->oldpos ==1&& hunk->oldlines ==1&&4059/* does preimage begin with the heading? */4060(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&4061starts_with(++preimage, heading) &&4062/* does it record full SHA-1? */4063!get_oid_hex(preimage +sizeof(heading) -1, oid) &&4064 preimage[sizeof(heading) + GIT_SHA1_HEXSZ -1] =='\n'&&4065/* does the abbreviated name on the index line agree with it? */4066starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))4067return0;/* it all looks fine */40684069/* we may have full object name on the index line */4070returnget_oid_hex(p->old_sha1_prefix, oid);4071}40724073/* Build an index that contains the just the files needed for a 3way merge */4074static intbuild_fake_ancestor(struct apply_state *state,struct patch *list)4075{4076struct patch *patch;4077struct index_state result = { NULL };4078static struct lock_file lock;4079int res;40804081/* Once we start supporting the reverse patch, it may be4082 * worth showing the new sha1 prefix, but until then...4083 */4084for(patch = list; patch; patch = patch->next) {4085struct object_id oid;4086struct cache_entry *ce;4087const char*name;40884089 name = patch->old_name ? patch->old_name : patch->new_name;4090if(0< patch->is_new)4091continue;40924093if(S_ISGITLINK(patch->old_mode)) {4094if(!preimage_oid_in_gitlink_patch(patch, &oid))4095;/* ok, the textual part looks sane */4096else4097returnerror(_("sha1 information is lacking or "4098"useless for submodule%s"), name);4099}else if(!get_oid_blob(patch->old_sha1_prefix, &oid)) {4100;/* ok */4101}else if(!patch->lines_added && !patch->lines_deleted) {4102/* mode-only change: update the current */4103if(get_current_oid(state, patch->old_name, &oid))4104returnerror(_("mode change for%s, which is not "4105"in current HEAD"), name);4106}else4107returnerror(_("sha1 information is lacking or useless "4108"(%s)."), name);41094110 ce =make_cache_entry(patch->old_mode, oid.hash, name,0,0);4111if(!ce)4112returnerror(_("make_cache_entry failed for path '%s'"),4113 name);4114if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) {4115free(ce);4116returnerror(_("could not add%sto temporary index"),4117 name);4118}4119}41204121hold_lock_file_for_update(&lock, state->fake_ancestor, LOCK_DIE_ON_ERROR);4122 res =write_locked_index(&result, &lock, COMMIT_LOCK);4123discard_index(&result);41244125if(res)4126returnerror(_("could not write temporary index to%s"),4127 state->fake_ancestor);41284129return0;4130}41314132static voidstat_patch_list(struct apply_state *state,struct patch *patch)4133{4134int files, adds, dels;41354136for(files = adds = dels =0; patch ; patch = patch->next) {4137 files++;4138 adds += patch->lines_added;4139 dels += patch->lines_deleted;4140show_stats(state, patch);4141}41424143print_stat_summary(stdout, files, adds, dels);4144}41454146static voidnumstat_patch_list(struct apply_state *state,4147struct patch *patch)4148{4149for( ; patch; patch = patch->next) {4150const char*name;4151 name = patch->new_name ? patch->new_name : patch->old_name;4152if(patch->is_binary)4153printf("-\t-\t");4154else4155printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4156write_name_quoted(name, stdout, state->line_termination);4157}4158}41594160static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4161{4162if(mode)4163printf("%smode%06o%s\n", newdelete, mode, name);4164else4165printf("%s %s\n", newdelete, name);4166}41674168static voidshow_mode_change(struct patch *p,int show_name)4169{4170if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4171if(show_name)4172printf(" mode change%06o =>%06o%s\n",4173 p->old_mode, p->new_mode, p->new_name);4174else4175printf(" mode change%06o =>%06o\n",4176 p->old_mode, p->new_mode);4177}4178}41794180static voidshow_rename_copy(struct patch *p)4181{4182const char*renamecopy = p->is_rename ?"rename":"copy";4183const char*old, *new;41844185/* Find common prefix */4186 old = p->old_name;4187new= p->new_name;4188while(1) {4189const char*slash_old, *slash_new;4190 slash_old =strchr(old,'/');4191 slash_new =strchr(new,'/');4192if(!slash_old ||4193!slash_new ||4194 slash_old - old != slash_new -new||4195memcmp(old,new, slash_new -new))4196break;4197 old = slash_old +1;4198new= slash_new +1;4199}4200/* p->old_name thru old is the common prefix, and old and new4201 * through the end of names are renames4202 */4203if(old != p->old_name)4204printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4205(int)(old - p->old_name), p->old_name,4206 old,new, p->score);4207else4208printf("%s %s=>%s(%d%%)\n", renamecopy,4209 p->old_name, p->new_name, p->score);4210show_mode_change(p,0);4211}42124213static voidsummary_patch_list(struct patch *patch)4214{4215struct patch *p;42164217for(p = patch; p; p = p->next) {4218if(p->is_new)4219show_file_mode_name("create", p->new_mode, p->new_name);4220else if(p->is_delete)4221show_file_mode_name("delete", p->old_mode, p->old_name);4222else{4223if(p->is_rename || p->is_copy)4224show_rename_copy(p);4225else{4226if(p->score) {4227printf(" rewrite%s(%d%%)\n",4228 p->new_name, p->score);4229show_mode_change(p,0);4230}4231else4232show_mode_change(p,1);4233}4234}4235}4236}42374238static voidpatch_stats(struct apply_state *state,struct patch *patch)4239{4240int lines = patch->lines_added + patch->lines_deleted;42414242if(lines > state->max_change)4243 state->max_change = lines;4244if(patch->old_name) {4245int len =quote_c_style(patch->old_name, NULL, NULL,0);4246if(!len)4247 len =strlen(patch->old_name);4248if(len > state->max_len)4249 state->max_len = len;4250}4251if(patch->new_name) {4252int len =quote_c_style(patch->new_name, NULL, NULL,0);4253if(!len)4254 len =strlen(patch->new_name);4255if(len > state->max_len)4256 state->max_len = len;4257}4258}42594260static intremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4261{4262if(state->update_index) {4263if(remove_file_from_cache(patch->old_name) <0)4264returnerror(_("unable to remove%sfrom index"), patch->old_name);4265}4266if(!state->cached) {4267if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4268remove_path(patch->old_name);4269}4270}4271return0;4272}42734274static intadd_index_file(struct apply_state *state,4275const char*path,4276unsigned mode,4277void*buf,4278unsigned long size)4279{4280struct stat st;4281struct cache_entry *ce;4282int namelen =strlen(path);4283unsigned ce_size =cache_entry_size(namelen);42844285if(!state->update_index)4286return0;42874288 ce =xcalloc(1, ce_size);4289memcpy(ce->name, path, namelen);4290 ce->ce_mode =create_ce_mode(mode);4291 ce->ce_flags =create_ce_flags(0);4292 ce->ce_namelen = namelen;4293if(S_ISGITLINK(mode)) {4294const char*s;42954296if(!skip_prefix(buf,"Subproject commit ", &s) ||4297get_oid_hex(s, &ce->oid)) {4298free(ce);4299returnerror(_("corrupt patch for submodule%s"), path);4300}4301}else{4302if(!state->cached) {4303if(lstat(path, &st) <0) {4304free(ce);4305returnerror_errno(_("unable to stat newly "4306"created file '%s'"),4307 path);4308}4309fill_stat_cache_info(ce, &st);4310}4311if(write_sha1_file(buf, size, blob_type, ce->oid.hash) <0) {4312free(ce);4313returnerror(_("unable to create backing store "4314"for newly created file%s"), path);4315}4316}4317if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0) {4318free(ce);4319returnerror(_("unable to add cache entry for%s"), path);4320}43214322return0;4323}43244325/*4326 * Returns:4327 * -1 if an unrecoverable error happened4328 * 0 if everything went well4329 * 1 if a recoverable error happened4330 */4331static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4332{4333int fd, res;4334struct strbuf nbuf = STRBUF_INIT;43354336if(S_ISGITLINK(mode)) {4337struct stat st;4338if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4339return0;4340return!!mkdir(path,0777);4341}43424343if(has_symlinks &&S_ISLNK(mode))4344/* Although buf:size is counted string, it also is NUL4345 * terminated.4346 */4347return!!symlink(buf, path);43484349 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4350if(fd <0)4351return1;43524353if(convert_to_working_tree(path, buf, size, &nbuf)) {4354 size = nbuf.len;4355 buf = nbuf.buf;4356}43574358 res =write_in_full(fd, buf, size) <0;4359if(res)4360error_errno(_("failed to write to '%s'"), path);4361strbuf_release(&nbuf);43624363if(close(fd) <0&& !res)4364returnerror_errno(_("closing file '%s'"), path);43654366return res ? -1:0;4367}43684369/*4370 * We optimistically assume that the directories exist,4371 * which is true 99% of the time anyway. If they don't,4372 * we create them and try again.4373 *4374 * Returns:4375 * -1 on error4376 * 0 otherwise4377 */4378static intcreate_one_file(struct apply_state *state,4379char*path,4380unsigned mode,4381const char*buf,4382unsigned long size)4383{4384int res;43854386if(state->cached)4387return0;43884389 res =try_create_file(path, mode, buf, size);4390if(res <0)4391return-1;4392if(!res)4393return0;43944395if(errno == ENOENT) {4396if(safe_create_leading_directories(path))4397return0;4398 res =try_create_file(path, mode, buf, size);4399if(res <0)4400return-1;4401if(!res)4402return0;4403}44044405if(errno == EEXIST || errno == EACCES) {4406/* We may be trying to create a file where a directory4407 * used to be.4408 */4409struct stat st;4410if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4411 errno = EEXIST;4412}44134414if(errno == EEXIST) {4415unsigned int nr =getpid();44164417for(;;) {4418char newpath[PATH_MAX];4419mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4420 res =try_create_file(newpath, mode, buf, size);4421if(res <0)4422return-1;4423if(!res) {4424if(!rename(newpath, path))4425return0;4426unlink_or_warn(newpath);4427break;4428}4429if(errno != EEXIST)4430break;4431++nr;4432}4433}4434returnerror_errno(_("unable to write file '%s' mode%o"),4435 path, mode);4436}44374438static intadd_conflicted_stages_file(struct apply_state *state,4439struct patch *patch)4440{4441int stage, namelen;4442unsigned ce_size, mode;4443struct cache_entry *ce;44444445if(!state->update_index)4446return0;4447 namelen =strlen(patch->new_name);4448 ce_size =cache_entry_size(namelen);4449 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);44504451remove_file_from_cache(patch->new_name);4452for(stage =1; stage <4; stage++) {4453if(is_null_oid(&patch->threeway_stage[stage -1]))4454continue;4455 ce =xcalloc(1, ce_size);4456memcpy(ce->name, patch->new_name, namelen);4457 ce->ce_mode =create_ce_mode(mode);4458 ce->ce_flags =create_ce_flags(stage);4459 ce->ce_namelen = namelen;4460oidcpy(&ce->oid, &patch->threeway_stage[stage -1]);4461if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0) {4462free(ce);4463returnerror(_("unable to add cache entry for%s"),4464 patch->new_name);4465}4466}44674468return0;4469}44704471static intcreate_file(struct apply_state *state,struct patch *patch)4472{4473char*path = patch->new_name;4474unsigned mode = patch->new_mode;4475unsigned long size = patch->resultsize;4476char*buf = patch->result;44774478if(!mode)4479 mode = S_IFREG |0644;4480if(create_one_file(state, path, mode, buf, size))4481return-1;44824483if(patch->conflicted_threeway)4484returnadd_conflicted_stages_file(state, patch);4485else4486returnadd_index_file(state, path, mode, buf, size);4487}44884489/* phase zero is to remove, phase one is to create */4490static intwrite_out_one_result(struct apply_state *state,4491struct patch *patch,4492int phase)4493{4494if(patch->is_delete >0) {4495if(phase ==0)4496returnremove_file(state, patch,1);4497return0;4498}4499if(patch->is_new >0|| patch->is_copy) {4500if(phase ==1)4501returncreate_file(state, patch);4502return0;4503}4504/*4505 * Rename or modification boils down to the same4506 * thing: remove the old, write the new4507 */4508if(phase ==0)4509returnremove_file(state, patch, patch->is_rename);4510if(phase ==1)4511returncreate_file(state, patch);4512return0;4513}45144515static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4516{4517FILE*rej;4518char namebuf[PATH_MAX];4519struct fragment *frag;4520int cnt =0;4521struct strbuf sb = STRBUF_INIT;45224523for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4524if(!frag->rejected)4525continue;4526 cnt++;4527}45284529if(!cnt) {4530if(state->apply_verbosity > verbosity_normal)4531say_patch_name(stderr,4532_("Applied patch%scleanly."), patch);4533return0;4534}45354536/* This should not happen, because a removal patch that leaves4537 * contents are marked "rejected" at the patch level.4538 */4539if(!patch->new_name)4540die(_("internal error"));45414542/* Say this even without --verbose */4543strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4544"Applying patch %%swith%drejects...",4545 cnt),4546 cnt);4547if(state->apply_verbosity > verbosity_silent)4548say_patch_name(stderr, sb.buf, patch);4549strbuf_release(&sb);45504551 cnt =strlen(patch->new_name);4552if(ARRAY_SIZE(namebuf) <= cnt +5) {4553 cnt =ARRAY_SIZE(namebuf) -5;4554warning(_("truncating .rej filename to %.*s.rej"),4555 cnt -1, patch->new_name);4556}4557memcpy(namebuf, patch->new_name, cnt);4558memcpy(namebuf + cnt,".rej",5);45594560 rej =fopen(namebuf,"w");4561if(!rej)4562returnerror_errno(_("cannot open%s"), namebuf);45634564/* Normal git tools never deal with .rej, so do not pretend4565 * this is a git patch by saying --git or giving extended4566 * headers. While at it, maybe please "kompare" that wants4567 * the trailing TAB and some garbage at the end of line ;-).4568 */4569fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4570 patch->new_name, patch->new_name);4571for(cnt =1, frag = patch->fragments;4572 frag;4573 cnt++, frag = frag->next) {4574if(!frag->rejected) {4575if(state->apply_verbosity > verbosity_silent)4576fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4577continue;4578}4579if(state->apply_verbosity > verbosity_silent)4580fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4581fprintf(rej,"%.*s", frag->size, frag->patch);4582if(frag->patch[frag->size-1] !='\n')4583fputc('\n', rej);4584}4585fclose(rej);4586return-1;4587}45884589/*4590 * Returns:4591 * -1 if an error happened4592 * 0 if the patch applied cleanly4593 * 1 if the patch did not apply cleanly4594 */4595static intwrite_out_results(struct apply_state *state,struct patch *list)4596{4597int phase;4598int errs =0;4599struct patch *l;4600struct string_list cpath = STRING_LIST_INIT_DUP;46014602for(phase =0; phase <2; phase++) {4603 l = list;4604while(l) {4605if(l->rejected)4606 errs =1;4607else{4608if(write_out_one_result(state, l, phase)) {4609string_list_clear(&cpath,0);4610return-1;4611}4612if(phase ==1) {4613if(write_out_one_reject(state, l))4614 errs =1;4615if(l->conflicted_threeway) {4616string_list_append(&cpath, l->new_name);4617 errs =1;4618}4619}4620}4621 l = l->next;4622}4623}46244625if(cpath.nr) {4626struct string_list_item *item;46274628string_list_sort(&cpath);4629if(state->apply_verbosity > verbosity_silent) {4630for_each_string_list_item(item, &cpath)4631fprintf(stderr,"U%s\n", item->string);4632}4633string_list_clear(&cpath,0);46344635rerere(0);4636}46374638return errs;4639}46404641/*4642 * Try to apply a patch.4643 *4644 * Returns:4645 * -128 if a bad error happened (like patch unreadable)4646 * -1 if patch did not apply and user cannot deal with it4647 * 0 if the patch applied4648 * 1 if the patch did not apply but user might fix it4649 */4650static intapply_patch(struct apply_state *state,4651int fd,4652const char*filename,4653int options)4654{4655size_t offset;4656struct strbuf buf = STRBUF_INIT;/* owns the patch text */4657struct patch *list = NULL, **listp = &list;4658int skipped_patch =0;4659int res =0;46604661 state->patch_input_file = filename;4662if(read_patch_file(&buf, fd) <0)4663return-128;4664 offset =0;4665while(offset < buf.len) {4666struct patch *patch;4667int nr;46684669 patch =xcalloc(1,sizeof(*patch));4670 patch->inaccurate_eof = !!(options & APPLY_OPT_INACCURATE_EOF);4671 patch->recount = !!(options & APPLY_OPT_RECOUNT);4672 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4673if(nr <0) {4674free_patch(patch);4675if(nr == -128) {4676 res = -128;4677goto end;4678}4679break;4680}4681if(state->apply_in_reverse)4682reverse_patches(patch);4683if(use_patch(state, patch)) {4684patch_stats(state, patch);4685*listp = patch;4686 listp = &patch->next;4687}4688else{4689if(state->apply_verbosity > verbosity_normal)4690say_patch_name(stderr,_("Skipped patch '%s'."), patch);4691free_patch(patch);4692 skipped_patch++;4693}4694 offset += nr;4695}46964697if(!list && !skipped_patch) {4698error(_("unrecognized input"));4699 res = -128;4700goto end;4701}47024703if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4704 state->apply =0;47054706 state->update_index = state->check_index && state->apply;4707if(state->update_index && !is_lock_file_locked(&state->lock_file)) {4708if(state->index_file)4709hold_lock_file_for_update(&state->lock_file,4710 state->index_file,4711 LOCK_DIE_ON_ERROR);4712else4713hold_locked_index(&state->lock_file, LOCK_DIE_ON_ERROR);4714}47154716if(state->check_index &&read_apply_cache(state) <0) {4717error(_("unable to read index file"));4718 res = -128;4719goto end;4720}47214722if(state->check || state->apply) {4723int r =check_patch_list(state, list);4724if(r == -128) {4725 res = -128;4726goto end;4727}4728if(r <0&& !state->apply_with_reject) {4729 res = -1;4730goto end;4731}4732}47334734if(state->apply) {4735int write_res =write_out_results(state, list);4736if(write_res <0) {4737 res = -128;4738goto end;4739}4740if(write_res >0) {4741/* with --3way, we still need to write the index out */4742 res = state->apply_with_reject ? -1:1;4743goto end;4744}4745}47464747if(state->fake_ancestor &&4748build_fake_ancestor(state, list)) {4749 res = -128;4750goto end;4751}47524753if(state->diffstat && state->apply_verbosity > verbosity_silent)4754stat_patch_list(state, list);47554756if(state->numstat && state->apply_verbosity > verbosity_silent)4757numstat_patch_list(state, list);47584759if(state->summary && state->apply_verbosity > verbosity_silent)4760summary_patch_list(list);47614762end:4763free_patch_list(list);4764strbuf_release(&buf);4765string_list_clear(&state->fn_table,0);4766return res;4767}47684769static intapply_option_parse_exclude(const struct option *opt,4770const char*arg,int unset)4771{4772struct apply_state *state = opt->value;4773add_name_limit(state, arg,1);4774return0;4775}47764777static intapply_option_parse_include(const struct option *opt,4778const char*arg,int unset)4779{4780struct apply_state *state = opt->value;4781add_name_limit(state, arg,0);4782 state->has_include =1;4783return0;4784}47854786static intapply_option_parse_p(const struct option *opt,4787const char*arg,4788int unset)4789{4790struct apply_state *state = opt->value;4791 state->p_value =atoi(arg);4792 state->p_value_known =1;4793return0;4794}47954796static intapply_option_parse_space_change(const struct option *opt,4797const char*arg,int unset)4798{4799struct apply_state *state = opt->value;4800if(unset)4801 state->ws_ignore_action = ignore_ws_none;4802else4803 state->ws_ignore_action = ignore_ws_change;4804return0;4805}48064807static intapply_option_parse_whitespace(const struct option *opt,4808const char*arg,int unset)4809{4810struct apply_state *state = opt->value;4811 state->whitespace_option = arg;4812if(parse_whitespace_option(state, arg))4813exit(1);4814return0;4815}48164817static intapply_option_parse_directory(const struct option *opt,4818const char*arg,int unset)4819{4820struct apply_state *state = opt->value;4821strbuf_reset(&state->root);4822strbuf_addstr(&state->root, arg);4823strbuf_complete(&state->root,'/');4824return0;4825}48264827intapply_all_patches(struct apply_state *state,4828int argc,4829const char**argv,4830int options)4831{4832int i;4833int res;4834int errs =0;4835int read_stdin =1;48364837for(i =0; i < argc; i++) {4838const char*arg = argv[i];4839char*to_free = NULL;4840int fd;48414842if(!strcmp(arg,"-")) {4843 res =apply_patch(state,0,"<stdin>", options);4844if(res <0)4845goto end;4846 errs |= res;4847 read_stdin =0;4848continue;4849}else4850 arg = to_free =prefix_filename(state->prefix, arg);48514852 fd =open(arg, O_RDONLY);4853if(fd <0) {4854error(_("can't open patch '%s':%s"), arg,strerror(errno));4855 res = -128;4856free(to_free);4857goto end;4858}4859 read_stdin =0;4860set_default_whitespace_mode(state);4861 res =apply_patch(state, fd, arg, options);4862close(fd);4863free(to_free);4864if(res <0)4865goto end;4866 errs |= res;4867}4868set_default_whitespace_mode(state);4869if(read_stdin) {4870 res =apply_patch(state,0,"<stdin>", options);4871if(res <0)4872goto end;4873 errs |= res;4874}48754876if(state->whitespace_error) {4877if(state->squelch_whitespace_errors &&4878 state->squelch_whitespace_errors < state->whitespace_error) {4879int squelched =4880 state->whitespace_error - state->squelch_whitespace_errors;4881warning(Q_("squelched%dwhitespace error",4882"squelched%dwhitespace errors",4883 squelched),4884 squelched);4885}4886if(state->ws_error_action == die_on_ws_error) {4887error(Q_("%dline adds whitespace errors.",4888"%dlines add whitespace errors.",4889 state->whitespace_error),4890 state->whitespace_error);4891 res = -128;4892goto end;4893}4894if(state->applied_after_fixing_ws && state->apply)4895warning(Q_("%dline applied after"4896" fixing whitespace errors.",4897"%dlines applied after"4898" fixing whitespace errors.",4899 state->applied_after_fixing_ws),4900 state->applied_after_fixing_ws);4901else if(state->whitespace_error)4902warning(Q_("%dline adds whitespace errors.",4903"%dlines add whitespace errors.",4904 state->whitespace_error),4905 state->whitespace_error);4906}49074908if(state->update_index) {4909 res =write_locked_index(&the_index, &state->lock_file, COMMIT_LOCK);4910if(res) {4911error(_("Unable to write new index file"));4912 res = -128;4913goto end;4914}4915}49164917 res = !!errs;49184919end:4920rollback_lock_file(&state->lock_file);49214922if(state->apply_verbosity <= verbosity_silent) {4923set_error_routine(state->saved_error_routine);4924set_warn_routine(state->saved_warn_routine);4925}49264927if(res > -1)4928return res;4929return(res == -1?1:128);4930}49314932intapply_parse_options(int argc,const char**argv,4933struct apply_state *state,4934int*force_apply,int*options,4935const char*const*apply_usage)4936{4937struct option builtin_apply_options[] = {4938{ OPTION_CALLBACK,0,"exclude", state,N_("path"),4939N_("don't apply changes matching the given path"),49400, apply_option_parse_exclude },4941{ OPTION_CALLBACK,0,"include", state,N_("path"),4942N_("apply changes matching the given path"),49430, apply_option_parse_include },4944{ OPTION_CALLBACK,'p', NULL, state,N_("num"),4945N_("remove <num> leading slashes from traditional diff paths"),49460, apply_option_parse_p },4947OPT_BOOL(0,"no-add", &state->no_add,4948N_("ignore additions made by the patch")),4949OPT_BOOL(0,"stat", &state->diffstat,4950N_("instead of applying the patch, output diffstat for the input")),4951OPT_NOOP_NOARG(0,"allow-binary-replacement"),4952OPT_NOOP_NOARG(0,"binary"),4953OPT_BOOL(0,"numstat", &state->numstat,4954N_("show number of added and deleted lines in decimal notation")),4955OPT_BOOL(0,"summary", &state->summary,4956N_("instead of applying the patch, output a summary for the input")),4957OPT_BOOL(0,"check", &state->check,4958N_("instead of applying the patch, see if the patch is applicable")),4959OPT_BOOL(0,"index", &state->check_index,4960N_("make sure the patch is applicable to the current index")),4961OPT_BOOL(0,"cached", &state->cached,4962N_("apply a patch without touching the working tree")),4963OPT_BOOL(0,"unsafe-paths", &state->unsafe_paths,4964N_("accept a patch that touches outside the working area")),4965OPT_BOOL(0,"apply", force_apply,4966N_("also apply the patch (use with --stat/--summary/--check)")),4967OPT_BOOL('3',"3way", &state->threeway,4968N_("attempt three-way merge if a patch does not apply")),4969OPT_FILENAME(0,"build-fake-ancestor", &state->fake_ancestor,4970N_("build a temporary index based on embedded index information")),4971/* Think twice before adding "--nul" synonym to this */4972OPT_SET_INT('z', NULL, &state->line_termination,4973N_("paths are separated with NUL character"),'\0'),4974OPT_INTEGER('C', NULL, &state->p_context,4975N_("ensure at least <n> lines of context match")),4976{ OPTION_CALLBACK,0,"whitespace", state,N_("action"),4977N_("detect new or modified lines that have whitespace errors"),49780, apply_option_parse_whitespace },4979{ OPTION_CALLBACK,0,"ignore-space-change", state, NULL,4980N_("ignore changes in whitespace when finding context"),4981 PARSE_OPT_NOARG, apply_option_parse_space_change },4982{ OPTION_CALLBACK,0,"ignore-whitespace", state, NULL,4983N_("ignore changes in whitespace when finding context"),4984 PARSE_OPT_NOARG, apply_option_parse_space_change },4985OPT_BOOL('R',"reverse", &state->apply_in_reverse,4986N_("apply the patch in reverse")),4987OPT_BOOL(0,"unidiff-zero", &state->unidiff_zero,4988N_("don't expect at least one line of context")),4989OPT_BOOL(0,"reject", &state->apply_with_reject,4990N_("leave the rejected hunks in corresponding *.rej files")),4991OPT_BOOL(0,"allow-overlap", &state->allow_overlap,4992N_("allow overlapping hunks")),4993OPT__VERBOSE(&state->apply_verbosity,N_("be verbose")),4994OPT_BIT(0,"inaccurate-eof", options,4995N_("tolerate incorrectly detected missing new-line at the end of file"),4996 APPLY_OPT_INACCURATE_EOF),4997OPT_BIT(0,"recount", options,4998N_("do not trust the line counts in the hunk headers"),4999 APPLY_OPT_RECOUNT),5000{ OPTION_CALLBACK,0,"directory", state,N_("root"),5001N_("prepend <root> to all filenames"),50020, apply_option_parse_directory },5003OPT_END()5004};50055006returnparse_options(argc, argv, state->prefix, builtin_apply_options, apply_usage,0);5007}