1/* 2 * apply.c 3 * 4 * Copyright (C) Linus Torvalds, 2005 5 * 6 * This applies patches on top of some (arbitrary) version of the SCM. 7 * 8 */ 9#include"cache.h" 10#include"cache-tree.h" 11#include"quote.h" 12#include"blob.h" 13#include"delta.h" 14#include"builtin.h" 15#include"string-list.h" 16#include"dir.h" 17#include"diff.h" 18#include"parse-options.h" 19 20/* 21 * --check turns on checking that the working tree matches the 22 * files that are being modified, but doesn't apply the patch 23 * --stat does just a diffstat, and doesn't actually apply 24 * --numstat does numeric diffstat, and doesn't actually apply 25 * --index-info shows the old and new index info for paths if available. 26 * --index updates the cache as well. 27 * --cached updates only the cache without ever touching the working tree. 28 */ 29static const char*prefix; 30static int prefix_length = -1; 31static int newfd = -1; 32 33static int unidiff_zero; 34static int p_value =1; 35static int p_value_known; 36static int check_index; 37static int update_index; 38static int cached; 39static int diffstat; 40static int numstat; 41static int summary; 42static int check; 43static int apply =1; 44static int apply_in_reverse; 45static int apply_with_reject; 46static int apply_verbosely; 47static int allow_overlap; 48static int no_add; 49static const char*fake_ancestor; 50static int line_termination ='\n'; 51static unsigned int p_context = UINT_MAX; 52static const char*const apply_usage[] = { 53"git apply [options] [<patch>...]", 54 NULL 55}; 56 57static enum ws_error_action { 58 nowarn_ws_error, 59 warn_on_ws_error, 60 die_on_ws_error, 61 correct_ws_error 62} ws_error_action = warn_on_ws_error; 63static int whitespace_error; 64static int squelch_whitespace_errors =5; 65static int applied_after_fixing_ws; 66 67static enum ws_ignore { 68 ignore_ws_none, 69 ignore_ws_change 70} ws_ignore_action = ignore_ws_none; 71 72 73static const char*patch_input_file; 74static const char*root; 75static int root_len; 76static int read_stdin =1; 77static int options; 78 79static voidparse_whitespace_option(const char*option) 80{ 81if(!option) { 82 ws_error_action = warn_on_ws_error; 83return; 84} 85if(!strcmp(option,"warn")) { 86 ws_error_action = warn_on_ws_error; 87return; 88} 89if(!strcmp(option,"nowarn")) { 90 ws_error_action = nowarn_ws_error; 91return; 92} 93if(!strcmp(option,"error")) { 94 ws_error_action = die_on_ws_error; 95return; 96} 97if(!strcmp(option,"error-all")) { 98 ws_error_action = die_on_ws_error; 99 squelch_whitespace_errors =0; 100return; 101} 102if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 103 ws_error_action = correct_ws_error; 104return; 105} 106die("unrecognized whitespace option '%s'", option); 107} 108 109static voidparse_ignorewhitespace_option(const char*option) 110{ 111if(!option || !strcmp(option,"no") || 112!strcmp(option,"false") || !strcmp(option,"never") || 113!strcmp(option,"none")) { 114 ws_ignore_action = ignore_ws_none; 115return; 116} 117if(!strcmp(option,"change")) { 118 ws_ignore_action = ignore_ws_change; 119return; 120} 121die("unrecognized whitespace ignore option '%s'", option); 122} 123 124static voidset_default_whitespace_mode(const char*whitespace_option) 125{ 126if(!whitespace_option && !apply_default_whitespace) 127 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 128} 129 130/* 131 * For "diff-stat" like behaviour, we keep track of the biggest change 132 * we've seen, and the longest filename. That allows us to do simple 133 * scaling. 134 */ 135static int max_change, max_len; 136 137/* 138 * Various "current state", notably line numbers and what 139 * file (and how) we're patching right now.. The "is_xxxx" 140 * things are flags, where -1 means "don't know yet". 141 */ 142static int linenr =1; 143 144/* 145 * This represents one "hunk" from a patch, starting with 146 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 147 * patch text is pointed at by patch, and its byte length 148 * is stored in size. leading and trailing are the number 149 * of context lines. 150 */ 151struct fragment { 152unsigned long leading, trailing; 153unsigned long oldpos, oldlines; 154unsigned long newpos, newlines; 155const char*patch; 156int size; 157int rejected; 158int linenr; 159struct fragment *next; 160}; 161 162/* 163 * When dealing with a binary patch, we reuse "leading" field 164 * to store the type of the binary hunk, either deflated "delta" 165 * or deflated "literal". 166 */ 167#define binary_patch_method leading 168#define BINARY_DELTA_DEFLATED 1 169#define BINARY_LITERAL_DEFLATED 2 170 171/* 172 * This represents a "patch" to a file, both metainfo changes 173 * such as creation/deletion, filemode and content changes represented 174 * as a series of fragments. 175 */ 176struct patch { 177char*new_name, *old_name, *def_name; 178unsigned int old_mode, new_mode; 179int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 180int rejected; 181unsigned ws_rule; 182unsigned long deflate_origlen; 183int lines_added, lines_deleted; 184int score; 185unsigned int is_toplevel_relative:1; 186unsigned int inaccurate_eof:1; 187unsigned int is_binary:1; 188unsigned int is_copy:1; 189unsigned int is_rename:1; 190unsigned int recount:1; 191struct fragment *fragments; 192char*result; 193size_t resultsize; 194char old_sha1_prefix[41]; 195char new_sha1_prefix[41]; 196struct patch *next; 197}; 198 199/* 200 * A line in a file, len-bytes long (includes the terminating LF, 201 * except for an incomplete line at the end if the file ends with 202 * one), and its contents hashes to 'hash'. 203 */ 204struct line { 205size_t len; 206unsigned hash :24; 207unsigned flag :8; 208#define LINE_COMMON 1 209#define LINE_PATCHED 2 210}; 211 212/* 213 * This represents a "file", which is an array of "lines". 214 */ 215struct image { 216char*buf; 217size_t len; 218size_t nr; 219size_t alloc; 220struct line *line_allocated; 221struct line *line; 222}; 223 224/* 225 * Records filenames that have been touched, in order to handle 226 * the case where more than one patches touch the same file. 227 */ 228 229static struct string_list fn_table; 230 231static uint32_thash_line(const char*cp,size_t len) 232{ 233size_t i; 234uint32_t h; 235for(i =0, h =0; i < len; i++) { 236if(!isspace(cp[i])) { 237 h = h *3+ (cp[i] &0xff); 238} 239} 240return h; 241} 242 243/* 244 * Compare lines s1 of length n1 and s2 of length n2, ignoring 245 * whitespace difference. Returns 1 if they match, 0 otherwise 246 */ 247static intfuzzy_matchlines(const char*s1,size_t n1, 248const char*s2,size_t n2) 249{ 250const char*last1 = s1 + n1 -1; 251const char*last2 = s2 + n2 -1; 252int result =0; 253 254/* ignore line endings */ 255while((*last1 =='\r') || (*last1 =='\n')) 256 last1--; 257while((*last2 =='\r') || (*last2 =='\n')) 258 last2--; 259 260/* skip leading whitespace */ 261while(isspace(*s1) && (s1 <= last1)) 262 s1++; 263while(isspace(*s2) && (s2 <= last2)) 264 s2++; 265/* early return if both lines are empty */ 266if((s1 > last1) && (s2 > last2)) 267return1; 268while(!result) { 269 result = *s1++ - *s2++; 270/* 271 * Skip whitespace inside. We check for whitespace on 272 * both buffers because we don't want "a b" to match 273 * "ab" 274 */ 275if(isspace(*s1) &&isspace(*s2)) { 276while(isspace(*s1) && s1 <= last1) 277 s1++; 278while(isspace(*s2) && s2 <= last2) 279 s2++; 280} 281/* 282 * If we reached the end on one side only, 283 * lines don't match 284 */ 285if( 286((s2 > last2) && (s1 <= last1)) || 287((s1 > last1) && (s2 <= last2))) 288return0; 289if((s1 > last1) && (s2 > last2)) 290break; 291} 292 293return!result; 294} 295 296static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 297{ 298ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 299 img->line_allocated[img->nr].len = len; 300 img->line_allocated[img->nr].hash =hash_line(bol, len); 301 img->line_allocated[img->nr].flag = flag; 302 img->nr++; 303} 304 305static voidprepare_image(struct image *image,char*buf,size_t len, 306int prepare_linetable) 307{ 308const char*cp, *ep; 309 310memset(image,0,sizeof(*image)); 311 image->buf = buf; 312 image->len = len; 313 314if(!prepare_linetable) 315return; 316 317 ep = image->buf + image->len; 318 cp = image->buf; 319while(cp < ep) { 320const char*next; 321for(next = cp; next < ep && *next !='\n'; next++) 322; 323if(next < ep) 324 next++; 325add_line_info(image, cp, next - cp,0); 326 cp = next; 327} 328 image->line = image->line_allocated; 329} 330 331static voidclear_image(struct image *image) 332{ 333free(image->buf); 334 image->buf = NULL; 335 image->len =0; 336} 337 338static voidsay_patch_name(FILE*output,const char*pre, 339struct patch *patch,const char*post) 340{ 341fputs(pre, output); 342if(patch->old_name && patch->new_name && 343strcmp(patch->old_name, patch->new_name)) { 344quote_c_style(patch->old_name, NULL, output,0); 345fputs(" => ", output); 346quote_c_style(patch->new_name, NULL, output,0); 347}else{ 348const char*n = patch->new_name; 349if(!n) 350 n = patch->old_name; 351quote_c_style(n, NULL, output,0); 352} 353fputs(post, output); 354} 355 356#define CHUNKSIZE (8192) 357#define SLOP (16) 358 359static voidread_patch_file(struct strbuf *sb,int fd) 360{ 361if(strbuf_read(sb, fd,0) <0) 362die_errno("git apply: failed to read"); 363 364/* 365 * Make sure that we have some slop in the buffer 366 * so that we can do speculative "memcmp" etc, and 367 * see to it that it is NUL-filled. 368 */ 369strbuf_grow(sb, SLOP); 370memset(sb->buf + sb->len,0, SLOP); 371} 372 373static unsigned longlinelen(const char*buffer,unsigned long size) 374{ 375unsigned long len =0; 376while(size--) { 377 len++; 378if(*buffer++ =='\n') 379break; 380} 381return len; 382} 383 384static intis_dev_null(const char*str) 385{ 386return!memcmp("/dev/null", str,9) &&isspace(str[9]); 387} 388 389#define TERM_SPACE 1 390#define TERM_TAB 2 391 392static intname_terminate(const char*name,int namelen,int c,int terminate) 393{ 394if(c ==' '&& !(terminate & TERM_SPACE)) 395return0; 396if(c =='\t'&& !(terminate & TERM_TAB)) 397return0; 398 399return1; 400} 401 402/* remove double slashes to make --index work with such filenames */ 403static char*squash_slash(char*name) 404{ 405int i =0, j =0; 406 407if(!name) 408return NULL; 409 410while(name[i]) { 411if((name[j++] = name[i++]) =='/') 412while(name[i] =='/') 413 i++; 414} 415 name[j] ='\0'; 416return name; 417} 418 419static char*find_name_gnu(const char*line,char*def,int p_value) 420{ 421struct strbuf name = STRBUF_INIT; 422char*cp; 423 424/* 425 * Proposed "new-style" GNU patch/diff format; see 426 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2 427 */ 428if(unquote_c_style(&name, line, NULL)) { 429strbuf_release(&name); 430return NULL; 431} 432 433for(cp = name.buf; p_value; p_value--) { 434 cp =strchr(cp,'/'); 435if(!cp) { 436strbuf_release(&name); 437return NULL; 438} 439 cp++; 440} 441 442/* name can later be freed, so we need 443 * to memmove, not just return cp 444 */ 445strbuf_remove(&name,0, cp - name.buf); 446free(def); 447if(root) 448strbuf_insert(&name,0, root, root_len); 449returnsquash_slash(strbuf_detach(&name, NULL)); 450} 451 452static size_tsane_tz_len(const char*line,size_t len) 453{ 454const char*tz, *p; 455 456if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 457return0; 458 tz = line + len -strlen(" +0500"); 459 460if(tz[1] !='+'&& tz[1] !='-') 461return0; 462 463for(p = tz +2; p != line + len; p++) 464if(!isdigit(*p)) 465return0; 466 467return line + len - tz; 468} 469 470static size_ttz_with_colon_len(const char*line,size_t len) 471{ 472const char*tz, *p; 473 474if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 475return0; 476 tz = line + len -strlen(" +08:00"); 477 478if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 479return0; 480 p = tz +2; 481if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 482!isdigit(*p++) || !isdigit(*p++)) 483return0; 484 485return line + len - tz; 486} 487 488static size_tdate_len(const char*line,size_t len) 489{ 490const char*date, *p; 491 492if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 493return0; 494 p = date = line + len -strlen("72-02-05"); 495 496if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 497!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 498!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 499return0; 500 501if(date - line >=strlen("19") && 502isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 503 date -=strlen("19"); 504 505return line + len - date; 506} 507 508static size_tshort_time_len(const char*line,size_t len) 509{ 510const char*time, *p; 511 512if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 513return0; 514 p = time = line + len -strlen(" 07:01:32"); 515 516/* Permit 1-digit hours? */ 517if(*p++ !=' '|| 518!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 519!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 520!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 521return0; 522 523return line + len - time; 524} 525 526static size_tfractional_time_len(const char*line,size_t len) 527{ 528const char*p; 529size_t n; 530 531/* Expected format: 19:41:17.620000023 */ 532if(!len || !isdigit(line[len -1])) 533return0; 534 p = line + len -1; 535 536/* Fractional seconds. */ 537while(p > line &&isdigit(*p)) 538 p--; 539if(*p !='.') 540return0; 541 542/* Hours, minutes, and whole seconds. */ 543 n =short_time_len(line, p - line); 544if(!n) 545return0; 546 547return line + len - p + n; 548} 549 550static size_ttrailing_spaces_len(const char*line,size_t len) 551{ 552const char*p; 553 554/* Expected format: ' ' x (1 or more) */ 555if(!len || line[len -1] !=' ') 556return0; 557 558 p = line + len; 559while(p != line) { 560 p--; 561if(*p !=' ') 562return line + len - (p +1); 563} 564 565/* All spaces! */ 566return len; 567} 568 569static size_tdiff_timestamp_len(const char*line,size_t len) 570{ 571const char*end = line + len; 572size_t n; 573 574/* 575 * Posix: 2010-07-05 19:41:17 576 * GNU: 2010-07-05 19:41:17.620000023 -0500 577 */ 578 579if(!isdigit(end[-1])) 580return0; 581 582 n =sane_tz_len(line, end - line); 583if(!n) 584 n =tz_with_colon_len(line, end - line); 585 end -= n; 586 587 n =short_time_len(line, end - line); 588if(!n) 589 n =fractional_time_len(line, end - line); 590 end -= n; 591 592 n =date_len(line, end - line); 593if(!n)/* No date. Too bad. */ 594return0; 595 end -= n; 596 597if(end == line)/* No space before date. */ 598return0; 599if(end[-1] =='\t') {/* Success! */ 600 end--; 601return line + len - end; 602} 603if(end[-1] !=' ')/* No space before date. */ 604return0; 605 606/* Whitespace damage. */ 607 end -=trailing_spaces_len(line, end - line); 608return line + len - end; 609} 610 611static char*find_name_common(const char*line,char*def,int p_value, 612const char*end,int terminate) 613{ 614int len; 615const char*start = NULL; 616 617if(p_value ==0) 618 start = line; 619while(line != end) { 620char c = *line; 621 622if(!end &&isspace(c)) { 623if(c =='\n') 624break; 625if(name_terminate(start, line-start, c, terminate)) 626break; 627} 628 line++; 629if(c =='/'&& !--p_value) 630 start = line; 631} 632if(!start) 633returnsquash_slash(def); 634 len = line - start; 635if(!len) 636returnsquash_slash(def); 637 638/* 639 * Generally we prefer the shorter name, especially 640 * if the other one is just a variation of that with 641 * something else tacked on to the end (ie "file.orig" 642 * or "file~"). 643 */ 644if(def) { 645int deflen =strlen(def); 646if(deflen < len && !strncmp(start, def, deflen)) 647returnsquash_slash(def); 648free(def); 649} 650 651if(root) { 652char*ret =xmalloc(root_len + len +1); 653strcpy(ret, root); 654memcpy(ret + root_len, start, len); 655 ret[root_len + len] ='\0'; 656returnsquash_slash(ret); 657} 658 659returnsquash_slash(xmemdupz(start, len)); 660} 661 662static char*find_name(const char*line,char*def,int p_value,int terminate) 663{ 664if(*line =='"') { 665char*name =find_name_gnu(line, def, p_value); 666if(name) 667return name; 668} 669 670returnfind_name_common(line, def, p_value, NULL, terminate); 671} 672 673static char*find_name_traditional(const char*line,char*def,int p_value) 674{ 675size_t len =strlen(line); 676size_t date_len; 677 678if(*line =='"') { 679char*name =find_name_gnu(line, def, p_value); 680if(name) 681return name; 682} 683 684 len =strchrnul(line,'\n') - line; 685 date_len =diff_timestamp_len(line, len); 686if(!date_len) 687returnfind_name_common(line, def, p_value, NULL, TERM_TAB); 688 len -= date_len; 689 690returnfind_name_common(line, def, p_value, line + len,0); 691} 692 693static intcount_slashes(const char*cp) 694{ 695int cnt =0; 696char ch; 697 698while((ch = *cp++)) 699if(ch =='/') 700 cnt++; 701return cnt; 702} 703 704/* 705 * Given the string after "--- " or "+++ ", guess the appropriate 706 * p_value for the given patch. 707 */ 708static intguess_p_value(const char*nameline) 709{ 710char*name, *cp; 711int val = -1; 712 713if(is_dev_null(nameline)) 714return-1; 715 name =find_name_traditional(nameline, NULL,0); 716if(!name) 717return-1; 718 cp =strchr(name,'/'); 719if(!cp) 720 val =0; 721else if(prefix) { 722/* 723 * Does it begin with "a/$our-prefix" and such? Then this is 724 * very likely to apply to our directory. 725 */ 726if(!strncmp(name, prefix, prefix_length)) 727 val =count_slashes(prefix); 728else{ 729 cp++; 730if(!strncmp(cp, prefix, prefix_length)) 731 val =count_slashes(prefix) +1; 732} 733} 734free(name); 735return val; 736} 737 738/* 739 * Does the ---/+++ line has the POSIX timestamp after the last HT? 740 * GNU diff puts epoch there to signal a creation/deletion event. Is 741 * this such a timestamp? 742 */ 743static inthas_epoch_timestamp(const char*nameline) 744{ 745/* 746 * We are only interested in epoch timestamp; any non-zero 747 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 748 * For the same reason, the date must be either 1969-12-31 or 749 * 1970-01-01, and the seconds part must be "00". 750 */ 751const char stamp_regexp[] = 752"^(1969-12-31|1970-01-01)" 753" " 754"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 755" " 756"([-+][0-2][0-9]:?[0-5][0-9])\n"; 757const char*timestamp = NULL, *cp, *colon; 758static regex_t *stamp; 759 regmatch_t m[10]; 760int zoneoffset; 761int hourminute; 762int status; 763 764for(cp = nameline; *cp !='\n'; cp++) { 765if(*cp =='\t') 766 timestamp = cp +1; 767} 768if(!timestamp) 769return0; 770if(!stamp) { 771 stamp =xmalloc(sizeof(*stamp)); 772if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 773warning("Cannot prepare timestamp regexp%s", 774 stamp_regexp); 775return0; 776} 777} 778 779 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 780if(status) { 781if(status != REG_NOMATCH) 782warning("regexec returned%dfor input:%s", 783 status, timestamp); 784return0; 785} 786 787 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 788if(*colon ==':') 789 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 790else 791 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 792if(timestamp[m[3].rm_so] =='-') 793 zoneoffset = -zoneoffset; 794 795/* 796 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 797 * (west of GMT) or 1970-01-01 (east of GMT) 798 */ 799if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 800(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 801return0; 802 803 hourminute = (strtol(timestamp +11, NULL,10) *60+ 804strtol(timestamp +14, NULL,10) - 805 zoneoffset); 806 807return((zoneoffset <0&& hourminute ==1440) || 808(0<= zoneoffset && !hourminute)); 809} 810 811/* 812 * Get the name etc info from the ---/+++ lines of a traditional patch header 813 * 814 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 815 * files, we can happily check the index for a match, but for creating a 816 * new file we should try to match whatever "patch" does. I have no idea. 817 */ 818static voidparse_traditional_patch(const char*first,const char*second,struct patch *patch) 819{ 820char*name; 821 822 first +=4;/* skip "--- " */ 823 second +=4;/* skip "+++ " */ 824if(!p_value_known) { 825int p, q; 826 p =guess_p_value(first); 827 q =guess_p_value(second); 828if(p <0) p = q; 829if(0<= p && p == q) { 830 p_value = p; 831 p_value_known =1; 832} 833} 834if(is_dev_null(first)) { 835 patch->is_new =1; 836 patch->is_delete =0; 837 name =find_name_traditional(second, NULL, p_value); 838 patch->new_name = name; 839}else if(is_dev_null(second)) { 840 patch->is_new =0; 841 patch->is_delete =1; 842 name =find_name_traditional(first, NULL, p_value); 843 patch->old_name = name; 844}else{ 845 name =find_name_traditional(first, NULL, p_value); 846 name =find_name_traditional(second, name, p_value); 847if(has_epoch_timestamp(first)) { 848 patch->is_new =1; 849 patch->is_delete =0; 850 patch->new_name = name; 851}else if(has_epoch_timestamp(second)) { 852 patch->is_new =0; 853 patch->is_delete =1; 854 patch->old_name = name; 855}else{ 856 patch->old_name = patch->new_name = name; 857} 858} 859if(!name) 860die("unable to find filename in patch at line%d", linenr); 861} 862 863static intgitdiff_hdrend(const char*line,struct patch *patch) 864{ 865return-1; 866} 867 868/* 869 * We're anal about diff header consistency, to make 870 * sure that we don't end up having strange ambiguous 871 * patches floating around. 872 * 873 * As a result, gitdiff_{old|new}name() will check 874 * their names against any previous information, just 875 * to make sure.. 876 */ 877static char*gitdiff_verify_name(const char*line,int isnull,char*orig_name,const char*oldnew) 878{ 879if(!orig_name && !isnull) 880returnfind_name(line, NULL, p_value, TERM_TAB); 881 882if(orig_name) { 883int len; 884const char*name; 885char*another; 886 name = orig_name; 887 len =strlen(name); 888if(isnull) 889die("git apply: bad git-diff - expected /dev/null, got%son line%d", name, linenr); 890 another =find_name(line, NULL, p_value, TERM_TAB); 891if(!another ||memcmp(another, name, len +1)) 892die("git apply: bad git-diff - inconsistent%sfilename on line%d", oldnew, linenr); 893free(another); 894return orig_name; 895} 896else{ 897/* expect "/dev/null" */ 898if(memcmp("/dev/null", line,9) || line[9] !='\n') 899die("git apply: bad git-diff - expected /dev/null on line%d", linenr); 900return NULL; 901} 902} 903 904static intgitdiff_oldname(const char*line,struct patch *patch) 905{ 906 patch->old_name =gitdiff_verify_name(line, patch->is_new, patch->old_name,"old"); 907return0; 908} 909 910static intgitdiff_newname(const char*line,struct patch *patch) 911{ 912 patch->new_name =gitdiff_verify_name(line, patch->is_delete, patch->new_name,"new"); 913return0; 914} 915 916static intgitdiff_oldmode(const char*line,struct patch *patch) 917{ 918 patch->old_mode =strtoul(line, NULL,8); 919return0; 920} 921 922static intgitdiff_newmode(const char*line,struct patch *patch) 923{ 924 patch->new_mode =strtoul(line, NULL,8); 925return0; 926} 927 928static intgitdiff_delete(const char*line,struct patch *patch) 929{ 930 patch->is_delete =1; 931 patch->old_name = patch->def_name; 932returngitdiff_oldmode(line, patch); 933} 934 935static intgitdiff_newfile(const char*line,struct patch *patch) 936{ 937 patch->is_new =1; 938 patch->new_name = patch->def_name; 939returngitdiff_newmode(line, patch); 940} 941 942static intgitdiff_copysrc(const char*line,struct patch *patch) 943{ 944 patch->is_copy =1; 945 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0); 946return0; 947} 948 949static intgitdiff_copydst(const char*line,struct patch *patch) 950{ 951 patch->is_copy =1; 952 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0); 953return0; 954} 955 956static intgitdiff_renamesrc(const char*line,struct patch *patch) 957{ 958 patch->is_rename =1; 959 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0); 960return0; 961} 962 963static intgitdiff_renamedst(const char*line,struct patch *patch) 964{ 965 patch->is_rename =1; 966 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0); 967return0; 968} 969 970static intgitdiff_similarity(const char*line,struct patch *patch) 971{ 972if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 973 patch->score =0; 974return0; 975} 976 977static intgitdiff_dissimilarity(const char*line,struct patch *patch) 978{ 979if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 980 patch->score =0; 981return0; 982} 983 984static intgitdiff_index(const char*line,struct patch *patch) 985{ 986/* 987 * index line is N hexadecimal, "..", N hexadecimal, 988 * and optional space with octal mode. 989 */ 990const char*ptr, *eol; 991int len; 992 993 ptr =strchr(line,'.'); 994if(!ptr || ptr[1] !='.'||40< ptr - line) 995return0; 996 len = ptr - line; 997memcpy(patch->old_sha1_prefix, line, len); 998 patch->old_sha1_prefix[len] =0; 9991000 line = ptr +2;1001 ptr =strchr(line,' ');1002 eol =strchr(line,'\n');10031004if(!ptr || eol < ptr)1005 ptr = eol;1006 len = ptr - line;10071008if(40< len)1009return0;1010memcpy(patch->new_sha1_prefix, line, len);1011 patch->new_sha1_prefix[len] =0;1012if(*ptr ==' ')1013 patch->old_mode =strtoul(ptr+1, NULL,8);1014return0;1015}10161017/*1018 * This is normal for a diff that doesn't change anything: we'll fall through1019 * into the next diff. Tell the parser to break out.1020 */1021static intgitdiff_unrecognized(const char*line,struct patch *patch)1022{1023return-1;1024}10251026static const char*stop_at_slash(const char*line,int llen)1027{1028int nslash = p_value;1029int i;10301031for(i =0; i < llen; i++) {1032int ch = line[i];1033if(ch =='/'&& --nslash <=0)1034return&line[i];1035}1036return NULL;1037}10381039/*1040 * This is to extract the same name that appears on "diff --git"1041 * line. We do not find and return anything if it is a rename1042 * patch, and it is OK because we will find the name elsewhere.1043 * We need to reliably find name only when it is mode-change only,1044 * creation or deletion of an empty file. In any of these cases,1045 * both sides are the same name under a/ and b/ respectively.1046 */1047static char*git_header_name(char*line,int llen)1048{1049const char*name;1050const char*second = NULL;1051size_t len, line_len;10521053 line +=strlen("diff --git ");1054 llen -=strlen("diff --git ");10551056if(*line =='"') {1057const char*cp;1058struct strbuf first = STRBUF_INIT;1059struct strbuf sp = STRBUF_INIT;10601061if(unquote_c_style(&first, line, &second))1062goto free_and_fail1;10631064/* advance to the first slash */1065 cp =stop_at_slash(first.buf, first.len);1066/* we do not accept absolute paths */1067if(!cp || cp == first.buf)1068goto free_and_fail1;1069strbuf_remove(&first,0, cp +1- first.buf);10701071/*1072 * second points at one past closing dq of name.1073 * find the second name.1074 */1075while((second < line + llen) &&isspace(*second))1076 second++;10771078if(line + llen <= second)1079goto free_and_fail1;1080if(*second =='"') {1081if(unquote_c_style(&sp, second, NULL))1082goto free_and_fail1;1083 cp =stop_at_slash(sp.buf, sp.len);1084if(!cp || cp == sp.buf)1085goto free_and_fail1;1086/* They must match, otherwise ignore */1087if(strcmp(cp +1, first.buf))1088goto free_and_fail1;1089strbuf_release(&sp);1090returnstrbuf_detach(&first, NULL);1091}10921093/* unquoted second */1094 cp =stop_at_slash(second, line + llen - second);1095if(!cp || cp == second)1096goto free_and_fail1;1097 cp++;1098if(line + llen - cp != first.len +1||1099memcmp(first.buf, cp, first.len))1100goto free_and_fail1;1101returnstrbuf_detach(&first, NULL);11021103 free_and_fail1:1104strbuf_release(&first);1105strbuf_release(&sp);1106return NULL;1107}11081109/* unquoted first name */1110 name =stop_at_slash(line, llen);1111if(!name || name == line)1112return NULL;1113 name++;11141115/*1116 * since the first name is unquoted, a dq if exists must be1117 * the beginning of the second name.1118 */1119for(second = name; second < line + llen; second++) {1120if(*second =='"') {1121struct strbuf sp = STRBUF_INIT;1122const char*np;11231124if(unquote_c_style(&sp, second, NULL))1125goto free_and_fail2;11261127 np =stop_at_slash(sp.buf, sp.len);1128if(!np || np == sp.buf)1129goto free_and_fail2;1130 np++;11311132 len = sp.buf + sp.len - np;1133if(len < second - name &&1134!strncmp(np, name, len) &&1135isspace(name[len])) {1136/* Good */1137strbuf_remove(&sp,0, np - sp.buf);1138returnstrbuf_detach(&sp, NULL);1139}11401141 free_and_fail2:1142strbuf_release(&sp);1143return NULL;1144}1145}11461147/*1148 * Accept a name only if it shows up twice, exactly the same1149 * form.1150 */1151 second =strchr(name,'\n');1152if(!second)1153return NULL;1154 line_len = second - name;1155for(len =0; ; len++) {1156switch(name[len]) {1157default:1158continue;1159case'\n':1160return NULL;1161case'\t':case' ':1162 second =stop_at_slash(name + len, line_len - len);1163if(!second)1164return NULL;1165 second++;1166if(second[len] =='\n'&& !strncmp(name, second, len)) {1167returnxmemdupz(name, len);1168}1169}1170}1171}11721173/* Verify that we recognize the lines following a git header */1174static intparse_git_header(char*line,int len,unsigned int size,struct patch *patch)1175{1176unsigned long offset;11771178/* A git diff has explicit new/delete information, so we don't guess */1179 patch->is_new =0;1180 patch->is_delete =0;11811182/*1183 * Some things may not have the old name in the1184 * rest of the headers anywhere (pure mode changes,1185 * or removing or adding empty files), so we get1186 * the default name from the header.1187 */1188 patch->def_name =git_header_name(line, len);1189if(patch->def_name && root) {1190char*s =xmalloc(root_len +strlen(patch->def_name) +1);1191strcpy(s, root);1192strcpy(s + root_len, patch->def_name);1193free(patch->def_name);1194 patch->def_name = s;1195}11961197 line += len;1198 size -= len;1199 linenr++;1200for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) {1201static const struct opentry {1202const char*str;1203int(*fn)(const char*,struct patch *);1204} optable[] = {1205{"@@ -", gitdiff_hdrend },1206{"--- ", gitdiff_oldname },1207{"+++ ", gitdiff_newname },1208{"old mode ", gitdiff_oldmode },1209{"new mode ", gitdiff_newmode },1210{"deleted file mode ", gitdiff_delete },1211{"new file mode ", gitdiff_newfile },1212{"copy from ", gitdiff_copysrc },1213{"copy to ", gitdiff_copydst },1214{"rename old ", gitdiff_renamesrc },1215{"rename new ", gitdiff_renamedst },1216{"rename from ", gitdiff_renamesrc },1217{"rename to ", gitdiff_renamedst },1218{"similarity index ", gitdiff_similarity },1219{"dissimilarity index ", gitdiff_dissimilarity },1220{"index ", gitdiff_index },1221{"", gitdiff_unrecognized },1222};1223int i;12241225 len =linelen(line, size);1226if(!len || line[len-1] !='\n')1227break;1228for(i =0; i <ARRAY_SIZE(optable); i++) {1229const struct opentry *p = optable + i;1230int oplen =strlen(p->str);1231if(len < oplen ||memcmp(p->str, line, oplen))1232continue;1233if(p->fn(line + oplen, patch) <0)1234return offset;1235break;1236}1237}12381239return offset;1240}12411242static intparse_num(const char*line,unsigned long*p)1243{1244char*ptr;12451246if(!isdigit(*line))1247return0;1248*p =strtoul(line, &ptr,10);1249return ptr - line;1250}12511252static intparse_range(const char*line,int len,int offset,const char*expect,1253unsigned long*p1,unsigned long*p2)1254{1255int digits, ex;12561257if(offset <0|| offset >= len)1258return-1;1259 line += offset;1260 len -= offset;12611262 digits =parse_num(line, p1);1263if(!digits)1264return-1;12651266 offset += digits;1267 line += digits;1268 len -= digits;12691270*p2 =1;1271if(*line ==',') {1272 digits =parse_num(line+1, p2);1273if(!digits)1274return-1;12751276 offset += digits+1;1277 line += digits+1;1278 len -= digits+1;1279}12801281 ex =strlen(expect);1282if(ex > len)1283return-1;1284if(memcmp(line, expect, ex))1285return-1;12861287return offset + ex;1288}12891290static voidrecount_diff(char*line,int size,struct fragment *fragment)1291{1292int oldlines =0, newlines =0, ret =0;12931294if(size <1) {1295warning("recount: ignore empty hunk");1296return;1297}12981299for(;;) {1300int len =linelen(line, size);1301 size -= len;1302 line += len;13031304if(size <1)1305break;13061307switch(*line) {1308case' ':case'\n':1309 newlines++;1310/* fall through */1311case'-':1312 oldlines++;1313continue;1314case'+':1315 newlines++;1316continue;1317case'\\':1318continue;1319case'@':1320 ret = size <3||prefixcmp(line,"@@ ");1321break;1322case'd':1323 ret = size <5||prefixcmp(line,"diff ");1324break;1325default:1326 ret = -1;1327break;1328}1329if(ret) {1330warning("recount: unexpected line: %.*s",1331(int)linelen(line, size), line);1332return;1333}1334break;1335}1336 fragment->oldlines = oldlines;1337 fragment->newlines = newlines;1338}13391340/*1341 * Parse a unified diff fragment header of the1342 * form "@@ -a,b +c,d @@"1343 */1344static intparse_fragment_header(char*line,int len,struct fragment *fragment)1345{1346int offset;13471348if(!len || line[len-1] !='\n')1349return-1;13501351/* Figure out the number of lines in a fragment */1352 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1353 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);13541355return offset;1356}13571358static intfind_header(char*line,unsigned long size,int*hdrsize,struct patch *patch)1359{1360unsigned long offset, len;13611362 patch->is_toplevel_relative =0;1363 patch->is_rename = patch->is_copy =0;1364 patch->is_new = patch->is_delete = -1;1365 patch->old_mode = patch->new_mode =0;1366 patch->old_name = patch->new_name = NULL;1367for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) {1368unsigned long nextlen;13691370 len =linelen(line, size);1371if(!len)1372break;13731374/* Testing this early allows us to take a few shortcuts.. */1375if(len <6)1376continue;13771378/*1379 * Make sure we don't find any unconnected patch fragments.1380 * That's a sign that we didn't find a header, and that a1381 * patch has become corrupted/broken up.1382 */1383if(!memcmp("@@ -", line,4)) {1384struct fragment dummy;1385if(parse_fragment_header(line, len, &dummy) <0)1386continue;1387die("patch fragment without header at line%d: %.*s",1388 linenr, (int)len-1, line);1389}13901391if(size < len +6)1392break;13931394/*1395 * Git patch? It might not have a real patch, just a rename1396 * or mode change, so we handle that specially1397 */1398if(!memcmp("diff --git ", line,11)) {1399int git_hdr_len =parse_git_header(line, len, size, patch);1400if(git_hdr_len <= len)1401continue;1402if(!patch->old_name && !patch->new_name) {1403if(!patch->def_name)1404die("git diff header lacks filename information when removing "1405"%dleading pathname components (line%d)", p_value, linenr);1406 patch->old_name = patch->new_name = patch->def_name;1407}1408if(!patch->is_delete && !patch->new_name)1409die("git diff header lacks filename information "1410"(line%d)", linenr);1411 patch->is_toplevel_relative =1;1412*hdrsize = git_hdr_len;1413return offset;1414}14151416/* --- followed by +++ ? */1417if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1418continue;14191420/*1421 * We only accept unified patches, so we want it to1422 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1423 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1424 */1425 nextlen =linelen(line + len, size - len);1426if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1427continue;14281429/* Ok, we'll consider it a patch */1430parse_traditional_patch(line, line+len, patch);1431*hdrsize = len + nextlen;1432 linenr +=2;1433return offset;1434}1435return-1;1436}14371438static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1439{1440char*err;14411442if(!result)1443return;14441445 whitespace_error++;1446if(squelch_whitespace_errors &&1447 squelch_whitespace_errors < whitespace_error)1448return;14491450 err =whitespace_error_string(result);1451fprintf(stderr,"%s:%d:%s.\n%.*s\n",1452 patch_input_file, linenr, err, len, line);1453free(err);1454}14551456static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1457{1458unsigned result =ws_check(line +1, len -1, ws_rule);14591460record_ws_error(result, line +1, len -2, linenr);1461}14621463/*1464 * Parse a unified diff. Note that this really needs to parse each1465 * fragment separately, since the only way to know the difference1466 * between a "---" that is part of a patch, and a "---" that starts1467 * the next patch is to look at the line counts..1468 */1469static intparse_fragment(char*line,unsigned long size,1470struct patch *patch,struct fragment *fragment)1471{1472int added, deleted;1473int len =linelen(line, size), offset;1474unsigned long oldlines, newlines;1475unsigned long leading, trailing;14761477 offset =parse_fragment_header(line, len, fragment);1478if(offset <0)1479return-1;1480if(offset >0&& patch->recount)1481recount_diff(line + offset, size - offset, fragment);1482 oldlines = fragment->oldlines;1483 newlines = fragment->newlines;1484 leading =0;1485 trailing =0;14861487/* Parse the thing.. */1488 line += len;1489 size -= len;1490 linenr++;1491 added = deleted =0;1492for(offset = len;14930< size;1494 offset += len, size -= len, line += len, linenr++) {1495if(!oldlines && !newlines)1496break;1497 len =linelen(line, size);1498if(!len || line[len-1] !='\n')1499return-1;1500switch(*line) {1501default:1502return-1;1503case'\n':/* newer GNU diff, an empty context line */1504case' ':1505 oldlines--;1506 newlines--;1507if(!deleted && !added)1508 leading++;1509 trailing++;1510break;1511case'-':1512if(apply_in_reverse &&1513 ws_error_action != nowarn_ws_error)1514check_whitespace(line, len, patch->ws_rule);1515 deleted++;1516 oldlines--;1517 trailing =0;1518break;1519case'+':1520if(!apply_in_reverse &&1521 ws_error_action != nowarn_ws_error)1522check_whitespace(line, len, patch->ws_rule);1523 added++;1524 newlines--;1525 trailing =0;1526break;15271528/*1529 * We allow "\ No newline at end of file". Depending1530 * on locale settings when the patch was produced we1531 * don't know what this line looks like. The only1532 * thing we do know is that it begins with "\ ".1533 * Checking for 12 is just for sanity check -- any1534 * l10n of "\ No newline..." is at least that long.1535 */1536case'\\':1537if(len <12||memcmp(line,"\\",2))1538return-1;1539break;1540}1541}1542if(oldlines || newlines)1543return-1;1544 fragment->leading = leading;1545 fragment->trailing = trailing;15461547/*1548 * If a fragment ends with an incomplete line, we failed to include1549 * it in the above loop because we hit oldlines == newlines == 01550 * before seeing it.1551 */1552if(12< size && !memcmp(line,"\\",2))1553 offset +=linelen(line, size);15541555 patch->lines_added += added;1556 patch->lines_deleted += deleted;15571558if(0< patch->is_new && oldlines)1559returnerror("new file depends on old contents");1560if(0< patch->is_delete && newlines)1561returnerror("deleted file still has contents");1562return offset;1563}15641565static intparse_single_patch(char*line,unsigned long size,struct patch *patch)1566{1567unsigned long offset =0;1568unsigned long oldlines =0, newlines =0, context =0;1569struct fragment **fragp = &patch->fragments;15701571while(size >4&& !memcmp(line,"@@ -",4)) {1572struct fragment *fragment;1573int len;15741575 fragment =xcalloc(1,sizeof(*fragment));1576 fragment->linenr = linenr;1577 len =parse_fragment(line, size, patch, fragment);1578if(len <=0)1579die("corrupt patch at line%d", linenr);1580 fragment->patch = line;1581 fragment->size = len;1582 oldlines += fragment->oldlines;1583 newlines += fragment->newlines;1584 context += fragment->leading + fragment->trailing;15851586*fragp = fragment;1587 fragp = &fragment->next;15881589 offset += len;1590 line += len;1591 size -= len;1592}15931594/*1595 * If something was removed (i.e. we have old-lines) it cannot1596 * be creation, and if something was added it cannot be1597 * deletion. However, the reverse is not true; --unified=01598 * patches that only add are not necessarily creation even1599 * though they do not have any old lines, and ones that only1600 * delete are not necessarily deletion.1601 *1602 * Unfortunately, a real creation/deletion patch do _not_ have1603 * any context line by definition, so we cannot safely tell it1604 * apart with --unified=0 insanity. At least if the patch has1605 * more than one hunk it is not creation or deletion.1606 */1607if(patch->is_new <0&&1608(oldlines || (patch->fragments && patch->fragments->next)))1609 patch->is_new =0;1610if(patch->is_delete <0&&1611(newlines || (patch->fragments && patch->fragments->next)))1612 patch->is_delete =0;16131614if(0< patch->is_new && oldlines)1615die("new file%sdepends on old contents", patch->new_name);1616if(0< patch->is_delete && newlines)1617die("deleted file%sstill has contents", patch->old_name);1618if(!patch->is_delete && !newlines && context)1619fprintf(stderr,"** warning: file%sbecomes empty but "1620"is not deleted\n", patch->new_name);16211622return offset;1623}16241625staticinlineintmetadata_changes(struct patch *patch)1626{1627return patch->is_rename >0||1628 patch->is_copy >0||1629 patch->is_new >0||1630 patch->is_delete ||1631(patch->old_mode && patch->new_mode &&1632 patch->old_mode != patch->new_mode);1633}16341635static char*inflate_it(const void*data,unsigned long size,1636unsigned long inflated_size)1637{1638 git_zstream stream;1639void*out;1640int st;16411642memset(&stream,0,sizeof(stream));16431644 stream.next_in = (unsigned char*)data;1645 stream.avail_in = size;1646 stream.next_out = out =xmalloc(inflated_size);1647 stream.avail_out = inflated_size;1648git_inflate_init(&stream);1649 st =git_inflate(&stream, Z_FINISH);1650git_inflate_end(&stream);1651if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1652free(out);1653return NULL;1654}1655return out;1656}16571658static struct fragment *parse_binary_hunk(char**buf_p,1659unsigned long*sz_p,1660int*status_p,1661int*used_p)1662{1663/*1664 * Expect a line that begins with binary patch method ("literal"1665 * or "delta"), followed by the length of data before deflating.1666 * a sequence of 'length-byte' followed by base-85 encoded data1667 * should follow, terminated by a newline.1668 *1669 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1670 * and we would limit the patch line to 66 characters,1671 * so one line can fit up to 13 groups that would decode1672 * to 52 bytes max. The length byte 'A'-'Z' corresponds1673 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1674 */1675int llen, used;1676unsigned long size = *sz_p;1677char*buffer = *buf_p;1678int patch_method;1679unsigned long origlen;1680char*data = NULL;1681int hunk_size =0;1682struct fragment *frag;16831684 llen =linelen(buffer, size);1685 used = llen;16861687*status_p =0;16881689if(!prefixcmp(buffer,"delta ")) {1690 patch_method = BINARY_DELTA_DEFLATED;1691 origlen =strtoul(buffer +6, NULL,10);1692}1693else if(!prefixcmp(buffer,"literal ")) {1694 patch_method = BINARY_LITERAL_DEFLATED;1695 origlen =strtoul(buffer +8, NULL,10);1696}1697else1698return NULL;16991700 linenr++;1701 buffer += llen;1702while(1) {1703int byte_length, max_byte_length, newsize;1704 llen =linelen(buffer, size);1705 used += llen;1706 linenr++;1707if(llen ==1) {1708/* consume the blank line */1709 buffer++;1710 size--;1711break;1712}1713/*1714 * Minimum line is "A00000\n" which is 7-byte long,1715 * and the line length must be multiple of 5 plus 2.1716 */1717if((llen <7) || (llen-2) %5)1718goto corrupt;1719 max_byte_length = (llen -2) /5*4;1720 byte_length = *buffer;1721if('A'<= byte_length && byte_length <='Z')1722 byte_length = byte_length -'A'+1;1723else if('a'<= byte_length && byte_length <='z')1724 byte_length = byte_length -'a'+27;1725else1726goto corrupt;1727/* if the input length was not multiple of 4, we would1728 * have filler at the end but the filler should never1729 * exceed 3 bytes1730 */1731if(max_byte_length < byte_length ||1732 byte_length <= max_byte_length -4)1733goto corrupt;1734 newsize = hunk_size + byte_length;1735 data =xrealloc(data, newsize);1736if(decode_85(data + hunk_size, buffer +1, byte_length))1737goto corrupt;1738 hunk_size = newsize;1739 buffer += llen;1740 size -= llen;1741}17421743 frag =xcalloc(1,sizeof(*frag));1744 frag->patch =inflate_it(data, hunk_size, origlen);1745if(!frag->patch)1746goto corrupt;1747free(data);1748 frag->size = origlen;1749*buf_p = buffer;1750*sz_p = size;1751*used_p = used;1752 frag->binary_patch_method = patch_method;1753return frag;17541755 corrupt:1756free(data);1757*status_p = -1;1758error("corrupt binary patch at line%d: %.*s",1759 linenr-1, llen-1, buffer);1760return NULL;1761}17621763static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1764{1765/*1766 * We have read "GIT binary patch\n"; what follows is a line1767 * that says the patch method (currently, either "literal" or1768 * "delta") and the length of data before deflating; a1769 * sequence of 'length-byte' followed by base-85 encoded data1770 * follows.1771 *1772 * When a binary patch is reversible, there is another binary1773 * hunk in the same format, starting with patch method (either1774 * "literal" or "delta") with the length of data, and a sequence1775 * of length-byte + base-85 encoded data, terminated with another1776 * empty line. This data, when applied to the postimage, produces1777 * the preimage.1778 */1779struct fragment *forward;1780struct fragment *reverse;1781int status;1782int used, used_1;17831784 forward =parse_binary_hunk(&buffer, &size, &status, &used);1785if(!forward && !status)1786/* there has to be one hunk (forward hunk) */1787returnerror("unrecognized binary patch at line%d", linenr-1);1788if(status)1789/* otherwise we already gave an error message */1790return status;17911792 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1793if(reverse)1794 used += used_1;1795else if(status) {1796/*1797 * Not having reverse hunk is not an error, but having1798 * a corrupt reverse hunk is.1799 */1800free((void*) forward->patch);1801free(forward);1802return status;1803}1804 forward->next = reverse;1805 patch->fragments = forward;1806 patch->is_binary =1;1807return used;1808}18091810static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1811{1812int hdrsize, patchsize;1813int offset =find_header(buffer, size, &hdrsize, patch);18141815if(offset <0)1816return offset;18171818 patch->ws_rule =whitespace_rule(patch->new_name1819? patch->new_name1820: patch->old_name);18211822 patchsize =parse_single_patch(buffer + offset + hdrsize,1823 size - offset - hdrsize, patch);18241825if(!patchsize) {1826static const char*binhdr[] = {1827"Binary files ",1828"Files ",1829 NULL,1830};1831static const char git_binary[] ="GIT binary patch\n";1832int i;1833int hd = hdrsize + offset;1834unsigned long llen =linelen(buffer + hd, size - hd);18351836if(llen ==sizeof(git_binary) -1&&1837!memcmp(git_binary, buffer + hd, llen)) {1838int used;1839 linenr++;1840 used =parse_binary(buffer + hd + llen,1841 size - hd - llen, patch);1842if(used)1843 patchsize = used + llen;1844else1845 patchsize =0;1846}1847else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1848for(i =0; binhdr[i]; i++) {1849int len =strlen(binhdr[i]);1850if(len < size - hd &&1851!memcmp(binhdr[i], buffer + hd, len)) {1852 linenr++;1853 patch->is_binary =1;1854 patchsize = llen;1855break;1856}1857}1858}18591860/* Empty patch cannot be applied if it is a text patch1861 * without metadata change. A binary patch appears1862 * empty to us here.1863 */1864if((apply || check) &&1865(!patch->is_binary && !metadata_changes(patch)))1866die("patch with only garbage at line%d", linenr);1867}18681869return offset + hdrsize + patchsize;1870}18711872#define swap(a,b) myswap((a),(b),sizeof(a))18731874#define myswap(a, b, size) do { \1875 unsigned char mytmp[size]; \1876 memcpy(mytmp, &a, size); \1877 memcpy(&a, &b, size); \1878 memcpy(&b, mytmp, size); \1879} while (0)18801881static voidreverse_patches(struct patch *p)1882{1883for(; p; p = p->next) {1884struct fragment *frag = p->fragments;18851886swap(p->new_name, p->old_name);1887swap(p->new_mode, p->old_mode);1888swap(p->is_new, p->is_delete);1889swap(p->lines_added, p->lines_deleted);1890swap(p->old_sha1_prefix, p->new_sha1_prefix);18911892for(; frag; frag = frag->next) {1893swap(frag->newpos, frag->oldpos);1894swap(frag->newlines, frag->oldlines);1895}1896}1897}18981899static const char pluses[] =1900"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";1901static const char minuses[]=1902"----------------------------------------------------------------------";19031904static voidshow_stats(struct patch *patch)1905{1906struct strbuf qname = STRBUF_INIT;1907char*cp = patch->new_name ? patch->new_name : patch->old_name;1908int max, add, del;19091910quote_c_style(cp, &qname, NULL,0);19111912/*1913 * "scale" the filename1914 */1915 max = max_len;1916if(max >50)1917 max =50;19181919if(qname.len > max) {1920 cp =strchr(qname.buf + qname.len +3- max,'/');1921if(!cp)1922 cp = qname.buf + qname.len +3- max;1923strbuf_splice(&qname,0, cp - qname.buf,"...",3);1924}19251926if(patch->is_binary) {1927printf(" %-*s | Bin\n", max, qname.buf);1928strbuf_release(&qname);1929return;1930}19311932printf(" %-*s |", max, qname.buf);1933strbuf_release(&qname);19341935/*1936 * scale the add/delete1937 */1938 max = max + max_change >70?70- max : max_change;1939 add = patch->lines_added;1940 del = patch->lines_deleted;19411942if(max_change >0) {1943int total = ((add + del) * max + max_change /2) / max_change;1944 add = (add * max + max_change /2) / max_change;1945 del = total - add;1946}1947printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,1948 add, pluses, del, minuses);1949}19501951static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)1952{1953switch(st->st_mode & S_IFMT) {1954case S_IFLNK:1955if(strbuf_readlink(buf, path, st->st_size) <0)1956returnerror("unable to read symlink%s", path);1957return0;1958case S_IFREG:1959if(strbuf_read_file(buf, path, st->st_size) != st->st_size)1960returnerror("unable to open or read%s", path);1961convert_to_git(path, buf->buf, buf->len, buf,0);1962return0;1963default:1964return-1;1965}1966}19671968/*1969 * Update the preimage, and the common lines in postimage,1970 * from buffer buf of length len. If postlen is 0 the postimage1971 * is updated in place, otherwise it's updated on a new buffer1972 * of length postlen1973 */19741975static voidupdate_pre_post_images(struct image *preimage,1976struct image *postimage,1977char*buf,1978size_t len,size_t postlen)1979{1980int i, ctx;1981char*new, *old, *fixed;1982struct image fixed_preimage;19831984/*1985 * Update the preimage with whitespace fixes. Note that we1986 * are not losing preimage->buf -- apply_one_fragment() will1987 * free "oldlines".1988 */1989prepare_image(&fixed_preimage, buf, len,1);1990assert(fixed_preimage.nr == preimage->nr);1991for(i =0; i < preimage->nr; i++)1992 fixed_preimage.line[i].flag = preimage->line[i].flag;1993free(preimage->line_allocated);1994*preimage = fixed_preimage;19951996/*1997 * Adjust the common context lines in postimage. This can be1998 * done in-place when we are just doing whitespace fixing,1999 * which does not make the string grow, but needs a new buffer2000 * when ignoring whitespace causes the update, since in this case2001 * we could have e.g. tabs converted to multiple spaces.2002 * We trust the caller to tell us if the update can be done2003 * in place (postlen==0) or not.2004 */2005 old = postimage->buf;2006if(postlen)2007new= postimage->buf =xmalloc(postlen);2008else2009new= old;2010 fixed = preimage->buf;2011for(i = ctx =0; i < postimage->nr; i++) {2012size_t len = postimage->line[i].len;2013if(!(postimage->line[i].flag & LINE_COMMON)) {2014/* an added line -- no counterparts in preimage */2015memmove(new, old, len);2016 old += len;2017new+= len;2018continue;2019}20202021/* a common context -- skip it in the original postimage */2022 old += len;20232024/* and find the corresponding one in the fixed preimage */2025while(ctx < preimage->nr &&2026!(preimage->line[ctx].flag & LINE_COMMON)) {2027 fixed += preimage->line[ctx].len;2028 ctx++;2029}2030if(preimage->nr <= ctx)2031die("oops");20322033/* and copy it in, while fixing the line length */2034 len = preimage->line[ctx].len;2035memcpy(new, fixed, len);2036new+= len;2037 fixed += len;2038 postimage->line[i].len = len;2039 ctx++;2040}20412042/* Fix the length of the whole thing */2043 postimage->len =new- postimage->buf;2044}20452046static intmatch_fragment(struct image *img,2047struct image *preimage,2048struct image *postimage,2049unsigned longtry,2050int try_lno,2051unsigned ws_rule,2052int match_beginning,int match_end)2053{2054int i;2055char*fixed_buf, *buf, *orig, *target;2056struct strbuf fixed;2057size_t fixed_len;2058int preimage_limit;20592060if(preimage->nr + try_lno <= img->nr) {2061/*2062 * The hunk falls within the boundaries of img.2063 */2064 preimage_limit = preimage->nr;2065if(match_end && (preimage->nr + try_lno != img->nr))2066return0;2067}else if(ws_error_action == correct_ws_error &&2068(ws_rule & WS_BLANK_AT_EOF)) {2069/*2070 * This hunk extends beyond the end of img, and we are2071 * removing blank lines at the end of the file. This2072 * many lines from the beginning of the preimage must2073 * match with img, and the remainder of the preimage2074 * must be blank.2075 */2076 preimage_limit = img->nr - try_lno;2077}else{2078/*2079 * The hunk extends beyond the end of the img and2080 * we are not removing blanks at the end, so we2081 * should reject the hunk at this position.2082 */2083return0;2084}20852086if(match_beginning && try_lno)2087return0;20882089/* Quick hash check */2090for(i =0; i < preimage_limit; i++)2091if((img->line[try_lno + i].flag & LINE_PATCHED) ||2092(preimage->line[i].hash != img->line[try_lno + i].hash))2093return0;20942095if(preimage_limit == preimage->nr) {2096/*2097 * Do we have an exact match? If we were told to match2098 * at the end, size must be exactly at try+fragsize,2099 * otherwise try+fragsize must be still within the preimage,2100 * and either case, the old piece should match the preimage2101 * exactly.2102 */2103if((match_end2104? (try+ preimage->len == img->len)2105: (try+ preimage->len <= img->len)) &&2106!memcmp(img->buf +try, preimage->buf, preimage->len))2107return1;2108}else{2109/*2110 * The preimage extends beyond the end of img, so2111 * there cannot be an exact match.2112 *2113 * There must be one non-blank context line that match2114 * a line before the end of img.2115 */2116char*buf_end;21172118 buf = preimage->buf;2119 buf_end = buf;2120for(i =0; i < preimage_limit; i++)2121 buf_end += preimage->line[i].len;21222123for( ; buf < buf_end; buf++)2124if(!isspace(*buf))2125break;2126if(buf == buf_end)2127return0;2128}21292130/*2131 * No exact match. If we are ignoring whitespace, run a line-by-line2132 * fuzzy matching. We collect all the line length information because2133 * we need it to adjust whitespace if we match.2134 */2135if(ws_ignore_action == ignore_ws_change) {2136size_t imgoff =0;2137size_t preoff =0;2138size_t postlen = postimage->len;2139size_t extra_chars;2140char*preimage_eof;2141char*preimage_end;2142for(i =0; i < preimage_limit; i++) {2143size_t prelen = preimage->line[i].len;2144size_t imglen = img->line[try_lno+i].len;21452146if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2147 preimage->buf + preoff, prelen))2148return0;2149if(preimage->line[i].flag & LINE_COMMON)2150 postlen += imglen - prelen;2151 imgoff += imglen;2152 preoff += prelen;2153}21542155/*2156 * Ok, the preimage matches with whitespace fuzz.2157 *2158 * imgoff now holds the true length of the target that2159 * matches the preimage before the end of the file.2160 *2161 * Count the number of characters in the preimage that fall2162 * beyond the end of the file and make sure that all of them2163 * are whitespace characters. (This can only happen if2164 * we are removing blank lines at the end of the file.)2165 */2166 buf = preimage_eof = preimage->buf + preoff;2167for( ; i < preimage->nr; i++)2168 preoff += preimage->line[i].len;2169 preimage_end = preimage->buf + preoff;2170for( ; buf < preimage_end; buf++)2171if(!isspace(*buf))2172return0;21732174/*2175 * Update the preimage and the common postimage context2176 * lines to use the same whitespace as the target.2177 * If whitespace is missing in the target (i.e.2178 * if the preimage extends beyond the end of the file),2179 * use the whitespace from the preimage.2180 */2181 extra_chars = preimage_end - preimage_eof;2182strbuf_init(&fixed, imgoff + extra_chars);2183strbuf_add(&fixed, img->buf +try, imgoff);2184strbuf_add(&fixed, preimage_eof, extra_chars);2185 fixed_buf =strbuf_detach(&fixed, &fixed_len);2186update_pre_post_images(preimage, postimage,2187 fixed_buf, fixed_len, postlen);2188return1;2189}21902191if(ws_error_action != correct_ws_error)2192return0;21932194/*2195 * The hunk does not apply byte-by-byte, but the hash says2196 * it might with whitespace fuzz. We haven't been asked to2197 * ignore whitespace, we were asked to correct whitespace2198 * errors, so let's try matching after whitespace correction.2199 *2200 * The preimage may extend beyond the end of the file,2201 * but in this loop we will only handle the part of the2202 * preimage that falls within the file.2203 */2204strbuf_init(&fixed, preimage->len +1);2205 orig = preimage->buf;2206 target = img->buf +try;2207for(i =0; i < preimage_limit; i++) {2208size_t oldlen = preimage->line[i].len;2209size_t tgtlen = img->line[try_lno + i].len;2210size_t fixstart = fixed.len;2211struct strbuf tgtfix;2212int match;22132214/* Try fixing the line in the preimage */2215ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);22162217/* Try fixing the line in the target */2218strbuf_init(&tgtfix, tgtlen);2219ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);22202221/*2222 * If they match, either the preimage was based on2223 * a version before our tree fixed whitespace breakage,2224 * or we are lacking a whitespace-fix patch the tree2225 * the preimage was based on already had (i.e. target2226 * has whitespace breakage, the preimage doesn't).2227 * In either case, we are fixing the whitespace breakages2228 * so we might as well take the fix together with their2229 * real change.2230 */2231 match = (tgtfix.len == fixed.len - fixstart &&2232!memcmp(tgtfix.buf, fixed.buf + fixstart,2233 fixed.len - fixstart));22342235strbuf_release(&tgtfix);2236if(!match)2237goto unmatch_exit;22382239 orig += oldlen;2240 target += tgtlen;2241}224222432244/*2245 * Now handle the lines in the preimage that falls beyond the2246 * end of the file (if any). They will only match if they are2247 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2248 * false).2249 */2250for( ; i < preimage->nr; i++) {2251size_t fixstart = fixed.len;/* start of the fixed preimage */2252size_t oldlen = preimage->line[i].len;2253int j;22542255/* Try fixing the line in the preimage */2256ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);22572258for(j = fixstart; j < fixed.len; j++)2259if(!isspace(fixed.buf[j]))2260goto unmatch_exit;22612262 orig += oldlen;2263}22642265/*2266 * Yes, the preimage is based on an older version that still2267 * has whitespace breakages unfixed, and fixing them makes the2268 * hunk match. Update the context lines in the postimage.2269 */2270 fixed_buf =strbuf_detach(&fixed, &fixed_len);2271update_pre_post_images(preimage, postimage,2272 fixed_buf, fixed_len,0);2273return1;22742275 unmatch_exit:2276strbuf_release(&fixed);2277return0;2278}22792280static intfind_pos(struct image *img,2281struct image *preimage,2282struct image *postimage,2283int line,2284unsigned ws_rule,2285int match_beginning,int match_end)2286{2287int i;2288unsigned long backwards, forwards,try;2289int backwards_lno, forwards_lno, try_lno;22902291/*2292 * If match_beginning or match_end is specified, there is no2293 * point starting from a wrong line that will never match and2294 * wander around and wait for a match at the specified end.2295 */2296if(match_beginning)2297 line =0;2298else if(match_end)2299 line = img->nr - preimage->nr;23002301/*2302 * Because the comparison is unsigned, the following test2303 * will also take care of a negative line number that can2304 * result when match_end and preimage is larger than the target.2305 */2306if((size_t) line > img->nr)2307 line = img->nr;23082309try=0;2310for(i =0; i < line; i++)2311try+= img->line[i].len;23122313/*2314 * There's probably some smart way to do this, but I'll leave2315 * that to the smart and beautiful people. I'm simple and stupid.2316 */2317 backwards =try;2318 backwards_lno = line;2319 forwards =try;2320 forwards_lno = line;2321 try_lno = line;23222323for(i =0; ; i++) {2324if(match_fragment(img, preimage, postimage,2325try, try_lno, ws_rule,2326 match_beginning, match_end))2327return try_lno;23282329 again:2330if(backwards_lno ==0&& forwards_lno == img->nr)2331break;23322333if(i &1) {2334if(backwards_lno ==0) {2335 i++;2336goto again;2337}2338 backwards_lno--;2339 backwards -= img->line[backwards_lno].len;2340try= backwards;2341 try_lno = backwards_lno;2342}else{2343if(forwards_lno == img->nr) {2344 i++;2345goto again;2346}2347 forwards += img->line[forwards_lno].len;2348 forwards_lno++;2349try= forwards;2350 try_lno = forwards_lno;2351}23522353}2354return-1;2355}23562357static voidremove_first_line(struct image *img)2358{2359 img->buf += img->line[0].len;2360 img->len -= img->line[0].len;2361 img->line++;2362 img->nr--;2363}23642365static voidremove_last_line(struct image *img)2366{2367 img->len -= img->line[--img->nr].len;2368}23692370static voidupdate_image(struct image *img,2371int applied_pos,2372struct image *preimage,2373struct image *postimage)2374{2375/*2376 * remove the copy of preimage at offset in img2377 * and replace it with postimage2378 */2379int i, nr;2380size_t remove_count, insert_count, applied_at =0;2381char*result;2382int preimage_limit;23832384/*2385 * If we are removing blank lines at the end of img,2386 * the preimage may extend beyond the end.2387 * If that is the case, we must be careful only to2388 * remove the part of the preimage that falls within2389 * the boundaries of img. Initialize preimage_limit2390 * to the number of lines in the preimage that falls2391 * within the boundaries.2392 */2393 preimage_limit = preimage->nr;2394if(preimage_limit > img->nr - applied_pos)2395 preimage_limit = img->nr - applied_pos;23962397for(i =0; i < applied_pos; i++)2398 applied_at += img->line[i].len;23992400 remove_count =0;2401for(i =0; i < preimage_limit; i++)2402 remove_count += img->line[applied_pos + i].len;2403 insert_count = postimage->len;24042405/* Adjust the contents */2406 result =xmalloc(img->len + insert_count - remove_count +1);2407memcpy(result, img->buf, applied_at);2408memcpy(result + applied_at, postimage->buf, postimage->len);2409memcpy(result + applied_at + postimage->len,2410 img->buf + (applied_at + remove_count),2411 img->len - (applied_at + remove_count));2412free(img->buf);2413 img->buf = result;2414 img->len += insert_count - remove_count;2415 result[img->len] ='\0';24162417/* Adjust the line table */2418 nr = img->nr + postimage->nr - preimage_limit;2419if(preimage_limit < postimage->nr) {2420/*2421 * NOTE: this knows that we never call remove_first_line()2422 * on anything other than pre/post image.2423 */2424 img->line =xrealloc(img->line, nr *sizeof(*img->line));2425 img->line_allocated = img->line;2426}2427if(preimage_limit != postimage->nr)2428memmove(img->line + applied_pos + postimage->nr,2429 img->line + applied_pos + preimage_limit,2430(img->nr - (applied_pos + preimage_limit)) *2431sizeof(*img->line));2432memcpy(img->line + applied_pos,2433 postimage->line,2434 postimage->nr *sizeof(*img->line));2435if(!allow_overlap)2436for(i =0; i < postimage->nr; i++)2437 img->line[applied_pos + i].flag |= LINE_PATCHED;2438 img->nr = nr;2439}24402441static intapply_one_fragment(struct image *img,struct fragment *frag,2442int inaccurate_eof,unsigned ws_rule,2443int nth_fragment)2444{2445int match_beginning, match_end;2446const char*patch = frag->patch;2447int size = frag->size;2448char*old, *oldlines;2449struct strbuf newlines;2450int new_blank_lines_at_end =0;2451int found_new_blank_lines_at_end =0;2452int hunk_linenr = frag->linenr;2453unsigned long leading, trailing;2454int pos, applied_pos;2455struct image preimage;2456struct image postimage;24572458memset(&preimage,0,sizeof(preimage));2459memset(&postimage,0,sizeof(postimage));2460 oldlines =xmalloc(size);2461strbuf_init(&newlines, size);24622463 old = oldlines;2464while(size >0) {2465char first;2466int len =linelen(patch, size);2467int plen;2468int added_blank_line =0;2469int is_blank_context =0;2470size_t start;24712472if(!len)2473break;24742475/*2476 * "plen" is how much of the line we should use for2477 * the actual patch data. Normally we just remove the2478 * first character on the line, but if the line is2479 * followed by "\ No newline", then we also remove the2480 * last one (which is the newline, of course).2481 */2482 plen = len -1;2483if(len < size && patch[len] =='\\')2484 plen--;2485 first = *patch;2486if(apply_in_reverse) {2487if(first =='-')2488 first ='+';2489else if(first =='+')2490 first ='-';2491}24922493switch(first) {2494case'\n':2495/* Newer GNU diff, empty context line */2496if(plen <0)2497/* ... followed by '\No newline'; nothing */2498break;2499*old++ ='\n';2500strbuf_addch(&newlines,'\n');2501add_line_info(&preimage,"\n",1, LINE_COMMON);2502add_line_info(&postimage,"\n",1, LINE_COMMON);2503 is_blank_context =1;2504break;2505case' ':2506if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2507ws_blank_line(patch +1, plen, ws_rule))2508 is_blank_context =1;2509case'-':2510memcpy(old, patch +1, plen);2511add_line_info(&preimage, old, plen,2512(first ==' '? LINE_COMMON :0));2513 old += plen;2514if(first =='-')2515break;2516/* Fall-through for ' ' */2517case'+':2518/* --no-add does not add new lines */2519if(first =='+'&& no_add)2520break;25212522 start = newlines.len;2523if(first !='+'||2524!whitespace_error ||2525 ws_error_action != correct_ws_error) {2526strbuf_add(&newlines, patch +1, plen);2527}2528else{2529ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2530}2531add_line_info(&postimage, newlines.buf + start, newlines.len - start,2532(first =='+'?0: LINE_COMMON));2533if(first =='+'&&2534(ws_rule & WS_BLANK_AT_EOF) &&2535ws_blank_line(patch +1, plen, ws_rule))2536 added_blank_line =1;2537break;2538case'@':case'\\':2539/* Ignore it, we already handled it */2540break;2541default:2542if(apply_verbosely)2543error("invalid start of line: '%c'", first);2544return-1;2545}2546if(added_blank_line) {2547if(!new_blank_lines_at_end)2548 found_new_blank_lines_at_end = hunk_linenr;2549 new_blank_lines_at_end++;2550}2551else if(is_blank_context)2552;2553else2554 new_blank_lines_at_end =0;2555 patch += len;2556 size -= len;2557 hunk_linenr++;2558}2559if(inaccurate_eof &&2560 old > oldlines && old[-1] =='\n'&&2561 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2562 old--;2563strbuf_setlen(&newlines, newlines.len -1);2564}25652566 leading = frag->leading;2567 trailing = frag->trailing;25682569/*2570 * A hunk to change lines at the beginning would begin with2571 * @@ -1,L +N,M @@2572 * but we need to be careful. -U0 that inserts before the second2573 * line also has this pattern.2574 *2575 * And a hunk to add to an empty file would begin with2576 * @@ -0,0 +N,M @@2577 *2578 * In other words, a hunk that is (frag->oldpos <= 1) with or2579 * without leading context must match at the beginning.2580 */2581 match_beginning = (!frag->oldpos ||2582(frag->oldpos ==1&& !unidiff_zero));25832584/*2585 * A hunk without trailing lines must match at the end.2586 * However, we simply cannot tell if a hunk must match end2587 * from the lack of trailing lines if the patch was generated2588 * with unidiff without any context.2589 */2590 match_end = !unidiff_zero && !trailing;25912592 pos = frag->newpos ? (frag->newpos -1) :0;2593 preimage.buf = oldlines;2594 preimage.len = old - oldlines;2595 postimage.buf = newlines.buf;2596 postimage.len = newlines.len;2597 preimage.line = preimage.line_allocated;2598 postimage.line = postimage.line_allocated;25992600for(;;) {26012602 applied_pos =find_pos(img, &preimage, &postimage, pos,2603 ws_rule, match_beginning, match_end);26042605if(applied_pos >=0)2606break;26072608/* Am I at my context limits? */2609if((leading <= p_context) && (trailing <= p_context))2610break;2611if(match_beginning || match_end) {2612 match_beginning = match_end =0;2613continue;2614}26152616/*2617 * Reduce the number of context lines; reduce both2618 * leading and trailing if they are equal otherwise2619 * just reduce the larger context.2620 */2621if(leading >= trailing) {2622remove_first_line(&preimage);2623remove_first_line(&postimage);2624 pos--;2625 leading--;2626}2627if(trailing > leading) {2628remove_last_line(&preimage);2629remove_last_line(&postimage);2630 trailing--;2631}2632}26332634if(applied_pos >=0) {2635if(new_blank_lines_at_end &&2636 preimage.nr + applied_pos >= img->nr &&2637(ws_rule & WS_BLANK_AT_EOF) &&2638 ws_error_action != nowarn_ws_error) {2639record_ws_error(WS_BLANK_AT_EOF,"+",1,2640 found_new_blank_lines_at_end);2641if(ws_error_action == correct_ws_error) {2642while(new_blank_lines_at_end--)2643remove_last_line(&postimage);2644}2645/*2646 * We would want to prevent write_out_results()2647 * from taking place in apply_patch() that follows2648 * the callchain led us here, which is:2649 * apply_patch->check_patch_list->check_patch->2650 * apply_data->apply_fragments->apply_one_fragment2651 */2652if(ws_error_action == die_on_ws_error)2653 apply =0;2654}26552656if(apply_verbosely && applied_pos != pos) {2657int offset = applied_pos - pos;2658if(apply_in_reverse)2659 offset =0- offset;2660fprintf(stderr,2661"Hunk #%dsucceeded at%d(offset%dlines).\n",2662 nth_fragment, applied_pos +1, offset);2663}26642665/*2666 * Warn if it was necessary to reduce the number2667 * of context lines.2668 */2669if((leading != frag->leading) ||2670(trailing != frag->trailing))2671fprintf(stderr,"Context reduced to (%ld/%ld)"2672" to apply fragment at%d\n",2673 leading, trailing, applied_pos+1);2674update_image(img, applied_pos, &preimage, &postimage);2675}else{2676if(apply_verbosely)2677error("while searching for:\n%.*s",2678(int)(old - oldlines), oldlines);2679}26802681free(oldlines);2682strbuf_release(&newlines);2683free(preimage.line_allocated);2684free(postimage.line_allocated);26852686return(applied_pos <0);2687}26882689static intapply_binary_fragment(struct image *img,struct patch *patch)2690{2691struct fragment *fragment = patch->fragments;2692unsigned long len;2693void*dst;26942695if(!fragment)2696returnerror("missing binary patch data for '%s'",2697 patch->new_name ?2698 patch->new_name :2699 patch->old_name);27002701/* Binary patch is irreversible without the optional second hunk */2702if(apply_in_reverse) {2703if(!fragment->next)2704returnerror("cannot reverse-apply a binary patch "2705"without the reverse hunk to '%s'",2706 patch->new_name2707? patch->new_name : patch->old_name);2708 fragment = fragment->next;2709}2710switch(fragment->binary_patch_method) {2711case BINARY_DELTA_DEFLATED:2712 dst =patch_delta(img->buf, img->len, fragment->patch,2713 fragment->size, &len);2714if(!dst)2715return-1;2716clear_image(img);2717 img->buf = dst;2718 img->len = len;2719return0;2720case BINARY_LITERAL_DEFLATED:2721clear_image(img);2722 img->len = fragment->size;2723 img->buf =xmalloc(img->len+1);2724memcpy(img->buf, fragment->patch, img->len);2725 img->buf[img->len] ='\0';2726return0;2727}2728return-1;2729}27302731static intapply_binary(struct image *img,struct patch *patch)2732{2733const char*name = patch->old_name ? patch->old_name : patch->new_name;2734unsigned char sha1[20];27352736/*2737 * For safety, we require patch index line to contain2738 * full 40-byte textual SHA1 for old and new, at least for now.2739 */2740if(strlen(patch->old_sha1_prefix) !=40||2741strlen(patch->new_sha1_prefix) !=40||2742get_sha1_hex(patch->old_sha1_prefix, sha1) ||2743get_sha1_hex(patch->new_sha1_prefix, sha1))2744returnerror("cannot apply binary patch to '%s' "2745"without full index line", name);27462747if(patch->old_name) {2748/*2749 * See if the old one matches what the patch2750 * applies to.2751 */2752hash_sha1_file(img->buf, img->len, blob_type, sha1);2753if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2754returnerror("the patch applies to '%s' (%s), "2755"which does not match the "2756"current contents.",2757 name,sha1_to_hex(sha1));2758}2759else{2760/* Otherwise, the old one must be empty. */2761if(img->len)2762returnerror("the patch applies to an empty "2763"'%s' but it is not empty", name);2764}27652766get_sha1_hex(patch->new_sha1_prefix, sha1);2767if(is_null_sha1(sha1)) {2768clear_image(img);2769return0;/* deletion patch */2770}27712772if(has_sha1_file(sha1)) {2773/* We already have the postimage */2774enum object_type type;2775unsigned long size;2776char*result;27772778 result =read_sha1_file(sha1, &type, &size);2779if(!result)2780returnerror("the necessary postimage%sfor "2781"'%s' cannot be read",2782 patch->new_sha1_prefix, name);2783clear_image(img);2784 img->buf = result;2785 img->len = size;2786}else{2787/*2788 * We have verified buf matches the preimage;2789 * apply the patch data to it, which is stored2790 * in the patch->fragments->{patch,size}.2791 */2792if(apply_binary_fragment(img, patch))2793returnerror("binary patch does not apply to '%s'",2794 name);27952796/* verify that the result matches */2797hash_sha1_file(img->buf, img->len, blob_type, sha1);2798if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2799returnerror("binary patch to '%s' creates incorrect result (expecting%s, got%s)",2800 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2801}28022803return0;2804}28052806static intapply_fragments(struct image *img,struct patch *patch)2807{2808struct fragment *frag = patch->fragments;2809const char*name = patch->old_name ? patch->old_name : patch->new_name;2810unsigned ws_rule = patch->ws_rule;2811unsigned inaccurate_eof = patch->inaccurate_eof;2812int nth =0;28132814if(patch->is_binary)2815returnapply_binary(img, patch);28162817while(frag) {2818 nth++;2819if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {2820error("patch failed:%s:%ld", name, frag->oldpos);2821if(!apply_with_reject)2822return-1;2823 frag->rejected =1;2824}2825 frag = frag->next;2826}2827return0;2828}28292830static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2831{2832if(!ce)2833return0;28342835if(S_ISGITLINK(ce->ce_mode)) {2836strbuf_grow(buf,100);2837strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2838}else{2839enum object_type type;2840unsigned long sz;2841char*result;28422843 result =read_sha1_file(ce->sha1, &type, &sz);2844if(!result)2845return-1;2846/* XXX read_sha1_file NUL-terminates */2847strbuf_attach(buf, result, sz, sz +1);2848}2849return0;2850}28512852static struct patch *in_fn_table(const char*name)2853{2854struct string_list_item *item;28552856if(name == NULL)2857return NULL;28582859 item =string_list_lookup(&fn_table, name);2860if(item != NULL)2861return(struct patch *)item->util;28622863return NULL;2864}28652866/*2867 * item->util in the filename table records the status of the path.2868 * Usually it points at a patch (whose result records the contents2869 * of it after applying it), but it could be PATH_WAS_DELETED for a2870 * path that a previously applied patch has already removed.2871 */2872#define PATH_TO_BE_DELETED ((struct patch *) -2)2873#define PATH_WAS_DELETED ((struct patch *) -1)28742875static intto_be_deleted(struct patch *patch)2876{2877return patch == PATH_TO_BE_DELETED;2878}28792880static intwas_deleted(struct patch *patch)2881{2882return patch == PATH_WAS_DELETED;2883}28842885static voidadd_to_fn_table(struct patch *patch)2886{2887struct string_list_item *item;28882889/*2890 * Always add new_name unless patch is a deletion2891 * This should cover the cases for normal diffs,2892 * file creations and copies2893 */2894if(patch->new_name != NULL) {2895 item =string_list_insert(&fn_table, patch->new_name);2896 item->util = patch;2897}28982899/*2900 * store a failure on rename/deletion cases because2901 * later chunks shouldn't patch old names2902 */2903if((patch->new_name == NULL) || (patch->is_rename)) {2904 item =string_list_insert(&fn_table, patch->old_name);2905 item->util = PATH_WAS_DELETED;2906}2907}29082909static voidprepare_fn_table(struct patch *patch)2910{2911/*2912 * store information about incoming file deletion2913 */2914while(patch) {2915if((patch->new_name == NULL) || (patch->is_rename)) {2916struct string_list_item *item;2917 item =string_list_insert(&fn_table, patch->old_name);2918 item->util = PATH_TO_BE_DELETED;2919}2920 patch = patch->next;2921}2922}29232924static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)2925{2926struct strbuf buf = STRBUF_INIT;2927struct image image;2928size_t len;2929char*img;2930struct patch *tpatch;29312932if(!(patch->is_copy || patch->is_rename) &&2933(tpatch =in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {2934if(was_deleted(tpatch)) {2935returnerror("patch%shas been renamed/deleted",2936 patch->old_name);2937}2938/* We have a patched copy in memory use that */2939strbuf_add(&buf, tpatch->result, tpatch->resultsize);2940}else if(cached) {2941if(read_file_or_gitlink(ce, &buf))2942returnerror("read of%sfailed", patch->old_name);2943}else if(patch->old_name) {2944if(S_ISGITLINK(patch->old_mode)) {2945if(ce) {2946read_file_or_gitlink(ce, &buf);2947}else{2948/*2949 * There is no way to apply subproject2950 * patch without looking at the index.2951 */2952 patch->fragments = NULL;2953}2954}else{2955if(read_old_data(st, patch->old_name, &buf))2956returnerror("read of%sfailed", patch->old_name);2957}2958}29592960 img =strbuf_detach(&buf, &len);2961prepare_image(&image, img, len, !patch->is_binary);29622963if(apply_fragments(&image, patch) <0)2964return-1;/* note with --reject this succeeds. */2965 patch->result = image.buf;2966 patch->resultsize = image.len;2967add_to_fn_table(patch);2968free(image.line_allocated);29692970if(0< patch->is_delete && patch->resultsize)2971returnerror("removal patch leaves file contents");29722973return0;2974}29752976static intcheck_to_create_blob(const char*new_name,int ok_if_exists)2977{2978struct stat nst;2979if(!lstat(new_name, &nst)) {2980if(S_ISDIR(nst.st_mode) || ok_if_exists)2981return0;2982/*2983 * A leading component of new_name might be a symlink2984 * that is going to be removed with this patch, but2985 * still pointing at somewhere that has the path.2986 * In such a case, path "new_name" does not exist as2987 * far as git is concerned.2988 */2989if(has_symlink_leading_path(new_name,strlen(new_name)))2990return0;29912992returnerror("%s: already exists in working directory", new_name);2993}2994else if((errno != ENOENT) && (errno != ENOTDIR))2995returnerror("%s:%s", new_name,strerror(errno));2996return0;2997}29982999static intverify_index_match(struct cache_entry *ce,struct stat *st)3000{3001if(S_ISGITLINK(ce->ce_mode)) {3002if(!S_ISDIR(st->st_mode))3003return-1;3004return0;3005}3006returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3007}30083009static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)3010{3011const char*old_name = patch->old_name;3012struct patch *tpatch = NULL;3013int stat_ret =0;3014unsigned st_mode =0;30153016/*3017 * Make sure that we do not have local modifications from the3018 * index when we are looking at the index. Also make sure3019 * we have the preimage file to be patched in the work tree,3020 * unless --cached, which tells git to apply only in the index.3021 */3022if(!old_name)3023return0;30243025assert(patch->is_new <=0);30263027if(!(patch->is_copy || patch->is_rename) &&3028(tpatch =in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {3029if(was_deleted(tpatch))3030returnerror("%s: has been deleted/renamed", old_name);3031 st_mode = tpatch->new_mode;3032}else if(!cached) {3033 stat_ret =lstat(old_name, st);3034if(stat_ret && errno != ENOENT)3035returnerror("%s:%s", old_name,strerror(errno));3036}30373038if(to_be_deleted(tpatch))3039 tpatch = NULL;30403041if(check_index && !tpatch) {3042int pos =cache_name_pos(old_name,strlen(old_name));3043if(pos <0) {3044if(patch->is_new <0)3045goto is_new;3046returnerror("%s: does not exist in index", old_name);3047}3048*ce = active_cache[pos];3049if(stat_ret <0) {3050struct checkout costate;3051/* checkout */3052memset(&costate,0,sizeof(costate));3053 costate.base_dir ="";3054 costate.refresh_cache =1;3055if(checkout_entry(*ce, &costate, NULL) ||3056lstat(old_name, st))3057return-1;3058}3059if(!cached &&verify_index_match(*ce, st))3060returnerror("%s: does not match index", old_name);3061if(cached)3062 st_mode = (*ce)->ce_mode;3063}else if(stat_ret <0) {3064if(patch->is_new <0)3065goto is_new;3066returnerror("%s:%s", old_name,strerror(errno));3067}30683069if(!cached && !tpatch)3070 st_mode =ce_mode_from_stat(*ce, st->st_mode);30713072if(patch->is_new <0)3073 patch->is_new =0;3074if(!patch->old_mode)3075 patch->old_mode = st_mode;3076if((st_mode ^ patch->old_mode) & S_IFMT)3077returnerror("%s: wrong type", old_name);3078if(st_mode != patch->old_mode)3079warning("%shas type%o, expected%o",3080 old_name, st_mode, patch->old_mode);3081if(!patch->new_mode && !patch->is_delete)3082 patch->new_mode = st_mode;3083return0;30843085 is_new:3086 patch->is_new =1;3087 patch->is_delete =0;3088 patch->old_name = NULL;3089return0;3090}30913092static intcheck_patch(struct patch *patch)3093{3094struct stat st;3095const char*old_name = patch->old_name;3096const char*new_name = patch->new_name;3097const char*name = old_name ? old_name : new_name;3098struct cache_entry *ce = NULL;3099struct patch *tpatch;3100int ok_if_exists;3101int status;31023103 patch->rejected =1;/* we will drop this after we succeed */31043105 status =check_preimage(patch, &ce, &st);3106if(status)3107return status;3108 old_name = patch->old_name;31093110if((tpatch =in_fn_table(new_name)) &&3111(was_deleted(tpatch) ||to_be_deleted(tpatch)))3112/*3113 * A type-change diff is always split into a patch to3114 * delete old, immediately followed by a patch to3115 * create new (see diff.c::run_diff()); in such a case3116 * it is Ok that the entry to be deleted by the3117 * previous patch is still in the working tree and in3118 * the index.3119 */3120 ok_if_exists =1;3121else3122 ok_if_exists =0;31233124if(new_name &&3125((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {3126if(check_index &&3127cache_name_pos(new_name,strlen(new_name)) >=0&&3128!ok_if_exists)3129returnerror("%s: already exists in index", new_name);3130if(!cached) {3131int err =check_to_create_blob(new_name, ok_if_exists);3132if(err)3133return err;3134}3135if(!patch->new_mode) {3136if(0< patch->is_new)3137 patch->new_mode = S_IFREG |0644;3138else3139 patch->new_mode = patch->old_mode;3140}3141}31423143if(new_name && old_name) {3144int same = !strcmp(old_name, new_name);3145if(!patch->new_mode)3146 patch->new_mode = patch->old_mode;3147if((patch->old_mode ^ patch->new_mode) & S_IFMT)3148returnerror("new mode (%o) of%sdoes not match old mode (%o)%s%s",3149 patch->new_mode, new_name, patch->old_mode,3150 same ?"":" of ", same ?"": old_name);3151}31523153if(apply_data(patch, &st, ce) <0)3154returnerror("%s: patch does not apply", name);3155 patch->rejected =0;3156return0;3157}31583159static intcheck_patch_list(struct patch *patch)3160{3161int err =0;31623163prepare_fn_table(patch);3164while(patch) {3165if(apply_verbosely)3166say_patch_name(stderr,3167"Checking patch ", patch,"...\n");3168 err |=check_patch(patch);3169 patch = patch->next;3170}3171return err;3172}31733174/* This function tries to read the sha1 from the current index */3175static intget_current_sha1(const char*path,unsigned char*sha1)3176{3177int pos;31783179if(read_cache() <0)3180return-1;3181 pos =cache_name_pos(path,strlen(path));3182if(pos <0)3183return-1;3184hashcpy(sha1, active_cache[pos]->sha1);3185return0;3186}31873188/* Build an index that contains the just the files needed for a 3way merge */3189static voidbuild_fake_ancestor(struct patch *list,const char*filename)3190{3191struct patch *patch;3192struct index_state result = { NULL };3193int fd;31943195/* Once we start supporting the reverse patch, it may be3196 * worth showing the new sha1 prefix, but until then...3197 */3198for(patch = list; patch; patch = patch->next) {3199const unsigned char*sha1_ptr;3200unsigned char sha1[20];3201struct cache_entry *ce;3202const char*name;32033204 name = patch->old_name ? patch->old_name : patch->new_name;3205if(0< patch->is_new)3206continue;3207else if(get_sha1(patch->old_sha1_prefix, sha1))3208/* git diff has no index line for mode/type changes */3209if(!patch->lines_added && !patch->lines_deleted) {3210if(get_current_sha1(patch->old_name, sha1))3211die("mode change for%s, which is not "3212"in current HEAD", name);3213 sha1_ptr = sha1;3214}else3215die("sha1 information is lacking or useless "3216"(%s).", name);3217else3218 sha1_ptr = sha1;32193220 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);3221if(!ce)3222die("make_cache_entry failed for path '%s'", name);3223if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3224die("Could not add%sto temporary index", name);3225}32263227 fd =open(filename, O_WRONLY | O_CREAT,0666);3228if(fd <0||write_index(&result, fd) ||close(fd))3229die("Could not write temporary index to%s", filename);32303231discard_index(&result);3232}32333234static voidstat_patch_list(struct patch *patch)3235{3236int files, adds, dels;32373238for(files = adds = dels =0; patch ; patch = patch->next) {3239 files++;3240 adds += patch->lines_added;3241 dels += patch->lines_deleted;3242show_stats(patch);3243}32443245print_stat_summary(stdout, files, adds, dels);3246}32473248static voidnumstat_patch_list(struct patch *patch)3249{3250for( ; patch; patch = patch->next) {3251const char*name;3252 name = patch->new_name ? patch->new_name : patch->old_name;3253if(patch->is_binary)3254printf("-\t-\t");3255else3256printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3257write_name_quoted(name, stdout, line_termination);3258}3259}32603261static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3262{3263if(mode)3264printf("%smode%06o%s\n", newdelete, mode, name);3265else3266printf("%s %s\n", newdelete, name);3267}32683269static voidshow_mode_change(struct patch *p,int show_name)3270{3271if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3272if(show_name)3273printf(" mode change%06o =>%06o%s\n",3274 p->old_mode, p->new_mode, p->new_name);3275else3276printf(" mode change%06o =>%06o\n",3277 p->old_mode, p->new_mode);3278}3279}32803281static voidshow_rename_copy(struct patch *p)3282{3283const char*renamecopy = p->is_rename ?"rename":"copy";3284const char*old, *new;32853286/* Find common prefix */3287 old = p->old_name;3288new= p->new_name;3289while(1) {3290const char*slash_old, *slash_new;3291 slash_old =strchr(old,'/');3292 slash_new =strchr(new,'/');3293if(!slash_old ||3294!slash_new ||3295 slash_old - old != slash_new -new||3296memcmp(old,new, slash_new -new))3297break;3298 old = slash_old +1;3299new= slash_new +1;3300}3301/* p->old_name thru old is the common prefix, and old and new3302 * through the end of names are renames3303 */3304if(old != p->old_name)3305printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,3306(int)(old - p->old_name), p->old_name,3307 old,new, p->score);3308else3309printf("%s %s=>%s(%d%%)\n", renamecopy,3310 p->old_name, p->new_name, p->score);3311show_mode_change(p,0);3312}33133314static voidsummary_patch_list(struct patch *patch)3315{3316struct patch *p;33173318for(p = patch; p; p = p->next) {3319if(p->is_new)3320show_file_mode_name("create", p->new_mode, p->new_name);3321else if(p->is_delete)3322show_file_mode_name("delete", p->old_mode, p->old_name);3323else{3324if(p->is_rename || p->is_copy)3325show_rename_copy(p);3326else{3327if(p->score) {3328printf(" rewrite%s(%d%%)\n",3329 p->new_name, p->score);3330show_mode_change(p,0);3331}3332else3333show_mode_change(p,1);3334}3335}3336}3337}33383339static voidpatch_stats(struct patch *patch)3340{3341int lines = patch->lines_added + patch->lines_deleted;33423343if(lines > max_change)3344 max_change = lines;3345if(patch->old_name) {3346int len =quote_c_style(patch->old_name, NULL, NULL,0);3347if(!len)3348 len =strlen(patch->old_name);3349if(len > max_len)3350 max_len = len;3351}3352if(patch->new_name) {3353int len =quote_c_style(patch->new_name, NULL, NULL,0);3354if(!len)3355 len =strlen(patch->new_name);3356if(len > max_len)3357 max_len = len;3358}3359}33603361static voidremove_file(struct patch *patch,int rmdir_empty)3362{3363if(update_index) {3364if(remove_file_from_cache(patch->old_name) <0)3365die("unable to remove%sfrom index", patch->old_name);3366}3367if(!cached) {3368if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {3369remove_path(patch->old_name);3370}3371}3372}33733374static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)3375{3376struct stat st;3377struct cache_entry *ce;3378int namelen =strlen(path);3379unsigned ce_size =cache_entry_size(namelen);33803381if(!update_index)3382return;33833384 ce =xcalloc(1, ce_size);3385memcpy(ce->name, path, namelen);3386 ce->ce_mode =create_ce_mode(mode);3387 ce->ce_flags = namelen;3388if(S_ISGITLINK(mode)) {3389const char*s = buf;33903391if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))3392die("corrupt patch for subproject%s", path);3393}else{3394if(!cached) {3395if(lstat(path, &st) <0)3396die_errno("unable to stat newly created file '%s'",3397 path);3398fill_stat_cache_info(ce, &st);3399}3400if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)3401die("unable to create backing store for newly created file%s", path);3402}3403if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3404die("unable to add cache entry for%s", path);3405}34063407static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)3408{3409int fd;3410struct strbuf nbuf = STRBUF_INIT;34113412if(S_ISGITLINK(mode)) {3413struct stat st;3414if(!lstat(path, &st) &&S_ISDIR(st.st_mode))3415return0;3416returnmkdir(path,0777);3417}34183419if(has_symlinks &&S_ISLNK(mode))3420/* Although buf:size is counted string, it also is NUL3421 * terminated.3422 */3423returnsymlink(buf, path);34243425 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);3426if(fd <0)3427return-1;34283429if(convert_to_working_tree(path, buf, size, &nbuf)) {3430 size = nbuf.len;3431 buf = nbuf.buf;3432}3433write_or_die(fd, buf, size);3434strbuf_release(&nbuf);34353436if(close(fd) <0)3437die_errno("closing file '%s'", path);3438return0;3439}34403441/*3442 * We optimistically assume that the directories exist,3443 * which is true 99% of the time anyway. If they don't,3444 * we create them and try again.3445 */3446static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)3447{3448if(cached)3449return;3450if(!try_create_file(path, mode, buf, size))3451return;34523453if(errno == ENOENT) {3454if(safe_create_leading_directories(path))3455return;3456if(!try_create_file(path, mode, buf, size))3457return;3458}34593460if(errno == EEXIST || errno == EACCES) {3461/* We may be trying to create a file where a directory3462 * used to be.3463 */3464struct stat st;3465if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))3466 errno = EEXIST;3467}34683469if(errno == EEXIST) {3470unsigned int nr =getpid();34713472for(;;) {3473char newpath[PATH_MAX];3474mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);3475if(!try_create_file(newpath, mode, buf, size)) {3476if(!rename(newpath, path))3477return;3478unlink_or_warn(newpath);3479break;3480}3481if(errno != EEXIST)3482break;3483++nr;3484}3485}3486die_errno("unable to write file '%s' mode%o", path, mode);3487}34883489static voidcreate_file(struct patch *patch)3490{3491char*path = patch->new_name;3492unsigned mode = patch->new_mode;3493unsigned long size = patch->resultsize;3494char*buf = patch->result;34953496if(!mode)3497 mode = S_IFREG |0644;3498create_one_file(path, mode, buf, size);3499add_index_file(path, mode, buf, size);3500}35013502/* phase zero is to remove, phase one is to create */3503static voidwrite_out_one_result(struct patch *patch,int phase)3504{3505if(patch->is_delete >0) {3506if(phase ==0)3507remove_file(patch,1);3508return;3509}3510if(patch->is_new >0|| patch->is_copy) {3511if(phase ==1)3512create_file(patch);3513return;3514}3515/*3516 * Rename or modification boils down to the same3517 * thing: remove the old, write the new3518 */3519if(phase ==0)3520remove_file(patch, patch->is_rename);3521if(phase ==1)3522create_file(patch);3523}35243525static intwrite_out_one_reject(struct patch *patch)3526{3527FILE*rej;3528char namebuf[PATH_MAX];3529struct fragment *frag;3530int cnt =0;35313532for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {3533if(!frag->rejected)3534continue;3535 cnt++;3536}35373538if(!cnt) {3539if(apply_verbosely)3540say_patch_name(stderr,3541"Applied patch ", patch," cleanly.\n");3542return0;3543}35443545/* This should not happen, because a removal patch that leaves3546 * contents are marked "rejected" at the patch level.3547 */3548if(!patch->new_name)3549die("internal error");35503551/* Say this even without --verbose */3552say_patch_name(stderr,"Applying patch ", patch," with");3553fprintf(stderr,"%drejects...\n", cnt);35543555 cnt =strlen(patch->new_name);3556if(ARRAY_SIZE(namebuf) <= cnt +5) {3557 cnt =ARRAY_SIZE(namebuf) -5;3558warning("truncating .rej filename to %.*s.rej",3559 cnt -1, patch->new_name);3560}3561memcpy(namebuf, patch->new_name, cnt);3562memcpy(namebuf + cnt,".rej",5);35633564 rej =fopen(namebuf,"w");3565if(!rej)3566returnerror("cannot open%s:%s", namebuf,strerror(errno));35673568/* Normal git tools never deal with .rej, so do not pretend3569 * this is a git patch by saying --git nor give extended3570 * headers. While at it, maybe please "kompare" that wants3571 * the trailing TAB and some garbage at the end of line ;-).3572 */3573fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",3574 patch->new_name, patch->new_name);3575for(cnt =1, frag = patch->fragments;3576 frag;3577 cnt++, frag = frag->next) {3578if(!frag->rejected) {3579fprintf(stderr,"Hunk #%dapplied cleanly.\n", cnt);3580continue;3581}3582fprintf(stderr,"Rejected hunk #%d.\n", cnt);3583fprintf(rej,"%.*s", frag->size, frag->patch);3584if(frag->patch[frag->size-1] !='\n')3585fputc('\n', rej);3586}3587fclose(rej);3588return-1;3589}35903591static intwrite_out_results(struct patch *list)3592{3593int phase;3594int errs =0;3595struct patch *l;35963597for(phase =0; phase <2; phase++) {3598 l = list;3599while(l) {3600if(l->rejected)3601 errs =1;3602else{3603write_out_one_result(l, phase);3604if(phase ==1&&write_out_one_reject(l))3605 errs =1;3606}3607 l = l->next;3608}3609}3610return errs;3611}36123613static struct lock_file lock_file;36143615static struct string_list limit_by_name;3616static int has_include;3617static voidadd_name_limit(const char*name,int exclude)3618{3619struct string_list_item *it;36203621 it =string_list_append(&limit_by_name, name);3622 it->util = exclude ? NULL : (void*)1;3623}36243625static intuse_patch(struct patch *p)3626{3627const char*pathname = p->new_name ? p->new_name : p->old_name;3628int i;36293630/* Paths outside are not touched regardless of "--include" */3631if(0< prefix_length) {3632int pathlen =strlen(pathname);3633if(pathlen <= prefix_length ||3634memcmp(prefix, pathname, prefix_length))3635return0;3636}36373638/* See if it matches any of exclude/include rule */3639for(i =0; i < limit_by_name.nr; i++) {3640struct string_list_item *it = &limit_by_name.items[i];3641if(!fnmatch(it->string, pathname,0))3642return(it->util != NULL);3643}36443645/*3646 * If we had any include, a path that does not match any rule is3647 * not used. Otherwise, we saw bunch of exclude rules (or none)3648 * and such a path is used.3649 */3650return!has_include;3651}365236533654static voidprefix_one(char**name)3655{3656char*old_name = *name;3657if(!old_name)3658return;3659*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3660free(old_name);3661}36623663static voidprefix_patches(struct patch *p)3664{3665if(!prefix || p->is_toplevel_relative)3666return;3667for( ; p; p = p->next) {3668if(p->new_name == p->old_name) {3669char*prefixed = p->new_name;3670prefix_one(&prefixed);3671 p->new_name = p->old_name = prefixed;3672}3673else{3674prefix_one(&p->new_name);3675prefix_one(&p->old_name);3676}3677}3678}36793680#define INACCURATE_EOF (1<<0)3681#define RECOUNT (1<<1)36823683static intapply_patch(int fd,const char*filename,int options)3684{3685size_t offset;3686struct strbuf buf = STRBUF_INIT;3687struct patch *list = NULL, **listp = &list;3688int skipped_patch =0;36893690/* FIXME - memory leak when using multiple patch files as inputs */3691memset(&fn_table,0,sizeof(struct string_list));3692 patch_input_file = filename;3693read_patch_file(&buf, fd);3694 offset =0;3695while(offset < buf.len) {3696struct patch *patch;3697int nr;36983699 patch =xcalloc(1,sizeof(*patch));3700 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3701 patch->recount = !!(options & RECOUNT);3702 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3703if(nr <0)3704break;3705if(apply_in_reverse)3706reverse_patches(patch);3707if(prefix)3708prefix_patches(patch);3709if(use_patch(patch)) {3710patch_stats(patch);3711*listp = patch;3712 listp = &patch->next;3713}3714else{3715/* perhaps free it a bit better? */3716free(patch);3717 skipped_patch++;3718}3719 offset += nr;3720}37213722if(!list && !skipped_patch)3723die("unrecognized input");37243725if(whitespace_error && (ws_error_action == die_on_ws_error))3726 apply =0;37273728 update_index = check_index && apply;3729if(update_index && newfd <0)3730 newfd =hold_locked_index(&lock_file,1);37313732if(check_index) {3733if(read_cache() <0)3734die("unable to read index file");3735}37363737if((check || apply) &&3738check_patch_list(list) <0&&3739!apply_with_reject)3740exit(1);37413742if(apply &&write_out_results(list))3743exit(1);37443745if(fake_ancestor)3746build_fake_ancestor(list, fake_ancestor);37473748if(diffstat)3749stat_patch_list(list);37503751if(numstat)3752numstat_patch_list(list);37533754if(summary)3755summary_patch_list(list);37563757strbuf_release(&buf);3758return0;3759}37603761static intgit_apply_config(const char*var,const char*value,void*cb)3762{3763if(!strcmp(var,"apply.whitespace"))3764returngit_config_string(&apply_default_whitespace, var, value);3765else if(!strcmp(var,"apply.ignorewhitespace"))3766returngit_config_string(&apply_default_ignorewhitespace, var, value);3767returngit_default_config(var, value, cb);3768}37693770static intoption_parse_exclude(const struct option *opt,3771const char*arg,int unset)3772{3773add_name_limit(arg,1);3774return0;3775}37763777static intoption_parse_include(const struct option *opt,3778const char*arg,int unset)3779{3780add_name_limit(arg,0);3781 has_include =1;3782return0;3783}37843785static intoption_parse_p(const struct option *opt,3786const char*arg,int unset)3787{3788 p_value =atoi(arg);3789 p_value_known =1;3790return0;3791}37923793static intoption_parse_z(const struct option *opt,3794const char*arg,int unset)3795{3796if(unset)3797 line_termination ='\n';3798else3799 line_termination =0;3800return0;3801}38023803static intoption_parse_space_change(const struct option *opt,3804const char*arg,int unset)3805{3806if(unset)3807 ws_ignore_action = ignore_ws_none;3808else3809 ws_ignore_action = ignore_ws_change;3810return0;3811}38123813static intoption_parse_whitespace(const struct option *opt,3814const char*arg,int unset)3815{3816const char**whitespace_option = opt->value;38173818*whitespace_option = arg;3819parse_whitespace_option(arg);3820return0;3821}38223823static intoption_parse_directory(const struct option *opt,3824const char*arg,int unset)3825{3826 root_len =strlen(arg);3827if(root_len && arg[root_len -1] !='/') {3828char*new_root;3829 root = new_root =xmalloc(root_len +2);3830strcpy(new_root, arg);3831strcpy(new_root + root_len++,"/");3832}else3833 root = arg;3834return0;3835}38363837intcmd_apply(int argc,const char**argv,const char*prefix_)3838{3839int i;3840int errs =0;3841int is_not_gitdir = !startup_info->have_repository;3842int force_apply =0;38433844const char*whitespace_option = NULL;38453846struct option builtin_apply_options[] = {3847{ OPTION_CALLBACK,0,"exclude", NULL,"path",3848"don't apply changes matching the given path",38490, option_parse_exclude },3850{ OPTION_CALLBACK,0,"include", NULL,"path",3851"apply changes matching the given path",38520, option_parse_include },3853{ OPTION_CALLBACK,'p', NULL, NULL,"num",3854"remove <num> leading slashes from traditional diff paths",38550, option_parse_p },3856OPT_BOOLEAN(0,"no-add", &no_add,3857"ignore additions made by the patch"),3858OPT_BOOLEAN(0,"stat", &diffstat,3859"instead of applying the patch, output diffstat for the input"),3860OPT_NOOP_NOARG(0,"allow-binary-replacement"),3861OPT_NOOP_NOARG(0,"binary"),3862OPT_BOOLEAN(0,"numstat", &numstat,3863"shows number of added and deleted lines in decimal notation"),3864OPT_BOOLEAN(0,"summary", &summary,3865"instead of applying the patch, output a summary for the input"),3866OPT_BOOLEAN(0,"check", &check,3867"instead of applying the patch, see if the patch is applicable"),3868OPT_BOOLEAN(0,"index", &check_index,3869"make sure the patch is applicable to the current index"),3870OPT_BOOLEAN(0,"cached", &cached,3871"apply a patch without touching the working tree"),3872OPT_BOOLEAN(0,"apply", &force_apply,3873"also apply the patch (use with --stat/--summary/--check)"),3874OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,3875"build a temporary index based on embedded index information"),3876{ OPTION_CALLBACK,'z', NULL, NULL, NULL,3877"paths are separated with NUL character",3878 PARSE_OPT_NOARG, option_parse_z },3879OPT_INTEGER('C', NULL, &p_context,3880"ensure at least <n> lines of context match"),3881{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,"action",3882"detect new or modified lines that have whitespace errors",38830, option_parse_whitespace },3884{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,3885"ignore changes in whitespace when finding context",3886 PARSE_OPT_NOARG, option_parse_space_change },3887{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,3888"ignore changes in whitespace when finding context",3889 PARSE_OPT_NOARG, option_parse_space_change },3890OPT_BOOLEAN('R',"reverse", &apply_in_reverse,3891"apply the patch in reverse"),3892OPT_BOOLEAN(0,"unidiff-zero", &unidiff_zero,3893"don't expect at least one line of context"),3894OPT_BOOLEAN(0,"reject", &apply_with_reject,3895"leave the rejected hunks in corresponding *.rej files"),3896OPT_BOOLEAN(0,"allow-overlap", &allow_overlap,3897"allow overlapping hunks"),3898OPT__VERBOSE(&apply_verbosely,"be verbose"),3899OPT_BIT(0,"inaccurate-eof", &options,3900"tolerate incorrectly detected missing new-line at the end of file",3901 INACCURATE_EOF),3902OPT_BIT(0,"recount", &options,3903"do not trust the line counts in the hunk headers",3904 RECOUNT),3905{ OPTION_CALLBACK,0,"directory", NULL,"root",3906"prepend <root> to all filenames",39070, option_parse_directory },3908OPT_END()3909};39103911 prefix = prefix_;3912 prefix_length = prefix ?strlen(prefix) :0;3913git_config(git_apply_config, NULL);3914if(apply_default_whitespace)3915parse_whitespace_option(apply_default_whitespace);3916if(apply_default_ignorewhitespace)3917parse_ignorewhitespace_option(apply_default_ignorewhitespace);39183919 argc =parse_options(argc, argv, prefix, builtin_apply_options,3920 apply_usage,0);39213922if(apply_with_reject)3923 apply = apply_verbosely =1;3924if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))3925 apply =0;3926if(check_index && is_not_gitdir)3927die("--index outside a repository");3928if(cached) {3929if(is_not_gitdir)3930die("--cached outside a repository");3931 check_index =1;3932}3933for(i =0; i < argc; i++) {3934const char*arg = argv[i];3935int fd;39363937if(!strcmp(arg,"-")) {3938 errs |=apply_patch(0,"<stdin>", options);3939 read_stdin =0;3940continue;3941}else if(0< prefix_length)3942 arg =prefix_filename(prefix, prefix_length, arg);39433944 fd =open(arg, O_RDONLY);3945if(fd <0)3946die_errno("can't open patch '%s'", arg);3947 read_stdin =0;3948set_default_whitespace_mode(whitespace_option);3949 errs |=apply_patch(fd, arg, options);3950close(fd);3951}3952set_default_whitespace_mode(whitespace_option);3953if(read_stdin)3954 errs |=apply_patch(0,"<stdin>", options);3955if(whitespace_error) {3956if(squelch_whitespace_errors &&3957 squelch_whitespace_errors < whitespace_error) {3958int squelched =3959 whitespace_error - squelch_whitespace_errors;3960warning("squelched%d"3961"whitespace error%s",3962 squelched,3963 squelched ==1?"":"s");3964}3965if(ws_error_action == die_on_ws_error)3966die("%dline%sadd%swhitespace errors.",3967 whitespace_error,3968 whitespace_error ==1?"":"s",3969 whitespace_error ==1?"s":"");3970if(applied_after_fixing_ws && apply)3971warning("%dline%sapplied after"3972" fixing whitespace errors.",3973 applied_after_fixing_ws,3974 applied_after_fixing_ws ==1?"":"s");3975else if(whitespace_error)3976warning("%dline%sadd%swhitespace errors.",3977 whitespace_error,3978 whitespace_error ==1?"":"s",3979 whitespace_error ==1?"s":"");3980}39813982if(update_index) {3983if(write_cache(newfd, active_cache, active_nr) ||3984commit_locked_index(&lock_file))3985die("Unable to write new index file");3986}39873988return!!errs;3989}