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#include"cache.h" 10#include"lockfile.h" 11#include"cache-tree.h" 12#include"quote.h" 13#include"blob.h" 14#include"delta.h" 15#include"builtin.h" 16#include"string-list.h" 17#include"dir.h" 18#include"diff.h" 19#include"parse-options.h" 20#include"xdiff-interface.h" 21#include"ll-merge.h" 22#include"rerere.h" 23 24enum ws_error_action { 25 nowarn_ws_error, 26 warn_on_ws_error, 27 die_on_ws_error, 28 correct_ws_error 29}; 30 31 32enum ws_ignore { 33 ignore_ws_none, 34 ignore_ws_change 35}; 36 37/* 38 * We need to keep track of how symlinks in the preimage are 39 * manipulated by the patches. A patch to add a/b/c where a/b 40 * is a symlink should not be allowed to affect the directory 41 * the symlink points at, but if the same patch removes a/b, 42 * it is perfectly fine, as the patch removes a/b to make room 43 * to create a directory a/b so that a/b/c can be created. 44 * 45 * See also "struct string_list symlink_changes" in "struct 46 * apply_state". 47 */ 48#define SYMLINK_GOES_AWAY 01 49#define SYMLINK_IN_RESULT 02 50 51struct apply_state { 52const char*prefix; 53int prefix_length; 54 55/* These control what gets looked at and modified */ 56int apply;/* this is not a dry-run */ 57int cached;/* apply to the index only */ 58int check;/* preimage must match working tree, don't actually apply */ 59int check_index;/* preimage must match the indexed version */ 60int update_index;/* check_index && apply */ 61 62/* These control cosmetic aspect of the output */ 63int diffstat;/* just show a diffstat, and don't actually apply */ 64int numstat;/* just show a numeric diffstat, and don't actually apply */ 65int summary;/* just report creation, deletion, etc, and don't actually apply */ 66 67/* These boolean parameters control how the apply is done */ 68int allow_overlap; 69int apply_in_reverse; 70int apply_with_reject; 71int apply_verbosely; 72int no_add; 73int threeway; 74int unidiff_zero; 75int unsafe_paths; 76 77/* Other non boolean parameters */ 78const char*fake_ancestor; 79const char*patch_input_file; 80int line_termination; 81struct strbuf root; 82int p_value; 83int p_value_known; 84unsigned int p_context; 85 86/* Exclude and include path parameters */ 87struct string_list limit_by_name; 88int has_include; 89 90/* Various "current state" */ 91int linenr;/* current line number */ 92struct string_list symlink_changes;/* we have to track symlinks */ 93 94/* 95 * For "diff-stat" like behaviour, we keep track of the biggest change 96 * we've seen, and the longest filename. That allows us to do simple 97 * scaling. 98 */ 99int max_change; 100int max_len; 101 102/* 103 * Records filenames that have been touched, in order to handle 104 * the case where more than one patches touch the same file. 105 */ 106struct string_list fn_table; 107 108/* These control whitespace errors */ 109enum ws_error_action ws_error_action; 110enum ws_ignore ws_ignore_action; 111const char*whitespace_option; 112int whitespace_error; 113int squelch_whitespace_errors; 114int applied_after_fixing_ws; 115}; 116 117static int newfd = -1; 118 119static const char*const apply_usage[] = { 120N_("git apply [<options>] [<patch>...]"), 121 NULL 122}; 123 124static voidparse_whitespace_option(struct apply_state *state,const char*option) 125{ 126if(!option) { 127 state->ws_error_action = warn_on_ws_error; 128return; 129} 130if(!strcmp(option,"warn")) { 131 state->ws_error_action = warn_on_ws_error; 132return; 133} 134if(!strcmp(option,"nowarn")) { 135 state->ws_error_action = nowarn_ws_error; 136return; 137} 138if(!strcmp(option,"error")) { 139 state->ws_error_action = die_on_ws_error; 140return; 141} 142if(!strcmp(option,"error-all")) { 143 state->ws_error_action = die_on_ws_error; 144 state->squelch_whitespace_errors =0; 145return; 146} 147if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 148 state->ws_error_action = correct_ws_error; 149return; 150} 151die(_("unrecognized whitespace option '%s'"), option); 152} 153 154static voidparse_ignorewhitespace_option(struct apply_state *state, 155const char*option) 156{ 157if(!option || !strcmp(option,"no") || 158!strcmp(option,"false") || !strcmp(option,"never") || 159!strcmp(option,"none")) { 160 state->ws_ignore_action = ignore_ws_none; 161return; 162} 163if(!strcmp(option,"change")) { 164 state->ws_ignore_action = ignore_ws_change; 165return; 166} 167die(_("unrecognized whitespace ignore option '%s'"), option); 168} 169 170static voidset_default_whitespace_mode(struct apply_state *state) 171{ 172if(!state->whitespace_option && !apply_default_whitespace) 173 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 174} 175 176/* 177 * This represents one "hunk" from a patch, starting with 178 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 179 * patch text is pointed at by patch, and its byte length 180 * is stored in size. leading and trailing are the number 181 * of context lines. 182 */ 183struct fragment { 184unsigned long leading, trailing; 185unsigned long oldpos, oldlines; 186unsigned long newpos, newlines; 187/* 188 * 'patch' is usually borrowed from buf in apply_patch(), 189 * but some codepaths store an allocated buffer. 190 */ 191const char*patch; 192unsigned free_patch:1, 193 rejected:1; 194int size; 195int linenr; 196struct fragment *next; 197}; 198 199/* 200 * When dealing with a binary patch, we reuse "leading" field 201 * to store the type of the binary hunk, either deflated "delta" 202 * or deflated "literal". 203 */ 204#define binary_patch_method leading 205#define BINARY_DELTA_DEFLATED 1 206#define BINARY_LITERAL_DEFLATED 2 207 208/* 209 * This represents a "patch" to a file, both metainfo changes 210 * such as creation/deletion, filemode and content changes represented 211 * as a series of fragments. 212 */ 213struct patch { 214char*new_name, *old_name, *def_name; 215unsigned int old_mode, new_mode; 216int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 217int rejected; 218unsigned ws_rule; 219int lines_added, lines_deleted; 220int score; 221unsigned int is_toplevel_relative:1; 222unsigned int inaccurate_eof:1; 223unsigned int is_binary:1; 224unsigned int is_copy:1; 225unsigned int is_rename:1; 226unsigned int recount:1; 227unsigned int conflicted_threeway:1; 228unsigned int direct_to_threeway:1; 229struct fragment *fragments; 230char*result; 231size_t resultsize; 232char old_sha1_prefix[41]; 233char new_sha1_prefix[41]; 234struct patch *next; 235 236/* three-way fallback result */ 237struct object_id threeway_stage[3]; 238}; 239 240static voidfree_fragment_list(struct fragment *list) 241{ 242while(list) { 243struct fragment *next = list->next; 244if(list->free_patch) 245free((char*)list->patch); 246free(list); 247 list = next; 248} 249} 250 251static voidfree_patch(struct patch *patch) 252{ 253free_fragment_list(patch->fragments); 254free(patch->def_name); 255free(patch->old_name); 256free(patch->new_name); 257free(patch->result); 258free(patch); 259} 260 261static voidfree_patch_list(struct patch *list) 262{ 263while(list) { 264struct patch *next = list->next; 265free_patch(list); 266 list = next; 267} 268} 269 270/* 271 * A line in a file, len-bytes long (includes the terminating LF, 272 * except for an incomplete line at the end if the file ends with 273 * one), and its contents hashes to 'hash'. 274 */ 275struct line { 276size_t len; 277unsigned hash :24; 278unsigned flag :8; 279#define LINE_COMMON 1 280#define LINE_PATCHED 2 281}; 282 283/* 284 * This represents a "file", which is an array of "lines". 285 */ 286struct image { 287char*buf; 288size_t len; 289size_t nr; 290size_t alloc; 291struct line *line_allocated; 292struct line *line; 293}; 294 295static uint32_thash_line(const char*cp,size_t len) 296{ 297size_t i; 298uint32_t h; 299for(i =0, h =0; i < len; i++) { 300if(!isspace(cp[i])) { 301 h = h *3+ (cp[i] &0xff); 302} 303} 304return h; 305} 306 307/* 308 * Compare lines s1 of length n1 and s2 of length n2, ignoring 309 * whitespace difference. Returns 1 if they match, 0 otherwise 310 */ 311static intfuzzy_matchlines(const char*s1,size_t n1, 312const char*s2,size_t n2) 313{ 314const char*last1 = s1 + n1 -1; 315const char*last2 = s2 + n2 -1; 316int result =0; 317 318/* ignore line endings */ 319while((*last1 =='\r') || (*last1 =='\n')) 320 last1--; 321while((*last2 =='\r') || (*last2 =='\n')) 322 last2--; 323 324/* skip leading whitespaces, if both begin with whitespace */ 325if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 326while(isspace(*s1) && (s1 <= last1)) 327 s1++; 328while(isspace(*s2) && (s2 <= last2)) 329 s2++; 330} 331/* early return if both lines are empty */ 332if((s1 > last1) && (s2 > last2)) 333return1; 334while(!result) { 335 result = *s1++ - *s2++; 336/* 337 * Skip whitespace inside. We check for whitespace on 338 * both buffers because we don't want "a b" to match 339 * "ab" 340 */ 341if(isspace(*s1) &&isspace(*s2)) { 342while(isspace(*s1) && s1 <= last1) 343 s1++; 344while(isspace(*s2) && s2 <= last2) 345 s2++; 346} 347/* 348 * If we reached the end on one side only, 349 * lines don't match 350 */ 351if( 352((s2 > last2) && (s1 <= last1)) || 353((s1 > last1) && (s2 <= last2))) 354return0; 355if((s1 > last1) && (s2 > last2)) 356break; 357} 358 359return!result; 360} 361 362static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 363{ 364ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 365 img->line_allocated[img->nr].len = len; 366 img->line_allocated[img->nr].hash =hash_line(bol, len); 367 img->line_allocated[img->nr].flag = flag; 368 img->nr++; 369} 370 371/* 372 * "buf" has the file contents to be patched (read from various sources). 373 * attach it to "image" and add line-based index to it. 374 * "image" now owns the "buf". 375 */ 376static voidprepare_image(struct image *image,char*buf,size_t len, 377int prepare_linetable) 378{ 379const char*cp, *ep; 380 381memset(image,0,sizeof(*image)); 382 image->buf = buf; 383 image->len = len; 384 385if(!prepare_linetable) 386return; 387 388 ep = image->buf + image->len; 389 cp = image->buf; 390while(cp < ep) { 391const char*next; 392for(next = cp; next < ep && *next !='\n'; next++) 393; 394if(next < ep) 395 next++; 396add_line_info(image, cp, next - cp,0); 397 cp = next; 398} 399 image->line = image->line_allocated; 400} 401 402static voidclear_image(struct image *image) 403{ 404free(image->buf); 405free(image->line_allocated); 406memset(image,0,sizeof(*image)); 407} 408 409/* fmt must contain _one_ %s and no other substitution */ 410static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 411{ 412struct strbuf sb = STRBUF_INIT; 413 414if(patch->old_name && patch->new_name && 415strcmp(patch->old_name, patch->new_name)) { 416quote_c_style(patch->old_name, &sb, NULL,0); 417strbuf_addstr(&sb," => "); 418quote_c_style(patch->new_name, &sb, NULL,0); 419}else{ 420const char*n = patch->new_name; 421if(!n) 422 n = patch->old_name; 423quote_c_style(n, &sb, NULL,0); 424} 425fprintf(output, fmt, sb.buf); 426fputc('\n', output); 427strbuf_release(&sb); 428} 429 430#define SLOP (16) 431 432static voidread_patch_file(struct strbuf *sb,int fd) 433{ 434if(strbuf_read(sb, fd,0) <0) 435die_errno("git apply: failed to read"); 436 437/* 438 * Make sure that we have some slop in the buffer 439 * so that we can do speculative "memcmp" etc, and 440 * see to it that it is NUL-filled. 441 */ 442strbuf_grow(sb, SLOP); 443memset(sb->buf + sb->len,0, SLOP); 444} 445 446static unsigned longlinelen(const char*buffer,unsigned long size) 447{ 448unsigned long len =0; 449while(size--) { 450 len++; 451if(*buffer++ =='\n') 452break; 453} 454return len; 455} 456 457static intis_dev_null(const char*str) 458{ 459returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 460} 461 462#define TERM_SPACE 1 463#define TERM_TAB 2 464 465static intname_terminate(const char*name,int namelen,int c,int terminate) 466{ 467if(c ==' '&& !(terminate & TERM_SPACE)) 468return0; 469if(c =='\t'&& !(terminate & TERM_TAB)) 470return0; 471 472return1; 473} 474 475/* remove double slashes to make --index work with such filenames */ 476static char*squash_slash(char*name) 477{ 478int i =0, j =0; 479 480if(!name) 481return NULL; 482 483while(name[i]) { 484if((name[j++] = name[i++]) =='/') 485while(name[i] =='/') 486 i++; 487} 488 name[j] ='\0'; 489return name; 490} 491 492static char*find_name_gnu(struct apply_state *state, 493const char*line, 494const char*def, 495int p_value) 496{ 497struct strbuf name = STRBUF_INIT; 498char*cp; 499 500/* 501 * Proposed "new-style" GNU patch/diff format; see 502 * http://marc.info/?l=git&m=112927316408690&w=2 503 */ 504if(unquote_c_style(&name, line, NULL)) { 505strbuf_release(&name); 506return NULL; 507} 508 509for(cp = name.buf; p_value; p_value--) { 510 cp =strchr(cp,'/'); 511if(!cp) { 512strbuf_release(&name); 513return NULL; 514} 515 cp++; 516} 517 518strbuf_remove(&name,0, cp - name.buf); 519if(state->root.len) 520strbuf_insert(&name,0, state->root.buf, state->root.len); 521returnsquash_slash(strbuf_detach(&name, NULL)); 522} 523 524static size_tsane_tz_len(const char*line,size_t len) 525{ 526const char*tz, *p; 527 528if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 529return0; 530 tz = line + len -strlen(" +0500"); 531 532if(tz[1] !='+'&& tz[1] !='-') 533return0; 534 535for(p = tz +2; p != line + len; p++) 536if(!isdigit(*p)) 537return0; 538 539return line + len - tz; 540} 541 542static size_ttz_with_colon_len(const char*line,size_t len) 543{ 544const char*tz, *p; 545 546if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 547return0; 548 tz = line + len -strlen(" +08:00"); 549 550if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 551return0; 552 p = tz +2; 553if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 554!isdigit(*p++) || !isdigit(*p++)) 555return0; 556 557return line + len - tz; 558} 559 560static size_tdate_len(const char*line,size_t len) 561{ 562const char*date, *p; 563 564if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 565return0; 566 p = date = line + len -strlen("72-02-05"); 567 568if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 569!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 570!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 571return0; 572 573if(date - line >=strlen("19") && 574isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 575 date -=strlen("19"); 576 577return line + len - date; 578} 579 580static size_tshort_time_len(const char*line,size_t len) 581{ 582const char*time, *p; 583 584if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 585return0; 586 p = time = line + len -strlen(" 07:01:32"); 587 588/* Permit 1-digit hours? */ 589if(*p++ !=' '|| 590!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 591!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 592!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 593return0; 594 595return line + len - time; 596} 597 598static size_tfractional_time_len(const char*line,size_t len) 599{ 600const char*p; 601size_t n; 602 603/* Expected format: 19:41:17.620000023 */ 604if(!len || !isdigit(line[len -1])) 605return0; 606 p = line + len -1; 607 608/* Fractional seconds. */ 609while(p > line &&isdigit(*p)) 610 p--; 611if(*p !='.') 612return0; 613 614/* Hours, minutes, and whole seconds. */ 615 n =short_time_len(line, p - line); 616if(!n) 617return0; 618 619return line + len - p + n; 620} 621 622static size_ttrailing_spaces_len(const char*line,size_t len) 623{ 624const char*p; 625 626/* Expected format: ' ' x (1 or more) */ 627if(!len || line[len -1] !=' ') 628return0; 629 630 p = line + len; 631while(p != line) { 632 p--; 633if(*p !=' ') 634return line + len - (p +1); 635} 636 637/* All spaces! */ 638return len; 639} 640 641static size_tdiff_timestamp_len(const char*line,size_t len) 642{ 643const char*end = line + len; 644size_t n; 645 646/* 647 * Posix: 2010-07-05 19:41:17 648 * GNU: 2010-07-05 19:41:17.620000023 -0500 649 */ 650 651if(!isdigit(end[-1])) 652return0; 653 654 n =sane_tz_len(line, end - line); 655if(!n) 656 n =tz_with_colon_len(line, end - line); 657 end -= n; 658 659 n =short_time_len(line, end - line); 660if(!n) 661 n =fractional_time_len(line, end - line); 662 end -= n; 663 664 n =date_len(line, end - line); 665if(!n)/* No date. Too bad. */ 666return0; 667 end -= n; 668 669if(end == line)/* No space before date. */ 670return0; 671if(end[-1] =='\t') {/* Success! */ 672 end--; 673return line + len - end; 674} 675if(end[-1] !=' ')/* No space before date. */ 676return0; 677 678/* Whitespace damage. */ 679 end -=trailing_spaces_len(line, end - line); 680return line + len - end; 681} 682 683static char*find_name_common(struct apply_state *state, 684const char*line, 685const char*def, 686int p_value, 687const char*end, 688int terminate) 689{ 690int len; 691const char*start = NULL; 692 693if(p_value ==0) 694 start = line; 695while(line != end) { 696char c = *line; 697 698if(!end &&isspace(c)) { 699if(c =='\n') 700break; 701if(name_terminate(start, line-start, c, terminate)) 702break; 703} 704 line++; 705if(c =='/'&& !--p_value) 706 start = line; 707} 708if(!start) 709returnsquash_slash(xstrdup_or_null(def)); 710 len = line - start; 711if(!len) 712returnsquash_slash(xstrdup_or_null(def)); 713 714/* 715 * Generally we prefer the shorter name, especially 716 * if the other one is just a variation of that with 717 * something else tacked on to the end (ie "file.orig" 718 * or "file~"). 719 */ 720if(def) { 721int deflen =strlen(def); 722if(deflen < len && !strncmp(start, def, deflen)) 723returnsquash_slash(xstrdup(def)); 724} 725 726if(state->root.len) { 727char*ret =xstrfmt("%s%.*s", state->root.buf, len, start); 728returnsquash_slash(ret); 729} 730 731returnsquash_slash(xmemdupz(start, len)); 732} 733 734static char*find_name(struct apply_state *state, 735const char*line, 736char*def, 737int p_value, 738int terminate) 739{ 740if(*line =='"') { 741char*name =find_name_gnu(state, line, def, p_value); 742if(name) 743return name; 744} 745 746returnfind_name_common(state, line, def, p_value, NULL, terminate); 747} 748 749static char*find_name_traditional(struct apply_state *state, 750const char*line, 751char*def, 752int p_value) 753{ 754size_t len; 755size_t date_len; 756 757if(*line =='"') { 758char*name =find_name_gnu(state, line, def, p_value); 759if(name) 760return name; 761} 762 763 len =strchrnul(line,'\n') - line; 764 date_len =diff_timestamp_len(line, len); 765if(!date_len) 766returnfind_name_common(state, line, def, p_value, NULL, TERM_TAB); 767 len -= date_len; 768 769returnfind_name_common(state, line, def, p_value, line + len,0); 770} 771 772static intcount_slashes(const char*cp) 773{ 774int cnt =0; 775char ch; 776 777while((ch = *cp++)) 778if(ch =='/') 779 cnt++; 780return cnt; 781} 782 783/* 784 * Given the string after "--- " or "+++ ", guess the appropriate 785 * p_value for the given patch. 786 */ 787static intguess_p_value(struct apply_state *state,const char*nameline) 788{ 789char*name, *cp; 790int val = -1; 791 792if(is_dev_null(nameline)) 793return-1; 794 name =find_name_traditional(state, nameline, NULL,0); 795if(!name) 796return-1; 797 cp =strchr(name,'/'); 798if(!cp) 799 val =0; 800else if(state->prefix) { 801/* 802 * Does it begin with "a/$our-prefix" and such? Then this is 803 * very likely to apply to our directory. 804 */ 805if(!strncmp(name, state->prefix, state->prefix_length)) 806 val =count_slashes(state->prefix); 807else{ 808 cp++; 809if(!strncmp(cp, state->prefix, state->prefix_length)) 810 val =count_slashes(state->prefix) +1; 811} 812} 813free(name); 814return val; 815} 816 817/* 818 * Does the ---/+++ line have the POSIX timestamp after the last HT? 819 * GNU diff puts epoch there to signal a creation/deletion event. Is 820 * this such a timestamp? 821 */ 822static inthas_epoch_timestamp(const char*nameline) 823{ 824/* 825 * We are only interested in epoch timestamp; any non-zero 826 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 827 * For the same reason, the date must be either 1969-12-31 or 828 * 1970-01-01, and the seconds part must be "00". 829 */ 830const char stamp_regexp[] = 831"^(1969-12-31|1970-01-01)" 832" " 833"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 834" " 835"([-+][0-2][0-9]:?[0-5][0-9])\n"; 836const char*timestamp = NULL, *cp, *colon; 837static regex_t *stamp; 838 regmatch_t m[10]; 839int zoneoffset; 840int hourminute; 841int status; 842 843for(cp = nameline; *cp !='\n'; cp++) { 844if(*cp =='\t') 845 timestamp = cp +1; 846} 847if(!timestamp) 848return0; 849if(!stamp) { 850 stamp =xmalloc(sizeof(*stamp)); 851if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 852warning(_("Cannot prepare timestamp regexp%s"), 853 stamp_regexp); 854return0; 855} 856} 857 858 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 859if(status) { 860if(status != REG_NOMATCH) 861warning(_("regexec returned%dfor input:%s"), 862 status, timestamp); 863return0; 864} 865 866 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 867if(*colon ==':') 868 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 869else 870 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 871if(timestamp[m[3].rm_so] =='-') 872 zoneoffset = -zoneoffset; 873 874/* 875 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 876 * (west of GMT) or 1970-01-01 (east of GMT) 877 */ 878if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 879(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 880return0; 881 882 hourminute = (strtol(timestamp +11, NULL,10) *60+ 883strtol(timestamp +14, NULL,10) - 884 zoneoffset); 885 886return((zoneoffset <0&& hourminute ==1440) || 887(0<= zoneoffset && !hourminute)); 888} 889 890/* 891 * Get the name etc info from the ---/+++ lines of a traditional patch header 892 * 893 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 894 * files, we can happily check the index for a match, but for creating a 895 * new file we should try to match whatever "patch" does. I have no idea. 896 */ 897static voidparse_traditional_patch(struct apply_state *state, 898const char*first, 899const char*second, 900struct patch *patch) 901{ 902char*name; 903 904 first +=4;/* skip "--- " */ 905 second +=4;/* skip "+++ " */ 906if(!state->p_value_known) { 907int p, q; 908 p =guess_p_value(state, first); 909 q =guess_p_value(state, second); 910if(p <0) p = q; 911if(0<= p && p == q) { 912 state->p_value = p; 913 state->p_value_known =1; 914} 915} 916if(is_dev_null(first)) { 917 patch->is_new =1; 918 patch->is_delete =0; 919 name =find_name_traditional(state, second, NULL, state->p_value); 920 patch->new_name = name; 921}else if(is_dev_null(second)) { 922 patch->is_new =0; 923 patch->is_delete =1; 924 name =find_name_traditional(state, first, NULL, state->p_value); 925 patch->old_name = name; 926}else{ 927char*first_name; 928 first_name =find_name_traditional(state, first, NULL, state->p_value); 929 name =find_name_traditional(state, second, first_name, state->p_value); 930free(first_name); 931if(has_epoch_timestamp(first)) { 932 patch->is_new =1; 933 patch->is_delete =0; 934 patch->new_name = name; 935}else if(has_epoch_timestamp(second)) { 936 patch->is_new =0; 937 patch->is_delete =1; 938 patch->old_name = name; 939}else{ 940 patch->old_name = name; 941 patch->new_name =xstrdup_or_null(name); 942} 943} 944if(!name) 945die(_("unable to find filename in patch at line%d"), state->linenr); 946} 947 948static intgitdiff_hdrend(struct apply_state *state, 949const char*line, 950struct patch *patch) 951{ 952return-1; 953} 954 955/* 956 * We're anal about diff header consistency, to make 957 * sure that we don't end up having strange ambiguous 958 * patches floating around. 959 * 960 * As a result, gitdiff_{old|new}name() will check 961 * their names against any previous information, just 962 * to make sure.. 963 */ 964#define DIFF_OLD_NAME 0 965#define DIFF_NEW_NAME 1 966 967static voidgitdiff_verify_name(struct apply_state *state, 968const char*line, 969int isnull, 970char**name, 971int side) 972{ 973if(!*name && !isnull) { 974*name =find_name(state, line, NULL, state->p_value, TERM_TAB); 975return; 976} 977 978if(*name) { 979int len =strlen(*name); 980char*another; 981if(isnull) 982die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 983*name, state->linenr); 984 another =find_name(state, line, NULL, state->p_value, TERM_TAB); 985if(!another ||memcmp(another, *name, len +1)) 986die((side == DIFF_NEW_NAME) ? 987_("git apply: bad git-diff - inconsistent new filename on line%d") : 988_("git apply: bad git-diff - inconsistent old filename on line%d"), state->linenr); 989free(another); 990}else{ 991/* expect "/dev/null" */ 992if(memcmp("/dev/null", line,9) || line[9] !='\n') 993die(_("git apply: bad git-diff - expected /dev/null on line%d"), state->linenr); 994} 995} 996 997static intgitdiff_oldname(struct apply_state *state, 998const char*line, 999struct patch *patch)1000{1001gitdiff_verify_name(state, line,1002 patch->is_new, &patch->old_name,1003 DIFF_OLD_NAME);1004return0;1005}10061007static intgitdiff_newname(struct apply_state *state,1008const char*line,1009struct patch *patch)1010{1011gitdiff_verify_name(state, line,1012 patch->is_delete, &patch->new_name,1013 DIFF_NEW_NAME);1014return0;1015}10161017static intgitdiff_oldmode(struct apply_state *state,1018const char*line,1019struct patch *patch)1020{1021 patch->old_mode =strtoul(line, NULL,8);1022return0;1023}10241025static intgitdiff_newmode(struct apply_state *state,1026const char*line,1027struct patch *patch)1028{1029 patch->new_mode =strtoul(line, NULL,8);1030return0;1031}10321033static intgitdiff_delete(struct apply_state *state,1034const char*line,1035struct patch *patch)1036{1037 patch->is_delete =1;1038free(patch->old_name);1039 patch->old_name =xstrdup_or_null(patch->def_name);1040returngitdiff_oldmode(state, line, patch);1041}10421043static intgitdiff_newfile(struct apply_state *state,1044const char*line,1045struct patch *patch)1046{1047 patch->is_new =1;1048free(patch->new_name);1049 patch->new_name =xstrdup_or_null(patch->def_name);1050returngitdiff_newmode(state, line, patch);1051}10521053static intgitdiff_copysrc(struct apply_state *state,1054const char*line,1055struct patch *patch)1056{1057 patch->is_copy =1;1058free(patch->old_name);1059 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1060return0;1061}10621063static intgitdiff_copydst(struct apply_state *state,1064const char*line,1065struct patch *patch)1066{1067 patch->is_copy =1;1068free(patch->new_name);1069 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1070return0;1071}10721073static intgitdiff_renamesrc(struct apply_state *state,1074const char*line,1075struct patch *patch)1076{1077 patch->is_rename =1;1078free(patch->old_name);1079 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1080return0;1081}10821083static intgitdiff_renamedst(struct apply_state *state,1084const char*line,1085struct patch *patch)1086{1087 patch->is_rename =1;1088free(patch->new_name);1089 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1090return0;1091}10921093static intgitdiff_similarity(struct apply_state *state,1094const char*line,1095struct patch *patch)1096{1097unsigned long val =strtoul(line, NULL,10);1098if(val <=100)1099 patch->score = val;1100return0;1101}11021103static intgitdiff_dissimilarity(struct apply_state *state,1104const char*line,1105struct patch *patch)1106{1107unsigned long val =strtoul(line, NULL,10);1108if(val <=100)1109 patch->score = val;1110return0;1111}11121113static intgitdiff_index(struct apply_state *state,1114const char*line,1115struct patch *patch)1116{1117/*1118 * index line is N hexadecimal, "..", N hexadecimal,1119 * and optional space with octal mode.1120 */1121const char*ptr, *eol;1122int len;11231124 ptr =strchr(line,'.');1125if(!ptr || ptr[1] !='.'||40< ptr - line)1126return0;1127 len = ptr - line;1128memcpy(patch->old_sha1_prefix, line, len);1129 patch->old_sha1_prefix[len] =0;11301131 line = ptr +2;1132 ptr =strchr(line,' ');1133 eol =strchrnul(line,'\n');11341135if(!ptr || eol < ptr)1136 ptr = eol;1137 len = ptr - line;11381139if(40< len)1140return0;1141memcpy(patch->new_sha1_prefix, line, len);1142 patch->new_sha1_prefix[len] =0;1143if(*ptr ==' ')1144 patch->old_mode =strtoul(ptr+1, NULL,8);1145return0;1146}11471148/*1149 * This is normal for a diff that doesn't change anything: we'll fall through1150 * into the next diff. Tell the parser to break out.1151 */1152static intgitdiff_unrecognized(struct apply_state *state,1153const char*line,1154struct patch *patch)1155{1156return-1;1157}11581159/*1160 * Skip p_value leading components from "line"; as we do not accept1161 * absolute paths, return NULL in that case.1162 */1163static const char*skip_tree_prefix(struct apply_state *state,1164const char*line,1165int llen)1166{1167int nslash;1168int i;11691170if(!state->p_value)1171return(llen && line[0] =='/') ? NULL : line;11721173 nslash = state->p_value;1174for(i =0; i < llen; i++) {1175int ch = line[i];1176if(ch =='/'&& --nslash <=0)1177return(i ==0) ? NULL : &line[i +1];1178}1179return NULL;1180}11811182/*1183 * This is to extract the same name that appears on "diff --git"1184 * line. We do not find and return anything if it is a rename1185 * patch, and it is OK because we will find the name elsewhere.1186 * We need to reliably find name only when it is mode-change only,1187 * creation or deletion of an empty file. In any of these cases,1188 * both sides are the same name under a/ and b/ respectively.1189 */1190static char*git_header_name(struct apply_state *state,1191const char*line,1192int llen)1193{1194const char*name;1195const char*second = NULL;1196size_t len, line_len;11971198 line +=strlen("diff --git ");1199 llen -=strlen("diff --git ");12001201if(*line =='"') {1202const char*cp;1203struct strbuf first = STRBUF_INIT;1204struct strbuf sp = STRBUF_INIT;12051206if(unquote_c_style(&first, line, &second))1207goto free_and_fail1;12081209/* strip the a/b prefix including trailing slash */1210 cp =skip_tree_prefix(state, first.buf, first.len);1211if(!cp)1212goto free_and_fail1;1213strbuf_remove(&first,0, cp - first.buf);12141215/*1216 * second points at one past closing dq of name.1217 * find the second name.1218 */1219while((second < line + llen) &&isspace(*second))1220 second++;12211222if(line + llen <= second)1223goto free_and_fail1;1224if(*second =='"') {1225if(unquote_c_style(&sp, second, NULL))1226goto free_and_fail1;1227 cp =skip_tree_prefix(state, sp.buf, sp.len);1228if(!cp)1229goto free_and_fail1;1230/* They must match, otherwise ignore */1231if(strcmp(cp, first.buf))1232goto free_and_fail1;1233strbuf_release(&sp);1234returnstrbuf_detach(&first, NULL);1235}12361237/* unquoted second */1238 cp =skip_tree_prefix(state, second, line + llen - second);1239if(!cp)1240goto free_and_fail1;1241if(line + llen - cp != first.len ||1242memcmp(first.buf, cp, first.len))1243goto free_and_fail1;1244returnstrbuf_detach(&first, NULL);12451246 free_and_fail1:1247strbuf_release(&first);1248strbuf_release(&sp);1249return NULL;1250}12511252/* unquoted first name */1253 name =skip_tree_prefix(state, line, llen);1254if(!name)1255return NULL;12561257/*1258 * since the first name is unquoted, a dq if exists must be1259 * the beginning of the second name.1260 */1261for(second = name; second < line + llen; second++) {1262if(*second =='"') {1263struct strbuf sp = STRBUF_INIT;1264const char*np;12651266if(unquote_c_style(&sp, second, NULL))1267goto free_and_fail2;12681269 np =skip_tree_prefix(state, sp.buf, sp.len);1270if(!np)1271goto free_and_fail2;12721273 len = sp.buf + sp.len - np;1274if(len < second - name &&1275!strncmp(np, name, len) &&1276isspace(name[len])) {1277/* Good */1278strbuf_remove(&sp,0, np - sp.buf);1279returnstrbuf_detach(&sp, NULL);1280}12811282 free_and_fail2:1283strbuf_release(&sp);1284return NULL;1285}1286}12871288/*1289 * Accept a name only if it shows up twice, exactly the same1290 * form.1291 */1292 second =strchr(name,'\n');1293if(!second)1294return NULL;1295 line_len = second - name;1296for(len =0; ; len++) {1297switch(name[len]) {1298default:1299continue;1300case'\n':1301return NULL;1302case'\t':case' ':1303/*1304 * Is this the separator between the preimage1305 * and the postimage pathname? Again, we are1306 * only interested in the case where there is1307 * no rename, as this is only to set def_name1308 * and a rename patch has the names elsewhere1309 * in an unambiguous form.1310 */1311if(!name[len +1])1312return NULL;/* no postimage name */1313 second =skip_tree_prefix(state, name + len +1,1314 line_len - (len +1));1315if(!second)1316return NULL;1317/*1318 * Does len bytes starting at "name" and "second"1319 * (that are separated by one HT or SP we just1320 * found) exactly match?1321 */1322if(second[len] =='\n'&& !strncmp(name, second, len))1323returnxmemdupz(name, len);1324}1325}1326}13271328/* Verify that we recognize the lines following a git header */1329static intparse_git_header(struct apply_state *state,1330const char*line,1331int len,1332unsigned int size,1333struct patch *patch)1334{1335unsigned long offset;13361337/* A git diff has explicit new/delete information, so we don't guess */1338 patch->is_new =0;1339 patch->is_delete =0;13401341/*1342 * Some things may not have the old name in the1343 * rest of the headers anywhere (pure mode changes,1344 * or removing or adding empty files), so we get1345 * the default name from the header.1346 */1347 patch->def_name =git_header_name(state, line, len);1348if(patch->def_name && state->root.len) {1349char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1350free(patch->def_name);1351 patch->def_name = s;1352}13531354 line += len;1355 size -= len;1356 state->linenr++;1357for(offset = len ; size >0; offset += len, size -= len, line += len, state->linenr++) {1358static const struct opentry {1359const char*str;1360int(*fn)(struct apply_state *,const char*,struct patch *);1361} optable[] = {1362{"@@ -", gitdiff_hdrend },1363{"--- ", gitdiff_oldname },1364{"+++ ", gitdiff_newname },1365{"old mode ", gitdiff_oldmode },1366{"new mode ", gitdiff_newmode },1367{"deleted file mode ", gitdiff_delete },1368{"new file mode ", gitdiff_newfile },1369{"copy from ", gitdiff_copysrc },1370{"copy to ", gitdiff_copydst },1371{"rename old ", gitdiff_renamesrc },1372{"rename new ", gitdiff_renamedst },1373{"rename from ", gitdiff_renamesrc },1374{"rename to ", gitdiff_renamedst },1375{"similarity index ", gitdiff_similarity },1376{"dissimilarity index ", gitdiff_dissimilarity },1377{"index ", gitdiff_index },1378{"", gitdiff_unrecognized },1379};1380int i;13811382 len =linelen(line, size);1383if(!len || line[len-1] !='\n')1384break;1385for(i =0; i <ARRAY_SIZE(optable); i++) {1386const struct opentry *p = optable + i;1387int oplen =strlen(p->str);1388if(len < oplen ||memcmp(p->str, line, oplen))1389continue;1390if(p->fn(state, line + oplen, patch) <0)1391return offset;1392break;1393}1394}13951396return offset;1397}13981399static intparse_num(const char*line,unsigned long*p)1400{1401char*ptr;14021403if(!isdigit(*line))1404return0;1405*p =strtoul(line, &ptr,10);1406return ptr - line;1407}14081409static intparse_range(const char*line,int len,int offset,const char*expect,1410unsigned long*p1,unsigned long*p2)1411{1412int digits, ex;14131414if(offset <0|| offset >= len)1415return-1;1416 line += offset;1417 len -= offset;14181419 digits =parse_num(line, p1);1420if(!digits)1421return-1;14221423 offset += digits;1424 line += digits;1425 len -= digits;14261427*p2 =1;1428if(*line ==',') {1429 digits =parse_num(line+1, p2);1430if(!digits)1431return-1;14321433 offset += digits+1;1434 line += digits+1;1435 len -= digits+1;1436}14371438 ex =strlen(expect);1439if(ex > len)1440return-1;1441if(memcmp(line, expect, ex))1442return-1;14431444return offset + ex;1445}14461447static voidrecount_diff(const char*line,int size,struct fragment *fragment)1448{1449int oldlines =0, newlines =0, ret =0;14501451if(size <1) {1452warning("recount: ignore empty hunk");1453return;1454}14551456for(;;) {1457int len =linelen(line, size);1458 size -= len;1459 line += len;14601461if(size <1)1462break;14631464switch(*line) {1465case' ':case'\n':1466 newlines++;1467/* fall through */1468case'-':1469 oldlines++;1470continue;1471case'+':1472 newlines++;1473continue;1474case'\\':1475continue;1476case'@':1477 ret = size <3|| !starts_with(line,"@@ ");1478break;1479case'd':1480 ret = size <5|| !starts_with(line,"diff ");1481break;1482default:1483 ret = -1;1484break;1485}1486if(ret) {1487warning(_("recount: unexpected line: %.*s"),1488(int)linelen(line, size), line);1489return;1490}1491break;1492}1493 fragment->oldlines = oldlines;1494 fragment->newlines = newlines;1495}14961497/*1498 * Parse a unified diff fragment header of the1499 * form "@@ -a,b +c,d @@"1500 */1501static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1502{1503int offset;15041505if(!len || line[len-1] !='\n')1506return-1;15071508/* Figure out the number of lines in a fragment */1509 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1510 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);15111512return offset;1513}15141515static intfind_header(struct apply_state *state,1516const char*line,1517unsigned long size,1518int*hdrsize,1519struct patch *patch)1520{1521unsigned long offset, len;15221523 patch->is_toplevel_relative =0;1524 patch->is_rename = patch->is_copy =0;1525 patch->is_new = patch->is_delete = -1;1526 patch->old_mode = patch->new_mode =0;1527 patch->old_name = patch->new_name = NULL;1528for(offset =0; size >0; offset += len, size -= len, line += len, state->linenr++) {1529unsigned long nextlen;15301531 len =linelen(line, size);1532if(!len)1533break;15341535/* Testing this early allows us to take a few shortcuts.. */1536if(len <6)1537continue;15381539/*1540 * Make sure we don't find any unconnected patch fragments.1541 * That's a sign that we didn't find a header, and that a1542 * patch has become corrupted/broken up.1543 */1544if(!memcmp("@@ -", line,4)) {1545struct fragment dummy;1546if(parse_fragment_header(line, len, &dummy) <0)1547continue;1548die(_("patch fragment without header at line%d: %.*s"),1549 state->linenr, (int)len-1, line);1550}15511552if(size < len +6)1553break;15541555/*1556 * Git patch? It might not have a real patch, just a rename1557 * or mode change, so we handle that specially1558 */1559if(!memcmp("diff --git ", line,11)) {1560int git_hdr_len =parse_git_header(state, line, len, size, patch);1561if(git_hdr_len <= len)1562continue;1563if(!patch->old_name && !patch->new_name) {1564if(!patch->def_name)1565die(Q_("git diff header lacks filename information when removing "1566"%dleading pathname component (line%d)",1567"git diff header lacks filename information when removing "1568"%dleading pathname components (line%d)",1569 state->p_value),1570 state->p_value, state->linenr);1571 patch->old_name =xstrdup(patch->def_name);1572 patch->new_name =xstrdup(patch->def_name);1573}1574if(!patch->is_delete && !patch->new_name)1575die("git diff header lacks filename information "1576"(line%d)", state->linenr);1577 patch->is_toplevel_relative =1;1578*hdrsize = git_hdr_len;1579return offset;1580}15811582/* --- followed by +++ ? */1583if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1584continue;15851586/*1587 * We only accept unified patches, so we want it to1588 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1589 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1590 */1591 nextlen =linelen(line + len, size - len);1592if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1593continue;15941595/* Ok, we'll consider it a patch */1596parse_traditional_patch(state, line, line+len, patch);1597*hdrsize = len + nextlen;1598 state->linenr +=2;1599return offset;1600}1601return-1;1602}16031604static voidrecord_ws_error(struct apply_state *state,1605unsigned result,1606const char*line,1607int len,1608int linenr)1609{1610char*err;16111612if(!result)1613return;16141615 state->whitespace_error++;1616if(state->squelch_whitespace_errors &&1617 state->squelch_whitespace_errors < state->whitespace_error)1618return;16191620 err =whitespace_error_string(result);1621fprintf(stderr,"%s:%d:%s.\n%.*s\n",1622 state->patch_input_file, linenr, err, len, line);1623free(err);1624}16251626static voidcheck_whitespace(struct apply_state *state,1627const char*line,1628int len,1629unsigned ws_rule)1630{1631unsigned result =ws_check(line +1, len -1, ws_rule);16321633record_ws_error(state, result, line +1, len -2, state->linenr);1634}16351636/*1637 * Parse a unified diff. Note that this really needs to parse each1638 * fragment separately, since the only way to know the difference1639 * between a "---" that is part of a patch, and a "---" that starts1640 * the next patch is to look at the line counts..1641 */1642static intparse_fragment(struct apply_state *state,1643const char*line,1644unsigned long size,1645struct patch *patch,1646struct fragment *fragment)1647{1648int added, deleted;1649int len =linelen(line, size), offset;1650unsigned long oldlines, newlines;1651unsigned long leading, trailing;16521653 offset =parse_fragment_header(line, len, fragment);1654if(offset <0)1655return-1;1656if(offset >0&& patch->recount)1657recount_diff(line + offset, size - offset, fragment);1658 oldlines = fragment->oldlines;1659 newlines = fragment->newlines;1660 leading =0;1661 trailing =0;16621663/* Parse the thing.. */1664 line += len;1665 size -= len;1666 state->linenr++;1667 added = deleted =0;1668for(offset = len;16690< size;1670 offset += len, size -= len, line += len, state->linenr++) {1671if(!oldlines && !newlines)1672break;1673 len =linelen(line, size);1674if(!len || line[len-1] !='\n')1675return-1;1676switch(*line) {1677default:1678return-1;1679case'\n':/* newer GNU diff, an empty context line */1680case' ':1681 oldlines--;1682 newlines--;1683if(!deleted && !added)1684 leading++;1685 trailing++;1686if(!state->apply_in_reverse &&1687 state->ws_error_action == correct_ws_error)1688check_whitespace(state, line, len, patch->ws_rule);1689break;1690case'-':1691if(state->apply_in_reverse &&1692 state->ws_error_action != nowarn_ws_error)1693check_whitespace(state, line, len, patch->ws_rule);1694 deleted++;1695 oldlines--;1696 trailing =0;1697break;1698case'+':1699if(!state->apply_in_reverse &&1700 state->ws_error_action != nowarn_ws_error)1701check_whitespace(state, line, len, patch->ws_rule);1702 added++;1703 newlines--;1704 trailing =0;1705break;17061707/*1708 * We allow "\ No newline at end of file". Depending1709 * on locale settings when the patch was produced we1710 * don't know what this line looks like. The only1711 * thing we do know is that it begins with "\ ".1712 * Checking for 12 is just for sanity check -- any1713 * l10n of "\ No newline..." is at least that long.1714 */1715case'\\':1716if(len <12||memcmp(line,"\\",2))1717return-1;1718break;1719}1720}1721if(oldlines || newlines)1722return-1;1723if(!deleted && !added)1724return-1;17251726 fragment->leading = leading;1727 fragment->trailing = trailing;17281729/*1730 * If a fragment ends with an incomplete line, we failed to include1731 * it in the above loop because we hit oldlines == newlines == 01732 * before seeing it.1733 */1734if(12< size && !memcmp(line,"\\",2))1735 offset +=linelen(line, size);17361737 patch->lines_added += added;1738 patch->lines_deleted += deleted;17391740if(0< patch->is_new && oldlines)1741returnerror(_("new file depends on old contents"));1742if(0< patch->is_delete && newlines)1743returnerror(_("deleted file still has contents"));1744return offset;1745}17461747/*1748 * We have seen "diff --git a/... b/..." header (or a traditional patch1749 * header). Read hunks that belong to this patch into fragments and hang1750 * them to the given patch structure.1751 *1752 * The (fragment->patch, fragment->size) pair points into the memory given1753 * by the caller, not a copy, when we return.1754 */1755static intparse_single_patch(struct apply_state *state,1756const char*line,1757unsigned long size,1758struct patch *patch)1759{1760unsigned long offset =0;1761unsigned long oldlines =0, newlines =0, context =0;1762struct fragment **fragp = &patch->fragments;17631764while(size >4&& !memcmp(line,"@@ -",4)) {1765struct fragment *fragment;1766int len;17671768 fragment =xcalloc(1,sizeof(*fragment));1769 fragment->linenr = state->linenr;1770 len =parse_fragment(state, line, size, patch, fragment);1771if(len <=0)1772die(_("corrupt patch at line%d"), state->linenr);1773 fragment->patch = line;1774 fragment->size = len;1775 oldlines += fragment->oldlines;1776 newlines += fragment->newlines;1777 context += fragment->leading + fragment->trailing;17781779*fragp = fragment;1780 fragp = &fragment->next;17811782 offset += len;1783 line += len;1784 size -= len;1785}17861787/*1788 * If something was removed (i.e. we have old-lines) it cannot1789 * be creation, and if something was added it cannot be1790 * deletion. However, the reverse is not true; --unified=01791 * patches that only add are not necessarily creation even1792 * though they do not have any old lines, and ones that only1793 * delete are not necessarily deletion.1794 *1795 * Unfortunately, a real creation/deletion patch do _not_ have1796 * any context line by definition, so we cannot safely tell it1797 * apart with --unified=0 insanity. At least if the patch has1798 * more than one hunk it is not creation or deletion.1799 */1800if(patch->is_new <0&&1801(oldlines || (patch->fragments && patch->fragments->next)))1802 patch->is_new =0;1803if(patch->is_delete <0&&1804(newlines || (patch->fragments && patch->fragments->next)))1805 patch->is_delete =0;18061807if(0< patch->is_new && oldlines)1808die(_("new file%sdepends on old contents"), patch->new_name);1809if(0< patch->is_delete && newlines)1810die(_("deleted file%sstill has contents"), patch->old_name);1811if(!patch->is_delete && !newlines && context)1812fprintf_ln(stderr,1813_("** warning: "1814"file%sbecomes empty but is not deleted"),1815 patch->new_name);18161817return offset;1818}18191820staticinlineintmetadata_changes(struct patch *patch)1821{1822return patch->is_rename >0||1823 patch->is_copy >0||1824 patch->is_new >0||1825 patch->is_delete ||1826(patch->old_mode && patch->new_mode &&1827 patch->old_mode != patch->new_mode);1828}18291830static char*inflate_it(const void*data,unsigned long size,1831unsigned long inflated_size)1832{1833 git_zstream stream;1834void*out;1835int st;18361837memset(&stream,0,sizeof(stream));18381839 stream.next_in = (unsigned char*)data;1840 stream.avail_in = size;1841 stream.next_out = out =xmalloc(inflated_size);1842 stream.avail_out = inflated_size;1843git_inflate_init(&stream);1844 st =git_inflate(&stream, Z_FINISH);1845git_inflate_end(&stream);1846if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1847free(out);1848return NULL;1849}1850return out;1851}18521853/*1854 * Read a binary hunk and return a new fragment; fragment->patch1855 * points at an allocated memory that the caller must free, so1856 * it is marked as "->free_patch = 1".1857 */1858static struct fragment *parse_binary_hunk(struct apply_state *state,1859char**buf_p,1860unsigned long*sz_p,1861int*status_p,1862int*used_p)1863{1864/*1865 * Expect a line that begins with binary patch method ("literal"1866 * or "delta"), followed by the length of data before deflating.1867 * a sequence of 'length-byte' followed by base-85 encoded data1868 * should follow, terminated by a newline.1869 *1870 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1871 * and we would limit the patch line to 66 characters,1872 * so one line can fit up to 13 groups that would decode1873 * to 52 bytes max. The length byte 'A'-'Z' corresponds1874 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1875 */1876int llen, used;1877unsigned long size = *sz_p;1878char*buffer = *buf_p;1879int patch_method;1880unsigned long origlen;1881char*data = NULL;1882int hunk_size =0;1883struct fragment *frag;18841885 llen =linelen(buffer, size);1886 used = llen;18871888*status_p =0;18891890if(starts_with(buffer,"delta ")) {1891 patch_method = BINARY_DELTA_DEFLATED;1892 origlen =strtoul(buffer +6, NULL,10);1893}1894else if(starts_with(buffer,"literal ")) {1895 patch_method = BINARY_LITERAL_DEFLATED;1896 origlen =strtoul(buffer +8, NULL,10);1897}1898else1899return NULL;19001901 state->linenr++;1902 buffer += llen;1903while(1) {1904int byte_length, max_byte_length, newsize;1905 llen =linelen(buffer, size);1906 used += llen;1907 state->linenr++;1908if(llen ==1) {1909/* consume the blank line */1910 buffer++;1911 size--;1912break;1913}1914/*1915 * Minimum line is "A00000\n" which is 7-byte long,1916 * and the line length must be multiple of 5 plus 2.1917 */1918if((llen <7) || (llen-2) %5)1919goto corrupt;1920 max_byte_length = (llen -2) /5*4;1921 byte_length = *buffer;1922if('A'<= byte_length && byte_length <='Z')1923 byte_length = byte_length -'A'+1;1924else if('a'<= byte_length && byte_length <='z')1925 byte_length = byte_length -'a'+27;1926else1927goto corrupt;1928/* if the input length was not multiple of 4, we would1929 * have filler at the end but the filler should never1930 * exceed 3 bytes1931 */1932if(max_byte_length < byte_length ||1933 byte_length <= max_byte_length -4)1934goto corrupt;1935 newsize = hunk_size + byte_length;1936 data =xrealloc(data, newsize);1937if(decode_85(data + hunk_size, buffer +1, byte_length))1938goto corrupt;1939 hunk_size = newsize;1940 buffer += llen;1941 size -= llen;1942}19431944 frag =xcalloc(1,sizeof(*frag));1945 frag->patch =inflate_it(data, hunk_size, origlen);1946 frag->free_patch =1;1947if(!frag->patch)1948goto corrupt;1949free(data);1950 frag->size = origlen;1951*buf_p = buffer;1952*sz_p = size;1953*used_p = used;1954 frag->binary_patch_method = patch_method;1955return frag;19561957 corrupt:1958free(data);1959*status_p = -1;1960error(_("corrupt binary patch at line%d: %.*s"),1961 state->linenr-1, llen-1, buffer);1962return NULL;1963}19641965/*1966 * Returns:1967 * -1 in case of error,1968 * the length of the parsed binary patch otherwise1969 */1970static intparse_binary(struct apply_state *state,1971char*buffer,1972unsigned long size,1973struct patch *patch)1974{1975/*1976 * We have read "GIT binary patch\n"; what follows is a line1977 * that says the patch method (currently, either "literal" or1978 * "delta") and the length of data before deflating; a1979 * sequence of 'length-byte' followed by base-85 encoded data1980 * follows.1981 *1982 * When a binary patch is reversible, there is another binary1983 * hunk in the same format, starting with patch method (either1984 * "literal" or "delta") with the length of data, and a sequence1985 * of length-byte + base-85 encoded data, terminated with another1986 * empty line. This data, when applied to the postimage, produces1987 * the preimage.1988 */1989struct fragment *forward;1990struct fragment *reverse;1991int status;1992int used, used_1;19931994 forward =parse_binary_hunk(state, &buffer, &size, &status, &used);1995if(!forward && !status)1996/* there has to be one hunk (forward hunk) */1997returnerror(_("unrecognized binary patch at line%d"), state->linenr-1);1998if(status)1999/* otherwise we already gave an error message */2000return status;20012002 reverse =parse_binary_hunk(state, &buffer, &size, &status, &used_1);2003if(reverse)2004 used += used_1;2005else if(status) {2006/*2007 * Not having reverse hunk is not an error, but having2008 * a corrupt reverse hunk is.2009 */2010free((void*) forward->patch);2011free(forward);2012return status;2013}2014 forward->next = reverse;2015 patch->fragments = forward;2016 patch->is_binary =1;2017return used;2018}20192020static voidprefix_one(struct apply_state *state,char**name)2021{2022char*old_name = *name;2023if(!old_name)2024return;2025*name =xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));2026free(old_name);2027}20282029static voidprefix_patch(struct apply_state *state,struct patch *p)2030{2031if(!state->prefix || p->is_toplevel_relative)2032return;2033prefix_one(state, &p->new_name);2034prefix_one(state, &p->old_name);2035}20362037/*2038 * include/exclude2039 */20402041static voidadd_name_limit(struct apply_state *state,2042const char*name,2043int exclude)2044{2045struct string_list_item *it;20462047 it =string_list_append(&state->limit_by_name, name);2048 it->util = exclude ? NULL : (void*)1;2049}20502051static intuse_patch(struct apply_state *state,struct patch *p)2052{2053const char*pathname = p->new_name ? p->new_name : p->old_name;2054int i;20552056/* Paths outside are not touched regardless of "--include" */2057if(0< state->prefix_length) {2058int pathlen =strlen(pathname);2059if(pathlen <= state->prefix_length ||2060memcmp(state->prefix, pathname, state->prefix_length))2061return0;2062}20632064/* See if it matches any of exclude/include rule */2065for(i =0; i < state->limit_by_name.nr; i++) {2066struct string_list_item *it = &state->limit_by_name.items[i];2067if(!wildmatch(it->string, pathname,0, NULL))2068return(it->util != NULL);2069}20702071/*2072 * If we had any include, a path that does not match any rule is2073 * not used. Otherwise, we saw bunch of exclude rules (or none)2074 * and such a path is used.2075 */2076return!state->has_include;2077}207820792080/*2081 * Read the patch text in "buffer" that extends for "size" bytes; stop2082 * reading after seeing a single patch (i.e. changes to a single file).2083 * Create fragments (i.e. patch hunks) and hang them to the given patch.2084 * Return the number of bytes consumed, so that the caller can call us2085 * again for the next patch.2086 */2087static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2088{2089int hdrsize, patchsize;2090int offset =find_header(state, buffer, size, &hdrsize, patch);20912092if(offset <0)2093return offset;20942095prefix_patch(state, patch);20962097if(!use_patch(state, patch))2098 patch->ws_rule =0;2099else2100 patch->ws_rule =whitespace_rule(patch->new_name2101? patch->new_name2102: patch->old_name);21032104 patchsize =parse_single_patch(state,2105 buffer + offset + hdrsize,2106 size - offset - hdrsize,2107 patch);21082109if(!patchsize) {2110static const char git_binary[] ="GIT binary patch\n";2111int hd = hdrsize + offset;2112unsigned long llen =linelen(buffer + hd, size - hd);21132114if(llen ==sizeof(git_binary) -1&&2115!memcmp(git_binary, buffer + hd, llen)) {2116int used;2117 state->linenr++;2118 used =parse_binary(state, buffer + hd + llen,2119 size - hd - llen, patch);2120if(used <0)2121return-1;2122if(used)2123 patchsize = used + llen;2124else2125 patchsize =0;2126}2127else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2128static const char*binhdr[] = {2129"Binary files ",2130"Files ",2131 NULL,2132};2133int i;2134for(i =0; binhdr[i]; i++) {2135int len =strlen(binhdr[i]);2136if(len < size - hd &&2137!memcmp(binhdr[i], buffer + hd, len)) {2138 state->linenr++;2139 patch->is_binary =1;2140 patchsize = llen;2141break;2142}2143}2144}21452146/* Empty patch cannot be applied if it is a text patch2147 * without metadata change. A binary patch appears2148 * empty to us here.2149 */2150if((state->apply || state->check) &&2151(!patch->is_binary && !metadata_changes(patch)))2152die(_("patch with only garbage at line%d"), state->linenr);2153}21542155return offset + hdrsize + patchsize;2156}21572158#define swap(a,b) myswap((a),(b),sizeof(a))21592160#define myswap(a, b, size) do { \2161 unsigned char mytmp[size]; \2162 memcpy(mytmp, &a, size); \2163 memcpy(&a, &b, size); \2164 memcpy(&b, mytmp, size); \2165} while (0)21662167static voidreverse_patches(struct patch *p)2168{2169for(; p; p = p->next) {2170struct fragment *frag = p->fragments;21712172swap(p->new_name, p->old_name);2173swap(p->new_mode, p->old_mode);2174swap(p->is_new, p->is_delete);2175swap(p->lines_added, p->lines_deleted);2176swap(p->old_sha1_prefix, p->new_sha1_prefix);21772178for(; frag; frag = frag->next) {2179swap(frag->newpos, frag->oldpos);2180swap(frag->newlines, frag->oldlines);2181}2182}2183}21842185static const char pluses[] =2186"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2187static const char minuses[]=2188"----------------------------------------------------------------------";21892190static voidshow_stats(struct apply_state *state,struct patch *patch)2191{2192struct strbuf qname = STRBUF_INIT;2193char*cp = patch->new_name ? patch->new_name : patch->old_name;2194int max, add, del;21952196quote_c_style(cp, &qname, NULL,0);21972198/*2199 * "scale" the filename2200 */2201 max = state->max_len;2202if(max >50)2203 max =50;22042205if(qname.len > max) {2206 cp =strchr(qname.buf + qname.len +3- max,'/');2207if(!cp)2208 cp = qname.buf + qname.len +3- max;2209strbuf_splice(&qname,0, cp - qname.buf,"...",3);2210}22112212if(patch->is_binary) {2213printf(" %-*s | Bin\n", max, qname.buf);2214strbuf_release(&qname);2215return;2216}22172218printf(" %-*s |", max, qname.buf);2219strbuf_release(&qname);22202221/*2222 * scale the add/delete2223 */2224 max = max + state->max_change >70?70- max : state->max_change;2225 add = patch->lines_added;2226 del = patch->lines_deleted;22272228if(state->max_change >0) {2229int total = ((add + del) * max + state->max_change /2) / state->max_change;2230 add = (add * max + state->max_change /2) / state->max_change;2231 del = total - add;2232}2233printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2234 add, pluses, del, minuses);2235}22362237static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2238{2239switch(st->st_mode & S_IFMT) {2240case S_IFLNK:2241if(strbuf_readlink(buf, path, st->st_size) <0)2242returnerror(_("unable to read symlink%s"), path);2243return0;2244case S_IFREG:2245if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2246returnerror(_("unable to open or read%s"), path);2247convert_to_git(path, buf->buf, buf->len, buf,0);2248return0;2249default:2250return-1;2251}2252}22532254/*2255 * Update the preimage, and the common lines in postimage,2256 * from buffer buf of length len. If postlen is 0 the postimage2257 * is updated in place, otherwise it's updated on a new buffer2258 * of length postlen2259 */22602261static voidupdate_pre_post_images(struct image *preimage,2262struct image *postimage,2263char*buf,2264size_t len,size_t postlen)2265{2266int i, ctx, reduced;2267char*new, *old, *fixed;2268struct image fixed_preimage;22692270/*2271 * Update the preimage with whitespace fixes. Note that we2272 * are not losing preimage->buf -- apply_one_fragment() will2273 * free "oldlines".2274 */2275prepare_image(&fixed_preimage, buf, len,1);2276assert(postlen2277? fixed_preimage.nr == preimage->nr2278: fixed_preimage.nr <= preimage->nr);2279for(i =0; i < fixed_preimage.nr; i++)2280 fixed_preimage.line[i].flag = preimage->line[i].flag;2281free(preimage->line_allocated);2282*preimage = fixed_preimage;22832284/*2285 * Adjust the common context lines in postimage. This can be2286 * done in-place when we are shrinking it with whitespace2287 * fixing, but needs a new buffer when ignoring whitespace or2288 * expanding leading tabs to spaces.2289 *2290 * We trust the caller to tell us if the update can be done2291 * in place (postlen==0) or not.2292 */2293 old = postimage->buf;2294if(postlen)2295new= postimage->buf =xmalloc(postlen);2296else2297new= old;2298 fixed = preimage->buf;22992300for(i = reduced = ctx =0; i < postimage->nr; i++) {2301size_t l_len = postimage->line[i].len;2302if(!(postimage->line[i].flag & LINE_COMMON)) {2303/* an added line -- no counterparts in preimage */2304memmove(new, old, l_len);2305 old += l_len;2306new+= l_len;2307continue;2308}23092310/* a common context -- skip it in the original postimage */2311 old += l_len;23122313/* and find the corresponding one in the fixed preimage */2314while(ctx < preimage->nr &&2315!(preimage->line[ctx].flag & LINE_COMMON)) {2316 fixed += preimage->line[ctx].len;2317 ctx++;2318}23192320/*2321 * preimage is expected to run out, if the caller2322 * fixed addition of trailing blank lines.2323 */2324if(preimage->nr <= ctx) {2325 reduced++;2326continue;2327}23282329/* and copy it in, while fixing the line length */2330 l_len = preimage->line[ctx].len;2331memcpy(new, fixed, l_len);2332new+= l_len;2333 fixed += l_len;2334 postimage->line[i].len = l_len;2335 ctx++;2336}23372338if(postlen2339? postlen <new- postimage->buf2340: postimage->len <new- postimage->buf)2341die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2342(int)postlen, (int) postimage->len, (int)(new- postimage->buf));23432344/* Fix the length of the whole thing */2345 postimage->len =new- postimage->buf;2346 postimage->nr -= reduced;2347}23482349static intline_by_line_fuzzy_match(struct image *img,2350struct image *preimage,2351struct image *postimage,2352unsigned longtry,2353int try_lno,2354int preimage_limit)2355{2356int i;2357size_t imgoff =0;2358size_t preoff =0;2359size_t postlen = postimage->len;2360size_t extra_chars;2361char*buf;2362char*preimage_eof;2363char*preimage_end;2364struct strbuf fixed;2365char*fixed_buf;2366size_t fixed_len;23672368for(i =0; i < preimage_limit; i++) {2369size_t prelen = preimage->line[i].len;2370size_t imglen = img->line[try_lno+i].len;23712372if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2373 preimage->buf + preoff, prelen))2374return0;2375if(preimage->line[i].flag & LINE_COMMON)2376 postlen += imglen - prelen;2377 imgoff += imglen;2378 preoff += prelen;2379}23802381/*2382 * Ok, the preimage matches with whitespace fuzz.2383 *2384 * imgoff now holds the true length of the target that2385 * matches the preimage before the end of the file.2386 *2387 * Count the number of characters in the preimage that fall2388 * beyond the end of the file and make sure that all of them2389 * are whitespace characters. (This can only happen if2390 * we are removing blank lines at the end of the file.)2391 */2392 buf = preimage_eof = preimage->buf + preoff;2393for( ; i < preimage->nr; i++)2394 preoff += preimage->line[i].len;2395 preimage_end = preimage->buf + preoff;2396for( ; buf < preimage_end; buf++)2397if(!isspace(*buf))2398return0;23992400/*2401 * Update the preimage and the common postimage context2402 * lines to use the same whitespace as the target.2403 * If whitespace is missing in the target (i.e.2404 * if the preimage extends beyond the end of the file),2405 * use the whitespace from the preimage.2406 */2407 extra_chars = preimage_end - preimage_eof;2408strbuf_init(&fixed, imgoff + extra_chars);2409strbuf_add(&fixed, img->buf +try, imgoff);2410strbuf_add(&fixed, preimage_eof, extra_chars);2411 fixed_buf =strbuf_detach(&fixed, &fixed_len);2412update_pre_post_images(preimage, postimage,2413 fixed_buf, fixed_len, postlen);2414return1;2415}24162417static intmatch_fragment(struct apply_state *state,2418struct image *img,2419struct image *preimage,2420struct image *postimage,2421unsigned longtry,2422int try_lno,2423unsigned ws_rule,2424int match_beginning,int match_end)2425{2426int i;2427char*fixed_buf, *buf, *orig, *target;2428struct strbuf fixed;2429size_t fixed_len, postlen;2430int preimage_limit;24312432if(preimage->nr + try_lno <= img->nr) {2433/*2434 * The hunk falls within the boundaries of img.2435 */2436 preimage_limit = preimage->nr;2437if(match_end && (preimage->nr + try_lno != img->nr))2438return0;2439}else if(state->ws_error_action == correct_ws_error &&2440(ws_rule & WS_BLANK_AT_EOF)) {2441/*2442 * This hunk extends beyond the end of img, and we are2443 * removing blank lines at the end of the file. This2444 * many lines from the beginning of the preimage must2445 * match with img, and the remainder of the preimage2446 * must be blank.2447 */2448 preimage_limit = img->nr - try_lno;2449}else{2450/*2451 * The hunk extends beyond the end of the img and2452 * we are not removing blanks at the end, so we2453 * should reject the hunk at this position.2454 */2455return0;2456}24572458if(match_beginning && try_lno)2459return0;24602461/* Quick hash check */2462for(i =0; i < preimage_limit; i++)2463if((img->line[try_lno + i].flag & LINE_PATCHED) ||2464(preimage->line[i].hash != img->line[try_lno + i].hash))2465return0;24662467if(preimage_limit == preimage->nr) {2468/*2469 * Do we have an exact match? If we were told to match2470 * at the end, size must be exactly at try+fragsize,2471 * otherwise try+fragsize must be still within the preimage,2472 * and either case, the old piece should match the preimage2473 * exactly.2474 */2475if((match_end2476? (try+ preimage->len == img->len)2477: (try+ preimage->len <= img->len)) &&2478!memcmp(img->buf +try, preimage->buf, preimage->len))2479return1;2480}else{2481/*2482 * The preimage extends beyond the end of img, so2483 * there cannot be an exact match.2484 *2485 * There must be one non-blank context line that match2486 * a line before the end of img.2487 */2488char*buf_end;24892490 buf = preimage->buf;2491 buf_end = buf;2492for(i =0; i < preimage_limit; i++)2493 buf_end += preimage->line[i].len;24942495for( ; buf < buf_end; buf++)2496if(!isspace(*buf))2497break;2498if(buf == buf_end)2499return0;2500}25012502/*2503 * No exact match. If we are ignoring whitespace, run a line-by-line2504 * fuzzy matching. We collect all the line length information because2505 * we need it to adjust whitespace if we match.2506 */2507if(state->ws_ignore_action == ignore_ws_change)2508returnline_by_line_fuzzy_match(img, preimage, postimage,2509try, try_lno, preimage_limit);25102511if(state->ws_error_action != correct_ws_error)2512return0;25132514/*2515 * The hunk does not apply byte-by-byte, but the hash says2516 * it might with whitespace fuzz. We weren't asked to2517 * ignore whitespace, we were asked to correct whitespace2518 * errors, so let's try matching after whitespace correction.2519 *2520 * While checking the preimage against the target, whitespace2521 * errors in both fixed, we count how large the corresponding2522 * postimage needs to be. The postimage prepared by2523 * apply_one_fragment() has whitespace errors fixed on added2524 * lines already, but the common lines were propagated as-is,2525 * which may become longer when their whitespace errors are2526 * fixed.2527 */25282529/* First count added lines in postimage */2530 postlen =0;2531for(i =0; i < postimage->nr; i++) {2532if(!(postimage->line[i].flag & LINE_COMMON))2533 postlen += postimage->line[i].len;2534}25352536/*2537 * The preimage may extend beyond the end of the file,2538 * but in this loop we will only handle the part of the2539 * preimage that falls within the file.2540 */2541strbuf_init(&fixed, preimage->len +1);2542 orig = preimage->buf;2543 target = img->buf +try;2544for(i =0; i < preimage_limit; i++) {2545size_t oldlen = preimage->line[i].len;2546size_t tgtlen = img->line[try_lno + i].len;2547size_t fixstart = fixed.len;2548struct strbuf tgtfix;2549int match;25502551/* Try fixing the line in the preimage */2552ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25532554/* Try fixing the line in the target */2555strbuf_init(&tgtfix, tgtlen);2556ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);25572558/*2559 * If they match, either the preimage was based on2560 * a version before our tree fixed whitespace breakage,2561 * or we are lacking a whitespace-fix patch the tree2562 * the preimage was based on already had (i.e. target2563 * has whitespace breakage, the preimage doesn't).2564 * In either case, we are fixing the whitespace breakages2565 * so we might as well take the fix together with their2566 * real change.2567 */2568 match = (tgtfix.len == fixed.len - fixstart &&2569!memcmp(tgtfix.buf, fixed.buf + fixstart,2570 fixed.len - fixstart));25712572/* Add the length if this is common with the postimage */2573if(preimage->line[i].flag & LINE_COMMON)2574 postlen += tgtfix.len;25752576strbuf_release(&tgtfix);2577if(!match)2578goto unmatch_exit;25792580 orig += oldlen;2581 target += tgtlen;2582}258325842585/*2586 * Now handle the lines in the preimage that falls beyond the2587 * end of the file (if any). They will only match if they are2588 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2589 * false).2590 */2591for( ; i < preimage->nr; i++) {2592size_t fixstart = fixed.len;/* start of the fixed preimage */2593size_t oldlen = preimage->line[i].len;2594int j;25952596/* Try fixing the line in the preimage */2597ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25982599for(j = fixstart; j < fixed.len; j++)2600if(!isspace(fixed.buf[j]))2601goto unmatch_exit;26022603 orig += oldlen;2604}26052606/*2607 * Yes, the preimage is based on an older version that still2608 * has whitespace breakages unfixed, and fixing them makes the2609 * hunk match. Update the context lines in the postimage.2610 */2611 fixed_buf =strbuf_detach(&fixed, &fixed_len);2612if(postlen < postimage->len)2613 postlen =0;2614update_pre_post_images(preimage, postimage,2615 fixed_buf, fixed_len, postlen);2616return1;26172618 unmatch_exit:2619strbuf_release(&fixed);2620return0;2621}26222623static intfind_pos(struct apply_state *state,2624struct image *img,2625struct image *preimage,2626struct image *postimage,2627int line,2628unsigned ws_rule,2629int match_beginning,int match_end)2630{2631int i;2632unsigned long backwards, forwards,try;2633int backwards_lno, forwards_lno, try_lno;26342635/*2636 * If match_beginning or match_end is specified, there is no2637 * point starting from a wrong line that will never match and2638 * wander around and wait for a match at the specified end.2639 */2640if(match_beginning)2641 line =0;2642else if(match_end)2643 line = img->nr - preimage->nr;26442645/*2646 * Because the comparison is unsigned, the following test2647 * will also take care of a negative line number that can2648 * result when match_end and preimage is larger than the target.2649 */2650if((size_t) line > img->nr)2651 line = img->nr;26522653try=0;2654for(i =0; i < line; i++)2655try+= img->line[i].len;26562657/*2658 * There's probably some smart way to do this, but I'll leave2659 * that to the smart and beautiful people. I'm simple and stupid.2660 */2661 backwards =try;2662 backwards_lno = line;2663 forwards =try;2664 forwards_lno = line;2665 try_lno = line;26662667for(i =0; ; i++) {2668if(match_fragment(state, img, preimage, postimage,2669try, try_lno, ws_rule,2670 match_beginning, match_end))2671return try_lno;26722673 again:2674if(backwards_lno ==0&& forwards_lno == img->nr)2675break;26762677if(i &1) {2678if(backwards_lno ==0) {2679 i++;2680goto again;2681}2682 backwards_lno--;2683 backwards -= img->line[backwards_lno].len;2684try= backwards;2685 try_lno = backwards_lno;2686}else{2687if(forwards_lno == img->nr) {2688 i++;2689goto again;2690}2691 forwards += img->line[forwards_lno].len;2692 forwards_lno++;2693try= forwards;2694 try_lno = forwards_lno;2695}26962697}2698return-1;2699}27002701static voidremove_first_line(struct image *img)2702{2703 img->buf += img->line[0].len;2704 img->len -= img->line[0].len;2705 img->line++;2706 img->nr--;2707}27082709static voidremove_last_line(struct image *img)2710{2711 img->len -= img->line[--img->nr].len;2712}27132714/*2715 * The change from "preimage" and "postimage" has been found to2716 * apply at applied_pos (counts in line numbers) in "img".2717 * Update "img" to remove "preimage" and replace it with "postimage".2718 */2719static voidupdate_image(struct apply_state *state,2720struct image *img,2721int applied_pos,2722struct image *preimage,2723struct image *postimage)2724{2725/*2726 * remove the copy of preimage at offset in img2727 * and replace it with postimage2728 */2729int i, nr;2730size_t remove_count, insert_count, applied_at =0;2731char*result;2732int preimage_limit;27332734/*2735 * If we are removing blank lines at the end of img,2736 * the preimage may extend beyond the end.2737 * If that is the case, we must be careful only to2738 * remove the part of the preimage that falls within2739 * the boundaries of img. Initialize preimage_limit2740 * to the number of lines in the preimage that falls2741 * within the boundaries.2742 */2743 preimage_limit = preimage->nr;2744if(preimage_limit > img->nr - applied_pos)2745 preimage_limit = img->nr - applied_pos;27462747for(i =0; i < applied_pos; i++)2748 applied_at += img->line[i].len;27492750 remove_count =0;2751for(i =0; i < preimage_limit; i++)2752 remove_count += img->line[applied_pos + i].len;2753 insert_count = postimage->len;27542755/* Adjust the contents */2756 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2757memcpy(result, img->buf, applied_at);2758memcpy(result + applied_at, postimage->buf, postimage->len);2759memcpy(result + applied_at + postimage->len,2760 img->buf + (applied_at + remove_count),2761 img->len - (applied_at + remove_count));2762free(img->buf);2763 img->buf = result;2764 img->len += insert_count - remove_count;2765 result[img->len] ='\0';27662767/* Adjust the line table */2768 nr = img->nr + postimage->nr - preimage_limit;2769if(preimage_limit < postimage->nr) {2770/*2771 * NOTE: this knows that we never call remove_first_line()2772 * on anything other than pre/post image.2773 */2774REALLOC_ARRAY(img->line, nr);2775 img->line_allocated = img->line;2776}2777if(preimage_limit != postimage->nr)2778memmove(img->line + applied_pos + postimage->nr,2779 img->line + applied_pos + preimage_limit,2780(img->nr - (applied_pos + preimage_limit)) *2781sizeof(*img->line));2782memcpy(img->line + applied_pos,2783 postimage->line,2784 postimage->nr *sizeof(*img->line));2785if(!state->allow_overlap)2786for(i =0; i < postimage->nr; i++)2787 img->line[applied_pos + i].flag |= LINE_PATCHED;2788 img->nr = nr;2789}27902791/*2792 * Use the patch-hunk text in "frag" to prepare two images (preimage and2793 * postimage) for the hunk. Find lines that match "preimage" in "img" and2794 * replace the part of "img" with "postimage" text.2795 */2796static intapply_one_fragment(struct apply_state *state,2797struct image *img,struct fragment *frag,2798int inaccurate_eof,unsigned ws_rule,2799int nth_fragment)2800{2801int match_beginning, match_end;2802const char*patch = frag->patch;2803int size = frag->size;2804char*old, *oldlines;2805struct strbuf newlines;2806int new_blank_lines_at_end =0;2807int found_new_blank_lines_at_end =0;2808int hunk_linenr = frag->linenr;2809unsigned long leading, trailing;2810int pos, applied_pos;2811struct image preimage;2812struct image postimage;28132814memset(&preimage,0,sizeof(preimage));2815memset(&postimage,0,sizeof(postimage));2816 oldlines =xmalloc(size);2817strbuf_init(&newlines, size);28182819 old = oldlines;2820while(size >0) {2821char first;2822int len =linelen(patch, size);2823int plen;2824int added_blank_line =0;2825int is_blank_context =0;2826size_t start;28272828if(!len)2829break;28302831/*2832 * "plen" is how much of the line we should use for2833 * the actual patch data. Normally we just remove the2834 * first character on the line, but if the line is2835 * followed by "\ No newline", then we also remove the2836 * last one (which is the newline, of course).2837 */2838 plen = len -1;2839if(len < size && patch[len] =='\\')2840 plen--;2841 first = *patch;2842if(state->apply_in_reverse) {2843if(first =='-')2844 first ='+';2845else if(first =='+')2846 first ='-';2847}28482849switch(first) {2850case'\n':2851/* Newer GNU diff, empty context line */2852if(plen <0)2853/* ... followed by '\No newline'; nothing */2854break;2855*old++ ='\n';2856strbuf_addch(&newlines,'\n');2857add_line_info(&preimage,"\n",1, LINE_COMMON);2858add_line_info(&postimage,"\n",1, LINE_COMMON);2859 is_blank_context =1;2860break;2861case' ':2862if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2863ws_blank_line(patch +1, plen, ws_rule))2864 is_blank_context =1;2865case'-':2866memcpy(old, patch +1, plen);2867add_line_info(&preimage, old, plen,2868(first ==' '? LINE_COMMON :0));2869 old += plen;2870if(first =='-')2871break;2872/* Fall-through for ' ' */2873case'+':2874/* --no-add does not add new lines */2875if(first =='+'&& state->no_add)2876break;28772878 start = newlines.len;2879if(first !='+'||2880!state->whitespace_error ||2881 state->ws_error_action != correct_ws_error) {2882strbuf_add(&newlines, patch +1, plen);2883}2884else{2885ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2886}2887add_line_info(&postimage, newlines.buf + start, newlines.len - start,2888(first =='+'?0: LINE_COMMON));2889if(first =='+'&&2890(ws_rule & WS_BLANK_AT_EOF) &&2891ws_blank_line(patch +1, plen, ws_rule))2892 added_blank_line =1;2893break;2894case'@':case'\\':2895/* Ignore it, we already handled it */2896break;2897default:2898if(state->apply_verbosely)2899error(_("invalid start of line: '%c'"), first);2900 applied_pos = -1;2901goto out;2902}2903if(added_blank_line) {2904if(!new_blank_lines_at_end)2905 found_new_blank_lines_at_end = hunk_linenr;2906 new_blank_lines_at_end++;2907}2908else if(is_blank_context)2909;2910else2911 new_blank_lines_at_end =0;2912 patch += len;2913 size -= len;2914 hunk_linenr++;2915}2916if(inaccurate_eof &&2917 old > oldlines && old[-1] =='\n'&&2918 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2919 old--;2920strbuf_setlen(&newlines, newlines.len -1);2921}29222923 leading = frag->leading;2924 trailing = frag->trailing;29252926/*2927 * A hunk to change lines at the beginning would begin with2928 * @@ -1,L +N,M @@2929 * but we need to be careful. -U0 that inserts before the second2930 * line also has this pattern.2931 *2932 * And a hunk to add to an empty file would begin with2933 * @@ -0,0 +N,M @@2934 *2935 * In other words, a hunk that is (frag->oldpos <= 1) with or2936 * without leading context must match at the beginning.2937 */2938 match_beginning = (!frag->oldpos ||2939(frag->oldpos ==1&& !state->unidiff_zero));29402941/*2942 * A hunk without trailing lines must match at the end.2943 * However, we simply cannot tell if a hunk must match end2944 * from the lack of trailing lines if the patch was generated2945 * with unidiff without any context.2946 */2947 match_end = !state->unidiff_zero && !trailing;29482949 pos = frag->newpos ? (frag->newpos -1) :0;2950 preimage.buf = oldlines;2951 preimage.len = old - oldlines;2952 postimage.buf = newlines.buf;2953 postimage.len = newlines.len;2954 preimage.line = preimage.line_allocated;2955 postimage.line = postimage.line_allocated;29562957for(;;) {29582959 applied_pos =find_pos(state, img, &preimage, &postimage, pos,2960 ws_rule, match_beginning, match_end);29612962if(applied_pos >=0)2963break;29642965/* Am I at my context limits? */2966if((leading <= state->p_context) && (trailing <= state->p_context))2967break;2968if(match_beginning || match_end) {2969 match_beginning = match_end =0;2970continue;2971}29722973/*2974 * Reduce the number of context lines; reduce both2975 * leading and trailing if they are equal otherwise2976 * just reduce the larger context.2977 */2978if(leading >= trailing) {2979remove_first_line(&preimage);2980remove_first_line(&postimage);2981 pos--;2982 leading--;2983}2984if(trailing > leading) {2985remove_last_line(&preimage);2986remove_last_line(&postimage);2987 trailing--;2988}2989}29902991if(applied_pos >=0) {2992if(new_blank_lines_at_end &&2993 preimage.nr + applied_pos >= img->nr &&2994(ws_rule & WS_BLANK_AT_EOF) &&2995 state->ws_error_action != nowarn_ws_error) {2996record_ws_error(state, WS_BLANK_AT_EOF,"+",1,2997 found_new_blank_lines_at_end);2998if(state->ws_error_action == correct_ws_error) {2999while(new_blank_lines_at_end--)3000remove_last_line(&postimage);3001}3002/*3003 * We would want to prevent write_out_results()3004 * from taking place in apply_patch() that follows3005 * the callchain led us here, which is:3006 * apply_patch->check_patch_list->check_patch->3007 * apply_data->apply_fragments->apply_one_fragment3008 */3009if(state->ws_error_action == die_on_ws_error)3010 state->apply =0;3011}30123013if(state->apply_verbosely && applied_pos != pos) {3014int offset = applied_pos - pos;3015if(state->apply_in_reverse)3016 offset =0- offset;3017fprintf_ln(stderr,3018Q_("Hunk #%dsucceeded at%d(offset%dline).",3019"Hunk #%dsucceeded at%d(offset%dlines).",3020 offset),3021 nth_fragment, applied_pos +1, offset);3022}30233024/*3025 * Warn if it was necessary to reduce the number3026 * of context lines.3027 */3028if((leading != frag->leading) ||3029(trailing != frag->trailing))3030fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"3031" to apply fragment at%d"),3032 leading, trailing, applied_pos+1);3033update_image(state, img, applied_pos, &preimage, &postimage);3034}else{3035if(state->apply_verbosely)3036error(_("while searching for:\n%.*s"),3037(int)(old - oldlines), oldlines);3038}30393040out:3041free(oldlines);3042strbuf_release(&newlines);3043free(preimage.line_allocated);3044free(postimage.line_allocated);30453046return(applied_pos <0);3047}30483049static intapply_binary_fragment(struct apply_state *state,3050struct image *img,3051struct patch *patch)3052{3053struct fragment *fragment = patch->fragments;3054unsigned long len;3055void*dst;30563057if(!fragment)3058returnerror(_("missing binary patch data for '%s'"),3059 patch->new_name ?3060 patch->new_name :3061 patch->old_name);30623063/* Binary patch is irreversible without the optional second hunk */3064if(state->apply_in_reverse) {3065if(!fragment->next)3066returnerror("cannot reverse-apply a binary patch "3067"without the reverse hunk to '%s'",3068 patch->new_name3069? patch->new_name : patch->old_name);3070 fragment = fragment->next;3071}3072switch(fragment->binary_patch_method) {3073case BINARY_DELTA_DEFLATED:3074 dst =patch_delta(img->buf, img->len, fragment->patch,3075 fragment->size, &len);3076if(!dst)3077return-1;3078clear_image(img);3079 img->buf = dst;3080 img->len = len;3081return0;3082case BINARY_LITERAL_DEFLATED:3083clear_image(img);3084 img->len = fragment->size;3085 img->buf =xmemdupz(fragment->patch, img->len);3086return0;3087}3088return-1;3089}30903091/*3092 * Replace "img" with the result of applying the binary patch.3093 * The binary patch data itself in patch->fragment is still kept3094 * but the preimage prepared by the caller in "img" is freed here3095 * or in the helper function apply_binary_fragment() this calls.3096 */3097static intapply_binary(struct apply_state *state,3098struct image *img,3099struct patch *patch)3100{3101const char*name = patch->old_name ? patch->old_name : patch->new_name;3102unsigned char sha1[20];31033104/*3105 * For safety, we require patch index line to contain3106 * full 40-byte textual SHA1 for old and new, at least for now.3107 */3108if(strlen(patch->old_sha1_prefix) !=40||3109strlen(patch->new_sha1_prefix) !=40||3110get_sha1_hex(patch->old_sha1_prefix, sha1) ||3111get_sha1_hex(patch->new_sha1_prefix, sha1))3112returnerror("cannot apply binary patch to '%s' "3113"without full index line", name);31143115if(patch->old_name) {3116/*3117 * See if the old one matches what the patch3118 * applies to.3119 */3120hash_sha1_file(img->buf, img->len, blob_type, sha1);3121if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3122returnerror("the patch applies to '%s' (%s), "3123"which does not match the "3124"current contents.",3125 name,sha1_to_hex(sha1));3126}3127else{3128/* Otherwise, the old one must be empty. */3129if(img->len)3130returnerror("the patch applies to an empty "3131"'%s' but it is not empty", name);3132}31333134get_sha1_hex(patch->new_sha1_prefix, sha1);3135if(is_null_sha1(sha1)) {3136clear_image(img);3137return0;/* deletion patch */3138}31393140if(has_sha1_file(sha1)) {3141/* We already have the postimage */3142enum object_type type;3143unsigned long size;3144char*result;31453146 result =read_sha1_file(sha1, &type, &size);3147if(!result)3148returnerror("the necessary postimage%sfor "3149"'%s' cannot be read",3150 patch->new_sha1_prefix, name);3151clear_image(img);3152 img->buf = result;3153 img->len = size;3154}else{3155/*3156 * We have verified buf matches the preimage;3157 * apply the patch data to it, which is stored3158 * in the patch->fragments->{patch,size}.3159 */3160if(apply_binary_fragment(state, img, patch))3161returnerror(_("binary patch does not apply to '%s'"),3162 name);31633164/* verify that the result matches */3165hash_sha1_file(img->buf, img->len, blob_type, sha1);3166if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3167returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3168 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3169}31703171return0;3172}31733174static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3175{3176struct fragment *frag = patch->fragments;3177const char*name = patch->old_name ? patch->old_name : patch->new_name;3178unsigned ws_rule = patch->ws_rule;3179unsigned inaccurate_eof = patch->inaccurate_eof;3180int nth =0;31813182if(patch->is_binary)3183returnapply_binary(state, img, patch);31843185while(frag) {3186 nth++;3187if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3188error(_("patch failed:%s:%ld"), name, frag->oldpos);3189if(!state->apply_with_reject)3190return-1;3191 frag->rejected =1;3192}3193 frag = frag->next;3194}3195return0;3196}31973198static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3199{3200if(S_ISGITLINK(mode)) {3201strbuf_grow(buf,100);3202strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3203}else{3204enum object_type type;3205unsigned long sz;3206char*result;32073208 result =read_sha1_file(sha1, &type, &sz);3209if(!result)3210return-1;3211/* XXX read_sha1_file NUL-terminates */3212strbuf_attach(buf, result, sz, sz +1);3213}3214return0;3215}32163217static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3218{3219if(!ce)3220return0;3221returnread_blob_object(buf, ce->sha1, ce->ce_mode);3222}32233224static struct patch *in_fn_table(struct apply_state *state,const char*name)3225{3226struct string_list_item *item;32273228if(name == NULL)3229return NULL;32303231 item =string_list_lookup(&state->fn_table, name);3232if(item != NULL)3233return(struct patch *)item->util;32343235return NULL;3236}32373238/*3239 * item->util in the filename table records the status of the path.3240 * Usually it points at a patch (whose result records the contents3241 * of it after applying it), but it could be PATH_WAS_DELETED for a3242 * path that a previously applied patch has already removed, or3243 * PATH_TO_BE_DELETED for a path that a later patch would remove.3244 *3245 * The latter is needed to deal with a case where two paths A and B3246 * are swapped by first renaming A to B and then renaming B to A;3247 * moving A to B should not be prevented due to presence of B as we3248 * will remove it in a later patch.3249 */3250#define PATH_TO_BE_DELETED ((struct patch *) -2)3251#define PATH_WAS_DELETED ((struct patch *) -1)32523253static intto_be_deleted(struct patch *patch)3254{3255return patch == PATH_TO_BE_DELETED;3256}32573258static intwas_deleted(struct patch *patch)3259{3260return patch == PATH_WAS_DELETED;3261}32623263static voidadd_to_fn_table(struct apply_state *state,struct patch *patch)3264{3265struct string_list_item *item;32663267/*3268 * Always add new_name unless patch is a deletion3269 * This should cover the cases for normal diffs,3270 * file creations and copies3271 */3272if(patch->new_name != NULL) {3273 item =string_list_insert(&state->fn_table, patch->new_name);3274 item->util = patch;3275}32763277/*3278 * store a failure on rename/deletion cases because3279 * later chunks shouldn't patch old names3280 */3281if((patch->new_name == NULL) || (patch->is_rename)) {3282 item =string_list_insert(&state->fn_table, patch->old_name);3283 item->util = PATH_WAS_DELETED;3284}3285}32863287static voidprepare_fn_table(struct apply_state *state,struct patch *patch)3288{3289/*3290 * store information about incoming file deletion3291 */3292while(patch) {3293if((patch->new_name == NULL) || (patch->is_rename)) {3294struct string_list_item *item;3295 item =string_list_insert(&state->fn_table, patch->old_name);3296 item->util = PATH_TO_BE_DELETED;3297}3298 patch = patch->next;3299}3300}33013302static intcheckout_target(struct index_state *istate,3303struct cache_entry *ce,struct stat *st)3304{3305struct checkout costate;33063307memset(&costate,0,sizeof(costate));3308 costate.base_dir ="";3309 costate.refresh_cache =1;3310 costate.istate = istate;3311if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3312returnerror(_("cannot checkout%s"), ce->name);3313return0;3314}33153316static struct patch *previous_patch(struct apply_state *state,3317struct patch *patch,3318int*gone)3319{3320struct patch *previous;33213322*gone =0;3323if(patch->is_copy || patch->is_rename)3324return NULL;/* "git" patches do not depend on the order */33253326 previous =in_fn_table(state, patch->old_name);3327if(!previous)3328return NULL;33293330if(to_be_deleted(previous))3331return NULL;/* the deletion hasn't happened yet */33323333if(was_deleted(previous))3334*gone =1;33353336return previous;3337}33383339static intverify_index_match(const struct cache_entry *ce,struct stat *st)3340{3341if(S_ISGITLINK(ce->ce_mode)) {3342if(!S_ISDIR(st->st_mode))3343return-1;3344return0;3345}3346returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3347}33483349#define SUBMODULE_PATCH_WITHOUT_INDEX 133503351static intload_patch_target(struct apply_state *state,3352struct strbuf *buf,3353const struct cache_entry *ce,3354struct stat *st,3355const char*name,3356unsigned expected_mode)3357{3358if(state->cached || state->check_index) {3359if(read_file_or_gitlink(ce, buf))3360returnerror(_("read of%sfailed"), name);3361}else if(name) {3362if(S_ISGITLINK(expected_mode)) {3363if(ce)3364returnread_file_or_gitlink(ce, buf);3365else3366return SUBMODULE_PATCH_WITHOUT_INDEX;3367}else if(has_symlink_leading_path(name,strlen(name))) {3368returnerror(_("reading from '%s' beyond a symbolic link"), name);3369}else{3370if(read_old_data(st, name, buf))3371returnerror(_("read of%sfailed"), name);3372}3373}3374return0;3375}33763377/*3378 * We are about to apply "patch"; populate the "image" with the3379 * current version we have, from the working tree or from the index,3380 * depending on the situation e.g. --cached/--index. If we are3381 * applying a non-git patch that incrementally updates the tree,3382 * we read from the result of a previous diff.3383 */3384static intload_preimage(struct apply_state *state,3385struct image *image,3386struct patch *patch,struct stat *st,3387const struct cache_entry *ce)3388{3389struct strbuf buf = STRBUF_INIT;3390size_t len;3391char*img;3392struct patch *previous;3393int status;33943395 previous =previous_patch(state, patch, &status);3396if(status)3397returnerror(_("path%shas been renamed/deleted"),3398 patch->old_name);3399if(previous) {3400/* We have a patched copy in memory; use that. */3401strbuf_add(&buf, previous->result, previous->resultsize);3402}else{3403 status =load_patch_target(state, &buf, ce, st,3404 patch->old_name, patch->old_mode);3405if(status <0)3406return status;3407else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3408/*3409 * There is no way to apply subproject3410 * patch without looking at the index.3411 * NEEDSWORK: shouldn't this be flagged3412 * as an error???3413 */3414free_fragment_list(patch->fragments);3415 patch->fragments = NULL;3416}else if(status) {3417returnerror(_("read of%sfailed"), patch->old_name);3418}3419}34203421 img =strbuf_detach(&buf, &len);3422prepare_image(image, img, len, !patch->is_binary);3423return0;3424}34253426static intthree_way_merge(struct image *image,3427char*path,3428const unsigned char*base,3429const unsigned char*ours,3430const unsigned char*theirs)3431{3432 mmfile_t base_file, our_file, their_file;3433 mmbuffer_t result = { NULL };3434int status;34353436read_mmblob(&base_file, base);3437read_mmblob(&our_file, ours);3438read_mmblob(&their_file, theirs);3439 status =ll_merge(&result, path,3440&base_file,"base",3441&our_file,"ours",3442&their_file,"theirs", NULL);3443free(base_file.ptr);3444free(our_file.ptr);3445free(their_file.ptr);3446if(status <0|| !result.ptr) {3447free(result.ptr);3448return-1;3449}3450clear_image(image);3451 image->buf = result.ptr;3452 image->len = result.size;34533454return status;3455}34563457/*3458 * When directly falling back to add/add three-way merge, we read from3459 * the current contents of the new_name. In no cases other than that3460 * this function will be called.3461 */3462static intload_current(struct apply_state *state,3463struct image *image,3464struct patch *patch)3465{3466struct strbuf buf = STRBUF_INIT;3467int status, pos;3468size_t len;3469char*img;3470struct stat st;3471struct cache_entry *ce;3472char*name = patch->new_name;3473unsigned mode = patch->new_mode;34743475if(!patch->is_new)3476die("BUG: patch to%sis not a creation", patch->old_name);34773478 pos =cache_name_pos(name,strlen(name));3479if(pos <0)3480returnerror(_("%s: does not exist in index"), name);3481 ce = active_cache[pos];3482if(lstat(name, &st)) {3483if(errno != ENOENT)3484returnerror(_("%s:%s"), name,strerror(errno));3485if(checkout_target(&the_index, ce, &st))3486return-1;3487}3488if(verify_index_match(ce, &st))3489returnerror(_("%s: does not match index"), name);34903491 status =load_patch_target(state, &buf, ce, &st, name, mode);3492if(status <0)3493return status;3494else if(status)3495return-1;3496 img =strbuf_detach(&buf, &len);3497prepare_image(image, img, len, !patch->is_binary);3498return0;3499}35003501static inttry_threeway(struct apply_state *state,3502struct image *image,3503struct patch *patch,3504struct stat *st,3505const struct cache_entry *ce)3506{3507unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3508struct strbuf buf = STRBUF_INIT;3509size_t len;3510int status;3511char*img;3512struct image tmp_image;35133514/* No point falling back to 3-way merge in these cases */3515if(patch->is_delete ||3516S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3517return-1;35183519/* Preimage the patch was prepared for */3520if(patch->is_new)3521write_sha1_file("",0, blob_type, pre_sha1);3522else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3523read_blob_object(&buf, pre_sha1, patch->old_mode))3524returnerror("repository lacks the necessary blob to fall back on 3-way merge.");35253526fprintf(stderr,"Falling back to three-way merge...\n");35273528 img =strbuf_detach(&buf, &len);3529prepare_image(&tmp_image, img, len,1);3530/* Apply the patch to get the post image */3531if(apply_fragments(state, &tmp_image, patch) <0) {3532clear_image(&tmp_image);3533return-1;3534}3535/* post_sha1[] is theirs */3536write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3537clear_image(&tmp_image);35383539/* our_sha1[] is ours */3540if(patch->is_new) {3541if(load_current(state, &tmp_image, patch))3542returnerror("cannot read the current contents of '%s'",3543 patch->new_name);3544}else{3545if(load_preimage(state, &tmp_image, patch, st, ce))3546returnerror("cannot read the current contents of '%s'",3547 patch->old_name);3548}3549write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3550clear_image(&tmp_image);35513552/* in-core three-way merge between post and our using pre as base */3553 status =three_way_merge(image, patch->new_name,3554 pre_sha1, our_sha1, post_sha1);3555if(status <0) {3556fprintf(stderr,"Failed to fall back on three-way merge...\n");3557return status;3558}35593560if(status) {3561 patch->conflicted_threeway =1;3562if(patch->is_new)3563oidclr(&patch->threeway_stage[0]);3564else3565hashcpy(patch->threeway_stage[0].hash, pre_sha1);3566hashcpy(patch->threeway_stage[1].hash, our_sha1);3567hashcpy(patch->threeway_stage[2].hash, post_sha1);3568fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3569}else{3570fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3571}3572return0;3573}35743575static intapply_data(struct apply_state *state,struct patch *patch,3576struct stat *st,const struct cache_entry *ce)3577{3578struct image image;35793580if(load_preimage(state, &image, patch, st, ce) <0)3581return-1;35823583if(patch->direct_to_threeway ||3584apply_fragments(state, &image, patch) <0) {3585/* Note: with --reject, apply_fragments() returns 0 */3586if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3587return-1;3588}3589 patch->result = image.buf;3590 patch->resultsize = image.len;3591add_to_fn_table(state, patch);3592free(image.line_allocated);35933594if(0< patch->is_delete && patch->resultsize)3595returnerror(_("removal patch leaves file contents"));35963597return0;3598}35993600/*3601 * If "patch" that we are looking at modifies or deletes what we have,3602 * we would want it not to lose any local modification we have, either3603 * in the working tree or in the index.3604 *3605 * This also decides if a non-git patch is a creation patch or a3606 * modification to an existing empty file. We do not check the state3607 * of the current tree for a creation patch in this function; the caller3608 * check_patch() separately makes sure (and errors out otherwise) that3609 * the path the patch creates does not exist in the current tree.3610 */3611static intcheck_preimage(struct apply_state *state,3612struct patch *patch,3613struct cache_entry **ce,3614struct stat *st)3615{3616const char*old_name = patch->old_name;3617struct patch *previous = NULL;3618int stat_ret =0, status;3619unsigned st_mode =0;36203621if(!old_name)3622return0;36233624assert(patch->is_new <=0);3625 previous =previous_patch(state, patch, &status);36263627if(status)3628returnerror(_("path%shas been renamed/deleted"), old_name);3629if(previous) {3630 st_mode = previous->new_mode;3631}else if(!state->cached) {3632 stat_ret =lstat(old_name, st);3633if(stat_ret && errno != ENOENT)3634returnerror(_("%s:%s"), old_name,strerror(errno));3635}36363637if(state->check_index && !previous) {3638int pos =cache_name_pos(old_name,strlen(old_name));3639if(pos <0) {3640if(patch->is_new <0)3641goto is_new;3642returnerror(_("%s: does not exist in index"), old_name);3643}3644*ce = active_cache[pos];3645if(stat_ret <0) {3646if(checkout_target(&the_index, *ce, st))3647return-1;3648}3649if(!state->cached &&verify_index_match(*ce, st))3650returnerror(_("%s: does not match index"), old_name);3651if(state->cached)3652 st_mode = (*ce)->ce_mode;3653}else if(stat_ret <0) {3654if(patch->is_new <0)3655goto is_new;3656returnerror(_("%s:%s"), old_name,strerror(errno));3657}36583659if(!state->cached && !previous)3660 st_mode =ce_mode_from_stat(*ce, st->st_mode);36613662if(patch->is_new <0)3663 patch->is_new =0;3664if(!patch->old_mode)3665 patch->old_mode = st_mode;3666if((st_mode ^ patch->old_mode) & S_IFMT)3667returnerror(_("%s: wrong type"), old_name);3668if(st_mode != patch->old_mode)3669warning(_("%shas type%o, expected%o"),3670 old_name, st_mode, patch->old_mode);3671if(!patch->new_mode && !patch->is_delete)3672 patch->new_mode = st_mode;3673return0;36743675 is_new:3676 patch->is_new =1;3677 patch->is_delete =0;3678free(patch->old_name);3679 patch->old_name = NULL;3680return0;3681}368236833684#define EXISTS_IN_INDEX 13685#define EXISTS_IN_WORKTREE 236863687static intcheck_to_create(struct apply_state *state,3688const char*new_name,3689int ok_if_exists)3690{3691struct stat nst;36923693if(state->check_index &&3694cache_name_pos(new_name,strlen(new_name)) >=0&&3695!ok_if_exists)3696return EXISTS_IN_INDEX;3697if(state->cached)3698return0;36993700if(!lstat(new_name, &nst)) {3701if(S_ISDIR(nst.st_mode) || ok_if_exists)3702return0;3703/*3704 * A leading component of new_name might be a symlink3705 * that is going to be removed with this patch, but3706 * still pointing at somewhere that has the path.3707 * In such a case, path "new_name" does not exist as3708 * far as git is concerned.3709 */3710if(has_symlink_leading_path(new_name,strlen(new_name)))3711return0;37123713return EXISTS_IN_WORKTREE;3714}else if((errno != ENOENT) && (errno != ENOTDIR)) {3715returnerror("%s:%s", new_name,strerror(errno));3716}3717return0;3718}37193720static uintptr_tregister_symlink_changes(struct apply_state *state,3721const char*path,3722uintptr_t what)3723{3724struct string_list_item *ent;37253726 ent =string_list_lookup(&state->symlink_changes, path);3727if(!ent) {3728 ent =string_list_insert(&state->symlink_changes, path);3729 ent->util = (void*)0;3730}3731 ent->util = (void*)(what | ((uintptr_t)ent->util));3732return(uintptr_t)ent->util;3733}37343735static uintptr_tcheck_symlink_changes(struct apply_state *state,const char*path)3736{3737struct string_list_item *ent;37383739 ent =string_list_lookup(&state->symlink_changes, path);3740if(!ent)3741return0;3742return(uintptr_t)ent->util;3743}37443745static voidprepare_symlink_changes(struct apply_state *state,struct patch *patch)3746{3747for( ; patch; patch = patch->next) {3748if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3749(patch->is_rename || patch->is_delete))3750/* the symlink at patch->old_name is removed */3751register_symlink_changes(state, patch->old_name, SYMLINK_GOES_AWAY);37523753if(patch->new_name &&S_ISLNK(patch->new_mode))3754/* the symlink at patch->new_name is created or remains */3755register_symlink_changes(state, patch->new_name, SYMLINK_IN_RESULT);3756}3757}37583759static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3760{3761do{3762unsigned int change;37633764while(--name->len && name->buf[name->len] !='/')3765;/* scan backwards */3766if(!name->len)3767break;3768 name->buf[name->len] ='\0';3769 change =check_symlink_changes(state, name->buf);3770if(change & SYMLINK_IN_RESULT)3771return1;3772if(change & SYMLINK_GOES_AWAY)3773/*3774 * This cannot be "return 0", because we may3775 * see a new one created at a higher level.3776 */3777continue;37783779/* otherwise, check the preimage */3780if(state->check_index) {3781struct cache_entry *ce;37823783 ce =cache_file_exists(name->buf, name->len, ignore_case);3784if(ce &&S_ISLNK(ce->ce_mode))3785return1;3786}else{3787struct stat st;3788if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3789return1;3790}3791}while(1);3792return0;3793}37943795static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3796{3797int ret;3798struct strbuf name = STRBUF_INIT;37993800assert(*name_ !='\0');3801strbuf_addstr(&name, name_);3802 ret =path_is_beyond_symlink_1(state, &name);3803strbuf_release(&name);38043805return ret;3806}38073808static voiddie_on_unsafe_path(struct patch *patch)3809{3810const char*old_name = NULL;3811const char*new_name = NULL;3812if(patch->is_delete)3813 old_name = patch->old_name;3814else if(!patch->is_new && !patch->is_copy)3815 old_name = patch->old_name;3816if(!patch->is_delete)3817 new_name = patch->new_name;38183819if(old_name && !verify_path(old_name))3820die(_("invalid path '%s'"), old_name);3821if(new_name && !verify_path(new_name))3822die(_("invalid path '%s'"), new_name);3823}38243825/*3826 * Check and apply the patch in-core; leave the result in patch->result3827 * for the caller to write it out to the final destination.3828 */3829static intcheck_patch(struct apply_state *state,struct patch *patch)3830{3831struct stat st;3832const char*old_name = patch->old_name;3833const char*new_name = patch->new_name;3834const char*name = old_name ? old_name : new_name;3835struct cache_entry *ce = NULL;3836struct patch *tpatch;3837int ok_if_exists;3838int status;38393840 patch->rejected =1;/* we will drop this after we succeed */38413842 status =check_preimage(state, patch, &ce, &st);3843if(status)3844return status;3845 old_name = patch->old_name;38463847/*3848 * A type-change diff is always split into a patch to delete3849 * old, immediately followed by a patch to create new (see3850 * diff.c::run_diff()); in such a case it is Ok that the entry3851 * to be deleted by the previous patch is still in the working3852 * tree and in the index.3853 *3854 * A patch to swap-rename between A and B would first rename A3855 * to B and then rename B to A. While applying the first one,3856 * the presence of B should not stop A from getting renamed to3857 * B; ask to_be_deleted() about the later rename. Removal of3858 * B and rename from A to B is handled the same way by asking3859 * was_deleted().3860 */3861if((tpatch =in_fn_table(state, new_name)) &&3862(was_deleted(tpatch) ||to_be_deleted(tpatch)))3863 ok_if_exists =1;3864else3865 ok_if_exists =0;38663867if(new_name &&3868((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3869int err =check_to_create(state, new_name, ok_if_exists);38703871if(err && state->threeway) {3872 patch->direct_to_threeway =1;3873}else switch(err) {3874case0:3875break;/* happy */3876case EXISTS_IN_INDEX:3877returnerror(_("%s: already exists in index"), new_name);3878break;3879case EXISTS_IN_WORKTREE:3880returnerror(_("%s: already exists in working directory"),3881 new_name);3882default:3883return err;3884}38853886if(!patch->new_mode) {3887if(0< patch->is_new)3888 patch->new_mode = S_IFREG |0644;3889else3890 patch->new_mode = patch->old_mode;3891}3892}38933894if(new_name && old_name) {3895int same = !strcmp(old_name, new_name);3896if(!patch->new_mode)3897 patch->new_mode = patch->old_mode;3898if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3899if(same)3900returnerror(_("new mode (%o) of%sdoes not "3901"match old mode (%o)"),3902 patch->new_mode, new_name,3903 patch->old_mode);3904else3905returnerror(_("new mode (%o) of%sdoes not "3906"match old mode (%o) of%s"),3907 patch->new_mode, new_name,3908 patch->old_mode, old_name);3909}3910}39113912if(!state->unsafe_paths)3913die_on_unsafe_path(patch);39143915/*3916 * An attempt to read from or delete a path that is beyond a3917 * symbolic link will be prevented by load_patch_target() that3918 * is called at the beginning of apply_data() so we do not3919 * have to worry about a patch marked with "is_delete" bit3920 * here. We however need to make sure that the patch result3921 * is not deposited to a path that is beyond a symbolic link3922 * here.3923 */3924if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3925returnerror(_("affected file '%s' is beyond a symbolic link"),3926 patch->new_name);39273928if(apply_data(state, patch, &st, ce) <0)3929returnerror(_("%s: patch does not apply"), name);3930 patch->rejected =0;3931return0;3932}39333934static intcheck_patch_list(struct apply_state *state,struct patch *patch)3935{3936int err =0;39373938prepare_symlink_changes(state, patch);3939prepare_fn_table(state, patch);3940while(patch) {3941if(state->apply_verbosely)3942say_patch_name(stderr,3943_("Checking patch%s..."), patch);3944 err |=check_patch(state, patch);3945 patch = patch->next;3946}3947return err;3948}39493950/* This function tries to read the sha1 from the current index */3951static intget_current_sha1(const char*path,unsigned char*sha1)3952{3953int pos;39543955if(read_cache() <0)3956return-1;3957 pos =cache_name_pos(path,strlen(path));3958if(pos <0)3959return-1;3960hashcpy(sha1, active_cache[pos]->sha1);3961return0;3962}39633964static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3965{3966/*3967 * A usable gitlink patch has only one fragment (hunk) that looks like:3968 * @@ -1 +1 @@3969 * -Subproject commit <old sha1>3970 * +Subproject commit <new sha1>3971 * or3972 * @@ -1 +0,0 @@3973 * -Subproject commit <old sha1>3974 * for a removal patch.3975 */3976struct fragment *hunk = p->fragments;3977static const char heading[] ="-Subproject commit ";3978char*preimage;39793980if(/* does the patch have only one hunk? */3981 hunk && !hunk->next &&3982/* is its preimage one line? */3983 hunk->oldpos ==1&& hunk->oldlines ==1&&3984/* does preimage begin with the heading? */3985(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3986starts_with(++preimage, heading) &&3987/* does it record full SHA-1? */3988!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3989 preimage[sizeof(heading) +40-1] =='\n'&&3990/* does the abbreviated name on the index line agree with it? */3991starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3992return0;/* it all looks fine */39933994/* we may have full object name on the index line */3995returnget_sha1_hex(p->old_sha1_prefix, sha1);3996}39973998/* Build an index that contains the just the files needed for a 3way merge */3999static voidbuild_fake_ancestor(struct patch *list,const char*filename)4000{4001struct patch *patch;4002struct index_state result = { NULL };4003static struct lock_file lock;40044005/* Once we start supporting the reverse patch, it may be4006 * worth showing the new sha1 prefix, but until then...4007 */4008for(patch = list; patch; patch = patch->next) {4009unsigned char sha1[20];4010struct cache_entry *ce;4011const char*name;40124013 name = patch->old_name ? patch->old_name : patch->new_name;4014if(0< patch->is_new)4015continue;40164017if(S_ISGITLINK(patch->old_mode)) {4018if(!preimage_sha1_in_gitlink_patch(patch, sha1))4019;/* ok, the textual part looks sane */4020else4021die("sha1 information is lacking or useless for submodule%s",4022 name);4023}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {4024;/* ok */4025}else if(!patch->lines_added && !patch->lines_deleted) {4026/* mode-only change: update the current */4027if(get_current_sha1(patch->old_name, sha1))4028die("mode change for%s, which is not "4029"in current HEAD", name);4030}else4031die("sha1 information is lacking or useless "4032"(%s).", name);40334034 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);4035if(!ce)4036die(_("make_cache_entry failed for path '%s'"), name);4037if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))4038die("Could not add%sto temporary index", name);4039}40404041hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);4042if(write_locked_index(&result, &lock, COMMIT_LOCK))4043die("Could not write temporary index to%s", filename);40444045discard_index(&result);4046}40474048static voidstat_patch_list(struct apply_state *state,struct patch *patch)4049{4050int files, adds, dels;40514052for(files = adds = dels =0; patch ; patch = patch->next) {4053 files++;4054 adds += patch->lines_added;4055 dels += patch->lines_deleted;4056show_stats(state, patch);4057}40584059print_stat_summary(stdout, files, adds, dels);4060}40614062static voidnumstat_patch_list(struct apply_state *state,4063struct patch *patch)4064{4065for( ; patch; patch = patch->next) {4066const char*name;4067 name = patch->new_name ? patch->new_name : patch->old_name;4068if(patch->is_binary)4069printf("-\t-\t");4070else4071printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4072write_name_quoted(name, stdout, state->line_termination);4073}4074}40754076static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4077{4078if(mode)4079printf("%smode%06o%s\n", newdelete, mode, name);4080else4081printf("%s %s\n", newdelete, name);4082}40834084static voidshow_mode_change(struct patch *p,int show_name)4085{4086if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4087if(show_name)4088printf(" mode change%06o =>%06o%s\n",4089 p->old_mode, p->new_mode, p->new_name);4090else4091printf(" mode change%06o =>%06o\n",4092 p->old_mode, p->new_mode);4093}4094}40954096static voidshow_rename_copy(struct patch *p)4097{4098const char*renamecopy = p->is_rename ?"rename":"copy";4099const char*old, *new;41004101/* Find common prefix */4102 old = p->old_name;4103new= p->new_name;4104while(1) {4105const char*slash_old, *slash_new;4106 slash_old =strchr(old,'/');4107 slash_new =strchr(new,'/');4108if(!slash_old ||4109!slash_new ||4110 slash_old - old != slash_new -new||4111memcmp(old,new, slash_new -new))4112break;4113 old = slash_old +1;4114new= slash_new +1;4115}4116/* p->old_name thru old is the common prefix, and old and new4117 * through the end of names are renames4118 */4119if(old != p->old_name)4120printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4121(int)(old - p->old_name), p->old_name,4122 old,new, p->score);4123else4124printf("%s %s=>%s(%d%%)\n", renamecopy,4125 p->old_name, p->new_name, p->score);4126show_mode_change(p,0);4127}41284129static voidsummary_patch_list(struct patch *patch)4130{4131struct patch *p;41324133for(p = patch; p; p = p->next) {4134if(p->is_new)4135show_file_mode_name("create", p->new_mode, p->new_name);4136else if(p->is_delete)4137show_file_mode_name("delete", p->old_mode, p->old_name);4138else{4139if(p->is_rename || p->is_copy)4140show_rename_copy(p);4141else{4142if(p->score) {4143printf(" rewrite%s(%d%%)\n",4144 p->new_name, p->score);4145show_mode_change(p,0);4146}4147else4148show_mode_change(p,1);4149}4150}4151}4152}41534154static voidpatch_stats(struct apply_state *state,struct patch *patch)4155{4156int lines = patch->lines_added + patch->lines_deleted;41574158if(lines > state->max_change)4159 state->max_change = lines;4160if(patch->old_name) {4161int len =quote_c_style(patch->old_name, NULL, NULL,0);4162if(!len)4163 len =strlen(patch->old_name);4164if(len > state->max_len)4165 state->max_len = len;4166}4167if(patch->new_name) {4168int len =quote_c_style(patch->new_name, NULL, NULL,0);4169if(!len)4170 len =strlen(patch->new_name);4171if(len > state->max_len)4172 state->max_len = len;4173}4174}41754176static voidremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4177{4178if(state->update_index) {4179if(remove_file_from_cache(patch->old_name) <0)4180die(_("unable to remove%sfrom index"), patch->old_name);4181}4182if(!state->cached) {4183if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4184remove_path(patch->old_name);4185}4186}4187}41884189static voidadd_index_file(struct apply_state *state,4190const char*path,4191unsigned mode,4192void*buf,4193unsigned long size)4194{4195struct stat st;4196struct cache_entry *ce;4197int namelen =strlen(path);4198unsigned ce_size =cache_entry_size(namelen);41994200if(!state->update_index)4201return;42024203 ce =xcalloc(1, ce_size);4204memcpy(ce->name, path, namelen);4205 ce->ce_mode =create_ce_mode(mode);4206 ce->ce_flags =create_ce_flags(0);4207 ce->ce_namelen = namelen;4208if(S_ISGITLINK(mode)) {4209const char*s;42104211if(!skip_prefix(buf,"Subproject commit ", &s) ||4212get_sha1_hex(s, ce->sha1))4213die(_("corrupt patch for submodule%s"), path);4214}else{4215if(!state->cached) {4216if(lstat(path, &st) <0)4217die_errno(_("unable to stat newly created file '%s'"),4218 path);4219fill_stat_cache_info(ce, &st);4220}4221if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4222die(_("unable to create backing store for newly created file%s"), path);4223}4224if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4225die(_("unable to add cache entry for%s"), path);4226}42274228static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4229{4230int fd;4231struct strbuf nbuf = STRBUF_INIT;42324233if(S_ISGITLINK(mode)) {4234struct stat st;4235if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4236return0;4237returnmkdir(path,0777);4238}42394240if(has_symlinks &&S_ISLNK(mode))4241/* Although buf:size is counted string, it also is NUL4242 * terminated.4243 */4244returnsymlink(buf, path);42454246 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4247if(fd <0)4248return-1;42494250if(convert_to_working_tree(path, buf, size, &nbuf)) {4251 size = nbuf.len;4252 buf = nbuf.buf;4253}4254write_or_die(fd, buf, size);4255strbuf_release(&nbuf);42564257if(close(fd) <0)4258die_errno(_("closing file '%s'"), path);4259return0;4260}42614262/*4263 * We optimistically assume that the directories exist,4264 * which is true 99% of the time anyway. If they don't,4265 * we create them and try again.4266 */4267static voidcreate_one_file(struct apply_state *state,4268char*path,4269unsigned mode,4270const char*buf,4271unsigned long size)4272{4273if(state->cached)4274return;4275if(!try_create_file(path, mode, buf, size))4276return;42774278if(errno == ENOENT) {4279if(safe_create_leading_directories(path))4280return;4281if(!try_create_file(path, mode, buf, size))4282return;4283}42844285if(errno == EEXIST || errno == EACCES) {4286/* We may be trying to create a file where a directory4287 * used to be.4288 */4289struct stat st;4290if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4291 errno = EEXIST;4292}42934294if(errno == EEXIST) {4295unsigned int nr =getpid();42964297for(;;) {4298char newpath[PATH_MAX];4299mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4300if(!try_create_file(newpath, mode, buf, size)) {4301if(!rename(newpath, path))4302return;4303unlink_or_warn(newpath);4304break;4305}4306if(errno != EEXIST)4307break;4308++nr;4309}4310}4311die_errno(_("unable to write file '%s' mode%o"), path, mode);4312}43134314static voidadd_conflicted_stages_file(struct apply_state *state,4315struct patch *patch)4316{4317int stage, namelen;4318unsigned ce_size, mode;4319struct cache_entry *ce;43204321if(!state->update_index)4322return;4323 namelen =strlen(patch->new_name);4324 ce_size =cache_entry_size(namelen);4325 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);43264327remove_file_from_cache(patch->new_name);4328for(stage =1; stage <4; stage++) {4329if(is_null_oid(&patch->threeway_stage[stage -1]))4330continue;4331 ce =xcalloc(1, ce_size);4332memcpy(ce->name, patch->new_name, namelen);4333 ce->ce_mode =create_ce_mode(mode);4334 ce->ce_flags =create_ce_flags(stage);4335 ce->ce_namelen = namelen;4336hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4337if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4338die(_("unable to add cache entry for%s"), patch->new_name);4339}4340}43414342static voidcreate_file(struct apply_state *state,struct patch *patch)4343{4344char*path = patch->new_name;4345unsigned mode = patch->new_mode;4346unsigned long size = patch->resultsize;4347char*buf = patch->result;43484349if(!mode)4350 mode = S_IFREG |0644;4351create_one_file(state, path, mode, buf, size);43524353if(patch->conflicted_threeway)4354add_conflicted_stages_file(state, patch);4355else4356add_index_file(state, path, mode, buf, size);4357}43584359/* phase zero is to remove, phase one is to create */4360static voidwrite_out_one_result(struct apply_state *state,4361struct patch *patch,4362int phase)4363{4364if(patch->is_delete >0) {4365if(phase ==0)4366remove_file(state, patch,1);4367return;4368}4369if(patch->is_new >0|| patch->is_copy) {4370if(phase ==1)4371create_file(state, patch);4372return;4373}4374/*4375 * Rename or modification boils down to the same4376 * thing: remove the old, write the new4377 */4378if(phase ==0)4379remove_file(state, patch, patch->is_rename);4380if(phase ==1)4381create_file(state, patch);4382}43834384static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4385{4386FILE*rej;4387char namebuf[PATH_MAX];4388struct fragment *frag;4389int cnt =0;4390struct strbuf sb = STRBUF_INIT;43914392for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4393if(!frag->rejected)4394continue;4395 cnt++;4396}43974398if(!cnt) {4399if(state->apply_verbosely)4400say_patch_name(stderr,4401_("Applied patch%scleanly."), patch);4402return0;4403}44044405/* This should not happen, because a removal patch that leaves4406 * contents are marked "rejected" at the patch level.4407 */4408if(!patch->new_name)4409die(_("internal error"));44104411/* Say this even without --verbose */4412strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4413"Applying patch %%swith%drejects...",4414 cnt),4415 cnt);4416say_patch_name(stderr, sb.buf, patch);4417strbuf_release(&sb);44184419 cnt =strlen(patch->new_name);4420if(ARRAY_SIZE(namebuf) <= cnt +5) {4421 cnt =ARRAY_SIZE(namebuf) -5;4422warning(_("truncating .rej filename to %.*s.rej"),4423 cnt -1, patch->new_name);4424}4425memcpy(namebuf, patch->new_name, cnt);4426memcpy(namebuf + cnt,".rej",5);44274428 rej =fopen(namebuf,"w");4429if(!rej)4430returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));44314432/* Normal git tools never deal with .rej, so do not pretend4433 * this is a git patch by saying --git or giving extended4434 * headers. While at it, maybe please "kompare" that wants4435 * the trailing TAB and some garbage at the end of line ;-).4436 */4437fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4438 patch->new_name, patch->new_name);4439for(cnt =1, frag = patch->fragments;4440 frag;4441 cnt++, frag = frag->next) {4442if(!frag->rejected) {4443fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4444continue;4445}4446fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4447fprintf(rej,"%.*s", frag->size, frag->patch);4448if(frag->patch[frag->size-1] !='\n')4449fputc('\n', rej);4450}4451fclose(rej);4452return-1;4453}44544455static intwrite_out_results(struct apply_state *state,struct patch *list)4456{4457int phase;4458int errs =0;4459struct patch *l;4460struct string_list cpath = STRING_LIST_INIT_DUP;44614462for(phase =0; phase <2; phase++) {4463 l = list;4464while(l) {4465if(l->rejected)4466 errs =1;4467else{4468write_out_one_result(state, l, phase);4469if(phase ==1) {4470if(write_out_one_reject(state, l))4471 errs =1;4472if(l->conflicted_threeway) {4473string_list_append(&cpath, l->new_name);4474 errs =1;4475}4476}4477}4478 l = l->next;4479}4480}44814482if(cpath.nr) {4483struct string_list_item *item;44844485string_list_sort(&cpath);4486for_each_string_list_item(item, &cpath)4487fprintf(stderr,"U%s\n", item->string);4488string_list_clear(&cpath,0);44894490rerere(0);4491}44924493return errs;4494}44954496static struct lock_file lock_file;44974498#define INACCURATE_EOF (1<<0)4499#define RECOUNT (1<<1)45004501static intapply_patch(struct apply_state *state,4502int fd,4503const char*filename,4504int options)4505{4506size_t offset;4507struct strbuf buf = STRBUF_INIT;/* owns the patch text */4508struct patch *list = NULL, **listp = &list;4509int skipped_patch =0;45104511 state->patch_input_file = filename;4512read_patch_file(&buf, fd);4513 offset =0;4514while(offset < buf.len) {4515struct patch *patch;4516int nr;45174518 patch =xcalloc(1,sizeof(*patch));4519 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4520 patch->recount = !!(options & RECOUNT);4521 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4522if(nr <0) {4523free_patch(patch);4524break;4525}4526if(state->apply_in_reverse)4527reverse_patches(patch);4528if(use_patch(state, patch)) {4529patch_stats(state, patch);4530*listp = patch;4531 listp = &patch->next;4532}4533else{4534if(state->apply_verbosely)4535say_patch_name(stderr,_("Skipped patch '%s'."), patch);4536free_patch(patch);4537 skipped_patch++;4538}4539 offset += nr;4540}45414542if(!list && !skipped_patch)4543die(_("unrecognized input"));45444545if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4546 state->apply =0;45474548 state->update_index = state->check_index && state->apply;4549if(state->update_index && newfd <0)4550 newfd =hold_locked_index(&lock_file,1);45514552if(state->check_index) {4553if(read_cache() <0)4554die(_("unable to read index file"));4555}45564557if((state->check || state->apply) &&4558check_patch_list(state, list) <0&&4559!state->apply_with_reject)4560exit(1);45614562if(state->apply &&write_out_results(state, list)) {4563if(state->apply_with_reject)4564exit(1);4565/* with --3way, we still need to write the index out */4566return1;4567}45684569if(state->fake_ancestor)4570build_fake_ancestor(list, state->fake_ancestor);45714572if(state->diffstat)4573stat_patch_list(state, list);45744575if(state->numstat)4576numstat_patch_list(state, list);45774578if(state->summary)4579summary_patch_list(list);45804581free_patch_list(list);4582strbuf_release(&buf);4583string_list_clear(&state->fn_table,0);4584return0;4585}45864587static voidgit_apply_config(void)4588{4589git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4590git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4591git_config(git_default_config, NULL);4592}45934594static intoption_parse_exclude(const struct option *opt,4595const char*arg,int unset)4596{4597struct apply_state *state = opt->value;4598add_name_limit(state, arg,1);4599return0;4600}46014602static intoption_parse_include(const struct option *opt,4603const char*arg,int unset)4604{4605struct apply_state *state = opt->value;4606add_name_limit(state, arg,0);4607 state->has_include =1;4608return0;4609}46104611static intoption_parse_p(const struct option *opt,4612const char*arg,4613int unset)4614{4615struct apply_state *state = opt->value;4616 state->p_value =atoi(arg);4617 state->p_value_known =1;4618return0;4619}46204621static intoption_parse_space_change(const struct option *opt,4622const char*arg,int unset)4623{4624struct apply_state *state = opt->value;4625if(unset)4626 state->ws_ignore_action = ignore_ws_none;4627else4628 state->ws_ignore_action = ignore_ws_change;4629return0;4630}46314632static intoption_parse_whitespace(const struct option *opt,4633const char*arg,int unset)4634{4635struct apply_state *state = opt->value;4636 state->whitespace_option = arg;4637parse_whitespace_option(state, arg);4638return0;4639}46404641static intoption_parse_directory(const struct option *opt,4642const char*arg,int unset)4643{4644struct apply_state *state = opt->value;4645strbuf_reset(&state->root);4646strbuf_addstr(&state->root, arg);4647strbuf_complete(&state->root,'/');4648return0;4649}46504651static voidinit_apply_state(struct apply_state *state,const char*prefix)4652{4653memset(state,0,sizeof(*state));4654 state->prefix = prefix;4655 state->prefix_length = state->prefix ?strlen(state->prefix) :0;4656 state->apply =1;4657 state->line_termination ='\n';4658 state->p_value =1;4659 state->p_context = UINT_MAX;4660 state->squelch_whitespace_errors =5;4661 state->ws_error_action = warn_on_ws_error;4662 state->ws_ignore_action = ignore_ws_none;4663 state->linenr =1;4664strbuf_init(&state->root,0);46654666git_apply_config();4667if(apply_default_whitespace)4668parse_whitespace_option(state, apply_default_whitespace);4669if(apply_default_ignorewhitespace)4670parse_ignorewhitespace_option(state, apply_default_ignorewhitespace);4671}46724673static voidclear_apply_state(struct apply_state *state)4674{4675string_list_clear(&state->limit_by_name,0);4676string_list_clear(&state->symlink_changes,0);4677strbuf_release(&state->root);46784679/* &state->fn_table is cleared at the end of apply_patch() */4680}46814682static voidcheck_apply_state(struct apply_state *state,int force_apply)4683{4684int is_not_gitdir = !startup_info->have_repository;46854686if(state->apply_with_reject && state->threeway)4687die("--reject and --3way cannot be used together.");4688if(state->cached && state->threeway)4689die("--cached and --3way cannot be used together.");4690if(state->threeway) {4691if(is_not_gitdir)4692die(_("--3way outside a repository"));4693 state->check_index =1;4694}4695if(state->apply_with_reject)4696 state->apply = state->apply_verbosely =1;4697if(!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor))4698 state->apply =0;4699if(state->check_index && is_not_gitdir)4700die(_("--index outside a repository"));4701if(state->cached) {4702if(is_not_gitdir)4703die(_("--cached outside a repository"));4704 state->check_index =1;4705}4706if(state->check_index)4707 state->unsafe_paths =0;4708}47094710static intapply_all_patches(struct apply_state *state,4711int argc,4712const char**argv,4713int options)4714{4715int i;4716int errs =0;4717int read_stdin =1;47184719for(i =0; i < argc; i++) {4720const char*arg = argv[i];4721int fd;47224723if(!strcmp(arg,"-")) {4724 errs |=apply_patch(state,0,"<stdin>", options);4725 read_stdin =0;4726continue;4727}else if(0< state->prefix_length)4728 arg =prefix_filename(state->prefix,4729 state->prefix_length,4730 arg);47314732 fd =open(arg, O_RDONLY);4733if(fd <0)4734die_errno(_("can't open patch '%s'"), arg);4735 read_stdin =0;4736set_default_whitespace_mode(state);4737 errs |=apply_patch(state, fd, arg, options);4738close(fd);4739}4740set_default_whitespace_mode(state);4741if(read_stdin)4742 errs |=apply_patch(state,0,"<stdin>", options);47434744if(state->whitespace_error) {4745if(state->squelch_whitespace_errors &&4746 state->squelch_whitespace_errors < state->whitespace_error) {4747int squelched =4748 state->whitespace_error - state->squelch_whitespace_errors;4749warning(Q_("squelched%dwhitespace error",4750"squelched%dwhitespace errors",4751 squelched),4752 squelched);4753}4754if(state->ws_error_action == die_on_ws_error)4755die(Q_("%dline adds whitespace errors.",4756"%dlines add whitespace errors.",4757 state->whitespace_error),4758 state->whitespace_error);4759if(state->applied_after_fixing_ws && state->apply)4760warning("%dline%sapplied after"4761" fixing whitespace errors.",4762 state->applied_after_fixing_ws,4763 state->applied_after_fixing_ws ==1?"":"s");4764else if(state->whitespace_error)4765warning(Q_("%dline adds whitespace errors.",4766"%dlines add whitespace errors.",4767 state->whitespace_error),4768 state->whitespace_error);4769}47704771if(state->update_index) {4772if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK))4773die(_("Unable to write new index file"));4774}47754776return!!errs;4777}47784779intcmd_apply(int argc,const char**argv,const char*prefix)4780{4781int force_apply =0;4782int options =0;4783int ret;4784struct apply_state state;47854786struct option builtin_apply_options[] = {4787{ OPTION_CALLBACK,0,"exclude", &state,N_("path"),4788N_("don't apply changes matching the given path"),47890, option_parse_exclude },4790{ OPTION_CALLBACK,0,"include", &state,N_("path"),4791N_("apply changes matching the given path"),47920, option_parse_include },4793{ OPTION_CALLBACK,'p', NULL, &state,N_("num"),4794N_("remove <num> leading slashes from traditional diff paths"),47950, option_parse_p },4796OPT_BOOL(0,"no-add", &state.no_add,4797N_("ignore additions made by the patch")),4798OPT_BOOL(0,"stat", &state.diffstat,4799N_("instead of applying the patch, output diffstat for the input")),4800OPT_NOOP_NOARG(0,"allow-binary-replacement"),4801OPT_NOOP_NOARG(0,"binary"),4802OPT_BOOL(0,"numstat", &state.numstat,4803N_("show number of added and deleted lines in decimal notation")),4804OPT_BOOL(0,"summary", &state.summary,4805N_("instead of applying the patch, output a summary for the input")),4806OPT_BOOL(0,"check", &state.check,4807N_("instead of applying the patch, see if the patch is applicable")),4808OPT_BOOL(0,"index", &state.check_index,4809N_("make sure the patch is applicable to the current index")),4810OPT_BOOL(0,"cached", &state.cached,4811N_("apply a patch without touching the working tree")),4812OPT_BOOL(0,"unsafe-paths", &state.unsafe_paths,4813N_("accept a patch that touches outside the working area")),4814OPT_BOOL(0,"apply", &force_apply,4815N_("also apply the patch (use with --stat/--summary/--check)")),4816OPT_BOOL('3',"3way", &state.threeway,4817N_("attempt three-way merge if a patch does not apply")),4818OPT_FILENAME(0,"build-fake-ancestor", &state.fake_ancestor,4819N_("build a temporary index based on embedded index information")),4820/* Think twice before adding "--nul" synonym to this */4821OPT_SET_INT('z', NULL, &state.line_termination,4822N_("paths are separated with NUL character"),'\0'),4823OPT_INTEGER('C', NULL, &state.p_context,4824N_("ensure at least <n> lines of context match")),4825{ OPTION_CALLBACK,0,"whitespace", &state,N_("action"),4826N_("detect new or modified lines that have whitespace errors"),48270, option_parse_whitespace },4828{ OPTION_CALLBACK,0,"ignore-space-change", &state, NULL,4829N_("ignore changes in whitespace when finding context"),4830 PARSE_OPT_NOARG, option_parse_space_change },4831{ OPTION_CALLBACK,0,"ignore-whitespace", &state, NULL,4832N_("ignore changes in whitespace when finding context"),4833 PARSE_OPT_NOARG, option_parse_space_change },4834OPT_BOOL('R',"reverse", &state.apply_in_reverse,4835N_("apply the patch in reverse")),4836OPT_BOOL(0,"unidiff-zero", &state.unidiff_zero,4837N_("don't expect at least one line of context")),4838OPT_BOOL(0,"reject", &state.apply_with_reject,4839N_("leave the rejected hunks in corresponding *.rej files")),4840OPT_BOOL(0,"allow-overlap", &state.allow_overlap,4841N_("allow overlapping hunks")),4842OPT__VERBOSE(&state.apply_verbosely,N_("be verbose")),4843OPT_BIT(0,"inaccurate-eof", &options,4844N_("tolerate incorrectly detected missing new-line at the end of file"),4845 INACCURATE_EOF),4846OPT_BIT(0,"recount", &options,4847N_("do not trust the line counts in the hunk headers"),4848 RECOUNT),4849{ OPTION_CALLBACK,0,"directory", &state,N_("root"),4850N_("prepend <root> to all filenames"),48510, option_parse_directory },4852OPT_END()4853};48544855init_apply_state(&state, prefix);48564857 argc =parse_options(argc, argv, state.prefix, builtin_apply_options,4858 apply_usage,0);48594860check_apply_state(&state, force_apply);48614862 ret =apply_all_patches(&state, argc, argv, options);48634864clear_apply_state(&state);48654866return ret;4867}