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}10241025static const char*stop_at_slash(const char*line,int llen)1026{1027int nslash = p_value;1028int i;10291030for(i =0; i < llen; i++) {1031int ch = line[i];1032if(ch =='/'&& --nslash <=0)1033return&line[i];1034}1035return NULL;1036}10371038/*1039 * This is to extract the same name that appears on "diff --git"1040 * line. We do not find and return anything if it is a rename1041 * patch, and it is OK because we will find the name elsewhere.1042 * We need to reliably find name only when it is mode-change only,1043 * creation or deletion of an empty file. In any of these cases,1044 * both sides are the same name under a/ and b/ respectively.1045 */1046static char*git_header_name(char*line,int llen)1047{1048const char*name;1049const char*second = NULL;1050size_t len, line_len;10511052 line +=strlen("diff --git ");1053 llen -=strlen("diff --git ");10541055if(*line =='"') {1056const char*cp;1057struct strbuf first = STRBUF_INIT;1058struct strbuf sp = STRBUF_INIT;10591060if(unquote_c_style(&first, line, &second))1061goto free_and_fail1;10621063/* advance to the first slash */1064 cp =stop_at_slash(first.buf, first.len);1065/* we do not accept absolute paths */1066if(!cp || cp == first.buf)1067goto free_and_fail1;1068strbuf_remove(&first,0, cp +1- first.buf);10691070/*1071 * second points at one past closing dq of name.1072 * find the second name.1073 */1074while((second < line + llen) &&isspace(*second))1075 second++;10761077if(line + llen <= second)1078goto free_and_fail1;1079if(*second =='"') {1080if(unquote_c_style(&sp, second, NULL))1081goto free_and_fail1;1082 cp =stop_at_slash(sp.buf, sp.len);1083if(!cp || cp == sp.buf)1084goto free_and_fail1;1085/* They must match, otherwise ignore */1086if(strcmp(cp +1, first.buf))1087goto free_and_fail1;1088strbuf_release(&sp);1089returnstrbuf_detach(&first, NULL);1090}10911092/* unquoted second */1093 cp =stop_at_slash(second, line + llen - second);1094if(!cp || cp == second)1095goto free_and_fail1;1096 cp++;1097if(line + llen - cp != first.len +1||1098memcmp(first.buf, cp, first.len))1099goto free_and_fail1;1100returnstrbuf_detach(&first, NULL);11011102 free_and_fail1:1103strbuf_release(&first);1104strbuf_release(&sp);1105return NULL;1106}11071108/* unquoted first name */1109 name =stop_at_slash(line, llen);1110if(!name || name == line)1111return NULL;1112 name++;11131114/*1115 * since the first name is unquoted, a dq if exists must be1116 * the beginning of the second name.1117 */1118for(second = name; second < line + llen; second++) {1119if(*second =='"') {1120struct strbuf sp = STRBUF_INIT;1121const char*np;11221123if(unquote_c_style(&sp, second, NULL))1124goto free_and_fail2;11251126 np =stop_at_slash(sp.buf, sp.len);1127if(!np || np == sp.buf)1128goto free_and_fail2;1129 np++;11301131 len = sp.buf + sp.len - np;1132if(len < second - name &&1133!strncmp(np, name, len) &&1134isspace(name[len])) {1135/* Good */1136strbuf_remove(&sp,0, np - sp.buf);1137returnstrbuf_detach(&sp, NULL);1138}11391140 free_and_fail2:1141strbuf_release(&sp);1142return NULL;1143}1144}11451146/*1147 * Accept a name only if it shows up twice, exactly the same1148 * form.1149 */1150 second =strchr(name,'\n');1151if(!second)1152return NULL;1153 line_len = second - name;1154for(len =0; ; len++) {1155switch(name[len]) {1156default:1157continue;1158case'\n':1159return NULL;1160case'\t':case' ':1161 second =stop_at_slash(name + len, line_len - len);1162if(!second)1163return NULL;1164 second++;1165if(second[len] =='\n'&& !strncmp(name, second, len)) {1166returnxmemdupz(name, len);1167}1168}1169}1170}11711172/* Verify that we recognize the lines following a git header */1173static intparse_git_header(char*line,int len,unsigned int size,struct patch *patch)1174{1175unsigned long offset;11761177/* A git diff has explicit new/delete information, so we don't guess */1178 patch->is_new =0;1179 patch->is_delete =0;11801181/*1182 * Some things may not have the old name in the1183 * rest of the headers anywhere (pure mode changes,1184 * or removing or adding empty files), so we get1185 * the default name from the header.1186 */1187 patch->def_name =git_header_name(line, len);1188if(patch->def_name && root) {1189char*s =xmalloc(root_len +strlen(patch->def_name) +1);1190strcpy(s, root);1191strcpy(s + root_len, patch->def_name);1192free(patch->def_name);1193 patch->def_name = s;1194}11951196 line += len;1197 size -= len;1198 linenr++;1199for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) {1200static const struct opentry {1201const char*str;1202int(*fn)(const char*,struct patch *);1203} optable[] = {1204{"@@ -", gitdiff_hdrend },1205{"--- ", gitdiff_oldname },1206{"+++ ", gitdiff_newname },1207{"old mode ", gitdiff_oldmode },1208{"new mode ", gitdiff_newmode },1209{"deleted file mode ", gitdiff_delete },1210{"new file mode ", gitdiff_newfile },1211{"copy from ", gitdiff_copysrc },1212{"copy to ", gitdiff_copydst },1213{"rename old ", gitdiff_renamesrc },1214{"rename new ", gitdiff_renamedst },1215{"rename from ", gitdiff_renamesrc },1216{"rename to ", gitdiff_renamedst },1217{"similarity index ", gitdiff_similarity },1218{"dissimilarity index ", gitdiff_dissimilarity },1219{"index ", gitdiff_index },1220{"", gitdiff_unrecognized },1221};1222int i;12231224 len =linelen(line, size);1225if(!len || line[len-1] !='\n')1226break;1227for(i =0; i <ARRAY_SIZE(optable); i++) {1228const struct opentry *p = optable + i;1229int oplen =strlen(p->str);1230if(len < oplen ||memcmp(p->str, line, oplen))1231continue;1232if(p->fn(line + oplen, patch) <0)1233return offset;1234break;1235}1236}12371238return offset;1239}12401241static intparse_num(const char*line,unsigned long*p)1242{1243char*ptr;12441245if(!isdigit(*line))1246return0;1247*p =strtoul(line, &ptr,10);1248return ptr - line;1249}12501251static intparse_range(const char*line,int len,int offset,const char*expect,1252unsigned long*p1,unsigned long*p2)1253{1254int digits, ex;12551256if(offset <0|| offset >= len)1257return-1;1258 line += offset;1259 len -= offset;12601261 digits =parse_num(line, p1);1262if(!digits)1263return-1;12641265 offset += digits;1266 line += digits;1267 len -= digits;12681269*p2 =1;1270if(*line ==',') {1271 digits =parse_num(line+1, p2);1272if(!digits)1273return-1;12741275 offset += digits+1;1276 line += digits+1;1277 len -= digits+1;1278}12791280 ex =strlen(expect);1281if(ex > len)1282return-1;1283if(memcmp(line, expect, ex))1284return-1;12851286return offset + ex;1287}12881289static voidrecount_diff(char*line,int size,struct fragment *fragment)1290{1291int oldlines =0, newlines =0, ret =0;12921293if(size <1) {1294warning("recount: ignore empty hunk");1295return;1296}12971298for(;;) {1299int len =linelen(line, size);1300 size -= len;1301 line += len;13021303if(size <1)1304break;13051306switch(*line) {1307case' ':case'\n':1308 newlines++;1309/* fall through */1310case'-':1311 oldlines++;1312continue;1313case'+':1314 newlines++;1315continue;1316case'\\':1317continue;1318case'@':1319 ret = size <3||prefixcmp(line,"@@ ");1320break;1321case'd':1322 ret = size <5||prefixcmp(line,"diff ");1323break;1324default:1325 ret = -1;1326break;1327}1328if(ret) {1329warning("recount: unexpected line: %.*s",1330(int)linelen(line, size), line);1331return;1332}1333break;1334}1335 fragment->oldlines = oldlines;1336 fragment->newlines = newlines;1337}13381339/*1340 * Parse a unified diff fragment header of the1341 * form "@@ -a,b +c,d @@"1342 */1343static intparse_fragment_header(char*line,int len,struct fragment *fragment)1344{1345int offset;13461347if(!len || line[len-1] !='\n')1348return-1;13491350/* Figure out the number of lines in a fragment */1351 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1352 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);13531354return offset;1355}13561357static intfind_header(char*line,unsigned long size,int*hdrsize,struct patch *patch)1358{1359unsigned long offset, len;13601361 patch->is_toplevel_relative =0;1362 patch->is_rename = patch->is_copy =0;1363 patch->is_new = patch->is_delete = -1;1364 patch->old_mode = patch->new_mode =0;1365 patch->old_name = patch->new_name = NULL;1366for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) {1367unsigned long nextlen;13681369 len =linelen(line, size);1370if(!len)1371break;13721373/* Testing this early allows us to take a few shortcuts.. */1374if(len <6)1375continue;13761377/*1378 * Make sure we don't find any unconnected patch fragments.1379 * That's a sign that we didn't find a header, and that a1380 * patch has become corrupted/broken up.1381 */1382if(!memcmp("@@ -", line,4)) {1383struct fragment dummy;1384if(parse_fragment_header(line, len, &dummy) <0)1385continue;1386die("patch fragment without header at line%d: %.*s",1387 linenr, (int)len-1, line);1388}13891390if(size < len +6)1391break;13921393/*1394 * Git patch? It might not have a real patch, just a rename1395 * or mode change, so we handle that specially1396 */1397if(!memcmp("diff --git ", line,11)) {1398int git_hdr_len =parse_git_header(line, len, size, patch);1399if(git_hdr_len <= len)1400continue;1401if(!patch->old_name && !patch->new_name) {1402if(!patch->def_name)1403die("git diff header lacks filename information when removing "1404"%dleading pathname components (line%d)", p_value, linenr);1405 patch->old_name = patch->new_name = patch->def_name;1406}1407if(!patch->is_delete && !patch->new_name)1408die("git diff header lacks filename information "1409"(line%d)", linenr);1410 patch->is_toplevel_relative =1;1411*hdrsize = git_hdr_len;1412return offset;1413}14141415/* --- followed by +++ ? */1416if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1417continue;14181419/*1420 * We only accept unified patches, so we want it to1421 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1422 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1423 */1424 nextlen =linelen(line + len, size - len);1425if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1426continue;14271428/* Ok, we'll consider it a patch */1429parse_traditional_patch(line, line+len, patch);1430*hdrsize = len + nextlen;1431 linenr +=2;1432return offset;1433}1434return-1;1435}14361437static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1438{1439char*err;14401441if(!result)1442return;14431444 whitespace_error++;1445if(squelch_whitespace_errors &&1446 squelch_whitespace_errors < whitespace_error)1447return;14481449 err =whitespace_error_string(result);1450fprintf(stderr,"%s:%d:%s.\n%.*s\n",1451 patch_input_file, linenr, err, len, line);1452free(err);1453}14541455static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1456{1457unsigned result =ws_check(line +1, len -1, ws_rule);14581459record_ws_error(result, line +1, len -2, linenr);1460}14611462/*1463 * Parse a unified diff. Note that this really needs to parse each1464 * fragment separately, since the only way to know the difference1465 * between a "---" that is part of a patch, and a "---" that starts1466 * the next patch is to look at the line counts..1467 */1468static intparse_fragment(char*line,unsigned long size,1469struct patch *patch,struct fragment *fragment)1470{1471int added, deleted;1472int len =linelen(line, size), offset;1473unsigned long oldlines, newlines;1474unsigned long leading, trailing;14751476 offset =parse_fragment_header(line, len, fragment);1477if(offset <0)1478return-1;1479if(offset >0&& patch->recount)1480recount_diff(line + offset, size - offset, fragment);1481 oldlines = fragment->oldlines;1482 newlines = fragment->newlines;1483 leading =0;1484 trailing =0;14851486/* Parse the thing.. */1487 line += len;1488 size -= len;1489 linenr++;1490 added = deleted =0;1491for(offset = len;14920< size;1493 offset += len, size -= len, line += len, linenr++) {1494if(!oldlines && !newlines)1495break;1496 len =linelen(line, size);1497if(!len || line[len-1] !='\n')1498return-1;1499switch(*line) {1500default:1501return-1;1502case'\n':/* newer GNU diff, an empty context line */1503case' ':1504 oldlines--;1505 newlines--;1506if(!deleted && !added)1507 leading++;1508 trailing++;1509break;1510case'-':1511if(apply_in_reverse &&1512 ws_error_action != nowarn_ws_error)1513check_whitespace(line, len, patch->ws_rule);1514 deleted++;1515 oldlines--;1516 trailing =0;1517break;1518case'+':1519if(!apply_in_reverse &&1520 ws_error_action != nowarn_ws_error)1521check_whitespace(line, len, patch->ws_rule);1522 added++;1523 newlines--;1524 trailing =0;1525break;15261527/*1528 * We allow "\ No newline at end of file". Depending1529 * on locale settings when the patch was produced we1530 * don't know what this line looks like. The only1531 * thing we do know is that it begins with "\ ".1532 * Checking for 12 is just for sanity check -- any1533 * l10n of "\ No newline..." is at least that long.1534 */1535case'\\':1536if(len <12||memcmp(line,"\\",2))1537return-1;1538break;1539}1540}1541if(oldlines || newlines)1542return-1;1543 fragment->leading = leading;1544 fragment->trailing = trailing;15451546/*1547 * If a fragment ends with an incomplete line, we failed to include1548 * it in the above loop because we hit oldlines == newlines == 01549 * before seeing it.1550 */1551if(12< size && !memcmp(line,"\\",2))1552 offset +=linelen(line, size);15531554 patch->lines_added += added;1555 patch->lines_deleted += deleted;15561557if(0< patch->is_new && oldlines)1558returnerror("new file depends on old contents");1559if(0< patch->is_delete && newlines)1560returnerror("deleted file still has contents");1561return offset;1562}15631564static intparse_single_patch(char*line,unsigned long size,struct patch *patch)1565{1566unsigned long offset =0;1567unsigned long oldlines =0, newlines =0, context =0;1568struct fragment **fragp = &patch->fragments;15691570while(size >4&& !memcmp(line,"@@ -",4)) {1571struct fragment *fragment;1572int len;15731574 fragment =xcalloc(1,sizeof(*fragment));1575 fragment->linenr = linenr;1576 len =parse_fragment(line, size, patch, fragment);1577if(len <=0)1578die("corrupt patch at line%d", linenr);1579 fragment->patch = line;1580 fragment->size = len;1581 oldlines += fragment->oldlines;1582 newlines += fragment->newlines;1583 context += fragment->leading + fragment->trailing;15841585*fragp = fragment;1586 fragp = &fragment->next;15871588 offset += len;1589 line += len;1590 size -= len;1591}15921593/*1594 * If something was removed (i.e. we have old-lines) it cannot1595 * be creation, and if something was added it cannot be1596 * deletion. However, the reverse is not true; --unified=01597 * patches that only add are not necessarily creation even1598 * though they do not have any old lines, and ones that only1599 * delete are not necessarily deletion.1600 *1601 * Unfortunately, a real creation/deletion patch do _not_ have1602 * any context line by definition, so we cannot safely tell it1603 * apart with --unified=0 insanity. At least if the patch has1604 * more than one hunk it is not creation or deletion.1605 */1606if(patch->is_new <0&&1607(oldlines || (patch->fragments && patch->fragments->next)))1608 patch->is_new =0;1609if(patch->is_delete <0&&1610(newlines || (patch->fragments && patch->fragments->next)))1611 patch->is_delete =0;16121613if(0< patch->is_new && oldlines)1614die("new file%sdepends on old contents", patch->new_name);1615if(0< patch->is_delete && newlines)1616die("deleted file%sstill has contents", patch->old_name);1617if(!patch->is_delete && !newlines && context)1618fprintf(stderr,"** warning: file%sbecomes empty but "1619"is not deleted\n", patch->new_name);16201621return offset;1622}16231624staticinlineintmetadata_changes(struct patch *patch)1625{1626return patch->is_rename >0||1627 patch->is_copy >0||1628 patch->is_new >0||1629 patch->is_delete ||1630(patch->old_mode && patch->new_mode &&1631 patch->old_mode != patch->new_mode);1632}16331634static char*inflate_it(const void*data,unsigned long size,1635unsigned long inflated_size)1636{1637 git_zstream stream;1638void*out;1639int st;16401641memset(&stream,0,sizeof(stream));16421643 stream.next_in = (unsigned char*)data;1644 stream.avail_in = size;1645 stream.next_out = out =xmalloc(inflated_size);1646 stream.avail_out = inflated_size;1647git_inflate_init(&stream);1648 st =git_inflate(&stream, Z_FINISH);1649git_inflate_end(&stream);1650if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1651free(out);1652return NULL;1653}1654return out;1655}16561657static struct fragment *parse_binary_hunk(char**buf_p,1658unsigned long*sz_p,1659int*status_p,1660int*used_p)1661{1662/*1663 * Expect a line that begins with binary patch method ("literal"1664 * or "delta"), followed by the length of data before deflating.1665 * a sequence of 'length-byte' followed by base-85 encoded data1666 * should follow, terminated by a newline.1667 *1668 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1669 * and we would limit the patch line to 66 characters,1670 * so one line can fit up to 13 groups that would decode1671 * to 52 bytes max. The length byte 'A'-'Z' corresponds1672 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1673 */1674int llen, used;1675unsigned long size = *sz_p;1676char*buffer = *buf_p;1677int patch_method;1678unsigned long origlen;1679char*data = NULL;1680int hunk_size =0;1681struct fragment *frag;16821683 llen =linelen(buffer, size);1684 used = llen;16851686*status_p =0;16871688if(!prefixcmp(buffer,"delta ")) {1689 patch_method = BINARY_DELTA_DEFLATED;1690 origlen =strtoul(buffer +6, NULL,10);1691}1692else if(!prefixcmp(buffer,"literal ")) {1693 patch_method = BINARY_LITERAL_DEFLATED;1694 origlen =strtoul(buffer +8, NULL,10);1695}1696else1697return NULL;16981699 linenr++;1700 buffer += llen;1701while(1) {1702int byte_length, max_byte_length, newsize;1703 llen =linelen(buffer, size);1704 used += llen;1705 linenr++;1706if(llen ==1) {1707/* consume the blank line */1708 buffer++;1709 size--;1710break;1711}1712/*1713 * Minimum line is "A00000\n" which is 7-byte long,1714 * and the line length must be multiple of 5 plus 2.1715 */1716if((llen <7) || (llen-2) %5)1717goto corrupt;1718 max_byte_length = (llen -2) /5*4;1719 byte_length = *buffer;1720if('A'<= byte_length && byte_length <='Z')1721 byte_length = byte_length -'A'+1;1722else if('a'<= byte_length && byte_length <='z')1723 byte_length = byte_length -'a'+27;1724else1725goto corrupt;1726/* if the input length was not multiple of 4, we would1727 * have filler at the end but the filler should never1728 * exceed 3 bytes1729 */1730if(max_byte_length < byte_length ||1731 byte_length <= max_byte_length -4)1732goto corrupt;1733 newsize = hunk_size + byte_length;1734 data =xrealloc(data, newsize);1735if(decode_85(data + hunk_size, buffer +1, byte_length))1736goto corrupt;1737 hunk_size = newsize;1738 buffer += llen;1739 size -= llen;1740}17411742 frag =xcalloc(1,sizeof(*frag));1743 frag->patch =inflate_it(data, hunk_size, origlen);1744if(!frag->patch)1745goto corrupt;1746free(data);1747 frag->size = origlen;1748*buf_p = buffer;1749*sz_p = size;1750*used_p = used;1751 frag->binary_patch_method = patch_method;1752return frag;17531754 corrupt:1755free(data);1756*status_p = -1;1757error("corrupt binary patch at line%d: %.*s",1758 linenr-1, llen-1, buffer);1759return NULL;1760}17611762static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1763{1764/*1765 * We have read "GIT binary patch\n"; what follows is a line1766 * that says the patch method (currently, either "literal" or1767 * "delta") and the length of data before deflating; a1768 * sequence of 'length-byte' followed by base-85 encoded data1769 * follows.1770 *1771 * When a binary patch is reversible, there is another binary1772 * hunk in the same format, starting with patch method (either1773 * "literal" or "delta") with the length of data, and a sequence1774 * of length-byte + base-85 encoded data, terminated with another1775 * empty line. This data, when applied to the postimage, produces1776 * the preimage.1777 */1778struct fragment *forward;1779struct fragment *reverse;1780int status;1781int used, used_1;17821783 forward =parse_binary_hunk(&buffer, &size, &status, &used);1784if(!forward && !status)1785/* there has to be one hunk (forward hunk) */1786returnerror("unrecognized binary patch at line%d", linenr-1);1787if(status)1788/* otherwise we already gave an error message */1789return status;17901791 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1792if(reverse)1793 used += used_1;1794else if(status) {1795/*1796 * Not having reverse hunk is not an error, but having1797 * a corrupt reverse hunk is.1798 */1799free((void*) forward->patch);1800free(forward);1801return status;1802}1803 forward->next = reverse;1804 patch->fragments = forward;1805 patch->is_binary =1;1806return used;1807}18081809static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1810{1811int hdrsize, patchsize;1812int offset =find_header(buffer, size, &hdrsize, patch);18131814if(offset <0)1815return offset;18161817 patch->ws_rule =whitespace_rule(patch->new_name1818? patch->new_name1819: patch->old_name);18201821 patchsize =parse_single_patch(buffer + offset + hdrsize,1822 size - offset - hdrsize, patch);18231824if(!patchsize) {1825static const char*binhdr[] = {1826"Binary files ",1827"Files ",1828 NULL,1829};1830static const char git_binary[] ="GIT binary patch\n";1831int i;1832int hd = hdrsize + offset;1833unsigned long llen =linelen(buffer + hd, size - hd);18341835if(llen ==sizeof(git_binary) -1&&1836!memcmp(git_binary, buffer + hd, llen)) {1837int used;1838 linenr++;1839 used =parse_binary(buffer + hd + llen,1840 size - hd - llen, patch);1841if(used)1842 patchsize = used + llen;1843else1844 patchsize =0;1845}1846else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1847for(i =0; binhdr[i]; i++) {1848int len =strlen(binhdr[i]);1849if(len < size - hd &&1850!memcmp(binhdr[i], buffer + hd, len)) {1851 linenr++;1852 patch->is_binary =1;1853 patchsize = llen;1854break;1855}1856}1857}18581859/* Empty patch cannot be applied if it is a text patch1860 * without metadata change. A binary patch appears1861 * empty to us here.1862 */1863if((apply || check) &&1864(!patch->is_binary && !metadata_changes(patch)))1865die("patch with only garbage at line%d", linenr);1866}18671868return offset + hdrsize + patchsize;1869}18701871#define swap(a,b) myswap((a),(b),sizeof(a))18721873#define myswap(a, b, size) do { \1874 unsigned char mytmp[size]; \1875 memcpy(mytmp, &a, size); \1876 memcpy(&a, &b, size); \1877 memcpy(&b, mytmp, size); \1878} while (0)18791880static voidreverse_patches(struct patch *p)1881{1882for(; p; p = p->next) {1883struct fragment *frag = p->fragments;18841885swap(p->new_name, p->old_name);1886swap(p->new_mode, p->old_mode);1887swap(p->is_new, p->is_delete);1888swap(p->lines_added, p->lines_deleted);1889swap(p->old_sha1_prefix, p->new_sha1_prefix);18901891for(; frag; frag = frag->next) {1892swap(frag->newpos, frag->oldpos);1893swap(frag->newlines, frag->oldlines);1894}1895}1896}18971898static const char pluses[] =1899"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";1900static const char minuses[]=1901"----------------------------------------------------------------------";19021903static voidshow_stats(struct patch *patch)1904{1905struct strbuf qname = STRBUF_INIT;1906char*cp = patch->new_name ? patch->new_name : patch->old_name;1907int max, add, del;19081909quote_c_style(cp, &qname, NULL,0);19101911/*1912 * "scale" the filename1913 */1914 max = max_len;1915if(max >50)1916 max =50;19171918if(qname.len > max) {1919 cp =strchr(qname.buf + qname.len +3- max,'/');1920if(!cp)1921 cp = qname.buf + qname.len +3- max;1922strbuf_splice(&qname,0, cp - qname.buf,"...",3);1923}19241925if(patch->is_binary) {1926printf(" %-*s | Bin\n", max, qname.buf);1927strbuf_release(&qname);1928return;1929}19301931printf(" %-*s |", max, qname.buf);1932strbuf_release(&qname);19331934/*1935 * scale the add/delete1936 */1937 max = max + max_change >70?70- max : max_change;1938 add = patch->lines_added;1939 del = patch->lines_deleted;19401941if(max_change >0) {1942int total = ((add + del) * max + max_change /2) / max_change;1943 add = (add * max + max_change /2) / max_change;1944 del = total - add;1945}1946printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,1947 add, pluses, del, minuses);1948}19491950static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)1951{1952switch(st->st_mode & S_IFMT) {1953case S_IFLNK:1954if(strbuf_readlink(buf, path, st->st_size) <0)1955returnerror("unable to read symlink%s", path);1956return0;1957case S_IFREG:1958if(strbuf_read_file(buf, path, st->st_size) != st->st_size)1959returnerror("unable to open or read%s", path);1960convert_to_git(path, buf->buf, buf->len, buf,0);1961return0;1962default:1963return-1;1964}1965}19661967/*1968 * Update the preimage, and the common lines in postimage,1969 * from buffer buf of length len. If postlen is 0 the postimage1970 * is updated in place, otherwise it's updated on a new buffer1971 * of length postlen1972 */19731974static voidupdate_pre_post_images(struct image *preimage,1975struct image *postimage,1976char*buf,1977size_t len,size_t postlen)1978{1979int i, ctx;1980char*new, *old, *fixed;1981struct image fixed_preimage;19821983/*1984 * Update the preimage with whitespace fixes. Note that we1985 * are not losing preimage->buf -- apply_one_fragment() will1986 * free "oldlines".1987 */1988prepare_image(&fixed_preimage, buf, len,1);1989assert(fixed_preimage.nr == preimage->nr);1990for(i =0; i < preimage->nr; i++)1991 fixed_preimage.line[i].flag = preimage->line[i].flag;1992free(preimage->line_allocated);1993*preimage = fixed_preimage;19941995/*1996 * Adjust the common context lines in postimage. This can be1997 * done in-place when we are just doing whitespace fixing,1998 * which does not make the string grow, but needs a new buffer1999 * when ignoring whitespace causes the update, since in this case2000 * we could have e.g. tabs converted to multiple spaces.2001 * We trust the caller to tell us if the update can be done2002 * in place (postlen==0) or not.2003 */2004 old = postimage->buf;2005if(postlen)2006new= postimage->buf =xmalloc(postlen);2007else2008new= old;2009 fixed = preimage->buf;2010for(i = ctx =0; i < postimage->nr; i++) {2011size_t len = postimage->line[i].len;2012if(!(postimage->line[i].flag & LINE_COMMON)) {2013/* an added line -- no counterparts in preimage */2014memmove(new, old, len);2015 old += len;2016new+= len;2017continue;2018}20192020/* a common context -- skip it in the original postimage */2021 old += len;20222023/* and find the corresponding one in the fixed preimage */2024while(ctx < preimage->nr &&2025!(preimage->line[ctx].flag & LINE_COMMON)) {2026 fixed += preimage->line[ctx].len;2027 ctx++;2028}2029if(preimage->nr <= ctx)2030die("oops");20312032/* and copy it in, while fixing the line length */2033 len = preimage->line[ctx].len;2034memcpy(new, fixed, len);2035new+= len;2036 fixed += len;2037 postimage->line[i].len = len;2038 ctx++;2039}20402041/* Fix the length of the whole thing */2042 postimage->len =new- postimage->buf;2043}20442045static intmatch_fragment(struct image *img,2046struct image *preimage,2047struct image *postimage,2048unsigned longtry,2049int try_lno,2050unsigned ws_rule,2051int match_beginning,int match_end)2052{2053int i;2054char*fixed_buf, *buf, *orig, *target;2055struct strbuf fixed;2056size_t fixed_len;2057int preimage_limit;20582059if(preimage->nr + try_lno <= img->nr) {2060/*2061 * The hunk falls within the boundaries of img.2062 */2063 preimage_limit = preimage->nr;2064if(match_end && (preimage->nr + try_lno != img->nr))2065return0;2066}else if(ws_error_action == correct_ws_error &&2067(ws_rule & WS_BLANK_AT_EOF)) {2068/*2069 * This hunk extends beyond the end of img, and we are2070 * removing blank lines at the end of the file. This2071 * many lines from the beginning of the preimage must2072 * match with img, and the remainder of the preimage2073 * must be blank.2074 */2075 preimage_limit = img->nr - try_lno;2076}else{2077/*2078 * The hunk extends beyond the end of the img and2079 * we are not removing blanks at the end, so we2080 * should reject the hunk at this position.2081 */2082return0;2083}20842085if(match_beginning && try_lno)2086return0;20872088/* Quick hash check */2089for(i =0; i < preimage_limit; i++)2090if((img->line[try_lno + i].flag & LINE_PATCHED) ||2091(preimage->line[i].hash != img->line[try_lno + i].hash))2092return0;20932094if(preimage_limit == preimage->nr) {2095/*2096 * Do we have an exact match? If we were told to match2097 * at the end, size must be exactly at try+fragsize,2098 * otherwise try+fragsize must be still within the preimage,2099 * and either case, the old piece should match the preimage2100 * exactly.2101 */2102if((match_end2103? (try+ preimage->len == img->len)2104: (try+ preimage->len <= img->len)) &&2105!memcmp(img->buf +try, preimage->buf, preimage->len))2106return1;2107}else{2108/*2109 * The preimage extends beyond the end of img, so2110 * there cannot be an exact match.2111 *2112 * There must be one non-blank context line that match2113 * a line before the end of img.2114 */2115char*buf_end;21162117 buf = preimage->buf;2118 buf_end = buf;2119for(i =0; i < preimage_limit; i++)2120 buf_end += preimage->line[i].len;21212122for( ; buf < buf_end; buf++)2123if(!isspace(*buf))2124break;2125if(buf == buf_end)2126return0;2127}21282129/*2130 * No exact match. If we are ignoring whitespace, run a line-by-line2131 * fuzzy matching. We collect all the line length information because2132 * we need it to adjust whitespace if we match.2133 */2134if(ws_ignore_action == ignore_ws_change) {2135size_t imgoff =0;2136size_t preoff =0;2137size_t postlen = postimage->len;2138size_t extra_chars;2139char*preimage_eof;2140char*preimage_end;2141for(i =0; i < preimage_limit; i++) {2142size_t prelen = preimage->line[i].len;2143size_t imglen = img->line[try_lno+i].len;21442145if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2146 preimage->buf + preoff, prelen))2147return0;2148if(preimage->line[i].flag & LINE_COMMON)2149 postlen += imglen - prelen;2150 imgoff += imglen;2151 preoff += prelen;2152}21532154/*2155 * Ok, the preimage matches with whitespace fuzz.2156 *2157 * imgoff now holds the true length of the target that2158 * matches the preimage before the end of the file.2159 *2160 * Count the number of characters in the preimage that fall2161 * beyond the end of the file and make sure that all of them2162 * are whitespace characters. (This can only happen if2163 * we are removing blank lines at the end of the file.)2164 */2165 buf = preimage_eof = preimage->buf + preoff;2166for( ; i < preimage->nr; i++)2167 preoff += preimage->line[i].len;2168 preimage_end = preimage->buf + preoff;2169for( ; buf < preimage_end; buf++)2170if(!isspace(*buf))2171return0;21722173/*2174 * Update the preimage and the common postimage context2175 * lines to use the same whitespace as the target.2176 * If whitespace is missing in the target (i.e.2177 * if the preimage extends beyond the end of the file),2178 * use the whitespace from the preimage.2179 */2180 extra_chars = preimage_end - preimage_eof;2181strbuf_init(&fixed, imgoff + extra_chars);2182strbuf_add(&fixed, img->buf +try, imgoff);2183strbuf_add(&fixed, preimage_eof, extra_chars);2184 fixed_buf =strbuf_detach(&fixed, &fixed_len);2185update_pre_post_images(preimage, postimage,2186 fixed_buf, fixed_len, postlen);2187return1;2188}21892190if(ws_error_action != correct_ws_error)2191return0;21922193/*2194 * The hunk does not apply byte-by-byte, but the hash says2195 * it might with whitespace fuzz. We haven't been asked to2196 * ignore whitespace, we were asked to correct whitespace2197 * errors, so let's try matching after whitespace correction.2198 *2199 * The preimage may extend beyond the end of the file,2200 * but in this loop we will only handle the part of the2201 * preimage that falls within the file.2202 */2203strbuf_init(&fixed, preimage->len +1);2204 orig = preimage->buf;2205 target = img->buf +try;2206for(i =0; i < preimage_limit; i++) {2207size_t oldlen = preimage->line[i].len;2208size_t tgtlen = img->line[try_lno + i].len;2209size_t fixstart = fixed.len;2210struct strbuf tgtfix;2211int match;22122213/* Try fixing the line in the preimage */2214ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);22152216/* Try fixing the line in the target */2217strbuf_init(&tgtfix, tgtlen);2218ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);22192220/*2221 * If they match, either the preimage was based on2222 * a version before our tree fixed whitespace breakage,2223 * or we are lacking a whitespace-fix patch the tree2224 * the preimage was based on already had (i.e. target2225 * has whitespace breakage, the preimage doesn't).2226 * In either case, we are fixing the whitespace breakages2227 * so we might as well take the fix together with their2228 * real change.2229 */2230 match = (tgtfix.len == fixed.len - fixstart &&2231!memcmp(tgtfix.buf, fixed.buf + fixstart,2232 fixed.len - fixstart));22332234strbuf_release(&tgtfix);2235if(!match)2236goto unmatch_exit;22372238 orig += oldlen;2239 target += tgtlen;2240}224122422243/*2244 * Now handle the lines in the preimage that falls beyond the2245 * end of the file (if any). They will only match if they are2246 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2247 * false).2248 */2249for( ; i < preimage->nr; i++) {2250size_t fixstart = fixed.len;/* start of the fixed preimage */2251size_t oldlen = preimage->line[i].len;2252int j;22532254/* Try fixing the line in the preimage */2255ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);22562257for(j = fixstart; j < fixed.len; j++)2258if(!isspace(fixed.buf[j]))2259goto unmatch_exit;22602261 orig += oldlen;2262}22632264/*2265 * Yes, the preimage is based on an older version that still2266 * has whitespace breakages unfixed, and fixing them makes the2267 * hunk match. Update the context lines in the postimage.2268 */2269 fixed_buf =strbuf_detach(&fixed, &fixed_len);2270update_pre_post_images(preimage, postimage,2271 fixed_buf, fixed_len,0);2272return1;22732274 unmatch_exit:2275strbuf_release(&fixed);2276return0;2277}22782279static intfind_pos(struct image *img,2280struct image *preimage,2281struct image *postimage,2282int line,2283unsigned ws_rule,2284int match_beginning,int match_end)2285{2286int i;2287unsigned long backwards, forwards,try;2288int backwards_lno, forwards_lno, try_lno;22892290/*2291 * If match_beginning or match_end is specified, there is no2292 * point starting from a wrong line that will never match and2293 * wander around and wait for a match at the specified end.2294 */2295if(match_beginning)2296 line =0;2297else if(match_end)2298 line = img->nr - preimage->nr;22992300/*2301 * Because the comparison is unsigned, the following test2302 * will also take care of a negative line number that can2303 * result when match_end and preimage is larger than the target.2304 */2305if((size_t) line > img->nr)2306 line = img->nr;23072308try=0;2309for(i =0; i < line; i++)2310try+= img->line[i].len;23112312/*2313 * There's probably some smart way to do this, but I'll leave2314 * that to the smart and beautiful people. I'm simple and stupid.2315 */2316 backwards =try;2317 backwards_lno = line;2318 forwards =try;2319 forwards_lno = line;2320 try_lno = line;23212322for(i =0; ; i++) {2323if(match_fragment(img, preimage, postimage,2324try, try_lno, ws_rule,2325 match_beginning, match_end))2326return try_lno;23272328 again:2329if(backwards_lno ==0&& forwards_lno == img->nr)2330break;23312332if(i &1) {2333if(backwards_lno ==0) {2334 i++;2335goto again;2336}2337 backwards_lno--;2338 backwards -= img->line[backwards_lno].len;2339try= backwards;2340 try_lno = backwards_lno;2341}else{2342if(forwards_lno == img->nr) {2343 i++;2344goto again;2345}2346 forwards += img->line[forwards_lno].len;2347 forwards_lno++;2348try= forwards;2349 try_lno = forwards_lno;2350}23512352}2353return-1;2354}23552356static voidremove_first_line(struct image *img)2357{2358 img->buf += img->line[0].len;2359 img->len -= img->line[0].len;2360 img->line++;2361 img->nr--;2362}23632364static voidremove_last_line(struct image *img)2365{2366 img->len -= img->line[--img->nr].len;2367}23682369static voidupdate_image(struct image *img,2370int applied_pos,2371struct image *preimage,2372struct image *postimage)2373{2374/*2375 * remove the copy of preimage at offset in img2376 * and replace it with postimage2377 */2378int i, nr;2379size_t remove_count, insert_count, applied_at =0;2380char*result;2381int preimage_limit;23822383/*2384 * If we are removing blank lines at the end of img,2385 * the preimage may extend beyond the end.2386 * If that is the case, we must be careful only to2387 * remove the part of the preimage that falls within2388 * the boundaries of img. Initialize preimage_limit2389 * to the number of lines in the preimage that falls2390 * within the boundaries.2391 */2392 preimage_limit = preimage->nr;2393if(preimage_limit > img->nr - applied_pos)2394 preimage_limit = img->nr - applied_pos;23952396for(i =0; i < applied_pos; i++)2397 applied_at += img->line[i].len;23982399 remove_count =0;2400for(i =0; i < preimage_limit; i++)2401 remove_count += img->line[applied_pos + i].len;2402 insert_count = postimage->len;24032404/* Adjust the contents */2405 result =xmalloc(img->len + insert_count - remove_count +1);2406memcpy(result, img->buf, applied_at);2407memcpy(result + applied_at, postimage->buf, postimage->len);2408memcpy(result + applied_at + postimage->len,2409 img->buf + (applied_at + remove_count),2410 img->len - (applied_at + remove_count));2411free(img->buf);2412 img->buf = result;2413 img->len += insert_count - remove_count;2414 result[img->len] ='\0';24152416/* Adjust the line table */2417 nr = img->nr + postimage->nr - preimage_limit;2418if(preimage_limit < postimage->nr) {2419/*2420 * NOTE: this knows that we never call remove_first_line()2421 * on anything other than pre/post image.2422 */2423 img->line =xrealloc(img->line, nr *sizeof(*img->line));2424 img->line_allocated = img->line;2425}2426if(preimage_limit != postimage->nr)2427memmove(img->line + applied_pos + postimage->nr,2428 img->line + applied_pos + preimage_limit,2429(img->nr - (applied_pos + preimage_limit)) *2430sizeof(*img->line));2431memcpy(img->line + applied_pos,2432 postimage->line,2433 postimage->nr *sizeof(*img->line));2434if(!allow_overlap)2435for(i =0; i < postimage->nr; i++)2436 img->line[applied_pos + i].flag |= LINE_PATCHED;2437 img->nr = nr;2438}24392440static intapply_one_fragment(struct image *img,struct fragment *frag,2441int inaccurate_eof,unsigned ws_rule,2442int nth_fragment)2443{2444int match_beginning, match_end;2445const char*patch = frag->patch;2446int size = frag->size;2447char*old, *oldlines;2448struct strbuf newlines;2449int new_blank_lines_at_end =0;2450int found_new_blank_lines_at_end =0;2451int hunk_linenr = frag->linenr;2452unsigned long leading, trailing;2453int pos, applied_pos;2454struct image preimage;2455struct image postimage;24562457memset(&preimage,0,sizeof(preimage));2458memset(&postimage,0,sizeof(postimage));2459 oldlines =xmalloc(size);2460strbuf_init(&newlines, size);24612462 old = oldlines;2463while(size >0) {2464char first;2465int len =linelen(patch, size);2466int plen;2467int added_blank_line =0;2468int is_blank_context =0;2469size_t start;24702471if(!len)2472break;24732474/*2475 * "plen" is how much of the line we should use for2476 * the actual patch data. Normally we just remove the2477 * first character on the line, but if the line is2478 * followed by "\ No newline", then we also remove the2479 * last one (which is the newline, of course).2480 */2481 plen = len -1;2482if(len < size && patch[len] =='\\')2483 plen--;2484 first = *patch;2485if(apply_in_reverse) {2486if(first =='-')2487 first ='+';2488else if(first =='+')2489 first ='-';2490}24912492switch(first) {2493case'\n':2494/* Newer GNU diff, empty context line */2495if(plen <0)2496/* ... followed by '\No newline'; nothing */2497break;2498*old++ ='\n';2499strbuf_addch(&newlines,'\n');2500add_line_info(&preimage,"\n",1, LINE_COMMON);2501add_line_info(&postimage,"\n",1, LINE_COMMON);2502 is_blank_context =1;2503break;2504case' ':2505if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2506ws_blank_line(patch +1, plen, ws_rule))2507 is_blank_context =1;2508case'-':2509memcpy(old, patch +1, plen);2510add_line_info(&preimage, old, plen,2511(first ==' '? LINE_COMMON :0));2512 old += plen;2513if(first =='-')2514break;2515/* Fall-through for ' ' */2516case'+':2517/* --no-add does not add new lines */2518if(first =='+'&& no_add)2519break;25202521 start = newlines.len;2522if(first !='+'||2523!whitespace_error ||2524 ws_error_action != correct_ws_error) {2525strbuf_add(&newlines, patch +1, plen);2526}2527else{2528ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2529}2530add_line_info(&postimage, newlines.buf + start, newlines.len - start,2531(first =='+'?0: LINE_COMMON));2532if(first =='+'&&2533(ws_rule & WS_BLANK_AT_EOF) &&2534ws_blank_line(patch +1, plen, ws_rule))2535 added_blank_line =1;2536break;2537case'@':case'\\':2538/* Ignore it, we already handled it */2539break;2540default:2541if(apply_verbosely)2542error("invalid start of line: '%c'", first);2543return-1;2544}2545if(added_blank_line) {2546if(!new_blank_lines_at_end)2547 found_new_blank_lines_at_end = hunk_linenr;2548 new_blank_lines_at_end++;2549}2550else if(is_blank_context)2551;2552else2553 new_blank_lines_at_end =0;2554 patch += len;2555 size -= len;2556 hunk_linenr++;2557}2558if(inaccurate_eof &&2559 old > oldlines && old[-1] =='\n'&&2560 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2561 old--;2562strbuf_setlen(&newlines, newlines.len -1);2563}25642565 leading = frag->leading;2566 trailing = frag->trailing;25672568/*2569 * A hunk to change lines at the beginning would begin with2570 * @@ -1,L +N,M @@2571 * but we need to be careful. -U0 that inserts before the second2572 * line also has this pattern.2573 *2574 * And a hunk to add to an empty file would begin with2575 * @@ -0,0 +N,M @@2576 *2577 * In other words, a hunk that is (frag->oldpos <= 1) with or2578 * without leading context must match at the beginning.2579 */2580 match_beginning = (!frag->oldpos ||2581(frag->oldpos ==1&& !unidiff_zero));25822583/*2584 * A hunk without trailing lines must match at the end.2585 * However, we simply cannot tell if a hunk must match end2586 * from the lack of trailing lines if the patch was generated2587 * with unidiff without any context.2588 */2589 match_end = !unidiff_zero && !trailing;25902591 pos = frag->newpos ? (frag->newpos -1) :0;2592 preimage.buf = oldlines;2593 preimage.len = old - oldlines;2594 postimage.buf = newlines.buf;2595 postimage.len = newlines.len;2596 preimage.line = preimage.line_allocated;2597 postimage.line = postimage.line_allocated;25982599for(;;) {26002601 applied_pos =find_pos(img, &preimage, &postimage, pos,2602 ws_rule, match_beginning, match_end);26032604if(applied_pos >=0)2605break;26062607/* Am I at my context limits? */2608if((leading <= p_context) && (trailing <= p_context))2609break;2610if(match_beginning || match_end) {2611 match_beginning = match_end =0;2612continue;2613}26142615/*2616 * Reduce the number of context lines; reduce both2617 * leading and trailing if they are equal otherwise2618 * just reduce the larger context.2619 */2620if(leading >= trailing) {2621remove_first_line(&preimage);2622remove_first_line(&postimage);2623 pos--;2624 leading--;2625}2626if(trailing > leading) {2627remove_last_line(&preimage);2628remove_last_line(&postimage);2629 trailing--;2630}2631}26322633if(applied_pos >=0) {2634if(new_blank_lines_at_end &&2635 preimage.nr + applied_pos >= img->nr &&2636(ws_rule & WS_BLANK_AT_EOF) &&2637 ws_error_action != nowarn_ws_error) {2638record_ws_error(WS_BLANK_AT_EOF,"+",1,2639 found_new_blank_lines_at_end);2640if(ws_error_action == correct_ws_error) {2641while(new_blank_lines_at_end--)2642remove_last_line(&postimage);2643}2644/*2645 * We would want to prevent write_out_results()2646 * from taking place in apply_patch() that follows2647 * the callchain led us here, which is:2648 * apply_patch->check_patch_list->check_patch->2649 * apply_data->apply_fragments->apply_one_fragment2650 */2651if(ws_error_action == die_on_ws_error)2652 apply =0;2653}26542655if(apply_verbosely && applied_pos != pos) {2656int offset = applied_pos - pos;2657if(apply_in_reverse)2658 offset =0- offset;2659fprintf(stderr,2660"Hunk #%dsucceeded at%d(offset%dlines).\n",2661 nth_fragment, applied_pos +1, offset);2662}26632664/*2665 * Warn if it was necessary to reduce the number2666 * of context lines.2667 */2668if((leading != frag->leading) ||2669(trailing != frag->trailing))2670fprintf(stderr,"Context reduced to (%ld/%ld)"2671" to apply fragment at%d\n",2672 leading, trailing, applied_pos+1);2673update_image(img, applied_pos, &preimage, &postimage);2674}else{2675if(apply_verbosely)2676error("while searching for:\n%.*s",2677(int)(old - oldlines), oldlines);2678}26792680free(oldlines);2681strbuf_release(&newlines);2682free(preimage.line_allocated);2683free(postimage.line_allocated);26842685return(applied_pos <0);2686}26872688static intapply_binary_fragment(struct image *img,struct patch *patch)2689{2690struct fragment *fragment = patch->fragments;2691unsigned long len;2692void*dst;26932694if(!fragment)2695returnerror("missing binary patch data for '%s'",2696 patch->new_name ?2697 patch->new_name :2698 patch->old_name);26992700/* Binary patch is irreversible without the optional second hunk */2701if(apply_in_reverse) {2702if(!fragment->next)2703returnerror("cannot reverse-apply a binary patch "2704"without the reverse hunk to '%s'",2705 patch->new_name2706? patch->new_name : patch->old_name);2707 fragment = fragment->next;2708}2709switch(fragment->binary_patch_method) {2710case BINARY_DELTA_DEFLATED:2711 dst =patch_delta(img->buf, img->len, fragment->patch,2712 fragment->size, &len);2713if(!dst)2714return-1;2715clear_image(img);2716 img->buf = dst;2717 img->len = len;2718return0;2719case BINARY_LITERAL_DEFLATED:2720clear_image(img);2721 img->len = fragment->size;2722 img->buf =xmalloc(img->len+1);2723memcpy(img->buf, fragment->patch, img->len);2724 img->buf[img->len] ='\0';2725return0;2726}2727return-1;2728}27292730static intapply_binary(struct image *img,struct patch *patch)2731{2732const char*name = patch->old_name ? patch->old_name : patch->new_name;2733unsigned char sha1[20];27342735/*2736 * For safety, we require patch index line to contain2737 * full 40-byte textual SHA1 for old and new, at least for now.2738 */2739if(strlen(patch->old_sha1_prefix) !=40||2740strlen(patch->new_sha1_prefix) !=40||2741get_sha1_hex(patch->old_sha1_prefix, sha1) ||2742get_sha1_hex(patch->new_sha1_prefix, sha1))2743returnerror("cannot apply binary patch to '%s' "2744"without full index line", name);27452746if(patch->old_name) {2747/*2748 * See if the old one matches what the patch2749 * applies to.2750 */2751hash_sha1_file(img->buf, img->len, blob_type, sha1);2752if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2753returnerror("the patch applies to '%s' (%s), "2754"which does not match the "2755"current contents.",2756 name,sha1_to_hex(sha1));2757}2758else{2759/* Otherwise, the old one must be empty. */2760if(img->len)2761returnerror("the patch applies to an empty "2762"'%s' but it is not empty", name);2763}27642765get_sha1_hex(patch->new_sha1_prefix, sha1);2766if(is_null_sha1(sha1)) {2767clear_image(img);2768return0;/* deletion patch */2769}27702771if(has_sha1_file(sha1)) {2772/* We already have the postimage */2773enum object_type type;2774unsigned long size;2775char*result;27762777 result =read_sha1_file(sha1, &type, &size);2778if(!result)2779returnerror("the necessary postimage%sfor "2780"'%s' cannot be read",2781 patch->new_sha1_prefix, name);2782clear_image(img);2783 img->buf = result;2784 img->len = size;2785}else{2786/*2787 * We have verified buf matches the preimage;2788 * apply the patch data to it, which is stored2789 * in the patch->fragments->{patch,size}.2790 */2791if(apply_binary_fragment(img, patch))2792returnerror("binary patch does not apply to '%s'",2793 name);27942795/* verify that the result matches */2796hash_sha1_file(img->buf, img->len, blob_type, sha1);2797if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2798returnerror("binary patch to '%s' creates incorrect result (expecting%s, got%s)",2799 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2800}28012802return0;2803}28042805static intapply_fragments(struct image *img,struct patch *patch)2806{2807struct fragment *frag = patch->fragments;2808const char*name = patch->old_name ? patch->old_name : patch->new_name;2809unsigned ws_rule = patch->ws_rule;2810unsigned inaccurate_eof = patch->inaccurate_eof;2811int nth =0;28122813if(patch->is_binary)2814returnapply_binary(img, patch);28152816while(frag) {2817 nth++;2818if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {2819error("patch failed:%s:%ld", name, frag->oldpos);2820if(!apply_with_reject)2821return-1;2822 frag->rejected =1;2823}2824 frag = frag->next;2825}2826return0;2827}28282829static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2830{2831if(!ce)2832return0;28332834if(S_ISGITLINK(ce->ce_mode)) {2835strbuf_grow(buf,100);2836strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2837}else{2838enum object_type type;2839unsigned long sz;2840char*result;28412842 result =read_sha1_file(ce->sha1, &type, &sz);2843if(!result)2844return-1;2845/* XXX read_sha1_file NUL-terminates */2846strbuf_attach(buf, result, sz, sz +1);2847}2848return0;2849}28502851static struct patch *in_fn_table(const char*name)2852{2853struct string_list_item *item;28542855if(name == NULL)2856return NULL;28572858 item =string_list_lookup(&fn_table, name);2859if(item != NULL)2860return(struct patch *)item->util;28612862return NULL;2863}28642865/*2866 * item->util in the filename table records the status of the path.2867 * Usually it points at a patch (whose result records the contents2868 * of it after applying it), but it could be PATH_WAS_DELETED for a2869 * path that a previously applied patch has already removed.2870 */2871#define PATH_TO_BE_DELETED ((struct patch *) -2)2872#define PATH_WAS_DELETED ((struct patch *) -1)28732874static intto_be_deleted(struct patch *patch)2875{2876return patch == PATH_TO_BE_DELETED;2877}28782879static intwas_deleted(struct patch *patch)2880{2881return patch == PATH_WAS_DELETED;2882}28832884static voidadd_to_fn_table(struct patch *patch)2885{2886struct string_list_item *item;28872888/*2889 * Always add new_name unless patch is a deletion2890 * This should cover the cases for normal diffs,2891 * file creations and copies2892 */2893if(patch->new_name != NULL) {2894 item =string_list_insert(&fn_table, patch->new_name);2895 item->util = patch;2896}28972898/*2899 * store a failure on rename/deletion cases because2900 * later chunks shouldn't patch old names2901 */2902if((patch->new_name == NULL) || (patch->is_rename)) {2903 item =string_list_insert(&fn_table, patch->old_name);2904 item->util = PATH_WAS_DELETED;2905}2906}29072908static voidprepare_fn_table(struct patch *patch)2909{2910/*2911 * store information about incoming file deletion2912 */2913while(patch) {2914if((patch->new_name == NULL) || (patch->is_rename)) {2915struct string_list_item *item;2916 item =string_list_insert(&fn_table, patch->old_name);2917 item->util = PATH_TO_BE_DELETED;2918}2919 patch = patch->next;2920}2921}29222923static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)2924{2925struct strbuf buf = STRBUF_INIT;2926struct image image;2927size_t len;2928char*img;2929struct patch *tpatch;29302931if(!(patch->is_copy || patch->is_rename) &&2932(tpatch =in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {2933if(was_deleted(tpatch)) {2934returnerror("patch%shas been renamed/deleted",2935 patch->old_name);2936}2937/* We have a patched copy in memory use that */2938strbuf_add(&buf, tpatch->result, tpatch->resultsize);2939}else if(cached) {2940if(read_file_or_gitlink(ce, &buf))2941returnerror("read of%sfailed", patch->old_name);2942}else if(patch->old_name) {2943if(S_ISGITLINK(patch->old_mode)) {2944if(ce) {2945read_file_or_gitlink(ce, &buf);2946}else{2947/*2948 * There is no way to apply subproject2949 * patch without looking at the index.2950 */2951 patch->fragments = NULL;2952}2953}else{2954if(read_old_data(st, patch->old_name, &buf))2955returnerror("read of%sfailed", patch->old_name);2956}2957}29582959 img =strbuf_detach(&buf, &len);2960prepare_image(&image, img, len, !patch->is_binary);29612962if(apply_fragments(&image, patch) <0)2963return-1;/* note with --reject this succeeds. */2964 patch->result = image.buf;2965 patch->resultsize = image.len;2966add_to_fn_table(patch);2967free(image.line_allocated);29682969if(0< patch->is_delete && patch->resultsize)2970returnerror("removal patch leaves file contents");29712972return0;2973}29742975static intcheck_to_create_blob(const char*new_name,int ok_if_exists)2976{2977struct stat nst;2978if(!lstat(new_name, &nst)) {2979if(S_ISDIR(nst.st_mode) || ok_if_exists)2980return0;2981/*2982 * A leading component of new_name might be a symlink2983 * that is going to be removed with this patch, but2984 * still pointing at somewhere that has the path.2985 * In such a case, path "new_name" does not exist as2986 * far as git is concerned.2987 */2988if(has_symlink_leading_path(new_name,strlen(new_name)))2989return0;29902991returnerror("%s: already exists in working directory", new_name);2992}2993else if((errno != ENOENT) && (errno != ENOTDIR))2994returnerror("%s:%s", new_name,strerror(errno));2995return0;2996}29972998static intverify_index_match(struct cache_entry *ce,struct stat *st)2999{3000if(S_ISGITLINK(ce->ce_mode)) {3001if(!S_ISDIR(st->st_mode))3002return-1;3003return0;3004}3005returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3006}30073008static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)3009{3010const char*old_name = patch->old_name;3011struct patch *tpatch = NULL;3012int stat_ret =0;3013unsigned st_mode =0;30143015/*3016 * Make sure that we do not have local modifications from the3017 * index when we are looking at the index. Also make sure3018 * we have the preimage file to be patched in the work tree,3019 * unless --cached, which tells git to apply only in the index.3020 */3021if(!old_name)3022return0;30233024assert(patch->is_new <=0);30253026if(!(patch->is_copy || patch->is_rename) &&3027(tpatch =in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {3028if(was_deleted(tpatch))3029returnerror("%s: has been deleted/renamed", old_name);3030 st_mode = tpatch->new_mode;3031}else if(!cached) {3032 stat_ret =lstat(old_name, st);3033if(stat_ret && errno != ENOENT)3034returnerror("%s:%s", old_name,strerror(errno));3035}30363037if(to_be_deleted(tpatch))3038 tpatch = NULL;30393040if(check_index && !tpatch) {3041int pos =cache_name_pos(old_name,strlen(old_name));3042if(pos <0) {3043if(patch->is_new <0)3044goto is_new;3045returnerror("%s: does not exist in index", old_name);3046}3047*ce = active_cache[pos];3048if(stat_ret <0) {3049struct checkout costate;3050/* checkout */3051memset(&costate,0,sizeof(costate));3052 costate.base_dir ="";3053 costate.refresh_cache =1;3054if(checkout_entry(*ce, &costate, NULL) ||3055lstat(old_name, st))3056return-1;3057}3058if(!cached &&verify_index_match(*ce, st))3059returnerror("%s: does not match index", old_name);3060if(cached)3061 st_mode = (*ce)->ce_mode;3062}else if(stat_ret <0) {3063if(patch->is_new <0)3064goto is_new;3065returnerror("%s:%s", old_name,strerror(errno));3066}30673068if(!cached && !tpatch)3069 st_mode =ce_mode_from_stat(*ce, st->st_mode);30703071if(patch->is_new <0)3072 patch->is_new =0;3073if(!patch->old_mode)3074 patch->old_mode = st_mode;3075if((st_mode ^ patch->old_mode) & S_IFMT)3076returnerror("%s: wrong type", old_name);3077if(st_mode != patch->old_mode)3078warning("%shas type%o, expected%o",3079 old_name, st_mode, patch->old_mode);3080if(!patch->new_mode && !patch->is_delete)3081 patch->new_mode = st_mode;3082return0;30833084 is_new:3085 patch->is_new =1;3086 patch->is_delete =0;3087 patch->old_name = NULL;3088return0;3089}30903091static intcheck_patch(struct patch *patch)3092{3093struct stat st;3094const char*old_name = patch->old_name;3095const char*new_name = patch->new_name;3096const char*name = old_name ? old_name : new_name;3097struct cache_entry *ce = NULL;3098struct patch *tpatch;3099int ok_if_exists;3100int status;31013102 patch->rejected =1;/* we will drop this after we succeed */31033104 status =check_preimage(patch, &ce, &st);3105if(status)3106return status;3107 old_name = patch->old_name;31083109if((tpatch =in_fn_table(new_name)) &&3110(was_deleted(tpatch) ||to_be_deleted(tpatch)))3111/*3112 * A type-change diff is always split into a patch to3113 * delete old, immediately followed by a patch to3114 * create new (see diff.c::run_diff()); in such a case3115 * it is Ok that the entry to be deleted by the3116 * previous patch is still in the working tree and in3117 * the index.3118 */3119 ok_if_exists =1;3120else3121 ok_if_exists =0;31223123if(new_name &&3124((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {3125if(check_index &&3126cache_name_pos(new_name,strlen(new_name)) >=0&&3127!ok_if_exists)3128returnerror("%s: already exists in index", new_name);3129if(!cached) {3130int err =check_to_create_blob(new_name, ok_if_exists);3131if(err)3132return err;3133}3134if(!patch->new_mode) {3135if(0< patch->is_new)3136 patch->new_mode = S_IFREG |0644;3137else3138 patch->new_mode = patch->old_mode;3139}3140}31413142if(new_name && old_name) {3143int same = !strcmp(old_name, new_name);3144if(!patch->new_mode)3145 patch->new_mode = patch->old_mode;3146if((patch->old_mode ^ patch->new_mode) & S_IFMT)3147returnerror("new mode (%o) of%sdoes not match old mode (%o)%s%s",3148 patch->new_mode, new_name, patch->old_mode,3149 same ?"":" of ", same ?"": old_name);3150}31513152if(apply_data(patch, &st, ce) <0)3153returnerror("%s: patch does not apply", name);3154 patch->rejected =0;3155return0;3156}31573158static intcheck_patch_list(struct patch *patch)3159{3160int err =0;31613162prepare_fn_table(patch);3163while(patch) {3164if(apply_verbosely)3165say_patch_name(stderr,3166"Checking patch ", patch,"...\n");3167 err |=check_patch(patch);3168 patch = patch->next;3169}3170return err;3171}31723173/* This function tries to read the sha1 from the current index */3174static intget_current_sha1(const char*path,unsigned char*sha1)3175{3176int pos;31773178if(read_cache() <0)3179return-1;3180 pos =cache_name_pos(path,strlen(path));3181if(pos <0)3182return-1;3183hashcpy(sha1, active_cache[pos]->sha1);3184return0;3185}31863187/* Build an index that contains the just the files needed for a 3way merge */3188static voidbuild_fake_ancestor(struct patch *list,const char*filename)3189{3190struct patch *patch;3191struct index_state result = { NULL };3192int fd;31933194/* Once we start supporting the reverse patch, it may be3195 * worth showing the new sha1 prefix, but until then...3196 */3197for(patch = list; patch; patch = patch->next) {3198const unsigned char*sha1_ptr;3199unsigned char sha1[20];3200struct cache_entry *ce;3201const char*name;32023203 name = patch->old_name ? patch->old_name : patch->new_name;3204if(0< patch->is_new)3205continue;3206else if(get_sha1(patch->old_sha1_prefix, sha1))3207/* git diff has no index line for mode/type changes */3208if(!patch->lines_added && !patch->lines_deleted) {3209if(get_current_sha1(patch->old_name, sha1))3210die("mode change for%s, which is not "3211"in current HEAD", name);3212 sha1_ptr = sha1;3213}else3214die("sha1 information is lacking or useless "3215"(%s).", name);3216else3217 sha1_ptr = sha1;32183219 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);3220if(!ce)3221die("make_cache_entry failed for path '%s'", name);3222if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3223die("Could not add%sto temporary index", name);3224}32253226 fd =open(filename, O_WRONLY | O_CREAT,0666);3227if(fd <0||write_index(&result, fd) ||close(fd))3228die("Could not write temporary index to%s", filename);32293230discard_index(&result);3231}32323233static voidstat_patch_list(struct patch *patch)3234{3235int files, adds, dels;32363237for(files = adds = dels =0; patch ; patch = patch->next) {3238 files++;3239 adds += patch->lines_added;3240 dels += patch->lines_deleted;3241show_stats(patch);3242}32433244printf("%dfiles changed,%dinsertions(+),%ddeletions(-)\n", files, adds, dels);3245}32463247static voidnumstat_patch_list(struct patch *patch)3248{3249for( ; patch; patch = patch->next) {3250const char*name;3251 name = patch->new_name ? patch->new_name : patch->old_name;3252if(patch->is_binary)3253printf("-\t-\t");3254else3255printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3256write_name_quoted(name, stdout, line_termination);3257}3258}32593260static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3261{3262if(mode)3263printf("%smode%06o%s\n", newdelete, mode, name);3264else3265printf("%s %s\n", newdelete, name);3266}32673268static voidshow_mode_change(struct patch *p,int show_name)3269{3270if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3271if(show_name)3272printf(" mode change%06o =>%06o%s\n",3273 p->old_mode, p->new_mode, p->new_name);3274else3275printf(" mode change%06o =>%06o\n",3276 p->old_mode, p->new_mode);3277}3278}32793280static voidshow_rename_copy(struct patch *p)3281{3282const char*renamecopy = p->is_rename ?"rename":"copy";3283const char*old, *new;32843285/* Find common prefix */3286 old = p->old_name;3287new= p->new_name;3288while(1) {3289const char*slash_old, *slash_new;3290 slash_old =strchr(old,'/');3291 slash_new =strchr(new,'/');3292if(!slash_old ||3293!slash_new ||3294 slash_old - old != slash_new -new||3295memcmp(old,new, slash_new -new))3296break;3297 old = slash_old +1;3298new= slash_new +1;3299}3300/* p->old_name thru old is the common prefix, and old and new3301 * through the end of names are renames3302 */3303if(old != p->old_name)3304printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,3305(int)(old - p->old_name), p->old_name,3306 old,new, p->score);3307else3308printf("%s %s=>%s(%d%%)\n", renamecopy,3309 p->old_name, p->new_name, p->score);3310show_mode_change(p,0);3311}33123313static voidsummary_patch_list(struct patch *patch)3314{3315struct patch *p;33163317for(p = patch; p; p = p->next) {3318if(p->is_new)3319show_file_mode_name("create", p->new_mode, p->new_name);3320else if(p->is_delete)3321show_file_mode_name("delete", p->old_mode, p->old_name);3322else{3323if(p->is_rename || p->is_copy)3324show_rename_copy(p);3325else{3326if(p->score) {3327printf(" rewrite%s(%d%%)\n",3328 p->new_name, p->score);3329show_mode_change(p,0);3330}3331else3332show_mode_change(p,1);3333}3334}3335}3336}33373338static voidpatch_stats(struct patch *patch)3339{3340int lines = patch->lines_added + patch->lines_deleted;33413342if(lines > max_change)3343 max_change = lines;3344if(patch->old_name) {3345int len =quote_c_style(patch->old_name, NULL, NULL,0);3346if(!len)3347 len =strlen(patch->old_name);3348if(len > max_len)3349 max_len = len;3350}3351if(patch->new_name) {3352int len =quote_c_style(patch->new_name, NULL, NULL,0);3353if(!len)3354 len =strlen(patch->new_name);3355if(len > max_len)3356 max_len = len;3357}3358}33593360static voidremove_file(struct patch *patch,int rmdir_empty)3361{3362if(update_index) {3363if(remove_file_from_cache(patch->old_name) <0)3364die("unable to remove%sfrom index", patch->old_name);3365}3366if(!cached) {3367if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {3368remove_path(patch->old_name);3369}3370}3371}33723373static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)3374{3375struct stat st;3376struct cache_entry *ce;3377int namelen =strlen(path);3378unsigned ce_size =cache_entry_size(namelen);33793380if(!update_index)3381return;33823383 ce =xcalloc(1, ce_size);3384memcpy(ce->name, path, namelen);3385 ce->ce_mode =create_ce_mode(mode);3386 ce->ce_flags = namelen;3387if(S_ISGITLINK(mode)) {3388const char*s = buf;33893390if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))3391die("corrupt patch for subproject%s", path);3392}else{3393if(!cached) {3394if(lstat(path, &st) <0)3395die_errno("unable to stat newly created file '%s'",3396 path);3397fill_stat_cache_info(ce, &st);3398}3399if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)3400die("unable to create backing store for newly created file%s", path);3401}3402if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3403die("unable to add cache entry for%s", path);3404}34053406static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)3407{3408int fd;3409struct strbuf nbuf = STRBUF_INIT;34103411if(S_ISGITLINK(mode)) {3412struct stat st;3413if(!lstat(path, &st) &&S_ISDIR(st.st_mode))3414return0;3415returnmkdir(path,0777);3416}34173418if(has_symlinks &&S_ISLNK(mode))3419/* Although buf:size is counted string, it also is NUL3420 * terminated.3421 */3422returnsymlink(buf, path);34233424 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);3425if(fd <0)3426return-1;34273428if(convert_to_working_tree(path, buf, size, &nbuf)) {3429 size = nbuf.len;3430 buf = nbuf.buf;3431}3432write_or_die(fd, buf, size);3433strbuf_release(&nbuf);34343435if(close(fd) <0)3436die_errno("closing file '%s'", path);3437return0;3438}34393440/*3441 * We optimistically assume that the directories exist,3442 * which is true 99% of the time anyway. If they don't,3443 * we create them and try again.3444 */3445static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)3446{3447if(cached)3448return;3449if(!try_create_file(path, mode, buf, size))3450return;34513452if(errno == ENOENT) {3453if(safe_create_leading_directories(path))3454return;3455if(!try_create_file(path, mode, buf, size))3456return;3457}34583459if(errno == EEXIST || errno == EACCES) {3460/* We may be trying to create a file where a directory3461 * used to be.3462 */3463struct stat st;3464if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))3465 errno = EEXIST;3466}34673468if(errno == EEXIST) {3469unsigned int nr =getpid();34703471for(;;) {3472char newpath[PATH_MAX];3473mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);3474if(!try_create_file(newpath, mode, buf, size)) {3475if(!rename(newpath, path))3476return;3477unlink_or_warn(newpath);3478break;3479}3480if(errno != EEXIST)3481break;3482++nr;3483}3484}3485die_errno("unable to write file '%s' mode%o", path, mode);3486}34873488static voidcreate_file(struct patch *patch)3489{3490char*path = patch->new_name;3491unsigned mode = patch->new_mode;3492unsigned long size = patch->resultsize;3493char*buf = patch->result;34943495if(!mode)3496 mode = S_IFREG |0644;3497create_one_file(path, mode, buf, size);3498add_index_file(path, mode, buf, size);3499}35003501/* phase zero is to remove, phase one is to create */3502static voidwrite_out_one_result(struct patch *patch,int phase)3503{3504if(patch->is_delete >0) {3505if(phase ==0)3506remove_file(patch,1);3507return;3508}3509if(patch->is_new >0|| patch->is_copy) {3510if(phase ==1)3511create_file(patch);3512return;3513}3514/*3515 * Rename or modification boils down to the same3516 * thing: remove the old, write the new3517 */3518if(phase ==0)3519remove_file(patch, patch->is_rename);3520if(phase ==1)3521create_file(patch);3522}35233524static intwrite_out_one_reject(struct patch *patch)3525{3526FILE*rej;3527char namebuf[PATH_MAX];3528struct fragment *frag;3529int cnt =0;35303531for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {3532if(!frag->rejected)3533continue;3534 cnt++;3535}35363537if(!cnt) {3538if(apply_verbosely)3539say_patch_name(stderr,3540"Applied patch ", patch," cleanly.\n");3541return0;3542}35433544/* This should not happen, because a removal patch that leaves3545 * contents are marked "rejected" at the patch level.3546 */3547if(!patch->new_name)3548die("internal error");35493550/* Say this even without --verbose */3551say_patch_name(stderr,"Applying patch ", patch," with");3552fprintf(stderr,"%drejects...\n", cnt);35533554 cnt =strlen(patch->new_name);3555if(ARRAY_SIZE(namebuf) <= cnt +5) {3556 cnt =ARRAY_SIZE(namebuf) -5;3557warning("truncating .rej filename to %.*s.rej",3558 cnt -1, patch->new_name);3559}3560memcpy(namebuf, patch->new_name, cnt);3561memcpy(namebuf + cnt,".rej",5);35623563 rej =fopen(namebuf,"w");3564if(!rej)3565returnerror("cannot open%s:%s", namebuf,strerror(errno));35663567/* Normal git tools never deal with .rej, so do not pretend3568 * this is a git patch by saying --git nor give extended3569 * headers. While at it, maybe please "kompare" that wants3570 * the trailing TAB and some garbage at the end of line ;-).3571 */3572fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",3573 patch->new_name, patch->new_name);3574for(cnt =1, frag = patch->fragments;3575 frag;3576 cnt++, frag = frag->next) {3577if(!frag->rejected) {3578fprintf(stderr,"Hunk #%dapplied cleanly.\n", cnt);3579continue;3580}3581fprintf(stderr,"Rejected hunk #%d.\n", cnt);3582fprintf(rej,"%.*s", frag->size, frag->patch);3583if(frag->patch[frag->size-1] !='\n')3584fputc('\n', rej);3585}3586fclose(rej);3587return-1;3588}35893590static intwrite_out_results(struct patch *list,int skipped_patch)3591{3592int phase;3593int errs =0;3594struct patch *l;35953596if(!list && !skipped_patch)3597returnerror("No changes");35983599for(phase =0; phase <2; phase++) {3600 l = list;3601while(l) {3602if(l->rejected)3603 errs =1;3604else{3605write_out_one_result(l, phase);3606if(phase ==1&&write_out_one_reject(l))3607 errs =1;3608}3609 l = l->next;3610}3611}3612return errs;3613}36143615static struct lock_file lock_file;36163617static struct string_list limit_by_name;3618static int has_include;3619static voidadd_name_limit(const char*name,int exclude)3620{3621struct string_list_item *it;36223623 it =string_list_append(&limit_by_name, name);3624 it->util = exclude ? NULL : (void*)1;3625}36263627static intuse_patch(struct patch *p)3628{3629const char*pathname = p->new_name ? p->new_name : p->old_name;3630int i;36313632/* Paths outside are not touched regardless of "--include" */3633if(0< prefix_length) {3634int pathlen =strlen(pathname);3635if(pathlen <= prefix_length ||3636memcmp(prefix, pathname, prefix_length))3637return0;3638}36393640/* See if it matches any of exclude/include rule */3641for(i =0; i < limit_by_name.nr; i++) {3642struct string_list_item *it = &limit_by_name.items[i];3643if(!fnmatch(it->string, pathname,0))3644return(it->util != NULL);3645}36463647/*3648 * If we had any include, a path that does not match any rule is3649 * not used. Otherwise, we saw bunch of exclude rules (or none)3650 * and such a path is used.3651 */3652return!has_include;3653}365436553656static voidprefix_one(char**name)3657{3658char*old_name = *name;3659if(!old_name)3660return;3661*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3662free(old_name);3663}36643665static voidprefix_patches(struct patch *p)3666{3667if(!prefix || p->is_toplevel_relative)3668return;3669for( ; p; p = p->next) {3670if(p->new_name == p->old_name) {3671char*prefixed = p->new_name;3672prefix_one(&prefixed);3673 p->new_name = p->old_name = prefixed;3674}3675else{3676prefix_one(&p->new_name);3677prefix_one(&p->old_name);3678}3679}3680}36813682#define INACCURATE_EOF (1<<0)3683#define RECOUNT (1<<1)36843685static intapply_patch(int fd,const char*filename,int options)3686{3687size_t offset;3688struct strbuf buf = STRBUF_INIT;3689struct patch *list = NULL, **listp = &list;3690int skipped_patch =0;36913692/* FIXME - memory leak when using multiple patch files as inputs */3693memset(&fn_table,0,sizeof(struct string_list));3694 patch_input_file = filename;3695read_patch_file(&buf, fd);3696 offset =0;3697while(offset < buf.len) {3698struct patch *patch;3699int nr;37003701 patch =xcalloc(1,sizeof(*patch));3702 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3703 patch->recount = !!(options & RECOUNT);3704 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3705if(nr <0)3706break;3707if(apply_in_reverse)3708reverse_patches(patch);3709if(prefix)3710prefix_patches(patch);3711if(use_patch(patch)) {3712patch_stats(patch);3713*listp = patch;3714 listp = &patch->next;3715}3716else{3717/* perhaps free it a bit better? */3718free(patch);3719 skipped_patch++;3720}3721 offset += nr;3722}37233724if(whitespace_error && (ws_error_action == die_on_ws_error))3725 apply =0;37263727 update_index = check_index && apply;3728if(update_index && newfd <0)3729 newfd =hold_locked_index(&lock_file,1);37303731if(check_index) {3732if(read_cache() <0)3733die("unable to read index file");3734}37353736if((check || apply) &&3737check_patch_list(list) <0&&3738!apply_with_reject)3739exit(1);37403741if(apply &&write_out_results(list, skipped_patch))3742exit(1);37433744if(fake_ancestor)3745build_fake_ancestor(list, fake_ancestor);37463747if(diffstat)3748stat_patch_list(list);37493750if(numstat)3751numstat_patch_list(list);37523753if(summary)3754summary_patch_list(list);37553756strbuf_release(&buf);3757return0;3758}37593760static intgit_apply_config(const char*var,const char*value,void*cb)3761{3762if(!strcmp(var,"apply.whitespace"))3763returngit_config_string(&apply_default_whitespace, var, value);3764else if(!strcmp(var,"apply.ignorewhitespace"))3765returngit_config_string(&apply_default_ignorewhitespace, var, value);3766returngit_default_config(var, value, cb);3767}37683769static intoption_parse_exclude(const struct option *opt,3770const char*arg,int unset)3771{3772add_name_limit(arg,1);3773return0;3774}37753776static intoption_parse_include(const struct option *opt,3777const char*arg,int unset)3778{3779add_name_limit(arg,0);3780 has_include =1;3781return0;3782}37833784static intoption_parse_p(const struct option *opt,3785const char*arg,int unset)3786{3787 p_value =atoi(arg);3788 p_value_known =1;3789return0;3790}37913792static intoption_parse_z(const struct option *opt,3793const char*arg,int unset)3794{3795if(unset)3796 line_termination ='\n';3797else3798 line_termination =0;3799return0;3800}38013802static intoption_parse_space_change(const struct option *opt,3803const char*arg,int unset)3804{3805if(unset)3806 ws_ignore_action = ignore_ws_none;3807else3808 ws_ignore_action = ignore_ws_change;3809return0;3810}38113812static intoption_parse_whitespace(const struct option *opt,3813const char*arg,int unset)3814{3815const char**whitespace_option = opt->value;38163817*whitespace_option = arg;3818parse_whitespace_option(arg);3819return0;3820}38213822static intoption_parse_directory(const struct option *opt,3823const char*arg,int unset)3824{3825 root_len =strlen(arg);3826if(root_len && arg[root_len -1] !='/') {3827char*new_root;3828 root = new_root =xmalloc(root_len +2);3829strcpy(new_root, arg);3830strcpy(new_root + root_len++,"/");3831}else3832 root = arg;3833return0;3834}38353836intcmd_apply(int argc,const char**argv,const char*prefix_)3837{3838int i;3839int errs =0;3840int is_not_gitdir = !startup_info->have_repository;3841int force_apply =0;38423843const char*whitespace_option = NULL;38443845struct option builtin_apply_options[] = {3846{ OPTION_CALLBACK,0,"exclude", NULL,"path",3847"don't apply changes matching the given path",38480, option_parse_exclude },3849{ OPTION_CALLBACK,0,"include", NULL,"path",3850"apply changes matching the given path",38510, option_parse_include },3852{ OPTION_CALLBACK,'p', NULL, NULL,"num",3853"remove <num> leading slashes from traditional diff paths",38540, option_parse_p },3855OPT_BOOLEAN(0,"no-add", &no_add,3856"ignore additions made by the patch"),3857OPT_BOOLEAN(0,"stat", &diffstat,3858"instead of applying the patch, output diffstat for the input"),3859OPT_NOOP_NOARG(0,"allow-binary-replacement"),3860OPT_NOOP_NOARG(0,"binary"),3861OPT_BOOLEAN(0,"numstat", &numstat,3862"shows number of added and deleted lines in decimal notation"),3863OPT_BOOLEAN(0,"summary", &summary,3864"instead of applying the patch, output a summary for the input"),3865OPT_BOOLEAN(0,"check", &check,3866"instead of applying the patch, see if the patch is applicable"),3867OPT_BOOLEAN(0,"index", &check_index,3868"make sure the patch is applicable to the current index"),3869OPT_BOOLEAN(0,"cached", &cached,3870"apply a patch without touching the working tree"),3871OPT_BOOLEAN(0,"apply", &force_apply,3872"also apply the patch (use with --stat/--summary/--check)"),3873OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,3874"build a temporary index based on embedded index information"),3875{ OPTION_CALLBACK,'z', NULL, NULL, NULL,3876"paths are separated with NUL character",3877 PARSE_OPT_NOARG, option_parse_z },3878OPT_INTEGER('C', NULL, &p_context,3879"ensure at least <n> lines of context match"),3880{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,"action",3881"detect new or modified lines that have whitespace errors",38820, option_parse_whitespace },3883{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,3884"ignore changes in whitespace when finding context",3885 PARSE_OPT_NOARG, option_parse_space_change },3886{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,3887"ignore changes in whitespace when finding context",3888 PARSE_OPT_NOARG, option_parse_space_change },3889OPT_BOOLEAN('R',"reverse", &apply_in_reverse,3890"apply the patch in reverse"),3891OPT_BOOLEAN(0,"unidiff-zero", &unidiff_zero,3892"don't expect at least one line of context"),3893OPT_BOOLEAN(0,"reject", &apply_with_reject,3894"leave the rejected hunks in corresponding *.rej files"),3895OPT_BOOLEAN(0,"allow-overlap", &allow_overlap,3896"allow overlapping hunks"),3897OPT__VERBOSE(&apply_verbosely,"be verbose"),3898OPT_BIT(0,"inaccurate-eof", &options,3899"tolerate incorrectly detected missing new-line at the end of file",3900 INACCURATE_EOF),3901OPT_BIT(0,"recount", &options,3902"do not trust the line counts in the hunk headers",3903 RECOUNT),3904{ OPTION_CALLBACK,0,"directory", NULL,"root",3905"prepend <root> to all filenames",39060, option_parse_directory },3907OPT_END()3908};39093910 prefix = prefix_;3911 prefix_length = prefix ?strlen(prefix) :0;3912git_config(git_apply_config, NULL);3913if(apply_default_whitespace)3914parse_whitespace_option(apply_default_whitespace);3915if(apply_default_ignorewhitespace)3916parse_ignorewhitespace_option(apply_default_ignorewhitespace);39173918 argc =parse_options(argc, argv, prefix, builtin_apply_options,3919 apply_usage,0);39203921if(apply_with_reject)3922 apply = apply_verbosely =1;3923if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))3924 apply =0;3925if(check_index && is_not_gitdir)3926die("--index outside a repository");3927if(cached) {3928if(is_not_gitdir)3929die("--cached outside a repository");3930 check_index =1;3931}3932for(i =0; i < argc; i++) {3933const char*arg = argv[i];3934int fd;39353936if(!strcmp(arg,"-")) {3937 errs |=apply_patch(0,"<stdin>", options);3938 read_stdin =0;3939continue;3940}else if(0< prefix_length)3941 arg =prefix_filename(prefix, prefix_length, arg);39423943 fd =open(arg, O_RDONLY);3944if(fd <0)3945die_errno("can't open patch '%s'", arg);3946 read_stdin =0;3947set_default_whitespace_mode(whitespace_option);3948 errs |=apply_patch(fd, arg, options);3949close(fd);3950}3951set_default_whitespace_mode(whitespace_option);3952if(read_stdin)3953 errs |=apply_patch(0,"<stdin>", options);3954if(whitespace_error) {3955if(squelch_whitespace_errors &&3956 squelch_whitespace_errors < whitespace_error) {3957int squelched =3958 whitespace_error - squelch_whitespace_errors;3959warning("squelched%d"3960"whitespace error%s",3961 squelched,3962 squelched ==1?"":"s");3963}3964if(ws_error_action == die_on_ws_error)3965die("%dline%sadd%swhitespace errors.",3966 whitespace_error,3967 whitespace_error ==1?"":"s",3968 whitespace_error ==1?"s":"");3969if(applied_after_fixing_ws && apply)3970warning("%dline%sapplied after"3971" fixing whitespace errors.",3972 applied_after_fixing_ws,3973 applied_after_fixing_ws ==1?"":"s");3974else if(whitespace_error)3975warning("%dline%sadd%swhitespace errors.",3976 whitespace_error,3977 whitespace_error ==1?"":"s",3978 whitespace_error ==1?"s":"");3979}39803981if(update_index) {3982if(write_cache(newfd, active_cache, active_nr) ||3983commit_locked_index(&lock_file))3984die("Unable to write new index file");3985}39863987return!!errs;3988}