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"cache-tree.h" 11#include"quote.h" 12#include"blob.h" 13#include"delta.h" 14#include"builtin.h" 15#include"string-list.h" 16#include"dir.h" 17#include"diff.h" 18#include"parse-options.h" 19#include"xdiff-interface.h" 20#include"ll-merge.h" 21#include"rerere.h" 22 23/* 24 * --check turns on checking that the working tree matches the 25 * files that are being modified, but doesn't apply the patch 26 * --stat does just a diffstat, and doesn't actually apply 27 * --numstat does numeric diffstat, and doesn't actually apply 28 * --index-info shows the old and new index info for paths if available. 29 * --index updates the cache as well. 30 * --cached updates only the cache without ever touching the working tree. 31 */ 32static const char*prefix; 33static int prefix_length = -1; 34static int newfd = -1; 35 36static int unidiff_zero; 37static int p_value =1; 38static int p_value_known; 39static int check_index; 40static int update_index; 41static int cached; 42static int diffstat; 43static int numstat; 44static int summary; 45static int check; 46static int apply =1; 47static int apply_in_reverse; 48static int apply_with_reject; 49static int apply_verbosely; 50static int allow_overlap; 51static int no_add; 52static int threeway; 53static const char*fake_ancestor; 54static int line_termination ='\n'; 55static unsigned int p_context = UINT_MAX; 56static const char*const apply_usage[] = { 57N_("git apply [options] [<patch>...]"), 58 NULL 59}; 60 61static enum ws_error_action { 62 nowarn_ws_error, 63 warn_on_ws_error, 64 die_on_ws_error, 65 correct_ws_error 66} ws_error_action = warn_on_ws_error; 67static int whitespace_error; 68static int squelch_whitespace_errors =5; 69static int applied_after_fixing_ws; 70 71static enum ws_ignore { 72 ignore_ws_none, 73 ignore_ws_change 74} ws_ignore_action = ignore_ws_none; 75 76 77static const char*patch_input_file; 78static const char*root; 79static int root_len; 80static int read_stdin =1; 81static int options; 82 83static voidparse_whitespace_option(const char*option) 84{ 85if(!option) { 86 ws_error_action = warn_on_ws_error; 87return; 88} 89if(!strcmp(option,"warn")) { 90 ws_error_action = warn_on_ws_error; 91return; 92} 93if(!strcmp(option,"nowarn")) { 94 ws_error_action = nowarn_ws_error; 95return; 96} 97if(!strcmp(option,"error")) { 98 ws_error_action = die_on_ws_error; 99return; 100} 101if(!strcmp(option,"error-all")) { 102 ws_error_action = die_on_ws_error; 103 squelch_whitespace_errors =0; 104return; 105} 106if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 107 ws_error_action = correct_ws_error; 108return; 109} 110die(_("unrecognized whitespace option '%s'"), option); 111} 112 113static voidparse_ignorewhitespace_option(const char*option) 114{ 115if(!option || !strcmp(option,"no") || 116!strcmp(option,"false") || !strcmp(option,"never") || 117!strcmp(option,"none")) { 118 ws_ignore_action = ignore_ws_none; 119return; 120} 121if(!strcmp(option,"change")) { 122 ws_ignore_action = ignore_ws_change; 123return; 124} 125die(_("unrecognized whitespace ignore option '%s'"), option); 126} 127 128static voidset_default_whitespace_mode(const char*whitespace_option) 129{ 130if(!whitespace_option && !apply_default_whitespace) 131 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 132} 133 134/* 135 * For "diff-stat" like behaviour, we keep track of the biggest change 136 * we've seen, and the longest filename. That allows us to do simple 137 * scaling. 138 */ 139static int max_change, max_len; 140 141/* 142 * Various "current state", notably line numbers and what 143 * file (and how) we're patching right now.. The "is_xxxx" 144 * things are flags, where -1 means "don't know yet". 145 */ 146static int linenr =1; 147 148/* 149 * This represents one "hunk" from a patch, starting with 150 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 151 * patch text is pointed at by patch, and its byte length 152 * is stored in size. leading and trailing are the number 153 * of context lines. 154 */ 155struct fragment { 156unsigned long leading, trailing; 157unsigned long oldpos, oldlines; 158unsigned long newpos, newlines; 159/* 160 * 'patch' is usually borrowed from buf in apply_patch(), 161 * but some codepaths store an allocated buffer. 162 */ 163const char*patch; 164unsigned free_patch:1, 165 rejected:1; 166int size; 167int linenr; 168struct fragment *next; 169}; 170 171/* 172 * When dealing with a binary patch, we reuse "leading" field 173 * to store the type of the binary hunk, either deflated "delta" 174 * or deflated "literal". 175 */ 176#define binary_patch_method leading 177#define BINARY_DELTA_DEFLATED 1 178#define BINARY_LITERAL_DEFLATED 2 179 180/* 181 * This represents a "patch" to a file, both metainfo changes 182 * such as creation/deletion, filemode and content changes represented 183 * as a series of fragments. 184 */ 185struct patch { 186char*new_name, *old_name, *def_name; 187unsigned int old_mode, new_mode; 188int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 189int rejected; 190unsigned ws_rule; 191unsigned long deflate_origlen; 192int lines_added, lines_deleted; 193int score; 194unsigned int is_toplevel_relative:1; 195unsigned int inaccurate_eof:1; 196unsigned int is_binary:1; 197unsigned int is_copy:1; 198unsigned int is_rename:1; 199unsigned int recount:1; 200unsigned int conflicted_threeway:1; 201unsigned int direct_to_threeway:1; 202struct fragment *fragments; 203char*result; 204size_t resultsize; 205char old_sha1_prefix[41]; 206char new_sha1_prefix[41]; 207struct patch *next; 208 209/* three-way fallback result */ 210unsigned char threeway_stage[3][20]; 211}; 212 213static voidfree_fragment_list(struct fragment *list) 214{ 215while(list) { 216struct fragment *next = list->next; 217if(list->free_patch) 218free((char*)list->patch); 219free(list); 220 list = next; 221} 222} 223 224static voidfree_patch(struct patch *patch) 225{ 226free_fragment_list(patch->fragments); 227free(patch->def_name); 228free(patch->old_name); 229free(patch->new_name); 230free(patch->result); 231free(patch); 232} 233 234static voidfree_patch_list(struct patch *list) 235{ 236while(list) { 237struct patch *next = list->next; 238free_patch(list); 239 list = next; 240} 241} 242 243/* 244 * A line in a file, len-bytes long (includes the terminating LF, 245 * except for an incomplete line at the end if the file ends with 246 * one), and its contents hashes to 'hash'. 247 */ 248struct line { 249size_t len; 250unsigned hash :24; 251unsigned flag :8; 252#define LINE_COMMON 1 253#define LINE_PATCHED 2 254}; 255 256/* 257 * This represents a "file", which is an array of "lines". 258 */ 259struct image { 260char*buf; 261size_t len; 262size_t nr; 263size_t alloc; 264struct line *line_allocated; 265struct line *line; 266}; 267 268/* 269 * Records filenames that have been touched, in order to handle 270 * the case where more than one patches touch the same file. 271 */ 272 273static struct string_list fn_table; 274 275static uint32_thash_line(const char*cp,size_t len) 276{ 277size_t i; 278uint32_t h; 279for(i =0, h =0; i < len; i++) { 280if(!isspace(cp[i])) { 281 h = h *3+ (cp[i] &0xff); 282} 283} 284return h; 285} 286 287/* 288 * Compare lines s1 of length n1 and s2 of length n2, ignoring 289 * whitespace difference. Returns 1 if they match, 0 otherwise 290 */ 291static intfuzzy_matchlines(const char*s1,size_t n1, 292const char*s2,size_t n2) 293{ 294const char*last1 = s1 + n1 -1; 295const char*last2 = s2 + n2 -1; 296int result =0; 297 298/* ignore line endings */ 299while((*last1 =='\r') || (*last1 =='\n')) 300 last1--; 301while((*last2 =='\r') || (*last2 =='\n')) 302 last2--; 303 304/* skip leading whitespace */ 305while(isspace(*s1) && (s1 <= last1)) 306 s1++; 307while(isspace(*s2) && (s2 <= last2)) 308 s2++; 309/* early return if both lines are empty */ 310if((s1 > last1) && (s2 > last2)) 311return1; 312while(!result) { 313 result = *s1++ - *s2++; 314/* 315 * Skip whitespace inside. We check for whitespace on 316 * both buffers because we don't want "a b" to match 317 * "ab" 318 */ 319if(isspace(*s1) &&isspace(*s2)) { 320while(isspace(*s1) && s1 <= last1) 321 s1++; 322while(isspace(*s2) && s2 <= last2) 323 s2++; 324} 325/* 326 * If we reached the end on one side only, 327 * lines don't match 328 */ 329if( 330((s2 > last2) && (s1 <= last1)) || 331((s1 > last1) && (s2 <= last2))) 332return0; 333if((s1 > last1) && (s2 > last2)) 334break; 335} 336 337return!result; 338} 339 340static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 341{ 342ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 343 img->line_allocated[img->nr].len = len; 344 img->line_allocated[img->nr].hash =hash_line(bol, len); 345 img->line_allocated[img->nr].flag = flag; 346 img->nr++; 347} 348 349/* 350 * "buf" has the file contents to be patched (read from various sources). 351 * attach it to "image" and add line-based index to it. 352 * "image" now owns the "buf". 353 */ 354static voidprepare_image(struct image *image,char*buf,size_t len, 355int prepare_linetable) 356{ 357const char*cp, *ep; 358 359memset(image,0,sizeof(*image)); 360 image->buf = buf; 361 image->len = len; 362 363if(!prepare_linetable) 364return; 365 366 ep = image->buf + image->len; 367 cp = image->buf; 368while(cp < ep) { 369const char*next; 370for(next = cp; next < ep && *next !='\n'; next++) 371; 372if(next < ep) 373 next++; 374add_line_info(image, cp, next - cp,0); 375 cp = next; 376} 377 image->line = image->line_allocated; 378} 379 380static voidclear_image(struct image *image) 381{ 382free(image->buf); 383free(image->line_allocated); 384memset(image,0,sizeof(*image)); 385} 386 387/* fmt must contain _one_ %s and no other substitution */ 388static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 389{ 390struct strbuf sb = STRBUF_INIT; 391 392if(patch->old_name && patch->new_name && 393strcmp(patch->old_name, patch->new_name)) { 394quote_c_style(patch->old_name, &sb, NULL,0); 395strbuf_addstr(&sb," => "); 396quote_c_style(patch->new_name, &sb, NULL,0); 397}else{ 398const char*n = patch->new_name; 399if(!n) 400 n = patch->old_name; 401quote_c_style(n, &sb, NULL,0); 402} 403fprintf(output, fmt, sb.buf); 404fputc('\n', output); 405strbuf_release(&sb); 406} 407 408#define SLOP (16) 409 410static voidread_patch_file(struct strbuf *sb,int fd) 411{ 412if(strbuf_read(sb, fd,0) <0) 413die_errno("git apply: failed to read"); 414 415/* 416 * Make sure that we have some slop in the buffer 417 * so that we can do speculative "memcmp" etc, and 418 * see to it that it is NUL-filled. 419 */ 420strbuf_grow(sb, SLOP); 421memset(sb->buf + sb->len,0, SLOP); 422} 423 424static unsigned longlinelen(const char*buffer,unsigned long size) 425{ 426unsigned long len =0; 427while(size--) { 428 len++; 429if(*buffer++ =='\n') 430break; 431} 432return len; 433} 434 435static intis_dev_null(const char*str) 436{ 437return!memcmp("/dev/null", str,9) &&isspace(str[9]); 438} 439 440#define TERM_SPACE 1 441#define TERM_TAB 2 442 443static intname_terminate(const char*name,int namelen,int c,int terminate) 444{ 445if(c ==' '&& !(terminate & TERM_SPACE)) 446return0; 447if(c =='\t'&& !(terminate & TERM_TAB)) 448return0; 449 450return1; 451} 452 453/* remove double slashes to make --index work with such filenames */ 454static char*squash_slash(char*name) 455{ 456int i =0, j =0; 457 458if(!name) 459return NULL; 460 461while(name[i]) { 462if((name[j++] = name[i++]) =='/') 463while(name[i] =='/') 464 i++; 465} 466 name[j] ='\0'; 467return name; 468} 469 470static char*find_name_gnu(const char*line,const char*def,int p_value) 471{ 472struct strbuf name = STRBUF_INIT; 473char*cp; 474 475/* 476 * Proposed "new-style" GNU patch/diff format; see 477 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2 478 */ 479if(unquote_c_style(&name, line, NULL)) { 480strbuf_release(&name); 481return NULL; 482} 483 484for(cp = name.buf; p_value; p_value--) { 485 cp =strchr(cp,'/'); 486if(!cp) { 487strbuf_release(&name); 488return NULL; 489} 490 cp++; 491} 492 493strbuf_remove(&name,0, cp - name.buf); 494if(root) 495strbuf_insert(&name,0, root, root_len); 496returnsquash_slash(strbuf_detach(&name, NULL)); 497} 498 499static size_tsane_tz_len(const char*line,size_t len) 500{ 501const char*tz, *p; 502 503if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 504return0; 505 tz = line + len -strlen(" +0500"); 506 507if(tz[1] !='+'&& tz[1] !='-') 508return0; 509 510for(p = tz +2; p != line + len; p++) 511if(!isdigit(*p)) 512return0; 513 514return line + len - tz; 515} 516 517static size_ttz_with_colon_len(const char*line,size_t len) 518{ 519const char*tz, *p; 520 521if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 522return0; 523 tz = line + len -strlen(" +08:00"); 524 525if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 526return0; 527 p = tz +2; 528if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 529!isdigit(*p++) || !isdigit(*p++)) 530return0; 531 532return line + len - tz; 533} 534 535static size_tdate_len(const char*line,size_t len) 536{ 537const char*date, *p; 538 539if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 540return0; 541 p = date = line + len -strlen("72-02-05"); 542 543if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 544!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 545!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 546return0; 547 548if(date - line >=strlen("19") && 549isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 550 date -=strlen("19"); 551 552return line + len - date; 553} 554 555static size_tshort_time_len(const char*line,size_t len) 556{ 557const char*time, *p; 558 559if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 560return0; 561 p = time = line + len -strlen(" 07:01:32"); 562 563/* Permit 1-digit hours? */ 564if(*p++ !=' '|| 565!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 566!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 567!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 568return0; 569 570return line + len - time; 571} 572 573static size_tfractional_time_len(const char*line,size_t len) 574{ 575const char*p; 576size_t n; 577 578/* Expected format: 19:41:17.620000023 */ 579if(!len || !isdigit(line[len -1])) 580return0; 581 p = line + len -1; 582 583/* Fractional seconds. */ 584while(p > line &&isdigit(*p)) 585 p--; 586if(*p !='.') 587return0; 588 589/* Hours, minutes, and whole seconds. */ 590 n =short_time_len(line, p - line); 591if(!n) 592return0; 593 594return line + len - p + n; 595} 596 597static size_ttrailing_spaces_len(const char*line,size_t len) 598{ 599const char*p; 600 601/* Expected format: ' ' x (1 or more) */ 602if(!len || line[len -1] !=' ') 603return0; 604 605 p = line + len; 606while(p != line) { 607 p--; 608if(*p !=' ') 609return line + len - (p +1); 610} 611 612/* All spaces! */ 613return len; 614} 615 616static size_tdiff_timestamp_len(const char*line,size_t len) 617{ 618const char*end = line + len; 619size_t n; 620 621/* 622 * Posix: 2010-07-05 19:41:17 623 * GNU: 2010-07-05 19:41:17.620000023 -0500 624 */ 625 626if(!isdigit(end[-1])) 627return0; 628 629 n =sane_tz_len(line, end - line); 630if(!n) 631 n =tz_with_colon_len(line, end - line); 632 end -= n; 633 634 n =short_time_len(line, end - line); 635if(!n) 636 n =fractional_time_len(line, end - line); 637 end -= n; 638 639 n =date_len(line, end - line); 640if(!n)/* No date. Too bad. */ 641return0; 642 end -= n; 643 644if(end == line)/* No space before date. */ 645return0; 646if(end[-1] =='\t') {/* Success! */ 647 end--; 648return line + len - end; 649} 650if(end[-1] !=' ')/* No space before date. */ 651return0; 652 653/* Whitespace damage. */ 654 end -=trailing_spaces_len(line, end - line); 655return line + len - end; 656} 657 658static char*null_strdup(const char*s) 659{ 660return s ?xstrdup(s) : NULL; 661} 662 663static char*find_name_common(const char*line,const char*def, 664int p_value,const char*end,int terminate) 665{ 666int len; 667const char*start = NULL; 668 669if(p_value ==0) 670 start = line; 671while(line != end) { 672char c = *line; 673 674if(!end &&isspace(c)) { 675if(c =='\n') 676break; 677if(name_terminate(start, line-start, c, terminate)) 678break; 679} 680 line++; 681if(c =='/'&& !--p_value) 682 start = line; 683} 684if(!start) 685returnsquash_slash(null_strdup(def)); 686 len = line - start; 687if(!len) 688returnsquash_slash(null_strdup(def)); 689 690/* 691 * Generally we prefer the shorter name, especially 692 * if the other one is just a variation of that with 693 * something else tacked on to the end (ie "file.orig" 694 * or "file~"). 695 */ 696if(def) { 697int deflen =strlen(def); 698if(deflen < len && !strncmp(start, def, deflen)) 699returnsquash_slash(xstrdup(def)); 700} 701 702if(root) { 703char*ret =xmalloc(root_len + len +1); 704strcpy(ret, root); 705memcpy(ret + root_len, start, len); 706 ret[root_len + len] ='\0'; 707returnsquash_slash(ret); 708} 709 710returnsquash_slash(xmemdupz(start, len)); 711} 712 713static char*find_name(const char*line,char*def,int p_value,int terminate) 714{ 715if(*line =='"') { 716char*name =find_name_gnu(line, def, p_value); 717if(name) 718return name; 719} 720 721returnfind_name_common(line, def, p_value, NULL, terminate); 722} 723 724static char*find_name_traditional(const char*line,char*def,int p_value) 725{ 726size_t len =strlen(line); 727size_t date_len; 728 729if(*line =='"') { 730char*name =find_name_gnu(line, def, p_value); 731if(name) 732return name; 733} 734 735 len =strchrnul(line,'\n') - line; 736 date_len =diff_timestamp_len(line, len); 737if(!date_len) 738returnfind_name_common(line, def, p_value, NULL, TERM_TAB); 739 len -= date_len; 740 741returnfind_name_common(line, def, p_value, line + len,0); 742} 743 744static intcount_slashes(const char*cp) 745{ 746int cnt =0; 747char ch; 748 749while((ch = *cp++)) 750if(ch =='/') 751 cnt++; 752return cnt; 753} 754 755/* 756 * Given the string after "--- " or "+++ ", guess the appropriate 757 * p_value for the given patch. 758 */ 759static intguess_p_value(const char*nameline) 760{ 761char*name, *cp; 762int val = -1; 763 764if(is_dev_null(nameline)) 765return-1; 766 name =find_name_traditional(nameline, NULL,0); 767if(!name) 768return-1; 769 cp =strchr(name,'/'); 770if(!cp) 771 val =0; 772else if(prefix) { 773/* 774 * Does it begin with "a/$our-prefix" and such? Then this is 775 * very likely to apply to our directory. 776 */ 777if(!strncmp(name, prefix, prefix_length)) 778 val =count_slashes(prefix); 779else{ 780 cp++; 781if(!strncmp(cp, prefix, prefix_length)) 782 val =count_slashes(prefix) +1; 783} 784} 785free(name); 786return val; 787} 788 789/* 790 * Does the ---/+++ line has the POSIX timestamp after the last HT? 791 * GNU diff puts epoch there to signal a creation/deletion event. Is 792 * this such a timestamp? 793 */ 794static inthas_epoch_timestamp(const char*nameline) 795{ 796/* 797 * We are only interested in epoch timestamp; any non-zero 798 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 799 * For the same reason, the date must be either 1969-12-31 or 800 * 1970-01-01, and the seconds part must be "00". 801 */ 802const char stamp_regexp[] = 803"^(1969-12-31|1970-01-01)" 804" " 805"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 806" " 807"([-+][0-2][0-9]:?[0-5][0-9])\n"; 808const char*timestamp = NULL, *cp, *colon; 809static regex_t *stamp; 810 regmatch_t m[10]; 811int zoneoffset; 812int hourminute; 813int status; 814 815for(cp = nameline; *cp !='\n'; cp++) { 816if(*cp =='\t') 817 timestamp = cp +1; 818} 819if(!timestamp) 820return0; 821if(!stamp) { 822 stamp =xmalloc(sizeof(*stamp)); 823if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 824warning(_("Cannot prepare timestamp regexp%s"), 825 stamp_regexp); 826return0; 827} 828} 829 830 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 831if(status) { 832if(status != REG_NOMATCH) 833warning(_("regexec returned%dfor input:%s"), 834 status, timestamp); 835return0; 836} 837 838 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 839if(*colon ==':') 840 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 841else 842 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 843if(timestamp[m[3].rm_so] =='-') 844 zoneoffset = -zoneoffset; 845 846/* 847 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 848 * (west of GMT) or 1970-01-01 (east of GMT) 849 */ 850if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 851(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 852return0; 853 854 hourminute = (strtol(timestamp +11, NULL,10) *60+ 855strtol(timestamp +14, NULL,10) - 856 zoneoffset); 857 858return((zoneoffset <0&& hourminute ==1440) || 859(0<= zoneoffset && !hourminute)); 860} 861 862/* 863 * Get the name etc info from the ---/+++ lines of a traditional patch header 864 * 865 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 866 * files, we can happily check the index for a match, but for creating a 867 * new file we should try to match whatever "patch" does. I have no idea. 868 */ 869static voidparse_traditional_patch(const char*first,const char*second,struct patch *patch) 870{ 871char*name; 872 873 first +=4;/* skip "--- " */ 874 second +=4;/* skip "+++ " */ 875if(!p_value_known) { 876int p, q; 877 p =guess_p_value(first); 878 q =guess_p_value(second); 879if(p <0) p = q; 880if(0<= p && p == q) { 881 p_value = p; 882 p_value_known =1; 883} 884} 885if(is_dev_null(first)) { 886 patch->is_new =1; 887 patch->is_delete =0; 888 name =find_name_traditional(second, NULL, p_value); 889 patch->new_name = name; 890}else if(is_dev_null(second)) { 891 patch->is_new =0; 892 patch->is_delete =1; 893 name =find_name_traditional(first, NULL, p_value); 894 patch->old_name = name; 895}else{ 896char*first_name; 897 first_name =find_name_traditional(first, NULL, p_value); 898 name =find_name_traditional(second, first_name, p_value); 899free(first_name); 900if(has_epoch_timestamp(first)) { 901 patch->is_new =1; 902 patch->is_delete =0; 903 patch->new_name = name; 904}else if(has_epoch_timestamp(second)) { 905 patch->is_new =0; 906 patch->is_delete =1; 907 patch->old_name = name; 908}else{ 909 patch->old_name = name; 910 patch->new_name =xstrdup(name); 911} 912} 913if(!name) 914die(_("unable to find filename in patch at line%d"), linenr); 915} 916 917static intgitdiff_hdrend(const char*line,struct patch *patch) 918{ 919return-1; 920} 921 922/* 923 * We're anal about diff header consistency, to make 924 * sure that we don't end up having strange ambiguous 925 * patches floating around. 926 * 927 * As a result, gitdiff_{old|new}name() will check 928 * their names against any previous information, just 929 * to make sure.. 930 */ 931#define DIFF_OLD_NAME 0 932#define DIFF_NEW_NAME 1 933 934static char*gitdiff_verify_name(const char*line,int isnull,char*orig_name,int side) 935{ 936if(!orig_name && !isnull) 937returnfind_name(line, NULL, p_value, TERM_TAB); 938 939if(orig_name) { 940int len; 941const char*name; 942char*another; 943 name = orig_name; 944 len =strlen(name); 945if(isnull) 946die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), name, linenr); 947 another =find_name(line, NULL, p_value, TERM_TAB); 948if(!another ||memcmp(another, name, len +1)) 949die((side == DIFF_NEW_NAME) ? 950_("git apply: bad git-diff - inconsistent new filename on line%d") : 951_("git apply: bad git-diff - inconsistent old filename on line%d"), linenr); 952free(another); 953return orig_name; 954} 955else{ 956/* expect "/dev/null" */ 957if(memcmp("/dev/null", line,9) || line[9] !='\n') 958die(_("git apply: bad git-diff - expected /dev/null on line%d"), linenr); 959return NULL; 960} 961} 962 963static intgitdiff_oldname(const char*line,struct patch *patch) 964{ 965char*orig = patch->old_name; 966 patch->old_name =gitdiff_verify_name(line, patch->is_new, patch->old_name, 967 DIFF_OLD_NAME); 968if(orig != patch->old_name) 969free(orig); 970return0; 971} 972 973static intgitdiff_newname(const char*line,struct patch *patch) 974{ 975char*orig = patch->new_name; 976 patch->new_name =gitdiff_verify_name(line, patch->is_delete, patch->new_name, 977 DIFF_NEW_NAME); 978if(orig != patch->new_name) 979free(orig); 980return0; 981} 982 983static intgitdiff_oldmode(const char*line,struct patch *patch) 984{ 985 patch->old_mode =strtoul(line, NULL,8); 986return0; 987} 988 989static intgitdiff_newmode(const char*line,struct patch *patch) 990{ 991 patch->new_mode =strtoul(line, NULL,8); 992return0; 993} 994 995static intgitdiff_delete(const char*line,struct patch *patch) 996{ 997 patch->is_delete =1; 998free(patch->old_name); 999 patch->old_name =null_strdup(patch->def_name);1000returngitdiff_oldmode(line, patch);1001}10021003static intgitdiff_newfile(const char*line,struct patch *patch)1004{1005 patch->is_new =1;1006free(patch->new_name);1007 patch->new_name =null_strdup(patch->def_name);1008returngitdiff_newmode(line, patch);1009}10101011static intgitdiff_copysrc(const char*line,struct patch *patch)1012{1013 patch->is_copy =1;1014free(patch->old_name);1015 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0);1016return0;1017}10181019static intgitdiff_copydst(const char*line,struct patch *patch)1020{1021 patch->is_copy =1;1022free(patch->new_name);1023 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0);1024return0;1025}10261027static intgitdiff_renamesrc(const char*line,struct patch *patch)1028{1029 patch->is_rename =1;1030free(patch->old_name);1031 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0);1032return0;1033}10341035static intgitdiff_renamedst(const char*line,struct patch *patch)1036{1037 patch->is_rename =1;1038free(patch->new_name);1039 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0);1040return0;1041}10421043static intgitdiff_similarity(const char*line,struct patch *patch)1044{1045if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX)1046 patch->score =0;1047return0;1048}10491050static intgitdiff_dissimilarity(const char*line,struct patch *patch)1051{1052if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX)1053 patch->score =0;1054return0;1055}10561057static intgitdiff_index(const char*line,struct patch *patch)1058{1059/*1060 * index line is N hexadecimal, "..", N hexadecimal,1061 * and optional space with octal mode.1062 */1063const char*ptr, *eol;1064int len;10651066 ptr =strchr(line,'.');1067if(!ptr || ptr[1] !='.'||40< ptr - line)1068return0;1069 len = ptr - line;1070memcpy(patch->old_sha1_prefix, line, len);1071 patch->old_sha1_prefix[len] =0;10721073 line = ptr +2;1074 ptr =strchr(line,' ');1075 eol =strchr(line,'\n');10761077if(!ptr || eol < ptr)1078 ptr = eol;1079 len = ptr - line;10801081if(40< len)1082return0;1083memcpy(patch->new_sha1_prefix, line, len);1084 patch->new_sha1_prefix[len] =0;1085if(*ptr ==' ')1086 patch->old_mode =strtoul(ptr+1, NULL,8);1087return0;1088}10891090/*1091 * This is normal for a diff that doesn't change anything: we'll fall through1092 * into the next diff. Tell the parser to break out.1093 */1094static intgitdiff_unrecognized(const char*line,struct patch *patch)1095{1096return-1;1097}10981099static const char*stop_at_slash(const char*line,int llen)1100{1101int nslash = p_value;1102int i;11031104for(i =0; i < llen; i++) {1105int ch = line[i];1106if(ch =='/'&& --nslash <=0)1107return&line[i];1108}1109return NULL;1110}11111112/*1113 * This is to extract the same name that appears on "diff --git"1114 * line. We do not find and return anything if it is a rename1115 * patch, and it is OK because we will find the name elsewhere.1116 * We need to reliably find name only when it is mode-change only,1117 * creation or deletion of an empty file. In any of these cases,1118 * both sides are the same name under a/ and b/ respectively.1119 */1120static char*git_header_name(const char*line,int llen)1121{1122const char*name;1123const char*second = NULL;1124size_t len, line_len;11251126 line +=strlen("diff --git ");1127 llen -=strlen("diff --git ");11281129if(*line =='"') {1130const char*cp;1131struct strbuf first = STRBUF_INIT;1132struct strbuf sp = STRBUF_INIT;11331134if(unquote_c_style(&first, line, &second))1135goto free_and_fail1;11361137/* advance to the first slash */1138 cp =stop_at_slash(first.buf, first.len);1139/* we do not accept absolute paths */1140if(!cp || cp == first.buf)1141goto free_and_fail1;1142strbuf_remove(&first,0, cp +1- first.buf);11431144/*1145 * second points at one past closing dq of name.1146 * find the second name.1147 */1148while((second < line + llen) &&isspace(*second))1149 second++;11501151if(line + llen <= second)1152goto free_and_fail1;1153if(*second =='"') {1154if(unquote_c_style(&sp, second, NULL))1155goto free_and_fail1;1156 cp =stop_at_slash(sp.buf, sp.len);1157if(!cp || cp == sp.buf)1158goto free_and_fail1;1159/* They must match, otherwise ignore */1160if(strcmp(cp +1, first.buf))1161goto free_and_fail1;1162strbuf_release(&sp);1163returnstrbuf_detach(&first, NULL);1164}11651166/* unquoted second */1167 cp =stop_at_slash(second, line + llen - second);1168if(!cp || cp == second)1169goto free_and_fail1;1170 cp++;1171if(line + llen - cp != first.len +1||1172memcmp(first.buf, cp, first.len))1173goto free_and_fail1;1174returnstrbuf_detach(&first, NULL);11751176 free_and_fail1:1177strbuf_release(&first);1178strbuf_release(&sp);1179return NULL;1180}11811182/* unquoted first name */1183 name =stop_at_slash(line, llen);1184if(!name || name == line)1185return NULL;1186 name++;11871188/*1189 * since the first name is unquoted, a dq if exists must be1190 * the beginning of the second name.1191 */1192for(second = name; second < line + llen; second++) {1193if(*second =='"') {1194struct strbuf sp = STRBUF_INIT;1195const char*np;11961197if(unquote_c_style(&sp, second, NULL))1198goto free_and_fail2;11991200 np =stop_at_slash(sp.buf, sp.len);1201if(!np || np == sp.buf)1202goto free_and_fail2;1203 np++;12041205 len = sp.buf + sp.len - np;1206if(len < second - name &&1207!strncmp(np, name, len) &&1208isspace(name[len])) {1209/* Good */1210strbuf_remove(&sp,0, np - sp.buf);1211returnstrbuf_detach(&sp, NULL);1212}12131214 free_and_fail2:1215strbuf_release(&sp);1216return NULL;1217}1218}12191220/*1221 * Accept a name only if it shows up twice, exactly the same1222 * form.1223 */1224 second =strchr(name,'\n');1225if(!second)1226return NULL;1227 line_len = second - name;1228for(len =0; ; len++) {1229switch(name[len]) {1230default:1231continue;1232case'\n':1233return NULL;1234case'\t':case' ':1235 second =stop_at_slash(name + len, line_len - len);1236if(!second)1237return NULL;1238 second++;1239if(second[len] =='\n'&& !strncmp(name, second, len)) {1240returnxmemdupz(name, len);1241}1242}1243}1244}12451246/* Verify that we recognize the lines following a git header */1247static intparse_git_header(const char*line,int len,unsigned int size,struct patch *patch)1248{1249unsigned long offset;12501251/* A git diff has explicit new/delete information, so we don't guess */1252 patch->is_new =0;1253 patch->is_delete =0;12541255/*1256 * Some things may not have the old name in the1257 * rest of the headers anywhere (pure mode changes,1258 * or removing or adding empty files), so we get1259 * the default name from the header.1260 */1261 patch->def_name =git_header_name(line, len);1262if(patch->def_name && root) {1263char*s =xmalloc(root_len +strlen(patch->def_name) +1);1264strcpy(s, root);1265strcpy(s + root_len, patch->def_name);1266free(patch->def_name);1267 patch->def_name = s;1268}12691270 line += len;1271 size -= len;1272 linenr++;1273for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) {1274static const struct opentry {1275const char*str;1276int(*fn)(const char*,struct patch *);1277} optable[] = {1278{"@@ -", gitdiff_hdrend },1279{"--- ", gitdiff_oldname },1280{"+++ ", gitdiff_newname },1281{"old mode ", gitdiff_oldmode },1282{"new mode ", gitdiff_newmode },1283{"deleted file mode ", gitdiff_delete },1284{"new file mode ", gitdiff_newfile },1285{"copy from ", gitdiff_copysrc },1286{"copy to ", gitdiff_copydst },1287{"rename old ", gitdiff_renamesrc },1288{"rename new ", gitdiff_renamedst },1289{"rename from ", gitdiff_renamesrc },1290{"rename to ", gitdiff_renamedst },1291{"similarity index ", gitdiff_similarity },1292{"dissimilarity index ", gitdiff_dissimilarity },1293{"index ", gitdiff_index },1294{"", gitdiff_unrecognized },1295};1296int i;12971298 len =linelen(line, size);1299if(!len || line[len-1] !='\n')1300break;1301for(i =0; i <ARRAY_SIZE(optable); i++) {1302const struct opentry *p = optable + i;1303int oplen =strlen(p->str);1304if(len < oplen ||memcmp(p->str, line, oplen))1305continue;1306if(p->fn(line + oplen, patch) <0)1307return offset;1308break;1309}1310}13111312return offset;1313}13141315static intparse_num(const char*line,unsigned long*p)1316{1317char*ptr;13181319if(!isdigit(*line))1320return0;1321*p =strtoul(line, &ptr,10);1322return ptr - line;1323}13241325static intparse_range(const char*line,int len,int offset,const char*expect,1326unsigned long*p1,unsigned long*p2)1327{1328int digits, ex;13291330if(offset <0|| offset >= len)1331return-1;1332 line += offset;1333 len -= offset;13341335 digits =parse_num(line, p1);1336if(!digits)1337return-1;13381339 offset += digits;1340 line += digits;1341 len -= digits;13421343*p2 =1;1344if(*line ==',') {1345 digits =parse_num(line+1, p2);1346if(!digits)1347return-1;13481349 offset += digits+1;1350 line += digits+1;1351 len -= digits+1;1352}13531354 ex =strlen(expect);1355if(ex > len)1356return-1;1357if(memcmp(line, expect, ex))1358return-1;13591360return offset + ex;1361}13621363static voidrecount_diff(const char*line,int size,struct fragment *fragment)1364{1365int oldlines =0, newlines =0, ret =0;13661367if(size <1) {1368warning("recount: ignore empty hunk");1369return;1370}13711372for(;;) {1373int len =linelen(line, size);1374 size -= len;1375 line += len;13761377if(size <1)1378break;13791380switch(*line) {1381case' ':case'\n':1382 newlines++;1383/* fall through */1384case'-':1385 oldlines++;1386continue;1387case'+':1388 newlines++;1389continue;1390case'\\':1391continue;1392case'@':1393 ret = size <3||prefixcmp(line,"@@ ");1394break;1395case'd':1396 ret = size <5||prefixcmp(line,"diff ");1397break;1398default:1399 ret = -1;1400break;1401}1402if(ret) {1403warning(_("recount: unexpected line: %.*s"),1404(int)linelen(line, size), line);1405return;1406}1407break;1408}1409 fragment->oldlines = oldlines;1410 fragment->newlines = newlines;1411}14121413/*1414 * Parse a unified diff fragment header of the1415 * form "@@ -a,b +c,d @@"1416 */1417static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1418{1419int offset;14201421if(!len || line[len-1] !='\n')1422return-1;14231424/* Figure out the number of lines in a fragment */1425 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1426 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14271428return offset;1429}14301431static intfind_header(const char*line,unsigned long size,int*hdrsize,struct patch *patch)1432{1433unsigned long offset, len;14341435 patch->is_toplevel_relative =0;1436 patch->is_rename = patch->is_copy =0;1437 patch->is_new = patch->is_delete = -1;1438 patch->old_mode = patch->new_mode =0;1439 patch->old_name = patch->new_name = NULL;1440for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) {1441unsigned long nextlen;14421443 len =linelen(line, size);1444if(!len)1445break;14461447/* Testing this early allows us to take a few shortcuts.. */1448if(len <6)1449continue;14501451/*1452 * Make sure we don't find any unconnected patch fragments.1453 * That's a sign that we didn't find a header, and that a1454 * patch has become corrupted/broken up.1455 */1456if(!memcmp("@@ -", line,4)) {1457struct fragment dummy;1458if(parse_fragment_header(line, len, &dummy) <0)1459continue;1460die(_("patch fragment without header at line%d: %.*s"),1461 linenr, (int)len-1, line);1462}14631464if(size < len +6)1465break;14661467/*1468 * Git patch? It might not have a real patch, just a rename1469 * or mode change, so we handle that specially1470 */1471if(!memcmp("diff --git ", line,11)) {1472int git_hdr_len =parse_git_header(line, len, size, patch);1473if(git_hdr_len <= len)1474continue;1475if(!patch->old_name && !patch->new_name) {1476if(!patch->def_name)1477die(Q_("git diff header lacks filename information when removing "1478"%dleading pathname component (line%d)",1479"git diff header lacks filename information when removing "1480"%dleading pathname components (line%d)",1481 p_value),1482 p_value, linenr);1483 patch->old_name =xstrdup(patch->def_name);1484 patch->new_name =xstrdup(patch->def_name);1485}1486if(!patch->is_delete && !patch->new_name)1487die("git diff header lacks filename information "1488"(line%d)", linenr);1489 patch->is_toplevel_relative =1;1490*hdrsize = git_hdr_len;1491return offset;1492}14931494/* --- followed by +++ ? */1495if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1496continue;14971498/*1499 * We only accept unified patches, so we want it to1500 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1501 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1502 */1503 nextlen =linelen(line + len, size - len);1504if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1505continue;15061507/* Ok, we'll consider it a patch */1508parse_traditional_patch(line, line+len, patch);1509*hdrsize = len + nextlen;1510 linenr +=2;1511return offset;1512}1513return-1;1514}15151516static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1517{1518char*err;15191520if(!result)1521return;15221523 whitespace_error++;1524if(squelch_whitespace_errors &&1525 squelch_whitespace_errors < whitespace_error)1526return;15271528 err =whitespace_error_string(result);1529fprintf(stderr,"%s:%d:%s.\n%.*s\n",1530 patch_input_file, linenr, err, len, line);1531free(err);1532}15331534static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1535{1536unsigned result =ws_check(line +1, len -1, ws_rule);15371538record_ws_error(result, line +1, len -2, linenr);1539}15401541/*1542 * Parse a unified diff. Note that this really needs to parse each1543 * fragment separately, since the only way to know the difference1544 * between a "---" that is part of a patch, and a "---" that starts1545 * the next patch is to look at the line counts..1546 */1547static intparse_fragment(const char*line,unsigned long size,1548struct patch *patch,struct fragment *fragment)1549{1550int added, deleted;1551int len =linelen(line, size), offset;1552unsigned long oldlines, newlines;1553unsigned long leading, trailing;15541555 offset =parse_fragment_header(line, len, fragment);1556if(offset <0)1557return-1;1558if(offset >0&& patch->recount)1559recount_diff(line + offset, size - offset, fragment);1560 oldlines = fragment->oldlines;1561 newlines = fragment->newlines;1562 leading =0;1563 trailing =0;15641565/* Parse the thing.. */1566 line += len;1567 size -= len;1568 linenr++;1569 added = deleted =0;1570for(offset = len;15710< size;1572 offset += len, size -= len, line += len, linenr++) {1573if(!oldlines && !newlines)1574break;1575 len =linelen(line, size);1576if(!len || line[len-1] !='\n')1577return-1;1578switch(*line) {1579default:1580return-1;1581case'\n':/* newer GNU diff, an empty context line */1582case' ':1583 oldlines--;1584 newlines--;1585if(!deleted && !added)1586 leading++;1587 trailing++;1588break;1589case'-':1590if(apply_in_reverse &&1591 ws_error_action != nowarn_ws_error)1592check_whitespace(line, len, patch->ws_rule);1593 deleted++;1594 oldlines--;1595 trailing =0;1596break;1597case'+':1598if(!apply_in_reverse &&1599 ws_error_action != nowarn_ws_error)1600check_whitespace(line, len, patch->ws_rule);1601 added++;1602 newlines--;1603 trailing =0;1604break;16051606/*1607 * We allow "\ No newline at end of file". Depending1608 * on locale settings when the patch was produced we1609 * don't know what this line looks like. The only1610 * thing we do know is that it begins with "\ ".1611 * Checking for 12 is just for sanity check -- any1612 * l10n of "\ No newline..." is at least that long.1613 */1614case'\\':1615if(len <12||memcmp(line,"\\",2))1616return-1;1617break;1618}1619}1620if(oldlines || newlines)1621return-1;1622 fragment->leading = leading;1623 fragment->trailing = trailing;16241625/*1626 * If a fragment ends with an incomplete line, we failed to include1627 * it in the above loop because we hit oldlines == newlines == 01628 * before seeing it.1629 */1630if(12< size && !memcmp(line,"\\",2))1631 offset +=linelen(line, size);16321633 patch->lines_added += added;1634 patch->lines_deleted += deleted;16351636if(0< patch->is_new && oldlines)1637returnerror(_("new file depends on old contents"));1638if(0< patch->is_delete && newlines)1639returnerror(_("deleted file still has contents"));1640return offset;1641}16421643/*1644 * We have seen "diff --git a/... b/..." header (or a traditional patch1645 * header). Read hunks that belong to this patch into fragments and hang1646 * them to the given patch structure.1647 *1648 * The (fragment->patch, fragment->size) pair points into the memory given1649 * by the caller, not a copy, when we return.1650 */1651static intparse_single_patch(const char*line,unsigned long size,struct patch *patch)1652{1653unsigned long offset =0;1654unsigned long oldlines =0, newlines =0, context =0;1655struct fragment **fragp = &patch->fragments;16561657while(size >4&& !memcmp(line,"@@ -",4)) {1658struct fragment *fragment;1659int len;16601661 fragment =xcalloc(1,sizeof(*fragment));1662 fragment->linenr = linenr;1663 len =parse_fragment(line, size, patch, fragment);1664if(len <=0)1665die(_("corrupt patch at line%d"), linenr);1666 fragment->patch = line;1667 fragment->size = len;1668 oldlines += fragment->oldlines;1669 newlines += fragment->newlines;1670 context += fragment->leading + fragment->trailing;16711672*fragp = fragment;1673 fragp = &fragment->next;16741675 offset += len;1676 line += len;1677 size -= len;1678}16791680/*1681 * If something was removed (i.e. we have old-lines) it cannot1682 * be creation, and if something was added it cannot be1683 * deletion. However, the reverse is not true; --unified=01684 * patches that only add are not necessarily creation even1685 * though they do not have any old lines, and ones that only1686 * delete are not necessarily deletion.1687 *1688 * Unfortunately, a real creation/deletion patch do _not_ have1689 * any context line by definition, so we cannot safely tell it1690 * apart with --unified=0 insanity. At least if the patch has1691 * more than one hunk it is not creation or deletion.1692 */1693if(patch->is_new <0&&1694(oldlines || (patch->fragments && patch->fragments->next)))1695 patch->is_new =0;1696if(patch->is_delete <0&&1697(newlines || (patch->fragments && patch->fragments->next)))1698 patch->is_delete =0;16991700if(0< patch->is_new && oldlines)1701die(_("new file%sdepends on old contents"), patch->new_name);1702if(0< patch->is_delete && newlines)1703die(_("deleted file%sstill has contents"), patch->old_name);1704if(!patch->is_delete && !newlines && context)1705fprintf_ln(stderr,1706_("** warning: "1707"file%sbecomes empty but is not deleted"),1708 patch->new_name);17091710return offset;1711}17121713staticinlineintmetadata_changes(struct patch *patch)1714{1715return patch->is_rename >0||1716 patch->is_copy >0||1717 patch->is_new >0||1718 patch->is_delete ||1719(patch->old_mode && patch->new_mode &&1720 patch->old_mode != patch->new_mode);1721}17221723static char*inflate_it(const void*data,unsigned long size,1724unsigned long inflated_size)1725{1726 git_zstream stream;1727void*out;1728int st;17291730memset(&stream,0,sizeof(stream));17311732 stream.next_in = (unsigned char*)data;1733 stream.avail_in = size;1734 stream.next_out = out =xmalloc(inflated_size);1735 stream.avail_out = inflated_size;1736git_inflate_init(&stream);1737 st =git_inflate(&stream, Z_FINISH);1738git_inflate_end(&stream);1739if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1740free(out);1741return NULL;1742}1743return out;1744}17451746/*1747 * Read a binary hunk and return a new fragment; fragment->patch1748 * points at an allocated memory that the caller must free, so1749 * it is marked as "->free_patch = 1".1750 */1751static struct fragment *parse_binary_hunk(char**buf_p,1752unsigned long*sz_p,1753int*status_p,1754int*used_p)1755{1756/*1757 * Expect a line that begins with binary patch method ("literal"1758 * or "delta"), followed by the length of data before deflating.1759 * a sequence of 'length-byte' followed by base-85 encoded data1760 * should follow, terminated by a newline.1761 *1762 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1763 * and we would limit the patch line to 66 characters,1764 * so one line can fit up to 13 groups that would decode1765 * to 52 bytes max. The length byte 'A'-'Z' corresponds1766 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1767 */1768int llen, used;1769unsigned long size = *sz_p;1770char*buffer = *buf_p;1771int patch_method;1772unsigned long origlen;1773char*data = NULL;1774int hunk_size =0;1775struct fragment *frag;17761777 llen =linelen(buffer, size);1778 used = llen;17791780*status_p =0;17811782if(!prefixcmp(buffer,"delta ")) {1783 patch_method = BINARY_DELTA_DEFLATED;1784 origlen =strtoul(buffer +6, NULL,10);1785}1786else if(!prefixcmp(buffer,"literal ")) {1787 patch_method = BINARY_LITERAL_DEFLATED;1788 origlen =strtoul(buffer +8, NULL,10);1789}1790else1791return NULL;17921793 linenr++;1794 buffer += llen;1795while(1) {1796int byte_length, max_byte_length, newsize;1797 llen =linelen(buffer, size);1798 used += llen;1799 linenr++;1800if(llen ==1) {1801/* consume the blank line */1802 buffer++;1803 size--;1804break;1805}1806/*1807 * Minimum line is "A00000\n" which is 7-byte long,1808 * and the line length must be multiple of 5 plus 2.1809 */1810if((llen <7) || (llen-2) %5)1811goto corrupt;1812 max_byte_length = (llen -2) /5*4;1813 byte_length = *buffer;1814if('A'<= byte_length && byte_length <='Z')1815 byte_length = byte_length -'A'+1;1816else if('a'<= byte_length && byte_length <='z')1817 byte_length = byte_length -'a'+27;1818else1819goto corrupt;1820/* if the input length was not multiple of 4, we would1821 * have filler at the end but the filler should never1822 * exceed 3 bytes1823 */1824if(max_byte_length < byte_length ||1825 byte_length <= max_byte_length -4)1826goto corrupt;1827 newsize = hunk_size + byte_length;1828 data =xrealloc(data, newsize);1829if(decode_85(data + hunk_size, buffer +1, byte_length))1830goto corrupt;1831 hunk_size = newsize;1832 buffer += llen;1833 size -= llen;1834}18351836 frag =xcalloc(1,sizeof(*frag));1837 frag->patch =inflate_it(data, hunk_size, origlen);1838 frag->free_patch =1;1839if(!frag->patch)1840goto corrupt;1841free(data);1842 frag->size = origlen;1843*buf_p = buffer;1844*sz_p = size;1845*used_p = used;1846 frag->binary_patch_method = patch_method;1847return frag;18481849 corrupt:1850free(data);1851*status_p = -1;1852error(_("corrupt binary patch at line%d: %.*s"),1853 linenr-1, llen-1, buffer);1854return NULL;1855}18561857static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1858{1859/*1860 * We have read "GIT binary patch\n"; what follows is a line1861 * that says the patch method (currently, either "literal" or1862 * "delta") and the length of data before deflating; a1863 * sequence of 'length-byte' followed by base-85 encoded data1864 * follows.1865 *1866 * When a binary patch is reversible, there is another binary1867 * hunk in the same format, starting with patch method (either1868 * "literal" or "delta") with the length of data, and a sequence1869 * of length-byte + base-85 encoded data, terminated with another1870 * empty line. This data, when applied to the postimage, produces1871 * the preimage.1872 */1873struct fragment *forward;1874struct fragment *reverse;1875int status;1876int used, used_1;18771878 forward =parse_binary_hunk(&buffer, &size, &status, &used);1879if(!forward && !status)1880/* there has to be one hunk (forward hunk) */1881returnerror(_("unrecognized binary patch at line%d"), linenr-1);1882if(status)1883/* otherwise we already gave an error message */1884return status;18851886 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1887if(reverse)1888 used += used_1;1889else if(status) {1890/*1891 * Not having reverse hunk is not an error, but having1892 * a corrupt reverse hunk is.1893 */1894free((void*) forward->patch);1895free(forward);1896return status;1897}1898 forward->next = reverse;1899 patch->fragments = forward;1900 patch->is_binary =1;1901return used;1902}19031904/*1905 * Read the patch text in "buffer" taht extends for "size" bytes; stop1906 * reading after seeing a single patch (i.e. changes to a single file).1907 * Create fragments (i.e. patch hunks) and hang them to the given patch.1908 * Return the number of bytes consumed, so that the caller can call us1909 * again for the next patch.1910 */1911static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1912{1913int hdrsize, patchsize;1914int offset =find_header(buffer, size, &hdrsize, patch);19151916if(offset <0)1917return offset;19181919 patch->ws_rule =whitespace_rule(patch->new_name1920? patch->new_name1921: patch->old_name);19221923 patchsize =parse_single_patch(buffer + offset + hdrsize,1924 size - offset - hdrsize, patch);19251926if(!patchsize) {1927static const char*binhdr[] = {1928"Binary files ",1929"Files ",1930 NULL,1931};1932static const char git_binary[] ="GIT binary patch\n";1933int i;1934int hd = hdrsize + offset;1935unsigned long llen =linelen(buffer + hd, size - hd);19361937if(llen ==sizeof(git_binary) -1&&1938!memcmp(git_binary, buffer + hd, llen)) {1939int used;1940 linenr++;1941 used =parse_binary(buffer + hd + llen,1942 size - hd - llen, patch);1943if(used)1944 patchsize = used + llen;1945else1946 patchsize =0;1947}1948else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1949for(i =0; binhdr[i]; i++) {1950int len =strlen(binhdr[i]);1951if(len < size - hd &&1952!memcmp(binhdr[i], buffer + hd, len)) {1953 linenr++;1954 patch->is_binary =1;1955 patchsize = llen;1956break;1957}1958}1959}19601961/* Empty patch cannot be applied if it is a text patch1962 * without metadata change. A binary patch appears1963 * empty to us here.1964 */1965if((apply || check) &&1966(!patch->is_binary && !metadata_changes(patch)))1967die(_("patch with only garbage at line%d"), linenr);1968}19691970return offset + hdrsize + patchsize;1971}19721973#define swap(a,b) myswap((a),(b),sizeof(a))19741975#define myswap(a, b, size) do { \1976 unsigned char mytmp[size]; \1977 memcpy(mytmp, &a, size); \1978 memcpy(&a, &b, size); \1979 memcpy(&b, mytmp, size); \1980} while (0)19811982static voidreverse_patches(struct patch *p)1983{1984for(; p; p = p->next) {1985struct fragment *frag = p->fragments;19861987swap(p->new_name, p->old_name);1988swap(p->new_mode, p->old_mode);1989swap(p->is_new, p->is_delete);1990swap(p->lines_added, p->lines_deleted);1991swap(p->old_sha1_prefix, p->new_sha1_prefix);19921993for(; frag; frag = frag->next) {1994swap(frag->newpos, frag->oldpos);1995swap(frag->newlines, frag->oldlines);1996}1997}1998}19992000static const char pluses[] =2001"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2002static const char minuses[]=2003"----------------------------------------------------------------------";20042005static voidshow_stats(struct patch *patch)2006{2007struct strbuf qname = STRBUF_INIT;2008char*cp = patch->new_name ? patch->new_name : patch->old_name;2009int max, add, del;20102011quote_c_style(cp, &qname, NULL,0);20122013/*2014 * "scale" the filename2015 */2016 max = max_len;2017if(max >50)2018 max =50;20192020if(qname.len > max) {2021 cp =strchr(qname.buf + qname.len +3- max,'/');2022if(!cp)2023 cp = qname.buf + qname.len +3- max;2024strbuf_splice(&qname,0, cp - qname.buf,"...",3);2025}20262027if(patch->is_binary) {2028printf(" %-*s | Bin\n", max, qname.buf);2029strbuf_release(&qname);2030return;2031}20322033printf(" %-*s |", max, qname.buf);2034strbuf_release(&qname);20352036/*2037 * scale the add/delete2038 */2039 max = max + max_change >70?70- max : max_change;2040 add = patch->lines_added;2041 del = patch->lines_deleted;20422043if(max_change >0) {2044int total = ((add + del) * max + max_change /2) / max_change;2045 add = (add * max + max_change /2) / max_change;2046 del = total - add;2047}2048printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2049 add, pluses, del, minuses);2050}20512052static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2053{2054switch(st->st_mode & S_IFMT) {2055case S_IFLNK:2056if(strbuf_readlink(buf, path, st->st_size) <0)2057returnerror(_("unable to read symlink%s"), path);2058return0;2059case S_IFREG:2060if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2061returnerror(_("unable to open or read%s"), path);2062convert_to_git(path, buf->buf, buf->len, buf,0);2063return0;2064default:2065return-1;2066}2067}20682069/*2070 * Update the preimage, and the common lines in postimage,2071 * from buffer buf of length len. If postlen is 0 the postimage2072 * is updated in place, otherwise it's updated on a new buffer2073 * of length postlen2074 */20752076static voidupdate_pre_post_images(struct image *preimage,2077struct image *postimage,2078char*buf,2079size_t len,size_t postlen)2080{2081int i, ctx;2082char*new, *old, *fixed;2083struct image fixed_preimage;20842085/*2086 * Update the preimage with whitespace fixes. Note that we2087 * are not losing preimage->buf -- apply_one_fragment() will2088 * free "oldlines".2089 */2090prepare_image(&fixed_preimage, buf, len,1);2091assert(fixed_preimage.nr == preimage->nr);2092for(i =0; i < preimage->nr; i++)2093 fixed_preimage.line[i].flag = preimage->line[i].flag;2094free(preimage->line_allocated);2095*preimage = fixed_preimage;20962097/*2098 * Adjust the common context lines in postimage. This can be2099 * done in-place when we are just doing whitespace fixing,2100 * which does not make the string grow, but needs a new buffer2101 * when ignoring whitespace causes the update, since in this case2102 * we could have e.g. tabs converted to multiple spaces.2103 * We trust the caller to tell us if the update can be done2104 * in place (postlen==0) or not.2105 */2106 old = postimage->buf;2107if(postlen)2108new= postimage->buf =xmalloc(postlen);2109else2110new= old;2111 fixed = preimage->buf;2112for(i = ctx =0; i < postimage->nr; i++) {2113size_t len = postimage->line[i].len;2114if(!(postimage->line[i].flag & LINE_COMMON)) {2115/* an added line -- no counterparts in preimage */2116memmove(new, old, len);2117 old += len;2118new+= len;2119continue;2120}21212122/* a common context -- skip it in the original postimage */2123 old += len;21242125/* and find the corresponding one in the fixed preimage */2126while(ctx < preimage->nr &&2127!(preimage->line[ctx].flag & LINE_COMMON)) {2128 fixed += preimage->line[ctx].len;2129 ctx++;2130}2131if(preimage->nr <= ctx)2132die(_("oops"));21332134/* and copy it in, while fixing the line length */2135 len = preimage->line[ctx].len;2136memcpy(new, fixed, len);2137new+= len;2138 fixed += len;2139 postimage->line[i].len = len;2140 ctx++;2141}21422143/* Fix the length of the whole thing */2144 postimage->len =new- postimage->buf;2145}21462147static intmatch_fragment(struct image *img,2148struct image *preimage,2149struct image *postimage,2150unsigned longtry,2151int try_lno,2152unsigned ws_rule,2153int match_beginning,int match_end)2154{2155int i;2156char*fixed_buf, *buf, *orig, *target;2157struct strbuf fixed;2158size_t fixed_len;2159int preimage_limit;21602161if(preimage->nr + try_lno <= img->nr) {2162/*2163 * The hunk falls within the boundaries of img.2164 */2165 preimage_limit = preimage->nr;2166if(match_end && (preimage->nr + try_lno != img->nr))2167return0;2168}else if(ws_error_action == correct_ws_error &&2169(ws_rule & WS_BLANK_AT_EOF)) {2170/*2171 * This hunk extends beyond the end of img, and we are2172 * removing blank lines at the end of the file. This2173 * many lines from the beginning of the preimage must2174 * match with img, and the remainder of the preimage2175 * must be blank.2176 */2177 preimage_limit = img->nr - try_lno;2178}else{2179/*2180 * The hunk extends beyond the end of the img and2181 * we are not removing blanks at the end, so we2182 * should reject the hunk at this position.2183 */2184return0;2185}21862187if(match_beginning && try_lno)2188return0;21892190/* Quick hash check */2191for(i =0; i < preimage_limit; i++)2192if((img->line[try_lno + i].flag & LINE_PATCHED) ||2193(preimage->line[i].hash != img->line[try_lno + i].hash))2194return0;21952196if(preimage_limit == preimage->nr) {2197/*2198 * Do we have an exact match? If we were told to match2199 * at the end, size must be exactly at try+fragsize,2200 * otherwise try+fragsize must be still within the preimage,2201 * and either case, the old piece should match the preimage2202 * exactly.2203 */2204if((match_end2205? (try+ preimage->len == img->len)2206: (try+ preimage->len <= img->len)) &&2207!memcmp(img->buf +try, preimage->buf, preimage->len))2208return1;2209}else{2210/*2211 * The preimage extends beyond the end of img, so2212 * there cannot be an exact match.2213 *2214 * There must be one non-blank context line that match2215 * a line before the end of img.2216 */2217char*buf_end;22182219 buf = preimage->buf;2220 buf_end = buf;2221for(i =0; i < preimage_limit; i++)2222 buf_end += preimage->line[i].len;22232224for( ; buf < buf_end; buf++)2225if(!isspace(*buf))2226break;2227if(buf == buf_end)2228return0;2229}22302231/*2232 * No exact match. If we are ignoring whitespace, run a line-by-line2233 * fuzzy matching. We collect all the line length information because2234 * we need it to adjust whitespace if we match.2235 */2236if(ws_ignore_action == ignore_ws_change) {2237size_t imgoff =0;2238size_t preoff =0;2239size_t postlen = postimage->len;2240size_t extra_chars;2241char*preimage_eof;2242char*preimage_end;2243for(i =0; i < preimage_limit; i++) {2244size_t prelen = preimage->line[i].len;2245size_t imglen = img->line[try_lno+i].len;22462247if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2248 preimage->buf + preoff, prelen))2249return0;2250if(preimage->line[i].flag & LINE_COMMON)2251 postlen += imglen - prelen;2252 imgoff += imglen;2253 preoff += prelen;2254}22552256/*2257 * Ok, the preimage matches with whitespace fuzz.2258 *2259 * imgoff now holds the true length of the target that2260 * matches the preimage before the end of the file.2261 *2262 * Count the number of characters in the preimage that fall2263 * beyond the end of the file and make sure that all of them2264 * are whitespace characters. (This can only happen if2265 * we are removing blank lines at the end of the file.)2266 */2267 buf = preimage_eof = preimage->buf + preoff;2268for( ; i < preimage->nr; i++)2269 preoff += preimage->line[i].len;2270 preimage_end = preimage->buf + preoff;2271for( ; buf < preimage_end; buf++)2272if(!isspace(*buf))2273return0;22742275/*2276 * Update the preimage and the common postimage context2277 * lines to use the same whitespace as the target.2278 * If whitespace is missing in the target (i.e.2279 * if the preimage extends beyond the end of the file),2280 * use the whitespace from the preimage.2281 */2282 extra_chars = preimage_end - preimage_eof;2283strbuf_init(&fixed, imgoff + extra_chars);2284strbuf_add(&fixed, img->buf +try, imgoff);2285strbuf_add(&fixed, preimage_eof, extra_chars);2286 fixed_buf =strbuf_detach(&fixed, &fixed_len);2287update_pre_post_images(preimage, postimage,2288 fixed_buf, fixed_len, postlen);2289return1;2290}22912292if(ws_error_action != correct_ws_error)2293return0;22942295/*2296 * The hunk does not apply byte-by-byte, but the hash says2297 * it might with whitespace fuzz. We haven't been asked to2298 * ignore whitespace, we were asked to correct whitespace2299 * errors, so let's try matching after whitespace correction.2300 *2301 * The preimage may extend beyond the end of the file,2302 * but in this loop we will only handle the part of the2303 * preimage that falls within the file.2304 */2305strbuf_init(&fixed, preimage->len +1);2306 orig = preimage->buf;2307 target = img->buf +try;2308for(i =0; i < preimage_limit; i++) {2309size_t oldlen = preimage->line[i].len;2310size_t tgtlen = img->line[try_lno + i].len;2311size_t fixstart = fixed.len;2312struct strbuf tgtfix;2313int match;23142315/* Try fixing the line in the preimage */2316ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);23172318/* Try fixing the line in the target */2319strbuf_init(&tgtfix, tgtlen);2320ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);23212322/*2323 * If they match, either the preimage was based on2324 * a version before our tree fixed whitespace breakage,2325 * or we are lacking a whitespace-fix patch the tree2326 * the preimage was based on already had (i.e. target2327 * has whitespace breakage, the preimage doesn't).2328 * In either case, we are fixing the whitespace breakages2329 * so we might as well take the fix together with their2330 * real change.2331 */2332 match = (tgtfix.len == fixed.len - fixstart &&2333!memcmp(tgtfix.buf, fixed.buf + fixstart,2334 fixed.len - fixstart));23352336strbuf_release(&tgtfix);2337if(!match)2338goto unmatch_exit;23392340 orig += oldlen;2341 target += tgtlen;2342}234323442345/*2346 * Now handle the lines in the preimage that falls beyond the2347 * end of the file (if any). They will only match if they are2348 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2349 * false).2350 */2351for( ; i < preimage->nr; i++) {2352size_t fixstart = fixed.len;/* start of the fixed preimage */2353size_t oldlen = preimage->line[i].len;2354int j;23552356/* Try fixing the line in the preimage */2357ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);23582359for(j = fixstart; j < fixed.len; j++)2360if(!isspace(fixed.buf[j]))2361goto unmatch_exit;23622363 orig += oldlen;2364}23652366/*2367 * Yes, the preimage is based on an older version that still2368 * has whitespace breakages unfixed, and fixing them makes the2369 * hunk match. Update the context lines in the postimage.2370 */2371 fixed_buf =strbuf_detach(&fixed, &fixed_len);2372update_pre_post_images(preimage, postimage,2373 fixed_buf, fixed_len,0);2374return1;23752376 unmatch_exit:2377strbuf_release(&fixed);2378return0;2379}23802381static intfind_pos(struct image *img,2382struct image *preimage,2383struct image *postimage,2384int line,2385unsigned ws_rule,2386int match_beginning,int match_end)2387{2388int i;2389unsigned long backwards, forwards,try;2390int backwards_lno, forwards_lno, try_lno;23912392/*2393 * If match_beginning or match_end is specified, there is no2394 * point starting from a wrong line that will never match and2395 * wander around and wait for a match at the specified end.2396 */2397if(match_beginning)2398 line =0;2399else if(match_end)2400 line = img->nr - preimage->nr;24012402/*2403 * Because the comparison is unsigned, the following test2404 * will also take care of a negative line number that can2405 * result when match_end and preimage is larger than the target.2406 */2407if((size_t) line > img->nr)2408 line = img->nr;24092410try=0;2411for(i =0; i < line; i++)2412try+= img->line[i].len;24132414/*2415 * There's probably some smart way to do this, but I'll leave2416 * that to the smart and beautiful people. I'm simple and stupid.2417 */2418 backwards =try;2419 backwards_lno = line;2420 forwards =try;2421 forwards_lno = line;2422 try_lno = line;24232424for(i =0; ; i++) {2425if(match_fragment(img, preimage, postimage,2426try, try_lno, ws_rule,2427 match_beginning, match_end))2428return try_lno;24292430 again:2431if(backwards_lno ==0&& forwards_lno == img->nr)2432break;24332434if(i &1) {2435if(backwards_lno ==0) {2436 i++;2437goto again;2438}2439 backwards_lno--;2440 backwards -= img->line[backwards_lno].len;2441try= backwards;2442 try_lno = backwards_lno;2443}else{2444if(forwards_lno == img->nr) {2445 i++;2446goto again;2447}2448 forwards += img->line[forwards_lno].len;2449 forwards_lno++;2450try= forwards;2451 try_lno = forwards_lno;2452}24532454}2455return-1;2456}24572458static voidremove_first_line(struct image *img)2459{2460 img->buf += img->line[0].len;2461 img->len -= img->line[0].len;2462 img->line++;2463 img->nr--;2464}24652466static voidremove_last_line(struct image *img)2467{2468 img->len -= img->line[--img->nr].len;2469}24702471/*2472 * The change from "preimage" and "postimage" has been found to2473 * apply at applied_pos (counts in line numbers) in "img".2474 * Update "img" to remove "preimage" and replace it with "postimage".2475 */2476static voidupdate_image(struct image *img,2477int applied_pos,2478struct image *preimage,2479struct image *postimage)2480{2481/*2482 * remove the copy of preimage at offset in img2483 * and replace it with postimage2484 */2485int i, nr;2486size_t remove_count, insert_count, applied_at =0;2487char*result;2488int preimage_limit;24892490/*2491 * If we are removing blank lines at the end of img,2492 * the preimage may extend beyond the end.2493 * If that is the case, we must be careful only to2494 * remove the part of the preimage that falls within2495 * the boundaries of img. Initialize preimage_limit2496 * to the number of lines in the preimage that falls2497 * within the boundaries.2498 */2499 preimage_limit = preimage->nr;2500if(preimage_limit > img->nr - applied_pos)2501 preimage_limit = img->nr - applied_pos;25022503for(i =0; i < applied_pos; i++)2504 applied_at += img->line[i].len;25052506 remove_count =0;2507for(i =0; i < preimage_limit; i++)2508 remove_count += img->line[applied_pos + i].len;2509 insert_count = postimage->len;25102511/* Adjust the contents */2512 result =xmalloc(img->len + insert_count - remove_count +1);2513memcpy(result, img->buf, applied_at);2514memcpy(result + applied_at, postimage->buf, postimage->len);2515memcpy(result + applied_at + postimage->len,2516 img->buf + (applied_at + remove_count),2517 img->len - (applied_at + remove_count));2518free(img->buf);2519 img->buf = result;2520 img->len += insert_count - remove_count;2521 result[img->len] ='\0';25222523/* Adjust the line table */2524 nr = img->nr + postimage->nr - preimage_limit;2525if(preimage_limit < postimage->nr) {2526/*2527 * NOTE: this knows that we never call remove_first_line()2528 * on anything other than pre/post image.2529 */2530 img->line =xrealloc(img->line, nr *sizeof(*img->line));2531 img->line_allocated = img->line;2532}2533if(preimage_limit != postimage->nr)2534memmove(img->line + applied_pos + postimage->nr,2535 img->line + applied_pos + preimage_limit,2536(img->nr - (applied_pos + preimage_limit)) *2537sizeof(*img->line));2538memcpy(img->line + applied_pos,2539 postimage->line,2540 postimage->nr *sizeof(*img->line));2541if(!allow_overlap)2542for(i =0; i < postimage->nr; i++)2543 img->line[applied_pos + i].flag |= LINE_PATCHED;2544 img->nr = nr;2545}25462547/*2548 * Use the patch-hunk text in "frag" to prepare two images (preimage and2549 * postimage) for the hunk. Find lines that match "preimage" in "img" and2550 * replace the part of "img" with "postimage" text.2551 */2552static intapply_one_fragment(struct image *img,struct fragment *frag,2553int inaccurate_eof,unsigned ws_rule,2554int nth_fragment)2555{2556int match_beginning, match_end;2557const char*patch = frag->patch;2558int size = frag->size;2559char*old, *oldlines;2560struct strbuf newlines;2561int new_blank_lines_at_end =0;2562int found_new_blank_lines_at_end =0;2563int hunk_linenr = frag->linenr;2564unsigned long leading, trailing;2565int pos, applied_pos;2566struct image preimage;2567struct image postimage;25682569memset(&preimage,0,sizeof(preimage));2570memset(&postimage,0,sizeof(postimage));2571 oldlines =xmalloc(size);2572strbuf_init(&newlines, size);25732574 old = oldlines;2575while(size >0) {2576char first;2577int len =linelen(patch, size);2578int plen;2579int added_blank_line =0;2580int is_blank_context =0;2581size_t start;25822583if(!len)2584break;25852586/*2587 * "plen" is how much of the line we should use for2588 * the actual patch data. Normally we just remove the2589 * first character on the line, but if the line is2590 * followed by "\ No newline", then we also remove the2591 * last one (which is the newline, of course).2592 */2593 plen = len -1;2594if(len < size && patch[len] =='\\')2595 plen--;2596 first = *patch;2597if(apply_in_reverse) {2598if(first =='-')2599 first ='+';2600else if(first =='+')2601 first ='-';2602}26032604switch(first) {2605case'\n':2606/* Newer GNU diff, empty context line */2607if(plen <0)2608/* ... followed by '\No newline'; nothing */2609break;2610*old++ ='\n';2611strbuf_addch(&newlines,'\n');2612add_line_info(&preimage,"\n",1, LINE_COMMON);2613add_line_info(&postimage,"\n",1, LINE_COMMON);2614 is_blank_context =1;2615break;2616case' ':2617if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2618ws_blank_line(patch +1, plen, ws_rule))2619 is_blank_context =1;2620case'-':2621memcpy(old, patch +1, plen);2622add_line_info(&preimage, old, plen,2623(first ==' '? LINE_COMMON :0));2624 old += plen;2625if(first =='-')2626break;2627/* Fall-through for ' ' */2628case'+':2629/* --no-add does not add new lines */2630if(first =='+'&& no_add)2631break;26322633 start = newlines.len;2634if(first !='+'||2635!whitespace_error ||2636 ws_error_action != correct_ws_error) {2637strbuf_add(&newlines, patch +1, plen);2638}2639else{2640ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2641}2642add_line_info(&postimage, newlines.buf + start, newlines.len - start,2643(first =='+'?0: LINE_COMMON));2644if(first =='+'&&2645(ws_rule & WS_BLANK_AT_EOF) &&2646ws_blank_line(patch +1, plen, ws_rule))2647 added_blank_line =1;2648break;2649case'@':case'\\':2650/* Ignore it, we already handled it */2651break;2652default:2653if(apply_verbosely)2654error(_("invalid start of line: '%c'"), first);2655return-1;2656}2657if(added_blank_line) {2658if(!new_blank_lines_at_end)2659 found_new_blank_lines_at_end = hunk_linenr;2660 new_blank_lines_at_end++;2661}2662else if(is_blank_context)2663;2664else2665 new_blank_lines_at_end =0;2666 patch += len;2667 size -= len;2668 hunk_linenr++;2669}2670if(inaccurate_eof &&2671 old > oldlines && old[-1] =='\n'&&2672 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2673 old--;2674strbuf_setlen(&newlines, newlines.len -1);2675}26762677 leading = frag->leading;2678 trailing = frag->trailing;26792680/*2681 * A hunk to change lines at the beginning would begin with2682 * @@ -1,L +N,M @@2683 * but we need to be careful. -U0 that inserts before the second2684 * line also has this pattern.2685 *2686 * And a hunk to add to an empty file would begin with2687 * @@ -0,0 +N,M @@2688 *2689 * In other words, a hunk that is (frag->oldpos <= 1) with or2690 * without leading context must match at the beginning.2691 */2692 match_beginning = (!frag->oldpos ||2693(frag->oldpos ==1&& !unidiff_zero));26942695/*2696 * A hunk without trailing lines must match at the end.2697 * However, we simply cannot tell if a hunk must match end2698 * from the lack of trailing lines if the patch was generated2699 * with unidiff without any context.2700 */2701 match_end = !unidiff_zero && !trailing;27022703 pos = frag->newpos ? (frag->newpos -1) :0;2704 preimage.buf = oldlines;2705 preimage.len = old - oldlines;2706 postimage.buf = newlines.buf;2707 postimage.len = newlines.len;2708 preimage.line = preimage.line_allocated;2709 postimage.line = postimage.line_allocated;27102711for(;;) {27122713 applied_pos =find_pos(img, &preimage, &postimage, pos,2714 ws_rule, match_beginning, match_end);27152716if(applied_pos >=0)2717break;27182719/* Am I at my context limits? */2720if((leading <= p_context) && (trailing <= p_context))2721break;2722if(match_beginning || match_end) {2723 match_beginning = match_end =0;2724continue;2725}27262727/*2728 * Reduce the number of context lines; reduce both2729 * leading and trailing if they are equal otherwise2730 * just reduce the larger context.2731 */2732if(leading >= trailing) {2733remove_first_line(&preimage);2734remove_first_line(&postimage);2735 pos--;2736 leading--;2737}2738if(trailing > leading) {2739remove_last_line(&preimage);2740remove_last_line(&postimage);2741 trailing--;2742}2743}27442745if(applied_pos >=0) {2746if(new_blank_lines_at_end &&2747 preimage.nr + applied_pos >= img->nr &&2748(ws_rule & WS_BLANK_AT_EOF) &&2749 ws_error_action != nowarn_ws_error) {2750record_ws_error(WS_BLANK_AT_EOF,"+",1,2751 found_new_blank_lines_at_end);2752if(ws_error_action == correct_ws_error) {2753while(new_blank_lines_at_end--)2754remove_last_line(&postimage);2755}2756/*2757 * We would want to prevent write_out_results()2758 * from taking place in apply_patch() that follows2759 * the callchain led us here, which is:2760 * apply_patch->check_patch_list->check_patch->2761 * apply_data->apply_fragments->apply_one_fragment2762 */2763if(ws_error_action == die_on_ws_error)2764 apply =0;2765}27662767if(apply_verbosely && applied_pos != pos) {2768int offset = applied_pos - pos;2769if(apply_in_reverse)2770 offset =0- offset;2771fprintf_ln(stderr,2772Q_("Hunk #%dsucceeded at%d(offset%dline).",2773"Hunk #%dsucceeded at%d(offset%dlines).",2774 offset),2775 nth_fragment, applied_pos +1, offset);2776}27772778/*2779 * Warn if it was necessary to reduce the number2780 * of context lines.2781 */2782if((leading != frag->leading) ||2783(trailing != frag->trailing))2784fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2785" to apply fragment at%d"),2786 leading, trailing, applied_pos+1);2787update_image(img, applied_pos, &preimage, &postimage);2788}else{2789if(apply_verbosely)2790error(_("while searching for:\n%.*s"),2791(int)(old - oldlines), oldlines);2792}27932794free(oldlines);2795strbuf_release(&newlines);2796free(preimage.line_allocated);2797free(postimage.line_allocated);27982799return(applied_pos <0);2800}28012802static intapply_binary_fragment(struct image *img,struct patch *patch)2803{2804struct fragment *fragment = patch->fragments;2805unsigned long len;2806void*dst;28072808if(!fragment)2809returnerror(_("missing binary patch data for '%s'"),2810 patch->new_name ?2811 patch->new_name :2812 patch->old_name);28132814/* Binary patch is irreversible without the optional second hunk */2815if(apply_in_reverse) {2816if(!fragment->next)2817returnerror("cannot reverse-apply a binary patch "2818"without the reverse hunk to '%s'",2819 patch->new_name2820? patch->new_name : patch->old_name);2821 fragment = fragment->next;2822}2823switch(fragment->binary_patch_method) {2824case BINARY_DELTA_DEFLATED:2825 dst =patch_delta(img->buf, img->len, fragment->patch,2826 fragment->size, &len);2827if(!dst)2828return-1;2829clear_image(img);2830 img->buf = dst;2831 img->len = len;2832return0;2833case BINARY_LITERAL_DEFLATED:2834clear_image(img);2835 img->len = fragment->size;2836 img->buf =xmalloc(img->len+1);2837memcpy(img->buf, fragment->patch, img->len);2838 img->buf[img->len] ='\0';2839return0;2840}2841return-1;2842}28432844/*2845 * Replace "img" with the result of applying the binary patch.2846 * The binary patch data itself in patch->fragment is still kept2847 * but the preimage prepared by the caller in "img" is freed here2848 * or in the helper function apply_binary_fragment() this calls.2849 */2850static intapply_binary(struct image *img,struct patch *patch)2851{2852const char*name = patch->old_name ? patch->old_name : patch->new_name;2853unsigned char sha1[20];28542855/*2856 * For safety, we require patch index line to contain2857 * full 40-byte textual SHA1 for old and new, at least for now.2858 */2859if(strlen(patch->old_sha1_prefix) !=40||2860strlen(patch->new_sha1_prefix) !=40||2861get_sha1_hex(patch->old_sha1_prefix, sha1) ||2862get_sha1_hex(patch->new_sha1_prefix, sha1))2863returnerror("cannot apply binary patch to '%s' "2864"without full index line", name);28652866if(patch->old_name) {2867/*2868 * See if the old one matches what the patch2869 * applies to.2870 */2871hash_sha1_file(img->buf, img->len, blob_type, sha1);2872if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2873returnerror("the patch applies to '%s' (%s), "2874"which does not match the "2875"current contents.",2876 name,sha1_to_hex(sha1));2877}2878else{2879/* Otherwise, the old one must be empty. */2880if(img->len)2881returnerror("the patch applies to an empty "2882"'%s' but it is not empty", name);2883}28842885get_sha1_hex(patch->new_sha1_prefix, sha1);2886if(is_null_sha1(sha1)) {2887clear_image(img);2888return0;/* deletion patch */2889}28902891if(has_sha1_file(sha1)) {2892/* We already have the postimage */2893enum object_type type;2894unsigned long size;2895char*result;28962897 result =read_sha1_file(sha1, &type, &size);2898if(!result)2899returnerror("the necessary postimage%sfor "2900"'%s' cannot be read",2901 patch->new_sha1_prefix, name);2902clear_image(img);2903 img->buf = result;2904 img->len = size;2905}else{2906/*2907 * We have verified buf matches the preimage;2908 * apply the patch data to it, which is stored2909 * in the patch->fragments->{patch,size}.2910 */2911if(apply_binary_fragment(img, patch))2912returnerror(_("binary patch does not apply to '%s'"),2913 name);29142915/* verify that the result matches */2916hash_sha1_file(img->buf, img->len, blob_type, sha1);2917if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2918returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),2919 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2920}29212922return0;2923}29242925static intapply_fragments(struct image *img,struct patch *patch)2926{2927struct fragment *frag = patch->fragments;2928const char*name = patch->old_name ? patch->old_name : patch->new_name;2929unsigned ws_rule = patch->ws_rule;2930unsigned inaccurate_eof = patch->inaccurate_eof;2931int nth =0;29322933if(patch->is_binary)2934returnapply_binary(img, patch);29352936while(frag) {2937 nth++;2938if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {2939error(_("patch failed:%s:%ld"), name, frag->oldpos);2940if(!apply_with_reject)2941return-1;2942 frag->rejected =1;2943}2944 frag = frag->next;2945}2946return0;2947}29482949static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)2950{2951if(S_ISGITLINK(mode)) {2952strbuf_grow(buf,100);2953strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));2954}else{2955enum object_type type;2956unsigned long sz;2957char*result;29582959 result =read_sha1_file(sha1, &type, &sz);2960if(!result)2961return-1;2962/* XXX read_sha1_file NUL-terminates */2963strbuf_attach(buf, result, sz, sz +1);2964}2965return0;2966}29672968static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2969{2970if(!ce)2971return0;2972returnread_blob_object(buf, ce->sha1, ce->ce_mode);2973}29742975static struct patch *in_fn_table(const char*name)2976{2977struct string_list_item *item;29782979if(name == NULL)2980return NULL;29812982 item =string_list_lookup(&fn_table, name);2983if(item != NULL)2984return(struct patch *)item->util;29852986return NULL;2987}29882989/*2990 * item->util in the filename table records the status of the path.2991 * Usually it points at a patch (whose result records the contents2992 * of it after applying it), but it could be PATH_WAS_DELETED for a2993 * path that a previously applied patch has already removed, or2994 * PATH_TO_BE_DELETED for a path that a later patch would remove.2995 *2996 * The latter is needed to deal with a case where two paths A and B2997 * are swapped by first renaming A to B and then renaming B to A;2998 * moving A to B should not be prevented due to presense of B as we2999 * will remove it in a later patch.3000 */3001#define PATH_TO_BE_DELETED ((struct patch *) -2)3002#define PATH_WAS_DELETED ((struct patch *) -1)30033004static intto_be_deleted(struct patch *patch)3005{3006return patch == PATH_TO_BE_DELETED;3007}30083009static intwas_deleted(struct patch *patch)3010{3011return patch == PATH_WAS_DELETED;3012}30133014static voidadd_to_fn_table(struct patch *patch)3015{3016struct string_list_item *item;30173018/*3019 * Always add new_name unless patch is a deletion3020 * This should cover the cases for normal diffs,3021 * file creations and copies3022 */3023if(patch->new_name != NULL) {3024 item =string_list_insert(&fn_table, patch->new_name);3025 item->util = patch;3026}30273028/*3029 * store a failure on rename/deletion cases because3030 * later chunks shouldn't patch old names3031 */3032if((patch->new_name == NULL) || (patch->is_rename)) {3033 item =string_list_insert(&fn_table, patch->old_name);3034 item->util = PATH_WAS_DELETED;3035}3036}30373038static voidprepare_fn_table(struct patch *patch)3039{3040/*3041 * store information about incoming file deletion3042 */3043while(patch) {3044if((patch->new_name == NULL) || (patch->is_rename)) {3045struct string_list_item *item;3046 item =string_list_insert(&fn_table, patch->old_name);3047 item->util = PATH_TO_BE_DELETED;3048}3049 patch = patch->next;3050}3051}30523053static intcheckout_target(struct cache_entry *ce,struct stat *st)3054{3055struct checkout costate;30563057memset(&costate,0,sizeof(costate));3058 costate.base_dir ="";3059 costate.refresh_cache =1;3060if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3061returnerror(_("cannot checkout%s"), ce->name);3062return0;3063}30643065static struct patch *previous_patch(struct patch *patch,int*gone)3066{3067struct patch *previous;30683069*gone =0;3070if(patch->is_copy || patch->is_rename)3071return NULL;/* "git" patches do not depend on the order */30723073 previous =in_fn_table(patch->old_name);3074if(!previous)3075return NULL;30763077if(to_be_deleted(previous))3078return NULL;/* the deletion hasn't happened yet */30793080if(was_deleted(previous))3081*gone =1;30823083return previous;3084}30853086static intverify_index_match(struct cache_entry *ce,struct stat *st)3087{3088if(S_ISGITLINK(ce->ce_mode)) {3089if(!S_ISDIR(st->st_mode))3090return-1;3091return0;3092}3093returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3094}30953096#define SUBMODULE_PATCH_WITHOUT_INDEX 130973098static intload_patch_target(struct strbuf *buf,3099struct cache_entry *ce,3100struct stat *st,3101const char*name,3102unsigned expected_mode)3103{3104if(cached) {3105if(read_file_or_gitlink(ce, buf))3106returnerror(_("read of%sfailed"), name);3107}else if(name) {3108if(S_ISGITLINK(expected_mode)) {3109if(ce)3110returnread_file_or_gitlink(ce, buf);3111else3112return SUBMODULE_PATCH_WITHOUT_INDEX;3113}else{3114if(read_old_data(st, name, buf))3115returnerror(_("read of%sfailed"), name);3116}3117}3118return0;3119}31203121/*3122 * We are about to apply "patch"; populate the "image" with the3123 * current version we have, from the working tree or from the index,3124 * depending on the situation e.g. --cached/--index. If we are3125 * applying a non-git patch that incrementally updates the tree,3126 * we read from the result of a previous diff.3127 */3128static intload_preimage(struct image *image,3129struct patch *patch,struct stat *st,struct cache_entry *ce)3130{3131struct strbuf buf = STRBUF_INIT;3132size_t len;3133char*img;3134struct patch *previous;3135int status;31363137 previous =previous_patch(patch, &status);3138if(status)3139returnerror(_("path%shas been renamed/deleted"),3140 patch->old_name);3141if(previous) {3142/* We have a patched copy in memory; use that. */3143strbuf_add(&buf, previous->result, previous->resultsize);3144}else{3145 status =load_patch_target(&buf, ce, st,3146 patch->old_name, patch->old_mode);3147if(status <0)3148return status;3149else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3150/*3151 * There is no way to apply subproject3152 * patch without looking at the index.3153 * NEEDSWORK: shouldn't this be flagged3154 * as an error???3155 */3156free_fragment_list(patch->fragments);3157 patch->fragments = NULL;3158}else if(status) {3159returnerror(_("read of%sfailed"), patch->old_name);3160}3161}31623163 img =strbuf_detach(&buf, &len);3164prepare_image(image, img, len, !patch->is_binary);3165return0;3166}31673168static intthree_way_merge(struct image *image,3169char*path,3170const unsigned char*base,3171const unsigned char*ours,3172const unsigned char*theirs)3173{3174 mmfile_t base_file, our_file, their_file;3175 mmbuffer_t result = { NULL };3176int status;31773178read_mmblob(&base_file, base);3179read_mmblob(&our_file, ours);3180read_mmblob(&their_file, theirs);3181 status =ll_merge(&result, path,3182&base_file,"base",3183&our_file,"ours",3184&their_file,"theirs", NULL);3185free(base_file.ptr);3186free(our_file.ptr);3187free(their_file.ptr);3188if(status <0|| !result.ptr) {3189free(result.ptr);3190return-1;3191}3192clear_image(image);3193 image->buf = result.ptr;3194 image->len = result.size;31953196return status;3197}31983199/*3200 * When directly falling back to add/add three-way merge, we read from3201 * the current contents of the new_name. In no cases other than that3202 * this function will be called.3203 */3204static intload_current(struct image *image,struct patch *patch)3205{3206struct strbuf buf = STRBUF_INIT;3207int status, pos;3208size_t len;3209char*img;3210struct stat st;3211struct cache_entry *ce;3212char*name = patch->new_name;3213unsigned mode = patch->new_mode;32143215if(!patch->is_new)3216die("BUG: patch to%sis not a creation", patch->old_name);32173218 pos =cache_name_pos(name,strlen(name));3219if(pos <0)3220returnerror(_("%s: does not exist in index"), name);3221 ce = active_cache[pos];3222if(lstat(name, &st)) {3223if(errno != ENOENT)3224returnerror(_("%s:%s"), name,strerror(errno));3225if(checkout_target(ce, &st))3226return-1;3227}3228if(verify_index_match(ce, &st))3229returnerror(_("%s: does not match index"), name);32303231 status =load_patch_target(&buf, ce, &st, name, mode);3232if(status <0)3233return status;3234else if(status)3235return-1;3236 img =strbuf_detach(&buf, &len);3237prepare_image(image, img, len, !patch->is_binary);3238return0;3239}32403241static inttry_threeway(struct image *image,struct patch *patch,3242struct stat *st,struct cache_entry *ce)3243{3244unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3245struct strbuf buf = STRBUF_INIT;3246size_t len;3247int status;3248char*img;3249struct image tmp_image;32503251/* No point falling back to 3-way merge in these cases */3252if(patch->is_delete ||3253S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3254return-1;32553256/* Preimage the patch was prepared for */3257if(patch->is_new)3258write_sha1_file("",0, blob_type, pre_sha1);3259else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3260read_blob_object(&buf, pre_sha1, patch->old_mode))3261returnerror("repository lacks the necessary blob to fall back on 3-way merge.");32623263fprintf(stderr,"Falling back to three-way merge...\n");32643265 img =strbuf_detach(&buf, &len);3266prepare_image(&tmp_image, img, len,1);3267/* Apply the patch to get the post image */3268if(apply_fragments(&tmp_image, patch) <0) {3269clear_image(&tmp_image);3270return-1;3271}3272/* post_sha1[] is theirs */3273write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3274clear_image(&tmp_image);32753276/* our_sha1[] is ours */3277if(patch->is_new) {3278if(load_current(&tmp_image, patch))3279returnerror("cannot read the current contents of '%s'",3280 patch->new_name);3281}else{3282if(load_preimage(&tmp_image, patch, st, ce))3283returnerror("cannot read the current contents of '%s'",3284 patch->old_name);3285}3286write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3287clear_image(&tmp_image);32883289/* in-core three-way merge between post and our using pre as base */3290 status =three_way_merge(image, patch->new_name,3291 pre_sha1, our_sha1, post_sha1);3292if(status <0) {3293fprintf(stderr,"Failed to fall back on three-way merge...\n");3294return status;3295}32963297if(status) {3298 patch->conflicted_threeway =1;3299if(patch->is_new)3300hashclr(patch->threeway_stage[0]);3301else3302hashcpy(patch->threeway_stage[0], pre_sha1);3303hashcpy(patch->threeway_stage[1], our_sha1);3304hashcpy(patch->threeway_stage[2], post_sha1);3305fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3306}else{3307fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3308}3309return0;3310}33113312static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)3313{3314struct image image;33153316if(load_preimage(&image, patch, st, ce) <0)3317return-1;33183319if(patch->direct_to_threeway ||3320apply_fragments(&image, patch) <0) {3321/* Note: with --reject, apply_fragments() returns 0 */3322if(!threeway ||try_threeway(&image, patch, st, ce) <0)3323return-1;3324}3325 patch->result = image.buf;3326 patch->resultsize = image.len;3327add_to_fn_table(patch);3328free(image.line_allocated);33293330if(0< patch->is_delete && patch->resultsize)3331returnerror(_("removal patch leaves file contents"));33323333return0;3334}33353336/*3337 * If "patch" that we are looking at modifies or deletes what we have,3338 * we would want it not to lose any local modification we have, either3339 * in the working tree or in the index.3340 *3341 * This also decides if a non-git patch is a creation patch or a3342 * modification to an existing empty file. We do not check the state3343 * of the current tree for a creation patch in this function; the caller3344 * check_patch() separately makes sure (and errors out otherwise) that3345 * the path the patch creates does not exist in the current tree.3346 */3347static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)3348{3349const char*old_name = patch->old_name;3350struct patch *previous = NULL;3351int stat_ret =0, status;3352unsigned st_mode =0;33533354if(!old_name)3355return0;33563357assert(patch->is_new <=0);3358 previous =previous_patch(patch, &status);33593360if(status)3361returnerror(_("path%shas been renamed/deleted"), old_name);3362if(previous) {3363 st_mode = previous->new_mode;3364}else if(!cached) {3365 stat_ret =lstat(old_name, st);3366if(stat_ret && errno != ENOENT)3367returnerror(_("%s:%s"), old_name,strerror(errno));3368}33693370if(check_index && !previous) {3371int pos =cache_name_pos(old_name,strlen(old_name));3372if(pos <0) {3373if(patch->is_new <0)3374goto is_new;3375returnerror(_("%s: does not exist in index"), old_name);3376}3377*ce = active_cache[pos];3378if(stat_ret <0) {3379if(checkout_target(*ce, st))3380return-1;3381}3382if(!cached &&verify_index_match(*ce, st))3383returnerror(_("%s: does not match index"), old_name);3384if(cached)3385 st_mode = (*ce)->ce_mode;3386}else if(stat_ret <0) {3387if(patch->is_new <0)3388goto is_new;3389returnerror(_("%s:%s"), old_name,strerror(errno));3390}33913392if(!cached && !previous)3393 st_mode =ce_mode_from_stat(*ce, st->st_mode);33943395if(patch->is_new <0)3396 patch->is_new =0;3397if(!patch->old_mode)3398 patch->old_mode = st_mode;3399if((st_mode ^ patch->old_mode) & S_IFMT)3400returnerror(_("%s: wrong type"), old_name);3401if(st_mode != patch->old_mode)3402warning(_("%shas type%o, expected%o"),3403 old_name, st_mode, patch->old_mode);3404if(!patch->new_mode && !patch->is_delete)3405 patch->new_mode = st_mode;3406return0;34073408 is_new:3409 patch->is_new =1;3410 patch->is_delete =0;3411free(patch->old_name);3412 patch->old_name = NULL;3413return0;3414}341534163417#define EXISTS_IN_INDEX 13418#define EXISTS_IN_WORKTREE 234193420static intcheck_to_create(const char*new_name,int ok_if_exists)3421{3422struct stat nst;34233424if(check_index &&3425cache_name_pos(new_name,strlen(new_name)) >=0&&3426!ok_if_exists)3427return EXISTS_IN_INDEX;3428if(cached)3429return0;34303431if(!lstat(new_name, &nst)) {3432if(S_ISDIR(nst.st_mode) || ok_if_exists)3433return0;3434/*3435 * A leading component of new_name might be a symlink3436 * that is going to be removed with this patch, but3437 * still pointing at somewhere that has the path.3438 * In such a case, path "new_name" does not exist as3439 * far as git is concerned.3440 */3441if(has_symlink_leading_path(new_name,strlen(new_name)))3442return0;34433444return EXISTS_IN_WORKTREE;3445}else if((errno != ENOENT) && (errno != ENOTDIR)) {3446returnerror("%s:%s", new_name,strerror(errno));3447}3448return0;3449}34503451/*3452 * Check and apply the patch in-core; leave the result in patch->result3453 * for the caller to write it out to the final destination.3454 */3455static intcheck_patch(struct patch *patch)3456{3457struct stat st;3458const char*old_name = patch->old_name;3459const char*new_name = patch->new_name;3460const char*name = old_name ? old_name : new_name;3461struct cache_entry *ce = NULL;3462struct patch *tpatch;3463int ok_if_exists;3464int status;34653466 patch->rejected =1;/* we will drop this after we succeed */34673468 status =check_preimage(patch, &ce, &st);3469if(status)3470return status;3471 old_name = patch->old_name;34723473/*3474 * A type-change diff is always split into a patch to delete3475 * old, immediately followed by a patch to create new (see3476 * diff.c::run_diff()); in such a case it is Ok that the entry3477 * to be deleted by the previous patch is still in the working3478 * tree and in the index.3479 *3480 * A patch to swap-rename between A and B would first rename A3481 * to B and then rename B to A. While applying the first one,3482 * the presense of B should not stop A from getting renamed to3483 * B; ask to_be_deleted() about the later rename. Removal of3484 * B and rename from A to B is handled the same way by asking3485 * was_deleted().3486 */3487if((tpatch =in_fn_table(new_name)) &&3488(was_deleted(tpatch) ||to_be_deleted(tpatch)))3489 ok_if_exists =1;3490else3491 ok_if_exists =0;34923493if(new_name &&3494((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {3495int err =check_to_create(new_name, ok_if_exists);34963497if(err && threeway) {3498 patch->direct_to_threeway =1;3499}else switch(err) {3500case0:3501break;/* happy */3502case EXISTS_IN_INDEX:3503returnerror(_("%s: already exists in index"), new_name);3504break;3505case EXISTS_IN_WORKTREE:3506returnerror(_("%s: already exists in working directory"),3507 new_name);3508default:3509return err;3510}35113512if(!patch->new_mode) {3513if(0< patch->is_new)3514 patch->new_mode = S_IFREG |0644;3515else3516 patch->new_mode = patch->old_mode;3517}3518}35193520if(new_name && old_name) {3521int same = !strcmp(old_name, new_name);3522if(!patch->new_mode)3523 patch->new_mode = patch->old_mode;3524if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3525if(same)3526returnerror(_("new mode (%o) of%sdoes not "3527"match old mode (%o)"),3528 patch->new_mode, new_name,3529 patch->old_mode);3530else3531returnerror(_("new mode (%o) of%sdoes not "3532"match old mode (%o) of%s"),3533 patch->new_mode, new_name,3534 patch->old_mode, old_name);3535}3536}35373538if(apply_data(patch, &st, ce) <0)3539returnerror(_("%s: patch does not apply"), name);3540 patch->rejected =0;3541return0;3542}35433544static intcheck_patch_list(struct patch *patch)3545{3546int err =0;35473548prepare_fn_table(patch);3549while(patch) {3550if(apply_verbosely)3551say_patch_name(stderr,3552_("Checking patch%s..."), patch);3553 err |=check_patch(patch);3554 patch = patch->next;3555}3556return err;3557}35583559/* This function tries to read the sha1 from the current index */3560static intget_current_sha1(const char*path,unsigned char*sha1)3561{3562int pos;35633564if(read_cache() <0)3565return-1;3566 pos =cache_name_pos(path,strlen(path));3567if(pos <0)3568return-1;3569hashcpy(sha1, active_cache[pos]->sha1);3570return0;3571}35723573/* Build an index that contains the just the files needed for a 3way merge */3574static voidbuild_fake_ancestor(struct patch *list,const char*filename)3575{3576struct patch *patch;3577struct index_state result = { NULL };3578int fd;35793580/* Once we start supporting the reverse patch, it may be3581 * worth showing the new sha1 prefix, but until then...3582 */3583for(patch = list; patch; patch = patch->next) {3584const unsigned char*sha1_ptr;3585unsigned char sha1[20];3586struct cache_entry *ce;3587const char*name;35883589 name = patch->old_name ? patch->old_name : patch->new_name;3590if(0< patch->is_new)3591continue;3592else if(get_sha1_blob(patch->old_sha1_prefix, sha1))3593/* git diff has no index line for mode/type changes */3594if(!patch->lines_added && !patch->lines_deleted) {3595if(get_current_sha1(patch->old_name, sha1))3596die("mode change for%s, which is not "3597"in current HEAD", name);3598 sha1_ptr = sha1;3599}else3600die("sha1 information is lacking or useless "3601"(%s).", name);3602else3603 sha1_ptr = sha1;36043605 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);3606if(!ce)3607die(_("make_cache_entry failed for path '%s'"), name);3608if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3609die("Could not add%sto temporary index", name);3610}36113612 fd =open(filename, O_WRONLY | O_CREAT,0666);3613if(fd <0||write_index(&result, fd) ||close(fd))3614die("Could not write temporary index to%s", filename);36153616discard_index(&result);3617}36183619static voidstat_patch_list(struct patch *patch)3620{3621int files, adds, dels;36223623for(files = adds = dels =0; patch ; patch = patch->next) {3624 files++;3625 adds += patch->lines_added;3626 dels += patch->lines_deleted;3627show_stats(patch);3628}36293630print_stat_summary(stdout, files, adds, dels);3631}36323633static voidnumstat_patch_list(struct patch *patch)3634{3635for( ; patch; patch = patch->next) {3636const char*name;3637 name = patch->new_name ? patch->new_name : patch->old_name;3638if(patch->is_binary)3639printf("-\t-\t");3640else3641printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3642write_name_quoted(name, stdout, line_termination);3643}3644}36453646static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3647{3648if(mode)3649printf("%smode%06o%s\n", newdelete, mode, name);3650else3651printf("%s %s\n", newdelete, name);3652}36533654static voidshow_mode_change(struct patch *p,int show_name)3655{3656if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3657if(show_name)3658printf(" mode change%06o =>%06o%s\n",3659 p->old_mode, p->new_mode, p->new_name);3660else3661printf(" mode change%06o =>%06o\n",3662 p->old_mode, p->new_mode);3663}3664}36653666static voidshow_rename_copy(struct patch *p)3667{3668const char*renamecopy = p->is_rename ?"rename":"copy";3669const char*old, *new;36703671/* Find common prefix */3672 old = p->old_name;3673new= p->new_name;3674while(1) {3675const char*slash_old, *slash_new;3676 slash_old =strchr(old,'/');3677 slash_new =strchr(new,'/');3678if(!slash_old ||3679!slash_new ||3680 slash_old - old != slash_new -new||3681memcmp(old,new, slash_new -new))3682break;3683 old = slash_old +1;3684new= slash_new +1;3685}3686/* p->old_name thru old is the common prefix, and old and new3687 * through the end of names are renames3688 */3689if(old != p->old_name)3690printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,3691(int)(old - p->old_name), p->old_name,3692 old,new, p->score);3693else3694printf("%s %s=>%s(%d%%)\n", renamecopy,3695 p->old_name, p->new_name, p->score);3696show_mode_change(p,0);3697}36983699static voidsummary_patch_list(struct patch *patch)3700{3701struct patch *p;37023703for(p = patch; p; p = p->next) {3704if(p->is_new)3705show_file_mode_name("create", p->new_mode, p->new_name);3706else if(p->is_delete)3707show_file_mode_name("delete", p->old_mode, p->old_name);3708else{3709if(p->is_rename || p->is_copy)3710show_rename_copy(p);3711else{3712if(p->score) {3713printf(" rewrite%s(%d%%)\n",3714 p->new_name, p->score);3715show_mode_change(p,0);3716}3717else3718show_mode_change(p,1);3719}3720}3721}3722}37233724static voidpatch_stats(struct patch *patch)3725{3726int lines = patch->lines_added + patch->lines_deleted;37273728if(lines > max_change)3729 max_change = lines;3730if(patch->old_name) {3731int len =quote_c_style(patch->old_name, NULL, NULL,0);3732if(!len)3733 len =strlen(patch->old_name);3734if(len > max_len)3735 max_len = len;3736}3737if(patch->new_name) {3738int len =quote_c_style(patch->new_name, NULL, NULL,0);3739if(!len)3740 len =strlen(patch->new_name);3741if(len > max_len)3742 max_len = len;3743}3744}37453746static voidremove_file(struct patch *patch,int rmdir_empty)3747{3748if(update_index) {3749if(remove_file_from_cache(patch->old_name) <0)3750die(_("unable to remove%sfrom index"), patch->old_name);3751}3752if(!cached) {3753if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {3754remove_path(patch->old_name);3755}3756}3757}37583759static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)3760{3761struct stat st;3762struct cache_entry *ce;3763int namelen =strlen(path);3764unsigned ce_size =cache_entry_size(namelen);37653766if(!update_index)3767return;37683769 ce =xcalloc(1, ce_size);3770memcpy(ce->name, path, namelen);3771 ce->ce_mode =create_ce_mode(mode);3772 ce->ce_flags =create_ce_flags(0);3773 ce->ce_namelen = namelen;3774if(S_ISGITLINK(mode)) {3775const char*s = buf;37763777if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))3778die(_("corrupt patch for subproject%s"), path);3779}else{3780if(!cached) {3781if(lstat(path, &st) <0)3782die_errno(_("unable to stat newly created file '%s'"),3783 path);3784fill_stat_cache_info(ce, &st);3785}3786if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)3787die(_("unable to create backing store for newly created file%s"), path);3788}3789if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3790die(_("unable to add cache entry for%s"), path);3791}37923793static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)3794{3795int fd;3796struct strbuf nbuf = STRBUF_INIT;37973798if(S_ISGITLINK(mode)) {3799struct stat st;3800if(!lstat(path, &st) &&S_ISDIR(st.st_mode))3801return0;3802returnmkdir(path,0777);3803}38043805if(has_symlinks &&S_ISLNK(mode))3806/* Although buf:size is counted string, it also is NUL3807 * terminated.3808 */3809returnsymlink(buf, path);38103811 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);3812if(fd <0)3813return-1;38143815if(convert_to_working_tree(path, buf, size, &nbuf)) {3816 size = nbuf.len;3817 buf = nbuf.buf;3818}3819write_or_die(fd, buf, size);3820strbuf_release(&nbuf);38213822if(close(fd) <0)3823die_errno(_("closing file '%s'"), path);3824return0;3825}38263827/*3828 * We optimistically assume that the directories exist,3829 * which is true 99% of the time anyway. If they don't,3830 * we create them and try again.3831 */3832static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)3833{3834if(cached)3835return;3836if(!try_create_file(path, mode, buf, size))3837return;38383839if(errno == ENOENT) {3840if(safe_create_leading_directories(path))3841return;3842if(!try_create_file(path, mode, buf, size))3843return;3844}38453846if(errno == EEXIST || errno == EACCES) {3847/* We may be trying to create a file where a directory3848 * used to be.3849 */3850struct stat st;3851if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))3852 errno = EEXIST;3853}38543855if(errno == EEXIST) {3856unsigned int nr =getpid();38573858for(;;) {3859char newpath[PATH_MAX];3860mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);3861if(!try_create_file(newpath, mode, buf, size)) {3862if(!rename(newpath, path))3863return;3864unlink_or_warn(newpath);3865break;3866}3867if(errno != EEXIST)3868break;3869++nr;3870}3871}3872die_errno(_("unable to write file '%s' mode%o"), path, mode);3873}38743875static voidadd_conflicted_stages_file(struct patch *patch)3876{3877int stage, namelen;3878unsigned ce_size, mode;3879struct cache_entry *ce;38803881if(!update_index)3882return;3883 namelen =strlen(patch->new_name);3884 ce_size =cache_entry_size(namelen);3885 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);38863887remove_file_from_cache(patch->new_name);3888for(stage =1; stage <4; stage++) {3889if(is_null_sha1(patch->threeway_stage[stage -1]))3890continue;3891 ce =xcalloc(1, ce_size);3892memcpy(ce->name, patch->new_name, namelen);3893 ce->ce_mode =create_ce_mode(mode);3894 ce->ce_flags =create_ce_flags(stage);3895 ce->ce_namelen = namelen;3896hashcpy(ce->sha1, patch->threeway_stage[stage -1]);3897if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3898die(_("unable to add cache entry for%s"), patch->new_name);3899}3900}39013902static voidcreate_file(struct patch *patch)3903{3904char*path = patch->new_name;3905unsigned mode = patch->new_mode;3906unsigned long size = patch->resultsize;3907char*buf = patch->result;39083909if(!mode)3910 mode = S_IFREG |0644;3911create_one_file(path, mode, buf, size);39123913if(patch->conflicted_threeway)3914add_conflicted_stages_file(patch);3915else3916add_index_file(path, mode, buf, size);3917}39183919/* phase zero is to remove, phase one is to create */3920static voidwrite_out_one_result(struct patch *patch,int phase)3921{3922if(patch->is_delete >0) {3923if(phase ==0)3924remove_file(patch,1);3925return;3926}3927if(patch->is_new >0|| patch->is_copy) {3928if(phase ==1)3929create_file(patch);3930return;3931}3932/*3933 * Rename or modification boils down to the same3934 * thing: remove the old, write the new3935 */3936if(phase ==0)3937remove_file(patch, patch->is_rename);3938if(phase ==1)3939create_file(patch);3940}39413942static intwrite_out_one_reject(struct patch *patch)3943{3944FILE*rej;3945char namebuf[PATH_MAX];3946struct fragment *frag;3947int cnt =0;3948struct strbuf sb = STRBUF_INIT;39493950for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {3951if(!frag->rejected)3952continue;3953 cnt++;3954}39553956if(!cnt) {3957if(apply_verbosely)3958say_patch_name(stderr,3959_("Applied patch%scleanly."), patch);3960return0;3961}39623963/* This should not happen, because a removal patch that leaves3964 * contents are marked "rejected" at the patch level.3965 */3966if(!patch->new_name)3967die(_("internal error"));39683969/* Say this even without --verbose */3970strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",3971"Applying patch %%swith%drejects...",3972 cnt),3973 cnt);3974say_patch_name(stderr, sb.buf, patch);3975strbuf_release(&sb);39763977 cnt =strlen(patch->new_name);3978if(ARRAY_SIZE(namebuf) <= cnt +5) {3979 cnt =ARRAY_SIZE(namebuf) -5;3980warning(_("truncating .rej filename to %.*s.rej"),3981 cnt -1, patch->new_name);3982}3983memcpy(namebuf, patch->new_name, cnt);3984memcpy(namebuf + cnt,".rej",5);39853986 rej =fopen(namebuf,"w");3987if(!rej)3988returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));39893990/* Normal git tools never deal with .rej, so do not pretend3991 * this is a git patch by saying --git nor give extended3992 * headers. While at it, maybe please "kompare" that wants3993 * the trailing TAB and some garbage at the end of line ;-).3994 */3995fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",3996 patch->new_name, patch->new_name);3997for(cnt =1, frag = patch->fragments;3998 frag;3999 cnt++, frag = frag->next) {4000if(!frag->rejected) {4001fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4002continue;4003}4004fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4005fprintf(rej,"%.*s", frag->size, frag->patch);4006if(frag->patch[frag->size-1] !='\n')4007fputc('\n', rej);4008}4009fclose(rej);4010return-1;4011}40124013static intwrite_out_results(struct patch *list)4014{4015int phase;4016int errs =0;4017struct patch *l;4018struct string_list cpath = STRING_LIST_INIT_DUP;40194020for(phase =0; phase <2; phase++) {4021 l = list;4022while(l) {4023if(l->rejected)4024 errs =1;4025else{4026write_out_one_result(l, phase);4027if(phase ==1) {4028if(write_out_one_reject(l))4029 errs =1;4030if(l->conflicted_threeway) {4031string_list_append(&cpath, l->new_name);4032 errs =1;4033}4034}4035}4036 l = l->next;4037}4038}40394040if(cpath.nr) {4041struct string_list_item *item;40424043sort_string_list(&cpath);4044for_each_string_list_item(item, &cpath)4045fprintf(stderr,"U%s\n", item->string);4046string_list_clear(&cpath,0);40474048rerere(0);4049}40504051return errs;4052}40534054static struct lock_file lock_file;40554056static struct string_list limit_by_name;4057static int has_include;4058static voidadd_name_limit(const char*name,int exclude)4059{4060struct string_list_item *it;40614062 it =string_list_append(&limit_by_name, name);4063 it->util = exclude ? NULL : (void*)1;4064}40654066static intuse_patch(struct patch *p)4067{4068const char*pathname = p->new_name ? p->new_name : p->old_name;4069int i;40704071/* Paths outside are not touched regardless of "--include" */4072if(0< prefix_length) {4073int pathlen =strlen(pathname);4074if(pathlen <= prefix_length ||4075memcmp(prefix, pathname, prefix_length))4076return0;4077}40784079/* See if it matches any of exclude/include rule */4080for(i =0; i < limit_by_name.nr; i++) {4081struct string_list_item *it = &limit_by_name.items[i];4082if(!fnmatch(it->string, pathname,0))4083return(it->util != NULL);4084}40854086/*4087 * If we had any include, a path that does not match any rule is4088 * not used. Otherwise, we saw bunch of exclude rules (or none)4089 * and such a path is used.4090 */4091return!has_include;4092}409340944095static voidprefix_one(char**name)4096{4097char*old_name = *name;4098if(!old_name)4099return;4100*name =xstrdup(prefix_filename(prefix, prefix_length, *name));4101free(old_name);4102}41034104static voidprefix_patches(struct patch *p)4105{4106if(!prefix || p->is_toplevel_relative)4107return;4108for( ; p; p = p->next) {4109prefix_one(&p->new_name);4110prefix_one(&p->old_name);4111}4112}41134114#define INACCURATE_EOF (1<<0)4115#define RECOUNT (1<<1)41164117static intapply_patch(int fd,const char*filename,int options)4118{4119size_t offset;4120struct strbuf buf = STRBUF_INIT;/* owns the patch text */4121struct patch *list = NULL, **listp = &list;4122int skipped_patch =0;41234124 patch_input_file = filename;4125read_patch_file(&buf, fd);4126 offset =0;4127while(offset < buf.len) {4128struct patch *patch;4129int nr;41304131 patch =xcalloc(1,sizeof(*patch));4132 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4133 patch->recount = !!(options & RECOUNT);4134 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);4135if(nr <0)4136break;4137if(apply_in_reverse)4138reverse_patches(patch);4139if(prefix)4140prefix_patches(patch);4141if(use_patch(patch)) {4142patch_stats(patch);4143*listp = patch;4144 listp = &patch->next;4145}4146else{4147free_patch(patch);4148 skipped_patch++;4149}4150 offset += nr;4151}41524153if(!list && !skipped_patch)4154die(_("unrecognized input"));41554156if(whitespace_error && (ws_error_action == die_on_ws_error))4157 apply =0;41584159 update_index = check_index && apply;4160if(update_index && newfd <0)4161 newfd =hold_locked_index(&lock_file,1);41624163if(check_index) {4164if(read_cache() <0)4165die(_("unable to read index file"));4166}41674168if((check || apply) &&4169check_patch_list(list) <0&&4170!apply_with_reject)4171exit(1);41724173if(apply &&write_out_results(list)) {4174if(apply_with_reject)4175exit(1);4176/* with --3way, we still need to write the index out */4177return1;4178}41794180if(fake_ancestor)4181build_fake_ancestor(list, fake_ancestor);41824183if(diffstat)4184stat_patch_list(list);41854186if(numstat)4187numstat_patch_list(list);41884189if(summary)4190summary_patch_list(list);41914192free_patch_list(list);4193strbuf_release(&buf);4194string_list_clear(&fn_table,0);4195return0;4196}41974198static intgit_apply_config(const char*var,const char*value,void*cb)4199{4200if(!strcmp(var,"apply.whitespace"))4201returngit_config_string(&apply_default_whitespace, var, value);4202else if(!strcmp(var,"apply.ignorewhitespace"))4203returngit_config_string(&apply_default_ignorewhitespace, var, value);4204returngit_default_config(var, value, cb);4205}42064207static intoption_parse_exclude(const struct option *opt,4208const char*arg,int unset)4209{4210add_name_limit(arg,1);4211return0;4212}42134214static intoption_parse_include(const struct option *opt,4215const char*arg,int unset)4216{4217add_name_limit(arg,0);4218 has_include =1;4219return0;4220}42214222static intoption_parse_p(const struct option *opt,4223const char*arg,int unset)4224{4225 p_value =atoi(arg);4226 p_value_known =1;4227return0;4228}42294230static intoption_parse_z(const struct option *opt,4231const char*arg,int unset)4232{4233if(unset)4234 line_termination ='\n';4235else4236 line_termination =0;4237return0;4238}42394240static intoption_parse_space_change(const struct option *opt,4241const char*arg,int unset)4242{4243if(unset)4244 ws_ignore_action = ignore_ws_none;4245else4246 ws_ignore_action = ignore_ws_change;4247return0;4248}42494250static intoption_parse_whitespace(const struct option *opt,4251const char*arg,int unset)4252{4253const char**whitespace_option = opt->value;42544255*whitespace_option = arg;4256parse_whitespace_option(arg);4257return0;4258}42594260static intoption_parse_directory(const struct option *opt,4261const char*arg,int unset)4262{4263 root_len =strlen(arg);4264if(root_len && arg[root_len -1] !='/') {4265char*new_root;4266 root = new_root =xmalloc(root_len +2);4267strcpy(new_root, arg);4268strcpy(new_root + root_len++,"/");4269}else4270 root = arg;4271return0;4272}42734274intcmd_apply(int argc,const char**argv,const char*prefix_)4275{4276int i;4277int errs =0;4278int is_not_gitdir = !startup_info->have_repository;4279int force_apply =0;42804281const char*whitespace_option = NULL;42824283struct option builtin_apply_options[] = {4284{ OPTION_CALLBACK,0,"exclude", NULL,N_("path"),4285N_("don't apply changes matching the given path"),42860, option_parse_exclude },4287{ OPTION_CALLBACK,0,"include", NULL,N_("path"),4288N_("apply changes matching the given path"),42890, option_parse_include },4290{ OPTION_CALLBACK,'p', NULL, NULL,N_("num"),4291N_("remove <num> leading slashes from traditional diff paths"),42920, option_parse_p },4293OPT_BOOLEAN(0,"no-add", &no_add,4294N_("ignore additions made by the patch")),4295OPT_BOOLEAN(0,"stat", &diffstat,4296N_("instead of applying the patch, output diffstat for the input")),4297OPT_NOOP_NOARG(0,"allow-binary-replacement"),4298OPT_NOOP_NOARG(0,"binary"),4299OPT_BOOLEAN(0,"numstat", &numstat,4300N_("shows number of added and deleted lines in decimal notation")),4301OPT_BOOLEAN(0,"summary", &summary,4302N_("instead of applying the patch, output a summary for the input")),4303OPT_BOOLEAN(0,"check", &check,4304N_("instead of applying the patch, see if the patch is applicable")),4305OPT_BOOLEAN(0,"index", &check_index,4306N_("make sure the patch is applicable to the current index")),4307OPT_BOOLEAN(0,"cached", &cached,4308N_("apply a patch without touching the working tree")),4309OPT_BOOLEAN(0,"apply", &force_apply,4310N_("also apply the patch (use with --stat/--summary/--check)")),4311OPT_BOOL('3',"3way", &threeway,4312N_("attempt three-way merge if a patch does not apply")),4313OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,4314N_("build a temporary index based on embedded index information")),4315{ OPTION_CALLBACK,'z', NULL, NULL, NULL,4316N_("paths are separated with NUL character"),4317 PARSE_OPT_NOARG, option_parse_z },4318OPT_INTEGER('C', NULL, &p_context,4319N_("ensure at least <n> lines of context match")),4320{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,N_("action"),4321N_("detect new or modified lines that have whitespace errors"),43220, option_parse_whitespace },4323{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,4324N_("ignore changes in whitespace when finding context"),4325 PARSE_OPT_NOARG, option_parse_space_change },4326{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,4327N_("ignore changes in whitespace when finding context"),4328 PARSE_OPT_NOARG, option_parse_space_change },4329OPT_BOOLEAN('R',"reverse", &apply_in_reverse,4330N_("apply the patch in reverse")),4331OPT_BOOLEAN(0,"unidiff-zero", &unidiff_zero,4332N_("don't expect at least one line of context")),4333OPT_BOOLEAN(0,"reject", &apply_with_reject,4334N_("leave the rejected hunks in corresponding *.rej files")),4335OPT_BOOLEAN(0,"allow-overlap", &allow_overlap,4336N_("allow overlapping hunks")),4337OPT__VERBOSE(&apply_verbosely,N_("be verbose")),4338OPT_BIT(0,"inaccurate-eof", &options,4339N_("tolerate incorrectly detected missing new-line at the end of file"),4340 INACCURATE_EOF),4341OPT_BIT(0,"recount", &options,4342N_("do not trust the line counts in the hunk headers"),4343 RECOUNT),4344{ OPTION_CALLBACK,0,"directory", NULL,N_("root"),4345N_("prepend <root> to all filenames"),43460, option_parse_directory },4347OPT_END()4348};43494350 prefix = prefix_;4351 prefix_length = prefix ?strlen(prefix) :0;4352git_config(git_apply_config, NULL);4353if(apply_default_whitespace)4354parse_whitespace_option(apply_default_whitespace);4355if(apply_default_ignorewhitespace)4356parse_ignorewhitespace_option(apply_default_ignorewhitespace);43574358 argc =parse_options(argc, argv, prefix, builtin_apply_options,4359 apply_usage,0);43604361if(apply_with_reject && threeway)4362die("--reject and --3way cannot be used together.");4363if(cached && threeway)4364die("--cached and --3way cannot be used together.");4365if(threeway) {4366if(is_not_gitdir)4367die(_("--3way outside a repository"));4368 check_index =1;4369}4370if(apply_with_reject)4371 apply = apply_verbosely =1;4372if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))4373 apply =0;4374if(check_index && is_not_gitdir)4375die(_("--index outside a repository"));4376if(cached) {4377if(is_not_gitdir)4378die(_("--cached outside a repository"));4379 check_index =1;4380}4381for(i =0; i < argc; i++) {4382const char*arg = argv[i];4383int fd;43844385if(!strcmp(arg,"-")) {4386 errs |=apply_patch(0,"<stdin>", options);4387 read_stdin =0;4388continue;4389}else if(0< prefix_length)4390 arg =prefix_filename(prefix, prefix_length, arg);43914392 fd =open(arg, O_RDONLY);4393if(fd <0)4394die_errno(_("can't open patch '%s'"), arg);4395 read_stdin =0;4396set_default_whitespace_mode(whitespace_option);4397 errs |=apply_patch(fd, arg, options);4398close(fd);4399}4400set_default_whitespace_mode(whitespace_option);4401if(read_stdin)4402 errs |=apply_patch(0,"<stdin>", options);4403if(whitespace_error) {4404if(squelch_whitespace_errors &&4405 squelch_whitespace_errors < whitespace_error) {4406int squelched =4407 whitespace_error - squelch_whitespace_errors;4408warning(Q_("squelched%dwhitespace error",4409"squelched%dwhitespace errors",4410 squelched),4411 squelched);4412}4413if(ws_error_action == die_on_ws_error)4414die(Q_("%dline adds whitespace errors.",4415"%dlines add whitespace errors.",4416 whitespace_error),4417 whitespace_error);4418if(applied_after_fixing_ws && apply)4419warning("%dline%sapplied after"4420" fixing whitespace errors.",4421 applied_after_fixing_ws,4422 applied_after_fixing_ws ==1?"":"s");4423else if(whitespace_error)4424warning(Q_("%dline adds whitespace errors.",4425"%dlines add whitespace errors.",4426 whitespace_error),4427 whitespace_error);4428}44294430if(update_index) {4431if(write_cache(newfd, active_cache, active_nr) ||4432commit_locked_index(&lock_file))4433die(_("Unable to write new index file"));4434}44354436return!!errs;4437}