1/* 2 * apply.c 3 * 4 * Copyright (C) Linus Torvalds, 2005 5 * 6 * This applies patches on top of some (arbitrary) version of the SCM. 7 * 8 */ 9 10#include"cache.h" 11#include"config.h" 12#include"object-store.h" 13#include"blob.h" 14#include"delta.h" 15#include"diff.h" 16#include"dir.h" 17#include"xdiff-interface.h" 18#include"ll-merge.h" 19#include"lockfile.h" 20#include"parse-options.h" 21#include"quote.h" 22#include"rerere.h" 23#include"apply.h" 24 25struct gitdiff_data { 26struct strbuf *root; 27int linenr; 28int p_value; 29}; 30 31static voidgit_apply_config(void) 32{ 33git_config_get_string_const("apply.whitespace", &apply_default_whitespace); 34git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace); 35git_config(git_default_config, NULL); 36} 37 38static intparse_whitespace_option(struct apply_state *state,const char*option) 39{ 40if(!option) { 41 state->ws_error_action = warn_on_ws_error; 42return0; 43} 44if(!strcmp(option,"warn")) { 45 state->ws_error_action = warn_on_ws_error; 46return0; 47} 48if(!strcmp(option,"nowarn")) { 49 state->ws_error_action = nowarn_ws_error; 50return0; 51} 52if(!strcmp(option,"error")) { 53 state->ws_error_action = die_on_ws_error; 54return0; 55} 56if(!strcmp(option,"error-all")) { 57 state->ws_error_action = die_on_ws_error; 58 state->squelch_whitespace_errors =0; 59return0; 60} 61if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 62 state->ws_error_action = correct_ws_error; 63return0; 64} 65/* 66 * Please update $__git_whitespacelist in git-completion.bash 67 * when you add new options. 68 */ 69returnerror(_("unrecognized whitespace option '%s'"), option); 70} 71 72static intparse_ignorewhitespace_option(struct apply_state *state, 73const char*option) 74{ 75if(!option || !strcmp(option,"no") || 76!strcmp(option,"false") || !strcmp(option,"never") || 77!strcmp(option,"none")) { 78 state->ws_ignore_action = ignore_ws_none; 79return0; 80} 81if(!strcmp(option,"change")) { 82 state->ws_ignore_action = ignore_ws_change; 83return0; 84} 85returnerror(_("unrecognized whitespace ignore option '%s'"), option); 86} 87 88intinit_apply_state(struct apply_state *state, 89struct repository *repo, 90const char*prefix) 91{ 92memset(state,0,sizeof(*state)); 93 state->prefix = prefix; 94 state->repo = repo; 95 state->apply =1; 96 state->line_termination ='\n'; 97 state->p_value =1; 98 state->p_context = UINT_MAX; 99 state->squelch_whitespace_errors =5; 100 state->ws_error_action = warn_on_ws_error; 101 state->ws_ignore_action = ignore_ws_none; 102 state->linenr =1; 103string_list_init(&state->fn_table,0); 104string_list_init(&state->limit_by_name,0); 105string_list_init(&state->symlink_changes,0); 106strbuf_init(&state->root,0); 107 108git_apply_config(); 109if(apply_default_whitespace &&parse_whitespace_option(state, apply_default_whitespace)) 110return-1; 111if(apply_default_ignorewhitespace &&parse_ignorewhitespace_option(state, apply_default_ignorewhitespace)) 112return-1; 113return0; 114} 115 116voidclear_apply_state(struct apply_state *state) 117{ 118string_list_clear(&state->limit_by_name,0); 119string_list_clear(&state->symlink_changes,0); 120strbuf_release(&state->root); 121 122/* &state->fn_table is cleared at the end of apply_patch() */ 123} 124 125static voidmute_routine(const char*msg,va_list params) 126{ 127/* do nothing */ 128} 129 130intcheck_apply_state(struct apply_state *state,int force_apply) 131{ 132int is_not_gitdir = !startup_info->have_repository; 133 134if(state->apply_with_reject && state->threeway) 135returnerror(_("--reject and --3way cannot be used together.")); 136if(state->cached && state->threeway) 137returnerror(_("--cached and --3way cannot be used together.")); 138if(state->threeway) { 139if(is_not_gitdir) 140returnerror(_("--3way outside a repository")); 141 state->check_index =1; 142} 143if(state->apply_with_reject) { 144 state->apply =1; 145if(state->apply_verbosity == verbosity_normal) 146 state->apply_verbosity = verbosity_verbose; 147} 148if(!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor)) 149 state->apply =0; 150if(state->check_index && is_not_gitdir) 151returnerror(_("--index outside a repository")); 152if(state->cached) { 153if(is_not_gitdir) 154returnerror(_("--cached outside a repository")); 155 state->check_index =1; 156} 157if(state->ita_only && (state->check_index || is_not_gitdir)) 158 state->ita_only =0; 159if(state->check_index) 160 state->unsafe_paths =0; 161 162if(state->apply_verbosity <= verbosity_silent) { 163 state->saved_error_routine =get_error_routine(); 164 state->saved_warn_routine =get_warn_routine(); 165set_error_routine(mute_routine); 166set_warn_routine(mute_routine); 167} 168 169return0; 170} 171 172static voidset_default_whitespace_mode(struct apply_state *state) 173{ 174if(!state->whitespace_option && !apply_default_whitespace) 175 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 176} 177 178/* 179 * This represents one "hunk" from a patch, starting with 180 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 181 * patch text is pointed at by patch, and its byte length 182 * is stored in size. leading and trailing are the number 183 * of context lines. 184 */ 185struct fragment { 186unsigned long leading, trailing; 187unsigned long oldpos, oldlines; 188unsigned long newpos, newlines; 189/* 190 * 'patch' is usually borrowed from buf in apply_patch(), 191 * but some codepaths store an allocated buffer. 192 */ 193const char*patch; 194unsigned free_patch:1, 195 rejected:1; 196int size; 197int linenr; 198struct fragment *next; 199}; 200 201/* 202 * When dealing with a binary patch, we reuse "leading" field 203 * to store the type of the binary hunk, either deflated "delta" 204 * or deflated "literal". 205 */ 206#define binary_patch_method leading 207#define BINARY_DELTA_DEFLATED 1 208#define BINARY_LITERAL_DEFLATED 2 209 210static voidfree_fragment_list(struct fragment *list) 211{ 212while(list) { 213struct fragment *next = list->next; 214if(list->free_patch) 215free((char*)list->patch); 216free(list); 217 list = next; 218} 219} 220 221static voidfree_patch(struct patch *patch) 222{ 223free_fragment_list(patch->fragments); 224free(patch->def_name); 225free(patch->old_name); 226free(patch->new_name); 227free(patch->result); 228free(patch); 229} 230 231static voidfree_patch_list(struct patch *list) 232{ 233while(list) { 234struct patch *next = list->next; 235free_patch(list); 236 list = next; 237} 238} 239 240/* 241 * A line in a file, len-bytes long (includes the terminating LF, 242 * except for an incomplete line at the end if the file ends with 243 * one), and its contents hashes to 'hash'. 244 */ 245struct line { 246size_t len; 247unsigned hash :24; 248unsigned flag :8; 249#define LINE_COMMON 1 250#define LINE_PATCHED 2 251}; 252 253/* 254 * This represents a "file", which is an array of "lines". 255 */ 256struct image { 257char*buf; 258size_t len; 259size_t nr; 260size_t alloc; 261struct line *line_allocated; 262struct line *line; 263}; 264 265static uint32_thash_line(const char*cp,size_t len) 266{ 267size_t i; 268uint32_t h; 269for(i =0, h =0; i < len; i++) { 270if(!isspace(cp[i])) { 271 h = h *3+ (cp[i] &0xff); 272} 273} 274return h; 275} 276 277/* 278 * Compare lines s1 of length n1 and s2 of length n2, ignoring 279 * whitespace difference. Returns 1 if they match, 0 otherwise 280 */ 281static intfuzzy_matchlines(const char*s1,size_t n1, 282const char*s2,size_t n2) 283{ 284const char*end1 = s1 + n1; 285const char*end2 = s2 + n2; 286 287/* ignore line endings */ 288while(s1 < end1 && (end1[-1] =='\r'|| end1[-1] =='\n')) 289 end1--; 290while(s2 < end2 && (end2[-1] =='\r'|| end2[-1] =='\n')) 291 end2--; 292 293while(s1 < end1 && s2 < end2) { 294if(isspace(*s1)) { 295/* 296 * Skip whitespace. We check on both buffers 297 * because we don't want "a b" to match "ab". 298 */ 299if(!isspace(*s2)) 300return0; 301while(s1 < end1 &&isspace(*s1)) 302 s1++; 303while(s2 < end2 &&isspace(*s2)) 304 s2++; 305}else if(*s1++ != *s2++) 306return0; 307} 308 309/* If we reached the end on one side only, lines don't match. */ 310return s1 == end1 && s2 == end2; 311} 312 313static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 314{ 315ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 316 img->line_allocated[img->nr].len = len; 317 img->line_allocated[img->nr].hash =hash_line(bol, len); 318 img->line_allocated[img->nr].flag = flag; 319 img->nr++; 320} 321 322/* 323 * "buf" has the file contents to be patched (read from various sources). 324 * attach it to "image" and add line-based index to it. 325 * "image" now owns the "buf". 326 */ 327static voidprepare_image(struct image *image,char*buf,size_t len, 328int prepare_linetable) 329{ 330const char*cp, *ep; 331 332memset(image,0,sizeof(*image)); 333 image->buf = buf; 334 image->len = len; 335 336if(!prepare_linetable) 337return; 338 339 ep = image->buf + image->len; 340 cp = image->buf; 341while(cp < ep) { 342const char*next; 343for(next = cp; next < ep && *next !='\n'; next++) 344; 345if(next < ep) 346 next++; 347add_line_info(image, cp, next - cp,0); 348 cp = next; 349} 350 image->line = image->line_allocated; 351} 352 353static voidclear_image(struct image *image) 354{ 355free(image->buf); 356free(image->line_allocated); 357memset(image,0,sizeof(*image)); 358} 359 360/* fmt must contain _one_ %s and no other substitution */ 361static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 362{ 363struct strbuf sb = STRBUF_INIT; 364 365if(patch->old_name && patch->new_name && 366strcmp(patch->old_name, patch->new_name)) { 367quote_c_style(patch->old_name, &sb, NULL,0); 368strbuf_addstr(&sb," => "); 369quote_c_style(patch->new_name, &sb, NULL,0); 370}else{ 371const char*n = patch->new_name; 372if(!n) 373 n = patch->old_name; 374quote_c_style(n, &sb, NULL,0); 375} 376fprintf(output, fmt, sb.buf); 377fputc('\n', output); 378strbuf_release(&sb); 379} 380 381#define SLOP (16) 382 383static intread_patch_file(struct strbuf *sb,int fd) 384{ 385if(strbuf_read(sb, fd,0) <0) 386returnerror_errno("git apply: failed to read"); 387 388/* 389 * Make sure that we have some slop in the buffer 390 * so that we can do speculative "memcmp" etc, and 391 * see to it that it is NUL-filled. 392 */ 393strbuf_grow(sb, SLOP); 394memset(sb->buf + sb->len,0, SLOP); 395return0; 396} 397 398static unsigned longlinelen(const char*buffer,unsigned long size) 399{ 400unsigned long len =0; 401while(size--) { 402 len++; 403if(*buffer++ =='\n') 404break; 405} 406return len; 407} 408 409static intis_dev_null(const char*str) 410{ 411returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 412} 413 414#define TERM_SPACE 1 415#define TERM_TAB 2 416 417static intname_terminate(int c,int terminate) 418{ 419if(c ==' '&& !(terminate & TERM_SPACE)) 420return0; 421if(c =='\t'&& !(terminate & TERM_TAB)) 422return0; 423 424return1; 425} 426 427/* remove double slashes to make --index work with such filenames */ 428static char*squash_slash(char*name) 429{ 430int i =0, j =0; 431 432if(!name) 433return NULL; 434 435while(name[i]) { 436if((name[j++] = name[i++]) =='/') 437while(name[i] =='/') 438 i++; 439} 440 name[j] ='\0'; 441return name; 442} 443 444static char*find_name_gnu(struct strbuf *root, 445const char*line, 446int p_value) 447{ 448struct strbuf name = STRBUF_INIT; 449char*cp; 450 451/* 452 * Proposed "new-style" GNU patch/diff format; see 453 * https://public-inbox.org/git/7vll0wvb2a.fsf@assigned-by-dhcp.cox.net/ 454 */ 455if(unquote_c_style(&name, line, NULL)) { 456strbuf_release(&name); 457return NULL; 458} 459 460for(cp = name.buf; p_value; p_value--) { 461 cp =strchr(cp,'/'); 462if(!cp) { 463strbuf_release(&name); 464return NULL; 465} 466 cp++; 467} 468 469strbuf_remove(&name,0, cp - name.buf); 470if(root->len) 471strbuf_insert(&name,0, root->buf, root->len); 472returnsquash_slash(strbuf_detach(&name, NULL)); 473} 474 475static size_tsane_tz_len(const char*line,size_t len) 476{ 477const char*tz, *p; 478 479if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 480return0; 481 tz = line + len -strlen(" +0500"); 482 483if(tz[1] !='+'&& tz[1] !='-') 484return0; 485 486for(p = tz +2; p != line + len; p++) 487if(!isdigit(*p)) 488return0; 489 490return line + len - tz; 491} 492 493static size_ttz_with_colon_len(const char*line,size_t len) 494{ 495const char*tz, *p; 496 497if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 498return0; 499 tz = line + len -strlen(" +08:00"); 500 501if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 502return0; 503 p = tz +2; 504if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 505!isdigit(*p++) || !isdigit(*p++)) 506return0; 507 508return line + len - tz; 509} 510 511static size_tdate_len(const char*line,size_t len) 512{ 513const char*date, *p; 514 515if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 516return0; 517 p = date = line + len -strlen("72-02-05"); 518 519if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 520!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 521!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 522return0; 523 524if(date - line >=strlen("19") && 525isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 526 date -=strlen("19"); 527 528return line + len - date; 529} 530 531static size_tshort_time_len(const char*line,size_t len) 532{ 533const char*time, *p; 534 535if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 536return0; 537 p = time = line + len -strlen(" 07:01:32"); 538 539/* Permit 1-digit hours? */ 540if(*p++ !=' '|| 541!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 542!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 543!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 544return0; 545 546return line + len - time; 547} 548 549static size_tfractional_time_len(const char*line,size_t len) 550{ 551const char*p; 552size_t n; 553 554/* Expected format: 19:41:17.620000023 */ 555if(!len || !isdigit(line[len -1])) 556return0; 557 p = line + len -1; 558 559/* Fractional seconds. */ 560while(p > line &&isdigit(*p)) 561 p--; 562if(*p !='.') 563return0; 564 565/* Hours, minutes, and whole seconds. */ 566 n =short_time_len(line, p - line); 567if(!n) 568return0; 569 570return line + len - p + n; 571} 572 573static size_ttrailing_spaces_len(const char*line,size_t len) 574{ 575const char*p; 576 577/* Expected format: ' ' x (1 or more) */ 578if(!len || line[len -1] !=' ') 579return0; 580 581 p = line + len; 582while(p != line) { 583 p--; 584if(*p !=' ') 585return line + len - (p +1); 586} 587 588/* All spaces! */ 589return len; 590} 591 592static size_tdiff_timestamp_len(const char*line,size_t len) 593{ 594const char*end = line + len; 595size_t n; 596 597/* 598 * Posix: 2010-07-05 19:41:17 599 * GNU: 2010-07-05 19:41:17.620000023 -0500 600 */ 601 602if(!isdigit(end[-1])) 603return0; 604 605 n =sane_tz_len(line, end - line); 606if(!n) 607 n =tz_with_colon_len(line, end - line); 608 end -= n; 609 610 n =short_time_len(line, end - line); 611if(!n) 612 n =fractional_time_len(line, end - line); 613 end -= n; 614 615 n =date_len(line, end - line); 616if(!n)/* No date. Too bad. */ 617return0; 618 end -= n; 619 620if(end == line)/* No space before date. */ 621return0; 622if(end[-1] =='\t') {/* Success! */ 623 end--; 624return line + len - end; 625} 626if(end[-1] !=' ')/* No space before date. */ 627return0; 628 629/* Whitespace damage. */ 630 end -=trailing_spaces_len(line, end - line); 631return line + len - end; 632} 633 634static char*find_name_common(struct strbuf *root, 635const char*line, 636const char*def, 637int p_value, 638const char*end, 639int terminate) 640{ 641int len; 642const char*start = NULL; 643 644if(p_value ==0) 645 start = line; 646while(line != end) { 647char c = *line; 648 649if(!end &&isspace(c)) { 650if(c =='\n') 651break; 652if(name_terminate(c, terminate)) 653break; 654} 655 line++; 656if(c =='/'&& !--p_value) 657 start = line; 658} 659if(!start) 660returnsquash_slash(xstrdup_or_null(def)); 661 len = line - start; 662if(!len) 663returnsquash_slash(xstrdup_or_null(def)); 664 665/* 666 * Generally we prefer the shorter name, especially 667 * if the other one is just a variation of that with 668 * something else tacked on to the end (ie "file.orig" 669 * or "file~"). 670 */ 671if(def) { 672int deflen =strlen(def); 673if(deflen < len && !strncmp(start, def, deflen)) 674returnsquash_slash(xstrdup(def)); 675} 676 677if(root->len) { 678char*ret =xstrfmt("%s%.*s", root->buf, len, start); 679returnsquash_slash(ret); 680} 681 682returnsquash_slash(xmemdupz(start, len)); 683} 684 685static char*find_name(struct strbuf *root, 686const char*line, 687char*def, 688int p_value, 689int terminate) 690{ 691if(*line =='"') { 692char*name =find_name_gnu(root, line, p_value); 693if(name) 694return name; 695} 696 697returnfind_name_common(root, line, def, p_value, NULL, terminate); 698} 699 700static char*find_name_traditional(struct strbuf *root, 701const char*line, 702char*def, 703int p_value) 704{ 705size_t len; 706size_t date_len; 707 708if(*line =='"') { 709char*name =find_name_gnu(root, line, p_value); 710if(name) 711return name; 712} 713 714 len =strchrnul(line,'\n') - line; 715 date_len =diff_timestamp_len(line, len); 716if(!date_len) 717returnfind_name_common(root, line, def, p_value, NULL, TERM_TAB); 718 len -= date_len; 719 720returnfind_name_common(root, line, def, p_value, line + len,0); 721} 722 723/* 724 * Given the string after "--- " or "+++ ", guess the appropriate 725 * p_value for the given patch. 726 */ 727static intguess_p_value(struct apply_state *state,const char*nameline) 728{ 729char*name, *cp; 730int val = -1; 731 732if(is_dev_null(nameline)) 733return-1; 734 name =find_name_traditional(&state->root, nameline, NULL,0); 735if(!name) 736return-1; 737 cp =strchr(name,'/'); 738if(!cp) 739 val =0; 740else if(state->prefix) { 741/* 742 * Does it begin with "a/$our-prefix" and such? Then this is 743 * very likely to apply to our directory. 744 */ 745if(starts_with(name, state->prefix)) 746 val =count_slashes(state->prefix); 747else{ 748 cp++; 749if(starts_with(cp, state->prefix)) 750 val =count_slashes(state->prefix) +1; 751} 752} 753free(name); 754return val; 755} 756 757/* 758 * Does the ---/+++ line have the POSIX timestamp after the last HT? 759 * GNU diff puts epoch there to signal a creation/deletion event. Is 760 * this such a timestamp? 761 */ 762static inthas_epoch_timestamp(const char*nameline) 763{ 764/* 765 * We are only interested in epoch timestamp; any non-zero 766 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 767 * For the same reason, the date must be either 1969-12-31 or 768 * 1970-01-01, and the seconds part must be "00". 769 */ 770const char stamp_regexp[] = 771"^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?" 772" " 773"([-+][0-2][0-9]:?[0-5][0-9])\n"; 774const char*timestamp = NULL, *cp, *colon; 775static regex_t *stamp; 776 regmatch_t m[10]; 777int zoneoffset, epoch_hour, hour, minute; 778int status; 779 780for(cp = nameline; *cp !='\n'; cp++) { 781if(*cp =='\t') 782 timestamp = cp +1; 783} 784if(!timestamp) 785return0; 786 787/* 788 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 789 * (west of GMT) or 1970-01-01 (east of GMT) 790 */ 791if(skip_prefix(timestamp,"1969-12-31 ", ×tamp)) 792 epoch_hour =24; 793else if(skip_prefix(timestamp,"1970-01-01 ", ×tamp)) 794 epoch_hour =0; 795else 796return0; 797 798if(!stamp) { 799 stamp =xmalloc(sizeof(*stamp)); 800if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 801warning(_("Cannot prepare timestamp regexp%s"), 802 stamp_regexp); 803return0; 804} 805} 806 807 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 808if(status) { 809if(status != REG_NOMATCH) 810warning(_("regexec returned%dfor input:%s"), 811 status, timestamp); 812return0; 813} 814 815 hour =strtol(timestamp, NULL,10); 816 minute =strtol(timestamp + m[1].rm_so, NULL,10); 817 818 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 819if(*colon ==':') 820 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 821else 822 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 823if(timestamp[m[3].rm_so] =='-') 824 zoneoffset = -zoneoffset; 825 826return hour *60+ minute - zoneoffset == epoch_hour *60; 827} 828 829/* 830 * Get the name etc info from the ---/+++ lines of a traditional patch header 831 * 832 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 833 * files, we can happily check the index for a match, but for creating a 834 * new file we should try to match whatever "patch" does. I have no idea. 835 */ 836static intparse_traditional_patch(struct apply_state *state, 837const char*first, 838const char*second, 839struct patch *patch) 840{ 841char*name; 842 843 first +=4;/* skip "--- " */ 844 second +=4;/* skip "+++ " */ 845if(!state->p_value_known) { 846int p, q; 847 p =guess_p_value(state, first); 848 q =guess_p_value(state, second); 849if(p <0) p = q; 850if(0<= p && p == q) { 851 state->p_value = p; 852 state->p_value_known =1; 853} 854} 855if(is_dev_null(first)) { 856 patch->is_new =1; 857 patch->is_delete =0; 858 name =find_name_traditional(&state->root, second, NULL, state->p_value); 859 patch->new_name = name; 860}else if(is_dev_null(second)) { 861 patch->is_new =0; 862 patch->is_delete =1; 863 name =find_name_traditional(&state->root, first, NULL, state->p_value); 864 patch->old_name = name; 865}else{ 866char*first_name; 867 first_name =find_name_traditional(&state->root, first, NULL, state->p_value); 868 name =find_name_traditional(&state->root, second, first_name, state->p_value); 869free(first_name); 870if(has_epoch_timestamp(first)) { 871 patch->is_new =1; 872 patch->is_delete =0; 873 patch->new_name = name; 874}else if(has_epoch_timestamp(second)) { 875 patch->is_new =0; 876 patch->is_delete =1; 877 patch->old_name = name; 878}else{ 879 patch->old_name = name; 880 patch->new_name =xstrdup_or_null(name); 881} 882} 883if(!name) 884returnerror(_("unable to find filename in patch at line%d"), state->linenr); 885 886return0; 887} 888 889static intgitdiff_hdrend(struct gitdiff_data *state, 890const char*line, 891struct patch *patch) 892{ 893return1; 894} 895 896/* 897 * We're anal about diff header consistency, to make 898 * sure that we don't end up having strange ambiguous 899 * patches floating around. 900 * 901 * As a result, gitdiff_{old|new}name() will check 902 * their names against any previous information, just 903 * to make sure.. 904 */ 905#define DIFF_OLD_NAME 0 906#define DIFF_NEW_NAME 1 907 908static intgitdiff_verify_name(struct gitdiff_data *state, 909const char*line, 910int isnull, 911char**name, 912int side) 913{ 914if(!*name && !isnull) { 915*name =find_name(state->root, line, NULL, state->p_value, TERM_TAB); 916return0; 917} 918 919if(*name) { 920char*another; 921if(isnull) 922returnerror(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 923*name, state->linenr); 924 another =find_name(state->root, line, NULL, state->p_value, TERM_TAB); 925if(!another ||strcmp(another, *name)) { 926free(another); 927returnerror((side == DIFF_NEW_NAME) ? 928_("git apply: bad git-diff - inconsistent new filename on line%d") : 929_("git apply: bad git-diff - inconsistent old filename on line%d"), state->linenr); 930} 931free(another); 932}else{ 933if(!is_dev_null(line)) 934returnerror(_("git apply: bad git-diff - expected /dev/null on line%d"), state->linenr); 935} 936 937return0; 938} 939 940static intgitdiff_oldname(struct gitdiff_data *state, 941const char*line, 942struct patch *patch) 943{ 944returngitdiff_verify_name(state, line, 945 patch->is_new, &patch->old_name, 946 DIFF_OLD_NAME); 947} 948 949static intgitdiff_newname(struct gitdiff_data *state, 950const char*line, 951struct patch *patch) 952{ 953returngitdiff_verify_name(state, line, 954 patch->is_delete, &patch->new_name, 955 DIFF_NEW_NAME); 956} 957 958static intparse_mode_line(const char*line,int linenr,unsigned int*mode) 959{ 960char*end; 961*mode =strtoul(line, &end,8); 962if(end == line || !isspace(*end)) 963returnerror(_("invalid mode on line%d:%s"), linenr, line); 964return0; 965} 966 967static intgitdiff_oldmode(struct gitdiff_data *state, 968const char*line, 969struct patch *patch) 970{ 971returnparse_mode_line(line, state->linenr, &patch->old_mode); 972} 973 974static intgitdiff_newmode(struct gitdiff_data *state, 975const char*line, 976struct patch *patch) 977{ 978returnparse_mode_line(line, state->linenr, &patch->new_mode); 979} 980 981static intgitdiff_delete(struct gitdiff_data *state, 982const char*line, 983struct patch *patch) 984{ 985 patch->is_delete =1; 986free(patch->old_name); 987 patch->old_name =xstrdup_or_null(patch->def_name); 988returngitdiff_oldmode(state, line, patch); 989} 990 991static intgitdiff_newfile(struct gitdiff_data *state, 992const char*line, 993struct patch *patch) 994{ 995 patch->is_new =1; 996free(patch->new_name); 997 patch->new_name =xstrdup_or_null(patch->def_name); 998returngitdiff_newmode(state, line, patch); 999}10001001static intgitdiff_copysrc(struct gitdiff_data *state,1002const char*line,1003struct patch *patch)1004{1005 patch->is_copy =1;1006free(patch->old_name);1007 patch->old_name =find_name(state->root, line, NULL, state->p_value ? state->p_value -1:0,0);1008return0;1009}10101011static intgitdiff_copydst(struct gitdiff_data *state,1012const char*line,1013struct patch *patch)1014{1015 patch->is_copy =1;1016free(patch->new_name);1017 patch->new_name =find_name(state->root, line, NULL, state->p_value ? state->p_value -1:0,0);1018return0;1019}10201021static intgitdiff_renamesrc(struct gitdiff_data *state,1022const char*line,1023struct patch *patch)1024{1025 patch->is_rename =1;1026free(patch->old_name);1027 patch->old_name =find_name(state->root, line, NULL, state->p_value ? state->p_value -1:0,0);1028return0;1029}10301031static intgitdiff_renamedst(struct gitdiff_data *state,1032const char*line,1033struct patch *patch)1034{1035 patch->is_rename =1;1036free(patch->new_name);1037 patch->new_name =find_name(state->root, line, NULL, state->p_value ? state->p_value -1:0,0);1038return0;1039}10401041static intgitdiff_similarity(struct gitdiff_data *state,1042const char*line,1043struct patch *patch)1044{1045unsigned long val =strtoul(line, NULL,10);1046if(val <=100)1047 patch->score = val;1048return0;1049}10501051static intgitdiff_dissimilarity(struct gitdiff_data *state,1052const char*line,1053struct patch *patch)1054{1055unsigned long val =strtoul(line, NULL,10);1056if(val <=100)1057 patch->score = val;1058return0;1059}10601061static intgitdiff_index(struct gitdiff_data *state,1062const char*line,1063struct patch *patch)1064{1065/*1066 * index line is N hexadecimal, "..", N hexadecimal,1067 * and optional space with octal mode.1068 */1069const char*ptr, *eol;1070int len;1071const unsigned hexsz = the_hash_algo->hexsz;10721073 ptr =strchr(line,'.');1074if(!ptr || ptr[1] !='.'|| hexsz < ptr - line)1075return0;1076 len = ptr - line;1077memcpy(patch->old_oid_prefix, line, len);1078 patch->old_oid_prefix[len] =0;10791080 line = ptr +2;1081 ptr =strchr(line,' ');1082 eol =strchrnul(line,'\n');10831084if(!ptr || eol < ptr)1085 ptr = eol;1086 len = ptr - line;10871088if(hexsz < len)1089return0;1090memcpy(patch->new_oid_prefix, line, len);1091 patch->new_oid_prefix[len] =0;1092if(*ptr ==' ')1093returngitdiff_oldmode(state, ptr +1, patch);1094return0;1095}10961097/*1098 * This is normal for a diff that doesn't change anything: we'll fall through1099 * into the next diff. Tell the parser to break out.1100 */1101static intgitdiff_unrecognized(struct gitdiff_data *state,1102const char*line,1103struct patch *patch)1104{1105return1;1106}11071108/*1109 * Skip p_value leading components from "line"; as we do not accept1110 * absolute paths, return NULL in that case.1111 */1112static const char*skip_tree_prefix(int p_value,1113const char*line,1114int llen)1115{1116int nslash;1117int i;11181119if(!p_value)1120return(llen && line[0] =='/') ? NULL : line;11211122 nslash = p_value;1123for(i =0; i < llen; i++) {1124int ch = line[i];1125if(ch =='/'&& --nslash <=0)1126return(i ==0) ? NULL : &line[i +1];1127}1128return NULL;1129}11301131/*1132 * This is to extract the same name that appears on "diff --git"1133 * line. We do not find and return anything if it is a rename1134 * patch, and it is OK because we will find the name elsewhere.1135 * We need to reliably find name only when it is mode-change only,1136 * creation or deletion of an empty file. In any of these cases,1137 * both sides are the same name under a/ and b/ respectively.1138 */1139static char*git_header_name(int p_value,1140const char*line,1141int llen)1142{1143const char*name;1144const char*second = NULL;1145size_t len, line_len;11461147 line +=strlen("diff --git ");1148 llen -=strlen("diff --git ");11491150if(*line =='"') {1151const char*cp;1152struct strbuf first = STRBUF_INIT;1153struct strbuf sp = STRBUF_INIT;11541155if(unquote_c_style(&first, line, &second))1156goto free_and_fail1;11571158/* strip the a/b prefix including trailing slash */1159 cp =skip_tree_prefix(p_value, first.buf, first.len);1160if(!cp)1161goto free_and_fail1;1162strbuf_remove(&first,0, cp - first.buf);11631164/*1165 * second points at one past closing dq of name.1166 * find the second name.1167 */1168while((second < line + llen) &&isspace(*second))1169 second++;11701171if(line + llen <= second)1172goto free_and_fail1;1173if(*second =='"') {1174if(unquote_c_style(&sp, second, NULL))1175goto free_and_fail1;1176 cp =skip_tree_prefix(p_value, sp.buf, sp.len);1177if(!cp)1178goto free_and_fail1;1179/* They must match, otherwise ignore */1180if(strcmp(cp, first.buf))1181goto free_and_fail1;1182strbuf_release(&sp);1183returnstrbuf_detach(&first, NULL);1184}11851186/* unquoted second */1187 cp =skip_tree_prefix(p_value, second, line + llen - second);1188if(!cp)1189goto free_and_fail1;1190if(line + llen - cp != first.len ||1191memcmp(first.buf, cp, first.len))1192goto free_and_fail1;1193returnstrbuf_detach(&first, NULL);11941195 free_and_fail1:1196strbuf_release(&first);1197strbuf_release(&sp);1198return NULL;1199}12001201/* unquoted first name */1202 name =skip_tree_prefix(p_value, line, llen);1203if(!name)1204return NULL;12051206/*1207 * since the first name is unquoted, a dq if exists must be1208 * the beginning of the second name.1209 */1210for(second = name; second < line + llen; second++) {1211if(*second =='"') {1212struct strbuf sp = STRBUF_INIT;1213const char*np;12141215if(unquote_c_style(&sp, second, NULL))1216goto free_and_fail2;12171218 np =skip_tree_prefix(p_value, sp.buf, sp.len);1219if(!np)1220goto free_and_fail2;12211222 len = sp.buf + sp.len - np;1223if(len < second - name &&1224!strncmp(np, name, len) &&1225isspace(name[len])) {1226/* Good */1227strbuf_remove(&sp,0, np - sp.buf);1228returnstrbuf_detach(&sp, NULL);1229}12301231 free_and_fail2:1232strbuf_release(&sp);1233return NULL;1234}1235}12361237/*1238 * Accept a name only if it shows up twice, exactly the same1239 * form.1240 */1241 second =strchr(name,'\n');1242if(!second)1243return NULL;1244 line_len = second - name;1245for(len =0; ; len++) {1246switch(name[len]) {1247default:1248continue;1249case'\n':1250return NULL;1251case'\t':case' ':1252/*1253 * Is this the separator between the preimage1254 * and the postimage pathname? Again, we are1255 * only interested in the case where there is1256 * no rename, as this is only to set def_name1257 * and a rename patch has the names elsewhere1258 * in an unambiguous form.1259 */1260if(!name[len +1])1261return NULL;/* no postimage name */1262 second =skip_tree_prefix(p_value, name + len +1,1263 line_len - (len +1));1264if(!second)1265return NULL;1266/*1267 * Does len bytes starting at "name" and "second"1268 * (that are separated by one HT or SP we just1269 * found) exactly match?1270 */1271if(second[len] =='\n'&& !strncmp(name, second, len))1272returnxmemdupz(name, len);1273}1274}1275}12761277static intcheck_header_line(int linenr,struct patch *patch)1278{1279int extensions = (patch->is_delete ==1) + (patch->is_new ==1) +1280(patch->is_rename ==1) + (patch->is_copy ==1);1281if(extensions >1)1282returnerror(_("inconsistent header lines%dand%d"),1283 patch->extension_linenr, linenr);1284if(extensions && !patch->extension_linenr)1285 patch->extension_linenr = linenr;1286return0;1287}12881289intparse_git_diff_header(struct strbuf *root,1290int*linenr,1291int p_value,1292const char*line,1293int len,1294unsigned int size,1295struct patch *patch)1296{1297unsigned long offset;1298struct gitdiff_data parse_hdr_state;12991300/* A git diff has explicit new/delete information, so we don't guess */1301 patch->is_new =0;1302 patch->is_delete =0;13031304/*1305 * Some things may not have the old name in the1306 * rest of the headers anywhere (pure mode changes,1307 * or removing or adding empty files), so we get1308 * the default name from the header.1309 */1310 patch->def_name =git_header_name(p_value, line, len);1311if(patch->def_name && root->len) {1312char*s =xstrfmt("%s%s", root->buf, patch->def_name);1313free(patch->def_name);1314 patch->def_name = s;1315}13161317 line += len;1318 size -= len;1319(*linenr)++;1320 parse_hdr_state.root = root;1321 parse_hdr_state.linenr = *linenr;1322 parse_hdr_state.p_value = p_value;13231324for(offset = len ; size >0; offset += len, size -= len, line += len, (*linenr)++) {1325static const struct opentry {1326const char*str;1327int(*fn)(struct gitdiff_data *,const char*,struct patch *);1328} optable[] = {1329{"@@ -", gitdiff_hdrend },1330{"--- ", gitdiff_oldname },1331{"+++ ", gitdiff_newname },1332{"old mode ", gitdiff_oldmode },1333{"new mode ", gitdiff_newmode },1334{"deleted file mode ", gitdiff_delete },1335{"new file mode ", gitdiff_newfile },1336{"copy from ", gitdiff_copysrc },1337{"copy to ", gitdiff_copydst },1338{"rename old ", gitdiff_renamesrc },1339{"rename new ", gitdiff_renamedst },1340{"rename from ", gitdiff_renamesrc },1341{"rename to ", gitdiff_renamedst },1342{"similarity index ", gitdiff_similarity },1343{"dissimilarity index ", gitdiff_dissimilarity },1344{"index ", gitdiff_index },1345{"", gitdiff_unrecognized },1346};1347int i;13481349 len =linelen(line, size);1350if(!len || line[len-1] !='\n')1351break;1352for(i =0; i <ARRAY_SIZE(optable); i++) {1353const struct opentry *p = optable + i;1354int oplen =strlen(p->str);1355int res;1356if(len < oplen ||memcmp(p->str, line, oplen))1357continue;1358 res = p->fn(&parse_hdr_state, line + oplen, patch);1359if(res <0)1360return-1;1361if(check_header_line(*linenr, patch))1362return-1;1363if(res >0)1364return offset;1365break;1366}1367}13681369return offset;1370}13711372static intparse_num(const char*line,unsigned long*p)1373{1374char*ptr;13751376if(!isdigit(*line))1377return0;1378*p =strtoul(line, &ptr,10);1379return ptr - line;1380}13811382static intparse_range(const char*line,int len,int offset,const char*expect,1383unsigned long*p1,unsigned long*p2)1384{1385int digits, ex;13861387if(offset <0|| offset >= len)1388return-1;1389 line += offset;1390 len -= offset;13911392 digits =parse_num(line, p1);1393if(!digits)1394return-1;13951396 offset += digits;1397 line += digits;1398 len -= digits;13991400*p2 =1;1401if(*line ==',') {1402 digits =parse_num(line+1, p2);1403if(!digits)1404return-1;14051406 offset += digits+1;1407 line += digits+1;1408 len -= digits+1;1409}14101411 ex =strlen(expect);1412if(ex > len)1413return-1;1414if(memcmp(line, expect, ex))1415return-1;14161417return offset + ex;1418}14191420static voidrecount_diff(const char*line,int size,struct fragment *fragment)1421{1422int oldlines =0, newlines =0, ret =0;14231424if(size <1) {1425warning("recount: ignore empty hunk");1426return;1427}14281429for(;;) {1430int len =linelen(line, size);1431 size -= len;1432 line += len;14331434if(size <1)1435break;14361437switch(*line) {1438case' ':case'\n':1439 newlines++;1440/* fall through */1441case'-':1442 oldlines++;1443continue;1444case'+':1445 newlines++;1446continue;1447case'\\':1448continue;1449case'@':1450 ret = size <3|| !starts_with(line,"@@ ");1451break;1452case'd':1453 ret = size <5|| !starts_with(line,"diff ");1454break;1455default:1456 ret = -1;1457break;1458}1459if(ret) {1460warning(_("recount: unexpected line: %.*s"),1461(int)linelen(line, size), line);1462return;1463}1464break;1465}1466 fragment->oldlines = oldlines;1467 fragment->newlines = newlines;1468}14691470/*1471 * Parse a unified diff fragment header of the1472 * form "@@ -a,b +c,d @@"1473 */1474static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1475{1476int offset;14771478if(!len || line[len-1] !='\n')1479return-1;14801481/* Figure out the number of lines in a fragment */1482 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1483 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14841485return offset;1486}14871488/*1489 * Find file diff header1490 *1491 * Returns:1492 * -1 if no header was found1493 * -128 in case of error1494 * the size of the header in bytes (called "offset") otherwise1495 */1496static intfind_header(struct apply_state *state,1497const char*line,1498unsigned long size,1499int*hdrsize,1500struct patch *patch)1501{1502unsigned long offset, len;15031504 patch->is_toplevel_relative =0;1505 patch->is_rename = patch->is_copy =0;1506 patch->is_new = patch->is_delete = -1;1507 patch->old_mode = patch->new_mode =0;1508 patch->old_name = patch->new_name = NULL;1509for(offset =0; size >0; offset += len, size -= len, line += len, state->linenr++) {1510unsigned long nextlen;15111512 len =linelen(line, size);1513if(!len)1514break;15151516/* Testing this early allows us to take a few shortcuts.. */1517if(len <6)1518continue;15191520/*1521 * Make sure we don't find any unconnected patch fragments.1522 * That's a sign that we didn't find a header, and that a1523 * patch has become corrupted/broken up.1524 */1525if(!memcmp("@@ -", line,4)) {1526struct fragment dummy;1527if(parse_fragment_header(line, len, &dummy) <0)1528continue;1529error(_("patch fragment without header at line%d: %.*s"),1530 state->linenr, (int)len-1, line);1531return-128;1532}15331534if(size < len +6)1535break;15361537/*1538 * Git patch? It might not have a real patch, just a rename1539 * or mode change, so we handle that specially1540 */1541if(!memcmp("diff --git ", line,11)) {1542int git_hdr_len =parse_git_diff_header(&state->root, &state->linenr,1543 state->p_value, line, len,1544 size, patch);1545if(git_hdr_len <0)1546return-128;1547if(git_hdr_len <= len)1548continue;1549if(!patch->old_name && !patch->new_name) {1550if(!patch->def_name) {1551error(Q_("git diff header lacks filename information when removing "1552"%dleading pathname component (line%d)",1553"git diff header lacks filename information when removing "1554"%dleading pathname components (line%d)",1555 state->p_value),1556 state->p_value, state->linenr);1557return-128;1558}1559 patch->old_name =xstrdup(patch->def_name);1560 patch->new_name =xstrdup(patch->def_name);1561}1562if((!patch->new_name && !patch->is_delete) ||1563(!patch->old_name && !patch->is_new)) {1564error(_("git diff header lacks filename information "1565"(line%d)"), state->linenr);1566return-128;1567}1568 patch->is_toplevel_relative =1;1569*hdrsize = git_hdr_len;1570return offset;1571}15721573/* --- followed by +++ ? */1574if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1575continue;15761577/*1578 * We only accept unified patches, so we want it to1579 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1580 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1581 */1582 nextlen =linelen(line + len, size - len);1583if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1584continue;15851586/* Ok, we'll consider it a patch */1587if(parse_traditional_patch(state, line, line+len, patch))1588return-128;1589*hdrsize = len + nextlen;1590 state->linenr +=2;1591return offset;1592}1593return-1;1594}15951596static voidrecord_ws_error(struct apply_state *state,1597unsigned result,1598const char*line,1599int len,1600int linenr)1601{1602char*err;16031604if(!result)1605return;16061607 state->whitespace_error++;1608if(state->squelch_whitespace_errors &&1609 state->squelch_whitespace_errors < state->whitespace_error)1610return;16111612 err =whitespace_error_string(result);1613if(state->apply_verbosity > verbosity_silent)1614fprintf(stderr,"%s:%d:%s.\n%.*s\n",1615 state->patch_input_file, linenr, err, len, line);1616free(err);1617}16181619static voidcheck_whitespace(struct apply_state *state,1620const char*line,1621int len,1622unsigned ws_rule)1623{1624unsigned result =ws_check(line +1, len -1, ws_rule);16251626record_ws_error(state, result, line +1, len -2, state->linenr);1627}16281629/*1630 * Check if the patch has context lines with CRLF or1631 * the patch wants to remove lines with CRLF.1632 */1633static voidcheck_old_for_crlf(struct patch *patch,const char*line,int len)1634{1635if(len >=2&& line[len-1] =='\n'&& line[len-2] =='\r') {1636 patch->ws_rule |= WS_CR_AT_EOL;1637 patch->crlf_in_old =1;1638}1639}164016411642/*1643 * Parse a unified diff. Note that this really needs to parse each1644 * fragment separately, since the only way to know the difference1645 * between a "---" that is part of a patch, and a "---" that starts1646 * the next patch is to look at the line counts..1647 */1648static intparse_fragment(struct apply_state *state,1649const char*line,1650unsigned long size,1651struct patch *patch,1652struct fragment *fragment)1653{1654int added, deleted;1655int len =linelen(line, size), offset;1656unsigned long oldlines, newlines;1657unsigned long leading, trailing;16581659 offset =parse_fragment_header(line, len, fragment);1660if(offset <0)1661return-1;1662if(offset >0&& patch->recount)1663recount_diff(line + offset, size - offset, fragment);1664 oldlines = fragment->oldlines;1665 newlines = fragment->newlines;1666 leading =0;1667 trailing =0;16681669/* Parse the thing.. */1670 line += len;1671 size -= len;1672 state->linenr++;1673 added = deleted =0;1674for(offset = len;16750< size;1676 offset += len, size -= len, line += len, state->linenr++) {1677if(!oldlines && !newlines)1678break;1679 len =linelen(line, size);1680if(!len || line[len-1] !='\n')1681return-1;1682switch(*line) {1683default:1684return-1;1685case'\n':/* newer GNU diff, an empty context line */1686case' ':1687 oldlines--;1688 newlines--;1689if(!deleted && !added)1690 leading++;1691 trailing++;1692check_old_for_crlf(patch, line, len);1693if(!state->apply_in_reverse &&1694 state->ws_error_action == correct_ws_error)1695check_whitespace(state, line, len, patch->ws_rule);1696break;1697case'-':1698if(!state->apply_in_reverse)1699check_old_for_crlf(patch, line, len);1700if(state->apply_in_reverse &&1701 state->ws_error_action != nowarn_ws_error)1702check_whitespace(state, line, len, patch->ws_rule);1703 deleted++;1704 oldlines--;1705 trailing =0;1706break;1707case'+':1708if(state->apply_in_reverse)1709check_old_for_crlf(patch, line, len);1710if(!state->apply_in_reverse &&1711 state->ws_error_action != nowarn_ws_error)1712check_whitespace(state, line, len, patch->ws_rule);1713 added++;1714 newlines--;1715 trailing =0;1716break;17171718/*1719 * We allow "\ No newline at end of file". Depending1720 * on locale settings when the patch was produced we1721 * don't know what this line looks like. The only1722 * thing we do know is that it begins with "\ ".1723 * Checking for 12 is just for sanity check -- any1724 * l10n of "\ No newline..." is at least that long.1725 */1726case'\\':1727if(len <12||memcmp(line,"\\",2))1728return-1;1729break;1730}1731}1732if(oldlines || newlines)1733return-1;1734if(!patch->recount && !deleted && !added)1735return-1;17361737 fragment->leading = leading;1738 fragment->trailing = trailing;17391740/*1741 * If a fragment ends with an incomplete line, we failed to include1742 * it in the above loop because we hit oldlines == newlines == 01743 * before seeing it.1744 */1745if(12< size && !memcmp(line,"\\",2))1746 offset +=linelen(line, size);17471748 patch->lines_added += added;1749 patch->lines_deleted += deleted;17501751if(0< patch->is_new && oldlines)1752returnerror(_("new file depends on old contents"));1753if(0< patch->is_delete && newlines)1754returnerror(_("deleted file still has contents"));1755return offset;1756}17571758/*1759 * We have seen "diff --git a/... b/..." header (or a traditional patch1760 * header). Read hunks that belong to this patch into fragments and hang1761 * them to the given patch structure.1762 *1763 * The (fragment->patch, fragment->size) pair points into the memory given1764 * by the caller, not a copy, when we return.1765 *1766 * Returns:1767 * -1 in case of error,1768 * the number of bytes in the patch otherwise.1769 */1770static intparse_single_patch(struct apply_state *state,1771const char*line,1772unsigned long size,1773struct patch *patch)1774{1775unsigned long offset =0;1776unsigned long oldlines =0, newlines =0, context =0;1777struct fragment **fragp = &patch->fragments;17781779while(size >4&& !memcmp(line,"@@ -",4)) {1780struct fragment *fragment;1781int len;17821783 fragment =xcalloc(1,sizeof(*fragment));1784 fragment->linenr = state->linenr;1785 len =parse_fragment(state, line, size, patch, fragment);1786if(len <=0) {1787free(fragment);1788returnerror(_("corrupt patch at line%d"), state->linenr);1789}1790 fragment->patch = line;1791 fragment->size = len;1792 oldlines += fragment->oldlines;1793 newlines += fragment->newlines;1794 context += fragment->leading + fragment->trailing;17951796*fragp = fragment;1797 fragp = &fragment->next;17981799 offset += len;1800 line += len;1801 size -= len;1802}18031804/*1805 * If something was removed (i.e. we have old-lines) it cannot1806 * be creation, and if something was added it cannot be1807 * deletion. However, the reverse is not true; --unified=01808 * patches that only add are not necessarily creation even1809 * though they do not have any old lines, and ones that only1810 * delete are not necessarily deletion.1811 *1812 * Unfortunately, a real creation/deletion patch do _not_ have1813 * any context line by definition, so we cannot safely tell it1814 * apart with --unified=0 insanity. At least if the patch has1815 * more than one hunk it is not creation or deletion.1816 */1817if(patch->is_new <0&&1818(oldlines || (patch->fragments && patch->fragments->next)))1819 patch->is_new =0;1820if(patch->is_delete <0&&1821(newlines || (patch->fragments && patch->fragments->next)))1822 patch->is_delete =0;18231824if(0< patch->is_new && oldlines)1825returnerror(_("new file%sdepends on old contents"), patch->new_name);1826if(0< patch->is_delete && newlines)1827returnerror(_("deleted file%sstill has contents"), patch->old_name);1828if(!patch->is_delete && !newlines && context && state->apply_verbosity > verbosity_silent)1829fprintf_ln(stderr,1830_("** warning: "1831"file%sbecomes empty but is not deleted"),1832 patch->new_name);18331834return offset;1835}18361837staticinlineintmetadata_changes(struct patch *patch)1838{1839return patch->is_rename >0||1840 patch->is_copy >0||1841 patch->is_new >0||1842 patch->is_delete ||1843(patch->old_mode && patch->new_mode &&1844 patch->old_mode != patch->new_mode);1845}18461847static char*inflate_it(const void*data,unsigned long size,1848unsigned long inflated_size)1849{1850 git_zstream stream;1851void*out;1852int st;18531854memset(&stream,0,sizeof(stream));18551856 stream.next_in = (unsigned char*)data;1857 stream.avail_in = size;1858 stream.next_out = out =xmalloc(inflated_size);1859 stream.avail_out = inflated_size;1860git_inflate_init(&stream);1861 st =git_inflate(&stream, Z_FINISH);1862git_inflate_end(&stream);1863if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1864free(out);1865return NULL;1866}1867return out;1868}18691870/*1871 * Read a binary hunk and return a new fragment; fragment->patch1872 * points at an allocated memory that the caller must free, so1873 * it is marked as "->free_patch = 1".1874 */1875static struct fragment *parse_binary_hunk(struct apply_state *state,1876char**buf_p,1877unsigned long*sz_p,1878int*status_p,1879int*used_p)1880{1881/*1882 * Expect a line that begins with binary patch method ("literal"1883 * or "delta"), followed by the length of data before deflating.1884 * a sequence of 'length-byte' followed by base-85 encoded data1885 * should follow, terminated by a newline.1886 *1887 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1888 * and we would limit the patch line to 66 characters,1889 * so one line can fit up to 13 groups that would decode1890 * to 52 bytes max. The length byte 'A'-'Z' corresponds1891 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1892 */1893int llen, used;1894unsigned long size = *sz_p;1895char*buffer = *buf_p;1896int patch_method;1897unsigned long origlen;1898char*data = NULL;1899int hunk_size =0;1900struct fragment *frag;19011902 llen =linelen(buffer, size);1903 used = llen;19041905*status_p =0;19061907if(starts_with(buffer,"delta ")) {1908 patch_method = BINARY_DELTA_DEFLATED;1909 origlen =strtoul(buffer +6, NULL,10);1910}1911else if(starts_with(buffer,"literal ")) {1912 patch_method = BINARY_LITERAL_DEFLATED;1913 origlen =strtoul(buffer +8, NULL,10);1914}1915else1916return NULL;19171918 state->linenr++;1919 buffer += llen;1920while(1) {1921int byte_length, max_byte_length, newsize;1922 llen =linelen(buffer, size);1923 used += llen;1924 state->linenr++;1925if(llen ==1) {1926/* consume the blank line */1927 buffer++;1928 size--;1929break;1930}1931/*1932 * Minimum line is "A00000\n" which is 7-byte long,1933 * and the line length must be multiple of 5 plus 2.1934 */1935if((llen <7) || (llen-2) %5)1936goto corrupt;1937 max_byte_length = (llen -2) /5*4;1938 byte_length = *buffer;1939if('A'<= byte_length && byte_length <='Z')1940 byte_length = byte_length -'A'+1;1941else if('a'<= byte_length && byte_length <='z')1942 byte_length = byte_length -'a'+27;1943else1944goto corrupt;1945/* if the input length was not multiple of 4, we would1946 * have filler at the end but the filler should never1947 * exceed 3 bytes1948 */1949if(max_byte_length < byte_length ||1950 byte_length <= max_byte_length -4)1951goto corrupt;1952 newsize = hunk_size + byte_length;1953 data =xrealloc(data, newsize);1954if(decode_85(data + hunk_size, buffer +1, byte_length))1955goto corrupt;1956 hunk_size = newsize;1957 buffer += llen;1958 size -= llen;1959}19601961 frag =xcalloc(1,sizeof(*frag));1962 frag->patch =inflate_it(data, hunk_size, origlen);1963 frag->free_patch =1;1964if(!frag->patch)1965goto corrupt;1966free(data);1967 frag->size = origlen;1968*buf_p = buffer;1969*sz_p = size;1970*used_p = used;1971 frag->binary_patch_method = patch_method;1972return frag;19731974 corrupt:1975free(data);1976*status_p = -1;1977error(_("corrupt binary patch at line%d: %.*s"),1978 state->linenr-1, llen-1, buffer);1979return NULL;1980}19811982/*1983 * Returns:1984 * -1 in case of error,1985 * the length of the parsed binary patch otherwise1986 */1987static intparse_binary(struct apply_state *state,1988char*buffer,1989unsigned long size,1990struct patch *patch)1991{1992/*1993 * We have read "GIT binary patch\n"; what follows is a line1994 * that says the patch method (currently, either "literal" or1995 * "delta") and the length of data before deflating; a1996 * sequence of 'length-byte' followed by base-85 encoded data1997 * follows.1998 *1999 * When a binary patch is reversible, there is another binary2000 * hunk in the same format, starting with patch method (either2001 * "literal" or "delta") with the length of data, and a sequence2002 * of length-byte + base-85 encoded data, terminated with another2003 * empty line. This data, when applied to the postimage, produces2004 * the preimage.2005 */2006struct fragment *forward;2007struct fragment *reverse;2008int status;2009int used, used_1;20102011 forward =parse_binary_hunk(state, &buffer, &size, &status, &used);2012if(!forward && !status)2013/* there has to be one hunk (forward hunk) */2014returnerror(_("unrecognized binary patch at line%d"), state->linenr-1);2015if(status)2016/* otherwise we already gave an error message */2017return status;20182019 reverse =parse_binary_hunk(state, &buffer, &size, &status, &used_1);2020if(reverse)2021 used += used_1;2022else if(status) {2023/*2024 * Not having reverse hunk is not an error, but having2025 * a corrupt reverse hunk is.2026 */2027free((void*) forward->patch);2028free(forward);2029return status;2030}2031 forward->next = reverse;2032 patch->fragments = forward;2033 patch->is_binary =1;2034return used;2035}20362037static voidprefix_one(struct apply_state *state,char**name)2038{2039char*old_name = *name;2040if(!old_name)2041return;2042*name =prefix_filename(state->prefix, *name);2043free(old_name);2044}20452046static voidprefix_patch(struct apply_state *state,struct patch *p)2047{2048if(!state->prefix || p->is_toplevel_relative)2049return;2050prefix_one(state, &p->new_name);2051prefix_one(state, &p->old_name);2052}20532054/*2055 * include/exclude2056 */20572058static voidadd_name_limit(struct apply_state *state,2059const char*name,2060int exclude)2061{2062struct string_list_item *it;20632064 it =string_list_append(&state->limit_by_name, name);2065 it->util = exclude ? NULL : (void*)1;2066}20672068static intuse_patch(struct apply_state *state,struct patch *p)2069{2070const char*pathname = p->new_name ? p->new_name : p->old_name;2071int i;20722073/* Paths outside are not touched regardless of "--include" */2074if(state->prefix && *state->prefix) {2075const char*rest;2076if(!skip_prefix(pathname, state->prefix, &rest) || !*rest)2077return0;2078}20792080/* See if it matches any of exclude/include rule */2081for(i =0; i < state->limit_by_name.nr; i++) {2082struct string_list_item *it = &state->limit_by_name.items[i];2083if(!wildmatch(it->string, pathname,0))2084return(it->util != NULL);2085}20862087/*2088 * If we had any include, a path that does not match any rule is2089 * not used. Otherwise, we saw bunch of exclude rules (or none)2090 * and such a path is used.2091 */2092return!state->has_include;2093}20942095/*2096 * Read the patch text in "buffer" that extends for "size" bytes; stop2097 * reading after seeing a single patch (i.e. changes to a single file).2098 * Create fragments (i.e. patch hunks) and hang them to the given patch.2099 *2100 * Returns:2101 * -1 if no header was found or parse_binary() failed,2102 * -128 on another error,2103 * the number of bytes consumed otherwise,2104 * so that the caller can call us again for the next patch.2105 */2106static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2107{2108int hdrsize, patchsize;2109int offset =find_header(state, buffer, size, &hdrsize, patch);21102111if(offset <0)2112return offset;21132114prefix_patch(state, patch);21152116if(!use_patch(state, patch))2117 patch->ws_rule =0;2118else if(patch->new_name)2119 patch->ws_rule =whitespace_rule(state->repo->index,2120 patch->new_name);2121else2122 patch->ws_rule =whitespace_rule(state->repo->index,2123 patch->old_name);21242125 patchsize =parse_single_patch(state,2126 buffer + offset + hdrsize,2127 size - offset - hdrsize,2128 patch);21292130if(patchsize <0)2131return-128;21322133if(!patchsize) {2134static const char git_binary[] ="GIT binary patch\n";2135int hd = hdrsize + offset;2136unsigned long llen =linelen(buffer + hd, size - hd);21372138if(llen ==sizeof(git_binary) -1&&2139!memcmp(git_binary, buffer + hd, llen)) {2140int used;2141 state->linenr++;2142 used =parse_binary(state, buffer + hd + llen,2143 size - hd - llen, patch);2144if(used <0)2145return-1;2146if(used)2147 patchsize = used + llen;2148else2149 patchsize =0;2150}2151else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2152static const char*binhdr[] = {2153"Binary files ",2154"Files ",2155 NULL,2156};2157int i;2158for(i =0; binhdr[i]; i++) {2159int len =strlen(binhdr[i]);2160if(len < size - hd &&2161!memcmp(binhdr[i], buffer + hd, len)) {2162 state->linenr++;2163 patch->is_binary =1;2164 patchsize = llen;2165break;2166}2167}2168}21692170/* Empty patch cannot be applied if it is a text patch2171 * without metadata change. A binary patch appears2172 * empty to us here.2173 */2174if((state->apply || state->check) &&2175(!patch->is_binary && !metadata_changes(patch))) {2176error(_("patch with only garbage at line%d"), state->linenr);2177return-128;2178}2179}21802181return offset + hdrsize + patchsize;2182}21832184static voidreverse_patches(struct patch *p)2185{2186for(; p; p = p->next) {2187struct fragment *frag = p->fragments;21882189SWAP(p->new_name, p->old_name);2190SWAP(p->new_mode, p->old_mode);2191SWAP(p->is_new, p->is_delete);2192SWAP(p->lines_added, p->lines_deleted);2193SWAP(p->old_oid_prefix, p->new_oid_prefix);21942195for(; frag; frag = frag->next) {2196SWAP(frag->newpos, frag->oldpos);2197SWAP(frag->newlines, frag->oldlines);2198}2199}2200}22012202static const char pluses[] =2203"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2204static const char minuses[]=2205"----------------------------------------------------------------------";22062207static voidshow_stats(struct apply_state *state,struct patch *patch)2208{2209struct strbuf qname = STRBUF_INIT;2210char*cp = patch->new_name ? patch->new_name : patch->old_name;2211int max, add, del;22122213quote_c_style(cp, &qname, NULL,0);22142215/*2216 * "scale" the filename2217 */2218 max = state->max_len;2219if(max >50)2220 max =50;22212222if(qname.len > max) {2223 cp =strchr(qname.buf + qname.len +3- max,'/');2224if(!cp)2225 cp = qname.buf + qname.len +3- max;2226strbuf_splice(&qname,0, cp - qname.buf,"...",3);2227}22282229if(patch->is_binary) {2230printf(" %-*s | Bin\n", max, qname.buf);2231strbuf_release(&qname);2232return;2233}22342235printf(" %-*s |", max, qname.buf);2236strbuf_release(&qname);22372238/*2239 * scale the add/delete2240 */2241 max = max + state->max_change >70?70- max : state->max_change;2242 add = patch->lines_added;2243 del = patch->lines_deleted;22442245if(state->max_change >0) {2246int total = ((add + del) * max + state->max_change /2) / state->max_change;2247 add = (add * max + state->max_change /2) / state->max_change;2248 del = total - add;2249}2250printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2251 add, pluses, del, minuses);2252}22532254static intread_old_data(struct stat *st,struct patch *patch,2255const char*path,struct strbuf *buf)2256{2257int conv_flags = patch->crlf_in_old ?2258 CONV_EOL_KEEP_CRLF : CONV_EOL_RENORMALIZE;2259switch(st->st_mode & S_IFMT) {2260case S_IFLNK:2261if(strbuf_readlink(buf, path, st->st_size) <0)2262returnerror(_("unable to read symlink%s"), path);2263return0;2264case S_IFREG:2265if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2266returnerror(_("unable to open or read%s"), path);2267/*2268 * "git apply" without "--index/--cached" should never look2269 * at the index; the target file may not have been added to2270 * the index yet, and we may not even be in any Git repository.2271 * Pass NULL to convert_to_git() to stress this; the function2272 * should never look at the index when explicit crlf option2273 * is given.2274 */2275convert_to_git(NULL, path, buf->buf, buf->len, buf, conv_flags);2276return0;2277default:2278return-1;2279}2280}22812282/*2283 * Update the preimage, and the common lines in postimage,2284 * from buffer buf of length len. If postlen is 0 the postimage2285 * is updated in place, otherwise it's updated on a new buffer2286 * of length postlen2287 */22882289static voidupdate_pre_post_images(struct image *preimage,2290struct image *postimage,2291char*buf,2292size_t len,size_t postlen)2293{2294int i, ctx, reduced;2295char*new_buf, *old_buf, *fixed;2296struct image fixed_preimage;22972298/*2299 * Update the preimage with whitespace fixes. Note that we2300 * are not losing preimage->buf -- apply_one_fragment() will2301 * free "oldlines".2302 */2303prepare_image(&fixed_preimage, buf, len,1);2304assert(postlen2305? fixed_preimage.nr == preimage->nr2306: fixed_preimage.nr <= preimage->nr);2307for(i =0; i < fixed_preimage.nr; i++)2308 fixed_preimage.line[i].flag = preimage->line[i].flag;2309free(preimage->line_allocated);2310*preimage = fixed_preimage;23112312/*2313 * Adjust the common context lines in postimage. This can be2314 * done in-place when we are shrinking it with whitespace2315 * fixing, but needs a new buffer when ignoring whitespace or2316 * expanding leading tabs to spaces.2317 *2318 * We trust the caller to tell us if the update can be done2319 * in place (postlen==0) or not.2320 */2321 old_buf = postimage->buf;2322if(postlen)2323 new_buf = postimage->buf =xmalloc(postlen);2324else2325 new_buf = old_buf;2326 fixed = preimage->buf;23272328for(i = reduced = ctx =0; i < postimage->nr; i++) {2329size_t l_len = postimage->line[i].len;2330if(!(postimage->line[i].flag & LINE_COMMON)) {2331/* an added line -- no counterparts in preimage */2332memmove(new_buf, old_buf, l_len);2333 old_buf += l_len;2334 new_buf += l_len;2335continue;2336}23372338/* a common context -- skip it in the original postimage */2339 old_buf += l_len;23402341/* and find the corresponding one in the fixed preimage */2342while(ctx < preimage->nr &&2343!(preimage->line[ctx].flag & LINE_COMMON)) {2344 fixed += preimage->line[ctx].len;2345 ctx++;2346}23472348/*2349 * preimage is expected to run out, if the caller2350 * fixed addition of trailing blank lines.2351 */2352if(preimage->nr <= ctx) {2353 reduced++;2354continue;2355}23562357/* and copy it in, while fixing the line length */2358 l_len = preimage->line[ctx].len;2359memcpy(new_buf, fixed, l_len);2360 new_buf += l_len;2361 fixed += l_len;2362 postimage->line[i].len = l_len;2363 ctx++;2364}23652366if(postlen2367? postlen < new_buf - postimage->buf2368: postimage->len < new_buf - postimage->buf)2369BUG("caller miscounted postlen: asked%d, orig =%d, used =%d",2370(int)postlen, (int) postimage->len, (int)(new_buf - postimage->buf));23712372/* Fix the length of the whole thing */2373 postimage->len = new_buf - postimage->buf;2374 postimage->nr -= reduced;2375}23762377static intline_by_line_fuzzy_match(struct image *img,2378struct image *preimage,2379struct image *postimage,2380unsigned long current,2381int current_lno,2382int preimage_limit)2383{2384int i;2385size_t imgoff =0;2386size_t preoff =0;2387size_t postlen = postimage->len;2388size_t extra_chars;2389char*buf;2390char*preimage_eof;2391char*preimage_end;2392struct strbuf fixed;2393char*fixed_buf;2394size_t fixed_len;23952396for(i =0; i < preimage_limit; i++) {2397size_t prelen = preimage->line[i].len;2398size_t imglen = img->line[current_lno+i].len;23992400if(!fuzzy_matchlines(img->buf + current + imgoff, imglen,2401 preimage->buf + preoff, prelen))2402return0;2403if(preimage->line[i].flag & LINE_COMMON)2404 postlen += imglen - prelen;2405 imgoff += imglen;2406 preoff += prelen;2407}24082409/*2410 * Ok, the preimage matches with whitespace fuzz.2411 *2412 * imgoff now holds the true length of the target that2413 * matches the preimage before the end of the file.2414 *2415 * Count the number of characters in the preimage that fall2416 * beyond the end of the file and make sure that all of them2417 * are whitespace characters. (This can only happen if2418 * we are removing blank lines at the end of the file.)2419 */2420 buf = preimage_eof = preimage->buf + preoff;2421for( ; i < preimage->nr; i++)2422 preoff += preimage->line[i].len;2423 preimage_end = preimage->buf + preoff;2424for( ; buf < preimage_end; buf++)2425if(!isspace(*buf))2426return0;24272428/*2429 * Update the preimage and the common postimage context2430 * lines to use the same whitespace as the target.2431 * If whitespace is missing in the target (i.e.2432 * if the preimage extends beyond the end of the file),2433 * use the whitespace from the preimage.2434 */2435 extra_chars = preimage_end - preimage_eof;2436strbuf_init(&fixed, imgoff + extra_chars);2437strbuf_add(&fixed, img->buf + current, imgoff);2438strbuf_add(&fixed, preimage_eof, extra_chars);2439 fixed_buf =strbuf_detach(&fixed, &fixed_len);2440update_pre_post_images(preimage, postimage,2441 fixed_buf, fixed_len, postlen);2442return1;2443}24442445static intmatch_fragment(struct apply_state *state,2446struct image *img,2447struct image *preimage,2448struct image *postimage,2449unsigned long current,2450int current_lno,2451unsigned ws_rule,2452int match_beginning,int match_end)2453{2454int i;2455char*fixed_buf, *buf, *orig, *target;2456struct strbuf fixed;2457size_t fixed_len, postlen;2458int preimage_limit;24592460if(preimage->nr + current_lno <= img->nr) {2461/*2462 * The hunk falls within the boundaries of img.2463 */2464 preimage_limit = preimage->nr;2465if(match_end && (preimage->nr + current_lno != img->nr))2466return0;2467}else if(state->ws_error_action == correct_ws_error &&2468(ws_rule & WS_BLANK_AT_EOF)) {2469/*2470 * This hunk extends beyond the end of img, and we are2471 * removing blank lines at the end of the file. This2472 * many lines from the beginning of the preimage must2473 * match with img, and the remainder of the preimage2474 * must be blank.2475 */2476 preimage_limit = img->nr - current_lno;2477}else{2478/*2479 * The hunk extends beyond the end of the img and2480 * we are not removing blanks at the end, so we2481 * should reject the hunk at this position.2482 */2483return0;2484}24852486if(match_beginning && current_lno)2487return0;24882489/* Quick hash check */2490for(i =0; i < preimage_limit; i++)2491if((img->line[current_lno + i].flag & LINE_PATCHED) ||2492(preimage->line[i].hash != img->line[current_lno + i].hash))2493return0;24942495if(preimage_limit == preimage->nr) {2496/*2497 * Do we have an exact match? If we were told to match2498 * at the end, size must be exactly at current+fragsize,2499 * otherwise current+fragsize must be still within the preimage,2500 * and either case, the old piece should match the preimage2501 * exactly.2502 */2503if((match_end2504? (current + preimage->len == img->len)2505: (current + preimage->len <= img->len)) &&2506!memcmp(img->buf + current, preimage->buf, preimage->len))2507return1;2508}else{2509/*2510 * The preimage extends beyond the end of img, so2511 * there cannot be an exact match.2512 *2513 * There must be one non-blank context line that match2514 * a line before the end of img.2515 */2516char*buf_end;25172518 buf = preimage->buf;2519 buf_end = buf;2520for(i =0; i < preimage_limit; i++)2521 buf_end += preimage->line[i].len;25222523for( ; buf < buf_end; buf++)2524if(!isspace(*buf))2525break;2526if(buf == buf_end)2527return0;2528}25292530/*2531 * No exact match. If we are ignoring whitespace, run a line-by-line2532 * fuzzy matching. We collect all the line length information because2533 * we need it to adjust whitespace if we match.2534 */2535if(state->ws_ignore_action == ignore_ws_change)2536returnline_by_line_fuzzy_match(img, preimage, postimage,2537 current, current_lno, preimage_limit);25382539if(state->ws_error_action != correct_ws_error)2540return0;25412542/*2543 * The hunk does not apply byte-by-byte, but the hash says2544 * it might with whitespace fuzz. We weren't asked to2545 * ignore whitespace, we were asked to correct whitespace2546 * errors, so let's try matching after whitespace correction.2547 *2548 * While checking the preimage against the target, whitespace2549 * errors in both fixed, we count how large the corresponding2550 * postimage needs to be. The postimage prepared by2551 * apply_one_fragment() has whitespace errors fixed on added2552 * lines already, but the common lines were propagated as-is,2553 * which may become longer when their whitespace errors are2554 * fixed.2555 */25562557/* First count added lines in postimage */2558 postlen =0;2559for(i =0; i < postimage->nr; i++) {2560if(!(postimage->line[i].flag & LINE_COMMON))2561 postlen += postimage->line[i].len;2562}25632564/*2565 * The preimage may extend beyond the end of the file,2566 * but in this loop we will only handle the part of the2567 * preimage that falls within the file.2568 */2569strbuf_init(&fixed, preimage->len +1);2570 orig = preimage->buf;2571 target = img->buf + current;2572for(i =0; i < preimage_limit; i++) {2573size_t oldlen = preimage->line[i].len;2574size_t tgtlen = img->line[current_lno + i].len;2575size_t fixstart = fixed.len;2576struct strbuf tgtfix;2577int match;25782579/* Try fixing the line in the preimage */2580ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25812582/* Try fixing the line in the target */2583strbuf_init(&tgtfix, tgtlen);2584ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);25852586/*2587 * If they match, either the preimage was based on2588 * a version before our tree fixed whitespace breakage,2589 * or we are lacking a whitespace-fix patch the tree2590 * the preimage was based on already had (i.e. target2591 * has whitespace breakage, the preimage doesn't).2592 * In either case, we are fixing the whitespace breakages2593 * so we might as well take the fix together with their2594 * real change.2595 */2596 match = (tgtfix.len == fixed.len - fixstart &&2597!memcmp(tgtfix.buf, fixed.buf + fixstart,2598 fixed.len - fixstart));25992600/* Add the length if this is common with the postimage */2601if(preimage->line[i].flag & LINE_COMMON)2602 postlen += tgtfix.len;26032604strbuf_release(&tgtfix);2605if(!match)2606goto unmatch_exit;26072608 orig += oldlen;2609 target += tgtlen;2610}261126122613/*2614 * Now handle the lines in the preimage that falls beyond the2615 * end of the file (if any). They will only match if they are2616 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2617 * false).2618 */2619for( ; i < preimage->nr; i++) {2620size_t fixstart = fixed.len;/* start of the fixed preimage */2621size_t oldlen = preimage->line[i].len;2622int j;26232624/* Try fixing the line in the preimage */2625ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);26262627for(j = fixstart; j < fixed.len; j++)2628if(!isspace(fixed.buf[j]))2629goto unmatch_exit;26302631 orig += oldlen;2632}26332634/*2635 * Yes, the preimage is based on an older version that still2636 * has whitespace breakages unfixed, and fixing them makes the2637 * hunk match. Update the context lines in the postimage.2638 */2639 fixed_buf =strbuf_detach(&fixed, &fixed_len);2640if(postlen < postimage->len)2641 postlen =0;2642update_pre_post_images(preimage, postimage,2643 fixed_buf, fixed_len, postlen);2644return1;26452646 unmatch_exit:2647strbuf_release(&fixed);2648return0;2649}26502651static intfind_pos(struct apply_state *state,2652struct image *img,2653struct image *preimage,2654struct image *postimage,2655int line,2656unsigned ws_rule,2657int match_beginning,int match_end)2658{2659int i;2660unsigned long backwards, forwards, current;2661int backwards_lno, forwards_lno, current_lno;26622663/*2664 * If match_beginning or match_end is specified, there is no2665 * point starting from a wrong line that will never match and2666 * wander around and wait for a match at the specified end.2667 */2668if(match_beginning)2669 line =0;2670else if(match_end)2671 line = img->nr - preimage->nr;26722673/*2674 * Because the comparison is unsigned, the following test2675 * will also take care of a negative line number that can2676 * result when match_end and preimage is larger than the target.2677 */2678if((size_t) line > img->nr)2679 line = img->nr;26802681 current =0;2682for(i =0; i < line; i++)2683 current += img->line[i].len;26842685/*2686 * There's probably some smart way to do this, but I'll leave2687 * that to the smart and beautiful people. I'm simple and stupid.2688 */2689 backwards = current;2690 backwards_lno = line;2691 forwards = current;2692 forwards_lno = line;2693 current_lno = line;26942695for(i =0; ; i++) {2696if(match_fragment(state, img, preimage, postimage,2697 current, current_lno, ws_rule,2698 match_beginning, match_end))2699return current_lno;27002701 again:2702if(backwards_lno ==0&& forwards_lno == img->nr)2703break;27042705if(i &1) {2706if(backwards_lno ==0) {2707 i++;2708goto again;2709}2710 backwards_lno--;2711 backwards -= img->line[backwards_lno].len;2712 current = backwards;2713 current_lno = backwards_lno;2714}else{2715if(forwards_lno == img->nr) {2716 i++;2717goto again;2718}2719 forwards += img->line[forwards_lno].len;2720 forwards_lno++;2721 current = forwards;2722 current_lno = forwards_lno;2723}27242725}2726return-1;2727}27282729static voidremove_first_line(struct image *img)2730{2731 img->buf += img->line[0].len;2732 img->len -= img->line[0].len;2733 img->line++;2734 img->nr--;2735}27362737static voidremove_last_line(struct image *img)2738{2739 img->len -= img->line[--img->nr].len;2740}27412742/*2743 * The change from "preimage" and "postimage" has been found to2744 * apply at applied_pos (counts in line numbers) in "img".2745 * Update "img" to remove "preimage" and replace it with "postimage".2746 */2747static voidupdate_image(struct apply_state *state,2748struct image *img,2749int applied_pos,2750struct image *preimage,2751struct image *postimage)2752{2753/*2754 * remove the copy of preimage at offset in img2755 * and replace it with postimage2756 */2757int i, nr;2758size_t remove_count, insert_count, applied_at =0;2759char*result;2760int preimage_limit;27612762/*2763 * If we are removing blank lines at the end of img,2764 * the preimage may extend beyond the end.2765 * If that is the case, we must be careful only to2766 * remove the part of the preimage that falls within2767 * the boundaries of img. Initialize preimage_limit2768 * to the number of lines in the preimage that falls2769 * within the boundaries.2770 */2771 preimage_limit = preimage->nr;2772if(preimage_limit > img->nr - applied_pos)2773 preimage_limit = img->nr - applied_pos;27742775for(i =0; i < applied_pos; i++)2776 applied_at += img->line[i].len;27772778 remove_count =0;2779for(i =0; i < preimage_limit; i++)2780 remove_count += img->line[applied_pos + i].len;2781 insert_count = postimage->len;27822783/* Adjust the contents */2784 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2785memcpy(result, img->buf, applied_at);2786memcpy(result + applied_at, postimage->buf, postimage->len);2787memcpy(result + applied_at + postimage->len,2788 img->buf + (applied_at + remove_count),2789 img->len - (applied_at + remove_count));2790free(img->buf);2791 img->buf = result;2792 img->len += insert_count - remove_count;2793 result[img->len] ='\0';27942795/* Adjust the line table */2796 nr = img->nr + postimage->nr - preimage_limit;2797if(preimage_limit < postimage->nr) {2798/*2799 * NOTE: this knows that we never call remove_first_line()2800 * on anything other than pre/post image.2801 */2802REALLOC_ARRAY(img->line, nr);2803 img->line_allocated = img->line;2804}2805if(preimage_limit != postimage->nr)2806MOVE_ARRAY(img->line + applied_pos + postimage->nr,2807 img->line + applied_pos + preimage_limit,2808 img->nr - (applied_pos + preimage_limit));2809COPY_ARRAY(img->line + applied_pos, postimage->line, postimage->nr);2810if(!state->allow_overlap)2811for(i =0; i < postimage->nr; i++)2812 img->line[applied_pos + i].flag |= LINE_PATCHED;2813 img->nr = nr;2814}28152816/*2817 * Use the patch-hunk text in "frag" to prepare two images (preimage and2818 * postimage) for the hunk. Find lines that match "preimage" in "img" and2819 * replace the part of "img" with "postimage" text.2820 */2821static intapply_one_fragment(struct apply_state *state,2822struct image *img,struct fragment *frag,2823int inaccurate_eof,unsigned ws_rule,2824int nth_fragment)2825{2826int match_beginning, match_end;2827const char*patch = frag->patch;2828int size = frag->size;2829char*old, *oldlines;2830struct strbuf newlines;2831int new_blank_lines_at_end =0;2832int found_new_blank_lines_at_end =0;2833int hunk_linenr = frag->linenr;2834unsigned long leading, trailing;2835int pos, applied_pos;2836struct image preimage;2837struct image postimage;28382839memset(&preimage,0,sizeof(preimage));2840memset(&postimage,0,sizeof(postimage));2841 oldlines =xmalloc(size);2842strbuf_init(&newlines, size);28432844 old = oldlines;2845while(size >0) {2846char first;2847int len =linelen(patch, size);2848int plen;2849int added_blank_line =0;2850int is_blank_context =0;2851size_t start;28522853if(!len)2854break;28552856/*2857 * "plen" is how much of the line we should use for2858 * the actual patch data. Normally we just remove the2859 * first character on the line, but if the line is2860 * followed by "\ No newline", then we also remove the2861 * last one (which is the newline, of course).2862 */2863 plen = len -1;2864if(len < size && patch[len] =='\\')2865 plen--;2866 first = *patch;2867if(state->apply_in_reverse) {2868if(first =='-')2869 first ='+';2870else if(first =='+')2871 first ='-';2872}28732874switch(first) {2875case'\n':2876/* Newer GNU diff, empty context line */2877if(plen <0)2878/* ... followed by '\No newline'; nothing */2879break;2880*old++ ='\n';2881strbuf_addch(&newlines,'\n');2882add_line_info(&preimage,"\n",1, LINE_COMMON);2883add_line_info(&postimage,"\n",1, LINE_COMMON);2884 is_blank_context =1;2885break;2886case' ':2887if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2888ws_blank_line(patch +1, plen, ws_rule))2889 is_blank_context =1;2890/* fallthrough */2891case'-':2892memcpy(old, patch +1, plen);2893add_line_info(&preimage, old, plen,2894(first ==' '? LINE_COMMON :0));2895 old += plen;2896if(first =='-')2897break;2898/* fallthrough */2899case'+':2900/* --no-add does not add new lines */2901if(first =='+'&& state->no_add)2902break;29032904 start = newlines.len;2905if(first !='+'||2906!state->whitespace_error ||2907 state->ws_error_action != correct_ws_error) {2908strbuf_add(&newlines, patch +1, plen);2909}2910else{2911ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2912}2913add_line_info(&postimage, newlines.buf + start, newlines.len - start,2914(first =='+'?0: LINE_COMMON));2915if(first =='+'&&2916(ws_rule & WS_BLANK_AT_EOF) &&2917ws_blank_line(patch +1, plen, ws_rule))2918 added_blank_line =1;2919break;2920case'@':case'\\':2921/* Ignore it, we already handled it */2922break;2923default:2924if(state->apply_verbosity > verbosity_normal)2925error(_("invalid start of line: '%c'"), first);2926 applied_pos = -1;2927goto out;2928}2929if(added_blank_line) {2930if(!new_blank_lines_at_end)2931 found_new_blank_lines_at_end = hunk_linenr;2932 new_blank_lines_at_end++;2933}2934else if(is_blank_context)2935;2936else2937 new_blank_lines_at_end =0;2938 patch += len;2939 size -= len;2940 hunk_linenr++;2941}2942if(inaccurate_eof &&2943 old > oldlines && old[-1] =='\n'&&2944 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2945 old--;2946strbuf_setlen(&newlines, newlines.len -1);2947 preimage.line_allocated[preimage.nr -1].len--;2948 postimage.line_allocated[postimage.nr -1].len--;2949}29502951 leading = frag->leading;2952 trailing = frag->trailing;29532954/*2955 * A hunk to change lines at the beginning would begin with2956 * @@ -1,L +N,M @@2957 * but we need to be careful. -U0 that inserts before the second2958 * line also has this pattern.2959 *2960 * And a hunk to add to an empty file would begin with2961 * @@ -0,0 +N,M @@2962 *2963 * In other words, a hunk that is (frag->oldpos <= 1) with or2964 * without leading context must match at the beginning.2965 */2966 match_beginning = (!frag->oldpos ||2967(frag->oldpos ==1&& !state->unidiff_zero));29682969/*2970 * A hunk without trailing lines must match at the end.2971 * However, we simply cannot tell if a hunk must match end2972 * from the lack of trailing lines if the patch was generated2973 * with unidiff without any context.2974 */2975 match_end = !state->unidiff_zero && !trailing;29762977 pos = frag->newpos ? (frag->newpos -1) :0;2978 preimage.buf = oldlines;2979 preimage.len = old - oldlines;2980 postimage.buf = newlines.buf;2981 postimage.len = newlines.len;2982 preimage.line = preimage.line_allocated;2983 postimage.line = postimage.line_allocated;29842985for(;;) {29862987 applied_pos =find_pos(state, img, &preimage, &postimage, pos,2988 ws_rule, match_beginning, match_end);29892990if(applied_pos >=0)2991break;29922993/* Am I at my context limits? */2994if((leading <= state->p_context) && (trailing <= state->p_context))2995break;2996if(match_beginning || match_end) {2997 match_beginning = match_end =0;2998continue;2999}30003001/*3002 * Reduce the number of context lines; reduce both3003 * leading and trailing if they are equal otherwise3004 * just reduce the larger context.3005 */3006if(leading >= trailing) {3007remove_first_line(&preimage);3008remove_first_line(&postimage);3009 pos--;3010 leading--;3011}3012if(trailing > leading) {3013remove_last_line(&preimage);3014remove_last_line(&postimage);3015 trailing--;3016}3017}30183019if(applied_pos >=0) {3020if(new_blank_lines_at_end &&3021 preimage.nr + applied_pos >= img->nr &&3022(ws_rule & WS_BLANK_AT_EOF) &&3023 state->ws_error_action != nowarn_ws_error) {3024record_ws_error(state, WS_BLANK_AT_EOF,"+",1,3025 found_new_blank_lines_at_end);3026if(state->ws_error_action == correct_ws_error) {3027while(new_blank_lines_at_end--)3028remove_last_line(&postimage);3029}3030/*3031 * We would want to prevent write_out_results()3032 * from taking place in apply_patch() that follows3033 * the callchain led us here, which is:3034 * apply_patch->check_patch_list->check_patch->3035 * apply_data->apply_fragments->apply_one_fragment3036 */3037if(state->ws_error_action == die_on_ws_error)3038 state->apply =0;3039}30403041if(state->apply_verbosity > verbosity_normal && applied_pos != pos) {3042int offset = applied_pos - pos;3043if(state->apply_in_reverse)3044 offset =0- offset;3045fprintf_ln(stderr,3046Q_("Hunk #%dsucceeded at%d(offset%dline).",3047"Hunk #%dsucceeded at%d(offset%dlines).",3048 offset),3049 nth_fragment, applied_pos +1, offset);3050}30513052/*3053 * Warn if it was necessary to reduce the number3054 * of context lines.3055 */3056if((leading != frag->leading ||3057 trailing != frag->trailing) && state->apply_verbosity > verbosity_silent)3058fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"3059" to apply fragment at%d"),3060 leading, trailing, applied_pos+1);3061update_image(state, img, applied_pos, &preimage, &postimage);3062}else{3063if(state->apply_verbosity > verbosity_normal)3064error(_("while searching for:\n%.*s"),3065(int)(old - oldlines), oldlines);3066}30673068out:3069free(oldlines);3070strbuf_release(&newlines);3071free(preimage.line_allocated);3072free(postimage.line_allocated);30733074return(applied_pos <0);3075}30763077static intapply_binary_fragment(struct apply_state *state,3078struct image *img,3079struct patch *patch)3080{3081struct fragment *fragment = patch->fragments;3082unsigned long len;3083void*dst;30843085if(!fragment)3086returnerror(_("missing binary patch data for '%s'"),3087 patch->new_name ?3088 patch->new_name :3089 patch->old_name);30903091/* Binary patch is irreversible without the optional second hunk */3092if(state->apply_in_reverse) {3093if(!fragment->next)3094returnerror(_("cannot reverse-apply a binary patch "3095"without the reverse hunk to '%s'"),3096 patch->new_name3097? patch->new_name : patch->old_name);3098 fragment = fragment->next;3099}3100switch(fragment->binary_patch_method) {3101case BINARY_DELTA_DEFLATED:3102 dst =patch_delta(img->buf, img->len, fragment->patch,3103 fragment->size, &len);3104if(!dst)3105return-1;3106clear_image(img);3107 img->buf = dst;3108 img->len = len;3109return0;3110case BINARY_LITERAL_DEFLATED:3111clear_image(img);3112 img->len = fragment->size;3113 img->buf =xmemdupz(fragment->patch, img->len);3114return0;3115}3116return-1;3117}31183119/*3120 * Replace "img" with the result of applying the binary patch.3121 * The binary patch data itself in patch->fragment is still kept3122 * but the preimage prepared by the caller in "img" is freed here3123 * or in the helper function apply_binary_fragment() this calls.3124 */3125static intapply_binary(struct apply_state *state,3126struct image *img,3127struct patch *patch)3128{3129const char*name = patch->old_name ? patch->old_name : patch->new_name;3130struct object_id oid;3131const unsigned hexsz = the_hash_algo->hexsz;31323133/*3134 * For safety, we require patch index line to contain3135 * full hex textual object ID for old and new, at least for now.3136 */3137if(strlen(patch->old_oid_prefix) != hexsz ||3138strlen(patch->new_oid_prefix) != hexsz ||3139get_oid_hex(patch->old_oid_prefix, &oid) ||3140get_oid_hex(patch->new_oid_prefix, &oid))3141returnerror(_("cannot apply binary patch to '%s' "3142"without full index line"), name);31433144if(patch->old_name) {3145/*3146 * See if the old one matches what the patch3147 * applies to.3148 */3149hash_object_file(img->buf, img->len, blob_type, &oid);3150if(strcmp(oid_to_hex(&oid), patch->old_oid_prefix))3151returnerror(_("the patch applies to '%s' (%s), "3152"which does not match the "3153"current contents."),3154 name,oid_to_hex(&oid));3155}3156else{3157/* Otherwise, the old one must be empty. */3158if(img->len)3159returnerror(_("the patch applies to an empty "3160"'%s' but it is not empty"), name);3161}31623163get_oid_hex(patch->new_oid_prefix, &oid);3164if(is_null_oid(&oid)) {3165clear_image(img);3166return0;/* deletion patch */3167}31683169if(has_object_file(&oid)) {3170/* We already have the postimage */3171enum object_type type;3172unsigned long size;3173char*result;31743175 result =read_object_file(&oid, &type, &size);3176if(!result)3177returnerror(_("the necessary postimage%sfor "3178"'%s' cannot be read"),3179 patch->new_oid_prefix, name);3180clear_image(img);3181 img->buf = result;3182 img->len = size;3183}else{3184/*3185 * We have verified buf matches the preimage;3186 * apply the patch data to it, which is stored3187 * in the patch->fragments->{patch,size}.3188 */3189if(apply_binary_fragment(state, img, patch))3190returnerror(_("binary patch does not apply to '%s'"),3191 name);31923193/* verify that the result matches */3194hash_object_file(img->buf, img->len, blob_type, &oid);3195if(strcmp(oid_to_hex(&oid), patch->new_oid_prefix))3196returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3197 name, patch->new_oid_prefix,oid_to_hex(&oid));3198}31993200return0;3201}32023203static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3204{3205struct fragment *frag = patch->fragments;3206const char*name = patch->old_name ? patch->old_name : patch->new_name;3207unsigned ws_rule = patch->ws_rule;3208unsigned inaccurate_eof = patch->inaccurate_eof;3209int nth =0;32103211if(patch->is_binary)3212returnapply_binary(state, img, patch);32133214while(frag) {3215 nth++;3216if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3217error(_("patch failed:%s:%ld"), name, frag->oldpos);3218if(!state->apply_with_reject)3219return-1;3220 frag->rejected =1;3221}3222 frag = frag->next;3223}3224return0;3225}32263227static intread_blob_object(struct strbuf *buf,const struct object_id *oid,unsigned mode)3228{3229if(S_ISGITLINK(mode)) {3230strbuf_grow(buf,100);3231strbuf_addf(buf,"Subproject commit%s\n",oid_to_hex(oid));3232}else{3233enum object_type type;3234unsigned long sz;3235char*result;32363237 result =read_object_file(oid, &type, &sz);3238if(!result)3239return-1;3240/* XXX read_sha1_file NUL-terminates */3241strbuf_attach(buf, result, sz, sz +1);3242}3243return0;3244}32453246static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3247{3248if(!ce)3249return0;3250returnread_blob_object(buf, &ce->oid, ce->ce_mode);3251}32523253static struct patch *in_fn_table(struct apply_state *state,const char*name)3254{3255struct string_list_item *item;32563257if(name == NULL)3258return NULL;32593260 item =string_list_lookup(&state->fn_table, name);3261if(item != NULL)3262return(struct patch *)item->util;32633264return NULL;3265}32663267/*3268 * item->util in the filename table records the status of the path.3269 * Usually it points at a patch (whose result records the contents3270 * of it after applying it), but it could be PATH_WAS_DELETED for a3271 * path that a previously applied patch has already removed, or3272 * PATH_TO_BE_DELETED for a path that a later patch would remove.3273 *3274 * The latter is needed to deal with a case where two paths A and B3275 * are swapped by first renaming A to B and then renaming B to A;3276 * moving A to B should not be prevented due to presence of B as we3277 * will remove it in a later patch.3278 */3279#define PATH_TO_BE_DELETED ((struct patch *) -2)3280#define PATH_WAS_DELETED ((struct patch *) -1)32813282static intto_be_deleted(struct patch *patch)3283{3284return patch == PATH_TO_BE_DELETED;3285}32863287static intwas_deleted(struct patch *patch)3288{3289return patch == PATH_WAS_DELETED;3290}32913292static voidadd_to_fn_table(struct apply_state *state,struct patch *patch)3293{3294struct string_list_item *item;32953296/*3297 * Always add new_name unless patch is a deletion3298 * This should cover the cases for normal diffs,3299 * file creations and copies3300 */3301if(patch->new_name != NULL) {3302 item =string_list_insert(&state->fn_table, patch->new_name);3303 item->util = patch;3304}33053306/*3307 * store a failure on rename/deletion cases because3308 * later chunks shouldn't patch old names3309 */3310if((patch->new_name == NULL) || (patch->is_rename)) {3311 item =string_list_insert(&state->fn_table, patch->old_name);3312 item->util = PATH_WAS_DELETED;3313}3314}33153316static voidprepare_fn_table(struct apply_state *state,struct patch *patch)3317{3318/*3319 * store information about incoming file deletion3320 */3321while(patch) {3322if((patch->new_name == NULL) || (patch->is_rename)) {3323struct string_list_item *item;3324 item =string_list_insert(&state->fn_table, patch->old_name);3325 item->util = PATH_TO_BE_DELETED;3326}3327 patch = patch->next;3328}3329}33303331static intcheckout_target(struct index_state *istate,3332struct cache_entry *ce,struct stat *st)3333{3334struct checkout costate = CHECKOUT_INIT;33353336 costate.refresh_cache =1;3337 costate.istate = istate;3338if(checkout_entry(ce, &costate, NULL, NULL) ||3339lstat(ce->name, st))3340returnerror(_("cannot checkout%s"), ce->name);3341return0;3342}33433344static struct patch *previous_patch(struct apply_state *state,3345struct patch *patch,3346int*gone)3347{3348struct patch *previous;33493350*gone =0;3351if(patch->is_copy || patch->is_rename)3352return NULL;/* "git" patches do not depend on the order */33533354 previous =in_fn_table(state, patch->old_name);3355if(!previous)3356return NULL;33573358if(to_be_deleted(previous))3359return NULL;/* the deletion hasn't happened yet */33603361if(was_deleted(previous))3362*gone =1;33633364return previous;3365}33663367static intverify_index_match(struct apply_state *state,3368const struct cache_entry *ce,3369struct stat *st)3370{3371if(S_ISGITLINK(ce->ce_mode)) {3372if(!S_ISDIR(st->st_mode))3373return-1;3374return0;3375}3376returnie_match_stat(state->repo->index, ce, st,3377 CE_MATCH_IGNORE_VALID | CE_MATCH_IGNORE_SKIP_WORKTREE);3378}33793380#define SUBMODULE_PATCH_WITHOUT_INDEX 133813382static intload_patch_target(struct apply_state *state,3383struct strbuf *buf,3384const struct cache_entry *ce,3385struct stat *st,3386struct patch *patch,3387const char*name,3388unsigned expected_mode)3389{3390if(state->cached || state->check_index) {3391if(read_file_or_gitlink(ce, buf))3392returnerror(_("failed to read%s"), name);3393}else if(name) {3394if(S_ISGITLINK(expected_mode)) {3395if(ce)3396returnread_file_or_gitlink(ce, buf);3397else3398return SUBMODULE_PATCH_WITHOUT_INDEX;3399}else if(has_symlink_leading_path(name,strlen(name))) {3400returnerror(_("reading from '%s' beyond a symbolic link"), name);3401}else{3402if(read_old_data(st, patch, name, buf))3403returnerror(_("failed to read%s"), name);3404}3405}3406return0;3407}34083409/*3410 * We are about to apply "patch"; populate the "image" with the3411 * current version we have, from the working tree or from the index,3412 * depending on the situation e.g. --cached/--index. If we are3413 * applying a non-git patch that incrementally updates the tree,3414 * we read from the result of a previous diff.3415 */3416static intload_preimage(struct apply_state *state,3417struct image *image,3418struct patch *patch,struct stat *st,3419const struct cache_entry *ce)3420{3421struct strbuf buf = STRBUF_INIT;3422size_t len;3423char*img;3424struct patch *previous;3425int status;34263427 previous =previous_patch(state, patch, &status);3428if(status)3429returnerror(_("path%shas been renamed/deleted"),3430 patch->old_name);3431if(previous) {3432/* We have a patched copy in memory; use that. */3433strbuf_add(&buf, previous->result, previous->resultsize);3434}else{3435 status =load_patch_target(state, &buf, ce, st, patch,3436 patch->old_name, patch->old_mode);3437if(status <0)3438return status;3439else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3440/*3441 * There is no way to apply subproject3442 * patch without looking at the index.3443 * NEEDSWORK: shouldn't this be flagged3444 * as an error???3445 */3446free_fragment_list(patch->fragments);3447 patch->fragments = NULL;3448}else if(status) {3449returnerror(_("failed to read%s"), patch->old_name);3450}3451}34523453 img =strbuf_detach(&buf, &len);3454prepare_image(image, img, len, !patch->is_binary);3455return0;3456}34573458static intthree_way_merge(struct apply_state *state,3459struct image *image,3460char*path,3461const struct object_id *base,3462const struct object_id *ours,3463const struct object_id *theirs)3464{3465 mmfile_t base_file, our_file, their_file;3466 mmbuffer_t result = { NULL };3467int status;34683469read_mmblob(&base_file, base);3470read_mmblob(&our_file, ours);3471read_mmblob(&their_file, theirs);3472 status =ll_merge(&result, path,3473&base_file,"base",3474&our_file,"ours",3475&their_file,"theirs",3476 state->repo->index,3477 NULL);3478free(base_file.ptr);3479free(our_file.ptr);3480free(their_file.ptr);3481if(status <0|| !result.ptr) {3482free(result.ptr);3483return-1;3484}3485clear_image(image);3486 image->buf = result.ptr;3487 image->len = result.size;34883489return status;3490}34913492/*3493 * When directly falling back to add/add three-way merge, we read from3494 * the current contents of the new_name. In no cases other than that3495 * this function will be called.3496 */3497static intload_current(struct apply_state *state,3498struct image *image,3499struct patch *patch)3500{3501struct strbuf buf = STRBUF_INIT;3502int status, pos;3503size_t len;3504char*img;3505struct stat st;3506struct cache_entry *ce;3507char*name = patch->new_name;3508unsigned mode = patch->new_mode;35093510if(!patch->is_new)3511BUG("patch to%sis not a creation", patch->old_name);35123513 pos =index_name_pos(state->repo->index, name,strlen(name));3514if(pos <0)3515returnerror(_("%s: does not exist in index"), name);3516 ce = state->repo->index->cache[pos];3517if(lstat(name, &st)) {3518if(errno != ENOENT)3519returnerror_errno("%s", name);3520if(checkout_target(state->repo->index, ce, &st))3521return-1;3522}3523if(verify_index_match(state, ce, &st))3524returnerror(_("%s: does not match index"), name);35253526 status =load_patch_target(state, &buf, ce, &st, patch, name, mode);3527if(status <0)3528return status;3529else if(status)3530return-1;3531 img =strbuf_detach(&buf, &len);3532prepare_image(image, img, len, !patch->is_binary);3533return0;3534}35353536static inttry_threeway(struct apply_state *state,3537struct image *image,3538struct patch *patch,3539struct stat *st,3540const struct cache_entry *ce)3541{3542struct object_id pre_oid, post_oid, our_oid;3543struct strbuf buf = STRBUF_INIT;3544size_t len;3545int status;3546char*img;3547struct image tmp_image;35483549/* No point falling back to 3-way merge in these cases */3550if(patch->is_delete ||3551S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3552return-1;35533554/* Preimage the patch was prepared for */3555if(patch->is_new)3556write_object_file("",0, blob_type, &pre_oid);3557else if(get_oid(patch->old_oid_prefix, &pre_oid) ||3558read_blob_object(&buf, &pre_oid, patch->old_mode))3559returnerror(_("repository lacks the necessary blob to fall back on 3-way merge."));35603561if(state->apply_verbosity > verbosity_silent)3562fprintf(stderr,_("Falling back to three-way merge...\n"));35633564 img =strbuf_detach(&buf, &len);3565prepare_image(&tmp_image, img, len,1);3566/* Apply the patch to get the post image */3567if(apply_fragments(state, &tmp_image, patch) <0) {3568clear_image(&tmp_image);3569return-1;3570}3571/* post_oid is theirs */3572write_object_file(tmp_image.buf, tmp_image.len, blob_type, &post_oid);3573clear_image(&tmp_image);35743575/* our_oid is ours */3576if(patch->is_new) {3577if(load_current(state, &tmp_image, patch))3578returnerror(_("cannot read the current contents of '%s'"),3579 patch->new_name);3580}else{3581if(load_preimage(state, &tmp_image, patch, st, ce))3582returnerror(_("cannot read the current contents of '%s'"),3583 patch->old_name);3584}3585write_object_file(tmp_image.buf, tmp_image.len, blob_type, &our_oid);3586clear_image(&tmp_image);35873588/* in-core three-way merge between post and our using pre as base */3589 status =three_way_merge(state, image, patch->new_name,3590&pre_oid, &our_oid, &post_oid);3591if(status <0) {3592if(state->apply_verbosity > verbosity_silent)3593fprintf(stderr,3594_("Failed to fall back on three-way merge...\n"));3595return status;3596}35973598if(status) {3599 patch->conflicted_threeway =1;3600if(patch->is_new)3601oidclr(&patch->threeway_stage[0]);3602else3603oidcpy(&patch->threeway_stage[0], &pre_oid);3604oidcpy(&patch->threeway_stage[1], &our_oid);3605oidcpy(&patch->threeway_stage[2], &post_oid);3606if(state->apply_verbosity > verbosity_silent)3607fprintf(stderr,3608_("Applied patch to '%s' with conflicts.\n"),3609 patch->new_name);3610}else{3611if(state->apply_verbosity > verbosity_silent)3612fprintf(stderr,3613_("Applied patch to '%s' cleanly.\n"),3614 patch->new_name);3615}3616return0;3617}36183619static intapply_data(struct apply_state *state,struct patch *patch,3620struct stat *st,const struct cache_entry *ce)3621{3622struct image image;36233624if(load_preimage(state, &image, patch, st, ce) <0)3625return-1;36263627if(patch->direct_to_threeway ||3628apply_fragments(state, &image, patch) <0) {3629/* Note: with --reject, apply_fragments() returns 0 */3630if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3631return-1;3632}3633 patch->result = image.buf;3634 patch->resultsize = image.len;3635add_to_fn_table(state, patch);3636free(image.line_allocated);36373638if(0< patch->is_delete && patch->resultsize)3639returnerror(_("removal patch leaves file contents"));36403641return0;3642}36433644/*3645 * If "patch" that we are looking at modifies or deletes what we have,3646 * we would want it not to lose any local modification we have, either3647 * in the working tree or in the index.3648 *3649 * This also decides if a non-git patch is a creation patch or a3650 * modification to an existing empty file. We do not check the state3651 * of the current tree for a creation patch in this function; the caller3652 * check_patch() separately makes sure (and errors out otherwise) that3653 * the path the patch creates does not exist in the current tree.3654 */3655static intcheck_preimage(struct apply_state *state,3656struct patch *patch,3657struct cache_entry **ce,3658struct stat *st)3659{3660const char*old_name = patch->old_name;3661struct patch *previous = NULL;3662int stat_ret =0, status;3663unsigned st_mode =0;36643665if(!old_name)3666return0;36673668assert(patch->is_new <=0);3669 previous =previous_patch(state, patch, &status);36703671if(status)3672returnerror(_("path%shas been renamed/deleted"), old_name);3673if(previous) {3674 st_mode = previous->new_mode;3675}else if(!state->cached) {3676 stat_ret =lstat(old_name, st);3677if(stat_ret && errno != ENOENT)3678returnerror_errno("%s", old_name);3679}36803681if(state->check_index && !previous) {3682int pos =index_name_pos(state->repo->index, old_name,3683strlen(old_name));3684if(pos <0) {3685if(patch->is_new <0)3686goto is_new;3687returnerror(_("%s: does not exist in index"), old_name);3688}3689*ce = state->repo->index->cache[pos];3690if(stat_ret <0) {3691if(checkout_target(state->repo->index, *ce, st))3692return-1;3693}3694if(!state->cached &&verify_index_match(state, *ce, st))3695returnerror(_("%s: does not match index"), old_name);3696if(state->cached)3697 st_mode = (*ce)->ce_mode;3698}else if(stat_ret <0) {3699if(patch->is_new <0)3700goto is_new;3701returnerror_errno("%s", old_name);3702}37033704if(!state->cached && !previous)3705 st_mode =ce_mode_from_stat(*ce, st->st_mode);37063707if(patch->is_new <0)3708 patch->is_new =0;3709if(!patch->old_mode)3710 patch->old_mode = st_mode;3711if((st_mode ^ patch->old_mode) & S_IFMT)3712returnerror(_("%s: wrong type"), old_name);3713if(st_mode != patch->old_mode)3714warning(_("%shas type%o, expected%o"),3715 old_name, st_mode, patch->old_mode);3716if(!patch->new_mode && !patch->is_delete)3717 patch->new_mode = st_mode;3718return0;37193720 is_new:3721 patch->is_new =1;3722 patch->is_delete =0;3723FREE_AND_NULL(patch->old_name);3724return0;3725}372637273728#define EXISTS_IN_INDEX 13729#define EXISTS_IN_WORKTREE 237303731static intcheck_to_create(struct apply_state *state,3732const char*new_name,3733int ok_if_exists)3734{3735struct stat nst;37363737if(state->check_index &&3738index_name_pos(state->repo->index, new_name,strlen(new_name)) >=0&&3739!ok_if_exists)3740return EXISTS_IN_INDEX;3741if(state->cached)3742return0;37433744if(!lstat(new_name, &nst)) {3745if(S_ISDIR(nst.st_mode) || ok_if_exists)3746return0;3747/*3748 * A leading component of new_name might be a symlink3749 * that is going to be removed with this patch, but3750 * still pointing at somewhere that has the path.3751 * In such a case, path "new_name" does not exist as3752 * far as git is concerned.3753 */3754if(has_symlink_leading_path(new_name,strlen(new_name)))3755return0;37563757return EXISTS_IN_WORKTREE;3758}else if(!is_missing_file_error(errno)) {3759returnerror_errno("%s", new_name);3760}3761return0;3762}37633764static uintptr_tregister_symlink_changes(struct apply_state *state,3765const char*path,3766uintptr_t what)3767{3768struct string_list_item *ent;37693770 ent =string_list_lookup(&state->symlink_changes, path);3771if(!ent) {3772 ent =string_list_insert(&state->symlink_changes, path);3773 ent->util = (void*)0;3774}3775 ent->util = (void*)(what | ((uintptr_t)ent->util));3776return(uintptr_t)ent->util;3777}37783779static uintptr_tcheck_symlink_changes(struct apply_state *state,const char*path)3780{3781struct string_list_item *ent;37823783 ent =string_list_lookup(&state->symlink_changes, path);3784if(!ent)3785return0;3786return(uintptr_t)ent->util;3787}37883789static voidprepare_symlink_changes(struct apply_state *state,struct patch *patch)3790{3791for( ; patch; patch = patch->next) {3792if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3793(patch->is_rename || patch->is_delete))3794/* the symlink at patch->old_name is removed */3795register_symlink_changes(state, patch->old_name, APPLY_SYMLINK_GOES_AWAY);37963797if(patch->new_name &&S_ISLNK(patch->new_mode))3798/* the symlink at patch->new_name is created or remains */3799register_symlink_changes(state, patch->new_name, APPLY_SYMLINK_IN_RESULT);3800}3801}38023803static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3804{3805do{3806unsigned int change;38073808while(--name->len && name->buf[name->len] !='/')3809;/* scan backwards */3810if(!name->len)3811break;3812 name->buf[name->len] ='\0';3813 change =check_symlink_changes(state, name->buf);3814if(change & APPLY_SYMLINK_IN_RESULT)3815return1;3816if(change & APPLY_SYMLINK_GOES_AWAY)3817/*3818 * This cannot be "return 0", because we may3819 * see a new one created at a higher level.3820 */3821continue;38223823/* otherwise, check the preimage */3824if(state->check_index) {3825struct cache_entry *ce;38263827 ce =index_file_exists(state->repo->index, name->buf,3828 name->len, ignore_case);3829if(ce &&S_ISLNK(ce->ce_mode))3830return1;3831}else{3832struct stat st;3833if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3834return1;3835}3836}while(1);3837return0;3838}38393840static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3841{3842int ret;3843struct strbuf name = STRBUF_INIT;38443845assert(*name_ !='\0');3846strbuf_addstr(&name, name_);3847 ret =path_is_beyond_symlink_1(state, &name);3848strbuf_release(&name);38493850return ret;3851}38523853static intcheck_unsafe_path(struct patch *patch)3854{3855const char*old_name = NULL;3856const char*new_name = NULL;3857if(patch->is_delete)3858 old_name = patch->old_name;3859else if(!patch->is_new && !patch->is_copy)3860 old_name = patch->old_name;3861if(!patch->is_delete)3862 new_name = patch->new_name;38633864if(old_name && !verify_path(old_name, patch->old_mode))3865returnerror(_("invalid path '%s'"), old_name);3866if(new_name && !verify_path(new_name, patch->new_mode))3867returnerror(_("invalid path '%s'"), new_name);3868return0;3869}38703871/*3872 * Check and apply the patch in-core; leave the result in patch->result3873 * for the caller to write it out to the final destination.3874 */3875static intcheck_patch(struct apply_state *state,struct patch *patch)3876{3877struct stat st;3878const char*old_name = patch->old_name;3879const char*new_name = patch->new_name;3880const char*name = old_name ? old_name : new_name;3881struct cache_entry *ce = NULL;3882struct patch *tpatch;3883int ok_if_exists;3884int status;38853886 patch->rejected =1;/* we will drop this after we succeed */38873888 status =check_preimage(state, patch, &ce, &st);3889if(status)3890return status;3891 old_name = patch->old_name;38923893/*3894 * A type-change diff is always split into a patch to delete3895 * old, immediately followed by a patch to create new (see3896 * diff.c::run_diff()); in such a case it is Ok that the entry3897 * to be deleted by the previous patch is still in the working3898 * tree and in the index.3899 *3900 * A patch to swap-rename between A and B would first rename A3901 * to B and then rename B to A. While applying the first one,3902 * the presence of B should not stop A from getting renamed to3903 * B; ask to_be_deleted() about the later rename. Removal of3904 * B and rename from A to B is handled the same way by asking3905 * was_deleted().3906 */3907if((tpatch =in_fn_table(state, new_name)) &&3908(was_deleted(tpatch) ||to_be_deleted(tpatch)))3909 ok_if_exists =1;3910else3911 ok_if_exists =0;39123913if(new_name &&3914((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3915int err =check_to_create(state, new_name, ok_if_exists);39163917if(err && state->threeway) {3918 patch->direct_to_threeway =1;3919}else switch(err) {3920case0:3921break;/* happy */3922case EXISTS_IN_INDEX:3923returnerror(_("%s: already exists in index"), new_name);3924break;3925case EXISTS_IN_WORKTREE:3926returnerror(_("%s: already exists in working directory"),3927 new_name);3928default:3929return err;3930}39313932if(!patch->new_mode) {3933if(0< patch->is_new)3934 patch->new_mode = S_IFREG |0644;3935else3936 patch->new_mode = patch->old_mode;3937}3938}39393940if(new_name && old_name) {3941int same = !strcmp(old_name, new_name);3942if(!patch->new_mode)3943 patch->new_mode = patch->old_mode;3944if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3945if(same)3946returnerror(_("new mode (%o) of%sdoes not "3947"match old mode (%o)"),3948 patch->new_mode, new_name,3949 patch->old_mode);3950else3951returnerror(_("new mode (%o) of%sdoes not "3952"match old mode (%o) of%s"),3953 patch->new_mode, new_name,3954 patch->old_mode, old_name);3955}3956}39573958if(!state->unsafe_paths &&check_unsafe_path(patch))3959return-128;39603961/*3962 * An attempt to read from or delete a path that is beyond a3963 * symbolic link will be prevented by load_patch_target() that3964 * is called at the beginning of apply_data() so we do not3965 * have to worry about a patch marked with "is_delete" bit3966 * here. We however need to make sure that the patch result3967 * is not deposited to a path that is beyond a symbolic link3968 * here.3969 */3970if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3971returnerror(_("affected file '%s' is beyond a symbolic link"),3972 patch->new_name);39733974if(apply_data(state, patch, &st, ce) <0)3975returnerror(_("%s: patch does not apply"), name);3976 patch->rejected =0;3977return0;3978}39793980static intcheck_patch_list(struct apply_state *state,struct patch *patch)3981{3982int err =0;39833984prepare_symlink_changes(state, patch);3985prepare_fn_table(state, patch);3986while(patch) {3987int res;3988if(state->apply_verbosity > verbosity_normal)3989say_patch_name(stderr,3990_("Checking patch%s..."), patch);3991 res =check_patch(state, patch);3992if(res == -128)3993return-128;3994 err |= res;3995 patch = patch->next;3996}3997return err;3998}39994000static intread_apply_cache(struct apply_state *state)4001{4002if(state->index_file)4003returnread_index_from(state->repo->index, state->index_file,4004get_git_dir());4005else4006returnrepo_read_index(state->repo);4007}40084009/* This function tries to read the object name from the current index */4010static intget_current_oid(struct apply_state *state,const char*path,4011struct object_id *oid)4012{4013int pos;40144015if(read_apply_cache(state) <0)4016return-1;4017 pos =index_name_pos(state->repo->index, path,strlen(path));4018if(pos <0)4019return-1;4020oidcpy(oid, &state->repo->index->cache[pos]->oid);4021return0;4022}40234024static intpreimage_oid_in_gitlink_patch(struct patch *p,struct object_id *oid)4025{4026/*4027 * A usable gitlink patch has only one fragment (hunk) that looks like:4028 * @@ -1 +1 @@4029 * -Subproject commit <old sha1>4030 * +Subproject commit <new sha1>4031 * or4032 * @@ -1 +0,0 @@4033 * -Subproject commit <old sha1>4034 * for a removal patch.4035 */4036struct fragment *hunk = p->fragments;4037static const char heading[] ="-Subproject commit ";4038char*preimage;40394040if(/* does the patch have only one hunk? */4041 hunk && !hunk->next &&4042/* is its preimage one line? */4043 hunk->oldpos ==1&& hunk->oldlines ==1&&4044/* does preimage begin with the heading? */4045(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&4046starts_with(++preimage, heading) &&4047/* does it record full SHA-1? */4048!get_oid_hex(preimage +sizeof(heading) -1, oid) &&4049 preimage[sizeof(heading) + the_hash_algo->hexsz -1] =='\n'&&4050/* does the abbreviated name on the index line agree with it? */4051starts_with(preimage +sizeof(heading) -1, p->old_oid_prefix))4052return0;/* it all looks fine */40534054/* we may have full object name on the index line */4055returnget_oid_hex(p->old_oid_prefix, oid);4056}40574058/* Build an index that contains just the files needed for a 3way merge */4059static intbuild_fake_ancestor(struct apply_state *state,struct patch *list)4060{4061struct patch *patch;4062struct index_state result = { NULL };4063struct lock_file lock = LOCK_INIT;4064int res;40654066/* Once we start supporting the reverse patch, it may be4067 * worth showing the new sha1 prefix, but until then...4068 */4069for(patch = list; patch; patch = patch->next) {4070struct object_id oid;4071struct cache_entry *ce;4072const char*name;40734074 name = patch->old_name ? patch->old_name : patch->new_name;4075if(0< patch->is_new)4076continue;40774078if(S_ISGITLINK(patch->old_mode)) {4079if(!preimage_oid_in_gitlink_patch(patch, &oid))4080;/* ok, the textual part looks sane */4081else4082returnerror(_("sha1 information is lacking or "4083"useless for submodule%s"), name);4084}else if(!get_oid_blob(patch->old_oid_prefix, &oid)) {4085;/* ok */4086}else if(!patch->lines_added && !patch->lines_deleted) {4087/* mode-only change: update the current */4088if(get_current_oid(state, patch->old_name, &oid))4089returnerror(_("mode change for%s, which is not "4090"in current HEAD"), name);4091}else4092returnerror(_("sha1 information is lacking or useless "4093"(%s)."), name);40944095 ce =make_cache_entry(&result, patch->old_mode, &oid, name,0,0);4096if(!ce)4097returnerror(_("make_cache_entry failed for path '%s'"),4098 name);4099if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) {4100discard_cache_entry(ce);4101returnerror(_("could not add%sto temporary index"),4102 name);4103}4104}41054106hold_lock_file_for_update(&lock, state->fake_ancestor, LOCK_DIE_ON_ERROR);4107 res =write_locked_index(&result, &lock, COMMIT_LOCK);4108discard_index(&result);41094110if(res)4111returnerror(_("could not write temporary index to%s"),4112 state->fake_ancestor);41134114return0;4115}41164117static voidstat_patch_list(struct apply_state *state,struct patch *patch)4118{4119int files, adds, dels;41204121for(files = adds = dels =0; patch ; patch = patch->next) {4122 files++;4123 adds += patch->lines_added;4124 dels += patch->lines_deleted;4125show_stats(state, patch);4126}41274128print_stat_summary(stdout, files, adds, dels);4129}41304131static voidnumstat_patch_list(struct apply_state *state,4132struct patch *patch)4133{4134for( ; patch; patch = patch->next) {4135const char*name;4136 name = patch->new_name ? patch->new_name : patch->old_name;4137if(patch->is_binary)4138printf("-\t-\t");4139else4140printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4141write_name_quoted(name, stdout, state->line_termination);4142}4143}41444145static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4146{4147if(mode)4148printf("%smode%06o%s\n", newdelete, mode, name);4149else4150printf("%s %s\n", newdelete, name);4151}41524153static voidshow_mode_change(struct patch *p,int show_name)4154{4155if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4156if(show_name)4157printf(" mode change%06o =>%06o%s\n",4158 p->old_mode, p->new_mode, p->new_name);4159else4160printf(" mode change%06o =>%06o\n",4161 p->old_mode, p->new_mode);4162}4163}41644165static voidshow_rename_copy(struct patch *p)4166{4167const char*renamecopy = p->is_rename ?"rename":"copy";4168const char*old_name, *new_name;41694170/* Find common prefix */4171 old_name = p->old_name;4172 new_name = p->new_name;4173while(1) {4174const char*slash_old, *slash_new;4175 slash_old =strchr(old_name,'/');4176 slash_new =strchr(new_name,'/');4177if(!slash_old ||4178!slash_new ||4179 slash_old - old_name != slash_new - new_name ||4180memcmp(old_name, new_name, slash_new - new_name))4181break;4182 old_name = slash_old +1;4183 new_name = slash_new +1;4184}4185/* p->old_name thru old_name is the common prefix, and old_name and new_name4186 * through the end of names are renames4187 */4188if(old_name != p->old_name)4189printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4190(int)(old_name - p->old_name), p->old_name,4191 old_name, new_name, p->score);4192else4193printf("%s %s=>%s(%d%%)\n", renamecopy,4194 p->old_name, p->new_name, p->score);4195show_mode_change(p,0);4196}41974198static voidsummary_patch_list(struct patch *patch)4199{4200struct patch *p;42014202for(p = patch; p; p = p->next) {4203if(p->is_new)4204show_file_mode_name("create", p->new_mode, p->new_name);4205else if(p->is_delete)4206show_file_mode_name("delete", p->old_mode, p->old_name);4207else{4208if(p->is_rename || p->is_copy)4209show_rename_copy(p);4210else{4211if(p->score) {4212printf(" rewrite%s(%d%%)\n",4213 p->new_name, p->score);4214show_mode_change(p,0);4215}4216else4217show_mode_change(p,1);4218}4219}4220}4221}42224223static voidpatch_stats(struct apply_state *state,struct patch *patch)4224{4225int lines = patch->lines_added + patch->lines_deleted;42264227if(lines > state->max_change)4228 state->max_change = lines;4229if(patch->old_name) {4230int len =quote_c_style(patch->old_name, NULL, NULL,0);4231if(!len)4232 len =strlen(patch->old_name);4233if(len > state->max_len)4234 state->max_len = len;4235}4236if(patch->new_name) {4237int len =quote_c_style(patch->new_name, NULL, NULL,0);4238if(!len)4239 len =strlen(patch->new_name);4240if(len > state->max_len)4241 state->max_len = len;4242}4243}42444245static intremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4246{4247if(state->update_index && !state->ita_only) {4248if(remove_file_from_index(state->repo->index, patch->old_name) <0)4249returnerror(_("unable to remove%sfrom index"), patch->old_name);4250}4251if(!state->cached) {4252if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4253remove_path(patch->old_name);4254}4255}4256return0;4257}42584259static intadd_index_file(struct apply_state *state,4260const char*path,4261unsigned mode,4262void*buf,4263unsigned long size)4264{4265struct stat st;4266struct cache_entry *ce;4267int namelen =strlen(path);42684269 ce =make_empty_cache_entry(state->repo->index, namelen);4270memcpy(ce->name, path, namelen);4271 ce->ce_mode =create_ce_mode(mode);4272 ce->ce_flags =create_ce_flags(0);4273 ce->ce_namelen = namelen;4274if(state->ita_only) {4275 ce->ce_flags |= CE_INTENT_TO_ADD;4276set_object_name_for_intent_to_add_entry(ce);4277}else if(S_ISGITLINK(mode)) {4278const char*s;42794280if(!skip_prefix(buf,"Subproject commit ", &s) ||4281get_oid_hex(s, &ce->oid)) {4282discard_cache_entry(ce);4283returnerror(_("corrupt patch for submodule%s"), path);4284}4285}else{4286if(!state->cached) {4287if(lstat(path, &st) <0) {4288discard_cache_entry(ce);4289returnerror_errno(_("unable to stat newly "4290"created file '%s'"),4291 path);4292}4293fill_stat_cache_info(state->repo->index, ce, &st);4294}4295if(write_object_file(buf, size, blob_type, &ce->oid) <0) {4296discard_cache_entry(ce);4297returnerror(_("unable to create backing store "4298"for newly created file%s"), path);4299}4300}4301if(add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) <0) {4302discard_cache_entry(ce);4303returnerror(_("unable to add cache entry for%s"), path);4304}43054306return0;4307}43084309/*4310 * Returns:4311 * -1 if an unrecoverable error happened4312 * 0 if everything went well4313 * 1 if a recoverable error happened4314 */4315static inttry_create_file(struct apply_state *state,const char*path,4316unsigned int mode,const char*buf,4317unsigned long size)4318{4319int fd, res;4320struct strbuf nbuf = STRBUF_INIT;43214322if(S_ISGITLINK(mode)) {4323struct stat st;4324if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4325return0;4326return!!mkdir(path,0777);4327}43284329if(has_symlinks &&S_ISLNK(mode))4330/* Although buf:size is counted string, it also is NUL4331 * terminated.4332 */4333return!!symlink(buf, path);43344335 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4336if(fd <0)4337return1;43384339if(convert_to_working_tree(state->repo->index, path, buf, size, &nbuf)) {4340 size = nbuf.len;4341 buf = nbuf.buf;4342}43434344 res =write_in_full(fd, buf, size) <0;4345if(res)4346error_errno(_("failed to write to '%s'"), path);4347strbuf_release(&nbuf);43484349if(close(fd) <0&& !res)4350returnerror_errno(_("closing file '%s'"), path);43514352return res ? -1:0;4353}43544355/*4356 * We optimistically assume that the directories exist,4357 * which is true 99% of the time anyway. If they don't,4358 * we create them and try again.4359 *4360 * Returns:4361 * -1 on error4362 * 0 otherwise4363 */4364static intcreate_one_file(struct apply_state *state,4365char*path,4366unsigned mode,4367const char*buf,4368unsigned long size)4369{4370int res;43714372if(state->cached)4373return0;43744375 res =try_create_file(state, path, mode, buf, size);4376if(res <0)4377return-1;4378if(!res)4379return0;43804381if(errno == ENOENT) {4382if(safe_create_leading_directories(path))4383return0;4384 res =try_create_file(state, path, mode, buf, size);4385if(res <0)4386return-1;4387if(!res)4388return0;4389}43904391if(errno == EEXIST || errno == EACCES) {4392/* We may be trying to create a file where a directory4393 * used to be.4394 */4395struct stat st;4396if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4397 errno = EEXIST;4398}43994400if(errno == EEXIST) {4401unsigned int nr =getpid();44024403for(;;) {4404char newpath[PATH_MAX];4405mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4406 res =try_create_file(state, newpath, mode, buf, size);4407if(res <0)4408return-1;4409if(!res) {4410if(!rename(newpath, path))4411return0;4412unlink_or_warn(newpath);4413break;4414}4415if(errno != EEXIST)4416break;4417++nr;4418}4419}4420returnerror_errno(_("unable to write file '%s' mode%o"),4421 path, mode);4422}44234424static intadd_conflicted_stages_file(struct apply_state *state,4425struct patch *patch)4426{4427int stage, namelen;4428unsigned mode;4429struct cache_entry *ce;44304431if(!state->update_index)4432return0;4433 namelen =strlen(patch->new_name);4434 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);44354436remove_file_from_index(state->repo->index, patch->new_name);4437for(stage =1; stage <4; stage++) {4438if(is_null_oid(&patch->threeway_stage[stage -1]))4439continue;4440 ce =make_empty_cache_entry(state->repo->index, namelen);4441memcpy(ce->name, patch->new_name, namelen);4442 ce->ce_mode =create_ce_mode(mode);4443 ce->ce_flags =create_ce_flags(stage);4444 ce->ce_namelen = namelen;4445oidcpy(&ce->oid, &patch->threeway_stage[stage -1]);4446if(add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) <0) {4447discard_cache_entry(ce);4448returnerror(_("unable to add cache entry for%s"),4449 patch->new_name);4450}4451}44524453return0;4454}44554456static intcreate_file(struct apply_state *state,struct patch *patch)4457{4458char*path = patch->new_name;4459unsigned mode = patch->new_mode;4460unsigned long size = patch->resultsize;4461char*buf = patch->result;44624463if(!mode)4464 mode = S_IFREG |0644;4465if(create_one_file(state, path, mode, buf, size))4466return-1;44674468if(patch->conflicted_threeway)4469returnadd_conflicted_stages_file(state, patch);4470else if(state->update_index)4471returnadd_index_file(state, path, mode, buf, size);4472return0;4473}44744475/* phase zero is to remove, phase one is to create */4476static intwrite_out_one_result(struct apply_state *state,4477struct patch *patch,4478int phase)4479{4480if(patch->is_delete >0) {4481if(phase ==0)4482returnremove_file(state, patch,1);4483return0;4484}4485if(patch->is_new >0|| patch->is_copy) {4486if(phase ==1)4487returncreate_file(state, patch);4488return0;4489}4490/*4491 * Rename or modification boils down to the same4492 * thing: remove the old, write the new4493 */4494if(phase ==0)4495returnremove_file(state, patch, patch->is_rename);4496if(phase ==1)4497returncreate_file(state, patch);4498return0;4499}45004501static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4502{4503FILE*rej;4504char namebuf[PATH_MAX];4505struct fragment *frag;4506int cnt =0;4507struct strbuf sb = STRBUF_INIT;45084509for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4510if(!frag->rejected)4511continue;4512 cnt++;4513}45144515if(!cnt) {4516if(state->apply_verbosity > verbosity_normal)4517say_patch_name(stderr,4518_("Applied patch%scleanly."), patch);4519return0;4520}45214522/* This should not happen, because a removal patch that leaves4523 * contents are marked "rejected" at the patch level.4524 */4525if(!patch->new_name)4526die(_("internal error"));45274528/* Say this even without --verbose */4529strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4530"Applying patch %%swith%drejects...",4531 cnt),4532 cnt);4533if(state->apply_verbosity > verbosity_silent)4534say_patch_name(stderr, sb.buf, patch);4535strbuf_release(&sb);45364537 cnt =strlen(patch->new_name);4538if(ARRAY_SIZE(namebuf) <= cnt +5) {4539 cnt =ARRAY_SIZE(namebuf) -5;4540warning(_("truncating .rej filename to %.*s.rej"),4541 cnt -1, patch->new_name);4542}4543memcpy(namebuf, patch->new_name, cnt);4544memcpy(namebuf + cnt,".rej",5);45454546 rej =fopen(namebuf,"w");4547if(!rej)4548returnerror_errno(_("cannot open%s"), namebuf);45494550/* Normal git tools never deal with .rej, so do not pretend4551 * this is a git patch by saying --git or giving extended4552 * headers. While at it, maybe please "kompare" that wants4553 * the trailing TAB and some garbage at the end of line ;-).4554 */4555fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4556 patch->new_name, patch->new_name);4557for(cnt =1, frag = patch->fragments;4558 frag;4559 cnt++, frag = frag->next) {4560if(!frag->rejected) {4561if(state->apply_verbosity > verbosity_silent)4562fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4563continue;4564}4565if(state->apply_verbosity > verbosity_silent)4566fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4567fprintf(rej,"%.*s", frag->size, frag->patch);4568if(frag->patch[frag->size-1] !='\n')4569fputc('\n', rej);4570}4571fclose(rej);4572return-1;4573}45744575/*4576 * Returns:4577 * -1 if an error happened4578 * 0 if the patch applied cleanly4579 * 1 if the patch did not apply cleanly4580 */4581static intwrite_out_results(struct apply_state *state,struct patch *list)4582{4583int phase;4584int errs =0;4585struct patch *l;4586struct string_list cpath = STRING_LIST_INIT_DUP;45874588for(phase =0; phase <2; phase++) {4589 l = list;4590while(l) {4591if(l->rejected)4592 errs =1;4593else{4594if(write_out_one_result(state, l, phase)) {4595string_list_clear(&cpath,0);4596return-1;4597}4598if(phase ==1) {4599if(write_out_one_reject(state, l))4600 errs =1;4601if(l->conflicted_threeway) {4602string_list_append(&cpath, l->new_name);4603 errs =1;4604}4605}4606}4607 l = l->next;4608}4609}46104611if(cpath.nr) {4612struct string_list_item *item;46134614string_list_sort(&cpath);4615if(state->apply_verbosity > verbosity_silent) {4616for_each_string_list_item(item, &cpath)4617fprintf(stderr,"U%s\n", item->string);4618}4619string_list_clear(&cpath,0);46204621repo_rerere(state->repo,0);4622}46234624return errs;4625}46264627/*4628 * Try to apply a patch.4629 *4630 * Returns:4631 * -128 if a bad error happened (like patch unreadable)4632 * -1 if patch did not apply and user cannot deal with it4633 * 0 if the patch applied4634 * 1 if the patch did not apply but user might fix it4635 */4636static intapply_patch(struct apply_state *state,4637int fd,4638const char*filename,4639int options)4640{4641size_t offset;4642struct strbuf buf = STRBUF_INIT;/* owns the patch text */4643struct patch *list = NULL, **listp = &list;4644int skipped_patch =0;4645int res =0;4646int flush_attributes =0;46474648 state->patch_input_file = filename;4649if(read_patch_file(&buf, fd) <0)4650return-128;4651 offset =0;4652while(offset < buf.len) {4653struct patch *patch;4654int nr;46554656 patch =xcalloc(1,sizeof(*patch));4657 patch->inaccurate_eof = !!(options & APPLY_OPT_INACCURATE_EOF);4658 patch->recount = !!(options & APPLY_OPT_RECOUNT);4659 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4660if(nr <0) {4661free_patch(patch);4662if(nr == -128) {4663 res = -128;4664goto end;4665}4666break;4667}4668if(state->apply_in_reverse)4669reverse_patches(patch);4670if(use_patch(state, patch)) {4671patch_stats(state, patch);4672*listp = patch;4673 listp = &patch->next;46744675if((patch->new_name &&4676ends_with_path_components(patch->new_name,4677 GITATTRIBUTES_FILE)) ||4678(patch->old_name &&4679ends_with_path_components(patch->old_name,4680 GITATTRIBUTES_FILE)))4681 flush_attributes =1;4682}4683else{4684if(state->apply_verbosity > verbosity_normal)4685say_patch_name(stderr,_("Skipped patch '%s'."), patch);4686free_patch(patch);4687 skipped_patch++;4688}4689 offset += nr;4690}46914692if(!list && !skipped_patch) {4693error(_("unrecognized input"));4694 res = -128;4695goto end;4696}46974698if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4699 state->apply =0;47004701 state->update_index = (state->check_index || state->ita_only) && state->apply;4702if(state->update_index && !is_lock_file_locked(&state->lock_file)) {4703if(state->index_file)4704hold_lock_file_for_update(&state->lock_file,4705 state->index_file,4706 LOCK_DIE_ON_ERROR);4707else4708repo_hold_locked_index(state->repo, &state->lock_file,4709 LOCK_DIE_ON_ERROR);4710}47114712if(state->check_index &&read_apply_cache(state) <0) {4713error(_("unable to read index file"));4714 res = -128;4715goto end;4716}47174718if(state->check || state->apply) {4719int r =check_patch_list(state, list);4720if(r == -128) {4721 res = -128;4722goto end;4723}4724if(r <0&& !state->apply_with_reject) {4725 res = -1;4726goto end;4727}4728}47294730if(state->apply) {4731int write_res =write_out_results(state, list);4732if(write_res <0) {4733 res = -128;4734goto end;4735}4736if(write_res >0) {4737/* with --3way, we still need to write the index out */4738 res = state->apply_with_reject ? -1:1;4739goto end;4740}4741}47424743if(state->fake_ancestor &&4744build_fake_ancestor(state, list)) {4745 res = -128;4746goto end;4747}47484749if(state->diffstat && state->apply_verbosity > verbosity_silent)4750stat_patch_list(state, list);47514752if(state->numstat && state->apply_verbosity > verbosity_silent)4753numstat_patch_list(state, list);47544755if(state->summary && state->apply_verbosity > verbosity_silent)4756summary_patch_list(list);47574758if(flush_attributes)4759reset_parsed_attributes();4760end:4761free_patch_list(list);4762strbuf_release(&buf);4763string_list_clear(&state->fn_table,0);4764return res;4765}47664767static intapply_option_parse_exclude(const struct option *opt,4768const char*arg,int unset)4769{4770struct apply_state *state = opt->value;47714772BUG_ON_OPT_NEG(unset);47734774add_name_limit(state, arg,1);4775return0;4776}47774778static intapply_option_parse_include(const struct option *opt,4779const char*arg,int unset)4780{4781struct apply_state *state = opt->value;47824783BUG_ON_OPT_NEG(unset);47844785add_name_limit(state, arg,0);4786 state->has_include =1;4787return0;4788}47894790static intapply_option_parse_p(const struct option *opt,4791const char*arg,4792int unset)4793{4794struct apply_state *state = opt->value;47954796BUG_ON_OPT_NEG(unset);47974798 state->p_value =atoi(arg);4799 state->p_value_known =1;4800return0;4801}48024803static intapply_option_parse_space_change(const struct option *opt,4804const char*arg,int unset)4805{4806struct apply_state *state = opt->value;48074808BUG_ON_OPT_ARG(arg);48094810if(unset)4811 state->ws_ignore_action = ignore_ws_none;4812else4813 state->ws_ignore_action = ignore_ws_change;4814return0;4815}48164817static intapply_option_parse_whitespace(const struct option *opt,4818const char*arg,int unset)4819{4820struct apply_state *state = opt->value;48214822BUG_ON_OPT_NEG(unset);48234824 state->whitespace_option = arg;4825if(parse_whitespace_option(state, arg))4826return-1;4827return0;4828}48294830static intapply_option_parse_directory(const struct option *opt,4831const char*arg,int unset)4832{4833struct apply_state *state = opt->value;48344835BUG_ON_OPT_NEG(unset);48364837strbuf_reset(&state->root);4838strbuf_addstr(&state->root, arg);4839strbuf_complete(&state->root,'/');4840return0;4841}48424843intapply_all_patches(struct apply_state *state,4844int argc,4845const char**argv,4846int options)4847{4848int i;4849int res;4850int errs =0;4851int read_stdin =1;48524853for(i =0; i < argc; i++) {4854const char*arg = argv[i];4855char*to_free = NULL;4856int fd;48574858if(!strcmp(arg,"-")) {4859 res =apply_patch(state,0,"<stdin>", options);4860if(res <0)4861goto end;4862 errs |= res;4863 read_stdin =0;4864continue;4865}else4866 arg = to_free =prefix_filename(state->prefix, arg);48674868 fd =open(arg, O_RDONLY);4869if(fd <0) {4870error(_("can't open patch '%s':%s"), arg,strerror(errno));4871 res = -128;4872free(to_free);4873goto end;4874}4875 read_stdin =0;4876set_default_whitespace_mode(state);4877 res =apply_patch(state, fd, arg, options);4878close(fd);4879free(to_free);4880if(res <0)4881goto end;4882 errs |= res;4883}4884set_default_whitespace_mode(state);4885if(read_stdin) {4886 res =apply_patch(state,0,"<stdin>", options);4887if(res <0)4888goto end;4889 errs |= res;4890}48914892if(state->whitespace_error) {4893if(state->squelch_whitespace_errors &&4894 state->squelch_whitespace_errors < state->whitespace_error) {4895int squelched =4896 state->whitespace_error - state->squelch_whitespace_errors;4897warning(Q_("squelched%dwhitespace error",4898"squelched%dwhitespace errors",4899 squelched),4900 squelched);4901}4902if(state->ws_error_action == die_on_ws_error) {4903error(Q_("%dline adds whitespace errors.",4904"%dlines add whitespace errors.",4905 state->whitespace_error),4906 state->whitespace_error);4907 res = -128;4908goto end;4909}4910if(state->applied_after_fixing_ws && state->apply)4911warning(Q_("%dline applied after"4912" fixing whitespace errors.",4913"%dlines applied after"4914" fixing whitespace errors.",4915 state->applied_after_fixing_ws),4916 state->applied_after_fixing_ws);4917else if(state->whitespace_error)4918warning(Q_("%dline adds whitespace errors.",4919"%dlines add whitespace errors.",4920 state->whitespace_error),4921 state->whitespace_error);4922}49234924if(state->update_index) {4925 res =write_locked_index(state->repo->index, &state->lock_file, COMMIT_LOCK);4926if(res) {4927error(_("Unable to write new index file"));4928 res = -128;4929goto end;4930}4931}49324933 res = !!errs;49344935end:4936rollback_lock_file(&state->lock_file);49374938if(state->apply_verbosity <= verbosity_silent) {4939set_error_routine(state->saved_error_routine);4940set_warn_routine(state->saved_warn_routine);4941}49424943if(res > -1)4944return res;4945return(res == -1?1:128);4946}49474948intapply_parse_options(int argc,const char**argv,4949struct apply_state *state,4950int*force_apply,int*options,4951const char*const*apply_usage)4952{4953struct option builtin_apply_options[] = {4954{ OPTION_CALLBACK,0,"exclude", state,N_("path"),4955N_("don't apply changes matching the given path"),4956 PARSE_OPT_NONEG, apply_option_parse_exclude },4957{ OPTION_CALLBACK,0,"include", state,N_("path"),4958N_("apply changes matching the given path"),4959 PARSE_OPT_NONEG, apply_option_parse_include },4960{ OPTION_CALLBACK,'p', NULL, state,N_("num"),4961N_("remove <num> leading slashes from traditional diff paths"),49620, apply_option_parse_p },4963OPT_BOOL(0,"no-add", &state->no_add,4964N_("ignore additions made by the patch")),4965OPT_BOOL(0,"stat", &state->diffstat,4966N_("instead of applying the patch, output diffstat for the input")),4967OPT_NOOP_NOARG(0,"allow-binary-replacement"),4968OPT_NOOP_NOARG(0,"binary"),4969OPT_BOOL(0,"numstat", &state->numstat,4970N_("show number of added and deleted lines in decimal notation")),4971OPT_BOOL(0,"summary", &state->summary,4972N_("instead of applying the patch, output a summary for the input")),4973OPT_BOOL(0,"check", &state->check,4974N_("instead of applying the patch, see if the patch is applicable")),4975OPT_BOOL(0,"index", &state->check_index,4976N_("make sure the patch is applicable to the current index")),4977OPT_BOOL('N',"intent-to-add", &state->ita_only,4978N_("mark new files with `git add --intent-to-add`")),4979OPT_BOOL(0,"cached", &state->cached,4980N_("apply a patch without touching the working tree")),4981OPT_BOOL_F(0,"unsafe-paths", &state->unsafe_paths,4982N_("accept a patch that touches outside the working area"),4983 PARSE_OPT_NOCOMPLETE),4984OPT_BOOL(0,"apply", force_apply,4985N_("also apply the patch (use with --stat/--summary/--check)")),4986OPT_BOOL('3',"3way", &state->threeway,4987N_("attempt three-way merge if a patch does not apply")),4988OPT_FILENAME(0,"build-fake-ancestor", &state->fake_ancestor,4989N_("build a temporary index based on embedded index information")),4990/* Think twice before adding "--nul" synonym to this */4991OPT_SET_INT('z', NULL, &state->line_termination,4992N_("paths are separated with NUL character"),'\0'),4993OPT_INTEGER('C', NULL, &state->p_context,4994N_("ensure at least <n> lines of context match")),4995{ OPTION_CALLBACK,0,"whitespace", state,N_("action"),4996N_("detect new or modified lines that have whitespace errors"),49970, apply_option_parse_whitespace },4998{ OPTION_CALLBACK,0,"ignore-space-change", state, NULL,4999N_("ignore changes in whitespace when finding context"),5000 PARSE_OPT_NOARG, apply_option_parse_space_change },5001{ OPTION_CALLBACK,0,"ignore-whitespace", state, NULL,5002N_("ignore changes in whitespace when finding context"),5003 PARSE_OPT_NOARG, apply_option_parse_space_change },5004OPT_BOOL('R',"reverse", &state->apply_in_reverse,5005N_("apply the patch in reverse")),5006OPT_BOOL(0,"unidiff-zero", &state->unidiff_zero,5007N_("don't expect at least one line of context")),5008OPT_BOOL(0,"reject", &state->apply_with_reject,5009N_("leave the rejected hunks in corresponding *.rej files")),5010OPT_BOOL(0,"allow-overlap", &state->allow_overlap,5011N_("allow overlapping hunks")),5012OPT__VERBOSE(&state->apply_verbosity,N_("be verbose")),5013OPT_BIT(0,"inaccurate-eof", options,5014N_("tolerate incorrectly detected missing new-line at the end of file"),5015 APPLY_OPT_INACCURATE_EOF),5016OPT_BIT(0,"recount", options,5017N_("do not trust the line counts in the hunk headers"),5018 APPLY_OPT_RECOUNT),5019{ OPTION_CALLBACK,0,"directory", state,N_("root"),5020N_("prepend <root> to all filenames"),50210, apply_option_parse_directory },5022OPT_END()5023};50245025returnparse_options(argc, argv, state->prefix, builtin_apply_options, apply_usage,0);5026}