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"parse-options.h" 18 19/* 20 * --check turns on checking that the working tree matches the 21 * files that are being modified, but doesn't apply the patch 22 * --stat does just a diffstat, and doesn't actually apply 23 * --numstat does numeric diffstat, and doesn't actually apply 24 * --index-info shows the old and new index info for paths if available. 25 * --index updates the cache as well. 26 * --cached updates only the cache without ever touching the working tree. 27 */ 28static const char*prefix; 29static int prefix_length = -1; 30static int newfd = -1; 31 32static int unidiff_zero; 33static int p_value =1; 34static int p_value_known; 35static int check_index; 36static int update_index; 37static int cached; 38static int diffstat; 39static int numstat; 40static int summary; 41static int check; 42static int apply =1; 43static int apply_in_reverse; 44static int apply_with_reject; 45static int apply_verbosely; 46static int allow_overlap; 47static int no_add; 48static const char*fake_ancestor; 49static int line_termination ='\n'; 50static unsigned int p_context = UINT_MAX; 51static const char*const apply_usage[] = { 52"git apply [options] [<patch>...]", 53 NULL 54}; 55 56static enum ws_error_action { 57 nowarn_ws_error, 58 warn_on_ws_error, 59 die_on_ws_error, 60 correct_ws_error 61} ws_error_action = warn_on_ws_error; 62static int whitespace_error; 63static int squelch_whitespace_errors =5; 64static int applied_after_fixing_ws; 65 66static enum ws_ignore { 67 ignore_ws_none, 68 ignore_ws_change 69} ws_ignore_action = ignore_ws_none; 70 71 72static const char*patch_input_file; 73static const char*root; 74static int root_len; 75static int read_stdin =1; 76static int options; 77 78static voidparse_whitespace_option(const char*option) 79{ 80if(!option) { 81 ws_error_action = warn_on_ws_error; 82return; 83} 84if(!strcmp(option,"warn")) { 85 ws_error_action = warn_on_ws_error; 86return; 87} 88if(!strcmp(option,"nowarn")) { 89 ws_error_action = nowarn_ws_error; 90return; 91} 92if(!strcmp(option,"error")) { 93 ws_error_action = die_on_ws_error; 94return; 95} 96if(!strcmp(option,"error-all")) { 97 ws_error_action = die_on_ws_error; 98 squelch_whitespace_errors =0; 99return; 100} 101if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 102 ws_error_action = correct_ws_error; 103return; 104} 105die("unrecognized whitespace option '%s'", option); 106} 107 108static voidparse_ignorewhitespace_option(const char*option) 109{ 110if(!option || !strcmp(option,"no") || 111!strcmp(option,"false") || !strcmp(option,"never") || 112!strcmp(option,"none")) { 113 ws_ignore_action = ignore_ws_none; 114return; 115} 116if(!strcmp(option,"change")) { 117 ws_ignore_action = ignore_ws_change; 118return; 119} 120die("unrecognized whitespace ignore option '%s'", option); 121} 122 123static voidset_default_whitespace_mode(const char*whitespace_option) 124{ 125if(!whitespace_option && !apply_default_whitespace) 126 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 127} 128 129/* 130 * For "diff-stat" like behaviour, we keep track of the biggest change 131 * we've seen, and the longest filename. That allows us to do simple 132 * scaling. 133 */ 134static int max_change, max_len; 135 136/* 137 * Various "current state", notably line numbers and what 138 * file (and how) we're patching right now.. The "is_xxxx" 139 * things are flags, where -1 means "don't know yet". 140 */ 141static int linenr =1; 142 143/* 144 * This represents one "hunk" from a patch, starting with 145 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 146 * patch text is pointed at by patch, and its byte length 147 * is stored in size. leading and trailing are the number 148 * of context lines. 149 */ 150struct fragment { 151unsigned long leading, trailing; 152unsigned long oldpos, oldlines; 153unsigned long newpos, newlines; 154const char*patch; 155int size; 156int rejected; 157int linenr; 158struct fragment *next; 159}; 160 161/* 162 * When dealing with a binary patch, we reuse "leading" field 163 * to store the type of the binary hunk, either deflated "delta" 164 * or deflated "literal". 165 */ 166#define binary_patch_method leading 167#define BINARY_DELTA_DEFLATED 1 168#define BINARY_LITERAL_DEFLATED 2 169 170/* 171 * This represents a "patch" to a file, both metainfo changes 172 * such as creation/deletion, filemode and content changes represented 173 * as a series of fragments. 174 */ 175struct patch { 176char*new_name, *old_name, *def_name; 177unsigned int old_mode, new_mode; 178int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 179int rejected; 180unsigned ws_rule; 181unsigned long deflate_origlen; 182int lines_added, lines_deleted; 183int score; 184unsigned int is_toplevel_relative:1; 185unsigned int inaccurate_eof:1; 186unsigned int is_binary:1; 187unsigned int is_copy:1; 188unsigned int is_rename:1; 189unsigned int recount:1; 190struct fragment *fragments; 191char*result; 192size_t resultsize; 193char old_sha1_prefix[41]; 194char new_sha1_prefix[41]; 195struct patch *next; 196}; 197 198/* 199 * A line in a file, len-bytes long (includes the terminating LF, 200 * except for an incomplete line at the end if the file ends with 201 * one), and its contents hashes to 'hash'. 202 */ 203struct line { 204size_t len; 205unsigned hash :24; 206unsigned flag :8; 207#define LINE_COMMON 1 208#define LINE_PATCHED 2 209}; 210 211/* 212 * This represents a "file", which is an array of "lines". 213 */ 214struct image { 215char*buf; 216size_t len; 217size_t nr; 218size_t alloc; 219struct line *line_allocated; 220struct line *line; 221}; 222 223/* 224 * Records filenames that have been touched, in order to handle 225 * the case where more than one patches touch the same file. 226 */ 227 228static struct string_list fn_table; 229 230static uint32_thash_line(const char*cp,size_t len) 231{ 232size_t i; 233uint32_t h; 234for(i =0, h =0; i < len; i++) { 235if(!isspace(cp[i])) { 236 h = h *3+ (cp[i] &0xff); 237} 238} 239return h; 240} 241 242/* 243 * Compare lines s1 of length n1 and s2 of length n2, ignoring 244 * whitespace difference. Returns 1 if they match, 0 otherwise 245 */ 246static intfuzzy_matchlines(const char*s1,size_t n1, 247const char*s2,size_t n2) 248{ 249const char*last1 = s1 + n1 -1; 250const char*last2 = s2 + n2 -1; 251int result =0; 252 253/* ignore line endings */ 254while((*last1 =='\r') || (*last1 =='\n')) 255 last1--; 256while((*last2 =='\r') || (*last2 =='\n')) 257 last2--; 258 259/* skip leading whitespace */ 260while(isspace(*s1) && (s1 <= last1)) 261 s1++; 262while(isspace(*s2) && (s2 <= last2)) 263 s2++; 264/* early return if both lines are empty */ 265if((s1 > last1) && (s2 > last2)) 266return1; 267while(!result) { 268 result = *s1++ - *s2++; 269/* 270 * Skip whitespace inside. We check for whitespace on 271 * both buffers because we don't want "a b" to match 272 * "ab" 273 */ 274if(isspace(*s1) &&isspace(*s2)) { 275while(isspace(*s1) && s1 <= last1) 276 s1++; 277while(isspace(*s2) && s2 <= last2) 278 s2++; 279} 280/* 281 * If we reached the end on one side only, 282 * lines don't match 283 */ 284if( 285((s2 > last2) && (s1 <= last1)) || 286((s1 > last1) && (s2 <= last2))) 287return0; 288if((s1 > last1) && (s2 > last2)) 289break; 290} 291 292return!result; 293} 294 295static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 296{ 297ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 298 img->line_allocated[img->nr].len = len; 299 img->line_allocated[img->nr].hash =hash_line(bol, len); 300 img->line_allocated[img->nr].flag = flag; 301 img->nr++; 302} 303 304static voidprepare_image(struct image *image,char*buf,size_t len, 305int prepare_linetable) 306{ 307const char*cp, *ep; 308 309memset(image,0,sizeof(*image)); 310 image->buf = buf; 311 image->len = len; 312 313if(!prepare_linetable) 314return; 315 316 ep = image->buf + image->len; 317 cp = image->buf; 318while(cp < ep) { 319const char*next; 320for(next = cp; next < ep && *next !='\n'; next++) 321; 322if(next < ep) 323 next++; 324add_line_info(image, cp, next - cp,0); 325 cp = next; 326} 327 image->line = image->line_allocated; 328} 329 330static voidclear_image(struct image *image) 331{ 332free(image->buf); 333 image->buf = NULL; 334 image->len =0; 335} 336 337static voidsay_patch_name(FILE*output,const char*pre, 338struct patch *patch,const char*post) 339{ 340fputs(pre, output); 341if(patch->old_name && patch->new_name && 342strcmp(patch->old_name, patch->new_name)) { 343quote_c_style(patch->old_name, NULL, output,0); 344fputs(" => ", output); 345quote_c_style(patch->new_name, NULL, output,0); 346}else{ 347const char*n = patch->new_name; 348if(!n) 349 n = patch->old_name; 350quote_c_style(n, NULL, output,0); 351} 352fputs(post, output); 353} 354 355#define CHUNKSIZE (8192) 356#define SLOP (16) 357 358static voidread_patch_file(struct strbuf *sb,int fd) 359{ 360if(strbuf_read(sb, fd,0) <0) 361die_errno("git apply: failed to read"); 362 363/* 364 * Make sure that we have some slop in the buffer 365 * so that we can do speculative "memcmp" etc, and 366 * see to it that it is NUL-filled. 367 */ 368strbuf_grow(sb, SLOP); 369memset(sb->buf + sb->len,0, SLOP); 370} 371 372static unsigned longlinelen(const char*buffer,unsigned long size) 373{ 374unsigned long len =0; 375while(size--) { 376 len++; 377if(*buffer++ =='\n') 378break; 379} 380return len; 381} 382 383static intis_dev_null(const char*str) 384{ 385return!memcmp("/dev/null", str,9) &&isspace(str[9]); 386} 387 388#define TERM_SPACE 1 389#define TERM_TAB 2 390 391static intname_terminate(const char*name,int namelen,int c,int terminate) 392{ 393if(c ==' '&& !(terminate & TERM_SPACE)) 394return0; 395if(c =='\t'&& !(terminate & TERM_TAB)) 396return0; 397 398return1; 399} 400 401/* remove double slashes to make --index work with such filenames */ 402static char*squash_slash(char*name) 403{ 404int i =0, j =0; 405 406if(!name) 407return NULL; 408 409while(name[i]) { 410if((name[j++] = name[i++]) =='/') 411while(name[i] =='/') 412 i++; 413} 414 name[j] ='\0'; 415return name; 416} 417 418static char*find_name_gnu(const char*line,char*def,int p_value) 419{ 420struct strbuf name = STRBUF_INIT; 421char*cp; 422 423/* 424 * Proposed "new-style" GNU patch/diff format; see 425 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2 426 */ 427if(unquote_c_style(&name, line, NULL)) { 428strbuf_release(&name); 429return NULL; 430} 431 432for(cp = name.buf; p_value; p_value--) { 433 cp =strchr(cp,'/'); 434if(!cp) { 435strbuf_release(&name); 436return NULL; 437} 438 cp++; 439} 440 441/* name can later be freed, so we need 442 * to memmove, not just return cp 443 */ 444strbuf_remove(&name,0, cp - name.buf); 445free(def); 446if(root) 447strbuf_insert(&name,0, root, root_len); 448returnsquash_slash(strbuf_detach(&name, NULL)); 449} 450 451static size_tsane_tz_len(const char*line,size_t len) 452{ 453const char*tz, *p; 454 455if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 456return0; 457 tz = line + len -strlen(" +0500"); 458 459if(tz[1] !='+'&& tz[1] !='-') 460return0; 461 462for(p = tz +2; p != line + len; p++) 463if(!isdigit(*p)) 464return0; 465 466return line + len - tz; 467} 468 469static size_ttz_with_colon_len(const char*line,size_t len) 470{ 471const char*tz, *p; 472 473if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 474return0; 475 tz = line + len -strlen(" +08:00"); 476 477if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 478return0; 479 p = tz +2; 480if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 481!isdigit(*p++) || !isdigit(*p++)) 482return0; 483 484return line + len - tz; 485} 486 487static size_tdate_len(const char*line,size_t len) 488{ 489const char*date, *p; 490 491if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 492return0; 493 p = date = line + len -strlen("72-02-05"); 494 495if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 496!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 497!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 498return0; 499 500if(date - line >=strlen("19") && 501isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 502 date -=strlen("19"); 503 504return line + len - date; 505} 506 507static size_tshort_time_len(const char*line,size_t len) 508{ 509const char*time, *p; 510 511if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 512return0; 513 p = time = line + len -strlen(" 07:01:32"); 514 515/* Permit 1-digit hours? */ 516if(*p++ !=' '|| 517!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 518!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 519!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 520return0; 521 522return line + len - time; 523} 524 525static size_tfractional_time_len(const char*line,size_t len) 526{ 527const char*p; 528size_t n; 529 530/* Expected format: 19:41:17.620000023 */ 531if(!len || !isdigit(line[len -1])) 532return0; 533 p = line + len -1; 534 535/* Fractional seconds. */ 536while(p > line &&isdigit(*p)) 537 p--; 538if(*p !='.') 539return0; 540 541/* Hours, minutes, and whole seconds. */ 542 n =short_time_len(line, p - line); 543if(!n) 544return0; 545 546return line + len - p + n; 547} 548 549static size_ttrailing_spaces_len(const char*line,size_t len) 550{ 551const char*p; 552 553/* Expected format: ' ' x (1 or more) */ 554if(!len || line[len -1] !=' ') 555return0; 556 557 p = line + len; 558while(p != line) { 559 p--; 560if(*p !=' ') 561return line + len - (p +1); 562} 563 564/* All spaces! */ 565return len; 566} 567 568static size_tdiff_timestamp_len(const char*line,size_t len) 569{ 570const char*end = line + len; 571size_t n; 572 573/* 574 * Posix: 2010-07-05 19:41:17 575 * GNU: 2010-07-05 19:41:17.620000023 -0500 576 */ 577 578if(!isdigit(end[-1])) 579return0; 580 581 n =sane_tz_len(line, end - line); 582if(!n) 583 n =tz_with_colon_len(line, end - line); 584 end -= n; 585 586 n =short_time_len(line, end - line); 587if(!n) 588 n =fractional_time_len(line, end - line); 589 end -= n; 590 591 n =date_len(line, end - line); 592if(!n)/* No date. Too bad. */ 593return0; 594 end -= n; 595 596if(end == line)/* No space before date. */ 597return0; 598if(end[-1] =='\t') {/* Success! */ 599 end--; 600return line + len - end; 601} 602if(end[-1] !=' ')/* No space before date. */ 603return0; 604 605/* Whitespace damage. */ 606 end -=trailing_spaces_len(line, end - line); 607return line + len - end; 608} 609 610static char*find_name_common(const char*line,char*def,int p_value, 611const char*end,int terminate) 612{ 613int len; 614const char*start = NULL; 615 616if(p_value ==0) 617 start = line; 618while(line != end) { 619char c = *line; 620 621if(!end &&isspace(c)) { 622if(c =='\n') 623break; 624if(name_terminate(start, line-start, c, terminate)) 625break; 626} 627 line++; 628if(c =='/'&& !--p_value) 629 start = line; 630} 631if(!start) 632returnsquash_slash(def); 633 len = line - start; 634if(!len) 635returnsquash_slash(def); 636 637/* 638 * Generally we prefer the shorter name, especially 639 * if the other one is just a variation of that with 640 * something else tacked on to the end (ie "file.orig" 641 * or "file~"). 642 */ 643if(def) { 644int deflen =strlen(def); 645if(deflen < len && !strncmp(start, def, deflen)) 646returnsquash_slash(def); 647free(def); 648} 649 650if(root) { 651char*ret =xmalloc(root_len + len +1); 652strcpy(ret, root); 653memcpy(ret + root_len, start, len); 654 ret[root_len + len] ='\0'; 655returnsquash_slash(ret); 656} 657 658returnsquash_slash(xmemdupz(start, len)); 659} 660 661static char*find_name(const char*line,char*def,int p_value,int terminate) 662{ 663if(*line =='"') { 664char*name =find_name_gnu(line, def, p_value); 665if(name) 666return name; 667} 668 669returnfind_name_common(line, def, p_value, NULL, terminate); 670} 671 672static char*find_name_traditional(const char*line,char*def,int p_value) 673{ 674size_t len =strlen(line); 675size_t date_len; 676 677if(*line =='"') { 678char*name =find_name_gnu(line, def, p_value); 679if(name) 680return name; 681} 682 683 len =strchrnul(line,'\n') - line; 684 date_len =diff_timestamp_len(line, len); 685if(!date_len) 686returnfind_name_common(line, def, p_value, NULL, TERM_TAB); 687 len -= date_len; 688 689returnfind_name_common(line, def, p_value, line + len,0); 690} 691 692static intcount_slashes(const char*cp) 693{ 694int cnt =0; 695char ch; 696 697while((ch = *cp++)) 698if(ch =='/') 699 cnt++; 700return cnt; 701} 702 703/* 704 * Given the string after "--- " or "+++ ", guess the appropriate 705 * p_value for the given patch. 706 */ 707static intguess_p_value(const char*nameline) 708{ 709char*name, *cp; 710int val = -1; 711 712if(is_dev_null(nameline)) 713return-1; 714 name =find_name_traditional(nameline, NULL,0); 715if(!name) 716return-1; 717 cp =strchr(name,'/'); 718if(!cp) 719 val =0; 720else if(prefix) { 721/* 722 * Does it begin with "a/$our-prefix" and such? Then this is 723 * very likely to apply to our directory. 724 */ 725if(!strncmp(name, prefix, prefix_length)) 726 val =count_slashes(prefix); 727else{ 728 cp++; 729if(!strncmp(cp, prefix, prefix_length)) 730 val =count_slashes(prefix) +1; 731} 732} 733free(name); 734return val; 735} 736 737/* 738 * Does the ---/+++ line has the POSIX timestamp after the last HT? 739 * GNU diff puts epoch there to signal a creation/deletion event. Is 740 * this such a timestamp? 741 */ 742static inthas_epoch_timestamp(const char*nameline) 743{ 744/* 745 * We are only interested in epoch timestamp; any non-zero 746 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 747 * For the same reason, the date must be either 1969-12-31 or 748 * 1970-01-01, and the seconds part must be "00". 749 */ 750const char stamp_regexp[] = 751"^(1969-12-31|1970-01-01)" 752" " 753"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 754" " 755"([-+][0-2][0-9]:?[0-5][0-9])\n"; 756const char*timestamp = NULL, *cp, *colon; 757static regex_t *stamp; 758 regmatch_t m[10]; 759int zoneoffset; 760int hourminute; 761int status; 762 763for(cp = nameline; *cp !='\n'; cp++) { 764if(*cp =='\t') 765 timestamp = cp +1; 766} 767if(!timestamp) 768return0; 769if(!stamp) { 770 stamp =xmalloc(sizeof(*stamp)); 771if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 772warning("Cannot prepare timestamp regexp%s", 773 stamp_regexp); 774return0; 775} 776} 777 778 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 779if(status) { 780if(status != REG_NOMATCH) 781warning("regexec returned%dfor input:%s", 782 status, timestamp); 783return0; 784} 785 786 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 787if(*colon ==':') 788 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 789else 790 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 791if(timestamp[m[3].rm_so] =='-') 792 zoneoffset = -zoneoffset; 793 794/* 795 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 796 * (west of GMT) or 1970-01-01 (east of GMT) 797 */ 798if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 799(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 800return0; 801 802 hourminute = (strtol(timestamp +11, NULL,10) *60+ 803strtol(timestamp +14, NULL,10) - 804 zoneoffset); 805 806return((zoneoffset <0&& hourminute ==1440) || 807(0<= zoneoffset && !hourminute)); 808} 809 810/* 811 * Get the name etc info from the ---/+++ lines of a traditional patch header 812 * 813 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 814 * files, we can happily check the index for a match, but for creating a 815 * new file we should try to match whatever "patch" does. I have no idea. 816 */ 817static voidparse_traditional_patch(const char*first,const char*second,struct patch *patch) 818{ 819char*name; 820 821 first +=4;/* skip "--- " */ 822 second +=4;/* skip "+++ " */ 823if(!p_value_known) { 824int p, q; 825 p =guess_p_value(first); 826 q =guess_p_value(second); 827if(p <0) p = q; 828if(0<= p && p == q) { 829 p_value = p; 830 p_value_known =1; 831} 832} 833if(is_dev_null(first)) { 834 patch->is_new =1; 835 patch->is_delete =0; 836 name =find_name_traditional(second, NULL, p_value); 837 patch->new_name = name; 838}else if(is_dev_null(second)) { 839 patch->is_new =0; 840 patch->is_delete =1; 841 name =find_name_traditional(first, NULL, p_value); 842 patch->old_name = name; 843}else{ 844 name =find_name_traditional(first, NULL, p_value); 845 name =find_name_traditional(second, name, p_value); 846if(has_epoch_timestamp(first)) { 847 patch->is_new =1; 848 patch->is_delete =0; 849 patch->new_name = name; 850}else if(has_epoch_timestamp(second)) { 851 patch->is_new =0; 852 patch->is_delete =1; 853 patch->old_name = name; 854}else{ 855 patch->old_name = patch->new_name = name; 856} 857} 858if(!name) 859die("unable to find filename in patch at line%d", linenr); 860} 861 862static intgitdiff_hdrend(const char*line,struct patch *patch) 863{ 864return-1; 865} 866 867/* 868 * We're anal about diff header consistency, to make 869 * sure that we don't end up having strange ambiguous 870 * patches floating around. 871 * 872 * As a result, gitdiff_{old|new}name() will check 873 * their names against any previous information, just 874 * to make sure.. 875 */ 876static char*gitdiff_verify_name(const char*line,int isnull,char*orig_name,const char*oldnew) 877{ 878if(!orig_name && !isnull) 879returnfind_name(line, NULL, p_value, TERM_TAB); 880 881if(orig_name) { 882int len; 883const char*name; 884char*another; 885 name = orig_name; 886 len =strlen(name); 887if(isnull) 888die("git apply: bad git-diff - expected /dev/null, got%son line%d", name, linenr); 889 another =find_name(line, NULL, p_value, TERM_TAB); 890if(!another ||memcmp(another, name, len +1)) 891die("git apply: bad git-diff - inconsistent%sfilename on line%d", oldnew, linenr); 892free(another); 893return orig_name; 894} 895else{ 896/* expect "/dev/null" */ 897if(memcmp("/dev/null", line,9) || line[9] !='\n') 898die("git apply: bad git-diff - expected /dev/null on line%d", linenr); 899return NULL; 900} 901} 902 903static intgitdiff_oldname(const char*line,struct patch *patch) 904{ 905 patch->old_name =gitdiff_verify_name(line, patch->is_new, patch->old_name,"old"); 906return0; 907} 908 909static intgitdiff_newname(const char*line,struct patch *patch) 910{ 911 patch->new_name =gitdiff_verify_name(line, patch->is_delete, patch->new_name,"new"); 912return0; 913} 914 915static intgitdiff_oldmode(const char*line,struct patch *patch) 916{ 917 patch->old_mode =strtoul(line, NULL,8); 918return0; 919} 920 921static intgitdiff_newmode(const char*line,struct patch *patch) 922{ 923 patch->new_mode =strtoul(line, NULL,8); 924return0; 925} 926 927static intgitdiff_delete(const char*line,struct patch *patch) 928{ 929 patch->is_delete =1; 930 patch->old_name = patch->def_name; 931returngitdiff_oldmode(line, patch); 932} 933 934static intgitdiff_newfile(const char*line,struct patch *patch) 935{ 936 patch->is_new =1; 937 patch->new_name = patch->def_name; 938returngitdiff_newmode(line, patch); 939} 940 941static intgitdiff_copysrc(const char*line,struct patch *patch) 942{ 943 patch->is_copy =1; 944 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0); 945return0; 946} 947 948static intgitdiff_copydst(const char*line,struct patch *patch) 949{ 950 patch->is_copy =1; 951 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0); 952return0; 953} 954 955static intgitdiff_renamesrc(const char*line,struct patch *patch) 956{ 957 patch->is_rename =1; 958 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0); 959return0; 960} 961 962static intgitdiff_renamedst(const char*line,struct patch *patch) 963{ 964 patch->is_rename =1; 965 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0); 966return0; 967} 968 969static intgitdiff_similarity(const char*line,struct patch *patch) 970{ 971if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 972 patch->score =0; 973return0; 974} 975 976static intgitdiff_dissimilarity(const char*line,struct patch *patch) 977{ 978if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 979 patch->score =0; 980return0; 981} 982 983static intgitdiff_index(const char*line,struct patch *patch) 984{ 985/* 986 * index line is N hexadecimal, "..", N hexadecimal, 987 * and optional space with octal mode. 988 */ 989const char*ptr, *eol; 990int len; 991 992 ptr =strchr(line,'.'); 993if(!ptr || ptr[1] !='.'||40< ptr - line) 994return0; 995 len = ptr - line; 996memcpy(patch->old_sha1_prefix, line, len); 997 patch->old_sha1_prefix[len] =0; 998 999 line = ptr +2;1000 ptr =strchr(line,' ');1001 eol =strchr(line,'\n');10021003if(!ptr || eol < ptr)1004 ptr = eol;1005 len = ptr - line;10061007if(40< len)1008return0;1009memcpy(patch->new_sha1_prefix, line, len);1010 patch->new_sha1_prefix[len] =0;1011if(*ptr ==' ')1012 patch->old_mode =strtoul(ptr+1, NULL,8);1013return0;1014}10151016/*1017 * This is normal for a diff that doesn't change anything: we'll fall through1018 * into the next diff. Tell the parser to break out.1019 */1020static intgitdiff_unrecognized(const char*line,struct patch *patch)1021{1022return-1;1023}10241025/*1026 * Skip p_value leading components from "line"; as we do not accept1027 * absolute paths, return NULL in that case.1028 */1029static const char*skip_tree_prefix(const char*line,int llen)1030{1031int nslash;1032int i;10331034if(!p_value)1035return(llen && line[0] =='/') ? NULL : line;10361037 nslash = p_value;1038for(i =0; i < llen; i++) {1039int ch = line[i];1040if(ch =='/'&& --nslash <=0)1041return(i ==0) ? NULL : &line[i +1];1042}1043return NULL;1044}10451046/*1047 * This is to extract the same name that appears on "diff --git"1048 * line. We do not find and return anything if it is a rename1049 * patch, and it is OK because we will find the name elsewhere.1050 * We need to reliably find name only when it is mode-change only,1051 * creation or deletion of an empty file. In any of these cases,1052 * both sides are the same name under a/ and b/ respectively.1053 */1054static char*git_header_name(char*line,int llen)1055{1056const char*name;1057const char*second = NULL;1058size_t len, line_len;10591060 line +=strlen("diff --git ");1061 llen -=strlen("diff --git ");10621063if(*line =='"') {1064const char*cp;1065struct strbuf first = STRBUF_INIT;1066struct strbuf sp = STRBUF_INIT;10671068if(unquote_c_style(&first, line, &second))1069goto free_and_fail1;10701071/* strip the a/b prefix including trailing slash */1072 cp =skip_tree_prefix(first.buf, first.len);1073if(!cp)1074goto free_and_fail1;1075strbuf_remove(&first,0, cp - first.buf);10761077/*1078 * second points at one past closing dq of name.1079 * find the second name.1080 */1081while((second < line + llen) &&isspace(*second))1082 second++;10831084if(line + llen <= second)1085goto free_and_fail1;1086if(*second =='"') {1087if(unquote_c_style(&sp, second, NULL))1088goto free_and_fail1;1089 cp =skip_tree_prefix(sp.buf, sp.len);1090if(!cp)1091goto free_and_fail1;1092/* They must match, otherwise ignore */1093if(strcmp(cp, first.buf))1094goto free_and_fail1;1095strbuf_release(&sp);1096returnstrbuf_detach(&first, NULL);1097}10981099/* unquoted second */1100 cp =skip_tree_prefix(second, line + llen - second);1101if(!cp)1102goto free_and_fail1;1103if(line + llen - cp != first.len ||1104memcmp(first.buf, cp, first.len))1105goto free_and_fail1;1106returnstrbuf_detach(&first, NULL);11071108 free_and_fail1:1109strbuf_release(&first);1110strbuf_release(&sp);1111return NULL;1112}11131114/* unquoted first name */1115 name =skip_tree_prefix(line, llen);1116if(!name)1117return NULL;11181119/*1120 * since the first name is unquoted, a dq if exists must be1121 * the beginning of the second name.1122 */1123for(second = name; second < line + llen; second++) {1124if(*second =='"') {1125struct strbuf sp = STRBUF_INIT;1126const char*np;11271128if(unquote_c_style(&sp, second, NULL))1129goto free_and_fail2;11301131 np =skip_tree_prefix(sp.buf, sp.len);1132if(!np)1133goto free_and_fail2;11341135 len = sp.buf + sp.len - np;1136if(len < second - name &&1137!strncmp(np, name, len) &&1138isspace(name[len])) {1139/* Good */1140strbuf_remove(&sp,0, np - sp.buf);1141returnstrbuf_detach(&sp, NULL);1142}11431144 free_and_fail2:1145strbuf_release(&sp);1146return NULL;1147}1148}11491150/*1151 * Accept a name only if it shows up twice, exactly the same1152 * form.1153 */1154 second =strchr(name,'\n');1155if(!second)1156return NULL;1157 line_len = second - name;1158for(len =0; ; len++) {1159switch(name[len]) {1160default:1161continue;1162case'\n':1163return NULL;1164case'\t':case' ':1165/*1166 * Is this the separator between the preimage1167 * and the postimage pathname? Again, we are1168 * only interested in the case where there is1169 * no rename, as this is only to set def_name1170 * and a rename patch has the names elsewhere1171 * in an unambiguous form.1172 */1173if(!name[len +1])1174return NULL;/* no postimage name */1175 second =skip_tree_prefix(name + len +1,1176 line_len - (len +1));1177if(!second)1178return NULL;1179/*1180 * Does len bytes starting at "name" and "second"1181 * (that are separated by one HT or SP we just1182 * found) exactly match?1183 */1184if(second[len] =='\n'&& !strncmp(name, second, len))1185returnxmemdupz(name, len);1186}1187}1188}11891190/* Verify that we recognize the lines following a git header */1191static intparse_git_header(char*line,int len,unsigned int size,struct patch *patch)1192{1193unsigned long offset;11941195/* A git diff has explicit new/delete information, so we don't guess */1196 patch->is_new =0;1197 patch->is_delete =0;11981199/*1200 * Some things may not have the old name in the1201 * rest of the headers anywhere (pure mode changes,1202 * or removing or adding empty files), so we get1203 * the default name from the header.1204 */1205 patch->def_name =git_header_name(line, len);1206if(patch->def_name && root) {1207char*s =xmalloc(root_len +strlen(patch->def_name) +1);1208strcpy(s, root);1209strcpy(s + root_len, patch->def_name);1210free(patch->def_name);1211 patch->def_name = s;1212}12131214 line += len;1215 size -= len;1216 linenr++;1217for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) {1218static const struct opentry {1219const char*str;1220int(*fn)(const char*,struct patch *);1221} optable[] = {1222{"@@ -", gitdiff_hdrend },1223{"--- ", gitdiff_oldname },1224{"+++ ", gitdiff_newname },1225{"old mode ", gitdiff_oldmode },1226{"new mode ", gitdiff_newmode },1227{"deleted file mode ", gitdiff_delete },1228{"new file mode ", gitdiff_newfile },1229{"copy from ", gitdiff_copysrc },1230{"copy to ", gitdiff_copydst },1231{"rename old ", gitdiff_renamesrc },1232{"rename new ", gitdiff_renamedst },1233{"rename from ", gitdiff_renamesrc },1234{"rename to ", gitdiff_renamedst },1235{"similarity index ", gitdiff_similarity },1236{"dissimilarity index ", gitdiff_dissimilarity },1237{"index ", gitdiff_index },1238{"", gitdiff_unrecognized },1239};1240int i;12411242 len =linelen(line, size);1243if(!len || line[len-1] !='\n')1244break;1245for(i =0; i <ARRAY_SIZE(optable); i++) {1246const struct opentry *p = optable + i;1247int oplen =strlen(p->str);1248if(len < oplen ||memcmp(p->str, line, oplen))1249continue;1250if(p->fn(line + oplen, patch) <0)1251return offset;1252break;1253}1254}12551256return offset;1257}12581259static intparse_num(const char*line,unsigned long*p)1260{1261char*ptr;12621263if(!isdigit(*line))1264return0;1265*p =strtoul(line, &ptr,10);1266return ptr - line;1267}12681269static intparse_range(const char*line,int len,int offset,const char*expect,1270unsigned long*p1,unsigned long*p2)1271{1272int digits, ex;12731274if(offset <0|| offset >= len)1275return-1;1276 line += offset;1277 len -= offset;12781279 digits =parse_num(line, p1);1280if(!digits)1281return-1;12821283 offset += digits;1284 line += digits;1285 len -= digits;12861287*p2 =1;1288if(*line ==',') {1289 digits =parse_num(line+1, p2);1290if(!digits)1291return-1;12921293 offset += digits+1;1294 line += digits+1;1295 len -= digits+1;1296}12971298 ex =strlen(expect);1299if(ex > len)1300return-1;1301if(memcmp(line, expect, ex))1302return-1;13031304return offset + ex;1305}13061307static voidrecount_diff(char*line,int size,struct fragment *fragment)1308{1309int oldlines =0, newlines =0, ret =0;13101311if(size <1) {1312warning("recount: ignore empty hunk");1313return;1314}13151316for(;;) {1317int len =linelen(line, size);1318 size -= len;1319 line += len;13201321if(size <1)1322break;13231324switch(*line) {1325case' ':case'\n':1326 newlines++;1327/* fall through */1328case'-':1329 oldlines++;1330continue;1331case'+':1332 newlines++;1333continue;1334case'\\':1335continue;1336case'@':1337 ret = size <3||prefixcmp(line,"@@ ");1338break;1339case'd':1340 ret = size <5||prefixcmp(line,"diff ");1341break;1342default:1343 ret = -1;1344break;1345}1346if(ret) {1347warning("recount: unexpected line: %.*s",1348(int)linelen(line, size), line);1349return;1350}1351break;1352}1353 fragment->oldlines = oldlines;1354 fragment->newlines = newlines;1355}13561357/*1358 * Parse a unified diff fragment header of the1359 * form "@@ -a,b +c,d @@"1360 */1361static intparse_fragment_header(char*line,int len,struct fragment *fragment)1362{1363int offset;13641365if(!len || line[len-1] !='\n')1366return-1;13671368/* Figure out the number of lines in a fragment */1369 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1370 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);13711372return offset;1373}13741375static intfind_header(char*line,unsigned long size,int*hdrsize,struct patch *patch)1376{1377unsigned long offset, len;13781379 patch->is_toplevel_relative =0;1380 patch->is_rename = patch->is_copy =0;1381 patch->is_new = patch->is_delete = -1;1382 patch->old_mode = patch->new_mode =0;1383 patch->old_name = patch->new_name = NULL;1384for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) {1385unsigned long nextlen;13861387 len =linelen(line, size);1388if(!len)1389break;13901391/* Testing this early allows us to take a few shortcuts.. */1392if(len <6)1393continue;13941395/*1396 * Make sure we don't find any unconnected patch fragments.1397 * That's a sign that we didn't find a header, and that a1398 * patch has become corrupted/broken up.1399 */1400if(!memcmp("@@ -", line,4)) {1401struct fragment dummy;1402if(parse_fragment_header(line, len, &dummy) <0)1403continue;1404die("patch fragment without header at line%d: %.*s",1405 linenr, (int)len-1, line);1406}14071408if(size < len +6)1409break;14101411/*1412 * Git patch? It might not have a real patch, just a rename1413 * or mode change, so we handle that specially1414 */1415if(!memcmp("diff --git ", line,11)) {1416int git_hdr_len =parse_git_header(line, len, size, patch);1417if(git_hdr_len <= len)1418continue;1419if(!patch->old_name && !patch->new_name) {1420if(!patch->def_name)1421die("git diff header lacks filename information when removing "1422"%dleading pathname components (line%d)", p_value, linenr);1423 patch->old_name = patch->new_name = patch->def_name;1424}1425if(!patch->is_delete && !patch->new_name)1426die("git diff header lacks filename information "1427"(line%d)", linenr);1428 patch->is_toplevel_relative =1;1429*hdrsize = git_hdr_len;1430return offset;1431}14321433/* --- followed by +++ ? */1434if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1435continue;14361437/*1438 * We only accept unified patches, so we want it to1439 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1440 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1441 */1442 nextlen =linelen(line + len, size - len);1443if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1444continue;14451446/* Ok, we'll consider it a patch */1447parse_traditional_patch(line, line+len, patch);1448*hdrsize = len + nextlen;1449 linenr +=2;1450return offset;1451}1452return-1;1453}14541455static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1456{1457char*err;14581459if(!result)1460return;14611462 whitespace_error++;1463if(squelch_whitespace_errors &&1464 squelch_whitespace_errors < whitespace_error)1465return;14661467 err =whitespace_error_string(result);1468fprintf(stderr,"%s:%d:%s.\n%.*s\n",1469 patch_input_file, linenr, err, len, line);1470free(err);1471}14721473static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1474{1475unsigned result =ws_check(line +1, len -1, ws_rule);14761477record_ws_error(result, line +1, len -2, linenr);1478}14791480/*1481 * Parse a unified diff. Note that this really needs to parse each1482 * fragment separately, since the only way to know the difference1483 * between a "---" that is part of a patch, and a "---" that starts1484 * the next patch is to look at the line counts..1485 */1486static intparse_fragment(char*line,unsigned long size,1487struct patch *patch,struct fragment *fragment)1488{1489int added, deleted;1490int len =linelen(line, size), offset;1491unsigned long oldlines, newlines;1492unsigned long leading, trailing;14931494 offset =parse_fragment_header(line, len, fragment);1495if(offset <0)1496return-1;1497if(offset >0&& patch->recount)1498recount_diff(line + offset, size - offset, fragment);1499 oldlines = fragment->oldlines;1500 newlines = fragment->newlines;1501 leading =0;1502 trailing =0;15031504/* Parse the thing.. */1505 line += len;1506 size -= len;1507 linenr++;1508 added = deleted =0;1509for(offset = len;15100< size;1511 offset += len, size -= len, line += len, linenr++) {1512if(!oldlines && !newlines)1513break;1514 len =linelen(line, size);1515if(!len || line[len-1] !='\n')1516return-1;1517switch(*line) {1518default:1519return-1;1520case'\n':/* newer GNU diff, an empty context line */1521case' ':1522 oldlines--;1523 newlines--;1524if(!deleted && !added)1525 leading++;1526 trailing++;1527break;1528case'-':1529if(apply_in_reverse &&1530 ws_error_action != nowarn_ws_error)1531check_whitespace(line, len, patch->ws_rule);1532 deleted++;1533 oldlines--;1534 trailing =0;1535break;1536case'+':1537if(!apply_in_reverse &&1538 ws_error_action != nowarn_ws_error)1539check_whitespace(line, len, patch->ws_rule);1540 added++;1541 newlines--;1542 trailing =0;1543break;15441545/*1546 * We allow "\ No newline at end of file". Depending1547 * on locale settings when the patch was produced we1548 * don't know what this line looks like. The only1549 * thing we do know is that it begins with "\ ".1550 * Checking for 12 is just for sanity check -- any1551 * l10n of "\ No newline..." is at least that long.1552 */1553case'\\':1554if(len <12||memcmp(line,"\\",2))1555return-1;1556break;1557}1558}1559if(oldlines || newlines)1560return-1;1561 fragment->leading = leading;1562 fragment->trailing = trailing;15631564/*1565 * If a fragment ends with an incomplete line, we failed to include1566 * it in the above loop because we hit oldlines == newlines == 01567 * before seeing it.1568 */1569if(12< size && !memcmp(line,"\\",2))1570 offset +=linelen(line, size);15711572 patch->lines_added += added;1573 patch->lines_deleted += deleted;15741575if(0< patch->is_new && oldlines)1576returnerror("new file depends on old contents");1577if(0< patch->is_delete && newlines)1578returnerror("deleted file still has contents");1579return offset;1580}15811582static intparse_single_patch(char*line,unsigned long size,struct patch *patch)1583{1584unsigned long offset =0;1585unsigned long oldlines =0, newlines =0, context =0;1586struct fragment **fragp = &patch->fragments;15871588while(size >4&& !memcmp(line,"@@ -",4)) {1589struct fragment *fragment;1590int len;15911592 fragment =xcalloc(1,sizeof(*fragment));1593 fragment->linenr = linenr;1594 len =parse_fragment(line, size, patch, fragment);1595if(len <=0)1596die("corrupt patch at line%d", linenr);1597 fragment->patch = line;1598 fragment->size = len;1599 oldlines += fragment->oldlines;1600 newlines += fragment->newlines;1601 context += fragment->leading + fragment->trailing;16021603*fragp = fragment;1604 fragp = &fragment->next;16051606 offset += len;1607 line += len;1608 size -= len;1609}16101611/*1612 * If something was removed (i.e. we have old-lines) it cannot1613 * be creation, and if something was added it cannot be1614 * deletion. However, the reverse is not true; --unified=01615 * patches that only add are not necessarily creation even1616 * though they do not have any old lines, and ones that only1617 * delete are not necessarily deletion.1618 *1619 * Unfortunately, a real creation/deletion patch do _not_ have1620 * any context line by definition, so we cannot safely tell it1621 * apart with --unified=0 insanity. At least if the patch has1622 * more than one hunk it is not creation or deletion.1623 */1624if(patch->is_new <0&&1625(oldlines || (patch->fragments && patch->fragments->next)))1626 patch->is_new =0;1627if(patch->is_delete <0&&1628(newlines || (patch->fragments && patch->fragments->next)))1629 patch->is_delete =0;16301631if(0< patch->is_new && oldlines)1632die("new file%sdepends on old contents", patch->new_name);1633if(0< patch->is_delete && newlines)1634die("deleted file%sstill has contents", patch->old_name);1635if(!patch->is_delete && !newlines && context)1636fprintf(stderr,"** warning: file%sbecomes empty but "1637"is not deleted\n", patch->new_name);16381639return offset;1640}16411642staticinlineintmetadata_changes(struct patch *patch)1643{1644return patch->is_rename >0||1645 patch->is_copy >0||1646 patch->is_new >0||1647 patch->is_delete ||1648(patch->old_mode && patch->new_mode &&1649 patch->old_mode != patch->new_mode);1650}16511652static char*inflate_it(const void*data,unsigned long size,1653unsigned long inflated_size)1654{1655 git_zstream stream;1656void*out;1657int st;16581659memset(&stream,0,sizeof(stream));16601661 stream.next_in = (unsigned char*)data;1662 stream.avail_in = size;1663 stream.next_out = out =xmalloc(inflated_size);1664 stream.avail_out = inflated_size;1665git_inflate_init(&stream);1666 st =git_inflate(&stream, Z_FINISH);1667git_inflate_end(&stream);1668if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1669free(out);1670return NULL;1671}1672return out;1673}16741675static struct fragment *parse_binary_hunk(char**buf_p,1676unsigned long*sz_p,1677int*status_p,1678int*used_p)1679{1680/*1681 * Expect a line that begins with binary patch method ("literal"1682 * or "delta"), followed by the length of data before deflating.1683 * a sequence of 'length-byte' followed by base-85 encoded data1684 * should follow, terminated by a newline.1685 *1686 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1687 * and we would limit the patch line to 66 characters,1688 * so one line can fit up to 13 groups that would decode1689 * to 52 bytes max. The length byte 'A'-'Z' corresponds1690 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1691 */1692int llen, used;1693unsigned long size = *sz_p;1694char*buffer = *buf_p;1695int patch_method;1696unsigned long origlen;1697char*data = NULL;1698int hunk_size =0;1699struct fragment *frag;17001701 llen =linelen(buffer, size);1702 used = llen;17031704*status_p =0;17051706if(!prefixcmp(buffer,"delta ")) {1707 patch_method = BINARY_DELTA_DEFLATED;1708 origlen =strtoul(buffer +6, NULL,10);1709}1710else if(!prefixcmp(buffer,"literal ")) {1711 patch_method = BINARY_LITERAL_DEFLATED;1712 origlen =strtoul(buffer +8, NULL,10);1713}1714else1715return NULL;17161717 linenr++;1718 buffer += llen;1719while(1) {1720int byte_length, max_byte_length, newsize;1721 llen =linelen(buffer, size);1722 used += llen;1723 linenr++;1724if(llen ==1) {1725/* consume the blank line */1726 buffer++;1727 size--;1728break;1729}1730/*1731 * Minimum line is "A00000\n" which is 7-byte long,1732 * and the line length must be multiple of 5 plus 2.1733 */1734if((llen <7) || (llen-2) %5)1735goto corrupt;1736 max_byte_length = (llen -2) /5*4;1737 byte_length = *buffer;1738if('A'<= byte_length && byte_length <='Z')1739 byte_length = byte_length -'A'+1;1740else if('a'<= byte_length && byte_length <='z')1741 byte_length = byte_length -'a'+27;1742else1743goto corrupt;1744/* if the input length was not multiple of 4, we would1745 * have filler at the end but the filler should never1746 * exceed 3 bytes1747 */1748if(max_byte_length < byte_length ||1749 byte_length <= max_byte_length -4)1750goto corrupt;1751 newsize = hunk_size + byte_length;1752 data =xrealloc(data, newsize);1753if(decode_85(data + hunk_size, buffer +1, byte_length))1754goto corrupt;1755 hunk_size = newsize;1756 buffer += llen;1757 size -= llen;1758}17591760 frag =xcalloc(1,sizeof(*frag));1761 frag->patch =inflate_it(data, hunk_size, origlen);1762if(!frag->patch)1763goto corrupt;1764free(data);1765 frag->size = origlen;1766*buf_p = buffer;1767*sz_p = size;1768*used_p = used;1769 frag->binary_patch_method = patch_method;1770return frag;17711772 corrupt:1773free(data);1774*status_p = -1;1775error("corrupt binary patch at line%d: %.*s",1776 linenr-1, llen-1, buffer);1777return NULL;1778}17791780static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1781{1782/*1783 * We have read "GIT binary patch\n"; what follows is a line1784 * that says the patch method (currently, either "literal" or1785 * "delta") and the length of data before deflating; a1786 * sequence of 'length-byte' followed by base-85 encoded data1787 * follows.1788 *1789 * When a binary patch is reversible, there is another binary1790 * hunk in the same format, starting with patch method (either1791 * "literal" or "delta") with the length of data, and a sequence1792 * of length-byte + base-85 encoded data, terminated with another1793 * empty line. This data, when applied to the postimage, produces1794 * the preimage.1795 */1796struct fragment *forward;1797struct fragment *reverse;1798int status;1799int used, used_1;18001801 forward =parse_binary_hunk(&buffer, &size, &status, &used);1802if(!forward && !status)1803/* there has to be one hunk (forward hunk) */1804returnerror("unrecognized binary patch at line%d", linenr-1);1805if(status)1806/* otherwise we already gave an error message */1807return status;18081809 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1810if(reverse)1811 used += used_1;1812else if(status) {1813/*1814 * Not having reverse hunk is not an error, but having1815 * a corrupt reverse hunk is.1816 */1817free((void*) forward->patch);1818free(forward);1819return status;1820}1821 forward->next = reverse;1822 patch->fragments = forward;1823 patch->is_binary =1;1824return used;1825}18261827static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1828{1829int hdrsize, patchsize;1830int offset =find_header(buffer, size, &hdrsize, patch);18311832if(offset <0)1833return offset;18341835 patch->ws_rule =whitespace_rule(patch->new_name1836? patch->new_name1837: patch->old_name);18381839 patchsize =parse_single_patch(buffer + offset + hdrsize,1840 size - offset - hdrsize, patch);18411842if(!patchsize) {1843static const char*binhdr[] = {1844"Binary files ",1845"Files ",1846 NULL,1847};1848static const char git_binary[] ="GIT binary patch\n";1849int i;1850int hd = hdrsize + offset;1851unsigned long llen =linelen(buffer + hd, size - hd);18521853if(llen ==sizeof(git_binary) -1&&1854!memcmp(git_binary, buffer + hd, llen)) {1855int used;1856 linenr++;1857 used =parse_binary(buffer + hd + llen,1858 size - hd - llen, patch);1859if(used)1860 patchsize = used + llen;1861else1862 patchsize =0;1863}1864else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1865for(i =0; binhdr[i]; i++) {1866int len =strlen(binhdr[i]);1867if(len < size - hd &&1868!memcmp(binhdr[i], buffer + hd, len)) {1869 linenr++;1870 patch->is_binary =1;1871 patchsize = llen;1872break;1873}1874}1875}18761877/* Empty patch cannot be applied if it is a text patch1878 * without metadata change. A binary patch appears1879 * empty to us here.1880 */1881if((apply || check) &&1882(!patch->is_binary && !metadata_changes(patch)))1883die("patch with only garbage at line%d", linenr);1884}18851886return offset + hdrsize + patchsize;1887}18881889#define swap(a,b) myswap((a),(b),sizeof(a))18901891#define myswap(a, b, size) do { \1892 unsigned char mytmp[size]; \1893 memcpy(mytmp, &a, size); \1894 memcpy(&a, &b, size); \1895 memcpy(&b, mytmp, size); \1896} while (0)18971898static voidreverse_patches(struct patch *p)1899{1900for(; p; p = p->next) {1901struct fragment *frag = p->fragments;19021903swap(p->new_name, p->old_name);1904swap(p->new_mode, p->old_mode);1905swap(p->is_new, p->is_delete);1906swap(p->lines_added, p->lines_deleted);1907swap(p->old_sha1_prefix, p->new_sha1_prefix);19081909for(; frag; frag = frag->next) {1910swap(frag->newpos, frag->oldpos);1911swap(frag->newlines, frag->oldlines);1912}1913}1914}19151916static const char pluses[] =1917"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";1918static const char minuses[]=1919"----------------------------------------------------------------------";19201921static voidshow_stats(struct patch *patch)1922{1923struct strbuf qname = STRBUF_INIT;1924char*cp = patch->new_name ? patch->new_name : patch->old_name;1925int max, add, del;19261927quote_c_style(cp, &qname, NULL,0);19281929/*1930 * "scale" the filename1931 */1932 max = max_len;1933if(max >50)1934 max =50;19351936if(qname.len > max) {1937 cp =strchr(qname.buf + qname.len +3- max,'/');1938if(!cp)1939 cp = qname.buf + qname.len +3- max;1940strbuf_splice(&qname,0, cp - qname.buf,"...",3);1941}19421943if(patch->is_binary) {1944printf(" %-*s | Bin\n", max, qname.buf);1945strbuf_release(&qname);1946return;1947}19481949printf(" %-*s |", max, qname.buf);1950strbuf_release(&qname);19511952/*1953 * scale the add/delete1954 */1955 max = max + max_change >70?70- max : max_change;1956 add = patch->lines_added;1957 del = patch->lines_deleted;19581959if(max_change >0) {1960int total = ((add + del) * max + max_change /2) / max_change;1961 add = (add * max + max_change /2) / max_change;1962 del = total - add;1963}1964printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,1965 add, pluses, del, minuses);1966}19671968static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)1969{1970switch(st->st_mode & S_IFMT) {1971case S_IFLNK:1972if(strbuf_readlink(buf, path, st->st_size) <0)1973returnerror("unable to read symlink%s", path);1974return0;1975case S_IFREG:1976if(strbuf_read_file(buf, path, st->st_size) != st->st_size)1977returnerror("unable to open or read%s", path);1978convert_to_git(path, buf->buf, buf->len, buf,0);1979return0;1980default:1981return-1;1982}1983}19841985/*1986 * Update the preimage, and the common lines in postimage,1987 * from buffer buf of length len. If postlen is 0 the postimage1988 * is updated in place, otherwise it's updated on a new buffer1989 * of length postlen1990 */19911992static voidupdate_pre_post_images(struct image *preimage,1993struct image *postimage,1994char*buf,1995size_t len,size_t postlen)1996{1997int i, ctx;1998char*new, *old, *fixed;1999struct image fixed_preimage;20002001/*2002 * Update the preimage with whitespace fixes. Note that we2003 * are not losing preimage->buf -- apply_one_fragment() will2004 * free "oldlines".2005 */2006prepare_image(&fixed_preimage, buf, len,1);2007assert(fixed_preimage.nr == preimage->nr);2008for(i =0; i < preimage->nr; i++)2009 fixed_preimage.line[i].flag = preimage->line[i].flag;2010free(preimage->line_allocated);2011*preimage = fixed_preimage;20122013/*2014 * Adjust the common context lines in postimage. This can be2015 * done in-place when we are just doing whitespace fixing,2016 * which does not make the string grow, but needs a new buffer2017 * when ignoring whitespace causes the update, since in this case2018 * we could have e.g. tabs converted to multiple spaces.2019 * We trust the caller to tell us if the update can be done2020 * in place (postlen==0) or not.2021 */2022 old = postimage->buf;2023if(postlen)2024new= postimage->buf =xmalloc(postlen);2025else2026new= old;2027 fixed = preimage->buf;2028for(i = ctx =0; i < postimage->nr; i++) {2029size_t len = postimage->line[i].len;2030if(!(postimage->line[i].flag & LINE_COMMON)) {2031/* an added line -- no counterparts in preimage */2032memmove(new, old, len);2033 old += len;2034new+= len;2035continue;2036}20372038/* a common context -- skip it in the original postimage */2039 old += len;20402041/* and find the corresponding one in the fixed preimage */2042while(ctx < preimage->nr &&2043!(preimage->line[ctx].flag & LINE_COMMON)) {2044 fixed += preimage->line[ctx].len;2045 ctx++;2046}2047if(preimage->nr <= ctx)2048die("oops");20492050/* and copy it in, while fixing the line length */2051 len = preimage->line[ctx].len;2052memcpy(new, fixed, len);2053new+= len;2054 fixed += len;2055 postimage->line[i].len = len;2056 ctx++;2057}20582059/* Fix the length of the whole thing */2060 postimage->len =new- postimage->buf;2061}20622063static intmatch_fragment(struct image *img,2064struct image *preimage,2065struct image *postimage,2066unsigned longtry,2067int try_lno,2068unsigned ws_rule,2069int match_beginning,int match_end)2070{2071int i;2072char*fixed_buf, *buf, *orig, *target;2073struct strbuf fixed;2074size_t fixed_len;2075int preimage_limit;20762077if(preimage->nr + try_lno <= img->nr) {2078/*2079 * The hunk falls within the boundaries of img.2080 */2081 preimage_limit = preimage->nr;2082if(match_end && (preimage->nr + try_lno != img->nr))2083return0;2084}else if(ws_error_action == correct_ws_error &&2085(ws_rule & WS_BLANK_AT_EOF)) {2086/*2087 * This hunk extends beyond the end of img, and we are2088 * removing blank lines at the end of the file. This2089 * many lines from the beginning of the preimage must2090 * match with img, and the remainder of the preimage2091 * must be blank.2092 */2093 preimage_limit = img->nr - try_lno;2094}else{2095/*2096 * The hunk extends beyond the end of the img and2097 * we are not removing blanks at the end, so we2098 * should reject the hunk at this position.2099 */2100return0;2101}21022103if(match_beginning && try_lno)2104return0;21052106/* Quick hash check */2107for(i =0; i < preimage_limit; i++)2108if((img->line[try_lno + i].flag & LINE_PATCHED) ||2109(preimage->line[i].hash != img->line[try_lno + i].hash))2110return0;21112112if(preimage_limit == preimage->nr) {2113/*2114 * Do we have an exact match? If we were told to match2115 * at the end, size must be exactly at try+fragsize,2116 * otherwise try+fragsize must be still within the preimage,2117 * and either case, the old piece should match the preimage2118 * exactly.2119 */2120if((match_end2121? (try+ preimage->len == img->len)2122: (try+ preimage->len <= img->len)) &&2123!memcmp(img->buf +try, preimage->buf, preimage->len))2124return1;2125}else{2126/*2127 * The preimage extends beyond the end of img, so2128 * there cannot be an exact match.2129 *2130 * There must be one non-blank context line that match2131 * a line before the end of img.2132 */2133char*buf_end;21342135 buf = preimage->buf;2136 buf_end = buf;2137for(i =0; i < preimage_limit; i++)2138 buf_end += preimage->line[i].len;21392140for( ; buf < buf_end; buf++)2141if(!isspace(*buf))2142break;2143if(buf == buf_end)2144return0;2145}21462147/*2148 * No exact match. If we are ignoring whitespace, run a line-by-line2149 * fuzzy matching. We collect all the line length information because2150 * we need it to adjust whitespace if we match.2151 */2152if(ws_ignore_action == ignore_ws_change) {2153size_t imgoff =0;2154size_t preoff =0;2155size_t postlen = postimage->len;2156size_t extra_chars;2157char*preimage_eof;2158char*preimage_end;2159for(i =0; i < preimage_limit; i++) {2160size_t prelen = preimage->line[i].len;2161size_t imglen = img->line[try_lno+i].len;21622163if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2164 preimage->buf + preoff, prelen))2165return0;2166if(preimage->line[i].flag & LINE_COMMON)2167 postlen += imglen - prelen;2168 imgoff += imglen;2169 preoff += prelen;2170}21712172/*2173 * Ok, the preimage matches with whitespace fuzz.2174 *2175 * imgoff now holds the true length of the target that2176 * matches the preimage before the end of the file.2177 *2178 * Count the number of characters in the preimage that fall2179 * beyond the end of the file and make sure that all of them2180 * are whitespace characters. (This can only happen if2181 * we are removing blank lines at the end of the file.)2182 */2183 buf = preimage_eof = preimage->buf + preoff;2184for( ; i < preimage->nr; i++)2185 preoff += preimage->line[i].len;2186 preimage_end = preimage->buf + preoff;2187for( ; buf < preimage_end; buf++)2188if(!isspace(*buf))2189return0;21902191/*2192 * Update the preimage and the common postimage context2193 * lines to use the same whitespace as the target.2194 * If whitespace is missing in the target (i.e.2195 * if the preimage extends beyond the end of the file),2196 * use the whitespace from the preimage.2197 */2198 extra_chars = preimage_end - preimage_eof;2199strbuf_init(&fixed, imgoff + extra_chars);2200strbuf_add(&fixed, img->buf +try, imgoff);2201strbuf_add(&fixed, preimage_eof, extra_chars);2202 fixed_buf =strbuf_detach(&fixed, &fixed_len);2203update_pre_post_images(preimage, postimage,2204 fixed_buf, fixed_len, postlen);2205return1;2206}22072208if(ws_error_action != correct_ws_error)2209return0;22102211/*2212 * The hunk does not apply byte-by-byte, but the hash says2213 * it might with whitespace fuzz. We haven't been asked to2214 * ignore whitespace, we were asked to correct whitespace2215 * errors, so let's try matching after whitespace correction.2216 *2217 * The preimage may extend beyond the end of the file,2218 * but in this loop we will only handle the part of the2219 * preimage that falls within the file.2220 */2221strbuf_init(&fixed, preimage->len +1);2222 orig = preimage->buf;2223 target = img->buf +try;2224for(i =0; i < preimage_limit; i++) {2225size_t oldlen = preimage->line[i].len;2226size_t tgtlen = img->line[try_lno + i].len;2227size_t fixstart = fixed.len;2228struct strbuf tgtfix;2229int match;22302231/* Try fixing the line in the preimage */2232ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);22332234/* Try fixing the line in the target */2235strbuf_init(&tgtfix, tgtlen);2236ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);22372238/*2239 * If they match, either the preimage was based on2240 * a version before our tree fixed whitespace breakage,2241 * or we are lacking a whitespace-fix patch the tree2242 * the preimage was based on already had (i.e. target2243 * has whitespace breakage, the preimage doesn't).2244 * In either case, we are fixing the whitespace breakages2245 * so we might as well take the fix together with their2246 * real change.2247 */2248 match = (tgtfix.len == fixed.len - fixstart &&2249!memcmp(tgtfix.buf, fixed.buf + fixstart,2250 fixed.len - fixstart));22512252strbuf_release(&tgtfix);2253if(!match)2254goto unmatch_exit;22552256 orig += oldlen;2257 target += tgtlen;2258}225922602261/*2262 * Now handle the lines in the preimage that falls beyond the2263 * end of the file (if any). They will only match if they are2264 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2265 * false).2266 */2267for( ; i < preimage->nr; i++) {2268size_t fixstart = fixed.len;/* start of the fixed preimage */2269size_t oldlen = preimage->line[i].len;2270int j;22712272/* Try fixing the line in the preimage */2273ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);22742275for(j = fixstart; j < fixed.len; j++)2276if(!isspace(fixed.buf[j]))2277goto unmatch_exit;22782279 orig += oldlen;2280}22812282/*2283 * Yes, the preimage is based on an older version that still2284 * has whitespace breakages unfixed, and fixing them makes the2285 * hunk match. Update the context lines in the postimage.2286 */2287 fixed_buf =strbuf_detach(&fixed, &fixed_len);2288update_pre_post_images(preimage, postimage,2289 fixed_buf, fixed_len,0);2290return1;22912292 unmatch_exit:2293strbuf_release(&fixed);2294return0;2295}22962297static intfind_pos(struct image *img,2298struct image *preimage,2299struct image *postimage,2300int line,2301unsigned ws_rule,2302int match_beginning,int match_end)2303{2304int i;2305unsigned long backwards, forwards,try;2306int backwards_lno, forwards_lno, try_lno;23072308/*2309 * If match_beginning or match_end is specified, there is no2310 * point starting from a wrong line that will never match and2311 * wander around and wait for a match at the specified end.2312 */2313if(match_beginning)2314 line =0;2315else if(match_end)2316 line = img->nr - preimage->nr;23172318/*2319 * Because the comparison is unsigned, the following test2320 * will also take care of a negative line number that can2321 * result when match_end and preimage is larger than the target.2322 */2323if((size_t) line > img->nr)2324 line = img->nr;23252326try=0;2327for(i =0; i < line; i++)2328try+= img->line[i].len;23292330/*2331 * There's probably some smart way to do this, but I'll leave2332 * that to the smart and beautiful people. I'm simple and stupid.2333 */2334 backwards =try;2335 backwards_lno = line;2336 forwards =try;2337 forwards_lno = line;2338 try_lno = line;23392340for(i =0; ; i++) {2341if(match_fragment(img, preimage, postimage,2342try, try_lno, ws_rule,2343 match_beginning, match_end))2344return try_lno;23452346 again:2347if(backwards_lno ==0&& forwards_lno == img->nr)2348break;23492350if(i &1) {2351if(backwards_lno ==0) {2352 i++;2353goto again;2354}2355 backwards_lno--;2356 backwards -= img->line[backwards_lno].len;2357try= backwards;2358 try_lno = backwards_lno;2359}else{2360if(forwards_lno == img->nr) {2361 i++;2362goto again;2363}2364 forwards += img->line[forwards_lno].len;2365 forwards_lno++;2366try= forwards;2367 try_lno = forwards_lno;2368}23692370}2371return-1;2372}23732374static voidremove_first_line(struct image *img)2375{2376 img->buf += img->line[0].len;2377 img->len -= img->line[0].len;2378 img->line++;2379 img->nr--;2380}23812382static voidremove_last_line(struct image *img)2383{2384 img->len -= img->line[--img->nr].len;2385}23862387static voidupdate_image(struct image *img,2388int applied_pos,2389struct image *preimage,2390struct image *postimage)2391{2392/*2393 * remove the copy of preimage at offset in img2394 * and replace it with postimage2395 */2396int i, nr;2397size_t remove_count, insert_count, applied_at =0;2398char*result;2399int preimage_limit;24002401/*2402 * If we are removing blank lines at the end of img,2403 * the preimage may extend beyond the end.2404 * If that is the case, we must be careful only to2405 * remove the part of the preimage that falls within2406 * the boundaries of img. Initialize preimage_limit2407 * to the number of lines in the preimage that falls2408 * within the boundaries.2409 */2410 preimage_limit = preimage->nr;2411if(preimage_limit > img->nr - applied_pos)2412 preimage_limit = img->nr - applied_pos;24132414for(i =0; i < applied_pos; i++)2415 applied_at += img->line[i].len;24162417 remove_count =0;2418for(i =0; i < preimage_limit; i++)2419 remove_count += img->line[applied_pos + i].len;2420 insert_count = postimage->len;24212422/* Adjust the contents */2423 result =xmalloc(img->len + insert_count - remove_count +1);2424memcpy(result, img->buf, applied_at);2425memcpy(result + applied_at, postimage->buf, postimage->len);2426memcpy(result + applied_at + postimage->len,2427 img->buf + (applied_at + remove_count),2428 img->len - (applied_at + remove_count));2429free(img->buf);2430 img->buf = result;2431 img->len += insert_count - remove_count;2432 result[img->len] ='\0';24332434/* Adjust the line table */2435 nr = img->nr + postimage->nr - preimage_limit;2436if(preimage_limit < postimage->nr) {2437/*2438 * NOTE: this knows that we never call remove_first_line()2439 * on anything other than pre/post image.2440 */2441 img->line =xrealloc(img->line, nr *sizeof(*img->line));2442 img->line_allocated = img->line;2443}2444if(preimage_limit != postimage->nr)2445memmove(img->line + applied_pos + postimage->nr,2446 img->line + applied_pos + preimage_limit,2447(img->nr - (applied_pos + preimage_limit)) *2448sizeof(*img->line));2449memcpy(img->line + applied_pos,2450 postimage->line,2451 postimage->nr *sizeof(*img->line));2452if(!allow_overlap)2453for(i =0; i < postimage->nr; i++)2454 img->line[applied_pos + i].flag |= LINE_PATCHED;2455 img->nr = nr;2456}24572458static intapply_one_fragment(struct image *img,struct fragment *frag,2459int inaccurate_eof,unsigned ws_rule,2460int nth_fragment)2461{2462int match_beginning, match_end;2463const char*patch = frag->patch;2464int size = frag->size;2465char*old, *oldlines;2466struct strbuf newlines;2467int new_blank_lines_at_end =0;2468int found_new_blank_lines_at_end =0;2469int hunk_linenr = frag->linenr;2470unsigned long leading, trailing;2471int pos, applied_pos;2472struct image preimage;2473struct image postimage;24742475memset(&preimage,0,sizeof(preimage));2476memset(&postimage,0,sizeof(postimage));2477 oldlines =xmalloc(size);2478strbuf_init(&newlines, size);24792480 old = oldlines;2481while(size >0) {2482char first;2483int len =linelen(patch, size);2484int plen;2485int added_blank_line =0;2486int is_blank_context =0;2487size_t start;24882489if(!len)2490break;24912492/*2493 * "plen" is how much of the line we should use for2494 * the actual patch data. Normally we just remove the2495 * first character on the line, but if the line is2496 * followed by "\ No newline", then we also remove the2497 * last one (which is the newline, of course).2498 */2499 plen = len -1;2500if(len < size && patch[len] =='\\')2501 plen--;2502 first = *patch;2503if(apply_in_reverse) {2504if(first =='-')2505 first ='+';2506else if(first =='+')2507 first ='-';2508}25092510switch(first) {2511case'\n':2512/* Newer GNU diff, empty context line */2513if(plen <0)2514/* ... followed by '\No newline'; nothing */2515break;2516*old++ ='\n';2517strbuf_addch(&newlines,'\n');2518add_line_info(&preimage,"\n",1, LINE_COMMON);2519add_line_info(&postimage,"\n",1, LINE_COMMON);2520 is_blank_context =1;2521break;2522case' ':2523if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2524ws_blank_line(patch +1, plen, ws_rule))2525 is_blank_context =1;2526case'-':2527memcpy(old, patch +1, plen);2528add_line_info(&preimage, old, plen,2529(first ==' '? LINE_COMMON :0));2530 old += plen;2531if(first =='-')2532break;2533/* Fall-through for ' ' */2534case'+':2535/* --no-add does not add new lines */2536if(first =='+'&& no_add)2537break;25382539 start = newlines.len;2540if(first !='+'||2541!whitespace_error ||2542 ws_error_action != correct_ws_error) {2543strbuf_add(&newlines, patch +1, plen);2544}2545else{2546ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2547}2548add_line_info(&postimage, newlines.buf + start, newlines.len - start,2549(first =='+'?0: LINE_COMMON));2550if(first =='+'&&2551(ws_rule & WS_BLANK_AT_EOF) &&2552ws_blank_line(patch +1, plen, ws_rule))2553 added_blank_line =1;2554break;2555case'@':case'\\':2556/* Ignore it, we already handled it */2557break;2558default:2559if(apply_verbosely)2560error("invalid start of line: '%c'", first);2561return-1;2562}2563if(added_blank_line) {2564if(!new_blank_lines_at_end)2565 found_new_blank_lines_at_end = hunk_linenr;2566 new_blank_lines_at_end++;2567}2568else if(is_blank_context)2569;2570else2571 new_blank_lines_at_end =0;2572 patch += len;2573 size -= len;2574 hunk_linenr++;2575}2576if(inaccurate_eof &&2577 old > oldlines && old[-1] =='\n'&&2578 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2579 old--;2580strbuf_setlen(&newlines, newlines.len -1);2581}25822583 leading = frag->leading;2584 trailing = frag->trailing;25852586/*2587 * A hunk to change lines at the beginning would begin with2588 * @@ -1,L +N,M @@2589 * but we need to be careful. -U0 that inserts before the second2590 * line also has this pattern.2591 *2592 * And a hunk to add to an empty file would begin with2593 * @@ -0,0 +N,M @@2594 *2595 * In other words, a hunk that is (frag->oldpos <= 1) with or2596 * without leading context must match at the beginning.2597 */2598 match_beginning = (!frag->oldpos ||2599(frag->oldpos ==1&& !unidiff_zero));26002601/*2602 * A hunk without trailing lines must match at the end.2603 * However, we simply cannot tell if a hunk must match end2604 * from the lack of trailing lines if the patch was generated2605 * with unidiff without any context.2606 */2607 match_end = !unidiff_zero && !trailing;26082609 pos = frag->newpos ? (frag->newpos -1) :0;2610 preimage.buf = oldlines;2611 preimage.len = old - oldlines;2612 postimage.buf = newlines.buf;2613 postimage.len = newlines.len;2614 preimage.line = preimage.line_allocated;2615 postimage.line = postimage.line_allocated;26162617for(;;) {26182619 applied_pos =find_pos(img, &preimage, &postimage, pos,2620 ws_rule, match_beginning, match_end);26212622if(applied_pos >=0)2623break;26242625/* Am I at my context limits? */2626if((leading <= p_context) && (trailing <= p_context))2627break;2628if(match_beginning || match_end) {2629 match_beginning = match_end =0;2630continue;2631}26322633/*2634 * Reduce the number of context lines; reduce both2635 * leading and trailing if they are equal otherwise2636 * just reduce the larger context.2637 */2638if(leading >= trailing) {2639remove_first_line(&preimage);2640remove_first_line(&postimage);2641 pos--;2642 leading--;2643}2644if(trailing > leading) {2645remove_last_line(&preimage);2646remove_last_line(&postimage);2647 trailing--;2648}2649}26502651if(applied_pos >=0) {2652if(new_blank_lines_at_end &&2653 preimage.nr + applied_pos >= img->nr &&2654(ws_rule & WS_BLANK_AT_EOF) &&2655 ws_error_action != nowarn_ws_error) {2656record_ws_error(WS_BLANK_AT_EOF,"+",1,2657 found_new_blank_lines_at_end);2658if(ws_error_action == correct_ws_error) {2659while(new_blank_lines_at_end--)2660remove_last_line(&postimage);2661}2662/*2663 * We would want to prevent write_out_results()2664 * from taking place in apply_patch() that follows2665 * the callchain led us here, which is:2666 * apply_patch->check_patch_list->check_patch->2667 * apply_data->apply_fragments->apply_one_fragment2668 */2669if(ws_error_action == die_on_ws_error)2670 apply =0;2671}26722673if(apply_verbosely && applied_pos != pos) {2674int offset = applied_pos - pos;2675if(apply_in_reverse)2676 offset =0- offset;2677fprintf(stderr,2678"Hunk #%dsucceeded at%d(offset%dlines).\n",2679 nth_fragment, applied_pos +1, offset);2680}26812682/*2683 * Warn if it was necessary to reduce the number2684 * of context lines.2685 */2686if((leading != frag->leading) ||2687(trailing != frag->trailing))2688fprintf(stderr,"Context reduced to (%ld/%ld)"2689" to apply fragment at%d\n",2690 leading, trailing, applied_pos+1);2691update_image(img, applied_pos, &preimage, &postimage);2692}else{2693if(apply_verbosely)2694error("while searching for:\n%.*s",2695(int)(old - oldlines), oldlines);2696}26972698free(oldlines);2699strbuf_release(&newlines);2700free(preimage.line_allocated);2701free(postimage.line_allocated);27022703return(applied_pos <0);2704}27052706static intapply_binary_fragment(struct image *img,struct patch *patch)2707{2708struct fragment *fragment = patch->fragments;2709unsigned long len;2710void*dst;27112712if(!fragment)2713returnerror("missing binary patch data for '%s'",2714 patch->new_name ?2715 patch->new_name :2716 patch->old_name);27172718/* Binary patch is irreversible without the optional second hunk */2719if(apply_in_reverse) {2720if(!fragment->next)2721returnerror("cannot reverse-apply a binary patch "2722"without the reverse hunk to '%s'",2723 patch->new_name2724? patch->new_name : patch->old_name);2725 fragment = fragment->next;2726}2727switch(fragment->binary_patch_method) {2728case BINARY_DELTA_DEFLATED:2729 dst =patch_delta(img->buf, img->len, fragment->patch,2730 fragment->size, &len);2731if(!dst)2732return-1;2733clear_image(img);2734 img->buf = dst;2735 img->len = len;2736return0;2737case BINARY_LITERAL_DEFLATED:2738clear_image(img);2739 img->len = fragment->size;2740 img->buf =xmalloc(img->len+1);2741memcpy(img->buf, fragment->patch, img->len);2742 img->buf[img->len] ='\0';2743return0;2744}2745return-1;2746}27472748static intapply_binary(struct image *img,struct patch *patch)2749{2750const char*name = patch->old_name ? patch->old_name : patch->new_name;2751unsigned char sha1[20];27522753/*2754 * For safety, we require patch index line to contain2755 * full 40-byte textual SHA1 for old and new, at least for now.2756 */2757if(strlen(patch->old_sha1_prefix) !=40||2758strlen(patch->new_sha1_prefix) !=40||2759get_sha1_hex(patch->old_sha1_prefix, sha1) ||2760get_sha1_hex(patch->new_sha1_prefix, sha1))2761returnerror("cannot apply binary patch to '%s' "2762"without full index line", name);27632764if(patch->old_name) {2765/*2766 * See if the old one matches what the patch2767 * applies to.2768 */2769hash_sha1_file(img->buf, img->len, blob_type, sha1);2770if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2771returnerror("the patch applies to '%s' (%s), "2772"which does not match the "2773"current contents.",2774 name,sha1_to_hex(sha1));2775}2776else{2777/* Otherwise, the old one must be empty. */2778if(img->len)2779returnerror("the patch applies to an empty "2780"'%s' but it is not empty", name);2781}27822783get_sha1_hex(patch->new_sha1_prefix, sha1);2784if(is_null_sha1(sha1)) {2785clear_image(img);2786return0;/* deletion patch */2787}27882789if(has_sha1_file(sha1)) {2790/* We already have the postimage */2791enum object_type type;2792unsigned long size;2793char*result;27942795 result =read_sha1_file(sha1, &type, &size);2796if(!result)2797returnerror("the necessary postimage%sfor "2798"'%s' cannot be read",2799 patch->new_sha1_prefix, name);2800clear_image(img);2801 img->buf = result;2802 img->len = size;2803}else{2804/*2805 * We have verified buf matches the preimage;2806 * apply the patch data to it, which is stored2807 * in the patch->fragments->{patch,size}.2808 */2809if(apply_binary_fragment(img, patch))2810returnerror("binary patch does not apply to '%s'",2811 name);28122813/* verify that the result matches */2814hash_sha1_file(img->buf, img->len, blob_type, sha1);2815if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2816returnerror("binary patch to '%s' creates incorrect result (expecting%s, got%s)",2817 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2818}28192820return0;2821}28222823static intapply_fragments(struct image *img,struct patch *patch)2824{2825struct fragment *frag = patch->fragments;2826const char*name = patch->old_name ? patch->old_name : patch->new_name;2827unsigned ws_rule = patch->ws_rule;2828unsigned inaccurate_eof = patch->inaccurate_eof;2829int nth =0;28302831if(patch->is_binary)2832returnapply_binary(img, patch);28332834while(frag) {2835 nth++;2836if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {2837error("patch failed:%s:%ld", name, frag->oldpos);2838if(!apply_with_reject)2839return-1;2840 frag->rejected =1;2841}2842 frag = frag->next;2843}2844return0;2845}28462847static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2848{2849if(!ce)2850return0;28512852if(S_ISGITLINK(ce->ce_mode)) {2853strbuf_grow(buf,100);2854strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2855}else{2856enum object_type type;2857unsigned long sz;2858char*result;28592860 result =read_sha1_file(ce->sha1, &type, &sz);2861if(!result)2862return-1;2863/* XXX read_sha1_file NUL-terminates */2864strbuf_attach(buf, result, sz, sz +1);2865}2866return0;2867}28682869static struct patch *in_fn_table(const char*name)2870{2871struct string_list_item *item;28722873if(name == NULL)2874return NULL;28752876 item =string_list_lookup(&fn_table, name);2877if(item != NULL)2878return(struct patch *)item->util;28792880return NULL;2881}28822883/*2884 * item->util in the filename table records the status of the path.2885 * Usually it points at a patch (whose result records the contents2886 * of it after applying it), but it could be PATH_WAS_DELETED for a2887 * path that a previously applied patch has already removed.2888 */2889#define PATH_TO_BE_DELETED ((struct patch *) -2)2890#define PATH_WAS_DELETED ((struct patch *) -1)28912892static intto_be_deleted(struct patch *patch)2893{2894return patch == PATH_TO_BE_DELETED;2895}28962897static intwas_deleted(struct patch *patch)2898{2899return patch == PATH_WAS_DELETED;2900}29012902static voidadd_to_fn_table(struct patch *patch)2903{2904struct string_list_item *item;29052906/*2907 * Always add new_name unless patch is a deletion2908 * This should cover the cases for normal diffs,2909 * file creations and copies2910 */2911if(patch->new_name != NULL) {2912 item =string_list_insert(&fn_table, patch->new_name);2913 item->util = patch;2914}29152916/*2917 * store a failure on rename/deletion cases because2918 * later chunks shouldn't patch old names2919 */2920if((patch->new_name == NULL) || (patch->is_rename)) {2921 item =string_list_insert(&fn_table, patch->old_name);2922 item->util = PATH_WAS_DELETED;2923}2924}29252926static voidprepare_fn_table(struct patch *patch)2927{2928/*2929 * store information about incoming file deletion2930 */2931while(patch) {2932if((patch->new_name == NULL) || (patch->is_rename)) {2933struct string_list_item *item;2934 item =string_list_insert(&fn_table, patch->old_name);2935 item->util = PATH_TO_BE_DELETED;2936}2937 patch = patch->next;2938}2939}29402941static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)2942{2943struct strbuf buf = STRBUF_INIT;2944struct image image;2945size_t len;2946char*img;2947struct patch *tpatch;29482949if(!(patch->is_copy || patch->is_rename) &&2950(tpatch =in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {2951if(was_deleted(tpatch)) {2952returnerror("patch%shas been renamed/deleted",2953 patch->old_name);2954}2955/* We have a patched copy in memory use that */2956strbuf_add(&buf, tpatch->result, tpatch->resultsize);2957}else if(cached) {2958if(read_file_or_gitlink(ce, &buf))2959returnerror("read of%sfailed", patch->old_name);2960}else if(patch->old_name) {2961if(S_ISGITLINK(patch->old_mode)) {2962if(ce) {2963read_file_or_gitlink(ce, &buf);2964}else{2965/*2966 * There is no way to apply subproject2967 * patch without looking at the index.2968 */2969 patch->fragments = NULL;2970}2971}else{2972if(read_old_data(st, patch->old_name, &buf))2973returnerror("read of%sfailed", patch->old_name);2974}2975}29762977 img =strbuf_detach(&buf, &len);2978prepare_image(&image, img, len, !patch->is_binary);29792980if(apply_fragments(&image, patch) <0)2981return-1;/* note with --reject this succeeds. */2982 patch->result = image.buf;2983 patch->resultsize = image.len;2984add_to_fn_table(patch);2985free(image.line_allocated);29862987if(0< patch->is_delete && patch->resultsize)2988returnerror("removal patch leaves file contents");29892990return0;2991}29922993static intcheck_to_create_blob(const char*new_name,int ok_if_exists)2994{2995struct stat nst;2996if(!lstat(new_name, &nst)) {2997if(S_ISDIR(nst.st_mode) || ok_if_exists)2998return0;2999/*3000 * A leading component of new_name might be a symlink3001 * that is going to be removed with this patch, but3002 * still pointing at somewhere that has the path.3003 * In such a case, path "new_name" does not exist as3004 * far as git is concerned.3005 */3006if(has_symlink_leading_path(new_name,strlen(new_name)))3007return0;30083009returnerror("%s: already exists in working directory", new_name);3010}3011else if((errno != ENOENT) && (errno != ENOTDIR))3012returnerror("%s:%s", new_name,strerror(errno));3013return0;3014}30153016static intverify_index_match(struct cache_entry *ce,struct stat *st)3017{3018if(S_ISGITLINK(ce->ce_mode)) {3019if(!S_ISDIR(st->st_mode))3020return-1;3021return0;3022}3023returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3024}30253026static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)3027{3028const char*old_name = patch->old_name;3029struct patch *tpatch = NULL;3030int stat_ret =0;3031unsigned st_mode =0;30323033/*3034 * Make sure that we do not have local modifications from the3035 * index when we are looking at the index. Also make sure3036 * we have the preimage file to be patched in the work tree,3037 * unless --cached, which tells git to apply only in the index.3038 */3039if(!old_name)3040return0;30413042assert(patch->is_new <=0);30433044if(!(patch->is_copy || patch->is_rename) &&3045(tpatch =in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {3046if(was_deleted(tpatch))3047returnerror("%s: has been deleted/renamed", old_name);3048 st_mode = tpatch->new_mode;3049}else if(!cached) {3050 stat_ret =lstat(old_name, st);3051if(stat_ret && errno != ENOENT)3052returnerror("%s:%s", old_name,strerror(errno));3053}30543055if(to_be_deleted(tpatch))3056 tpatch = NULL;30573058if(check_index && !tpatch) {3059int pos =cache_name_pos(old_name,strlen(old_name));3060if(pos <0) {3061if(patch->is_new <0)3062goto is_new;3063returnerror("%s: does not exist in index", old_name);3064}3065*ce = active_cache[pos];3066if(stat_ret <0) {3067struct checkout costate;3068/* checkout */3069memset(&costate,0,sizeof(costate));3070 costate.base_dir ="";3071 costate.refresh_cache =1;3072if(checkout_entry(*ce, &costate, NULL) ||3073lstat(old_name, st))3074return-1;3075}3076if(!cached &&verify_index_match(*ce, st))3077returnerror("%s: does not match index", old_name);3078if(cached)3079 st_mode = (*ce)->ce_mode;3080}else if(stat_ret <0) {3081if(patch->is_new <0)3082goto is_new;3083returnerror("%s:%s", old_name,strerror(errno));3084}30853086if(!cached && !tpatch)3087 st_mode =ce_mode_from_stat(*ce, st->st_mode);30883089if(patch->is_new <0)3090 patch->is_new =0;3091if(!patch->old_mode)3092 patch->old_mode = st_mode;3093if((st_mode ^ patch->old_mode) & S_IFMT)3094returnerror("%s: wrong type", old_name);3095if(st_mode != patch->old_mode)3096warning("%shas type%o, expected%o",3097 old_name, st_mode, patch->old_mode);3098if(!patch->new_mode && !patch->is_delete)3099 patch->new_mode = st_mode;3100return0;31013102 is_new:3103 patch->is_new =1;3104 patch->is_delete =0;3105 patch->old_name = NULL;3106return0;3107}31083109static intcheck_patch(struct patch *patch)3110{3111struct stat st;3112const char*old_name = patch->old_name;3113const char*new_name = patch->new_name;3114const char*name = old_name ? old_name : new_name;3115struct cache_entry *ce = NULL;3116struct patch *tpatch;3117int ok_if_exists;3118int status;31193120 patch->rejected =1;/* we will drop this after we succeed */31213122 status =check_preimage(patch, &ce, &st);3123if(status)3124return status;3125 old_name = patch->old_name;31263127if((tpatch =in_fn_table(new_name)) &&3128(was_deleted(tpatch) ||to_be_deleted(tpatch)))3129/*3130 * A type-change diff is always split into a patch to3131 * delete old, immediately followed by a patch to3132 * create new (see diff.c::run_diff()); in such a case3133 * it is Ok that the entry to be deleted by the3134 * previous patch is still in the working tree and in3135 * the index.3136 */3137 ok_if_exists =1;3138else3139 ok_if_exists =0;31403141if(new_name &&3142((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {3143if(check_index &&3144cache_name_pos(new_name,strlen(new_name)) >=0&&3145!ok_if_exists)3146returnerror("%s: already exists in index", new_name);3147if(!cached) {3148int err =check_to_create_blob(new_name, ok_if_exists);3149if(err)3150return err;3151}3152if(!patch->new_mode) {3153if(0< patch->is_new)3154 patch->new_mode = S_IFREG |0644;3155else3156 patch->new_mode = patch->old_mode;3157}3158}31593160if(new_name && old_name) {3161int same = !strcmp(old_name, new_name);3162if(!patch->new_mode)3163 patch->new_mode = patch->old_mode;3164if((patch->old_mode ^ patch->new_mode) & S_IFMT)3165returnerror("new mode (%o) of%sdoes not match old mode (%o)%s%s",3166 patch->new_mode, new_name, patch->old_mode,3167 same ?"":" of ", same ?"": old_name);3168}31693170if(apply_data(patch, &st, ce) <0)3171returnerror("%s: patch does not apply", name);3172 patch->rejected =0;3173return0;3174}31753176static intcheck_patch_list(struct patch *patch)3177{3178int err =0;31793180prepare_fn_table(patch);3181while(patch) {3182if(apply_verbosely)3183say_patch_name(stderr,3184"Checking patch ", patch,"...\n");3185 err |=check_patch(patch);3186 patch = patch->next;3187}3188return err;3189}31903191/* This function tries to read the sha1 from the current index */3192static intget_current_sha1(const char*path,unsigned char*sha1)3193{3194int pos;31953196if(read_cache() <0)3197return-1;3198 pos =cache_name_pos(path,strlen(path));3199if(pos <0)3200return-1;3201hashcpy(sha1, active_cache[pos]->sha1);3202return0;3203}32043205/* Build an index that contains the just the files needed for a 3way merge */3206static voidbuild_fake_ancestor(struct patch *list,const char*filename)3207{3208struct patch *patch;3209struct index_state result = { NULL };3210int fd;32113212/* Once we start supporting the reverse patch, it may be3213 * worth showing the new sha1 prefix, but until then...3214 */3215for(patch = list; patch; patch = patch->next) {3216const unsigned char*sha1_ptr;3217unsigned char sha1[20];3218struct cache_entry *ce;3219const char*name;32203221 name = patch->old_name ? patch->old_name : patch->new_name;3222if(0< patch->is_new)3223continue;3224else if(get_sha1(patch->old_sha1_prefix, sha1))3225/* git diff has no index line for mode/type changes */3226if(!patch->lines_added && !patch->lines_deleted) {3227if(get_current_sha1(patch->old_name, sha1))3228die("mode change for%s, which is not "3229"in current HEAD", name);3230 sha1_ptr = sha1;3231}else3232die("sha1 information is lacking or useless "3233"(%s).", name);3234else3235 sha1_ptr = sha1;32363237 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);3238if(!ce)3239die("make_cache_entry failed for path '%s'", name);3240if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3241die("Could not add%sto temporary index", name);3242}32433244 fd =open(filename, O_WRONLY | O_CREAT,0666);3245if(fd <0||write_index(&result, fd) ||close(fd))3246die("Could not write temporary index to%s", filename);32473248discard_index(&result);3249}32503251static voidstat_patch_list(struct patch *patch)3252{3253int files, adds, dels;32543255for(files = adds = dels =0; patch ; patch = patch->next) {3256 files++;3257 adds += patch->lines_added;3258 dels += patch->lines_deleted;3259show_stats(patch);3260}32613262printf("%dfiles changed,%dinsertions(+),%ddeletions(-)\n", files, adds, dels);3263}32643265static voidnumstat_patch_list(struct patch *patch)3266{3267for( ; patch; patch = patch->next) {3268const char*name;3269 name = patch->new_name ? patch->new_name : patch->old_name;3270if(patch->is_binary)3271printf("-\t-\t");3272else3273printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3274write_name_quoted(name, stdout, line_termination);3275}3276}32773278static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3279{3280if(mode)3281printf("%smode%06o%s\n", newdelete, mode, name);3282else3283printf("%s %s\n", newdelete, name);3284}32853286static voidshow_mode_change(struct patch *p,int show_name)3287{3288if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3289if(show_name)3290printf(" mode change%06o =>%06o%s\n",3291 p->old_mode, p->new_mode, p->new_name);3292else3293printf(" mode change%06o =>%06o\n",3294 p->old_mode, p->new_mode);3295}3296}32973298static voidshow_rename_copy(struct patch *p)3299{3300const char*renamecopy = p->is_rename ?"rename":"copy";3301const char*old, *new;33023303/* Find common prefix */3304 old = p->old_name;3305new= p->new_name;3306while(1) {3307const char*slash_old, *slash_new;3308 slash_old =strchr(old,'/');3309 slash_new =strchr(new,'/');3310if(!slash_old ||3311!slash_new ||3312 slash_old - old != slash_new -new||3313memcmp(old,new, slash_new -new))3314break;3315 old = slash_old +1;3316new= slash_new +1;3317}3318/* p->old_name thru old is the common prefix, and old and new3319 * through the end of names are renames3320 */3321if(old != p->old_name)3322printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,3323(int)(old - p->old_name), p->old_name,3324 old,new, p->score);3325else3326printf("%s %s=>%s(%d%%)\n", renamecopy,3327 p->old_name, p->new_name, p->score);3328show_mode_change(p,0);3329}33303331static voidsummary_patch_list(struct patch *patch)3332{3333struct patch *p;33343335for(p = patch; p; p = p->next) {3336if(p->is_new)3337show_file_mode_name("create", p->new_mode, p->new_name);3338else if(p->is_delete)3339show_file_mode_name("delete", p->old_mode, p->old_name);3340else{3341if(p->is_rename || p->is_copy)3342show_rename_copy(p);3343else{3344if(p->score) {3345printf(" rewrite%s(%d%%)\n",3346 p->new_name, p->score);3347show_mode_change(p,0);3348}3349else3350show_mode_change(p,1);3351}3352}3353}3354}33553356static voidpatch_stats(struct patch *patch)3357{3358int lines = patch->lines_added + patch->lines_deleted;33593360if(lines > max_change)3361 max_change = lines;3362if(patch->old_name) {3363int len =quote_c_style(patch->old_name, NULL, NULL,0);3364if(!len)3365 len =strlen(patch->old_name);3366if(len > max_len)3367 max_len = len;3368}3369if(patch->new_name) {3370int len =quote_c_style(patch->new_name, NULL, NULL,0);3371if(!len)3372 len =strlen(patch->new_name);3373if(len > max_len)3374 max_len = len;3375}3376}33773378static voidremove_file(struct patch *patch,int rmdir_empty)3379{3380if(update_index) {3381if(remove_file_from_cache(patch->old_name) <0)3382die("unable to remove%sfrom index", patch->old_name);3383}3384if(!cached) {3385if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {3386remove_path(patch->old_name);3387}3388}3389}33903391static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)3392{3393struct stat st;3394struct cache_entry *ce;3395int namelen =strlen(path);3396unsigned ce_size =cache_entry_size(namelen);33973398if(!update_index)3399return;34003401 ce =xcalloc(1, ce_size);3402memcpy(ce->name, path, namelen);3403 ce->ce_mode =create_ce_mode(mode);3404 ce->ce_flags = namelen;3405if(S_ISGITLINK(mode)) {3406const char*s = buf;34073408if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))3409die("corrupt patch for subproject%s", path);3410}else{3411if(!cached) {3412if(lstat(path, &st) <0)3413die_errno("unable to stat newly created file '%s'",3414 path);3415fill_stat_cache_info(ce, &st);3416}3417if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)3418die("unable to create backing store for newly created file%s", path);3419}3420if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3421die("unable to add cache entry for%s", path);3422}34233424static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)3425{3426int fd;3427struct strbuf nbuf = STRBUF_INIT;34283429if(S_ISGITLINK(mode)) {3430struct stat st;3431if(!lstat(path, &st) &&S_ISDIR(st.st_mode))3432return0;3433returnmkdir(path,0777);3434}34353436if(has_symlinks &&S_ISLNK(mode))3437/* Although buf:size is counted string, it also is NUL3438 * terminated.3439 */3440returnsymlink(buf, path);34413442 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);3443if(fd <0)3444return-1;34453446if(convert_to_working_tree(path, buf, size, &nbuf)) {3447 size = nbuf.len;3448 buf = nbuf.buf;3449}3450write_or_die(fd, buf, size);3451strbuf_release(&nbuf);34523453if(close(fd) <0)3454die_errno("closing file '%s'", path);3455return0;3456}34573458/*3459 * We optimistically assume that the directories exist,3460 * which is true 99% of the time anyway. If they don't,3461 * we create them and try again.3462 */3463static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)3464{3465if(cached)3466return;3467if(!try_create_file(path, mode, buf, size))3468return;34693470if(errno == ENOENT) {3471if(safe_create_leading_directories(path))3472return;3473if(!try_create_file(path, mode, buf, size))3474return;3475}34763477if(errno == EEXIST || errno == EACCES) {3478/* We may be trying to create a file where a directory3479 * used to be.3480 */3481struct stat st;3482if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))3483 errno = EEXIST;3484}34853486if(errno == EEXIST) {3487unsigned int nr =getpid();34883489for(;;) {3490char newpath[PATH_MAX];3491mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);3492if(!try_create_file(newpath, mode, buf, size)) {3493if(!rename(newpath, path))3494return;3495unlink_or_warn(newpath);3496break;3497}3498if(errno != EEXIST)3499break;3500++nr;3501}3502}3503die_errno("unable to write file '%s' mode%o", path, mode);3504}35053506static voidcreate_file(struct patch *patch)3507{3508char*path = patch->new_name;3509unsigned mode = patch->new_mode;3510unsigned long size = patch->resultsize;3511char*buf = patch->result;35123513if(!mode)3514 mode = S_IFREG |0644;3515create_one_file(path, mode, buf, size);3516add_index_file(path, mode, buf, size);3517}35183519/* phase zero is to remove, phase one is to create */3520static voidwrite_out_one_result(struct patch *patch,int phase)3521{3522if(patch->is_delete >0) {3523if(phase ==0)3524remove_file(patch,1);3525return;3526}3527if(patch->is_new >0|| patch->is_copy) {3528if(phase ==1)3529create_file(patch);3530return;3531}3532/*3533 * Rename or modification boils down to the same3534 * thing: remove the old, write the new3535 */3536if(phase ==0)3537remove_file(patch, patch->is_rename);3538if(phase ==1)3539create_file(patch);3540}35413542static intwrite_out_one_reject(struct patch *patch)3543{3544FILE*rej;3545char namebuf[PATH_MAX];3546struct fragment *frag;3547int cnt =0;35483549for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {3550if(!frag->rejected)3551continue;3552 cnt++;3553}35543555if(!cnt) {3556if(apply_verbosely)3557say_patch_name(stderr,3558"Applied patch ", patch," cleanly.\n");3559return0;3560}35613562/* This should not happen, because a removal patch that leaves3563 * contents are marked "rejected" at the patch level.3564 */3565if(!patch->new_name)3566die("internal error");35673568/* Say this even without --verbose */3569say_patch_name(stderr,"Applying patch ", patch," with");3570fprintf(stderr,"%drejects...\n", cnt);35713572 cnt =strlen(patch->new_name);3573if(ARRAY_SIZE(namebuf) <= cnt +5) {3574 cnt =ARRAY_SIZE(namebuf) -5;3575warning("truncating .rej filename to %.*s.rej",3576 cnt -1, patch->new_name);3577}3578memcpy(namebuf, patch->new_name, cnt);3579memcpy(namebuf + cnt,".rej",5);35803581 rej =fopen(namebuf,"w");3582if(!rej)3583returnerror("cannot open%s:%s", namebuf,strerror(errno));35843585/* Normal git tools never deal with .rej, so do not pretend3586 * this is a git patch by saying --git nor give extended3587 * headers. While at it, maybe please "kompare" that wants3588 * the trailing TAB and some garbage at the end of line ;-).3589 */3590fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",3591 patch->new_name, patch->new_name);3592for(cnt =1, frag = patch->fragments;3593 frag;3594 cnt++, frag = frag->next) {3595if(!frag->rejected) {3596fprintf(stderr,"Hunk #%dapplied cleanly.\n", cnt);3597continue;3598}3599fprintf(stderr,"Rejected hunk #%d.\n", cnt);3600fprintf(rej,"%.*s", frag->size, frag->patch);3601if(frag->patch[frag->size-1] !='\n')3602fputc('\n', rej);3603}3604fclose(rej);3605return-1;3606}36073608static intwrite_out_results(struct patch *list)3609{3610int phase;3611int errs =0;3612struct patch *l;36133614for(phase =0; phase <2; phase++) {3615 l = list;3616while(l) {3617if(l->rejected)3618 errs =1;3619else{3620write_out_one_result(l, phase);3621if(phase ==1&&write_out_one_reject(l))3622 errs =1;3623}3624 l = l->next;3625}3626}3627return errs;3628}36293630static struct lock_file lock_file;36313632static struct string_list limit_by_name;3633static int has_include;3634static voidadd_name_limit(const char*name,int exclude)3635{3636struct string_list_item *it;36373638 it =string_list_append(&limit_by_name, name);3639 it->util = exclude ? NULL : (void*)1;3640}36413642static intuse_patch(struct patch *p)3643{3644const char*pathname = p->new_name ? p->new_name : p->old_name;3645int i;36463647/* Paths outside are not touched regardless of "--include" */3648if(0< prefix_length) {3649int pathlen =strlen(pathname);3650if(pathlen <= prefix_length ||3651memcmp(prefix, pathname, prefix_length))3652return0;3653}36543655/* See if it matches any of exclude/include rule */3656for(i =0; i < limit_by_name.nr; i++) {3657struct string_list_item *it = &limit_by_name.items[i];3658if(!fnmatch(it->string, pathname,0))3659return(it->util != NULL);3660}36613662/*3663 * If we had any include, a path that does not match any rule is3664 * not used. Otherwise, we saw bunch of exclude rules (or none)3665 * and such a path is used.3666 */3667return!has_include;3668}366936703671static voidprefix_one(char**name)3672{3673char*old_name = *name;3674if(!old_name)3675return;3676*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3677free(old_name);3678}36793680static voidprefix_patches(struct patch *p)3681{3682if(!prefix || p->is_toplevel_relative)3683return;3684for( ; p; p = p->next) {3685if(p->new_name == p->old_name) {3686char*prefixed = p->new_name;3687prefix_one(&prefixed);3688 p->new_name = p->old_name = prefixed;3689}3690else{3691prefix_one(&p->new_name);3692prefix_one(&p->old_name);3693}3694}3695}36963697#define INACCURATE_EOF (1<<0)3698#define RECOUNT (1<<1)36993700static intapply_patch(int fd,const char*filename,int options)3701{3702size_t offset;3703struct strbuf buf = STRBUF_INIT;3704struct patch *list = NULL, **listp = &list;3705int skipped_patch =0;37063707/* FIXME - memory leak when using multiple patch files as inputs */3708memset(&fn_table,0,sizeof(struct string_list));3709 patch_input_file = filename;3710read_patch_file(&buf, fd);3711 offset =0;3712while(offset < buf.len) {3713struct patch *patch;3714int nr;37153716 patch =xcalloc(1,sizeof(*patch));3717 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3718 patch->recount = !!(options & RECOUNT);3719 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3720if(nr <0)3721break;3722if(apply_in_reverse)3723reverse_patches(patch);3724if(prefix)3725prefix_patches(patch);3726if(use_patch(patch)) {3727patch_stats(patch);3728*listp = patch;3729 listp = &patch->next;3730}3731else{3732/* perhaps free it a bit better? */3733free(patch);3734 skipped_patch++;3735}3736 offset += nr;3737}37383739if(!list && !skipped_patch)3740die("unrecognized input");37413742if(whitespace_error && (ws_error_action == die_on_ws_error))3743 apply =0;37443745 update_index = check_index && apply;3746if(update_index && newfd <0)3747 newfd =hold_locked_index(&lock_file,1);37483749if(check_index) {3750if(read_cache() <0)3751die("unable to read index file");3752}37533754if((check || apply) &&3755check_patch_list(list) <0&&3756!apply_with_reject)3757exit(1);37583759if(apply &&write_out_results(list))3760exit(1);37613762if(fake_ancestor)3763build_fake_ancestor(list, fake_ancestor);37643765if(diffstat)3766stat_patch_list(list);37673768if(numstat)3769numstat_patch_list(list);37703771if(summary)3772summary_patch_list(list);37733774strbuf_release(&buf);3775return0;3776}37773778static intgit_apply_config(const char*var,const char*value,void*cb)3779{3780if(!strcmp(var,"apply.whitespace"))3781returngit_config_string(&apply_default_whitespace, var, value);3782else if(!strcmp(var,"apply.ignorewhitespace"))3783returngit_config_string(&apply_default_ignorewhitespace, var, value);3784returngit_default_config(var, value, cb);3785}37863787static intoption_parse_exclude(const struct option *opt,3788const char*arg,int unset)3789{3790add_name_limit(arg,1);3791return0;3792}37933794static intoption_parse_include(const struct option *opt,3795const char*arg,int unset)3796{3797add_name_limit(arg,0);3798 has_include =1;3799return0;3800}38013802static intoption_parse_p(const struct option *opt,3803const char*arg,int unset)3804{3805 p_value =atoi(arg);3806 p_value_known =1;3807return0;3808}38093810static intoption_parse_z(const struct option *opt,3811const char*arg,int unset)3812{3813if(unset)3814 line_termination ='\n';3815else3816 line_termination =0;3817return0;3818}38193820static intoption_parse_space_change(const struct option *opt,3821const char*arg,int unset)3822{3823if(unset)3824 ws_ignore_action = ignore_ws_none;3825else3826 ws_ignore_action = ignore_ws_change;3827return0;3828}38293830static intoption_parse_whitespace(const struct option *opt,3831const char*arg,int unset)3832{3833const char**whitespace_option = opt->value;38343835*whitespace_option = arg;3836parse_whitespace_option(arg);3837return0;3838}38393840static intoption_parse_directory(const struct option *opt,3841const char*arg,int unset)3842{3843 root_len =strlen(arg);3844if(root_len && arg[root_len -1] !='/') {3845char*new_root;3846 root = new_root =xmalloc(root_len +2);3847strcpy(new_root, arg);3848strcpy(new_root + root_len++,"/");3849}else3850 root = arg;3851return0;3852}38533854intcmd_apply(int argc,const char**argv,const char*prefix_)3855{3856int i;3857int errs =0;3858int is_not_gitdir = !startup_info->have_repository;3859int force_apply =0;38603861const char*whitespace_option = NULL;38623863struct option builtin_apply_options[] = {3864{ OPTION_CALLBACK,0,"exclude", NULL,"path",3865"don't apply changes matching the given path",38660, option_parse_exclude },3867{ OPTION_CALLBACK,0,"include", NULL,"path",3868"apply changes matching the given path",38690, option_parse_include },3870{ OPTION_CALLBACK,'p', NULL, NULL,"num",3871"remove <num> leading slashes from traditional diff paths",38720, option_parse_p },3873OPT_BOOLEAN(0,"no-add", &no_add,3874"ignore additions made by the patch"),3875OPT_BOOLEAN(0,"stat", &diffstat,3876"instead of applying the patch, output diffstat for the input"),3877OPT_NOOP_NOARG(0,"allow-binary-replacement"),3878OPT_NOOP_NOARG(0,"binary"),3879OPT_BOOLEAN(0,"numstat", &numstat,3880"shows number of added and deleted lines in decimal notation"),3881OPT_BOOLEAN(0,"summary", &summary,3882"instead of applying the patch, output a summary for the input"),3883OPT_BOOLEAN(0,"check", &check,3884"instead of applying the patch, see if the patch is applicable"),3885OPT_BOOLEAN(0,"index", &check_index,3886"make sure the patch is applicable to the current index"),3887OPT_BOOLEAN(0,"cached", &cached,3888"apply a patch without touching the working tree"),3889OPT_BOOLEAN(0,"apply", &force_apply,3890"also apply the patch (use with --stat/--summary/--check)"),3891OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,3892"build a temporary index based on embedded index information"),3893{ OPTION_CALLBACK,'z', NULL, NULL, NULL,3894"paths are separated with NUL character",3895 PARSE_OPT_NOARG, option_parse_z },3896OPT_INTEGER('C', NULL, &p_context,3897"ensure at least <n> lines of context match"),3898{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,"action",3899"detect new or modified lines that have whitespace errors",39000, option_parse_whitespace },3901{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,3902"ignore changes in whitespace when finding context",3903 PARSE_OPT_NOARG, option_parse_space_change },3904{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,3905"ignore changes in whitespace when finding context",3906 PARSE_OPT_NOARG, option_parse_space_change },3907OPT_BOOLEAN('R',"reverse", &apply_in_reverse,3908"apply the patch in reverse"),3909OPT_BOOLEAN(0,"unidiff-zero", &unidiff_zero,3910"don't expect at least one line of context"),3911OPT_BOOLEAN(0,"reject", &apply_with_reject,3912"leave the rejected hunks in corresponding *.rej files"),3913OPT_BOOLEAN(0,"allow-overlap", &allow_overlap,3914"allow overlapping hunks"),3915OPT__VERBOSE(&apply_verbosely,"be verbose"),3916OPT_BIT(0,"inaccurate-eof", &options,3917"tolerate incorrectly detected missing new-line at the end of file",3918 INACCURATE_EOF),3919OPT_BIT(0,"recount", &options,3920"do not trust the line counts in the hunk headers",3921 RECOUNT),3922{ OPTION_CALLBACK,0,"directory", NULL,"root",3923"prepend <root> to all filenames",39240, option_parse_directory },3925OPT_END()3926};39273928 prefix = prefix_;3929 prefix_length = prefix ?strlen(prefix) :0;3930git_config(git_apply_config, NULL);3931if(apply_default_whitespace)3932parse_whitespace_option(apply_default_whitespace);3933if(apply_default_ignorewhitespace)3934parse_ignorewhitespace_option(apply_default_ignorewhitespace);39353936 argc =parse_options(argc, argv, prefix, builtin_apply_options,3937 apply_usage,0);39383939if(apply_with_reject)3940 apply = apply_verbosely =1;3941if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))3942 apply =0;3943if(check_index && is_not_gitdir)3944die("--index outside a repository");3945if(cached) {3946if(is_not_gitdir)3947die("--cached outside a repository");3948 check_index =1;3949}3950for(i =0; i < argc; i++) {3951const char*arg = argv[i];3952int fd;39533954if(!strcmp(arg,"-")) {3955 errs |=apply_patch(0,"<stdin>", options);3956 read_stdin =0;3957continue;3958}else if(0< prefix_length)3959 arg =prefix_filename(prefix, prefix_length, arg);39603961 fd =open(arg, O_RDONLY);3962if(fd <0)3963die_errno("can't open patch '%s'", arg);3964 read_stdin =0;3965set_default_whitespace_mode(whitespace_option);3966 errs |=apply_patch(fd, arg, options);3967close(fd);3968}3969set_default_whitespace_mode(whitespace_option);3970if(read_stdin)3971 errs |=apply_patch(0,"<stdin>", options);3972if(whitespace_error) {3973if(squelch_whitespace_errors &&3974 squelch_whitespace_errors < whitespace_error) {3975int squelched =3976 whitespace_error - squelch_whitespace_errors;3977warning("squelched%d"3978"whitespace error%s",3979 squelched,3980 squelched ==1?"":"s");3981}3982if(ws_error_action == die_on_ws_error)3983die("%dline%sadd%swhitespace errors.",3984 whitespace_error,3985 whitespace_error ==1?"":"s",3986 whitespace_error ==1?"s":"");3987if(applied_after_fixing_ws && apply)3988warning("%dline%sapplied after"3989" fixing whitespace errors.",3990 applied_after_fixing_ws,3991 applied_after_fixing_ws ==1?"":"s");3992else if(whitespace_error)3993warning("%dline%sadd%swhitespace errors.",3994 whitespace_error,3995 whitespace_error ==1?"":"s",3996 whitespace_error ==1?"s":"");3997}39983999if(update_index) {4000if(write_cache(newfd, active_cache, active_nr) ||4001commit_locked_index(&lock_file))4002die("Unable to write new index file");4003}40044005return!!errs;4006}