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}10971098static const char*stop_at_slash(const char*line,int llen)1099{1100int nslash = p_value;1101int i;11021103for(i =0; i < llen; i++) {1104int ch = line[i];1105if(ch =='/'&& --nslash <=0)1106return&line[i];1107}1108return NULL;1109}11101111/*1112 * This is to extract the same name that appears on "diff --git"1113 * line. We do not find and return anything if it is a rename1114 * patch, and it is OK because we will find the name elsewhere.1115 * We need to reliably find name only when it is mode-change only,1116 * creation or deletion of an empty file. In any of these cases,1117 * both sides are the same name under a/ and b/ respectively.1118 */1119static char*git_header_name(const char*line,int llen)1120{1121const char*name;1122const char*second = NULL;1123size_t len, line_len;11241125 line +=strlen("diff --git ");1126 llen -=strlen("diff --git ");11271128if(*line =='"') {1129const char*cp;1130struct strbuf first = STRBUF_INIT;1131struct strbuf sp = STRBUF_INIT;11321133if(unquote_c_style(&first, line, &second))1134goto free_and_fail1;11351136/* advance to the first slash */1137 cp =stop_at_slash(first.buf, first.len);1138/* we do not accept absolute paths */1139if(!cp || cp == first.buf)1140goto free_and_fail1;1141strbuf_remove(&first,0, cp +1- first.buf);11421143/*1144 * second points at one past closing dq of name.1145 * find the second name.1146 */1147while((second < line + llen) &&isspace(*second))1148 second++;11491150if(line + llen <= second)1151goto free_and_fail1;1152if(*second =='"') {1153if(unquote_c_style(&sp, second, NULL))1154goto free_and_fail1;1155 cp =stop_at_slash(sp.buf, sp.len);1156if(!cp || cp == sp.buf)1157goto free_and_fail1;1158/* They must match, otherwise ignore */1159if(strcmp(cp +1, first.buf))1160goto free_and_fail1;1161strbuf_release(&sp);1162returnstrbuf_detach(&first, NULL);1163}11641165/* unquoted second */1166 cp =stop_at_slash(second, line + llen - second);1167if(!cp || cp == second)1168goto free_and_fail1;1169 cp++;1170if(line + llen - cp != first.len +1||1171memcmp(first.buf, cp, first.len))1172goto free_and_fail1;1173returnstrbuf_detach(&first, NULL);11741175 free_and_fail1:1176strbuf_release(&first);1177strbuf_release(&sp);1178return NULL;1179}11801181/* unquoted first name */1182 name =stop_at_slash(line, llen);1183if(!name || name == line)1184return NULL;1185 name++;11861187/*1188 * since the first name is unquoted, a dq if exists must be1189 * the beginning of the second name.1190 */1191for(second = name; second < line + llen; second++) {1192if(*second =='"') {1193struct strbuf sp = STRBUF_INIT;1194const char*np;11951196if(unquote_c_style(&sp, second, NULL))1197goto free_and_fail2;11981199 np =stop_at_slash(sp.buf, sp.len);1200if(!np || np == sp.buf)1201goto free_and_fail2;1202 np++;12031204 len = sp.buf + sp.len - np;1205if(len < second - name &&1206!strncmp(np, name, len) &&1207isspace(name[len])) {1208/* Good */1209strbuf_remove(&sp,0, np - sp.buf);1210returnstrbuf_detach(&sp, NULL);1211}12121213 free_and_fail2:1214strbuf_release(&sp);1215return NULL;1216}1217}12181219/*1220 * Accept a name only if it shows up twice, exactly the same1221 * form.1222 */1223 second =strchr(name,'\n');1224if(!second)1225return NULL;1226 line_len = second - name;1227for(len =0; ; len++) {1228switch(name[len]) {1229default:1230continue;1231case'\n':1232return NULL;1233case'\t':case' ':1234 second =stop_at_slash(name + len, line_len - len);1235if(!second)1236return NULL;1237 second++;1238if(second[len] =='\n'&& !strncmp(name, second, len)) {1239returnxmemdupz(name, len);1240}1241}1242}1243}12441245/* Verify that we recognize the lines following a git header */1246static intparse_git_header(const char*line,int len,unsigned int size,struct patch *patch)1247{1248unsigned long offset;12491250/* A git diff has explicit new/delete information, so we don't guess */1251 patch->is_new =0;1252 patch->is_delete =0;12531254/*1255 * Some things may not have the old name in the1256 * rest of the headers anywhere (pure mode changes,1257 * or removing or adding empty files), so we get1258 * the default name from the header.1259 */1260 patch->def_name =git_header_name(line, len);1261if(patch->def_name && root) {1262char*s =xmalloc(root_len +strlen(patch->def_name) +1);1263strcpy(s, root);1264strcpy(s + root_len, patch->def_name);1265free(patch->def_name);1266 patch->def_name = s;1267}12681269 line += len;1270 size -= len;1271 linenr++;1272for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) {1273static const struct opentry {1274const char*str;1275int(*fn)(const char*,struct patch *);1276} optable[] = {1277{"@@ -", gitdiff_hdrend },1278{"--- ", gitdiff_oldname },1279{"+++ ", gitdiff_newname },1280{"old mode ", gitdiff_oldmode },1281{"new mode ", gitdiff_newmode },1282{"deleted file mode ", gitdiff_delete },1283{"new file mode ", gitdiff_newfile },1284{"copy from ", gitdiff_copysrc },1285{"copy to ", gitdiff_copydst },1286{"rename old ", gitdiff_renamesrc },1287{"rename new ", gitdiff_renamedst },1288{"rename from ", gitdiff_renamesrc },1289{"rename to ", gitdiff_renamedst },1290{"similarity index ", gitdiff_similarity },1291{"dissimilarity index ", gitdiff_dissimilarity },1292{"index ", gitdiff_index },1293{"", gitdiff_unrecognized },1294};1295int i;12961297 len =linelen(line, size);1298if(!len || line[len-1] !='\n')1299break;1300for(i =0; i <ARRAY_SIZE(optable); i++) {1301const struct opentry *p = optable + i;1302int oplen =strlen(p->str);1303if(len < oplen ||memcmp(p->str, line, oplen))1304continue;1305if(p->fn(line + oplen, patch) <0)1306return offset;1307break;1308}1309}13101311return offset;1312}13131314static intparse_num(const char*line,unsigned long*p)1315{1316char*ptr;13171318if(!isdigit(*line))1319return0;1320*p =strtoul(line, &ptr,10);1321return ptr - line;1322}13231324static intparse_range(const char*line,int len,int offset,const char*expect,1325unsigned long*p1,unsigned long*p2)1326{1327int digits, ex;13281329if(offset <0|| offset >= len)1330return-1;1331 line += offset;1332 len -= offset;13331334 digits =parse_num(line, p1);1335if(!digits)1336return-1;13371338 offset += digits;1339 line += digits;1340 len -= digits;13411342*p2 =1;1343if(*line ==',') {1344 digits =parse_num(line+1, p2);1345if(!digits)1346return-1;13471348 offset += digits+1;1349 line += digits+1;1350 len -= digits+1;1351}13521353 ex =strlen(expect);1354if(ex > len)1355return-1;1356if(memcmp(line, expect, ex))1357return-1;13581359return offset + ex;1360}13611362static voidrecount_diff(const char*line,int size,struct fragment *fragment)1363{1364int oldlines =0, newlines =0, ret =0;13651366if(size <1) {1367warning("recount: ignore empty hunk");1368return;1369}13701371for(;;) {1372int len =linelen(line, size);1373 size -= len;1374 line += len;13751376if(size <1)1377break;13781379switch(*line) {1380case' ':case'\n':1381 newlines++;1382/* fall through */1383case'-':1384 oldlines++;1385continue;1386case'+':1387 newlines++;1388continue;1389case'\\':1390continue;1391case'@':1392 ret = size <3||prefixcmp(line,"@@ ");1393break;1394case'd':1395 ret = size <5||prefixcmp(line,"diff ");1396break;1397default:1398 ret = -1;1399break;1400}1401if(ret) {1402warning(_("recount: unexpected line: %.*s"),1403(int)linelen(line, size), line);1404return;1405}1406break;1407}1408 fragment->oldlines = oldlines;1409 fragment->newlines = newlines;1410}14111412/*1413 * Parse a unified diff fragment header of the1414 * form "@@ -a,b +c,d @@"1415 */1416static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1417{1418int offset;14191420if(!len || line[len-1] !='\n')1421return-1;14221423/* Figure out the number of lines in a fragment */1424 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1425 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14261427return offset;1428}14291430static intfind_header(const char*line,unsigned long size,int*hdrsize,struct patch *patch)1431{1432unsigned long offset, len;14331434 patch->is_toplevel_relative =0;1435 patch->is_rename = patch->is_copy =0;1436 patch->is_new = patch->is_delete = -1;1437 patch->old_mode = patch->new_mode =0;1438 patch->old_name = patch->new_name = NULL;1439for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) {1440unsigned long nextlen;14411442 len =linelen(line, size);1443if(!len)1444break;14451446/* Testing this early allows us to take a few shortcuts.. */1447if(len <6)1448continue;14491450/*1451 * Make sure we don't find any unconnected patch fragments.1452 * That's a sign that we didn't find a header, and that a1453 * patch has become corrupted/broken up.1454 */1455if(!memcmp("@@ -", line,4)) {1456struct fragment dummy;1457if(parse_fragment_header(line, len, &dummy) <0)1458continue;1459die(_("patch fragment without header at line%d: %.*s"),1460 linenr, (int)len-1, line);1461}14621463if(size < len +6)1464break;14651466/*1467 * Git patch? It might not have a real patch, just a rename1468 * or mode change, so we handle that specially1469 */1470if(!memcmp("diff --git ", line,11)) {1471int git_hdr_len =parse_git_header(line, len, size, patch);1472if(git_hdr_len <= len)1473continue;1474if(!patch->old_name && !patch->new_name) {1475if(!patch->def_name)1476die(Q_("git diff header lacks filename information when removing "1477"%dleading pathname component (line%d)",1478"git diff header lacks filename information when removing "1479"%dleading pathname components (line%d)",1480 p_value),1481 p_value, linenr);1482 patch->old_name =xstrdup(patch->def_name);1483 patch->new_name =xstrdup(patch->def_name);1484}1485if(!patch->is_delete && !patch->new_name)1486die("git diff header lacks filename information "1487"(line%d)", linenr);1488 patch->is_toplevel_relative =1;1489*hdrsize = git_hdr_len;1490return offset;1491}14921493/* --- followed by +++ ? */1494if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1495continue;14961497/*1498 * We only accept unified patches, so we want it to1499 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1500 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1501 */1502 nextlen =linelen(line + len, size - len);1503if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1504continue;15051506/* Ok, we'll consider it a patch */1507parse_traditional_patch(line, line+len, patch);1508*hdrsize = len + nextlen;1509 linenr +=2;1510return offset;1511}1512return-1;1513}15141515static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1516{1517char*err;15181519if(!result)1520return;15211522 whitespace_error++;1523if(squelch_whitespace_errors &&1524 squelch_whitespace_errors < whitespace_error)1525return;15261527 err =whitespace_error_string(result);1528fprintf(stderr,"%s:%d:%s.\n%.*s\n",1529 patch_input_file, linenr, err, len, line);1530free(err);1531}15321533static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1534{1535unsigned result =ws_check(line +1, len -1, ws_rule);15361537record_ws_error(result, line +1, len -2, linenr);1538}15391540/*1541 * Parse a unified diff. Note that this really needs to parse each1542 * fragment separately, since the only way to know the difference1543 * between a "---" that is part of a patch, and a "---" that starts1544 * the next patch is to look at the line counts..1545 */1546static intparse_fragment(const char*line,unsigned long size,1547struct patch *patch,struct fragment *fragment)1548{1549int added, deleted;1550int len =linelen(line, size), offset;1551unsigned long oldlines, newlines;1552unsigned long leading, trailing;15531554 offset =parse_fragment_header(line, len, fragment);1555if(offset <0)1556return-1;1557if(offset >0&& patch->recount)1558recount_diff(line + offset, size - offset, fragment);1559 oldlines = fragment->oldlines;1560 newlines = fragment->newlines;1561 leading =0;1562 trailing =0;15631564/* Parse the thing.. */1565 line += len;1566 size -= len;1567 linenr++;1568 added = deleted =0;1569for(offset = len;15700< size;1571 offset += len, size -= len, line += len, linenr++) {1572if(!oldlines && !newlines)1573break;1574 len =linelen(line, size);1575if(!len || line[len-1] !='\n')1576return-1;1577switch(*line) {1578default:1579return-1;1580case'\n':/* newer GNU diff, an empty context line */1581case' ':1582 oldlines--;1583 newlines--;1584if(!deleted && !added)1585 leading++;1586 trailing++;1587break;1588case'-':1589if(apply_in_reverse &&1590 ws_error_action != nowarn_ws_error)1591check_whitespace(line, len, patch->ws_rule);1592 deleted++;1593 oldlines--;1594 trailing =0;1595break;1596case'+':1597if(!apply_in_reverse &&1598 ws_error_action != nowarn_ws_error)1599check_whitespace(line, len, patch->ws_rule);1600 added++;1601 newlines--;1602 trailing =0;1603break;16041605/*1606 * We allow "\ No newline at end of file". Depending1607 * on locale settings when the patch was produced we1608 * don't know what this line looks like. The only1609 * thing we do know is that it begins with "\ ".1610 * Checking for 12 is just for sanity check -- any1611 * l10n of "\ No newline..." is at least that long.1612 */1613case'\\':1614if(len <12||memcmp(line,"\\",2))1615return-1;1616break;1617}1618}1619if(oldlines || newlines)1620return-1;1621 fragment->leading = leading;1622 fragment->trailing = trailing;16231624/*1625 * If a fragment ends with an incomplete line, we failed to include1626 * it in the above loop because we hit oldlines == newlines == 01627 * before seeing it.1628 */1629if(12< size && !memcmp(line,"\\",2))1630 offset +=linelen(line, size);16311632 patch->lines_added += added;1633 patch->lines_deleted += deleted;16341635if(0< patch->is_new && oldlines)1636returnerror(_("new file depends on old contents"));1637if(0< patch->is_delete && newlines)1638returnerror(_("deleted file still has contents"));1639return offset;1640}16411642/*1643 * We have seen "diff --git a/... b/..." header (or a traditional patch1644 * header). Read hunks that belong to this patch into fragments and hang1645 * them to the given patch structure.1646 *1647 * The (fragment->patch, fragment->size) pair points into the memory given1648 * by the caller, not a copy, when we return.1649 */1650static intparse_single_patch(const char*line,unsigned long size,struct patch *patch)1651{1652unsigned long offset =0;1653unsigned long oldlines =0, newlines =0, context =0;1654struct fragment **fragp = &patch->fragments;16551656while(size >4&& !memcmp(line,"@@ -",4)) {1657struct fragment *fragment;1658int len;16591660 fragment =xcalloc(1,sizeof(*fragment));1661 fragment->linenr = linenr;1662 len =parse_fragment(line, size, patch, fragment);1663if(len <=0)1664die(_("corrupt patch at line%d"), linenr);1665 fragment->patch = line;1666 fragment->size = len;1667 oldlines += fragment->oldlines;1668 newlines += fragment->newlines;1669 context += fragment->leading + fragment->trailing;16701671*fragp = fragment;1672 fragp = &fragment->next;16731674 offset += len;1675 line += len;1676 size -= len;1677}16781679/*1680 * If something was removed (i.e. we have old-lines) it cannot1681 * be creation, and if something was added it cannot be1682 * deletion. However, the reverse is not true; --unified=01683 * patches that only add are not necessarily creation even1684 * though they do not have any old lines, and ones that only1685 * delete are not necessarily deletion.1686 *1687 * Unfortunately, a real creation/deletion patch do _not_ have1688 * any context line by definition, so we cannot safely tell it1689 * apart with --unified=0 insanity. At least if the patch has1690 * more than one hunk it is not creation or deletion.1691 */1692if(patch->is_new <0&&1693(oldlines || (patch->fragments && patch->fragments->next)))1694 patch->is_new =0;1695if(patch->is_delete <0&&1696(newlines || (patch->fragments && patch->fragments->next)))1697 patch->is_delete =0;16981699if(0< patch->is_new && oldlines)1700die(_("new file%sdepends on old contents"), patch->new_name);1701if(0< patch->is_delete && newlines)1702die(_("deleted file%sstill has contents"), patch->old_name);1703if(!patch->is_delete && !newlines && context)1704fprintf_ln(stderr,1705_("** warning: "1706"file%sbecomes empty but is not deleted"),1707 patch->new_name);17081709return offset;1710}17111712staticinlineintmetadata_changes(struct patch *patch)1713{1714return patch->is_rename >0||1715 patch->is_copy >0||1716 patch->is_new >0||1717 patch->is_delete ||1718(patch->old_mode && patch->new_mode &&1719 patch->old_mode != patch->new_mode);1720}17211722static char*inflate_it(const void*data,unsigned long size,1723unsigned long inflated_size)1724{1725 git_zstream stream;1726void*out;1727int st;17281729memset(&stream,0,sizeof(stream));17301731 stream.next_in = (unsigned char*)data;1732 stream.avail_in = size;1733 stream.next_out = out =xmalloc(inflated_size);1734 stream.avail_out = inflated_size;1735git_inflate_init(&stream);1736 st =git_inflate(&stream, Z_FINISH);1737git_inflate_end(&stream);1738if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1739free(out);1740return NULL;1741}1742return out;1743}17441745/*1746 * Read a binary hunk and return a new fragment; fragment->patch1747 * points at an allocated memory that the caller must free, so1748 * it is marked as "->free_patch = 1".1749 */1750static struct fragment *parse_binary_hunk(char**buf_p,1751unsigned long*sz_p,1752int*status_p,1753int*used_p)1754{1755/*1756 * Expect a line that begins with binary patch method ("literal"1757 * or "delta"), followed by the length of data before deflating.1758 * a sequence of 'length-byte' followed by base-85 encoded data1759 * should follow, terminated by a newline.1760 *1761 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1762 * and we would limit the patch line to 66 characters,1763 * so one line can fit up to 13 groups that would decode1764 * to 52 bytes max. The length byte 'A'-'Z' corresponds1765 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1766 */1767int llen, used;1768unsigned long size = *sz_p;1769char*buffer = *buf_p;1770int patch_method;1771unsigned long origlen;1772char*data = NULL;1773int hunk_size =0;1774struct fragment *frag;17751776 llen =linelen(buffer, size);1777 used = llen;17781779*status_p =0;17801781if(!prefixcmp(buffer,"delta ")) {1782 patch_method = BINARY_DELTA_DEFLATED;1783 origlen =strtoul(buffer +6, NULL,10);1784}1785else if(!prefixcmp(buffer,"literal ")) {1786 patch_method = BINARY_LITERAL_DEFLATED;1787 origlen =strtoul(buffer +8, NULL,10);1788}1789else1790return NULL;17911792 linenr++;1793 buffer += llen;1794while(1) {1795int byte_length, max_byte_length, newsize;1796 llen =linelen(buffer, size);1797 used += llen;1798 linenr++;1799if(llen ==1) {1800/* consume the blank line */1801 buffer++;1802 size--;1803break;1804}1805/*1806 * Minimum line is "A00000\n" which is 7-byte long,1807 * and the line length must be multiple of 5 plus 2.1808 */1809if((llen <7) || (llen-2) %5)1810goto corrupt;1811 max_byte_length = (llen -2) /5*4;1812 byte_length = *buffer;1813if('A'<= byte_length && byte_length <='Z')1814 byte_length = byte_length -'A'+1;1815else if('a'<= byte_length && byte_length <='z')1816 byte_length = byte_length -'a'+27;1817else1818goto corrupt;1819/* if the input length was not multiple of 4, we would1820 * have filler at the end but the filler should never1821 * exceed 3 bytes1822 */1823if(max_byte_length < byte_length ||1824 byte_length <= max_byte_length -4)1825goto corrupt;1826 newsize = hunk_size + byte_length;1827 data =xrealloc(data, newsize);1828if(decode_85(data + hunk_size, buffer +1, byte_length))1829goto corrupt;1830 hunk_size = newsize;1831 buffer += llen;1832 size -= llen;1833}18341835 frag =xcalloc(1,sizeof(*frag));1836 frag->patch =inflate_it(data, hunk_size, origlen);1837 frag->free_patch =1;1838if(!frag->patch)1839goto corrupt;1840free(data);1841 frag->size = origlen;1842*buf_p = buffer;1843*sz_p = size;1844*used_p = used;1845 frag->binary_patch_method = patch_method;1846return frag;18471848 corrupt:1849free(data);1850*status_p = -1;1851error(_("corrupt binary patch at line%d: %.*s"),1852 linenr-1, llen-1, buffer);1853return NULL;1854}18551856static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1857{1858/*1859 * We have read "GIT binary patch\n"; what follows is a line1860 * that says the patch method (currently, either "literal" or1861 * "delta") and the length of data before deflating; a1862 * sequence of 'length-byte' followed by base-85 encoded data1863 * follows.1864 *1865 * When a binary patch is reversible, there is another binary1866 * hunk in the same format, starting with patch method (either1867 * "literal" or "delta") with the length of data, and a sequence1868 * of length-byte + base-85 encoded data, terminated with another1869 * empty line. This data, when applied to the postimage, produces1870 * the preimage.1871 */1872struct fragment *forward;1873struct fragment *reverse;1874int status;1875int used, used_1;18761877 forward =parse_binary_hunk(&buffer, &size, &status, &used);1878if(!forward && !status)1879/* there has to be one hunk (forward hunk) */1880returnerror(_("unrecognized binary patch at line%d"), linenr-1);1881if(status)1882/* otherwise we already gave an error message */1883return status;18841885 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1886if(reverse)1887 used += used_1;1888else if(status) {1889/*1890 * Not having reverse hunk is not an error, but having1891 * a corrupt reverse hunk is.1892 */1893free((void*) forward->patch);1894free(forward);1895return status;1896}1897 forward->next = reverse;1898 patch->fragments = forward;1899 patch->is_binary =1;1900return used;1901}19021903/*1904 * Read the patch text in "buffer" taht extends for "size" bytes; stop1905 * reading after seeing a single patch (i.e. changes to a single file).1906 * Create fragments (i.e. patch hunks) and hang them to the given patch.1907 * Return the number of bytes consumed, so that the caller can call us1908 * again for the next patch.1909 */1910static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1911{1912int hdrsize, patchsize;1913int offset =find_header(buffer, size, &hdrsize, patch);19141915if(offset <0)1916return offset;19171918 patch->ws_rule =whitespace_rule(patch->new_name1919? patch->new_name1920: patch->old_name);19211922 patchsize =parse_single_patch(buffer + offset + hdrsize,1923 size - offset - hdrsize, patch);19241925if(!patchsize) {1926static const char*binhdr[] = {1927"Binary files ",1928"Files ",1929 NULL,1930};1931static const char git_binary[] ="GIT binary patch\n";1932int i;1933int hd = hdrsize + offset;1934unsigned long llen =linelen(buffer + hd, size - hd);19351936if(llen ==sizeof(git_binary) -1&&1937!memcmp(git_binary, buffer + hd, llen)) {1938int used;1939 linenr++;1940 used =parse_binary(buffer + hd + llen,1941 size - hd - llen, patch);1942if(used)1943 patchsize = used + llen;1944else1945 patchsize =0;1946}1947else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1948for(i =0; binhdr[i]; i++) {1949int len =strlen(binhdr[i]);1950if(len < size - hd &&1951!memcmp(binhdr[i], buffer + hd, len)) {1952 linenr++;1953 patch->is_binary =1;1954 patchsize = llen;1955break;1956}1957}1958}19591960/* Empty patch cannot be applied if it is a text patch1961 * without metadata change. A binary patch appears1962 * empty to us here.1963 */1964if((apply || check) &&1965(!patch->is_binary && !metadata_changes(patch)))1966die(_("patch with only garbage at line%d"), linenr);1967}19681969return offset + hdrsize + patchsize;1970}19711972#define swap(a,b) myswap((a),(b),sizeof(a))19731974#define myswap(a, b, size) do { \1975 unsigned char mytmp[size]; \1976 memcpy(mytmp, &a, size); \1977 memcpy(&a, &b, size); \1978 memcpy(&b, mytmp, size); \1979} while (0)19801981static voidreverse_patches(struct patch *p)1982{1983for(; p; p = p->next) {1984struct fragment *frag = p->fragments;19851986swap(p->new_name, p->old_name);1987swap(p->new_mode, p->old_mode);1988swap(p->is_new, p->is_delete);1989swap(p->lines_added, p->lines_deleted);1990swap(p->old_sha1_prefix, p->new_sha1_prefix);19911992for(; frag; frag = frag->next) {1993swap(frag->newpos, frag->oldpos);1994swap(frag->newlines, frag->oldlines);1995}1996}1997}19981999static const char pluses[] =2000"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2001static const char minuses[]=2002"----------------------------------------------------------------------";20032004static voidshow_stats(struct patch *patch)2005{2006struct strbuf qname = STRBUF_INIT;2007char*cp = patch->new_name ? patch->new_name : patch->old_name;2008int max, add, del;20092010quote_c_style(cp, &qname, NULL,0);20112012/*2013 * "scale" the filename2014 */2015 max = max_len;2016if(max >50)2017 max =50;20182019if(qname.len > max) {2020 cp =strchr(qname.buf + qname.len +3- max,'/');2021if(!cp)2022 cp = qname.buf + qname.len +3- max;2023strbuf_splice(&qname,0, cp - qname.buf,"...",3);2024}20252026if(patch->is_binary) {2027printf(" %-*s | Bin\n", max, qname.buf);2028strbuf_release(&qname);2029return;2030}20312032printf(" %-*s |", max, qname.buf);2033strbuf_release(&qname);20342035/*2036 * scale the add/delete2037 */2038 max = max + max_change >70?70- max : max_change;2039 add = patch->lines_added;2040 del = patch->lines_deleted;20412042if(max_change >0) {2043int total = ((add + del) * max + max_change /2) / max_change;2044 add = (add * max + max_change /2) / max_change;2045 del = total - add;2046}2047printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2048 add, pluses, del, minuses);2049}20502051static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2052{2053switch(st->st_mode & S_IFMT) {2054case S_IFLNK:2055if(strbuf_readlink(buf, path, st->st_size) <0)2056returnerror(_("unable to read symlink%s"), path);2057return0;2058case S_IFREG:2059if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2060returnerror(_("unable to open or read%s"), path);2061convert_to_git(path, buf->buf, buf->len, buf,0);2062return0;2063default:2064return-1;2065}2066}20672068/*2069 * Update the preimage, and the common lines in postimage,2070 * from buffer buf of length len. If postlen is 0 the postimage2071 * is updated in place, otherwise it's updated on a new buffer2072 * of length postlen2073 */20742075static voidupdate_pre_post_images(struct image *preimage,2076struct image *postimage,2077char*buf,2078size_t len,size_t postlen)2079{2080int i, ctx;2081char*new, *old, *fixed;2082struct image fixed_preimage;20832084/*2085 * Update the preimage with whitespace fixes. Note that we2086 * are not losing preimage->buf -- apply_one_fragment() will2087 * free "oldlines".2088 */2089prepare_image(&fixed_preimage, buf, len,1);2090assert(fixed_preimage.nr == preimage->nr);2091for(i =0; i < preimage->nr; i++)2092 fixed_preimage.line[i].flag = preimage->line[i].flag;2093free(preimage->line_allocated);2094*preimage = fixed_preimage;20952096/*2097 * Adjust the common context lines in postimage. This can be2098 * done in-place when we are just doing whitespace fixing,2099 * which does not make the string grow, but needs a new buffer2100 * when ignoring whitespace causes the update, since in this case2101 * we could have e.g. tabs converted to multiple spaces.2102 * We trust the caller to tell us if the update can be done2103 * in place (postlen==0) or not.2104 */2105 old = postimage->buf;2106if(postlen)2107new= postimage->buf =xmalloc(postlen);2108else2109new= old;2110 fixed = preimage->buf;2111for(i = ctx =0; i < postimage->nr; i++) {2112size_t len = postimage->line[i].len;2113if(!(postimage->line[i].flag & LINE_COMMON)) {2114/* an added line -- no counterparts in preimage */2115memmove(new, old, len);2116 old += len;2117new+= len;2118continue;2119}21202121/* a common context -- skip it in the original postimage */2122 old += len;21232124/* and find the corresponding one in the fixed preimage */2125while(ctx < preimage->nr &&2126!(preimage->line[ctx].flag & LINE_COMMON)) {2127 fixed += preimage->line[ctx].len;2128 ctx++;2129}2130if(preimage->nr <= ctx)2131die(_("oops"));21322133/* and copy it in, while fixing the line length */2134 len = preimage->line[ctx].len;2135memcpy(new, fixed, len);2136new+= len;2137 fixed += len;2138 postimage->line[i].len = len;2139 ctx++;2140}21412142/* Fix the length of the whole thing */2143 postimage->len =new- postimage->buf;2144}21452146static intmatch_fragment(struct image *img,2147struct image *preimage,2148struct image *postimage,2149unsigned longtry,2150int try_lno,2151unsigned ws_rule,2152int match_beginning,int match_end)2153{2154int i;2155char*fixed_buf, *buf, *orig, *target;2156struct strbuf fixed;2157size_t fixed_len;2158int preimage_limit;21592160if(preimage->nr + try_lno <= img->nr) {2161/*2162 * The hunk falls within the boundaries of img.2163 */2164 preimage_limit = preimage->nr;2165if(match_end && (preimage->nr + try_lno != img->nr))2166return0;2167}else if(ws_error_action == correct_ws_error &&2168(ws_rule & WS_BLANK_AT_EOF)) {2169/*2170 * This hunk extends beyond the end of img, and we are2171 * removing blank lines at the end of the file. This2172 * many lines from the beginning of the preimage must2173 * match with img, and the remainder of the preimage2174 * must be blank.2175 */2176 preimage_limit = img->nr - try_lno;2177}else{2178/*2179 * The hunk extends beyond the end of the img and2180 * we are not removing blanks at the end, so we2181 * should reject the hunk at this position.2182 */2183return0;2184}21852186if(match_beginning && try_lno)2187return0;21882189/* Quick hash check */2190for(i =0; i < preimage_limit; i++)2191if((img->line[try_lno + i].flag & LINE_PATCHED) ||2192(preimage->line[i].hash != img->line[try_lno + i].hash))2193return0;21942195if(preimage_limit == preimage->nr) {2196/*2197 * Do we have an exact match? If we were told to match2198 * at the end, size must be exactly at try+fragsize,2199 * otherwise try+fragsize must be still within the preimage,2200 * and either case, the old piece should match the preimage2201 * exactly.2202 */2203if((match_end2204? (try+ preimage->len == img->len)2205: (try+ preimage->len <= img->len)) &&2206!memcmp(img->buf +try, preimage->buf, preimage->len))2207return1;2208}else{2209/*2210 * The preimage extends beyond the end of img, so2211 * there cannot be an exact match.2212 *2213 * There must be one non-blank context line that match2214 * a line before the end of img.2215 */2216char*buf_end;22172218 buf = preimage->buf;2219 buf_end = buf;2220for(i =0; i < preimage_limit; i++)2221 buf_end += preimage->line[i].len;22222223for( ; buf < buf_end; buf++)2224if(!isspace(*buf))2225break;2226if(buf == buf_end)2227return0;2228}22292230/*2231 * No exact match. If we are ignoring whitespace, run a line-by-line2232 * fuzzy matching. We collect all the line length information because2233 * we need it to adjust whitespace if we match.2234 */2235if(ws_ignore_action == ignore_ws_change) {2236size_t imgoff =0;2237size_t preoff =0;2238size_t postlen = postimage->len;2239size_t extra_chars;2240char*preimage_eof;2241char*preimage_end;2242for(i =0; i < preimage_limit; i++) {2243size_t prelen = preimage->line[i].len;2244size_t imglen = img->line[try_lno+i].len;22452246if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2247 preimage->buf + preoff, prelen))2248return0;2249if(preimage->line[i].flag & LINE_COMMON)2250 postlen += imglen - prelen;2251 imgoff += imglen;2252 preoff += prelen;2253}22542255/*2256 * Ok, the preimage matches with whitespace fuzz.2257 *2258 * imgoff now holds the true length of the target that2259 * matches the preimage before the end of the file.2260 *2261 * Count the number of characters in the preimage that fall2262 * beyond the end of the file and make sure that all of them2263 * are whitespace characters. (This can only happen if2264 * we are removing blank lines at the end of the file.)2265 */2266 buf = preimage_eof = preimage->buf + preoff;2267for( ; i < preimage->nr; i++)2268 preoff += preimage->line[i].len;2269 preimage_end = preimage->buf + preoff;2270for( ; buf < preimage_end; buf++)2271if(!isspace(*buf))2272return0;22732274/*2275 * Update the preimage and the common postimage context2276 * lines to use the same whitespace as the target.2277 * If whitespace is missing in the target (i.e.2278 * if the preimage extends beyond the end of the file),2279 * use the whitespace from the preimage.2280 */2281 extra_chars = preimage_end - preimage_eof;2282strbuf_init(&fixed, imgoff + extra_chars);2283strbuf_add(&fixed, img->buf +try, imgoff);2284strbuf_add(&fixed, preimage_eof, extra_chars);2285 fixed_buf =strbuf_detach(&fixed, &fixed_len);2286update_pre_post_images(preimage, postimage,2287 fixed_buf, fixed_len, postlen);2288return1;2289}22902291if(ws_error_action != correct_ws_error)2292return0;22932294/*2295 * The hunk does not apply byte-by-byte, but the hash says2296 * it might with whitespace fuzz. We haven't been asked to2297 * ignore whitespace, we were asked to correct whitespace2298 * errors, so let's try matching after whitespace correction.2299 *2300 * The preimage may extend beyond the end of the file,2301 * but in this loop we will only handle the part of the2302 * preimage that falls within the file.2303 */2304strbuf_init(&fixed, preimage->len +1);2305 orig = preimage->buf;2306 target = img->buf +try;2307for(i =0; i < preimage_limit; i++) {2308size_t oldlen = preimage->line[i].len;2309size_t tgtlen = img->line[try_lno + i].len;2310size_t fixstart = fixed.len;2311struct strbuf tgtfix;2312int match;23132314/* Try fixing the line in the preimage */2315ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);23162317/* Try fixing the line in the target */2318strbuf_init(&tgtfix, tgtlen);2319ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);23202321/*2322 * If they match, either the preimage was based on2323 * a version before our tree fixed whitespace breakage,2324 * or we are lacking a whitespace-fix patch the tree2325 * the preimage was based on already had (i.e. target2326 * has whitespace breakage, the preimage doesn't).2327 * In either case, we are fixing the whitespace breakages2328 * so we might as well take the fix together with their2329 * real change.2330 */2331 match = (tgtfix.len == fixed.len - fixstart &&2332!memcmp(tgtfix.buf, fixed.buf + fixstart,2333 fixed.len - fixstart));23342335strbuf_release(&tgtfix);2336if(!match)2337goto unmatch_exit;23382339 orig += oldlen;2340 target += tgtlen;2341}234223432344/*2345 * Now handle the lines in the preimage that falls beyond the2346 * end of the file (if any). They will only match if they are2347 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2348 * false).2349 */2350for( ; i < preimage->nr; i++) {2351size_t fixstart = fixed.len;/* start of the fixed preimage */2352size_t oldlen = preimage->line[i].len;2353int j;23542355/* Try fixing the line in the preimage */2356ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);23572358for(j = fixstart; j < fixed.len; j++)2359if(!isspace(fixed.buf[j]))2360goto unmatch_exit;23612362 orig += oldlen;2363}23642365/*2366 * Yes, the preimage is based on an older version that still2367 * has whitespace breakages unfixed, and fixing them makes the2368 * hunk match. Update the context lines in the postimage.2369 */2370 fixed_buf =strbuf_detach(&fixed, &fixed_len);2371update_pre_post_images(preimage, postimage,2372 fixed_buf, fixed_len,0);2373return1;23742375 unmatch_exit:2376strbuf_release(&fixed);2377return0;2378}23792380static intfind_pos(struct image *img,2381struct image *preimage,2382struct image *postimage,2383int line,2384unsigned ws_rule,2385int match_beginning,int match_end)2386{2387int i;2388unsigned long backwards, forwards,try;2389int backwards_lno, forwards_lno, try_lno;23902391/*2392 * If match_beginning or match_end is specified, there is no2393 * point starting from a wrong line that will never match and2394 * wander around and wait for a match at the specified end.2395 */2396if(match_beginning)2397 line =0;2398else if(match_end)2399 line = img->nr - preimage->nr;24002401/*2402 * Because the comparison is unsigned, the following test2403 * will also take care of a negative line number that can2404 * result when match_end and preimage is larger than the target.2405 */2406if((size_t) line > img->nr)2407 line = img->nr;24082409try=0;2410for(i =0; i < line; i++)2411try+= img->line[i].len;24122413/*2414 * There's probably some smart way to do this, but I'll leave2415 * that to the smart and beautiful people. I'm simple and stupid.2416 */2417 backwards =try;2418 backwards_lno = line;2419 forwards =try;2420 forwards_lno = line;2421 try_lno = line;24222423for(i =0; ; i++) {2424if(match_fragment(img, preimage, postimage,2425try, try_lno, ws_rule,2426 match_beginning, match_end))2427return try_lno;24282429 again:2430if(backwards_lno ==0&& forwards_lno == img->nr)2431break;24322433if(i &1) {2434if(backwards_lno ==0) {2435 i++;2436goto again;2437}2438 backwards_lno--;2439 backwards -= img->line[backwards_lno].len;2440try= backwards;2441 try_lno = backwards_lno;2442}else{2443if(forwards_lno == img->nr) {2444 i++;2445goto again;2446}2447 forwards += img->line[forwards_lno].len;2448 forwards_lno++;2449try= forwards;2450 try_lno = forwards_lno;2451}24522453}2454return-1;2455}24562457static voidremove_first_line(struct image *img)2458{2459 img->buf += img->line[0].len;2460 img->len -= img->line[0].len;2461 img->line++;2462 img->nr--;2463}24642465static voidremove_last_line(struct image *img)2466{2467 img->len -= img->line[--img->nr].len;2468}24692470/*2471 * The change from "preimage" and "postimage" has been found to2472 * apply at applied_pos (counts in line numbers) in "img".2473 * Update "img" to remove "preimage" and replace it with "postimage".2474 */2475static voidupdate_image(struct image *img,2476int applied_pos,2477struct image *preimage,2478struct image *postimage)2479{2480/*2481 * remove the copy of preimage at offset in img2482 * and replace it with postimage2483 */2484int i, nr;2485size_t remove_count, insert_count, applied_at =0;2486char*result;2487int preimage_limit;24882489/*2490 * If we are removing blank lines at the end of img,2491 * the preimage may extend beyond the end.2492 * If that is the case, we must be careful only to2493 * remove the part of the preimage that falls within2494 * the boundaries of img. Initialize preimage_limit2495 * to the number of lines in the preimage that falls2496 * within the boundaries.2497 */2498 preimage_limit = preimage->nr;2499if(preimage_limit > img->nr - applied_pos)2500 preimage_limit = img->nr - applied_pos;25012502for(i =0; i < applied_pos; i++)2503 applied_at += img->line[i].len;25042505 remove_count =0;2506for(i =0; i < preimage_limit; i++)2507 remove_count += img->line[applied_pos + i].len;2508 insert_count = postimage->len;25092510/* Adjust the contents */2511 result =xmalloc(img->len + insert_count - remove_count +1);2512memcpy(result, img->buf, applied_at);2513memcpy(result + applied_at, postimage->buf, postimage->len);2514memcpy(result + applied_at + postimage->len,2515 img->buf + (applied_at + remove_count),2516 img->len - (applied_at + remove_count));2517free(img->buf);2518 img->buf = result;2519 img->len += insert_count - remove_count;2520 result[img->len] ='\0';25212522/* Adjust the line table */2523 nr = img->nr + postimage->nr - preimage_limit;2524if(preimage_limit < postimage->nr) {2525/*2526 * NOTE: this knows that we never call remove_first_line()2527 * on anything other than pre/post image.2528 */2529 img->line =xrealloc(img->line, nr *sizeof(*img->line));2530 img->line_allocated = img->line;2531}2532if(preimage_limit != postimage->nr)2533memmove(img->line + applied_pos + postimage->nr,2534 img->line + applied_pos + preimage_limit,2535(img->nr - (applied_pos + preimage_limit)) *2536sizeof(*img->line));2537memcpy(img->line + applied_pos,2538 postimage->line,2539 postimage->nr *sizeof(*img->line));2540if(!allow_overlap)2541for(i =0; i < postimage->nr; i++)2542 img->line[applied_pos + i].flag |= LINE_PATCHED;2543 img->nr = nr;2544}25452546/*2547 * Use the patch-hunk text in "frag" to prepare two images (preimage and2548 * postimage) for the hunk. Find lines that match "preimage" in "img" and2549 * replace the part of "img" with "postimage" text.2550 */2551static intapply_one_fragment(struct image *img,struct fragment *frag,2552int inaccurate_eof,unsigned ws_rule,2553int nth_fragment)2554{2555int match_beginning, match_end;2556const char*patch = frag->patch;2557int size = frag->size;2558char*old, *oldlines;2559struct strbuf newlines;2560int new_blank_lines_at_end =0;2561int found_new_blank_lines_at_end =0;2562int hunk_linenr = frag->linenr;2563unsigned long leading, trailing;2564int pos, applied_pos;2565struct image preimage;2566struct image postimage;25672568memset(&preimage,0,sizeof(preimage));2569memset(&postimage,0,sizeof(postimage));2570 oldlines =xmalloc(size);2571strbuf_init(&newlines, size);25722573 old = oldlines;2574while(size >0) {2575char first;2576int len =linelen(patch, size);2577int plen;2578int added_blank_line =0;2579int is_blank_context =0;2580size_t start;25812582if(!len)2583break;25842585/*2586 * "plen" is how much of the line we should use for2587 * the actual patch data. Normally we just remove the2588 * first character on the line, but if the line is2589 * followed by "\ No newline", then we also remove the2590 * last one (which is the newline, of course).2591 */2592 plen = len -1;2593if(len < size && patch[len] =='\\')2594 plen--;2595 first = *patch;2596if(apply_in_reverse) {2597if(first =='-')2598 first ='+';2599else if(first =='+')2600 first ='-';2601}26022603switch(first) {2604case'\n':2605/* Newer GNU diff, empty context line */2606if(plen <0)2607/* ... followed by '\No newline'; nothing */2608break;2609*old++ ='\n';2610strbuf_addch(&newlines,'\n');2611add_line_info(&preimage,"\n",1, LINE_COMMON);2612add_line_info(&postimage,"\n",1, LINE_COMMON);2613 is_blank_context =1;2614break;2615case' ':2616if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2617ws_blank_line(patch +1, plen, ws_rule))2618 is_blank_context =1;2619case'-':2620memcpy(old, patch +1, plen);2621add_line_info(&preimage, old, plen,2622(first ==' '? LINE_COMMON :0));2623 old += plen;2624if(first =='-')2625break;2626/* Fall-through for ' ' */2627case'+':2628/* --no-add does not add new lines */2629if(first =='+'&& no_add)2630break;26312632 start = newlines.len;2633if(first !='+'||2634!whitespace_error ||2635 ws_error_action != correct_ws_error) {2636strbuf_add(&newlines, patch +1, plen);2637}2638else{2639ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2640}2641add_line_info(&postimage, newlines.buf + start, newlines.len - start,2642(first =='+'?0: LINE_COMMON));2643if(first =='+'&&2644(ws_rule & WS_BLANK_AT_EOF) &&2645ws_blank_line(patch +1, plen, ws_rule))2646 added_blank_line =1;2647break;2648case'@':case'\\':2649/* Ignore it, we already handled it */2650break;2651default:2652if(apply_verbosely)2653error(_("invalid start of line: '%c'"), first);2654return-1;2655}2656if(added_blank_line) {2657if(!new_blank_lines_at_end)2658 found_new_blank_lines_at_end = hunk_linenr;2659 new_blank_lines_at_end++;2660}2661else if(is_blank_context)2662;2663else2664 new_blank_lines_at_end =0;2665 patch += len;2666 size -= len;2667 hunk_linenr++;2668}2669if(inaccurate_eof &&2670 old > oldlines && old[-1] =='\n'&&2671 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2672 old--;2673strbuf_setlen(&newlines, newlines.len -1);2674}26752676 leading = frag->leading;2677 trailing = frag->trailing;26782679/*2680 * A hunk to change lines at the beginning would begin with2681 * @@ -1,L +N,M @@2682 * but we need to be careful. -U0 that inserts before the second2683 * line also has this pattern.2684 *2685 * And a hunk to add to an empty file would begin with2686 * @@ -0,0 +N,M @@2687 *2688 * In other words, a hunk that is (frag->oldpos <= 1) with or2689 * without leading context must match at the beginning.2690 */2691 match_beginning = (!frag->oldpos ||2692(frag->oldpos ==1&& !unidiff_zero));26932694/*2695 * A hunk without trailing lines must match at the end.2696 * However, we simply cannot tell if a hunk must match end2697 * from the lack of trailing lines if the patch was generated2698 * with unidiff without any context.2699 */2700 match_end = !unidiff_zero && !trailing;27012702 pos = frag->newpos ? (frag->newpos -1) :0;2703 preimage.buf = oldlines;2704 preimage.len = old - oldlines;2705 postimage.buf = newlines.buf;2706 postimage.len = newlines.len;2707 preimage.line = preimage.line_allocated;2708 postimage.line = postimage.line_allocated;27092710for(;;) {27112712 applied_pos =find_pos(img, &preimage, &postimage, pos,2713 ws_rule, match_beginning, match_end);27142715if(applied_pos >=0)2716break;27172718/* Am I at my context limits? */2719if((leading <= p_context) && (trailing <= p_context))2720break;2721if(match_beginning || match_end) {2722 match_beginning = match_end =0;2723continue;2724}27252726/*2727 * Reduce the number of context lines; reduce both2728 * leading and trailing if they are equal otherwise2729 * just reduce the larger context.2730 */2731if(leading >= trailing) {2732remove_first_line(&preimage);2733remove_first_line(&postimage);2734 pos--;2735 leading--;2736}2737if(trailing > leading) {2738remove_last_line(&preimage);2739remove_last_line(&postimage);2740 trailing--;2741}2742}27432744if(applied_pos >=0) {2745if(new_blank_lines_at_end &&2746 preimage.nr + applied_pos >= img->nr &&2747(ws_rule & WS_BLANK_AT_EOF) &&2748 ws_error_action != nowarn_ws_error) {2749record_ws_error(WS_BLANK_AT_EOF,"+",1,2750 found_new_blank_lines_at_end);2751if(ws_error_action == correct_ws_error) {2752while(new_blank_lines_at_end--)2753remove_last_line(&postimage);2754}2755/*2756 * We would want to prevent write_out_results()2757 * from taking place in apply_patch() that follows2758 * the callchain led us here, which is:2759 * apply_patch->check_patch_list->check_patch->2760 * apply_data->apply_fragments->apply_one_fragment2761 */2762if(ws_error_action == die_on_ws_error)2763 apply =0;2764}27652766if(apply_verbosely && applied_pos != pos) {2767int offset = applied_pos - pos;2768if(apply_in_reverse)2769 offset =0- offset;2770fprintf_ln(stderr,2771Q_("Hunk #%dsucceeded at%d(offset%dline).",2772"Hunk #%dsucceeded at%d(offset%dlines).",2773 offset),2774 nth_fragment, applied_pos +1, offset);2775}27762777/*2778 * Warn if it was necessary to reduce the number2779 * of context lines.2780 */2781if((leading != frag->leading) ||2782(trailing != frag->trailing))2783fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2784" to apply fragment at%d"),2785 leading, trailing, applied_pos+1);2786update_image(img, applied_pos, &preimage, &postimage);2787}else{2788if(apply_verbosely)2789error(_("while searching for:\n%.*s"),2790(int)(old - oldlines), oldlines);2791}27922793free(oldlines);2794strbuf_release(&newlines);2795free(preimage.line_allocated);2796free(postimage.line_allocated);27972798return(applied_pos <0);2799}28002801static intapply_binary_fragment(struct image *img,struct patch *patch)2802{2803struct fragment *fragment = patch->fragments;2804unsigned long len;2805void*dst;28062807if(!fragment)2808returnerror(_("missing binary patch data for '%s'"),2809 patch->new_name ?2810 patch->new_name :2811 patch->old_name);28122813/* Binary patch is irreversible without the optional second hunk */2814if(apply_in_reverse) {2815if(!fragment->next)2816returnerror("cannot reverse-apply a binary patch "2817"without the reverse hunk to '%s'",2818 patch->new_name2819? patch->new_name : patch->old_name);2820 fragment = fragment->next;2821}2822switch(fragment->binary_patch_method) {2823case BINARY_DELTA_DEFLATED:2824 dst =patch_delta(img->buf, img->len, fragment->patch,2825 fragment->size, &len);2826if(!dst)2827return-1;2828clear_image(img);2829 img->buf = dst;2830 img->len = len;2831return0;2832case BINARY_LITERAL_DEFLATED:2833clear_image(img);2834 img->len = fragment->size;2835 img->buf =xmalloc(img->len+1);2836memcpy(img->buf, fragment->patch, img->len);2837 img->buf[img->len] ='\0';2838return0;2839}2840return-1;2841}28422843/*2844 * Replace "img" with the result of applying the binary patch.2845 * The binary patch data itself in patch->fragment is still kept2846 * but the preimage prepared by the caller in "img" is freed here2847 * or in the helper function apply_binary_fragment() this calls.2848 */2849static intapply_binary(struct image *img,struct patch *patch)2850{2851const char*name = patch->old_name ? patch->old_name : patch->new_name;2852unsigned char sha1[20];28532854/*2855 * For safety, we require patch index line to contain2856 * full 40-byte textual SHA1 for old and new, at least for now.2857 */2858if(strlen(patch->old_sha1_prefix) !=40||2859strlen(patch->new_sha1_prefix) !=40||2860get_sha1_hex(patch->old_sha1_prefix, sha1) ||2861get_sha1_hex(patch->new_sha1_prefix, sha1))2862returnerror("cannot apply binary patch to '%s' "2863"without full index line", name);28642865if(patch->old_name) {2866/*2867 * See if the old one matches what the patch2868 * applies to.2869 */2870hash_sha1_file(img->buf, img->len, blob_type, sha1);2871if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2872returnerror("the patch applies to '%s' (%s), "2873"which does not match the "2874"current contents.",2875 name,sha1_to_hex(sha1));2876}2877else{2878/* Otherwise, the old one must be empty. */2879if(img->len)2880returnerror("the patch applies to an empty "2881"'%s' but it is not empty", name);2882}28832884get_sha1_hex(patch->new_sha1_prefix, sha1);2885if(is_null_sha1(sha1)) {2886clear_image(img);2887return0;/* deletion patch */2888}28892890if(has_sha1_file(sha1)) {2891/* We already have the postimage */2892enum object_type type;2893unsigned long size;2894char*result;28952896 result =read_sha1_file(sha1, &type, &size);2897if(!result)2898returnerror("the necessary postimage%sfor "2899"'%s' cannot be read",2900 patch->new_sha1_prefix, name);2901clear_image(img);2902 img->buf = result;2903 img->len = size;2904}else{2905/*2906 * We have verified buf matches the preimage;2907 * apply the patch data to it, which is stored2908 * in the patch->fragments->{patch,size}.2909 */2910if(apply_binary_fragment(img, patch))2911returnerror(_("binary patch does not apply to '%s'"),2912 name);29132914/* verify that the result matches */2915hash_sha1_file(img->buf, img->len, blob_type, sha1);2916if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2917returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),2918 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2919}29202921return0;2922}29232924static intapply_fragments(struct image *img,struct patch *patch)2925{2926struct fragment *frag = patch->fragments;2927const char*name = patch->old_name ? patch->old_name : patch->new_name;2928unsigned ws_rule = patch->ws_rule;2929unsigned inaccurate_eof = patch->inaccurate_eof;2930int nth =0;29312932if(patch->is_binary)2933returnapply_binary(img, patch);29342935while(frag) {2936 nth++;2937if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {2938error(_("patch failed:%s:%ld"), name, frag->oldpos);2939if(!apply_with_reject)2940return-1;2941 frag->rejected =1;2942}2943 frag = frag->next;2944}2945return0;2946}29472948static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)2949{2950if(S_ISGITLINK(mode)) {2951strbuf_grow(buf,100);2952strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));2953}else{2954enum object_type type;2955unsigned long sz;2956char*result;29572958 result =read_sha1_file(sha1, &type, &sz);2959if(!result)2960return-1;2961/* XXX read_sha1_file NUL-terminates */2962strbuf_attach(buf, result, sz, sz +1);2963}2964return0;2965}29662967static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2968{2969if(!ce)2970return0;2971returnread_blob_object(buf, ce->sha1, ce->ce_mode);2972}29732974static struct patch *in_fn_table(const char*name)2975{2976struct string_list_item *item;29772978if(name == NULL)2979return NULL;29802981 item =string_list_lookup(&fn_table, name);2982if(item != NULL)2983return(struct patch *)item->util;29842985return NULL;2986}29872988/*2989 * item->util in the filename table records the status of the path.2990 * Usually it points at a patch (whose result records the contents2991 * of it after applying it), but it could be PATH_WAS_DELETED for a2992 * path that a previously applied patch has already removed, or2993 * PATH_TO_BE_DELETED for a path that a later patch would remove.2994 *2995 * The latter is needed to deal with a case where two paths A and B2996 * are swapped by first renaming A to B and then renaming B to A;2997 * moving A to B should not be prevented due to presense of B as we2998 * will remove it in a later patch.2999 */3000#define PATH_TO_BE_DELETED ((struct patch *) -2)3001#define PATH_WAS_DELETED ((struct patch *) -1)30023003static intto_be_deleted(struct patch *patch)3004{3005return patch == PATH_TO_BE_DELETED;3006}30073008static intwas_deleted(struct patch *patch)3009{3010return patch == PATH_WAS_DELETED;3011}30123013static voidadd_to_fn_table(struct patch *patch)3014{3015struct string_list_item *item;30163017/*3018 * Always add new_name unless patch is a deletion3019 * This should cover the cases for normal diffs,3020 * file creations and copies3021 */3022if(patch->new_name != NULL) {3023 item =string_list_insert(&fn_table, patch->new_name);3024 item->util = patch;3025}30263027/*3028 * store a failure on rename/deletion cases because3029 * later chunks shouldn't patch old names3030 */3031if((patch->new_name == NULL) || (patch->is_rename)) {3032 item =string_list_insert(&fn_table, patch->old_name);3033 item->util = PATH_WAS_DELETED;3034}3035}30363037static voidprepare_fn_table(struct patch *patch)3038{3039/*3040 * store information about incoming file deletion3041 */3042while(patch) {3043if((patch->new_name == NULL) || (patch->is_rename)) {3044struct string_list_item *item;3045 item =string_list_insert(&fn_table, patch->old_name);3046 item->util = PATH_TO_BE_DELETED;3047}3048 patch = patch->next;3049}3050}30513052static intcheckout_target(struct cache_entry *ce,struct stat *st)3053{3054struct checkout costate;30553056memset(&costate,0,sizeof(costate));3057 costate.base_dir ="";3058 costate.refresh_cache =1;3059if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3060returnerror(_("cannot checkout%s"), ce->name);3061return0;3062}30633064static struct patch *previous_patch(struct patch *patch,int*gone)3065{3066struct patch *previous;30673068*gone =0;3069if(patch->is_copy || patch->is_rename)3070return NULL;/* "git" patches do not depend on the order */30713072 previous =in_fn_table(patch->old_name);3073if(!previous)3074return NULL;30753076if(to_be_deleted(previous))3077return NULL;/* the deletion hasn't happened yet */30783079if(was_deleted(previous))3080*gone =1;30813082return previous;3083}30843085static intverify_index_match(struct cache_entry *ce,struct stat *st)3086{3087if(S_ISGITLINK(ce->ce_mode)) {3088if(!S_ISDIR(st->st_mode))3089return-1;3090return0;3091}3092returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3093}30943095#define SUBMODULE_PATCH_WITHOUT_INDEX 130963097static intload_patch_target(struct strbuf *buf,3098struct cache_entry *ce,3099struct stat *st,3100const char*name,3101unsigned expected_mode)3102{3103if(cached) {3104if(read_file_or_gitlink(ce, buf))3105returnerror(_("read of%sfailed"), name);3106}else if(name) {3107if(S_ISGITLINK(expected_mode)) {3108if(ce)3109returnread_file_or_gitlink(ce, buf);3110else3111return SUBMODULE_PATCH_WITHOUT_INDEX;3112}else{3113if(read_old_data(st, name, buf))3114returnerror(_("read of%sfailed"), name);3115}3116}3117return0;3118}31193120/*3121 * We are about to apply "patch"; populate the "image" with the3122 * current version we have, from the working tree or from the index,3123 * depending on the situation e.g. --cached/--index. If we are3124 * applying a non-git patch that incrementally updates the tree,3125 * we read from the result of a previous diff.3126 */3127static intload_preimage(struct image *image,3128struct patch *patch,struct stat *st,struct cache_entry *ce)3129{3130struct strbuf buf = STRBUF_INIT;3131size_t len;3132char*img;3133struct patch *previous;3134int status;31353136 previous =previous_patch(patch, &status);3137if(status)3138returnerror(_("path%shas been renamed/deleted"),3139 patch->old_name);3140if(previous) {3141/* We have a patched copy in memory; use that. */3142strbuf_add(&buf, previous->result, previous->resultsize);3143}else{3144 status =load_patch_target(&buf, ce, st,3145 patch->old_name, patch->old_mode);3146if(status <0)3147return status;3148else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3149/*3150 * There is no way to apply subproject3151 * patch without looking at the index.3152 * NEEDSWORK: shouldn't this be flagged3153 * as an error???3154 */3155free_fragment_list(patch->fragments);3156 patch->fragments = NULL;3157}else if(status) {3158returnerror(_("read of%sfailed"), patch->old_name);3159}3160}31613162 img =strbuf_detach(&buf, &len);3163prepare_image(image, img, len, !patch->is_binary);3164return0;3165}31663167static intthree_way_merge(struct image *image,3168char*path,3169const unsigned char*base,3170const unsigned char*ours,3171const unsigned char*theirs)3172{3173 mmfile_t base_file, our_file, their_file;3174 mmbuffer_t result = { NULL };3175int status;31763177read_mmblob(&base_file, base);3178read_mmblob(&our_file, ours);3179read_mmblob(&their_file, theirs);3180 status =ll_merge(&result, path,3181&base_file,"base",3182&our_file,"ours",3183&their_file,"theirs", NULL);3184free(base_file.ptr);3185free(our_file.ptr);3186free(their_file.ptr);3187if(status <0|| !result.ptr) {3188free(result.ptr);3189return-1;3190}3191clear_image(image);3192 image->buf = result.ptr;3193 image->len = result.size;31943195return status;3196}31973198/*3199 * When directly falling back to add/add three-way merge, we read from3200 * the current contents of the new_name. In no cases other than that3201 * this function will be called.3202 */3203static intload_current(struct image *image,struct patch *patch)3204{3205struct strbuf buf = STRBUF_INIT;3206int status, pos;3207size_t len;3208char*img;3209struct stat st;3210struct cache_entry *ce;3211char*name = patch->new_name;3212unsigned mode = patch->new_mode;32133214if(!patch->is_new)3215die("BUG: patch to%sis not a creation", patch->old_name);32163217 pos =cache_name_pos(name,strlen(name));3218if(pos <0)3219returnerror(_("%s: does not exist in index"), name);3220 ce = active_cache[pos];3221if(lstat(name, &st)) {3222if(errno != ENOENT)3223returnerror(_("%s:%s"), name,strerror(errno));3224if(checkout_target(ce, &st))3225return-1;3226}3227if(verify_index_match(ce, &st))3228returnerror(_("%s: does not match index"), name);32293230 status =load_patch_target(&buf, ce, &st, name, mode);3231if(status <0)3232return status;3233else if(status)3234return-1;3235 img =strbuf_detach(&buf, &len);3236prepare_image(image, img, len, !patch->is_binary);3237return0;3238}32393240static inttry_threeway(struct image *image,struct patch *patch,3241struct stat *st,struct cache_entry *ce)3242{3243unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3244struct strbuf buf = STRBUF_INIT;3245size_t len;3246int status;3247char*img;3248struct image tmp_image;32493250/* No point falling back to 3-way merge in these cases */3251if(patch->is_delete ||3252S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3253return-1;32543255/* Preimage the patch was prepared for */3256if(patch->is_new)3257write_sha1_file("",0, blob_type, pre_sha1);3258else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3259read_blob_object(&buf, pre_sha1, patch->old_mode))3260returnerror("repository lacks the necessary blob to fall back on 3-way merge.");32613262fprintf(stderr,"Falling back to three-way merge...\n");32633264 img =strbuf_detach(&buf, &len);3265prepare_image(&tmp_image, img, len,1);3266/* Apply the patch to get the post image */3267if(apply_fragments(&tmp_image, patch) <0) {3268clear_image(&tmp_image);3269return-1;3270}3271/* post_sha1[] is theirs */3272write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3273clear_image(&tmp_image);32743275/* our_sha1[] is ours */3276if(patch->is_new) {3277if(load_current(&tmp_image, patch))3278returnerror("cannot read the current contents of '%s'",3279 patch->new_name);3280}else{3281if(load_preimage(&tmp_image, patch, st, ce))3282returnerror("cannot read the current contents of '%s'",3283 patch->old_name);3284}3285write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3286clear_image(&tmp_image);32873288/* in-core three-way merge between post and our using pre as base */3289 status =three_way_merge(image, patch->new_name,3290 pre_sha1, our_sha1, post_sha1);3291if(status <0) {3292fprintf(stderr,"Failed to fall back on three-way merge...\n");3293return status;3294}32953296if(status) {3297 patch->conflicted_threeway =1;3298if(patch->is_new)3299hashclr(patch->threeway_stage[0]);3300else3301hashcpy(patch->threeway_stage[0], pre_sha1);3302hashcpy(patch->threeway_stage[1], our_sha1);3303hashcpy(patch->threeway_stage[2], post_sha1);3304fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3305}else{3306fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3307}3308return0;3309}33103311static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)3312{3313struct image image;33143315if(load_preimage(&image, patch, st, ce) <0)3316return-1;33173318if(patch->direct_to_threeway ||3319apply_fragments(&image, patch) <0) {3320/* Note: with --reject, apply_fragments() returns 0 */3321if(!threeway ||try_threeway(&image, patch, st, ce) <0)3322return-1;3323}3324 patch->result = image.buf;3325 patch->resultsize = image.len;3326add_to_fn_table(patch);3327free(image.line_allocated);33283329if(0< patch->is_delete && patch->resultsize)3330returnerror(_("removal patch leaves file contents"));33313332return0;3333}33343335/*3336 * If "patch" that we are looking at modifies or deletes what we have,3337 * we would want it not to lose any local modification we have, either3338 * in the working tree or in the index.3339 *3340 * This also decides if a non-git patch is a creation patch or a3341 * modification to an existing empty file. We do not check the state3342 * of the current tree for a creation patch in this function; the caller3343 * check_patch() separately makes sure (and errors out otherwise) that3344 * the path the patch creates does not exist in the current tree.3345 */3346static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)3347{3348const char*old_name = patch->old_name;3349struct patch *previous = NULL;3350int stat_ret =0, status;3351unsigned st_mode =0;33523353if(!old_name)3354return0;33553356assert(patch->is_new <=0);3357 previous =previous_patch(patch, &status);33583359if(status)3360returnerror(_("path%shas been renamed/deleted"), old_name);3361if(previous) {3362 st_mode = previous->new_mode;3363}else if(!cached) {3364 stat_ret =lstat(old_name, st);3365if(stat_ret && errno != ENOENT)3366returnerror(_("%s:%s"), old_name,strerror(errno));3367}33683369if(check_index && !previous) {3370int pos =cache_name_pos(old_name,strlen(old_name));3371if(pos <0) {3372if(patch->is_new <0)3373goto is_new;3374returnerror(_("%s: does not exist in index"), old_name);3375}3376*ce = active_cache[pos];3377if(stat_ret <0) {3378if(checkout_target(*ce, st))3379return-1;3380}3381if(!cached &&verify_index_match(*ce, st))3382returnerror(_("%s: does not match index"), old_name);3383if(cached)3384 st_mode = (*ce)->ce_mode;3385}else if(stat_ret <0) {3386if(patch->is_new <0)3387goto is_new;3388returnerror(_("%s:%s"), old_name,strerror(errno));3389}33903391if(!cached && !previous)3392 st_mode =ce_mode_from_stat(*ce, st->st_mode);33933394if(patch->is_new <0)3395 patch->is_new =0;3396if(!patch->old_mode)3397 patch->old_mode = st_mode;3398if((st_mode ^ patch->old_mode) & S_IFMT)3399returnerror(_("%s: wrong type"), old_name);3400if(st_mode != patch->old_mode)3401warning(_("%shas type%o, expected%o"),3402 old_name, st_mode, patch->old_mode);3403if(!patch->new_mode && !patch->is_delete)3404 patch->new_mode = st_mode;3405return0;34063407 is_new:3408 patch->is_new =1;3409 patch->is_delete =0;3410free(patch->old_name);3411 patch->old_name = NULL;3412return0;3413}341434153416#define EXISTS_IN_INDEX 13417#define EXISTS_IN_WORKTREE 234183419static intcheck_to_create(const char*new_name,int ok_if_exists)3420{3421struct stat nst;34223423if(check_index &&3424cache_name_pos(new_name,strlen(new_name)) >=0&&3425!ok_if_exists)3426return EXISTS_IN_INDEX;3427if(cached)3428return0;34293430if(!lstat(new_name, &nst)) {3431if(S_ISDIR(nst.st_mode) || ok_if_exists)3432return0;3433/*3434 * A leading component of new_name might be a symlink3435 * that is going to be removed with this patch, but3436 * still pointing at somewhere that has the path.3437 * In such a case, path "new_name" does not exist as3438 * far as git is concerned.3439 */3440if(has_symlink_leading_path(new_name,strlen(new_name)))3441return0;34423443return EXISTS_IN_WORKTREE;3444}else if((errno != ENOENT) && (errno != ENOTDIR)) {3445returnerror("%s:%s", new_name,strerror(errno));3446}3447return0;3448}34493450/*3451 * Check and apply the patch in-core; leave the result in patch->result3452 * for the caller to write it out to the final destination.3453 */3454static intcheck_patch(struct patch *patch)3455{3456struct stat st;3457const char*old_name = patch->old_name;3458const char*new_name = patch->new_name;3459const char*name = old_name ? old_name : new_name;3460struct cache_entry *ce = NULL;3461struct patch *tpatch;3462int ok_if_exists;3463int status;34643465 patch->rejected =1;/* we will drop this after we succeed */34663467 status =check_preimage(patch, &ce, &st);3468if(status)3469return status;3470 old_name = patch->old_name;34713472/*3473 * A type-change diff is always split into a patch to delete3474 * old, immediately followed by a patch to create new (see3475 * diff.c::run_diff()); in such a case it is Ok that the entry3476 * to be deleted by the previous patch is still in the working3477 * tree and in the index.3478 *3479 * A patch to swap-rename between A and B would first rename A3480 * to B and then rename B to A. While applying the first one,3481 * the presense of B should not stop A from getting renamed to3482 * B; ask to_be_deleted() about the later rename. Removal of3483 * B and rename from A to B is handled the same way by asking3484 * was_deleted().3485 */3486if((tpatch =in_fn_table(new_name)) &&3487(was_deleted(tpatch) ||to_be_deleted(tpatch)))3488 ok_if_exists =1;3489else3490 ok_if_exists =0;34913492if(new_name &&3493((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {3494int err =check_to_create(new_name, ok_if_exists);34953496if(err && threeway) {3497 patch->direct_to_threeway =1;3498}else switch(err) {3499case0:3500break;/* happy */3501case EXISTS_IN_INDEX:3502returnerror(_("%s: already exists in index"), new_name);3503break;3504case EXISTS_IN_WORKTREE:3505returnerror(_("%s: already exists in working directory"),3506 new_name);3507default:3508return err;3509}35103511if(!patch->new_mode) {3512if(0< patch->is_new)3513 patch->new_mode = S_IFREG |0644;3514else3515 patch->new_mode = patch->old_mode;3516}3517}35183519if(new_name && old_name) {3520int same = !strcmp(old_name, new_name);3521if(!patch->new_mode)3522 patch->new_mode = patch->old_mode;3523if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3524if(same)3525returnerror(_("new mode (%o) of%sdoes not "3526"match old mode (%o)"),3527 patch->new_mode, new_name,3528 patch->old_mode);3529else3530returnerror(_("new mode (%o) of%sdoes not "3531"match old mode (%o) of%s"),3532 patch->new_mode, new_name,3533 patch->old_mode, old_name);3534}3535}35363537if(apply_data(patch, &st, ce) <0)3538returnerror(_("%s: patch does not apply"), name);3539 patch->rejected =0;3540return0;3541}35423543static intcheck_patch_list(struct patch *patch)3544{3545int err =0;35463547prepare_fn_table(patch);3548while(patch) {3549if(apply_verbosely)3550say_patch_name(stderr,3551_("Checking patch%s..."), patch);3552 err |=check_patch(patch);3553 patch = patch->next;3554}3555return err;3556}35573558/* This function tries to read the sha1 from the current index */3559static intget_current_sha1(const char*path,unsigned char*sha1)3560{3561int pos;35623563if(read_cache() <0)3564return-1;3565 pos =cache_name_pos(path,strlen(path));3566if(pos <0)3567return-1;3568hashcpy(sha1, active_cache[pos]->sha1);3569return0;3570}35713572/* Build an index that contains the just the files needed for a 3way merge */3573static voidbuild_fake_ancestor(struct patch *list,const char*filename)3574{3575struct patch *patch;3576struct index_state result = { NULL };3577int fd;35783579/* Once we start supporting the reverse patch, it may be3580 * worth showing the new sha1 prefix, but until then...3581 */3582for(patch = list; patch; patch = patch->next) {3583const unsigned char*sha1_ptr;3584unsigned char sha1[20];3585struct cache_entry *ce;3586const char*name;35873588 name = patch->old_name ? patch->old_name : patch->new_name;3589if(0< patch->is_new)3590continue;3591else if(get_sha1_blob(patch->old_sha1_prefix, sha1))3592/* git diff has no index line for mode/type changes */3593if(!patch->lines_added && !patch->lines_deleted) {3594if(get_current_sha1(patch->old_name, sha1))3595die("mode change for%s, which is not "3596"in current HEAD", name);3597 sha1_ptr = sha1;3598}else3599die("sha1 information is lacking or useless "3600"(%s).", name);3601else3602 sha1_ptr = sha1;36033604 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);3605if(!ce)3606die(_("make_cache_entry failed for path '%s'"), name);3607if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3608die("Could not add%sto temporary index", name);3609}36103611 fd =open(filename, O_WRONLY | O_CREAT,0666);3612if(fd <0||write_index(&result, fd) ||close(fd))3613die("Could not write temporary index to%s", filename);36143615discard_index(&result);3616}36173618static voidstat_patch_list(struct patch *patch)3619{3620int files, adds, dels;36213622for(files = adds = dels =0; patch ; patch = patch->next) {3623 files++;3624 adds += patch->lines_added;3625 dels += patch->lines_deleted;3626show_stats(patch);3627}36283629print_stat_summary(stdout, files, adds, dels);3630}36313632static voidnumstat_patch_list(struct patch *patch)3633{3634for( ; patch; patch = patch->next) {3635const char*name;3636 name = patch->new_name ? patch->new_name : patch->old_name;3637if(patch->is_binary)3638printf("-\t-\t");3639else3640printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3641write_name_quoted(name, stdout, line_termination);3642}3643}36443645static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3646{3647if(mode)3648printf("%smode%06o%s\n", newdelete, mode, name);3649else3650printf("%s %s\n", newdelete, name);3651}36523653static voidshow_mode_change(struct patch *p,int show_name)3654{3655if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3656if(show_name)3657printf(" mode change%06o =>%06o%s\n",3658 p->old_mode, p->new_mode, p->new_name);3659else3660printf(" mode change%06o =>%06o\n",3661 p->old_mode, p->new_mode);3662}3663}36643665static voidshow_rename_copy(struct patch *p)3666{3667const char*renamecopy = p->is_rename ?"rename":"copy";3668const char*old, *new;36693670/* Find common prefix */3671 old = p->old_name;3672new= p->new_name;3673while(1) {3674const char*slash_old, *slash_new;3675 slash_old =strchr(old,'/');3676 slash_new =strchr(new,'/');3677if(!slash_old ||3678!slash_new ||3679 slash_old - old != slash_new -new||3680memcmp(old,new, slash_new -new))3681break;3682 old = slash_old +1;3683new= slash_new +1;3684}3685/* p->old_name thru old is the common prefix, and old and new3686 * through the end of names are renames3687 */3688if(old != p->old_name)3689printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,3690(int)(old - p->old_name), p->old_name,3691 old,new, p->score);3692else3693printf("%s %s=>%s(%d%%)\n", renamecopy,3694 p->old_name, p->new_name, p->score);3695show_mode_change(p,0);3696}36973698static voidsummary_patch_list(struct patch *patch)3699{3700struct patch *p;37013702for(p = patch; p; p = p->next) {3703if(p->is_new)3704show_file_mode_name("create", p->new_mode, p->new_name);3705else if(p->is_delete)3706show_file_mode_name("delete", p->old_mode, p->old_name);3707else{3708if(p->is_rename || p->is_copy)3709show_rename_copy(p);3710else{3711if(p->score) {3712printf(" rewrite%s(%d%%)\n",3713 p->new_name, p->score);3714show_mode_change(p,0);3715}3716else3717show_mode_change(p,1);3718}3719}3720}3721}37223723static voidpatch_stats(struct patch *patch)3724{3725int lines = patch->lines_added + patch->lines_deleted;37263727if(lines > max_change)3728 max_change = lines;3729if(patch->old_name) {3730int len =quote_c_style(patch->old_name, NULL, NULL,0);3731if(!len)3732 len =strlen(patch->old_name);3733if(len > max_len)3734 max_len = len;3735}3736if(patch->new_name) {3737int len =quote_c_style(patch->new_name, NULL, NULL,0);3738if(!len)3739 len =strlen(patch->new_name);3740if(len > max_len)3741 max_len = len;3742}3743}37443745static voidremove_file(struct patch *patch,int rmdir_empty)3746{3747if(update_index) {3748if(remove_file_from_cache(patch->old_name) <0)3749die(_("unable to remove%sfrom index"), patch->old_name);3750}3751if(!cached) {3752if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {3753remove_path(patch->old_name);3754}3755}3756}37573758static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)3759{3760struct stat st;3761struct cache_entry *ce;3762int namelen =strlen(path);3763unsigned ce_size =cache_entry_size(namelen);37643765if(!update_index)3766return;37673768 ce =xcalloc(1, ce_size);3769memcpy(ce->name, path, namelen);3770 ce->ce_mode =create_ce_mode(mode);3771 ce->ce_flags =create_ce_flags(0);3772 ce->ce_namelen = namelen;3773if(S_ISGITLINK(mode)) {3774const char*s = buf;37753776if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))3777die(_("corrupt patch for subproject%s"), path);3778}else{3779if(!cached) {3780if(lstat(path, &st) <0)3781die_errno(_("unable to stat newly created file '%s'"),3782 path);3783fill_stat_cache_info(ce, &st);3784}3785if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)3786die(_("unable to create backing store for newly created file%s"), path);3787}3788if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3789die(_("unable to add cache entry for%s"), path);3790}37913792static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)3793{3794int fd;3795struct strbuf nbuf = STRBUF_INIT;37963797if(S_ISGITLINK(mode)) {3798struct stat st;3799if(!lstat(path, &st) &&S_ISDIR(st.st_mode))3800return0;3801returnmkdir(path,0777);3802}38033804if(has_symlinks &&S_ISLNK(mode))3805/* Although buf:size is counted string, it also is NUL3806 * terminated.3807 */3808returnsymlink(buf, path);38093810 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);3811if(fd <0)3812return-1;38133814if(convert_to_working_tree(path, buf, size, &nbuf)) {3815 size = nbuf.len;3816 buf = nbuf.buf;3817}3818write_or_die(fd, buf, size);3819strbuf_release(&nbuf);38203821if(close(fd) <0)3822die_errno(_("closing file '%s'"), path);3823return0;3824}38253826/*3827 * We optimistically assume that the directories exist,3828 * which is true 99% of the time anyway. If they don't,3829 * we create them and try again.3830 */3831static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)3832{3833if(cached)3834return;3835if(!try_create_file(path, mode, buf, size))3836return;38373838if(errno == ENOENT) {3839if(safe_create_leading_directories(path))3840return;3841if(!try_create_file(path, mode, buf, size))3842return;3843}38443845if(errno == EEXIST || errno == EACCES) {3846/* We may be trying to create a file where a directory3847 * used to be.3848 */3849struct stat st;3850if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))3851 errno = EEXIST;3852}38533854if(errno == EEXIST) {3855unsigned int nr =getpid();38563857for(;;) {3858char newpath[PATH_MAX];3859mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);3860if(!try_create_file(newpath, mode, buf, size)) {3861if(!rename(newpath, path))3862return;3863unlink_or_warn(newpath);3864break;3865}3866if(errno != EEXIST)3867break;3868++nr;3869}3870}3871die_errno(_("unable to write file '%s' mode%o"), path, mode);3872}38733874static voidadd_conflicted_stages_file(struct patch *patch)3875{3876int stage, namelen;3877unsigned ce_size, mode;3878struct cache_entry *ce;38793880if(!update_index)3881return;3882 namelen =strlen(patch->new_name);3883 ce_size =cache_entry_size(namelen);3884 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);38853886remove_file_from_cache(patch->new_name);3887for(stage =1; stage <4; stage++) {3888if(is_null_sha1(patch->threeway_stage[stage -1]))3889continue;3890 ce =xcalloc(1, ce_size);3891memcpy(ce->name, patch->new_name, namelen);3892 ce->ce_mode =create_ce_mode(mode);3893 ce->ce_flags =create_ce_flags(stage);3894 ce->ce_namelen = namelen;3895hashcpy(ce->sha1, patch->threeway_stage[stage -1]);3896if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3897die(_("unable to add cache entry for%s"), patch->new_name);3898}3899}39003901static voidcreate_file(struct patch *patch)3902{3903char*path = patch->new_name;3904unsigned mode = patch->new_mode;3905unsigned long size = patch->resultsize;3906char*buf = patch->result;39073908if(!mode)3909 mode = S_IFREG |0644;3910create_one_file(path, mode, buf, size);39113912if(patch->conflicted_threeway)3913add_conflicted_stages_file(patch);3914else3915add_index_file(path, mode, buf, size);3916}39173918/* phase zero is to remove, phase one is to create */3919static voidwrite_out_one_result(struct patch *patch,int phase)3920{3921if(patch->is_delete >0) {3922if(phase ==0)3923remove_file(patch,1);3924return;3925}3926if(patch->is_new >0|| patch->is_copy) {3927if(phase ==1)3928create_file(patch);3929return;3930}3931/*3932 * Rename or modification boils down to the same3933 * thing: remove the old, write the new3934 */3935if(phase ==0)3936remove_file(patch, patch->is_rename);3937if(phase ==1)3938create_file(patch);3939}39403941static intwrite_out_one_reject(struct patch *patch)3942{3943FILE*rej;3944char namebuf[PATH_MAX];3945struct fragment *frag;3946int cnt =0;3947struct strbuf sb = STRBUF_INIT;39483949for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {3950if(!frag->rejected)3951continue;3952 cnt++;3953}39543955if(!cnt) {3956if(apply_verbosely)3957say_patch_name(stderr,3958_("Applied patch%scleanly."), patch);3959return0;3960}39613962/* This should not happen, because a removal patch that leaves3963 * contents are marked "rejected" at the patch level.3964 */3965if(!patch->new_name)3966die(_("internal error"));39673968/* Say this even without --verbose */3969strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",3970"Applying patch %%swith%drejects...",3971 cnt),3972 cnt);3973say_patch_name(stderr, sb.buf, patch);3974strbuf_release(&sb);39753976 cnt =strlen(patch->new_name);3977if(ARRAY_SIZE(namebuf) <= cnt +5) {3978 cnt =ARRAY_SIZE(namebuf) -5;3979warning(_("truncating .rej filename to %.*s.rej"),3980 cnt -1, patch->new_name);3981}3982memcpy(namebuf, patch->new_name, cnt);3983memcpy(namebuf + cnt,".rej",5);39843985 rej =fopen(namebuf,"w");3986if(!rej)3987returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));39883989/* Normal git tools never deal with .rej, so do not pretend3990 * this is a git patch by saying --git nor give extended3991 * headers. While at it, maybe please "kompare" that wants3992 * the trailing TAB and some garbage at the end of line ;-).3993 */3994fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",3995 patch->new_name, patch->new_name);3996for(cnt =1, frag = patch->fragments;3997 frag;3998 cnt++, frag = frag->next) {3999if(!frag->rejected) {4000fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4001continue;4002}4003fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4004fprintf(rej,"%.*s", frag->size, frag->patch);4005if(frag->patch[frag->size-1] !='\n')4006fputc('\n', rej);4007}4008fclose(rej);4009return-1;4010}40114012static intwrite_out_results(struct patch *list)4013{4014int phase;4015int errs =0;4016struct patch *l;4017struct string_list cpath = STRING_LIST_INIT_DUP;40184019for(phase =0; phase <2; phase++) {4020 l = list;4021while(l) {4022if(l->rejected)4023 errs =1;4024else{4025write_out_one_result(l, phase);4026if(phase ==1) {4027if(write_out_one_reject(l))4028 errs =1;4029if(l->conflicted_threeway) {4030string_list_append(&cpath, l->new_name);4031 errs =1;4032}4033}4034}4035 l = l->next;4036}4037}40384039if(cpath.nr) {4040struct string_list_item *item;40414042sort_string_list(&cpath);4043for_each_string_list_item(item, &cpath)4044fprintf(stderr,"U%s\n", item->string);4045string_list_clear(&cpath,0);40464047rerere(0);4048}40494050return errs;4051}40524053static struct lock_file lock_file;40544055static struct string_list limit_by_name;4056static int has_include;4057static voidadd_name_limit(const char*name,int exclude)4058{4059struct string_list_item *it;40604061 it =string_list_append(&limit_by_name, name);4062 it->util = exclude ? NULL : (void*)1;4063}40644065static intuse_patch(struct patch *p)4066{4067const char*pathname = p->new_name ? p->new_name : p->old_name;4068int i;40694070/* Paths outside are not touched regardless of "--include" */4071if(0< prefix_length) {4072int pathlen =strlen(pathname);4073if(pathlen <= prefix_length ||4074memcmp(prefix, pathname, prefix_length))4075return0;4076}40774078/* See if it matches any of exclude/include rule */4079for(i =0; i < limit_by_name.nr; i++) {4080struct string_list_item *it = &limit_by_name.items[i];4081if(!fnmatch(it->string, pathname,0))4082return(it->util != NULL);4083}40844085/*4086 * If we had any include, a path that does not match any rule is4087 * not used. Otherwise, we saw bunch of exclude rules (or none)4088 * and such a path is used.4089 */4090return!has_include;4091}409240934094static voidprefix_one(char**name)4095{4096char*old_name = *name;4097if(!old_name)4098return;4099*name =xstrdup(prefix_filename(prefix, prefix_length, *name));4100free(old_name);4101}41024103static voidprefix_patches(struct patch *p)4104{4105if(!prefix || p->is_toplevel_relative)4106return;4107for( ; p; p = p->next) {4108prefix_one(&p->new_name);4109prefix_one(&p->old_name);4110}4111}41124113#define INACCURATE_EOF (1<<0)4114#define RECOUNT (1<<1)41154116static intapply_patch(int fd,const char*filename,int options)4117{4118size_t offset;4119struct strbuf buf = STRBUF_INIT;/* owns the patch text */4120struct patch *list = NULL, **listp = &list;4121int skipped_patch =0;41224123 patch_input_file = filename;4124read_patch_file(&buf, fd);4125 offset =0;4126while(offset < buf.len) {4127struct patch *patch;4128int nr;41294130 patch =xcalloc(1,sizeof(*patch));4131 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4132 patch->recount = !!(options & RECOUNT);4133 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);4134if(nr <0)4135break;4136if(apply_in_reverse)4137reverse_patches(patch);4138if(prefix)4139prefix_patches(patch);4140if(use_patch(patch)) {4141patch_stats(patch);4142*listp = patch;4143 listp = &patch->next;4144}4145else{4146free_patch(patch);4147 skipped_patch++;4148}4149 offset += nr;4150}41514152if(!list && !skipped_patch)4153die(_("unrecognized input"));41544155if(whitespace_error && (ws_error_action == die_on_ws_error))4156 apply =0;41574158 update_index = check_index && apply;4159if(update_index && newfd <0)4160 newfd =hold_locked_index(&lock_file,1);41614162if(check_index) {4163if(read_cache() <0)4164die(_("unable to read index file"));4165}41664167if((check || apply) &&4168check_patch_list(list) <0&&4169!apply_with_reject)4170exit(1);41714172if(apply &&write_out_results(list)) {4173if(apply_with_reject)4174exit(1);4175/* with --3way, we still need to write the index out */4176return1;4177}41784179if(fake_ancestor)4180build_fake_ancestor(list, fake_ancestor);41814182if(diffstat)4183stat_patch_list(list);41844185if(numstat)4186numstat_patch_list(list);41874188if(summary)4189summary_patch_list(list);41904191free_patch_list(list);4192strbuf_release(&buf);4193string_list_clear(&fn_table,0);4194return0;4195}41964197static intgit_apply_config(const char*var,const char*value,void*cb)4198{4199if(!strcmp(var,"apply.whitespace"))4200returngit_config_string(&apply_default_whitespace, var, value);4201else if(!strcmp(var,"apply.ignorewhitespace"))4202returngit_config_string(&apply_default_ignorewhitespace, var, value);4203returngit_default_config(var, value, cb);4204}42054206static intoption_parse_exclude(const struct option *opt,4207const char*arg,int unset)4208{4209add_name_limit(arg,1);4210return0;4211}42124213static intoption_parse_include(const struct option *opt,4214const char*arg,int unset)4215{4216add_name_limit(arg,0);4217 has_include =1;4218return0;4219}42204221static intoption_parse_p(const struct option *opt,4222const char*arg,int unset)4223{4224 p_value =atoi(arg);4225 p_value_known =1;4226return0;4227}42284229static intoption_parse_z(const struct option *opt,4230const char*arg,int unset)4231{4232if(unset)4233 line_termination ='\n';4234else4235 line_termination =0;4236return0;4237}42384239static intoption_parse_space_change(const struct option *opt,4240const char*arg,int unset)4241{4242if(unset)4243 ws_ignore_action = ignore_ws_none;4244else4245 ws_ignore_action = ignore_ws_change;4246return0;4247}42484249static intoption_parse_whitespace(const struct option *opt,4250const char*arg,int unset)4251{4252const char**whitespace_option = opt->value;42534254*whitespace_option = arg;4255parse_whitespace_option(arg);4256return0;4257}42584259static intoption_parse_directory(const struct option *opt,4260const char*arg,int unset)4261{4262 root_len =strlen(arg);4263if(root_len && arg[root_len -1] !='/') {4264char*new_root;4265 root = new_root =xmalloc(root_len +2);4266strcpy(new_root, arg);4267strcpy(new_root + root_len++,"/");4268}else4269 root = arg;4270return0;4271}42724273intcmd_apply(int argc,const char**argv,const char*prefix_)4274{4275int i;4276int errs =0;4277int is_not_gitdir = !startup_info->have_repository;4278int force_apply =0;42794280const char*whitespace_option = NULL;42814282struct option builtin_apply_options[] = {4283{ OPTION_CALLBACK,0,"exclude", NULL,N_("path"),4284N_("don't apply changes matching the given path"),42850, option_parse_exclude },4286{ OPTION_CALLBACK,0,"include", NULL,N_("path"),4287N_("apply changes matching the given path"),42880, option_parse_include },4289{ OPTION_CALLBACK,'p', NULL, NULL,N_("num"),4290N_("remove <num> leading slashes from traditional diff paths"),42910, option_parse_p },4292OPT_BOOLEAN(0,"no-add", &no_add,4293N_("ignore additions made by the patch")),4294OPT_BOOLEAN(0,"stat", &diffstat,4295N_("instead of applying the patch, output diffstat for the input")),4296OPT_NOOP_NOARG(0,"allow-binary-replacement"),4297OPT_NOOP_NOARG(0,"binary"),4298OPT_BOOLEAN(0,"numstat", &numstat,4299N_("shows number of added and deleted lines in decimal notation")),4300OPT_BOOLEAN(0,"summary", &summary,4301N_("instead of applying the patch, output a summary for the input")),4302OPT_BOOLEAN(0,"check", &check,4303N_("instead of applying the patch, see if the patch is applicable")),4304OPT_BOOLEAN(0,"index", &check_index,4305N_("make sure the patch is applicable to the current index")),4306OPT_BOOLEAN(0,"cached", &cached,4307N_("apply a patch without touching the working tree")),4308OPT_BOOLEAN(0,"apply", &force_apply,4309N_("also apply the patch (use with --stat/--summary/--check)")),4310OPT_BOOL('3',"3way", &threeway,4311N_("attempt three-way merge if a patch does not apply")),4312OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,4313N_("build a temporary index based on embedded index information")),4314{ OPTION_CALLBACK,'z', NULL, NULL, NULL,4315N_("paths are separated with NUL character"),4316 PARSE_OPT_NOARG, option_parse_z },4317OPT_INTEGER('C', NULL, &p_context,4318N_("ensure at least <n> lines of context match")),4319{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,N_("action"),4320N_("detect new or modified lines that have whitespace errors"),43210, option_parse_whitespace },4322{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,4323N_("ignore changes in whitespace when finding context"),4324 PARSE_OPT_NOARG, option_parse_space_change },4325{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,4326N_("ignore changes in whitespace when finding context"),4327 PARSE_OPT_NOARG, option_parse_space_change },4328OPT_BOOLEAN('R',"reverse", &apply_in_reverse,4329N_("apply the patch in reverse")),4330OPT_BOOLEAN(0,"unidiff-zero", &unidiff_zero,4331N_("don't expect at least one line of context")),4332OPT_BOOLEAN(0,"reject", &apply_with_reject,4333N_("leave the rejected hunks in corresponding *.rej files")),4334OPT_BOOLEAN(0,"allow-overlap", &allow_overlap,4335N_("allow overlapping hunks")),4336OPT__VERBOSE(&apply_verbosely,N_("be verbose")),4337OPT_BIT(0,"inaccurate-eof", &options,4338N_("tolerate incorrectly detected missing new-line at the end of file"),4339 INACCURATE_EOF),4340OPT_BIT(0,"recount", &options,4341N_("do not trust the line counts in the hunk headers"),4342 RECOUNT),4343{ OPTION_CALLBACK,0,"directory", NULL,N_("root"),4344N_("prepend <root> to all filenames"),43450, option_parse_directory },4346OPT_END()4347};43484349 prefix = prefix_;4350 prefix_length = prefix ?strlen(prefix) :0;4351git_config(git_apply_config, NULL);4352if(apply_default_whitespace)4353parse_whitespace_option(apply_default_whitespace);4354if(apply_default_ignorewhitespace)4355parse_ignorewhitespace_option(apply_default_ignorewhitespace);43564357 argc =parse_options(argc, argv, prefix, builtin_apply_options,4358 apply_usage,0);43594360if(apply_with_reject && threeway)4361die("--reject and --3way cannot be used together.");4362if(cached && threeway)4363die("--cached and --3way cannot be used together.");4364if(threeway) {4365if(is_not_gitdir)4366die(_("--3way outside a repository"));4367 check_index =1;4368}4369if(apply_with_reject)4370 apply = apply_verbosely =1;4371if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))4372 apply =0;4373if(check_index && is_not_gitdir)4374die(_("--index outside a repository"));4375if(cached) {4376if(is_not_gitdir)4377die(_("--cached outside a repository"));4378 check_index =1;4379}4380for(i =0; i < argc; i++) {4381const char*arg = argv[i];4382int fd;43834384if(!strcmp(arg,"-")) {4385 errs |=apply_patch(0,"<stdin>", options);4386 read_stdin =0;4387continue;4388}else if(0< prefix_length)4389 arg =prefix_filename(prefix, prefix_length, arg);43904391 fd =open(arg, O_RDONLY);4392if(fd <0)4393die_errno(_("can't open patch '%s'"), arg);4394 read_stdin =0;4395set_default_whitespace_mode(whitespace_option);4396 errs |=apply_patch(fd, arg, options);4397close(fd);4398}4399set_default_whitespace_mode(whitespace_option);4400if(read_stdin)4401 errs |=apply_patch(0,"<stdin>", options);4402if(whitespace_error) {4403if(squelch_whitespace_errors &&4404 squelch_whitespace_errors < whitespace_error) {4405int squelched =4406 whitespace_error - squelch_whitespace_errors;4407warning(Q_("squelched%dwhitespace error",4408"squelched%dwhitespace errors",4409 squelched),4410 squelched);4411}4412if(ws_error_action == die_on_ws_error)4413die(Q_("%dline adds whitespace errors.",4414"%dlines add whitespace errors.",4415 whitespace_error),4416 whitespace_error);4417if(applied_after_fixing_ws && apply)4418warning("%dline%sapplied after"4419" fixing whitespace errors.",4420 applied_after_fixing_ws,4421 applied_after_fixing_ws ==1?"":"s");4422else if(whitespace_error)4423warning(Q_("%dline adds whitespace errors.",4424"%dlines add whitespace errors.",4425 whitespace_error),4426 whitespace_error);4427}44284429if(update_index) {4430if(write_cache(newfd, active_cache, active_nr) ||4431commit_locked_index(&lock_file))4432die(_("Unable to write new index file"));4433}44344435return!!errs;4436}