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; 191int lines_added, lines_deleted; 192int score; 193unsigned int is_toplevel_relative:1; 194unsigned int inaccurate_eof:1; 195unsigned int is_binary:1; 196unsigned int is_copy:1; 197unsigned int is_rename:1; 198unsigned int recount:1; 199unsigned int conflicted_threeway:1; 200unsigned int direct_to_threeway:1; 201struct fragment *fragments; 202char*result; 203size_t resultsize; 204char old_sha1_prefix[41]; 205char new_sha1_prefix[41]; 206struct patch *next; 207 208/* three-way fallback result */ 209unsigned char threeway_stage[3][20]; 210}; 211 212static voidfree_fragment_list(struct fragment *list) 213{ 214while(list) { 215struct fragment *next = list->next; 216if(list->free_patch) 217free((char*)list->patch); 218free(list); 219 list = next; 220} 221} 222 223static voidfree_patch(struct patch *patch) 224{ 225free_fragment_list(patch->fragments); 226free(patch->def_name); 227free(patch->old_name); 228free(patch->new_name); 229free(patch->result); 230free(patch); 231} 232 233static voidfree_patch_list(struct patch *list) 234{ 235while(list) { 236struct patch *next = list->next; 237free_patch(list); 238 list = next; 239} 240} 241 242/* 243 * A line in a file, len-bytes long (includes the terminating LF, 244 * except for an incomplete line at the end if the file ends with 245 * one), and its contents hashes to 'hash'. 246 */ 247struct line { 248size_t len; 249unsigned hash :24; 250unsigned flag :8; 251#define LINE_COMMON 1 252#define LINE_PATCHED 2 253}; 254 255/* 256 * This represents a "file", which is an array of "lines". 257 */ 258struct image { 259char*buf; 260size_t len; 261size_t nr; 262size_t alloc; 263struct line *line_allocated; 264struct line *line; 265}; 266 267/* 268 * Records filenames that have been touched, in order to handle 269 * the case where more than one patches touch the same file. 270 */ 271 272static struct string_list fn_table; 273 274static uint32_thash_line(const char*cp,size_t len) 275{ 276size_t i; 277uint32_t h; 278for(i =0, h =0; i < len; i++) { 279if(!isspace(cp[i])) { 280 h = h *3+ (cp[i] &0xff); 281} 282} 283return h; 284} 285 286/* 287 * Compare lines s1 of length n1 and s2 of length n2, ignoring 288 * whitespace difference. Returns 1 if they match, 0 otherwise 289 */ 290static intfuzzy_matchlines(const char*s1,size_t n1, 291const char*s2,size_t n2) 292{ 293const char*last1 = s1 + n1 -1; 294const char*last2 = s2 + n2 -1; 295int result =0; 296 297/* ignore line endings */ 298while((*last1 =='\r') || (*last1 =='\n')) 299 last1--; 300while((*last2 =='\r') || (*last2 =='\n')) 301 last2--; 302 303/* skip leading whitespace */ 304while(isspace(*s1) && (s1 <= last1)) 305 s1++; 306while(isspace(*s2) && (s2 <= last2)) 307 s2++; 308/* early return if both lines are empty */ 309if((s1 > last1) && (s2 > last2)) 310return1; 311while(!result) { 312 result = *s1++ - *s2++; 313/* 314 * Skip whitespace inside. We check for whitespace on 315 * both buffers because we don't want "a b" to match 316 * "ab" 317 */ 318if(isspace(*s1) &&isspace(*s2)) { 319while(isspace(*s1) && s1 <= last1) 320 s1++; 321while(isspace(*s2) && s2 <= last2) 322 s2++; 323} 324/* 325 * If we reached the end on one side only, 326 * lines don't match 327 */ 328if( 329((s2 > last2) && (s1 <= last1)) || 330((s1 > last1) && (s2 <= last2))) 331return0; 332if((s1 > last1) && (s2 > last2)) 333break; 334} 335 336return!result; 337} 338 339static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 340{ 341ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 342 img->line_allocated[img->nr].len = len; 343 img->line_allocated[img->nr].hash =hash_line(bol, len); 344 img->line_allocated[img->nr].flag = flag; 345 img->nr++; 346} 347 348/* 349 * "buf" has the file contents to be patched (read from various sources). 350 * attach it to "image" and add line-based index to it. 351 * "image" now owns the "buf". 352 */ 353static voidprepare_image(struct image *image,char*buf,size_t len, 354int prepare_linetable) 355{ 356const char*cp, *ep; 357 358memset(image,0,sizeof(*image)); 359 image->buf = buf; 360 image->len = len; 361 362if(!prepare_linetable) 363return; 364 365 ep = image->buf + image->len; 366 cp = image->buf; 367while(cp < ep) { 368const char*next; 369for(next = cp; next < ep && *next !='\n'; next++) 370; 371if(next < ep) 372 next++; 373add_line_info(image, cp, next - cp,0); 374 cp = next; 375} 376 image->line = image->line_allocated; 377} 378 379static voidclear_image(struct image *image) 380{ 381free(image->buf); 382free(image->line_allocated); 383memset(image,0,sizeof(*image)); 384} 385 386/* fmt must contain _one_ %s and no other substitution */ 387static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 388{ 389struct strbuf sb = STRBUF_INIT; 390 391if(patch->old_name && patch->new_name && 392strcmp(patch->old_name, patch->new_name)) { 393quote_c_style(patch->old_name, &sb, NULL,0); 394strbuf_addstr(&sb," => "); 395quote_c_style(patch->new_name, &sb, NULL,0); 396}else{ 397const char*n = patch->new_name; 398if(!n) 399 n = patch->old_name; 400quote_c_style(n, &sb, NULL,0); 401} 402fprintf(output, fmt, sb.buf); 403fputc('\n', output); 404strbuf_release(&sb); 405} 406 407#define SLOP (16) 408 409static voidread_patch_file(struct strbuf *sb,int fd) 410{ 411if(strbuf_read(sb, fd,0) <0) 412die_errno("git apply: failed to read"); 413 414/* 415 * Make sure that we have some slop in the buffer 416 * so that we can do speculative "memcmp" etc, and 417 * see to it that it is NUL-filled. 418 */ 419strbuf_grow(sb, SLOP); 420memset(sb->buf + sb->len,0, SLOP); 421} 422 423static unsigned longlinelen(const char*buffer,unsigned long size) 424{ 425unsigned long len =0; 426while(size--) { 427 len++; 428if(*buffer++ =='\n') 429break; 430} 431return len; 432} 433 434static intis_dev_null(const char*str) 435{ 436return!memcmp("/dev/null", str,9) &&isspace(str[9]); 437} 438 439#define TERM_SPACE 1 440#define TERM_TAB 2 441 442static intname_terminate(const char*name,int namelen,int c,int terminate) 443{ 444if(c ==' '&& !(terminate & TERM_SPACE)) 445return0; 446if(c =='\t'&& !(terminate & TERM_TAB)) 447return0; 448 449return1; 450} 451 452/* remove double slashes to make --index work with such filenames */ 453static char*squash_slash(char*name) 454{ 455int i =0, j =0; 456 457if(!name) 458return NULL; 459 460while(name[i]) { 461if((name[j++] = name[i++]) =='/') 462while(name[i] =='/') 463 i++; 464} 465 name[j] ='\0'; 466return name; 467} 468 469static char*find_name_gnu(const char*line,const char*def,int p_value) 470{ 471struct strbuf name = STRBUF_INIT; 472char*cp; 473 474/* 475 * Proposed "new-style" GNU patch/diff format; see 476 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2 477 */ 478if(unquote_c_style(&name, line, NULL)) { 479strbuf_release(&name); 480return NULL; 481} 482 483for(cp = name.buf; p_value; p_value--) { 484 cp =strchr(cp,'/'); 485if(!cp) { 486strbuf_release(&name); 487return NULL; 488} 489 cp++; 490} 491 492strbuf_remove(&name,0, cp - name.buf); 493if(root) 494strbuf_insert(&name,0, root, root_len); 495returnsquash_slash(strbuf_detach(&name, NULL)); 496} 497 498static size_tsane_tz_len(const char*line,size_t len) 499{ 500const char*tz, *p; 501 502if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 503return0; 504 tz = line + len -strlen(" +0500"); 505 506if(tz[1] !='+'&& tz[1] !='-') 507return0; 508 509for(p = tz +2; p != line + len; p++) 510if(!isdigit(*p)) 511return0; 512 513return line + len - tz; 514} 515 516static size_ttz_with_colon_len(const char*line,size_t len) 517{ 518const char*tz, *p; 519 520if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 521return0; 522 tz = line + len -strlen(" +08:00"); 523 524if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 525return0; 526 p = tz +2; 527if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 528!isdigit(*p++) || !isdigit(*p++)) 529return0; 530 531return line + len - tz; 532} 533 534static size_tdate_len(const char*line,size_t len) 535{ 536const char*date, *p; 537 538if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 539return0; 540 p = date = line + len -strlen("72-02-05"); 541 542if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 543!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 544!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 545return0; 546 547if(date - line >=strlen("19") && 548isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 549 date -=strlen("19"); 550 551return line + len - date; 552} 553 554static size_tshort_time_len(const char*line,size_t len) 555{ 556const char*time, *p; 557 558if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 559return0; 560 p = time = line + len -strlen(" 07:01:32"); 561 562/* Permit 1-digit hours? */ 563if(*p++ !=' '|| 564!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 565!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 566!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 567return0; 568 569return line + len - time; 570} 571 572static size_tfractional_time_len(const char*line,size_t len) 573{ 574const char*p; 575size_t n; 576 577/* Expected format: 19:41:17.620000023 */ 578if(!len || !isdigit(line[len -1])) 579return0; 580 p = line + len -1; 581 582/* Fractional seconds. */ 583while(p > line &&isdigit(*p)) 584 p--; 585if(*p !='.') 586return0; 587 588/* Hours, minutes, and whole seconds. */ 589 n =short_time_len(line, p - line); 590if(!n) 591return0; 592 593return line + len - p + n; 594} 595 596static size_ttrailing_spaces_len(const char*line,size_t len) 597{ 598const char*p; 599 600/* Expected format: ' ' x (1 or more) */ 601if(!len || line[len -1] !=' ') 602return0; 603 604 p = line + len; 605while(p != line) { 606 p--; 607if(*p !=' ') 608return line + len - (p +1); 609} 610 611/* All spaces! */ 612return len; 613} 614 615static size_tdiff_timestamp_len(const char*line,size_t len) 616{ 617const char*end = line + len; 618size_t n; 619 620/* 621 * Posix: 2010-07-05 19:41:17 622 * GNU: 2010-07-05 19:41:17.620000023 -0500 623 */ 624 625if(!isdigit(end[-1])) 626return0; 627 628 n =sane_tz_len(line, end - line); 629if(!n) 630 n =tz_with_colon_len(line, end - line); 631 end -= n; 632 633 n =short_time_len(line, end - line); 634if(!n) 635 n =fractional_time_len(line, end - line); 636 end -= n; 637 638 n =date_len(line, end - line); 639if(!n)/* No date. Too bad. */ 640return0; 641 end -= n; 642 643if(end == line)/* No space before date. */ 644return0; 645if(end[-1] =='\t') {/* Success! */ 646 end--; 647return line + len - end; 648} 649if(end[-1] !=' ')/* No space before date. */ 650return0; 651 652/* Whitespace damage. */ 653 end -=trailing_spaces_len(line, end - line); 654return line + len - end; 655} 656 657static char*null_strdup(const char*s) 658{ 659return s ?xstrdup(s) : NULL; 660} 661 662static char*find_name_common(const char*line,const char*def, 663int p_value,const char*end,int terminate) 664{ 665int len; 666const char*start = NULL; 667 668if(p_value ==0) 669 start = line; 670while(line != end) { 671char c = *line; 672 673if(!end &&isspace(c)) { 674if(c =='\n') 675break; 676if(name_terminate(start, line-start, c, terminate)) 677break; 678} 679 line++; 680if(c =='/'&& !--p_value) 681 start = line; 682} 683if(!start) 684returnsquash_slash(null_strdup(def)); 685 len = line - start; 686if(!len) 687returnsquash_slash(null_strdup(def)); 688 689/* 690 * Generally we prefer the shorter name, especially 691 * if the other one is just a variation of that with 692 * something else tacked on to the end (ie "file.orig" 693 * or "file~"). 694 */ 695if(def) { 696int deflen =strlen(def); 697if(deflen < len && !strncmp(start, def, deflen)) 698returnsquash_slash(xstrdup(def)); 699} 700 701if(root) { 702char*ret =xmalloc(root_len + len +1); 703strcpy(ret, root); 704memcpy(ret + root_len, start, len); 705 ret[root_len + len] ='\0'; 706returnsquash_slash(ret); 707} 708 709returnsquash_slash(xmemdupz(start, len)); 710} 711 712static char*find_name(const char*line,char*def,int p_value,int terminate) 713{ 714if(*line =='"') { 715char*name =find_name_gnu(line, def, p_value); 716if(name) 717return name; 718} 719 720returnfind_name_common(line, def, p_value, NULL, terminate); 721} 722 723static char*find_name_traditional(const char*line,char*def,int p_value) 724{ 725size_t len =strlen(line); 726size_t date_len; 727 728if(*line =='"') { 729char*name =find_name_gnu(line, def, p_value); 730if(name) 731return name; 732} 733 734 len =strchrnul(line,'\n') - line; 735 date_len =diff_timestamp_len(line, len); 736if(!date_len) 737returnfind_name_common(line, def, p_value, NULL, TERM_TAB); 738 len -= date_len; 739 740returnfind_name_common(line, def, p_value, line + len,0); 741} 742 743static intcount_slashes(const char*cp) 744{ 745int cnt =0; 746char ch; 747 748while((ch = *cp++)) 749if(ch =='/') 750 cnt++; 751return cnt; 752} 753 754/* 755 * Given the string after "--- " or "+++ ", guess the appropriate 756 * p_value for the given patch. 757 */ 758static intguess_p_value(const char*nameline) 759{ 760char*name, *cp; 761int val = -1; 762 763if(is_dev_null(nameline)) 764return-1; 765 name =find_name_traditional(nameline, NULL,0); 766if(!name) 767return-1; 768 cp =strchr(name,'/'); 769if(!cp) 770 val =0; 771else if(prefix) { 772/* 773 * Does it begin with "a/$our-prefix" and such? Then this is 774 * very likely to apply to our directory. 775 */ 776if(!strncmp(name, prefix, prefix_length)) 777 val =count_slashes(prefix); 778else{ 779 cp++; 780if(!strncmp(cp, prefix, prefix_length)) 781 val =count_slashes(prefix) +1; 782} 783} 784free(name); 785return val; 786} 787 788/* 789 * Does the ---/+++ line has the POSIX timestamp after the last HT? 790 * GNU diff puts epoch there to signal a creation/deletion event. Is 791 * this such a timestamp? 792 */ 793static inthas_epoch_timestamp(const char*nameline) 794{ 795/* 796 * We are only interested in epoch timestamp; any non-zero 797 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 798 * For the same reason, the date must be either 1969-12-31 or 799 * 1970-01-01, and the seconds part must be "00". 800 */ 801const char stamp_regexp[] = 802"^(1969-12-31|1970-01-01)" 803" " 804"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 805" " 806"([-+][0-2][0-9]:?[0-5][0-9])\n"; 807const char*timestamp = NULL, *cp, *colon; 808static regex_t *stamp; 809 regmatch_t m[10]; 810int zoneoffset; 811int hourminute; 812int status; 813 814for(cp = nameline; *cp !='\n'; cp++) { 815if(*cp =='\t') 816 timestamp = cp +1; 817} 818if(!timestamp) 819return0; 820if(!stamp) { 821 stamp =xmalloc(sizeof(*stamp)); 822if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 823warning(_("Cannot prepare timestamp regexp%s"), 824 stamp_regexp); 825return0; 826} 827} 828 829 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 830if(status) { 831if(status != REG_NOMATCH) 832warning(_("regexec returned%dfor input:%s"), 833 status, timestamp); 834return0; 835} 836 837 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 838if(*colon ==':') 839 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 840else 841 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 842if(timestamp[m[3].rm_so] =='-') 843 zoneoffset = -zoneoffset; 844 845/* 846 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 847 * (west of GMT) or 1970-01-01 (east of GMT) 848 */ 849if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 850(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 851return0; 852 853 hourminute = (strtol(timestamp +11, NULL,10) *60+ 854strtol(timestamp +14, NULL,10) - 855 zoneoffset); 856 857return((zoneoffset <0&& hourminute ==1440) || 858(0<= zoneoffset && !hourminute)); 859} 860 861/* 862 * Get the name etc info from the ---/+++ lines of a traditional patch header 863 * 864 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 865 * files, we can happily check the index for a match, but for creating a 866 * new file we should try to match whatever "patch" does. I have no idea. 867 */ 868static voidparse_traditional_patch(const char*first,const char*second,struct patch *patch) 869{ 870char*name; 871 872 first +=4;/* skip "--- " */ 873 second +=4;/* skip "+++ " */ 874if(!p_value_known) { 875int p, q; 876 p =guess_p_value(first); 877 q =guess_p_value(second); 878if(p <0) p = q; 879if(0<= p && p == q) { 880 p_value = p; 881 p_value_known =1; 882} 883} 884if(is_dev_null(first)) { 885 patch->is_new =1; 886 patch->is_delete =0; 887 name =find_name_traditional(second, NULL, p_value); 888 patch->new_name = name; 889}else if(is_dev_null(second)) { 890 patch->is_new =0; 891 patch->is_delete =1; 892 name =find_name_traditional(first, NULL, p_value); 893 patch->old_name = name; 894}else{ 895char*first_name; 896 first_name =find_name_traditional(first, NULL, p_value); 897 name =find_name_traditional(second, first_name, p_value); 898free(first_name); 899if(has_epoch_timestamp(first)) { 900 patch->is_new =1; 901 patch->is_delete =0; 902 patch->new_name = name; 903}else if(has_epoch_timestamp(second)) { 904 patch->is_new =0; 905 patch->is_delete =1; 906 patch->old_name = name; 907}else{ 908 patch->old_name = name; 909 patch->new_name =xstrdup(name); 910} 911} 912if(!name) 913die(_("unable to find filename in patch at line%d"), linenr); 914} 915 916static intgitdiff_hdrend(const char*line,struct patch *patch) 917{ 918return-1; 919} 920 921/* 922 * We're anal about diff header consistency, to make 923 * sure that we don't end up having strange ambiguous 924 * patches floating around. 925 * 926 * As a result, gitdiff_{old|new}name() will check 927 * their names against any previous information, just 928 * to make sure.. 929 */ 930#define DIFF_OLD_NAME 0 931#define DIFF_NEW_NAME 1 932 933static char*gitdiff_verify_name(const char*line,int isnull,char*orig_name,int side) 934{ 935if(!orig_name && !isnull) 936returnfind_name(line, NULL, p_value, TERM_TAB); 937 938if(orig_name) { 939int len; 940const char*name; 941char*another; 942 name = orig_name; 943 len =strlen(name); 944if(isnull) 945die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), name, linenr); 946 another =find_name(line, NULL, p_value, TERM_TAB); 947if(!another ||memcmp(another, name, len +1)) 948die((side == DIFF_NEW_NAME) ? 949_("git apply: bad git-diff - inconsistent new filename on line%d") : 950_("git apply: bad git-diff - inconsistent old filename on line%d"), linenr); 951free(another); 952return orig_name; 953} 954else{ 955/* expect "/dev/null" */ 956if(memcmp("/dev/null", line,9) || line[9] !='\n') 957die(_("git apply: bad git-diff - expected /dev/null on line%d"), linenr); 958return NULL; 959} 960} 961 962static intgitdiff_oldname(const char*line,struct patch *patch) 963{ 964char*orig = patch->old_name; 965 patch->old_name =gitdiff_verify_name(line, patch->is_new, patch->old_name, 966 DIFF_OLD_NAME); 967if(orig != patch->old_name) 968free(orig); 969return0; 970} 971 972static intgitdiff_newname(const char*line,struct patch *patch) 973{ 974char*orig = patch->new_name; 975 patch->new_name =gitdiff_verify_name(line, patch->is_delete, patch->new_name, 976 DIFF_NEW_NAME); 977if(orig != patch->new_name) 978free(orig); 979return0; 980} 981 982static intgitdiff_oldmode(const char*line,struct patch *patch) 983{ 984 patch->old_mode =strtoul(line, NULL,8); 985return0; 986} 987 988static intgitdiff_newmode(const char*line,struct patch *patch) 989{ 990 patch->new_mode =strtoul(line, NULL,8); 991return0; 992} 993 994static intgitdiff_delete(const char*line,struct patch *patch) 995{ 996 patch->is_delete =1; 997free(patch->old_name); 998 patch->old_name =null_strdup(patch->def_name); 999returngitdiff_oldmode(line, patch);1000}10011002static intgitdiff_newfile(const char*line,struct patch *patch)1003{1004 patch->is_new =1;1005free(patch->new_name);1006 patch->new_name =null_strdup(patch->def_name);1007returngitdiff_newmode(line, patch);1008}10091010static intgitdiff_copysrc(const char*line,struct patch *patch)1011{1012 patch->is_copy =1;1013free(patch->old_name);1014 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0);1015return0;1016}10171018static intgitdiff_copydst(const char*line,struct patch *patch)1019{1020 patch->is_copy =1;1021free(patch->new_name);1022 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0);1023return0;1024}10251026static intgitdiff_renamesrc(const char*line,struct patch *patch)1027{1028 patch->is_rename =1;1029free(patch->old_name);1030 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0);1031return0;1032}10331034static intgitdiff_renamedst(const char*line,struct patch *patch)1035{1036 patch->is_rename =1;1037free(patch->new_name);1038 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0);1039return0;1040}10411042static intgitdiff_similarity(const char*line,struct patch *patch)1043{1044if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX)1045 patch->score =0;1046return0;1047}10481049static intgitdiff_dissimilarity(const char*line,struct patch *patch)1050{1051if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX)1052 patch->score =0;1053return0;1054}10551056static intgitdiff_index(const char*line,struct patch *patch)1057{1058/*1059 * index line is N hexadecimal, "..", N hexadecimal,1060 * and optional space with octal mode.1061 */1062const char*ptr, *eol;1063int len;10641065 ptr =strchr(line,'.');1066if(!ptr || ptr[1] !='.'||40< ptr - line)1067return0;1068 len = ptr - line;1069memcpy(patch->old_sha1_prefix, line, len);1070 patch->old_sha1_prefix[len] =0;10711072 line = ptr +2;1073 ptr =strchr(line,' ');1074 eol =strchr(line,'\n');10751076if(!ptr || eol < ptr)1077 ptr = eol;1078 len = ptr - line;10791080if(40< len)1081return0;1082memcpy(patch->new_sha1_prefix, line, len);1083 patch->new_sha1_prefix[len] =0;1084if(*ptr ==' ')1085 patch->old_mode =strtoul(ptr+1, NULL,8);1086return0;1087}10881089/*1090 * This is normal for a diff that doesn't change anything: we'll fall through1091 * into the next diff. Tell the parser to break out.1092 */1093static intgitdiff_unrecognized(const char*line,struct patch *patch)1094{1095return-1;1096}10971098/*1099 * Skip p_value leading components from "line"; as we do not accept1100 * absolute paths, return NULL in that case.1101 */1102static const char*skip_tree_prefix(const char*line,int llen)1103{1104int nslash;1105int i;11061107if(!p_value)1108return(llen && line[0] =='/') ? NULL : line;11091110 nslash = p_value;1111for(i =0; i < llen; i++) {1112int ch = line[i];1113if(ch =='/'&& --nslash <=0)1114return(i ==0) ? NULL : &line[i +1];1115}1116return NULL;1117}11181119/*1120 * This is to extract the same name that appears on "diff --git"1121 * line. We do not find and return anything if it is a rename1122 * patch, and it is OK because we will find the name elsewhere.1123 * We need to reliably find name only when it is mode-change only,1124 * creation or deletion of an empty file. In any of these cases,1125 * both sides are the same name under a/ and b/ respectively.1126 */1127static char*git_header_name(const char*line,int llen)1128{1129const char*name;1130const char*second = NULL;1131size_t len, line_len;11321133 line +=strlen("diff --git ");1134 llen -=strlen("diff --git ");11351136if(*line =='"') {1137const char*cp;1138struct strbuf first = STRBUF_INIT;1139struct strbuf sp = STRBUF_INIT;11401141if(unquote_c_style(&first, line, &second))1142goto free_and_fail1;11431144/* strip the a/b prefix including trailing slash */1145 cp =skip_tree_prefix(first.buf, first.len);1146if(!cp)1147goto free_and_fail1;1148strbuf_remove(&first,0, cp - first.buf);11491150/*1151 * second points at one past closing dq of name.1152 * find the second name.1153 */1154while((second < line + llen) &&isspace(*second))1155 second++;11561157if(line + llen <= second)1158goto free_and_fail1;1159if(*second =='"') {1160if(unquote_c_style(&sp, second, NULL))1161goto free_and_fail1;1162 cp =skip_tree_prefix(sp.buf, sp.len);1163if(!cp)1164goto free_and_fail1;1165/* They must match, otherwise ignore */1166if(strcmp(cp, first.buf))1167goto free_and_fail1;1168strbuf_release(&sp);1169returnstrbuf_detach(&first, NULL);1170}11711172/* unquoted second */1173 cp =skip_tree_prefix(second, line + llen - second);1174if(!cp)1175goto free_and_fail1;1176if(line + llen - cp != first.len ||1177memcmp(first.buf, cp, first.len))1178goto free_and_fail1;1179returnstrbuf_detach(&first, NULL);11801181 free_and_fail1:1182strbuf_release(&first);1183strbuf_release(&sp);1184return NULL;1185}11861187/* unquoted first name */1188 name =skip_tree_prefix(line, llen);1189if(!name)1190return NULL;11911192/*1193 * since the first name is unquoted, a dq if exists must be1194 * the beginning of the second name.1195 */1196for(second = name; second < line + llen; second++) {1197if(*second =='"') {1198struct strbuf sp = STRBUF_INIT;1199const char*np;12001201if(unquote_c_style(&sp, second, NULL))1202goto free_and_fail2;12031204 np =skip_tree_prefix(sp.buf, sp.len);1205if(!np)1206goto free_and_fail2;12071208 len = sp.buf + sp.len - np;1209if(len < second - name &&1210!strncmp(np, name, len) &&1211isspace(name[len])) {1212/* Good */1213strbuf_remove(&sp,0, np - sp.buf);1214returnstrbuf_detach(&sp, NULL);1215}12161217 free_and_fail2:1218strbuf_release(&sp);1219return NULL;1220}1221}12221223/*1224 * Accept a name only if it shows up twice, exactly the same1225 * form.1226 */1227 second =strchr(name,'\n');1228if(!second)1229return NULL;1230 line_len = second - name;1231for(len =0; ; len++) {1232switch(name[len]) {1233default:1234continue;1235case'\n':1236return NULL;1237case'\t':case' ':1238/*1239 * Is this the separator between the preimage1240 * and the postimage pathname? Again, we are1241 * only interested in the case where there is1242 * no rename, as this is only to set def_name1243 * and a rename patch has the names elsewhere1244 * in an unambiguous form.1245 */1246if(!name[len +1])1247return NULL;/* no postimage name */1248 second =skip_tree_prefix(name + len +1,1249 line_len - (len +1));1250if(!second)1251return NULL;1252/*1253 * Does len bytes starting at "name" and "second"1254 * (that are separated by one HT or SP we just1255 * found) exactly match?1256 */1257if(second[len] =='\n'&& !strncmp(name, second, len))1258returnxmemdupz(name, len);1259}1260}1261}12621263/* Verify that we recognize the lines following a git header */1264static intparse_git_header(const char*line,int len,unsigned int size,struct patch *patch)1265{1266unsigned long offset;12671268/* A git diff has explicit new/delete information, so we don't guess */1269 patch->is_new =0;1270 patch->is_delete =0;12711272/*1273 * Some things may not have the old name in the1274 * rest of the headers anywhere (pure mode changes,1275 * or removing or adding empty files), so we get1276 * the default name from the header.1277 */1278 patch->def_name =git_header_name(line, len);1279if(patch->def_name && root) {1280char*s =xmalloc(root_len +strlen(patch->def_name) +1);1281strcpy(s, root);1282strcpy(s + root_len, patch->def_name);1283free(patch->def_name);1284 patch->def_name = s;1285}12861287 line += len;1288 size -= len;1289 linenr++;1290for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) {1291static const struct opentry {1292const char*str;1293int(*fn)(const char*,struct patch *);1294} optable[] = {1295{"@@ -", gitdiff_hdrend },1296{"--- ", gitdiff_oldname },1297{"+++ ", gitdiff_newname },1298{"old mode ", gitdiff_oldmode },1299{"new mode ", gitdiff_newmode },1300{"deleted file mode ", gitdiff_delete },1301{"new file mode ", gitdiff_newfile },1302{"copy from ", gitdiff_copysrc },1303{"copy to ", gitdiff_copydst },1304{"rename old ", gitdiff_renamesrc },1305{"rename new ", gitdiff_renamedst },1306{"rename from ", gitdiff_renamesrc },1307{"rename to ", gitdiff_renamedst },1308{"similarity index ", gitdiff_similarity },1309{"dissimilarity index ", gitdiff_dissimilarity },1310{"index ", gitdiff_index },1311{"", gitdiff_unrecognized },1312};1313int i;13141315 len =linelen(line, size);1316if(!len || line[len-1] !='\n')1317break;1318for(i =0; i <ARRAY_SIZE(optable); i++) {1319const struct opentry *p = optable + i;1320int oplen =strlen(p->str);1321if(len < oplen ||memcmp(p->str, line, oplen))1322continue;1323if(p->fn(line + oplen, patch) <0)1324return offset;1325break;1326}1327}13281329return offset;1330}13311332static intparse_num(const char*line,unsigned long*p)1333{1334char*ptr;13351336if(!isdigit(*line))1337return0;1338*p =strtoul(line, &ptr,10);1339return ptr - line;1340}13411342static intparse_range(const char*line,int len,int offset,const char*expect,1343unsigned long*p1,unsigned long*p2)1344{1345int digits, ex;13461347if(offset <0|| offset >= len)1348return-1;1349 line += offset;1350 len -= offset;13511352 digits =parse_num(line, p1);1353if(!digits)1354return-1;13551356 offset += digits;1357 line += digits;1358 len -= digits;13591360*p2 =1;1361if(*line ==',') {1362 digits =parse_num(line+1, p2);1363if(!digits)1364return-1;13651366 offset += digits+1;1367 line += digits+1;1368 len -= digits+1;1369}13701371 ex =strlen(expect);1372if(ex > len)1373return-1;1374if(memcmp(line, expect, ex))1375return-1;13761377return offset + ex;1378}13791380static voidrecount_diff(const char*line,int size,struct fragment *fragment)1381{1382int oldlines =0, newlines =0, ret =0;13831384if(size <1) {1385warning("recount: ignore empty hunk");1386return;1387}13881389for(;;) {1390int len =linelen(line, size);1391 size -= len;1392 line += len;13931394if(size <1)1395break;13961397switch(*line) {1398case' ':case'\n':1399 newlines++;1400/* fall through */1401case'-':1402 oldlines++;1403continue;1404case'+':1405 newlines++;1406continue;1407case'\\':1408continue;1409case'@':1410 ret = size <3||prefixcmp(line,"@@ ");1411break;1412case'd':1413 ret = size <5||prefixcmp(line,"diff ");1414break;1415default:1416 ret = -1;1417break;1418}1419if(ret) {1420warning(_("recount: unexpected line: %.*s"),1421(int)linelen(line, size), line);1422return;1423}1424break;1425}1426 fragment->oldlines = oldlines;1427 fragment->newlines = newlines;1428}14291430/*1431 * Parse a unified diff fragment header of the1432 * form "@@ -a,b +c,d @@"1433 */1434static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1435{1436int offset;14371438if(!len || line[len-1] !='\n')1439return-1;14401441/* Figure out the number of lines in a fragment */1442 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1443 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14441445return offset;1446}14471448static intfind_header(const char*line,unsigned long size,int*hdrsize,struct patch *patch)1449{1450unsigned long offset, len;14511452 patch->is_toplevel_relative =0;1453 patch->is_rename = patch->is_copy =0;1454 patch->is_new = patch->is_delete = -1;1455 patch->old_mode = patch->new_mode =0;1456 patch->old_name = patch->new_name = NULL;1457for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) {1458unsigned long nextlen;14591460 len =linelen(line, size);1461if(!len)1462break;14631464/* Testing this early allows us to take a few shortcuts.. */1465if(len <6)1466continue;14671468/*1469 * Make sure we don't find any unconnected patch fragments.1470 * That's a sign that we didn't find a header, and that a1471 * patch has become corrupted/broken up.1472 */1473if(!memcmp("@@ -", line,4)) {1474struct fragment dummy;1475if(parse_fragment_header(line, len, &dummy) <0)1476continue;1477die(_("patch fragment without header at line%d: %.*s"),1478 linenr, (int)len-1, line);1479}14801481if(size < len +6)1482break;14831484/*1485 * Git patch? It might not have a real patch, just a rename1486 * or mode change, so we handle that specially1487 */1488if(!memcmp("diff --git ", line,11)) {1489int git_hdr_len =parse_git_header(line, len, size, patch);1490if(git_hdr_len <= len)1491continue;1492if(!patch->old_name && !patch->new_name) {1493if(!patch->def_name)1494die(Q_("git diff header lacks filename information when removing "1495"%dleading pathname component (line%d)",1496"git diff header lacks filename information when removing "1497"%dleading pathname components (line%d)",1498 p_value),1499 p_value, linenr);1500 patch->old_name =xstrdup(patch->def_name);1501 patch->new_name =xstrdup(patch->def_name);1502}1503if(!patch->is_delete && !patch->new_name)1504die("git diff header lacks filename information "1505"(line%d)", linenr);1506 patch->is_toplevel_relative =1;1507*hdrsize = git_hdr_len;1508return offset;1509}15101511/* --- followed by +++ ? */1512if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1513continue;15141515/*1516 * We only accept unified patches, so we want it to1517 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1518 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1519 */1520 nextlen =linelen(line + len, size - len);1521if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1522continue;15231524/* Ok, we'll consider it a patch */1525parse_traditional_patch(line, line+len, patch);1526*hdrsize = len + nextlen;1527 linenr +=2;1528return offset;1529}1530return-1;1531}15321533static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1534{1535char*err;15361537if(!result)1538return;15391540 whitespace_error++;1541if(squelch_whitespace_errors &&1542 squelch_whitespace_errors < whitespace_error)1543return;15441545 err =whitespace_error_string(result);1546fprintf(stderr,"%s:%d:%s.\n%.*s\n",1547 patch_input_file, linenr, err, len, line);1548free(err);1549}15501551static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1552{1553unsigned result =ws_check(line +1, len -1, ws_rule);15541555record_ws_error(result, line +1, len -2, linenr);1556}15571558/*1559 * Parse a unified diff. Note that this really needs to parse each1560 * fragment separately, since the only way to know the difference1561 * between a "---" that is part of a patch, and a "---" that starts1562 * the next patch is to look at the line counts..1563 */1564static intparse_fragment(const char*line,unsigned long size,1565struct patch *patch,struct fragment *fragment)1566{1567int added, deleted;1568int len =linelen(line, size), offset;1569unsigned long oldlines, newlines;1570unsigned long leading, trailing;15711572 offset =parse_fragment_header(line, len, fragment);1573if(offset <0)1574return-1;1575if(offset >0&& patch->recount)1576recount_diff(line + offset, size - offset, fragment);1577 oldlines = fragment->oldlines;1578 newlines = fragment->newlines;1579 leading =0;1580 trailing =0;15811582/* Parse the thing.. */1583 line += len;1584 size -= len;1585 linenr++;1586 added = deleted =0;1587for(offset = len;15880< size;1589 offset += len, size -= len, line += len, linenr++) {1590if(!oldlines && !newlines)1591break;1592 len =linelen(line, size);1593if(!len || line[len-1] !='\n')1594return-1;1595switch(*line) {1596default:1597return-1;1598case'\n':/* newer GNU diff, an empty context line */1599case' ':1600 oldlines--;1601 newlines--;1602if(!deleted && !added)1603 leading++;1604 trailing++;1605break;1606case'-':1607if(apply_in_reverse &&1608 ws_error_action != nowarn_ws_error)1609check_whitespace(line, len, patch->ws_rule);1610 deleted++;1611 oldlines--;1612 trailing =0;1613break;1614case'+':1615if(!apply_in_reverse &&1616 ws_error_action != nowarn_ws_error)1617check_whitespace(line, len, patch->ws_rule);1618 added++;1619 newlines--;1620 trailing =0;1621break;16221623/*1624 * We allow "\ No newline at end of file". Depending1625 * on locale settings when the patch was produced we1626 * don't know what this line looks like. The only1627 * thing we do know is that it begins with "\ ".1628 * Checking for 12 is just for sanity check -- any1629 * l10n of "\ No newline..." is at least that long.1630 */1631case'\\':1632if(len <12||memcmp(line,"\\",2))1633return-1;1634break;1635}1636}1637if(oldlines || newlines)1638return-1;1639 fragment->leading = leading;1640 fragment->trailing = trailing;16411642/*1643 * If a fragment ends with an incomplete line, we failed to include1644 * it in the above loop because we hit oldlines == newlines == 01645 * before seeing it.1646 */1647if(12< size && !memcmp(line,"\\",2))1648 offset +=linelen(line, size);16491650 patch->lines_added += added;1651 patch->lines_deleted += deleted;16521653if(0< patch->is_new && oldlines)1654returnerror(_("new file depends on old contents"));1655if(0< patch->is_delete && newlines)1656returnerror(_("deleted file still has contents"));1657return offset;1658}16591660/*1661 * We have seen "diff --git a/... b/..." header (or a traditional patch1662 * header). Read hunks that belong to this patch into fragments and hang1663 * them to the given patch structure.1664 *1665 * The (fragment->patch, fragment->size) pair points into the memory given1666 * by the caller, not a copy, when we return.1667 */1668static intparse_single_patch(const char*line,unsigned long size,struct patch *patch)1669{1670unsigned long offset =0;1671unsigned long oldlines =0, newlines =0, context =0;1672struct fragment **fragp = &patch->fragments;16731674while(size >4&& !memcmp(line,"@@ -",4)) {1675struct fragment *fragment;1676int len;16771678 fragment =xcalloc(1,sizeof(*fragment));1679 fragment->linenr = linenr;1680 len =parse_fragment(line, size, patch, fragment);1681if(len <=0)1682die(_("corrupt patch at line%d"), linenr);1683 fragment->patch = line;1684 fragment->size = len;1685 oldlines += fragment->oldlines;1686 newlines += fragment->newlines;1687 context += fragment->leading + fragment->trailing;16881689*fragp = fragment;1690 fragp = &fragment->next;16911692 offset += len;1693 line += len;1694 size -= len;1695}16961697/*1698 * If something was removed (i.e. we have old-lines) it cannot1699 * be creation, and if something was added it cannot be1700 * deletion. However, the reverse is not true; --unified=01701 * patches that only add are not necessarily creation even1702 * though they do not have any old lines, and ones that only1703 * delete are not necessarily deletion.1704 *1705 * Unfortunately, a real creation/deletion patch do _not_ have1706 * any context line by definition, so we cannot safely tell it1707 * apart with --unified=0 insanity. At least if the patch has1708 * more than one hunk it is not creation or deletion.1709 */1710if(patch->is_new <0&&1711(oldlines || (patch->fragments && patch->fragments->next)))1712 patch->is_new =0;1713if(patch->is_delete <0&&1714(newlines || (patch->fragments && patch->fragments->next)))1715 patch->is_delete =0;17161717if(0< patch->is_new && oldlines)1718die(_("new file%sdepends on old contents"), patch->new_name);1719if(0< patch->is_delete && newlines)1720die(_("deleted file%sstill has contents"), patch->old_name);1721if(!patch->is_delete && !newlines && context)1722fprintf_ln(stderr,1723_("** warning: "1724"file%sbecomes empty but is not deleted"),1725 patch->new_name);17261727return offset;1728}17291730staticinlineintmetadata_changes(struct patch *patch)1731{1732return patch->is_rename >0||1733 patch->is_copy >0||1734 patch->is_new >0||1735 patch->is_delete ||1736(patch->old_mode && patch->new_mode &&1737 patch->old_mode != patch->new_mode);1738}17391740static char*inflate_it(const void*data,unsigned long size,1741unsigned long inflated_size)1742{1743 git_zstream stream;1744void*out;1745int st;17461747memset(&stream,0,sizeof(stream));17481749 stream.next_in = (unsigned char*)data;1750 stream.avail_in = size;1751 stream.next_out = out =xmalloc(inflated_size);1752 stream.avail_out = inflated_size;1753git_inflate_init(&stream);1754 st =git_inflate(&stream, Z_FINISH);1755git_inflate_end(&stream);1756if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1757free(out);1758return NULL;1759}1760return out;1761}17621763/*1764 * Read a binary hunk and return a new fragment; fragment->patch1765 * points at an allocated memory that the caller must free, so1766 * it is marked as "->free_patch = 1".1767 */1768static struct fragment *parse_binary_hunk(char**buf_p,1769unsigned long*sz_p,1770int*status_p,1771int*used_p)1772{1773/*1774 * Expect a line that begins with binary patch method ("literal"1775 * or "delta"), followed by the length of data before deflating.1776 * a sequence of 'length-byte' followed by base-85 encoded data1777 * should follow, terminated by a newline.1778 *1779 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1780 * and we would limit the patch line to 66 characters,1781 * so one line can fit up to 13 groups that would decode1782 * to 52 bytes max. The length byte 'A'-'Z' corresponds1783 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1784 */1785int llen, used;1786unsigned long size = *sz_p;1787char*buffer = *buf_p;1788int patch_method;1789unsigned long origlen;1790char*data = NULL;1791int hunk_size =0;1792struct fragment *frag;17931794 llen =linelen(buffer, size);1795 used = llen;17961797*status_p =0;17981799if(!prefixcmp(buffer,"delta ")) {1800 patch_method = BINARY_DELTA_DEFLATED;1801 origlen =strtoul(buffer +6, NULL,10);1802}1803else if(!prefixcmp(buffer,"literal ")) {1804 patch_method = BINARY_LITERAL_DEFLATED;1805 origlen =strtoul(buffer +8, NULL,10);1806}1807else1808return NULL;18091810 linenr++;1811 buffer += llen;1812while(1) {1813int byte_length, max_byte_length, newsize;1814 llen =linelen(buffer, size);1815 used += llen;1816 linenr++;1817if(llen ==1) {1818/* consume the blank line */1819 buffer++;1820 size--;1821break;1822}1823/*1824 * Minimum line is "A00000\n" which is 7-byte long,1825 * and the line length must be multiple of 5 plus 2.1826 */1827if((llen <7) || (llen-2) %5)1828goto corrupt;1829 max_byte_length = (llen -2) /5*4;1830 byte_length = *buffer;1831if('A'<= byte_length && byte_length <='Z')1832 byte_length = byte_length -'A'+1;1833else if('a'<= byte_length && byte_length <='z')1834 byte_length = byte_length -'a'+27;1835else1836goto corrupt;1837/* if the input length was not multiple of 4, we would1838 * have filler at the end but the filler should never1839 * exceed 3 bytes1840 */1841if(max_byte_length < byte_length ||1842 byte_length <= max_byte_length -4)1843goto corrupt;1844 newsize = hunk_size + byte_length;1845 data =xrealloc(data, newsize);1846if(decode_85(data + hunk_size, buffer +1, byte_length))1847goto corrupt;1848 hunk_size = newsize;1849 buffer += llen;1850 size -= llen;1851}18521853 frag =xcalloc(1,sizeof(*frag));1854 frag->patch =inflate_it(data, hunk_size, origlen);1855 frag->free_patch =1;1856if(!frag->patch)1857goto corrupt;1858free(data);1859 frag->size = origlen;1860*buf_p = buffer;1861*sz_p = size;1862*used_p = used;1863 frag->binary_patch_method = patch_method;1864return frag;18651866 corrupt:1867free(data);1868*status_p = -1;1869error(_("corrupt binary patch at line%d: %.*s"),1870 linenr-1, llen-1, buffer);1871return NULL;1872}18731874static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1875{1876/*1877 * We have read "GIT binary patch\n"; what follows is a line1878 * that says the patch method (currently, either "literal" or1879 * "delta") and the length of data before deflating; a1880 * sequence of 'length-byte' followed by base-85 encoded data1881 * follows.1882 *1883 * When a binary patch is reversible, there is another binary1884 * hunk in the same format, starting with patch method (either1885 * "literal" or "delta") with the length of data, and a sequence1886 * of length-byte + base-85 encoded data, terminated with another1887 * empty line. This data, when applied to the postimage, produces1888 * the preimage.1889 */1890struct fragment *forward;1891struct fragment *reverse;1892int status;1893int used, used_1;18941895 forward =parse_binary_hunk(&buffer, &size, &status, &used);1896if(!forward && !status)1897/* there has to be one hunk (forward hunk) */1898returnerror(_("unrecognized binary patch at line%d"), linenr-1);1899if(status)1900/* otherwise we already gave an error message */1901return status;19021903 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1904if(reverse)1905 used += used_1;1906else if(status) {1907/*1908 * Not having reverse hunk is not an error, but having1909 * a corrupt reverse hunk is.1910 */1911free((void*) forward->patch);1912free(forward);1913return status;1914}1915 forward->next = reverse;1916 patch->fragments = forward;1917 patch->is_binary =1;1918return used;1919}19201921/*1922 * Read the patch text in "buffer" taht extends for "size" bytes; stop1923 * reading after seeing a single patch (i.e. changes to a single file).1924 * Create fragments (i.e. patch hunks) and hang them to the given patch.1925 * Return the number of bytes consumed, so that the caller can call us1926 * again for the next patch.1927 */1928static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1929{1930int hdrsize, patchsize;1931int offset =find_header(buffer, size, &hdrsize, patch);19321933if(offset <0)1934return offset;19351936 patch->ws_rule =whitespace_rule(patch->new_name1937? patch->new_name1938: patch->old_name);19391940 patchsize =parse_single_patch(buffer + offset + hdrsize,1941 size - offset - hdrsize, patch);19421943if(!patchsize) {1944static const char*binhdr[] = {1945"Binary files ",1946"Files ",1947 NULL,1948};1949static const char git_binary[] ="GIT binary patch\n";1950int i;1951int hd = hdrsize + offset;1952unsigned long llen =linelen(buffer + hd, size - hd);19531954if(llen ==sizeof(git_binary) -1&&1955!memcmp(git_binary, buffer + hd, llen)) {1956int used;1957 linenr++;1958 used =parse_binary(buffer + hd + llen,1959 size - hd - llen, patch);1960if(used)1961 patchsize = used + llen;1962else1963 patchsize =0;1964}1965else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1966for(i =0; binhdr[i]; i++) {1967int len =strlen(binhdr[i]);1968if(len < size - hd &&1969!memcmp(binhdr[i], buffer + hd, len)) {1970 linenr++;1971 patch->is_binary =1;1972 patchsize = llen;1973break;1974}1975}1976}19771978/* Empty patch cannot be applied if it is a text patch1979 * without metadata change. A binary patch appears1980 * empty to us here.1981 */1982if((apply || check) &&1983(!patch->is_binary && !metadata_changes(patch)))1984die(_("patch with only garbage at line%d"), linenr);1985}19861987return offset + hdrsize + patchsize;1988}19891990#define swap(a,b) myswap((a),(b),sizeof(a))19911992#define myswap(a, b, size) do { \1993 unsigned char mytmp[size]; \1994 memcpy(mytmp, &a, size); \1995 memcpy(&a, &b, size); \1996 memcpy(&b, mytmp, size); \1997} while (0)19981999static voidreverse_patches(struct patch *p)2000{2001for(; p; p = p->next) {2002struct fragment *frag = p->fragments;20032004swap(p->new_name, p->old_name);2005swap(p->new_mode, p->old_mode);2006swap(p->is_new, p->is_delete);2007swap(p->lines_added, p->lines_deleted);2008swap(p->old_sha1_prefix, p->new_sha1_prefix);20092010for(; frag; frag = frag->next) {2011swap(frag->newpos, frag->oldpos);2012swap(frag->newlines, frag->oldlines);2013}2014}2015}20162017static const char pluses[] =2018"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2019static const char minuses[]=2020"----------------------------------------------------------------------";20212022static voidshow_stats(struct patch *patch)2023{2024struct strbuf qname = STRBUF_INIT;2025char*cp = patch->new_name ? patch->new_name : patch->old_name;2026int max, add, del;20272028quote_c_style(cp, &qname, NULL,0);20292030/*2031 * "scale" the filename2032 */2033 max = max_len;2034if(max >50)2035 max =50;20362037if(qname.len > max) {2038 cp =strchr(qname.buf + qname.len +3- max,'/');2039if(!cp)2040 cp = qname.buf + qname.len +3- max;2041strbuf_splice(&qname,0, cp - qname.buf,"...",3);2042}20432044if(patch->is_binary) {2045printf(" %-*s | Bin\n", max, qname.buf);2046strbuf_release(&qname);2047return;2048}20492050printf(" %-*s |", max, qname.buf);2051strbuf_release(&qname);20522053/*2054 * scale the add/delete2055 */2056 max = max + max_change >70?70- max : max_change;2057 add = patch->lines_added;2058 del = patch->lines_deleted;20592060if(max_change >0) {2061int total = ((add + del) * max + max_change /2) / max_change;2062 add = (add * max + max_change /2) / max_change;2063 del = total - add;2064}2065printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2066 add, pluses, del, minuses);2067}20682069static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2070{2071switch(st->st_mode & S_IFMT) {2072case S_IFLNK:2073if(strbuf_readlink(buf, path, st->st_size) <0)2074returnerror(_("unable to read symlink%s"), path);2075return0;2076case S_IFREG:2077if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2078returnerror(_("unable to open or read%s"), path);2079convert_to_git(path, buf->buf, buf->len, buf,0);2080return0;2081default:2082return-1;2083}2084}20852086/*2087 * Update the preimage, and the common lines in postimage,2088 * from buffer buf of length len. If postlen is 0 the postimage2089 * is updated in place, otherwise it's updated on a new buffer2090 * of length postlen2091 */20922093static voidupdate_pre_post_images(struct image *preimage,2094struct image *postimage,2095char*buf,2096size_t len,size_t postlen)2097{2098int i, ctx;2099char*new, *old, *fixed;2100struct image fixed_preimage;21012102/*2103 * Update the preimage with whitespace fixes. Note that we2104 * are not losing preimage->buf -- apply_one_fragment() will2105 * free "oldlines".2106 */2107prepare_image(&fixed_preimage, buf, len,1);2108assert(fixed_preimage.nr == preimage->nr);2109for(i =0; i < preimage->nr; i++)2110 fixed_preimage.line[i].flag = preimage->line[i].flag;2111free(preimage->line_allocated);2112*preimage = fixed_preimage;21132114/*2115 * Adjust the common context lines in postimage. This can be2116 * done in-place when we are just doing whitespace fixing,2117 * which does not make the string grow, but needs a new buffer2118 * when ignoring whitespace causes the update, since in this case2119 * we could have e.g. tabs converted to multiple spaces.2120 * We trust the caller to tell us if the update can be done2121 * in place (postlen==0) or not.2122 */2123 old = postimage->buf;2124if(postlen)2125new= postimage->buf =xmalloc(postlen);2126else2127new= old;2128 fixed = preimage->buf;2129for(i = ctx =0; i < postimage->nr; i++) {2130size_t len = postimage->line[i].len;2131if(!(postimage->line[i].flag & LINE_COMMON)) {2132/* an added line -- no counterparts in preimage */2133memmove(new, old, len);2134 old += len;2135new+= len;2136continue;2137}21382139/* a common context -- skip it in the original postimage */2140 old += len;21412142/* and find the corresponding one in the fixed preimage */2143while(ctx < preimage->nr &&2144!(preimage->line[ctx].flag & LINE_COMMON)) {2145 fixed += preimage->line[ctx].len;2146 ctx++;2147}2148if(preimage->nr <= ctx)2149die(_("oops"));21502151/* and copy it in, while fixing the line length */2152 len = preimage->line[ctx].len;2153memcpy(new, fixed, len);2154new+= len;2155 fixed += len;2156 postimage->line[i].len = len;2157 ctx++;2158}21592160/* Fix the length of the whole thing */2161 postimage->len =new- postimage->buf;2162}21632164static intmatch_fragment(struct image *img,2165struct image *preimage,2166struct image *postimage,2167unsigned longtry,2168int try_lno,2169unsigned ws_rule,2170int match_beginning,int match_end)2171{2172int i;2173char*fixed_buf, *buf, *orig, *target;2174struct strbuf fixed;2175size_t fixed_len;2176int preimage_limit;21772178if(preimage->nr + try_lno <= img->nr) {2179/*2180 * The hunk falls within the boundaries of img.2181 */2182 preimage_limit = preimage->nr;2183if(match_end && (preimage->nr + try_lno != img->nr))2184return0;2185}else if(ws_error_action == correct_ws_error &&2186(ws_rule & WS_BLANK_AT_EOF)) {2187/*2188 * This hunk extends beyond the end of img, and we are2189 * removing blank lines at the end of the file. This2190 * many lines from the beginning of the preimage must2191 * match with img, and the remainder of the preimage2192 * must be blank.2193 */2194 preimage_limit = img->nr - try_lno;2195}else{2196/*2197 * The hunk extends beyond the end of the img and2198 * we are not removing blanks at the end, so we2199 * should reject the hunk at this position.2200 */2201return0;2202}22032204if(match_beginning && try_lno)2205return0;22062207/* Quick hash check */2208for(i =0; i < preimage_limit; i++)2209if((img->line[try_lno + i].flag & LINE_PATCHED) ||2210(preimage->line[i].hash != img->line[try_lno + i].hash))2211return0;22122213if(preimage_limit == preimage->nr) {2214/*2215 * Do we have an exact match? If we were told to match2216 * at the end, size must be exactly at try+fragsize,2217 * otherwise try+fragsize must be still within the preimage,2218 * and either case, the old piece should match the preimage2219 * exactly.2220 */2221if((match_end2222? (try+ preimage->len == img->len)2223: (try+ preimage->len <= img->len)) &&2224!memcmp(img->buf +try, preimage->buf, preimage->len))2225return1;2226}else{2227/*2228 * The preimage extends beyond the end of img, so2229 * there cannot be an exact match.2230 *2231 * There must be one non-blank context line that match2232 * a line before the end of img.2233 */2234char*buf_end;22352236 buf = preimage->buf;2237 buf_end = buf;2238for(i =0; i < preimage_limit; i++)2239 buf_end += preimage->line[i].len;22402241for( ; buf < buf_end; buf++)2242if(!isspace(*buf))2243break;2244if(buf == buf_end)2245return0;2246}22472248/*2249 * No exact match. If we are ignoring whitespace, run a line-by-line2250 * fuzzy matching. We collect all the line length information because2251 * we need it to adjust whitespace if we match.2252 */2253if(ws_ignore_action == ignore_ws_change) {2254size_t imgoff =0;2255size_t preoff =0;2256size_t postlen = postimage->len;2257size_t extra_chars;2258char*preimage_eof;2259char*preimage_end;2260for(i =0; i < preimage_limit; i++) {2261size_t prelen = preimage->line[i].len;2262size_t imglen = img->line[try_lno+i].len;22632264if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2265 preimage->buf + preoff, prelen))2266return0;2267if(preimage->line[i].flag & LINE_COMMON)2268 postlen += imglen - prelen;2269 imgoff += imglen;2270 preoff += prelen;2271}22722273/*2274 * Ok, the preimage matches with whitespace fuzz.2275 *2276 * imgoff now holds the true length of the target that2277 * matches the preimage before the end of the file.2278 *2279 * Count the number of characters in the preimage that fall2280 * beyond the end of the file and make sure that all of them2281 * are whitespace characters. (This can only happen if2282 * we are removing blank lines at the end of the file.)2283 */2284 buf = preimage_eof = preimage->buf + preoff;2285for( ; i < preimage->nr; i++)2286 preoff += preimage->line[i].len;2287 preimage_end = preimage->buf + preoff;2288for( ; buf < preimage_end; buf++)2289if(!isspace(*buf))2290return0;22912292/*2293 * Update the preimage and the common postimage context2294 * lines to use the same whitespace as the target.2295 * If whitespace is missing in the target (i.e.2296 * if the preimage extends beyond the end of the file),2297 * use the whitespace from the preimage.2298 */2299 extra_chars = preimage_end - preimage_eof;2300strbuf_init(&fixed, imgoff + extra_chars);2301strbuf_add(&fixed, img->buf +try, imgoff);2302strbuf_add(&fixed, preimage_eof, extra_chars);2303 fixed_buf =strbuf_detach(&fixed, &fixed_len);2304update_pre_post_images(preimage, postimage,2305 fixed_buf, fixed_len, postlen);2306return1;2307}23082309if(ws_error_action != correct_ws_error)2310return0;23112312/*2313 * The hunk does not apply byte-by-byte, but the hash says2314 * it might with whitespace fuzz. We haven't been asked to2315 * ignore whitespace, we were asked to correct whitespace2316 * errors, so let's try matching after whitespace correction.2317 *2318 * The preimage may extend beyond the end of the file,2319 * but in this loop we will only handle the part of the2320 * preimage that falls within the file.2321 */2322strbuf_init(&fixed, preimage->len +1);2323 orig = preimage->buf;2324 target = img->buf +try;2325for(i =0; i < preimage_limit; i++) {2326size_t oldlen = preimage->line[i].len;2327size_t tgtlen = img->line[try_lno + i].len;2328size_t fixstart = fixed.len;2329struct strbuf tgtfix;2330int match;23312332/* Try fixing the line in the preimage */2333ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);23342335/* Try fixing the line in the target */2336strbuf_init(&tgtfix, tgtlen);2337ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);23382339/*2340 * If they match, either the preimage was based on2341 * a version before our tree fixed whitespace breakage,2342 * or we are lacking a whitespace-fix patch the tree2343 * the preimage was based on already had (i.e. target2344 * has whitespace breakage, the preimage doesn't).2345 * In either case, we are fixing the whitespace breakages2346 * so we might as well take the fix together with their2347 * real change.2348 */2349 match = (tgtfix.len == fixed.len - fixstart &&2350!memcmp(tgtfix.buf, fixed.buf + fixstart,2351 fixed.len - fixstart));23522353strbuf_release(&tgtfix);2354if(!match)2355goto unmatch_exit;23562357 orig += oldlen;2358 target += tgtlen;2359}236023612362/*2363 * Now handle the lines in the preimage that falls beyond the2364 * end of the file (if any). They will only match if they are2365 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2366 * false).2367 */2368for( ; i < preimage->nr; i++) {2369size_t fixstart = fixed.len;/* start of the fixed preimage */2370size_t oldlen = preimage->line[i].len;2371int j;23722373/* Try fixing the line in the preimage */2374ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);23752376for(j = fixstart; j < fixed.len; j++)2377if(!isspace(fixed.buf[j]))2378goto unmatch_exit;23792380 orig += oldlen;2381}23822383/*2384 * Yes, the preimage is based on an older version that still2385 * has whitespace breakages unfixed, and fixing them makes the2386 * hunk match. Update the context lines in the postimage.2387 */2388 fixed_buf =strbuf_detach(&fixed, &fixed_len);2389update_pre_post_images(preimage, postimage,2390 fixed_buf, fixed_len,0);2391return1;23922393 unmatch_exit:2394strbuf_release(&fixed);2395return0;2396}23972398static intfind_pos(struct image *img,2399struct image *preimage,2400struct image *postimage,2401int line,2402unsigned ws_rule,2403int match_beginning,int match_end)2404{2405int i;2406unsigned long backwards, forwards,try;2407int backwards_lno, forwards_lno, try_lno;24082409/*2410 * If match_beginning or match_end is specified, there is no2411 * point starting from a wrong line that will never match and2412 * wander around and wait for a match at the specified end.2413 */2414if(match_beginning)2415 line =0;2416else if(match_end)2417 line = img->nr - preimage->nr;24182419/*2420 * Because the comparison is unsigned, the following test2421 * will also take care of a negative line number that can2422 * result when match_end and preimage is larger than the target.2423 */2424if((size_t) line > img->nr)2425 line = img->nr;24262427try=0;2428for(i =0; i < line; i++)2429try+= img->line[i].len;24302431/*2432 * There's probably some smart way to do this, but I'll leave2433 * that to the smart and beautiful people. I'm simple and stupid.2434 */2435 backwards =try;2436 backwards_lno = line;2437 forwards =try;2438 forwards_lno = line;2439 try_lno = line;24402441for(i =0; ; i++) {2442if(match_fragment(img, preimage, postimage,2443try, try_lno, ws_rule,2444 match_beginning, match_end))2445return try_lno;24462447 again:2448if(backwards_lno ==0&& forwards_lno == img->nr)2449break;24502451if(i &1) {2452if(backwards_lno ==0) {2453 i++;2454goto again;2455}2456 backwards_lno--;2457 backwards -= img->line[backwards_lno].len;2458try= backwards;2459 try_lno = backwards_lno;2460}else{2461if(forwards_lno == img->nr) {2462 i++;2463goto again;2464}2465 forwards += img->line[forwards_lno].len;2466 forwards_lno++;2467try= forwards;2468 try_lno = forwards_lno;2469}24702471}2472return-1;2473}24742475static voidremove_first_line(struct image *img)2476{2477 img->buf += img->line[0].len;2478 img->len -= img->line[0].len;2479 img->line++;2480 img->nr--;2481}24822483static voidremove_last_line(struct image *img)2484{2485 img->len -= img->line[--img->nr].len;2486}24872488/*2489 * The change from "preimage" and "postimage" has been found to2490 * apply at applied_pos (counts in line numbers) in "img".2491 * Update "img" to remove "preimage" and replace it with "postimage".2492 */2493static voidupdate_image(struct image *img,2494int applied_pos,2495struct image *preimage,2496struct image *postimage)2497{2498/*2499 * remove the copy of preimage at offset in img2500 * and replace it with postimage2501 */2502int i, nr;2503size_t remove_count, insert_count, applied_at =0;2504char*result;2505int preimage_limit;25062507/*2508 * If we are removing blank lines at the end of img,2509 * the preimage may extend beyond the end.2510 * If that is the case, we must be careful only to2511 * remove the part of the preimage that falls within2512 * the boundaries of img. Initialize preimage_limit2513 * to the number of lines in the preimage that falls2514 * within the boundaries.2515 */2516 preimage_limit = preimage->nr;2517if(preimage_limit > img->nr - applied_pos)2518 preimage_limit = img->nr - applied_pos;25192520for(i =0; i < applied_pos; i++)2521 applied_at += img->line[i].len;25222523 remove_count =0;2524for(i =0; i < preimage_limit; i++)2525 remove_count += img->line[applied_pos + i].len;2526 insert_count = postimage->len;25272528/* Adjust the contents */2529 result =xmalloc(img->len + insert_count - remove_count +1);2530memcpy(result, img->buf, applied_at);2531memcpy(result + applied_at, postimage->buf, postimage->len);2532memcpy(result + applied_at + postimage->len,2533 img->buf + (applied_at + remove_count),2534 img->len - (applied_at + remove_count));2535free(img->buf);2536 img->buf = result;2537 img->len += insert_count - remove_count;2538 result[img->len] ='\0';25392540/* Adjust the line table */2541 nr = img->nr + postimage->nr - preimage_limit;2542if(preimage_limit < postimage->nr) {2543/*2544 * NOTE: this knows that we never call remove_first_line()2545 * on anything other than pre/post image.2546 */2547 img->line =xrealloc(img->line, nr *sizeof(*img->line));2548 img->line_allocated = img->line;2549}2550if(preimage_limit != postimage->nr)2551memmove(img->line + applied_pos + postimage->nr,2552 img->line + applied_pos + preimage_limit,2553(img->nr - (applied_pos + preimage_limit)) *2554sizeof(*img->line));2555memcpy(img->line + applied_pos,2556 postimage->line,2557 postimage->nr *sizeof(*img->line));2558if(!allow_overlap)2559for(i =0; i < postimage->nr; i++)2560 img->line[applied_pos + i].flag |= LINE_PATCHED;2561 img->nr = nr;2562}25632564/*2565 * Use the patch-hunk text in "frag" to prepare two images (preimage and2566 * postimage) for the hunk. Find lines that match "preimage" in "img" and2567 * replace the part of "img" with "postimage" text.2568 */2569static intapply_one_fragment(struct image *img,struct fragment *frag,2570int inaccurate_eof,unsigned ws_rule,2571int nth_fragment)2572{2573int match_beginning, match_end;2574const char*patch = frag->patch;2575int size = frag->size;2576char*old, *oldlines;2577struct strbuf newlines;2578int new_blank_lines_at_end =0;2579int found_new_blank_lines_at_end =0;2580int hunk_linenr = frag->linenr;2581unsigned long leading, trailing;2582int pos, applied_pos;2583struct image preimage;2584struct image postimage;25852586memset(&preimage,0,sizeof(preimage));2587memset(&postimage,0,sizeof(postimage));2588 oldlines =xmalloc(size);2589strbuf_init(&newlines, size);25902591 old = oldlines;2592while(size >0) {2593char first;2594int len =linelen(patch, size);2595int plen;2596int added_blank_line =0;2597int is_blank_context =0;2598size_t start;25992600if(!len)2601break;26022603/*2604 * "plen" is how much of the line we should use for2605 * the actual patch data. Normally we just remove the2606 * first character on the line, but if the line is2607 * followed by "\ No newline", then we also remove the2608 * last one (which is the newline, of course).2609 */2610 plen = len -1;2611if(len < size && patch[len] =='\\')2612 plen--;2613 first = *patch;2614if(apply_in_reverse) {2615if(first =='-')2616 first ='+';2617else if(first =='+')2618 first ='-';2619}26202621switch(first) {2622case'\n':2623/* Newer GNU diff, empty context line */2624if(plen <0)2625/* ... followed by '\No newline'; nothing */2626break;2627*old++ ='\n';2628strbuf_addch(&newlines,'\n');2629add_line_info(&preimage,"\n",1, LINE_COMMON);2630add_line_info(&postimage,"\n",1, LINE_COMMON);2631 is_blank_context =1;2632break;2633case' ':2634if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2635ws_blank_line(patch +1, plen, ws_rule))2636 is_blank_context =1;2637case'-':2638memcpy(old, patch +1, plen);2639add_line_info(&preimage, old, plen,2640(first ==' '? LINE_COMMON :0));2641 old += plen;2642if(first =='-')2643break;2644/* Fall-through for ' ' */2645case'+':2646/* --no-add does not add new lines */2647if(first =='+'&& no_add)2648break;26492650 start = newlines.len;2651if(first !='+'||2652!whitespace_error ||2653 ws_error_action != correct_ws_error) {2654strbuf_add(&newlines, patch +1, plen);2655}2656else{2657ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2658}2659add_line_info(&postimage, newlines.buf + start, newlines.len - start,2660(first =='+'?0: LINE_COMMON));2661if(first =='+'&&2662(ws_rule & WS_BLANK_AT_EOF) &&2663ws_blank_line(patch +1, plen, ws_rule))2664 added_blank_line =1;2665break;2666case'@':case'\\':2667/* Ignore it, we already handled it */2668break;2669default:2670if(apply_verbosely)2671error(_("invalid start of line: '%c'"), first);2672return-1;2673}2674if(added_blank_line) {2675if(!new_blank_lines_at_end)2676 found_new_blank_lines_at_end = hunk_linenr;2677 new_blank_lines_at_end++;2678}2679else if(is_blank_context)2680;2681else2682 new_blank_lines_at_end =0;2683 patch += len;2684 size -= len;2685 hunk_linenr++;2686}2687if(inaccurate_eof &&2688 old > oldlines && old[-1] =='\n'&&2689 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2690 old--;2691strbuf_setlen(&newlines, newlines.len -1);2692}26932694 leading = frag->leading;2695 trailing = frag->trailing;26962697/*2698 * A hunk to change lines at the beginning would begin with2699 * @@ -1,L +N,M @@2700 * but we need to be careful. -U0 that inserts before the second2701 * line also has this pattern.2702 *2703 * And a hunk to add to an empty file would begin with2704 * @@ -0,0 +N,M @@2705 *2706 * In other words, a hunk that is (frag->oldpos <= 1) with or2707 * without leading context must match at the beginning.2708 */2709 match_beginning = (!frag->oldpos ||2710(frag->oldpos ==1&& !unidiff_zero));27112712/*2713 * A hunk without trailing lines must match at the end.2714 * However, we simply cannot tell if a hunk must match end2715 * from the lack of trailing lines if the patch was generated2716 * with unidiff without any context.2717 */2718 match_end = !unidiff_zero && !trailing;27192720 pos = frag->newpos ? (frag->newpos -1) :0;2721 preimage.buf = oldlines;2722 preimage.len = old - oldlines;2723 postimage.buf = newlines.buf;2724 postimage.len = newlines.len;2725 preimage.line = preimage.line_allocated;2726 postimage.line = postimage.line_allocated;27272728for(;;) {27292730 applied_pos =find_pos(img, &preimage, &postimage, pos,2731 ws_rule, match_beginning, match_end);27322733if(applied_pos >=0)2734break;27352736/* Am I at my context limits? */2737if((leading <= p_context) && (trailing <= p_context))2738break;2739if(match_beginning || match_end) {2740 match_beginning = match_end =0;2741continue;2742}27432744/*2745 * Reduce the number of context lines; reduce both2746 * leading and trailing if they are equal otherwise2747 * just reduce the larger context.2748 */2749if(leading >= trailing) {2750remove_first_line(&preimage);2751remove_first_line(&postimage);2752 pos--;2753 leading--;2754}2755if(trailing > leading) {2756remove_last_line(&preimage);2757remove_last_line(&postimage);2758 trailing--;2759}2760}27612762if(applied_pos >=0) {2763if(new_blank_lines_at_end &&2764 preimage.nr + applied_pos >= img->nr &&2765(ws_rule & WS_BLANK_AT_EOF) &&2766 ws_error_action != nowarn_ws_error) {2767record_ws_error(WS_BLANK_AT_EOF,"+",1,2768 found_new_blank_lines_at_end);2769if(ws_error_action == correct_ws_error) {2770while(new_blank_lines_at_end--)2771remove_last_line(&postimage);2772}2773/*2774 * We would want to prevent write_out_results()2775 * from taking place in apply_patch() that follows2776 * the callchain led us here, which is:2777 * apply_patch->check_patch_list->check_patch->2778 * apply_data->apply_fragments->apply_one_fragment2779 */2780if(ws_error_action == die_on_ws_error)2781 apply =0;2782}27832784if(apply_verbosely && applied_pos != pos) {2785int offset = applied_pos - pos;2786if(apply_in_reverse)2787 offset =0- offset;2788fprintf_ln(stderr,2789Q_("Hunk #%dsucceeded at%d(offset%dline).",2790"Hunk #%dsucceeded at%d(offset%dlines).",2791 offset),2792 nth_fragment, applied_pos +1, offset);2793}27942795/*2796 * Warn if it was necessary to reduce the number2797 * of context lines.2798 */2799if((leading != frag->leading) ||2800(trailing != frag->trailing))2801fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2802" to apply fragment at%d"),2803 leading, trailing, applied_pos+1);2804update_image(img, applied_pos, &preimage, &postimage);2805}else{2806if(apply_verbosely)2807error(_("while searching for:\n%.*s"),2808(int)(old - oldlines), oldlines);2809}28102811free(oldlines);2812strbuf_release(&newlines);2813free(preimage.line_allocated);2814free(postimage.line_allocated);28152816return(applied_pos <0);2817}28182819static intapply_binary_fragment(struct image *img,struct patch *patch)2820{2821struct fragment *fragment = patch->fragments;2822unsigned long len;2823void*dst;28242825if(!fragment)2826returnerror(_("missing binary patch data for '%s'"),2827 patch->new_name ?2828 patch->new_name :2829 patch->old_name);28302831/* Binary patch is irreversible without the optional second hunk */2832if(apply_in_reverse) {2833if(!fragment->next)2834returnerror("cannot reverse-apply a binary patch "2835"without the reverse hunk to '%s'",2836 patch->new_name2837? patch->new_name : patch->old_name);2838 fragment = fragment->next;2839}2840switch(fragment->binary_patch_method) {2841case BINARY_DELTA_DEFLATED:2842 dst =patch_delta(img->buf, img->len, fragment->patch,2843 fragment->size, &len);2844if(!dst)2845return-1;2846clear_image(img);2847 img->buf = dst;2848 img->len = len;2849return0;2850case BINARY_LITERAL_DEFLATED:2851clear_image(img);2852 img->len = fragment->size;2853 img->buf =xmalloc(img->len+1);2854memcpy(img->buf, fragment->patch, img->len);2855 img->buf[img->len] ='\0';2856return0;2857}2858return-1;2859}28602861/*2862 * Replace "img" with the result of applying the binary patch.2863 * The binary patch data itself in patch->fragment is still kept2864 * but the preimage prepared by the caller in "img" is freed here2865 * or in the helper function apply_binary_fragment() this calls.2866 */2867static intapply_binary(struct image *img,struct patch *patch)2868{2869const char*name = patch->old_name ? patch->old_name : patch->new_name;2870unsigned char sha1[20];28712872/*2873 * For safety, we require patch index line to contain2874 * full 40-byte textual SHA1 for old and new, at least for now.2875 */2876if(strlen(patch->old_sha1_prefix) !=40||2877strlen(patch->new_sha1_prefix) !=40||2878get_sha1_hex(patch->old_sha1_prefix, sha1) ||2879get_sha1_hex(patch->new_sha1_prefix, sha1))2880returnerror("cannot apply binary patch to '%s' "2881"without full index line", name);28822883if(patch->old_name) {2884/*2885 * See if the old one matches what the patch2886 * applies to.2887 */2888hash_sha1_file(img->buf, img->len, blob_type, sha1);2889if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2890returnerror("the patch applies to '%s' (%s), "2891"which does not match the "2892"current contents.",2893 name,sha1_to_hex(sha1));2894}2895else{2896/* Otherwise, the old one must be empty. */2897if(img->len)2898returnerror("the patch applies to an empty "2899"'%s' but it is not empty", name);2900}29012902get_sha1_hex(patch->new_sha1_prefix, sha1);2903if(is_null_sha1(sha1)) {2904clear_image(img);2905return0;/* deletion patch */2906}29072908if(has_sha1_file(sha1)) {2909/* We already have the postimage */2910enum object_type type;2911unsigned long size;2912char*result;29132914 result =read_sha1_file(sha1, &type, &size);2915if(!result)2916returnerror("the necessary postimage%sfor "2917"'%s' cannot be read",2918 patch->new_sha1_prefix, name);2919clear_image(img);2920 img->buf = result;2921 img->len = size;2922}else{2923/*2924 * We have verified buf matches the preimage;2925 * apply the patch data to it, which is stored2926 * in the patch->fragments->{patch,size}.2927 */2928if(apply_binary_fragment(img, patch))2929returnerror(_("binary patch does not apply to '%s'"),2930 name);29312932/* verify that the result matches */2933hash_sha1_file(img->buf, img->len, blob_type, sha1);2934if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2935returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),2936 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2937}29382939return0;2940}29412942static intapply_fragments(struct image *img,struct patch *patch)2943{2944struct fragment *frag = patch->fragments;2945const char*name = patch->old_name ? patch->old_name : patch->new_name;2946unsigned ws_rule = patch->ws_rule;2947unsigned inaccurate_eof = patch->inaccurate_eof;2948int nth =0;29492950if(patch->is_binary)2951returnapply_binary(img, patch);29522953while(frag) {2954 nth++;2955if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {2956error(_("patch failed:%s:%ld"), name, frag->oldpos);2957if(!apply_with_reject)2958return-1;2959 frag->rejected =1;2960}2961 frag = frag->next;2962}2963return0;2964}29652966static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)2967{2968if(S_ISGITLINK(mode)) {2969strbuf_grow(buf,100);2970strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));2971}else{2972enum object_type type;2973unsigned long sz;2974char*result;29752976 result =read_sha1_file(sha1, &type, &sz);2977if(!result)2978return-1;2979/* XXX read_sha1_file NUL-terminates */2980strbuf_attach(buf, result, sz, sz +1);2981}2982return0;2983}29842985static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2986{2987if(!ce)2988return0;2989returnread_blob_object(buf, ce->sha1, ce->ce_mode);2990}29912992static struct patch *in_fn_table(const char*name)2993{2994struct string_list_item *item;29952996if(name == NULL)2997return NULL;29982999 item =string_list_lookup(&fn_table, name);3000if(item != NULL)3001return(struct patch *)item->util;30023003return NULL;3004}30053006/*3007 * item->util in the filename table records the status of the path.3008 * Usually it points at a patch (whose result records the contents3009 * of it after applying it), but it could be PATH_WAS_DELETED for a3010 * path that a previously applied patch has already removed, or3011 * PATH_TO_BE_DELETED for a path that a later patch would remove.3012 *3013 * The latter is needed to deal with a case where two paths A and B3014 * are swapped by first renaming A to B and then renaming B to A;3015 * moving A to B should not be prevented due to presense of B as we3016 * will remove it in a later patch.3017 */3018#define PATH_TO_BE_DELETED ((struct patch *) -2)3019#define PATH_WAS_DELETED ((struct patch *) -1)30203021static intto_be_deleted(struct patch *patch)3022{3023return patch == PATH_TO_BE_DELETED;3024}30253026static intwas_deleted(struct patch *patch)3027{3028return patch == PATH_WAS_DELETED;3029}30303031static voidadd_to_fn_table(struct patch *patch)3032{3033struct string_list_item *item;30343035/*3036 * Always add new_name unless patch is a deletion3037 * This should cover the cases for normal diffs,3038 * file creations and copies3039 */3040if(patch->new_name != NULL) {3041 item =string_list_insert(&fn_table, patch->new_name);3042 item->util = patch;3043}30443045/*3046 * store a failure on rename/deletion cases because3047 * later chunks shouldn't patch old names3048 */3049if((patch->new_name == NULL) || (patch->is_rename)) {3050 item =string_list_insert(&fn_table, patch->old_name);3051 item->util = PATH_WAS_DELETED;3052}3053}30543055static voidprepare_fn_table(struct patch *patch)3056{3057/*3058 * store information about incoming file deletion3059 */3060while(patch) {3061if((patch->new_name == NULL) || (patch->is_rename)) {3062struct string_list_item *item;3063 item =string_list_insert(&fn_table, patch->old_name);3064 item->util = PATH_TO_BE_DELETED;3065}3066 patch = patch->next;3067}3068}30693070static intcheckout_target(struct cache_entry *ce,struct stat *st)3071{3072struct checkout costate;30733074memset(&costate,0,sizeof(costate));3075 costate.base_dir ="";3076 costate.refresh_cache =1;3077if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3078returnerror(_("cannot checkout%s"), ce->name);3079return0;3080}30813082static struct patch *previous_patch(struct patch *patch,int*gone)3083{3084struct patch *previous;30853086*gone =0;3087if(patch->is_copy || patch->is_rename)3088return NULL;/* "git" patches do not depend on the order */30893090 previous =in_fn_table(patch->old_name);3091if(!previous)3092return NULL;30933094if(to_be_deleted(previous))3095return NULL;/* the deletion hasn't happened yet */30963097if(was_deleted(previous))3098*gone =1;30993100return previous;3101}31023103static intverify_index_match(struct cache_entry *ce,struct stat *st)3104{3105if(S_ISGITLINK(ce->ce_mode)) {3106if(!S_ISDIR(st->st_mode))3107return-1;3108return0;3109}3110returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3111}31123113#define SUBMODULE_PATCH_WITHOUT_INDEX 131143115static intload_patch_target(struct strbuf *buf,3116struct cache_entry *ce,3117struct stat *st,3118const char*name,3119unsigned expected_mode)3120{3121if(cached) {3122if(read_file_or_gitlink(ce, buf))3123returnerror(_("read of%sfailed"), name);3124}else if(name) {3125if(S_ISGITLINK(expected_mode)) {3126if(ce)3127returnread_file_or_gitlink(ce, buf);3128else3129return SUBMODULE_PATCH_WITHOUT_INDEX;3130}else{3131if(read_old_data(st, name, buf))3132returnerror(_("read of%sfailed"), name);3133}3134}3135return0;3136}31373138/*3139 * We are about to apply "patch"; populate the "image" with the3140 * current version we have, from the working tree or from the index,3141 * depending on the situation e.g. --cached/--index. If we are3142 * applying a non-git patch that incrementally updates the tree,3143 * we read from the result of a previous diff.3144 */3145static intload_preimage(struct image *image,3146struct patch *patch,struct stat *st,struct cache_entry *ce)3147{3148struct strbuf buf = STRBUF_INIT;3149size_t len;3150char*img;3151struct patch *previous;3152int status;31533154 previous =previous_patch(patch, &status);3155if(status)3156returnerror(_("path%shas been renamed/deleted"),3157 patch->old_name);3158if(previous) {3159/* We have a patched copy in memory; use that. */3160strbuf_add(&buf, previous->result, previous->resultsize);3161}else{3162 status =load_patch_target(&buf, ce, st,3163 patch->old_name, patch->old_mode);3164if(status <0)3165return status;3166else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3167/*3168 * There is no way to apply subproject3169 * patch without looking at the index.3170 * NEEDSWORK: shouldn't this be flagged3171 * as an error???3172 */3173free_fragment_list(patch->fragments);3174 patch->fragments = NULL;3175}else if(status) {3176returnerror(_("read of%sfailed"), patch->old_name);3177}3178}31793180 img =strbuf_detach(&buf, &len);3181prepare_image(image, img, len, !patch->is_binary);3182return0;3183}31843185static intthree_way_merge(struct image *image,3186char*path,3187const unsigned char*base,3188const unsigned char*ours,3189const unsigned char*theirs)3190{3191 mmfile_t base_file, our_file, their_file;3192 mmbuffer_t result = { NULL };3193int status;31943195read_mmblob(&base_file, base);3196read_mmblob(&our_file, ours);3197read_mmblob(&their_file, theirs);3198 status =ll_merge(&result, path,3199&base_file,"base",3200&our_file,"ours",3201&their_file,"theirs", NULL);3202free(base_file.ptr);3203free(our_file.ptr);3204free(their_file.ptr);3205if(status <0|| !result.ptr) {3206free(result.ptr);3207return-1;3208}3209clear_image(image);3210 image->buf = result.ptr;3211 image->len = result.size;32123213return status;3214}32153216/*3217 * When directly falling back to add/add three-way merge, we read from3218 * the current contents of the new_name. In no cases other than that3219 * this function will be called.3220 */3221static intload_current(struct image *image,struct patch *patch)3222{3223struct strbuf buf = STRBUF_INIT;3224int status, pos;3225size_t len;3226char*img;3227struct stat st;3228struct cache_entry *ce;3229char*name = patch->new_name;3230unsigned mode = patch->new_mode;32313232if(!patch->is_new)3233die("BUG: patch to%sis not a creation", patch->old_name);32343235 pos =cache_name_pos(name,strlen(name));3236if(pos <0)3237returnerror(_("%s: does not exist in index"), name);3238 ce = active_cache[pos];3239if(lstat(name, &st)) {3240if(errno != ENOENT)3241returnerror(_("%s:%s"), name,strerror(errno));3242if(checkout_target(ce, &st))3243return-1;3244}3245if(verify_index_match(ce, &st))3246returnerror(_("%s: does not match index"), name);32473248 status =load_patch_target(&buf, ce, &st, name, mode);3249if(status <0)3250return status;3251else if(status)3252return-1;3253 img =strbuf_detach(&buf, &len);3254prepare_image(image, img, len, !patch->is_binary);3255return0;3256}32573258static inttry_threeway(struct image *image,struct patch *patch,3259struct stat *st,struct cache_entry *ce)3260{3261unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3262struct strbuf buf = STRBUF_INIT;3263size_t len;3264int status;3265char*img;3266struct image tmp_image;32673268/* No point falling back to 3-way merge in these cases */3269if(patch->is_delete ||3270S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3271return-1;32723273/* Preimage the patch was prepared for */3274if(patch->is_new)3275write_sha1_file("",0, blob_type, pre_sha1);3276else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3277read_blob_object(&buf, pre_sha1, patch->old_mode))3278returnerror("repository lacks the necessary blob to fall back on 3-way merge.");32793280fprintf(stderr,"Falling back to three-way merge...\n");32813282 img =strbuf_detach(&buf, &len);3283prepare_image(&tmp_image, img, len,1);3284/* Apply the patch to get the post image */3285if(apply_fragments(&tmp_image, patch) <0) {3286clear_image(&tmp_image);3287return-1;3288}3289/* post_sha1[] is theirs */3290write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3291clear_image(&tmp_image);32923293/* our_sha1[] is ours */3294if(patch->is_new) {3295if(load_current(&tmp_image, patch))3296returnerror("cannot read the current contents of '%s'",3297 patch->new_name);3298}else{3299if(load_preimage(&tmp_image, patch, st, ce))3300returnerror("cannot read the current contents of '%s'",3301 patch->old_name);3302}3303write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3304clear_image(&tmp_image);33053306/* in-core three-way merge between post and our using pre as base */3307 status =three_way_merge(image, patch->new_name,3308 pre_sha1, our_sha1, post_sha1);3309if(status <0) {3310fprintf(stderr,"Failed to fall back on three-way merge...\n");3311return status;3312}33133314if(status) {3315 patch->conflicted_threeway =1;3316if(patch->is_new)3317hashclr(patch->threeway_stage[0]);3318else3319hashcpy(patch->threeway_stage[0], pre_sha1);3320hashcpy(patch->threeway_stage[1], our_sha1);3321hashcpy(patch->threeway_stage[2], post_sha1);3322fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3323}else{3324fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3325}3326return0;3327}33283329static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)3330{3331struct image image;33323333if(load_preimage(&image, patch, st, ce) <0)3334return-1;33353336if(patch->direct_to_threeway ||3337apply_fragments(&image, patch) <0) {3338/* Note: with --reject, apply_fragments() returns 0 */3339if(!threeway ||try_threeway(&image, patch, st, ce) <0)3340return-1;3341}3342 patch->result = image.buf;3343 patch->resultsize = image.len;3344add_to_fn_table(patch);3345free(image.line_allocated);33463347if(0< patch->is_delete && patch->resultsize)3348returnerror(_("removal patch leaves file contents"));33493350return0;3351}33523353/*3354 * If "patch" that we are looking at modifies or deletes what we have,3355 * we would want it not to lose any local modification we have, either3356 * in the working tree or in the index.3357 *3358 * This also decides if a non-git patch is a creation patch or a3359 * modification to an existing empty file. We do not check the state3360 * of the current tree for a creation patch in this function; the caller3361 * check_patch() separately makes sure (and errors out otherwise) that3362 * the path the patch creates does not exist in the current tree.3363 */3364static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)3365{3366const char*old_name = patch->old_name;3367struct patch *previous = NULL;3368int stat_ret =0, status;3369unsigned st_mode =0;33703371if(!old_name)3372return0;33733374assert(patch->is_new <=0);3375 previous =previous_patch(patch, &status);33763377if(status)3378returnerror(_("path%shas been renamed/deleted"), old_name);3379if(previous) {3380 st_mode = previous->new_mode;3381}else if(!cached) {3382 stat_ret =lstat(old_name, st);3383if(stat_ret && errno != ENOENT)3384returnerror(_("%s:%s"), old_name,strerror(errno));3385}33863387if(check_index && !previous) {3388int pos =cache_name_pos(old_name,strlen(old_name));3389if(pos <0) {3390if(patch->is_new <0)3391goto is_new;3392returnerror(_("%s: does not exist in index"), old_name);3393}3394*ce = active_cache[pos];3395if(stat_ret <0) {3396if(checkout_target(*ce, st))3397return-1;3398}3399if(!cached &&verify_index_match(*ce, st))3400returnerror(_("%s: does not match index"), old_name);3401if(cached)3402 st_mode = (*ce)->ce_mode;3403}else if(stat_ret <0) {3404if(patch->is_new <0)3405goto is_new;3406returnerror(_("%s:%s"), old_name,strerror(errno));3407}34083409if(!cached && !previous)3410 st_mode =ce_mode_from_stat(*ce, st->st_mode);34113412if(patch->is_new <0)3413 patch->is_new =0;3414if(!patch->old_mode)3415 patch->old_mode = st_mode;3416if((st_mode ^ patch->old_mode) & S_IFMT)3417returnerror(_("%s: wrong type"), old_name);3418if(st_mode != patch->old_mode)3419warning(_("%shas type%o, expected%o"),3420 old_name, st_mode, patch->old_mode);3421if(!patch->new_mode && !patch->is_delete)3422 patch->new_mode = st_mode;3423return0;34243425 is_new:3426 patch->is_new =1;3427 patch->is_delete =0;3428free(patch->old_name);3429 patch->old_name = NULL;3430return0;3431}343234333434#define EXISTS_IN_INDEX 13435#define EXISTS_IN_WORKTREE 234363437static intcheck_to_create(const char*new_name,int ok_if_exists)3438{3439struct stat nst;34403441if(check_index &&3442cache_name_pos(new_name,strlen(new_name)) >=0&&3443!ok_if_exists)3444return EXISTS_IN_INDEX;3445if(cached)3446return0;34473448if(!lstat(new_name, &nst)) {3449if(S_ISDIR(nst.st_mode) || ok_if_exists)3450return0;3451/*3452 * A leading component of new_name might be a symlink3453 * that is going to be removed with this patch, but3454 * still pointing at somewhere that has the path.3455 * In such a case, path "new_name" does not exist as3456 * far as git is concerned.3457 */3458if(has_symlink_leading_path(new_name,strlen(new_name)))3459return0;34603461return EXISTS_IN_WORKTREE;3462}else if((errno != ENOENT) && (errno != ENOTDIR)) {3463returnerror("%s:%s", new_name,strerror(errno));3464}3465return0;3466}34673468/*3469 * Check and apply the patch in-core; leave the result in patch->result3470 * for the caller to write it out to the final destination.3471 */3472static intcheck_patch(struct patch *patch)3473{3474struct stat st;3475const char*old_name = patch->old_name;3476const char*new_name = patch->new_name;3477const char*name = old_name ? old_name : new_name;3478struct cache_entry *ce = NULL;3479struct patch *tpatch;3480int ok_if_exists;3481int status;34823483 patch->rejected =1;/* we will drop this after we succeed */34843485 status =check_preimage(patch, &ce, &st);3486if(status)3487return status;3488 old_name = patch->old_name;34893490/*3491 * A type-change diff is always split into a patch to delete3492 * old, immediately followed by a patch to create new (see3493 * diff.c::run_diff()); in such a case it is Ok that the entry3494 * to be deleted by the previous patch is still in the working3495 * tree and in the index.3496 *3497 * A patch to swap-rename between A and B would first rename A3498 * to B and then rename B to A. While applying the first one,3499 * the presense of B should not stop A from getting renamed to3500 * B; ask to_be_deleted() about the later rename. Removal of3501 * B and rename from A to B is handled the same way by asking3502 * was_deleted().3503 */3504if((tpatch =in_fn_table(new_name)) &&3505(was_deleted(tpatch) ||to_be_deleted(tpatch)))3506 ok_if_exists =1;3507else3508 ok_if_exists =0;35093510if(new_name &&3511((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {3512int err =check_to_create(new_name, ok_if_exists);35133514if(err && threeway) {3515 patch->direct_to_threeway =1;3516}else switch(err) {3517case0:3518break;/* happy */3519case EXISTS_IN_INDEX:3520returnerror(_("%s: already exists in index"), new_name);3521break;3522case EXISTS_IN_WORKTREE:3523returnerror(_("%s: already exists in working directory"),3524 new_name);3525default:3526return err;3527}35283529if(!patch->new_mode) {3530if(0< patch->is_new)3531 patch->new_mode = S_IFREG |0644;3532else3533 patch->new_mode = patch->old_mode;3534}3535}35363537if(new_name && old_name) {3538int same = !strcmp(old_name, new_name);3539if(!patch->new_mode)3540 patch->new_mode = patch->old_mode;3541if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3542if(same)3543returnerror(_("new mode (%o) of%sdoes not "3544"match old mode (%o)"),3545 patch->new_mode, new_name,3546 patch->old_mode);3547else3548returnerror(_("new mode (%o) of%sdoes not "3549"match old mode (%o) of%s"),3550 patch->new_mode, new_name,3551 patch->old_mode, old_name);3552}3553}35543555if(apply_data(patch, &st, ce) <0)3556returnerror(_("%s: patch does not apply"), name);3557 patch->rejected =0;3558return0;3559}35603561static intcheck_patch_list(struct patch *patch)3562{3563int err =0;35643565prepare_fn_table(patch);3566while(patch) {3567if(apply_verbosely)3568say_patch_name(stderr,3569_("Checking patch%s..."), patch);3570 err |=check_patch(patch);3571 patch = patch->next;3572}3573return err;3574}35753576/* This function tries to read the sha1 from the current index */3577static intget_current_sha1(const char*path,unsigned char*sha1)3578{3579int pos;35803581if(read_cache() <0)3582return-1;3583 pos =cache_name_pos(path,strlen(path));3584if(pos <0)3585return-1;3586hashcpy(sha1, active_cache[pos]->sha1);3587return0;3588}35893590/* Build an index that contains the just the files needed for a 3way merge */3591static voidbuild_fake_ancestor(struct patch *list,const char*filename)3592{3593struct patch *patch;3594struct index_state result = { NULL };3595int fd;35963597/* Once we start supporting the reverse patch, it may be3598 * worth showing the new sha1 prefix, but until then...3599 */3600for(patch = list; patch; patch = patch->next) {3601const unsigned char*sha1_ptr;3602unsigned char sha1[20];3603struct cache_entry *ce;3604const char*name;36053606 name = patch->old_name ? patch->old_name : patch->new_name;3607if(0< patch->is_new)3608continue;3609else if(get_sha1_blob(patch->old_sha1_prefix, sha1))3610/* git diff has no index line for mode/type changes */3611if(!patch->lines_added && !patch->lines_deleted) {3612if(get_current_sha1(patch->old_name, sha1))3613die("mode change for%s, which is not "3614"in current HEAD", name);3615 sha1_ptr = sha1;3616}else3617die("sha1 information is lacking or useless "3618"(%s).", name);3619else3620 sha1_ptr = sha1;36213622 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);3623if(!ce)3624die(_("make_cache_entry failed for path '%s'"), name);3625if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3626die("Could not add%sto temporary index", name);3627}36283629 fd =open(filename, O_WRONLY | O_CREAT,0666);3630if(fd <0||write_index(&result, fd) ||close(fd))3631die("Could not write temporary index to%s", filename);36323633discard_index(&result);3634}36353636static voidstat_patch_list(struct patch *patch)3637{3638int files, adds, dels;36393640for(files = adds = dels =0; patch ; patch = patch->next) {3641 files++;3642 adds += patch->lines_added;3643 dels += patch->lines_deleted;3644show_stats(patch);3645}36463647print_stat_summary(stdout, files, adds, dels);3648}36493650static voidnumstat_patch_list(struct patch *patch)3651{3652for( ; patch; patch = patch->next) {3653const char*name;3654 name = patch->new_name ? patch->new_name : patch->old_name;3655if(patch->is_binary)3656printf("-\t-\t");3657else3658printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3659write_name_quoted(name, stdout, line_termination);3660}3661}36623663static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3664{3665if(mode)3666printf("%smode%06o%s\n", newdelete, mode, name);3667else3668printf("%s %s\n", newdelete, name);3669}36703671static voidshow_mode_change(struct patch *p,int show_name)3672{3673if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3674if(show_name)3675printf(" mode change%06o =>%06o%s\n",3676 p->old_mode, p->new_mode, p->new_name);3677else3678printf(" mode change%06o =>%06o\n",3679 p->old_mode, p->new_mode);3680}3681}36823683static voidshow_rename_copy(struct patch *p)3684{3685const char*renamecopy = p->is_rename ?"rename":"copy";3686const char*old, *new;36873688/* Find common prefix */3689 old = p->old_name;3690new= p->new_name;3691while(1) {3692const char*slash_old, *slash_new;3693 slash_old =strchr(old,'/');3694 slash_new =strchr(new,'/');3695if(!slash_old ||3696!slash_new ||3697 slash_old - old != slash_new -new||3698memcmp(old,new, slash_new -new))3699break;3700 old = slash_old +1;3701new= slash_new +1;3702}3703/* p->old_name thru old is the common prefix, and old and new3704 * through the end of names are renames3705 */3706if(old != p->old_name)3707printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,3708(int)(old - p->old_name), p->old_name,3709 old,new, p->score);3710else3711printf("%s %s=>%s(%d%%)\n", renamecopy,3712 p->old_name, p->new_name, p->score);3713show_mode_change(p,0);3714}37153716static voidsummary_patch_list(struct patch *patch)3717{3718struct patch *p;37193720for(p = patch; p; p = p->next) {3721if(p->is_new)3722show_file_mode_name("create", p->new_mode, p->new_name);3723else if(p->is_delete)3724show_file_mode_name("delete", p->old_mode, p->old_name);3725else{3726if(p->is_rename || p->is_copy)3727show_rename_copy(p);3728else{3729if(p->score) {3730printf(" rewrite%s(%d%%)\n",3731 p->new_name, p->score);3732show_mode_change(p,0);3733}3734else3735show_mode_change(p,1);3736}3737}3738}3739}37403741static voidpatch_stats(struct patch *patch)3742{3743int lines = patch->lines_added + patch->lines_deleted;37443745if(lines > max_change)3746 max_change = lines;3747if(patch->old_name) {3748int len =quote_c_style(patch->old_name, NULL, NULL,0);3749if(!len)3750 len =strlen(patch->old_name);3751if(len > max_len)3752 max_len = len;3753}3754if(patch->new_name) {3755int len =quote_c_style(patch->new_name, NULL, NULL,0);3756if(!len)3757 len =strlen(patch->new_name);3758if(len > max_len)3759 max_len = len;3760}3761}37623763static voidremove_file(struct patch *patch,int rmdir_empty)3764{3765if(update_index) {3766if(remove_file_from_cache(patch->old_name) <0)3767die(_("unable to remove%sfrom index"), patch->old_name);3768}3769if(!cached) {3770if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {3771remove_path(patch->old_name);3772}3773}3774}37753776static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)3777{3778struct stat st;3779struct cache_entry *ce;3780int namelen =strlen(path);3781unsigned ce_size =cache_entry_size(namelen);37823783if(!update_index)3784return;37853786 ce =xcalloc(1, ce_size);3787memcpy(ce->name, path, namelen);3788 ce->ce_mode =create_ce_mode(mode);3789 ce->ce_flags =create_ce_flags(0);3790 ce->ce_namelen = namelen;3791if(S_ISGITLINK(mode)) {3792const char*s = buf;37933794if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))3795die(_("corrupt patch for subproject%s"), path);3796}else{3797if(!cached) {3798if(lstat(path, &st) <0)3799die_errno(_("unable to stat newly created file '%s'"),3800 path);3801fill_stat_cache_info(ce, &st);3802}3803if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)3804die(_("unable to create backing store for newly created file%s"), path);3805}3806if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3807die(_("unable to add cache entry for%s"), path);3808}38093810static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)3811{3812int fd;3813struct strbuf nbuf = STRBUF_INIT;38143815if(S_ISGITLINK(mode)) {3816struct stat st;3817if(!lstat(path, &st) &&S_ISDIR(st.st_mode))3818return0;3819returnmkdir(path,0777);3820}38213822if(has_symlinks &&S_ISLNK(mode))3823/* Although buf:size is counted string, it also is NUL3824 * terminated.3825 */3826returnsymlink(buf, path);38273828 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);3829if(fd <0)3830return-1;38313832if(convert_to_working_tree(path, buf, size, &nbuf)) {3833 size = nbuf.len;3834 buf = nbuf.buf;3835}3836write_or_die(fd, buf, size);3837strbuf_release(&nbuf);38383839if(close(fd) <0)3840die_errno(_("closing file '%s'"), path);3841return0;3842}38433844/*3845 * We optimistically assume that the directories exist,3846 * which is true 99% of the time anyway. If they don't,3847 * we create them and try again.3848 */3849static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)3850{3851if(cached)3852return;3853if(!try_create_file(path, mode, buf, size))3854return;38553856if(errno == ENOENT) {3857if(safe_create_leading_directories(path))3858return;3859if(!try_create_file(path, mode, buf, size))3860return;3861}38623863if(errno == EEXIST || errno == EACCES) {3864/* We may be trying to create a file where a directory3865 * used to be.3866 */3867struct stat st;3868if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))3869 errno = EEXIST;3870}38713872if(errno == EEXIST) {3873unsigned int nr =getpid();38743875for(;;) {3876char newpath[PATH_MAX];3877mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);3878if(!try_create_file(newpath, mode, buf, size)) {3879if(!rename(newpath, path))3880return;3881unlink_or_warn(newpath);3882break;3883}3884if(errno != EEXIST)3885break;3886++nr;3887}3888}3889die_errno(_("unable to write file '%s' mode%o"), path, mode);3890}38913892static voidadd_conflicted_stages_file(struct patch *patch)3893{3894int stage, namelen;3895unsigned ce_size, mode;3896struct cache_entry *ce;38973898if(!update_index)3899return;3900 namelen =strlen(patch->new_name);3901 ce_size =cache_entry_size(namelen);3902 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);39033904remove_file_from_cache(patch->new_name);3905for(stage =1; stage <4; stage++) {3906if(is_null_sha1(patch->threeway_stage[stage -1]))3907continue;3908 ce =xcalloc(1, ce_size);3909memcpy(ce->name, patch->new_name, namelen);3910 ce->ce_mode =create_ce_mode(mode);3911 ce->ce_flags =create_ce_flags(stage);3912 ce->ce_namelen = namelen;3913hashcpy(ce->sha1, patch->threeway_stage[stage -1]);3914if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3915die(_("unable to add cache entry for%s"), patch->new_name);3916}3917}39183919static voidcreate_file(struct patch *patch)3920{3921char*path = patch->new_name;3922unsigned mode = patch->new_mode;3923unsigned long size = patch->resultsize;3924char*buf = patch->result;39253926if(!mode)3927 mode = S_IFREG |0644;3928create_one_file(path, mode, buf, size);39293930if(patch->conflicted_threeway)3931add_conflicted_stages_file(patch);3932else3933add_index_file(path, mode, buf, size);3934}39353936/* phase zero is to remove, phase one is to create */3937static voidwrite_out_one_result(struct patch *patch,int phase)3938{3939if(patch->is_delete >0) {3940if(phase ==0)3941remove_file(patch,1);3942return;3943}3944if(patch->is_new >0|| patch->is_copy) {3945if(phase ==1)3946create_file(patch);3947return;3948}3949/*3950 * Rename or modification boils down to the same3951 * thing: remove the old, write the new3952 */3953if(phase ==0)3954remove_file(patch, patch->is_rename);3955if(phase ==1)3956create_file(patch);3957}39583959static intwrite_out_one_reject(struct patch *patch)3960{3961FILE*rej;3962char namebuf[PATH_MAX];3963struct fragment *frag;3964int cnt =0;3965struct strbuf sb = STRBUF_INIT;39663967for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {3968if(!frag->rejected)3969continue;3970 cnt++;3971}39723973if(!cnt) {3974if(apply_verbosely)3975say_patch_name(stderr,3976_("Applied patch%scleanly."), patch);3977return0;3978}39793980/* This should not happen, because a removal patch that leaves3981 * contents are marked "rejected" at the patch level.3982 */3983if(!patch->new_name)3984die(_("internal error"));39853986/* Say this even without --verbose */3987strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",3988"Applying patch %%swith%drejects...",3989 cnt),3990 cnt);3991say_patch_name(stderr, sb.buf, patch);3992strbuf_release(&sb);39933994 cnt =strlen(patch->new_name);3995if(ARRAY_SIZE(namebuf) <= cnt +5) {3996 cnt =ARRAY_SIZE(namebuf) -5;3997warning(_("truncating .rej filename to %.*s.rej"),3998 cnt -1, patch->new_name);3999}4000memcpy(namebuf, patch->new_name, cnt);4001memcpy(namebuf + cnt,".rej",5);40024003 rej =fopen(namebuf,"w");4004if(!rej)4005returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));40064007/* Normal git tools never deal with .rej, so do not pretend4008 * this is a git patch by saying --git nor give extended4009 * headers. While at it, maybe please "kompare" that wants4010 * the trailing TAB and some garbage at the end of line ;-).4011 */4012fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4013 patch->new_name, patch->new_name);4014for(cnt =1, frag = patch->fragments;4015 frag;4016 cnt++, frag = frag->next) {4017if(!frag->rejected) {4018fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4019continue;4020}4021fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4022fprintf(rej,"%.*s", frag->size, frag->patch);4023if(frag->patch[frag->size-1] !='\n')4024fputc('\n', rej);4025}4026fclose(rej);4027return-1;4028}40294030static intwrite_out_results(struct patch *list)4031{4032int phase;4033int errs =0;4034struct patch *l;4035struct string_list cpath = STRING_LIST_INIT_DUP;40364037for(phase =0; phase <2; phase++) {4038 l = list;4039while(l) {4040if(l->rejected)4041 errs =1;4042else{4043write_out_one_result(l, phase);4044if(phase ==1) {4045if(write_out_one_reject(l))4046 errs =1;4047if(l->conflicted_threeway) {4048string_list_append(&cpath, l->new_name);4049 errs =1;4050}4051}4052}4053 l = l->next;4054}4055}40564057if(cpath.nr) {4058struct string_list_item *item;40594060sort_string_list(&cpath);4061for_each_string_list_item(item, &cpath)4062fprintf(stderr,"U%s\n", item->string);4063string_list_clear(&cpath,0);40644065rerere(0);4066}40674068return errs;4069}40704071static struct lock_file lock_file;40724073static struct string_list limit_by_name;4074static int has_include;4075static voidadd_name_limit(const char*name,int exclude)4076{4077struct string_list_item *it;40784079 it =string_list_append(&limit_by_name, name);4080 it->util = exclude ? NULL : (void*)1;4081}40824083static intuse_patch(struct patch *p)4084{4085const char*pathname = p->new_name ? p->new_name : p->old_name;4086int i;40874088/* Paths outside are not touched regardless of "--include" */4089if(0< prefix_length) {4090int pathlen =strlen(pathname);4091if(pathlen <= prefix_length ||4092memcmp(prefix, pathname, prefix_length))4093return0;4094}40954096/* See if it matches any of exclude/include rule */4097for(i =0; i < limit_by_name.nr; i++) {4098struct string_list_item *it = &limit_by_name.items[i];4099if(!fnmatch(it->string, pathname,0))4100return(it->util != NULL);4101}41024103/*4104 * If we had any include, a path that does not match any rule is4105 * not used. Otherwise, we saw bunch of exclude rules (or none)4106 * and such a path is used.4107 */4108return!has_include;4109}411041114112static voidprefix_one(char**name)4113{4114char*old_name = *name;4115if(!old_name)4116return;4117*name =xstrdup(prefix_filename(prefix, prefix_length, *name));4118free(old_name);4119}41204121static voidprefix_patches(struct patch *p)4122{4123if(!prefix || p->is_toplevel_relative)4124return;4125for( ; p; p = p->next) {4126prefix_one(&p->new_name);4127prefix_one(&p->old_name);4128}4129}41304131#define INACCURATE_EOF (1<<0)4132#define RECOUNT (1<<1)41334134static intapply_patch(int fd,const char*filename,int options)4135{4136size_t offset;4137struct strbuf buf = STRBUF_INIT;/* owns the patch text */4138struct patch *list = NULL, **listp = &list;4139int skipped_patch =0;41404141 patch_input_file = filename;4142read_patch_file(&buf, fd);4143 offset =0;4144while(offset < buf.len) {4145struct patch *patch;4146int nr;41474148 patch =xcalloc(1,sizeof(*patch));4149 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4150 patch->recount = !!(options & RECOUNT);4151 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);4152if(nr <0)4153break;4154if(apply_in_reverse)4155reverse_patches(patch);4156if(prefix)4157prefix_patches(patch);4158if(use_patch(patch)) {4159patch_stats(patch);4160*listp = patch;4161 listp = &patch->next;4162}4163else{4164free_patch(patch);4165 skipped_patch++;4166}4167 offset += nr;4168}41694170if(!list && !skipped_patch)4171die(_("unrecognized input"));41724173if(whitespace_error && (ws_error_action == die_on_ws_error))4174 apply =0;41754176 update_index = check_index && apply;4177if(update_index && newfd <0)4178 newfd =hold_locked_index(&lock_file,1);41794180if(check_index) {4181if(read_cache() <0)4182die(_("unable to read index file"));4183}41844185if((check || apply) &&4186check_patch_list(list) <0&&4187!apply_with_reject)4188exit(1);41894190if(apply &&write_out_results(list)) {4191if(apply_with_reject)4192exit(1);4193/* with --3way, we still need to write the index out */4194return1;4195}41964197if(fake_ancestor)4198build_fake_ancestor(list, fake_ancestor);41994200if(diffstat)4201stat_patch_list(list);42024203if(numstat)4204numstat_patch_list(list);42054206if(summary)4207summary_patch_list(list);42084209free_patch_list(list);4210strbuf_release(&buf);4211string_list_clear(&fn_table,0);4212return0;4213}42144215static intgit_apply_config(const char*var,const char*value,void*cb)4216{4217if(!strcmp(var,"apply.whitespace"))4218returngit_config_string(&apply_default_whitespace, var, value);4219else if(!strcmp(var,"apply.ignorewhitespace"))4220returngit_config_string(&apply_default_ignorewhitespace, var, value);4221returngit_default_config(var, value, cb);4222}42234224static intoption_parse_exclude(const struct option *opt,4225const char*arg,int unset)4226{4227add_name_limit(arg,1);4228return0;4229}42304231static intoption_parse_include(const struct option *opt,4232const char*arg,int unset)4233{4234add_name_limit(arg,0);4235 has_include =1;4236return0;4237}42384239static intoption_parse_p(const struct option *opt,4240const char*arg,int unset)4241{4242 p_value =atoi(arg);4243 p_value_known =1;4244return0;4245}42464247static intoption_parse_z(const struct option *opt,4248const char*arg,int unset)4249{4250if(unset)4251 line_termination ='\n';4252else4253 line_termination =0;4254return0;4255}42564257static intoption_parse_space_change(const struct option *opt,4258const char*arg,int unset)4259{4260if(unset)4261 ws_ignore_action = ignore_ws_none;4262else4263 ws_ignore_action = ignore_ws_change;4264return0;4265}42664267static intoption_parse_whitespace(const struct option *opt,4268const char*arg,int unset)4269{4270const char**whitespace_option = opt->value;42714272*whitespace_option = arg;4273parse_whitespace_option(arg);4274return0;4275}42764277static intoption_parse_directory(const struct option *opt,4278const char*arg,int unset)4279{4280 root_len =strlen(arg);4281if(root_len && arg[root_len -1] !='/') {4282char*new_root;4283 root = new_root =xmalloc(root_len +2);4284strcpy(new_root, arg);4285strcpy(new_root + root_len++,"/");4286}else4287 root = arg;4288return0;4289}42904291intcmd_apply(int argc,const char**argv,const char*prefix_)4292{4293int i;4294int errs =0;4295int is_not_gitdir = !startup_info->have_repository;4296int force_apply =0;42974298const char*whitespace_option = NULL;42994300struct option builtin_apply_options[] = {4301{ OPTION_CALLBACK,0,"exclude", NULL,N_("path"),4302N_("don't apply changes matching the given path"),43030, option_parse_exclude },4304{ OPTION_CALLBACK,0,"include", NULL,N_("path"),4305N_("apply changes matching the given path"),43060, option_parse_include },4307{ OPTION_CALLBACK,'p', NULL, NULL,N_("num"),4308N_("remove <num> leading slashes from traditional diff paths"),43090, option_parse_p },4310OPT_BOOLEAN(0,"no-add", &no_add,4311N_("ignore additions made by the patch")),4312OPT_BOOLEAN(0,"stat", &diffstat,4313N_("instead of applying the patch, output diffstat for the input")),4314OPT_NOOP_NOARG(0,"allow-binary-replacement"),4315OPT_NOOP_NOARG(0,"binary"),4316OPT_BOOLEAN(0,"numstat", &numstat,4317N_("shows number of added and deleted lines in decimal notation")),4318OPT_BOOLEAN(0,"summary", &summary,4319N_("instead of applying the patch, output a summary for the input")),4320OPT_BOOLEAN(0,"check", &check,4321N_("instead of applying the patch, see if the patch is applicable")),4322OPT_BOOLEAN(0,"index", &check_index,4323N_("make sure the patch is applicable to the current index")),4324OPT_BOOLEAN(0,"cached", &cached,4325N_("apply a patch without touching the working tree")),4326OPT_BOOLEAN(0,"apply", &force_apply,4327N_("also apply the patch (use with --stat/--summary/--check)")),4328OPT_BOOL('3',"3way", &threeway,4329N_("attempt three-way merge if a patch does not apply")),4330OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,4331N_("build a temporary index based on embedded index information")),4332{ OPTION_CALLBACK,'z', NULL, NULL, NULL,4333N_("paths are separated with NUL character"),4334 PARSE_OPT_NOARG, option_parse_z },4335OPT_INTEGER('C', NULL, &p_context,4336N_("ensure at least <n> lines of context match")),4337{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,N_("action"),4338N_("detect new or modified lines that have whitespace errors"),43390, option_parse_whitespace },4340{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,4341N_("ignore changes in whitespace when finding context"),4342 PARSE_OPT_NOARG, option_parse_space_change },4343{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,4344N_("ignore changes in whitespace when finding context"),4345 PARSE_OPT_NOARG, option_parse_space_change },4346OPT_BOOLEAN('R',"reverse", &apply_in_reverse,4347N_("apply the patch in reverse")),4348OPT_BOOLEAN(0,"unidiff-zero", &unidiff_zero,4349N_("don't expect at least one line of context")),4350OPT_BOOLEAN(0,"reject", &apply_with_reject,4351N_("leave the rejected hunks in corresponding *.rej files")),4352OPT_BOOLEAN(0,"allow-overlap", &allow_overlap,4353N_("allow overlapping hunks")),4354OPT__VERBOSE(&apply_verbosely,N_("be verbose")),4355OPT_BIT(0,"inaccurate-eof", &options,4356N_("tolerate incorrectly detected missing new-line at the end of file"),4357 INACCURATE_EOF),4358OPT_BIT(0,"recount", &options,4359N_("do not trust the line counts in the hunk headers"),4360 RECOUNT),4361{ OPTION_CALLBACK,0,"directory", NULL,N_("root"),4362N_("prepend <root> to all filenames"),43630, option_parse_directory },4364OPT_END()4365};43664367 prefix = prefix_;4368 prefix_length = prefix ?strlen(prefix) :0;4369git_config(git_apply_config, NULL);4370if(apply_default_whitespace)4371parse_whitespace_option(apply_default_whitespace);4372if(apply_default_ignorewhitespace)4373parse_ignorewhitespace_option(apply_default_ignorewhitespace);43744375 argc =parse_options(argc, argv, prefix, builtin_apply_options,4376 apply_usage,0);43774378if(apply_with_reject && threeway)4379die("--reject and --3way cannot be used together.");4380if(cached && threeway)4381die("--cached and --3way cannot be used together.");4382if(threeway) {4383if(is_not_gitdir)4384die(_("--3way outside a repository"));4385 check_index =1;4386}4387if(apply_with_reject)4388 apply = apply_verbosely =1;4389if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))4390 apply =0;4391if(check_index && is_not_gitdir)4392die(_("--index outside a repository"));4393if(cached) {4394if(is_not_gitdir)4395die(_("--cached outside a repository"));4396 check_index =1;4397}4398for(i =0; i < argc; i++) {4399const char*arg = argv[i];4400int fd;44014402if(!strcmp(arg,"-")) {4403 errs |=apply_patch(0,"<stdin>", options);4404 read_stdin =0;4405continue;4406}else if(0< prefix_length)4407 arg =prefix_filename(prefix, prefix_length, arg);44084409 fd =open(arg, O_RDONLY);4410if(fd <0)4411die_errno(_("can't open patch '%s'"), arg);4412 read_stdin =0;4413set_default_whitespace_mode(whitespace_option);4414 errs |=apply_patch(fd, arg, options);4415close(fd);4416}4417set_default_whitespace_mode(whitespace_option);4418if(read_stdin)4419 errs |=apply_patch(0,"<stdin>", options);4420if(whitespace_error) {4421if(squelch_whitespace_errors &&4422 squelch_whitespace_errors < whitespace_error) {4423int squelched =4424 whitespace_error - squelch_whitespace_errors;4425warning(Q_("squelched%dwhitespace error",4426"squelched%dwhitespace errors",4427 squelched),4428 squelched);4429}4430if(ws_error_action == die_on_ws_error)4431die(Q_("%dline adds whitespace errors.",4432"%dlines add whitespace errors.",4433 whitespace_error),4434 whitespace_error);4435if(applied_after_fixing_ws && apply)4436warning("%dline%sapplied after"4437" fixing whitespace errors.",4438 applied_after_fixing_ws,4439 applied_after_fixing_ws ==1?"":"s");4440else if(whitespace_error)4441warning(Q_("%dline adds whitespace errors.",4442"%dlines add whitespace errors.",4443 whitespace_error),4444 whitespace_error);4445}44464447if(update_index) {4448if(write_cache(newfd, active_cache, active_nr) ||4449commit_locked_index(&lock_file))4450die(_("Unable to write new index file"));4451}44524453return!!errs;4454}