1/* 2 * apply.c 3 * 4 * Copyright (C) Linus Torvalds, 2005 5 * 6 * This applies patches on top of some (arbitrary) version of the SCM. 7 * 8 */ 9#include"cache.h" 10#include"cache-tree.h" 11#include"quote.h" 12#include"blob.h" 13#include"delta.h" 14#include"builtin.h" 15#include"string-list.h" 16#include"dir.h" 17#include"parse-options.h" 18 19/* 20 * --check turns on checking that the working tree matches the 21 * files that are being modified, but doesn't apply the patch 22 * --stat does just a diffstat, and doesn't actually apply 23 * --numstat does numeric diffstat, and doesn't actually apply 24 * --index-info shows the old and new index info for paths if available. 25 * --index updates the cache as well. 26 * --cached updates only the cache without ever touching the working tree. 27 */ 28static const char*prefix; 29static int prefix_length = -1; 30static int newfd = -1; 31 32static int unidiff_zero; 33static int p_value =1; 34static int p_value_known; 35static int check_index; 36static int update_index; 37static int cached; 38static int diffstat; 39static int numstat; 40static int summary; 41static int check; 42static int apply =1; 43static int apply_in_reverse; 44static int apply_with_reject; 45static int apply_verbosely; 46static int no_add; 47static const char*fake_ancestor; 48static int line_termination ='\n'; 49static unsigned int p_context = UINT_MAX; 50static const char*const apply_usage[] = { 51"git apply [options] [<patch>...]", 52 NULL 53}; 54 55static enum ws_error_action { 56 nowarn_ws_error, 57 warn_on_ws_error, 58 die_on_ws_error, 59 correct_ws_error 60} ws_error_action = warn_on_ws_error; 61static int whitespace_error; 62static int squelch_whitespace_errors =5; 63static int applied_after_fixing_ws; 64 65static enum ws_ignore { 66 ignore_ws_none, 67 ignore_ws_change 68} ws_ignore_action = ignore_ws_none; 69 70 71static const char*patch_input_file; 72static const char*root; 73static int root_len; 74static int read_stdin =1; 75static int options; 76 77static voidparse_whitespace_option(const char*option) 78{ 79if(!option) { 80 ws_error_action = warn_on_ws_error; 81return; 82} 83if(!strcmp(option,"warn")) { 84 ws_error_action = warn_on_ws_error; 85return; 86} 87if(!strcmp(option,"nowarn")) { 88 ws_error_action = nowarn_ws_error; 89return; 90} 91if(!strcmp(option,"error")) { 92 ws_error_action = die_on_ws_error; 93return; 94} 95if(!strcmp(option,"error-all")) { 96 ws_error_action = die_on_ws_error; 97 squelch_whitespace_errors =0; 98return; 99} 100if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 101 ws_error_action = correct_ws_error; 102return; 103} 104die("unrecognized whitespace option '%s'", option); 105} 106 107static voidparse_ignorewhitespace_option(const char*option) 108{ 109if(!option || !strcmp(option,"no") || 110!strcmp(option,"false") || !strcmp(option,"never") || 111!strcmp(option,"none")) { 112 ws_ignore_action = ignore_ws_none; 113return; 114} 115if(!strcmp(option,"change")) { 116 ws_ignore_action = ignore_ws_change; 117return; 118} 119die("unrecognized whitespace ignore option '%s'", option); 120} 121 122static voidset_default_whitespace_mode(const char*whitespace_option) 123{ 124if(!whitespace_option && !apply_default_whitespace) 125 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 126} 127 128/* 129 * For "diff-stat" like behaviour, we keep track of the biggest change 130 * we've seen, and the longest filename. That allows us to do simple 131 * scaling. 132 */ 133static int max_change, max_len; 134 135/* 136 * Various "current state", notably line numbers and what 137 * file (and how) we're patching right now.. The "is_xxxx" 138 * things are flags, where -1 means "don't know yet". 139 */ 140static int linenr =1; 141 142/* 143 * This represents one "hunk" from a patch, starting with 144 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 145 * patch text is pointed at by patch, and its byte length 146 * is stored in size. leading and trailing are the number 147 * of context lines. 148 */ 149struct fragment { 150unsigned long leading, trailing; 151unsigned long oldpos, oldlines; 152unsigned long newpos, newlines; 153const char*patch; 154int size; 155int rejected; 156int linenr; 157struct fragment *next; 158}; 159 160/* 161 * When dealing with a binary patch, we reuse "leading" field 162 * to store the type of the binary hunk, either deflated "delta" 163 * or deflated "literal". 164 */ 165#define binary_patch_method leading 166#define BINARY_DELTA_DEFLATED 1 167#define BINARY_LITERAL_DEFLATED 2 168 169/* 170 * This represents a "patch" to a file, both metainfo changes 171 * such as creation/deletion, filemode and content changes represented 172 * as a series of fragments. 173 */ 174struct patch { 175char*new_name, *old_name, *def_name; 176unsigned int old_mode, new_mode; 177int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 178int rejected; 179unsigned ws_rule; 180unsigned long deflate_origlen; 181int lines_added, lines_deleted; 182int score; 183unsigned int is_toplevel_relative:1; 184unsigned int inaccurate_eof:1; 185unsigned int is_binary:1; 186unsigned int is_copy:1; 187unsigned int is_rename:1; 188unsigned int recount:1; 189struct fragment *fragments; 190char*result; 191size_t resultsize; 192char old_sha1_prefix[41]; 193char new_sha1_prefix[41]; 194struct patch *next; 195}; 196 197/* 198 * A line in a file, len-bytes long (includes the terminating LF, 199 * except for an incomplete line at the end if the file ends with 200 * one), and its contents hashes to 'hash'. 201 */ 202struct line { 203size_t len; 204unsigned hash :24; 205unsigned flag :8; 206#define LINE_COMMON 1 207}; 208 209/* 210 * This represents a "file", which is an array of "lines". 211 */ 212struct image { 213char*buf; 214size_t len; 215size_t nr; 216size_t alloc; 217struct line *line_allocated; 218struct line *line; 219}; 220 221/* 222 * Records filenames that have been touched, in order to handle 223 * the case where more than one patches touch the same file. 224 */ 225 226static struct string_list fn_table; 227 228static uint32_thash_line(const char*cp,size_t len) 229{ 230size_t i; 231uint32_t h; 232for(i =0, h =0; i < len; i++) { 233if(!isspace(cp[i])) { 234 h = h *3+ (cp[i] &0xff); 235} 236} 237return h; 238} 239 240/* 241 * Compare lines s1 of length n1 and s2 of length n2, ignoring 242 * whitespace difference. Returns 1 if they match, 0 otherwise 243 */ 244static intfuzzy_matchlines(const char*s1,size_t n1, 245const char*s2,size_t n2) 246{ 247const char*last1 = s1 + n1 -1; 248const char*last2 = s2 + n2 -1; 249int result =0; 250 251if(n1 <0|| n2 <0) 252return0; 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_ttz_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_tdate_len(const char*line,size_t len) 471{ 472const char*date, *p; 473 474if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 475return0; 476 p = date = line + len -strlen("72-02-05"); 477 478if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 479!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 480!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 481return0; 482 483if(date - line >=strlen("19") && 484isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 485 date -=strlen("19"); 486 487return line + len - date; 488} 489 490static size_tshort_time_len(const char*line,size_t len) 491{ 492const char*time, *p; 493 494if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 495return0; 496 p = time = line + len -strlen(" 07:01:32"); 497 498/* Permit 1-digit hours? */ 499if(*p++ !=' '|| 500!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 501!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 502!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 503return0; 504 505return line + len - time; 506} 507 508static size_tfractional_time_len(const char*line,size_t len) 509{ 510const char*p; 511size_t n; 512 513/* Expected format: 19:41:17.620000023 */ 514if(!len || !isdigit(line[len -1])) 515return0; 516 p = line + len -1; 517 518/* Fractional seconds. */ 519while(p > line &&isdigit(*p)) 520 p--; 521if(*p !='.') 522return0; 523 524/* Hours, minutes, and whole seconds. */ 525 n =short_time_len(line, p - line); 526if(!n) 527return0; 528 529return line + len - p + n; 530} 531 532static size_ttrailing_spaces_len(const char*line,size_t len) 533{ 534const char*p; 535 536/* Expected format: ' ' x (1 or more) */ 537if(!len || line[len -1] !=' ') 538return0; 539 540 p = line + len; 541while(p != line) { 542 p--; 543if(*p !=' ') 544return line + len - (p +1); 545} 546 547/* All spaces! */ 548return len; 549} 550 551static size_tdiff_timestamp_len(const char*line,size_t len) 552{ 553const char*end = line + len; 554size_t n; 555 556/* 557 * Posix: 2010-07-05 19:41:17 558 * GNU: 2010-07-05 19:41:17.620000023 -0500 559 */ 560 561if(!isdigit(end[-1])) 562return0; 563 564 n =tz_len(line, end - line); 565 end -= n; 566 567 n =short_time_len(line, end - line); 568if(!n) 569 n =fractional_time_len(line, end - line); 570 end -= n; 571 572 n =date_len(line, end - line); 573if(!n)/* No date. Too bad. */ 574return0; 575 end -= n; 576 577if(end == line)/* No space before date. */ 578return0; 579if(end[-1] =='\t') {/* Success! */ 580 end--; 581return line + len - end; 582} 583if(end[-1] !=' ')/* No space before date. */ 584return0; 585 586/* Whitespace damage. */ 587 end -=trailing_spaces_len(line, end - line); 588return line + len - end; 589} 590 591static char*find_name_common(const char*line,char*def,int p_value, 592const char*end,int terminate) 593{ 594int len; 595const char*start = NULL; 596 597if(p_value ==0) 598 start = line; 599while(line != end) { 600char c = *line; 601 602if(!end &&isspace(c)) { 603if(c =='\n') 604break; 605if(name_terminate(start, line-start, c, terminate)) 606break; 607} 608 line++; 609if(c =='/'&& !--p_value) 610 start = line; 611} 612if(!start) 613returnsquash_slash(def); 614 len = line - start; 615if(!len) 616returnsquash_slash(def); 617 618/* 619 * Generally we prefer the shorter name, especially 620 * if the other one is just a variation of that with 621 * something else tacked on to the end (ie "file.orig" 622 * or "file~"). 623 */ 624if(def) { 625int deflen =strlen(def); 626if(deflen < len && !strncmp(start, def, deflen)) 627returnsquash_slash(def); 628free(def); 629} 630 631if(root) { 632char*ret =xmalloc(root_len + len +1); 633strcpy(ret, root); 634memcpy(ret + root_len, start, len); 635 ret[root_len + len] ='\0'; 636returnsquash_slash(ret); 637} 638 639returnsquash_slash(xmemdupz(start, len)); 640} 641 642static char*find_name(const char*line,char*def,int p_value,int terminate) 643{ 644if(*line =='"') { 645char*name =find_name_gnu(line, def, p_value); 646if(name) 647return name; 648} 649 650returnfind_name_common(line, def, p_value, NULL, terminate); 651} 652 653static char*find_name_traditional(const char*line,char*def,int p_value) 654{ 655size_t len =strlen(line); 656size_t date_len; 657 658if(*line =='"') { 659char*name =find_name_gnu(line, def, p_value); 660if(name) 661return name; 662} 663 664 len =strchrnul(line,'\n') - line; 665 date_len =diff_timestamp_len(line, len); 666if(!date_len) 667returnfind_name_common(line, def, p_value, NULL, TERM_TAB); 668 len -= date_len; 669 670returnfind_name_common(line, def, p_value, line + len,0); 671} 672 673static intcount_slashes(const char*cp) 674{ 675int cnt =0; 676char ch; 677 678while((ch = *cp++)) 679if(ch =='/') 680 cnt++; 681return cnt; 682} 683 684/* 685 * Given the string after "--- " or "+++ ", guess the appropriate 686 * p_value for the given patch. 687 */ 688static intguess_p_value(const char*nameline) 689{ 690char*name, *cp; 691int val = -1; 692 693if(is_dev_null(nameline)) 694return-1; 695 name =find_name_traditional(nameline, NULL,0); 696if(!name) 697return-1; 698 cp =strchr(name,'/'); 699if(!cp) 700 val =0; 701else if(prefix) { 702/* 703 * Does it begin with "a/$our-prefix" and such? Then this is 704 * very likely to apply to our directory. 705 */ 706if(!strncmp(name, prefix, prefix_length)) 707 val =count_slashes(prefix); 708else{ 709 cp++; 710if(!strncmp(cp, prefix, prefix_length)) 711 val =count_slashes(prefix) +1; 712} 713} 714free(name); 715return val; 716} 717 718/* 719 * Does the ---/+++ line has the POSIX timestamp after the last HT? 720 * GNU diff puts epoch there to signal a creation/deletion event. Is 721 * this such a timestamp? 722 */ 723static inthas_epoch_timestamp(const char*nameline) 724{ 725/* 726 * We are only interested in epoch timestamp; any non-zero 727 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 728 * For the same reason, the date must be either 1969-12-31 or 729 * 1970-01-01, and the seconds part must be "00". 730 */ 731const char stamp_regexp[] = 732"^(1969-12-31|1970-01-01)" 733" " 734"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 735" " 736"([-+][0-2][0-9][0-5][0-9])\n"; 737const char*timestamp = NULL, *cp; 738static regex_t *stamp; 739 regmatch_t m[10]; 740int zoneoffset; 741int hourminute; 742int status; 743 744for(cp = nameline; *cp !='\n'; cp++) { 745if(*cp =='\t') 746 timestamp = cp +1; 747} 748if(!timestamp) 749return0; 750if(!stamp) { 751 stamp =xmalloc(sizeof(*stamp)); 752if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 753warning("Cannot prepare timestamp regexp%s", 754 stamp_regexp); 755return0; 756} 757} 758 759 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 760if(status) { 761if(status != REG_NOMATCH) 762warning("regexec returned%dfor input:%s", 763 status, timestamp); 764return0; 765} 766 767 zoneoffset =strtol(timestamp + m[3].rm_so +1, NULL,10); 768 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 769if(timestamp[m[3].rm_so] =='-') 770 zoneoffset = -zoneoffset; 771 772/* 773 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 774 * (west of GMT) or 1970-01-01 (east of GMT) 775 */ 776if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 777(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 778return0; 779 780 hourminute = (strtol(timestamp +11, NULL,10) *60+ 781strtol(timestamp +14, NULL,10) - 782 zoneoffset); 783 784return((zoneoffset <0&& hourminute ==1440) || 785(0<= zoneoffset && !hourminute)); 786} 787 788/* 789 * Get the name etc info from the ---/+++ lines of a traditional patch header 790 * 791 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 792 * files, we can happily check the index for a match, but for creating a 793 * new file we should try to match whatever "patch" does. I have no idea. 794 */ 795static voidparse_traditional_patch(const char*first,const char*second,struct patch *patch) 796{ 797char*name; 798 799 first +=4;/* skip "--- " */ 800 second +=4;/* skip "+++ " */ 801if(!p_value_known) { 802int p, q; 803 p =guess_p_value(first); 804 q =guess_p_value(second); 805if(p <0) p = q; 806if(0<= p && p == q) { 807 p_value = p; 808 p_value_known =1; 809} 810} 811if(is_dev_null(first)) { 812 patch->is_new =1; 813 patch->is_delete =0; 814 name =find_name_traditional(second, NULL, p_value); 815 patch->new_name = name; 816}else if(is_dev_null(second)) { 817 patch->is_new =0; 818 patch->is_delete =1; 819 name =find_name_traditional(first, NULL, p_value); 820 patch->old_name = name; 821}else{ 822 name =find_name_traditional(first, NULL, p_value); 823 name =find_name_traditional(second, name, p_value); 824if(has_epoch_timestamp(first)) { 825 patch->is_new =1; 826 patch->is_delete =0; 827 patch->new_name = name; 828}else if(has_epoch_timestamp(second)) { 829 patch->is_new =0; 830 patch->is_delete =1; 831 patch->old_name = name; 832}else{ 833 patch->old_name = patch->new_name = name; 834} 835} 836if(!name) 837die("unable to find filename in patch at line%d", linenr); 838} 839 840static intgitdiff_hdrend(const char*line,struct patch *patch) 841{ 842return-1; 843} 844 845/* 846 * We're anal about diff header consistency, to make 847 * sure that we don't end up having strange ambiguous 848 * patches floating around. 849 * 850 * As a result, gitdiff_{old|new}name() will check 851 * their names against any previous information, just 852 * to make sure.. 853 */ 854static char*gitdiff_verify_name(const char*line,int isnull,char*orig_name,const char*oldnew) 855{ 856if(!orig_name && !isnull) 857returnfind_name(line, NULL, p_value, TERM_TAB); 858 859if(orig_name) { 860int len; 861const char*name; 862char*another; 863 name = orig_name; 864 len =strlen(name); 865if(isnull) 866die("git apply: bad git-diff - expected /dev/null, got%son line%d", name, linenr); 867 another =find_name(line, NULL, p_value, TERM_TAB); 868if(!another ||memcmp(another, name, len +1)) 869die("git apply: bad git-diff - inconsistent%sfilename on line%d", oldnew, linenr); 870free(another); 871return orig_name; 872} 873else{ 874/* expect "/dev/null" */ 875if(memcmp("/dev/null", line,9) || line[9] !='\n') 876die("git apply: bad git-diff - expected /dev/null on line%d", linenr); 877return NULL; 878} 879} 880 881static intgitdiff_oldname(const char*line,struct patch *patch) 882{ 883 patch->old_name =gitdiff_verify_name(line, patch->is_new, patch->old_name,"old"); 884return0; 885} 886 887static intgitdiff_newname(const char*line,struct patch *patch) 888{ 889 patch->new_name =gitdiff_verify_name(line, patch->is_delete, patch->new_name,"new"); 890return0; 891} 892 893static intgitdiff_oldmode(const char*line,struct patch *patch) 894{ 895 patch->old_mode =strtoul(line, NULL,8); 896return0; 897} 898 899static intgitdiff_newmode(const char*line,struct patch *patch) 900{ 901 patch->new_mode =strtoul(line, NULL,8); 902return0; 903} 904 905static intgitdiff_delete(const char*line,struct patch *patch) 906{ 907 patch->is_delete =1; 908 patch->old_name = patch->def_name; 909returngitdiff_oldmode(line, patch); 910} 911 912static intgitdiff_newfile(const char*line,struct patch *patch) 913{ 914 patch->is_new =1; 915 patch->new_name = patch->def_name; 916returngitdiff_newmode(line, patch); 917} 918 919static intgitdiff_copysrc(const char*line,struct patch *patch) 920{ 921 patch->is_copy =1; 922 patch->old_name =find_name(line, NULL,0,0); 923return0; 924} 925 926static intgitdiff_copydst(const char*line,struct patch *patch) 927{ 928 patch->is_copy =1; 929 patch->new_name =find_name(line, NULL,0,0); 930return0; 931} 932 933static intgitdiff_renamesrc(const char*line,struct patch *patch) 934{ 935 patch->is_rename =1; 936 patch->old_name =find_name(line, NULL,0,0); 937return0; 938} 939 940static intgitdiff_renamedst(const char*line,struct patch *patch) 941{ 942 patch->is_rename =1; 943 patch->new_name =find_name(line, NULL,0,0); 944return0; 945} 946 947static intgitdiff_similarity(const char*line,struct patch *patch) 948{ 949if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 950 patch->score =0; 951return0; 952} 953 954static intgitdiff_dissimilarity(const char*line,struct patch *patch) 955{ 956if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 957 patch->score =0; 958return0; 959} 960 961static intgitdiff_index(const char*line,struct patch *patch) 962{ 963/* 964 * index line is N hexadecimal, "..", N hexadecimal, 965 * and optional space with octal mode. 966 */ 967const char*ptr, *eol; 968int len; 969 970 ptr =strchr(line,'.'); 971if(!ptr || ptr[1] !='.'||40< ptr - line) 972return0; 973 len = ptr - line; 974memcpy(patch->old_sha1_prefix, line, len); 975 patch->old_sha1_prefix[len] =0; 976 977 line = ptr +2; 978 ptr =strchr(line,' '); 979 eol =strchr(line,'\n'); 980 981if(!ptr || eol < ptr) 982 ptr = eol; 983 len = ptr - line; 984 985if(40< len) 986return0; 987memcpy(patch->new_sha1_prefix, line, len); 988 patch->new_sha1_prefix[len] =0; 989if(*ptr ==' ') 990 patch->old_mode =strtoul(ptr+1, NULL,8); 991return0; 992} 993 994/* 995 * This is normal for a diff that doesn't change anything: we'll fall through 996 * into the next diff. Tell the parser to break out. 997 */ 998static intgitdiff_unrecognized(const char*line,struct patch *patch) 999{1000return-1;1001}10021003static const char*stop_at_slash(const char*line,int llen)1004{1005int nslash = p_value;1006int i;10071008for(i =0; i < llen; i++) {1009int ch = line[i];1010if(ch =='/'&& --nslash <=0)1011return&line[i];1012}1013return NULL;1014}10151016/*1017 * This is to extract the same name that appears on "diff --git"1018 * line. We do not find and return anything if it is a rename1019 * patch, and it is OK because we will find the name elsewhere.1020 * We need to reliably find name only when it is mode-change only,1021 * creation or deletion of an empty file. In any of these cases,1022 * both sides are the same name under a/ and b/ respectively.1023 */1024static char*git_header_name(char*line,int llen)1025{1026const char*name;1027const char*second = NULL;1028size_t len;10291030 line +=strlen("diff --git ");1031 llen -=strlen("diff --git ");10321033if(*line =='"') {1034const char*cp;1035struct strbuf first = STRBUF_INIT;1036struct strbuf sp = STRBUF_INIT;10371038if(unquote_c_style(&first, line, &second))1039goto free_and_fail1;10401041/* advance to the first slash */1042 cp =stop_at_slash(first.buf, first.len);1043/* we do not accept absolute paths */1044if(!cp || cp == first.buf)1045goto free_and_fail1;1046strbuf_remove(&first,0, cp +1- first.buf);10471048/*1049 * second points at one past closing dq of name.1050 * find the second name.1051 */1052while((second < line + llen) &&isspace(*second))1053 second++;10541055if(line + llen <= second)1056goto free_and_fail1;1057if(*second =='"') {1058if(unquote_c_style(&sp, second, NULL))1059goto free_and_fail1;1060 cp =stop_at_slash(sp.buf, sp.len);1061if(!cp || cp == sp.buf)1062goto free_and_fail1;1063/* They must match, otherwise ignore */1064if(strcmp(cp +1, first.buf))1065goto free_and_fail1;1066strbuf_release(&sp);1067returnstrbuf_detach(&first, NULL);1068}10691070/* unquoted second */1071 cp =stop_at_slash(second, line + llen - second);1072if(!cp || cp == second)1073goto free_and_fail1;1074 cp++;1075if(line + llen - cp != first.len +1||1076memcmp(first.buf, cp, first.len))1077goto free_and_fail1;1078returnstrbuf_detach(&first, NULL);10791080 free_and_fail1:1081strbuf_release(&first);1082strbuf_release(&sp);1083return NULL;1084}10851086/* unquoted first name */1087 name =stop_at_slash(line, llen);1088if(!name || name == line)1089return NULL;1090 name++;10911092/*1093 * since the first name is unquoted, a dq if exists must be1094 * the beginning of the second name.1095 */1096for(second = name; second < line + llen; second++) {1097if(*second =='"') {1098struct strbuf sp = STRBUF_INIT;1099const char*np;11001101if(unquote_c_style(&sp, second, NULL))1102goto free_and_fail2;11031104 np =stop_at_slash(sp.buf, sp.len);1105if(!np || np == sp.buf)1106goto free_and_fail2;1107 np++;11081109 len = sp.buf + sp.len - np;1110if(len < second - name &&1111!strncmp(np, name, len) &&1112isspace(name[len])) {1113/* Good */1114strbuf_remove(&sp,0, np - sp.buf);1115returnstrbuf_detach(&sp, NULL);1116}11171118 free_and_fail2:1119strbuf_release(&sp);1120return NULL;1121}1122}11231124/*1125 * Accept a name only if it shows up twice, exactly the same1126 * form.1127 */1128for(len =0; ; len++) {1129switch(name[len]) {1130default:1131continue;1132case'\n':1133return NULL;1134case'\t':case' ':1135 second = name+len;1136for(;;) {1137char c = *second++;1138if(c =='\n')1139return NULL;1140if(c =='/')1141break;1142}1143if(second[len] =='\n'&& !memcmp(name, second, len)) {1144returnxmemdupz(name, len);1145}1146}1147}1148}11491150/* Verify that we recognize the lines following a git header */1151static intparse_git_header(char*line,int len,unsigned int size,struct patch *patch)1152{1153unsigned long offset;11541155/* A git diff has explicit new/delete information, so we don't guess */1156 patch->is_new =0;1157 patch->is_delete =0;11581159/*1160 * Some things may not have the old name in the1161 * rest of the headers anywhere (pure mode changes,1162 * or removing or adding empty files), so we get1163 * the default name from the header.1164 */1165 patch->def_name =git_header_name(line, len);1166if(patch->def_name && root) {1167char*s =xmalloc(root_len +strlen(patch->def_name) +1);1168strcpy(s, root);1169strcpy(s + root_len, patch->def_name);1170free(patch->def_name);1171 patch->def_name = s;1172}11731174 line += len;1175 size -= len;1176 linenr++;1177for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) {1178static const struct opentry {1179const char*str;1180int(*fn)(const char*,struct patch *);1181} optable[] = {1182{"@@ -", gitdiff_hdrend },1183{"--- ", gitdiff_oldname },1184{"+++ ", gitdiff_newname },1185{"old mode ", gitdiff_oldmode },1186{"new mode ", gitdiff_newmode },1187{"deleted file mode ", gitdiff_delete },1188{"new file mode ", gitdiff_newfile },1189{"copy from ", gitdiff_copysrc },1190{"copy to ", gitdiff_copydst },1191{"rename old ", gitdiff_renamesrc },1192{"rename new ", gitdiff_renamedst },1193{"rename from ", gitdiff_renamesrc },1194{"rename to ", gitdiff_renamedst },1195{"similarity index ", gitdiff_similarity },1196{"dissimilarity index ", gitdiff_dissimilarity },1197{"index ", gitdiff_index },1198{"", gitdiff_unrecognized },1199};1200int i;12011202 len =linelen(line, size);1203if(!len || line[len-1] !='\n')1204break;1205for(i =0; i <ARRAY_SIZE(optable); i++) {1206const struct opentry *p = optable + i;1207int oplen =strlen(p->str);1208if(len < oplen ||memcmp(p->str, line, oplen))1209continue;1210if(p->fn(line + oplen, patch) <0)1211return offset;1212break;1213}1214}12151216return offset;1217}12181219static intparse_num(const char*line,unsigned long*p)1220{1221char*ptr;12221223if(!isdigit(*line))1224return0;1225*p =strtoul(line, &ptr,10);1226return ptr - line;1227}12281229static intparse_range(const char*line,int len,int offset,const char*expect,1230unsigned long*p1,unsigned long*p2)1231{1232int digits, ex;12331234if(offset <0|| offset >= len)1235return-1;1236 line += offset;1237 len -= offset;12381239 digits =parse_num(line, p1);1240if(!digits)1241return-1;12421243 offset += digits;1244 line += digits;1245 len -= digits;12461247*p2 =1;1248if(*line ==',') {1249 digits =parse_num(line+1, p2);1250if(!digits)1251return-1;12521253 offset += digits+1;1254 line += digits+1;1255 len -= digits+1;1256}12571258 ex =strlen(expect);1259if(ex > len)1260return-1;1261if(memcmp(line, expect, ex))1262return-1;12631264return offset + ex;1265}12661267static voidrecount_diff(char*line,int size,struct fragment *fragment)1268{1269int oldlines =0, newlines =0, ret =0;12701271if(size <1) {1272warning("recount: ignore empty hunk");1273return;1274}12751276for(;;) {1277int len =linelen(line, size);1278 size -= len;1279 line += len;12801281if(size <1)1282break;12831284switch(*line) {1285case' ':case'\n':1286 newlines++;1287/* fall through */1288case'-':1289 oldlines++;1290continue;1291case'+':1292 newlines++;1293continue;1294case'\\':1295continue;1296case'@':1297 ret = size <3||prefixcmp(line,"@@ ");1298break;1299case'd':1300 ret = size <5||prefixcmp(line,"diff ");1301break;1302default:1303 ret = -1;1304break;1305}1306if(ret) {1307warning("recount: unexpected line: %.*s",1308(int)linelen(line, size), line);1309return;1310}1311break;1312}1313 fragment->oldlines = oldlines;1314 fragment->newlines = newlines;1315}13161317/*1318 * Parse a unified diff fragment header of the1319 * form "@@ -a,b +c,d @@"1320 */1321static intparse_fragment_header(char*line,int len,struct fragment *fragment)1322{1323int offset;13241325if(!len || line[len-1] !='\n')1326return-1;13271328/* Figure out the number of lines in a fragment */1329 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1330 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);13311332return offset;1333}13341335static intfind_header(char*line,unsigned long size,int*hdrsize,struct patch *patch)1336{1337unsigned long offset, len;13381339 patch->is_toplevel_relative =0;1340 patch->is_rename = patch->is_copy =0;1341 patch->is_new = patch->is_delete = -1;1342 patch->old_mode = patch->new_mode =0;1343 patch->old_name = patch->new_name = NULL;1344for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) {1345unsigned long nextlen;13461347 len =linelen(line, size);1348if(!len)1349break;13501351/* Testing this early allows us to take a few shortcuts.. */1352if(len <6)1353continue;13541355/*1356 * Make sure we don't find any unconnected patch fragments.1357 * That's a sign that we didn't find a header, and that a1358 * patch has become corrupted/broken up.1359 */1360if(!memcmp("@@ -", line,4)) {1361struct fragment dummy;1362if(parse_fragment_header(line, len, &dummy) <0)1363continue;1364die("patch fragment without header at line%d: %.*s",1365 linenr, (int)len-1, line);1366}13671368if(size < len +6)1369break;13701371/*1372 * Git patch? It might not have a real patch, just a rename1373 * or mode change, so we handle that specially1374 */1375if(!memcmp("diff --git ", line,11)) {1376int git_hdr_len =parse_git_header(line, len, size, patch);1377if(git_hdr_len <= len)1378continue;1379if(!patch->old_name && !patch->new_name) {1380if(!patch->def_name)1381die("git diff header lacks filename information when removing "1382"%dleading pathname components (line%d)", p_value, linenr);1383 patch->old_name = patch->new_name = patch->def_name;1384}1385 patch->is_toplevel_relative =1;1386*hdrsize = git_hdr_len;1387return offset;1388}13891390/* --- followed by +++ ? */1391if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1392continue;13931394/*1395 * We only accept unified patches, so we want it to1396 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1397 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1398 */1399 nextlen =linelen(line + len, size - len);1400if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1401continue;14021403/* Ok, we'll consider it a patch */1404parse_traditional_patch(line, line+len, patch);1405*hdrsize = len + nextlen;1406 linenr +=2;1407return offset;1408}1409return-1;1410}14111412static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1413{1414char*err;14151416if(!result)1417return;14181419 whitespace_error++;1420if(squelch_whitespace_errors &&1421 squelch_whitespace_errors < whitespace_error)1422return;14231424 err =whitespace_error_string(result);1425fprintf(stderr,"%s:%d:%s.\n%.*s\n",1426 patch_input_file, linenr, err, len, line);1427free(err);1428}14291430static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1431{1432unsigned result =ws_check(line +1, len -1, ws_rule);14331434record_ws_error(result, line +1, len -2, linenr);1435}14361437/*1438 * Parse a unified diff. Note that this really needs to parse each1439 * fragment separately, since the only way to know the difference1440 * between a "---" that is part of a patch, and a "---" that starts1441 * the next patch is to look at the line counts..1442 */1443static intparse_fragment(char*line,unsigned long size,1444struct patch *patch,struct fragment *fragment)1445{1446int added, deleted;1447int len =linelen(line, size), offset;1448unsigned long oldlines, newlines;1449unsigned long leading, trailing;14501451 offset =parse_fragment_header(line, len, fragment);1452if(offset <0)1453return-1;1454if(offset >0&& patch->recount)1455recount_diff(line + offset, size - offset, fragment);1456 oldlines = fragment->oldlines;1457 newlines = fragment->newlines;1458 leading =0;1459 trailing =0;14601461/* Parse the thing.. */1462 line += len;1463 size -= len;1464 linenr++;1465 added = deleted =0;1466for(offset = len;14670< size;1468 offset += len, size -= len, line += len, linenr++) {1469if(!oldlines && !newlines)1470break;1471 len =linelen(line, size);1472if(!len || line[len-1] !='\n')1473return-1;1474switch(*line) {1475default:1476return-1;1477case'\n':/* newer GNU diff, an empty context line */1478case' ':1479 oldlines--;1480 newlines--;1481if(!deleted && !added)1482 leading++;1483 trailing++;1484break;1485case'-':1486if(apply_in_reverse &&1487 ws_error_action != nowarn_ws_error)1488check_whitespace(line, len, patch->ws_rule);1489 deleted++;1490 oldlines--;1491 trailing =0;1492break;1493case'+':1494if(!apply_in_reverse &&1495 ws_error_action != nowarn_ws_error)1496check_whitespace(line, len, patch->ws_rule);1497 added++;1498 newlines--;1499 trailing =0;1500break;15011502/*1503 * We allow "\ No newline at end of file". Depending1504 * on locale settings when the patch was produced we1505 * don't know what this line looks like. The only1506 * thing we do know is that it begins with "\ ".1507 * Checking for 12 is just for sanity check -- any1508 * l10n of "\ No newline..." is at least that long.1509 */1510case'\\':1511if(len <12||memcmp(line,"\\",2))1512return-1;1513break;1514}1515}1516if(oldlines || newlines)1517return-1;1518 fragment->leading = leading;1519 fragment->trailing = trailing;15201521/*1522 * If a fragment ends with an incomplete line, we failed to include1523 * it in the above loop because we hit oldlines == newlines == 01524 * before seeing it.1525 */1526if(12< size && !memcmp(line,"\\",2))1527 offset +=linelen(line, size);15281529 patch->lines_added += added;1530 patch->lines_deleted += deleted;15311532if(0< patch->is_new && oldlines)1533returnerror("new file depends on old contents");1534if(0< patch->is_delete && newlines)1535returnerror("deleted file still has contents");1536return offset;1537}15381539static intparse_single_patch(char*line,unsigned long size,struct patch *patch)1540{1541unsigned long offset =0;1542unsigned long oldlines =0, newlines =0, context =0;1543struct fragment **fragp = &patch->fragments;15441545while(size >4&& !memcmp(line,"@@ -",4)) {1546struct fragment *fragment;1547int len;15481549 fragment =xcalloc(1,sizeof(*fragment));1550 fragment->linenr = linenr;1551 len =parse_fragment(line, size, patch, fragment);1552if(len <=0)1553die("corrupt patch at line%d", linenr);1554 fragment->patch = line;1555 fragment->size = len;1556 oldlines += fragment->oldlines;1557 newlines += fragment->newlines;1558 context += fragment->leading + fragment->trailing;15591560*fragp = fragment;1561 fragp = &fragment->next;15621563 offset += len;1564 line += len;1565 size -= len;1566}15671568/*1569 * If something was removed (i.e. we have old-lines) it cannot1570 * be creation, and if something was added it cannot be1571 * deletion. However, the reverse is not true; --unified=01572 * patches that only add are not necessarily creation even1573 * though they do not have any old lines, and ones that only1574 * delete are not necessarily deletion.1575 *1576 * Unfortunately, a real creation/deletion patch do _not_ have1577 * any context line by definition, so we cannot safely tell it1578 * apart with --unified=0 insanity. At least if the patch has1579 * more than one hunk it is not creation or deletion.1580 */1581if(patch->is_new <0&&1582(oldlines || (patch->fragments && patch->fragments->next)))1583 patch->is_new =0;1584if(patch->is_delete <0&&1585(newlines || (patch->fragments && patch->fragments->next)))1586 patch->is_delete =0;15871588if(0< patch->is_new && oldlines)1589die("new file%sdepends on old contents", patch->new_name);1590if(0< patch->is_delete && newlines)1591die("deleted file%sstill has contents", patch->old_name);1592if(!patch->is_delete && !newlines && context)1593fprintf(stderr,"** warning: file%sbecomes empty but "1594"is not deleted\n", patch->new_name);15951596return offset;1597}15981599staticinlineintmetadata_changes(struct patch *patch)1600{1601return patch->is_rename >0||1602 patch->is_copy >0||1603 patch->is_new >0||1604 patch->is_delete ||1605(patch->old_mode && patch->new_mode &&1606 patch->old_mode != patch->new_mode);1607}16081609static char*inflate_it(const void*data,unsigned long size,1610unsigned long inflated_size)1611{1612 z_stream stream;1613void*out;1614int st;16151616memset(&stream,0,sizeof(stream));16171618 stream.next_in = (unsigned char*)data;1619 stream.avail_in = size;1620 stream.next_out = out =xmalloc(inflated_size);1621 stream.avail_out = inflated_size;1622git_inflate_init(&stream);1623 st =git_inflate(&stream, Z_FINISH);1624git_inflate_end(&stream);1625if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1626free(out);1627return NULL;1628}1629return out;1630}16311632static struct fragment *parse_binary_hunk(char**buf_p,1633unsigned long*sz_p,1634int*status_p,1635int*used_p)1636{1637/*1638 * Expect a line that begins with binary patch method ("literal"1639 * or "delta"), followed by the length of data before deflating.1640 * a sequence of 'length-byte' followed by base-85 encoded data1641 * should follow, terminated by a newline.1642 *1643 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1644 * and we would limit the patch line to 66 characters,1645 * so one line can fit up to 13 groups that would decode1646 * to 52 bytes max. The length byte 'A'-'Z' corresponds1647 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1648 */1649int llen, used;1650unsigned long size = *sz_p;1651char*buffer = *buf_p;1652int patch_method;1653unsigned long origlen;1654char*data = NULL;1655int hunk_size =0;1656struct fragment *frag;16571658 llen =linelen(buffer, size);1659 used = llen;16601661*status_p =0;16621663if(!prefixcmp(buffer,"delta ")) {1664 patch_method = BINARY_DELTA_DEFLATED;1665 origlen =strtoul(buffer +6, NULL,10);1666}1667else if(!prefixcmp(buffer,"literal ")) {1668 patch_method = BINARY_LITERAL_DEFLATED;1669 origlen =strtoul(buffer +8, NULL,10);1670}1671else1672return NULL;16731674 linenr++;1675 buffer += llen;1676while(1) {1677int byte_length, max_byte_length, newsize;1678 llen =linelen(buffer, size);1679 used += llen;1680 linenr++;1681if(llen ==1) {1682/* consume the blank line */1683 buffer++;1684 size--;1685break;1686}1687/*1688 * Minimum line is "A00000\n" which is 7-byte long,1689 * and the line length must be multiple of 5 plus 2.1690 */1691if((llen <7) || (llen-2) %5)1692goto corrupt;1693 max_byte_length = (llen -2) /5*4;1694 byte_length = *buffer;1695if('A'<= byte_length && byte_length <='Z')1696 byte_length = byte_length -'A'+1;1697else if('a'<= byte_length && byte_length <='z')1698 byte_length = byte_length -'a'+27;1699else1700goto corrupt;1701/* if the input length was not multiple of 4, we would1702 * have filler at the end but the filler should never1703 * exceed 3 bytes1704 */1705if(max_byte_length < byte_length ||1706 byte_length <= max_byte_length -4)1707goto corrupt;1708 newsize = hunk_size + byte_length;1709 data =xrealloc(data, newsize);1710if(decode_85(data + hunk_size, buffer +1, byte_length))1711goto corrupt;1712 hunk_size = newsize;1713 buffer += llen;1714 size -= llen;1715}17161717 frag =xcalloc(1,sizeof(*frag));1718 frag->patch =inflate_it(data, hunk_size, origlen);1719if(!frag->patch)1720goto corrupt;1721free(data);1722 frag->size = origlen;1723*buf_p = buffer;1724*sz_p = size;1725*used_p = used;1726 frag->binary_patch_method = patch_method;1727return frag;17281729 corrupt:1730free(data);1731*status_p = -1;1732error("corrupt binary patch at line%d: %.*s",1733 linenr-1, llen-1, buffer);1734return NULL;1735}17361737static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1738{1739/*1740 * We have read "GIT binary patch\n"; what follows is a line1741 * that says the patch method (currently, either "literal" or1742 * "delta") and the length of data before deflating; a1743 * sequence of 'length-byte' followed by base-85 encoded data1744 * follows.1745 *1746 * When a binary patch is reversible, there is another binary1747 * hunk in the same format, starting with patch method (either1748 * "literal" or "delta") with the length of data, and a sequence1749 * of length-byte + base-85 encoded data, terminated with another1750 * empty line. This data, when applied to the postimage, produces1751 * the preimage.1752 */1753struct fragment *forward;1754struct fragment *reverse;1755int status;1756int used, used_1;17571758 forward =parse_binary_hunk(&buffer, &size, &status, &used);1759if(!forward && !status)1760/* there has to be one hunk (forward hunk) */1761returnerror("unrecognized binary patch at line%d", linenr-1);1762if(status)1763/* otherwise we already gave an error message */1764return status;17651766 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1767if(reverse)1768 used += used_1;1769else if(status) {1770/*1771 * Not having reverse hunk is not an error, but having1772 * a corrupt reverse hunk is.1773 */1774free((void*) forward->patch);1775free(forward);1776return status;1777}1778 forward->next = reverse;1779 patch->fragments = forward;1780 patch->is_binary =1;1781return used;1782}17831784static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1785{1786int hdrsize, patchsize;1787int offset =find_header(buffer, size, &hdrsize, patch);17881789if(offset <0)1790return offset;17911792 patch->ws_rule =whitespace_rule(patch->new_name1793? patch->new_name1794: patch->old_name);17951796 patchsize =parse_single_patch(buffer + offset + hdrsize,1797 size - offset - hdrsize, patch);17981799if(!patchsize) {1800static const char*binhdr[] = {1801"Binary files ",1802"Files ",1803 NULL,1804};1805static const char git_binary[] ="GIT binary patch\n";1806int i;1807int hd = hdrsize + offset;1808unsigned long llen =linelen(buffer + hd, size - hd);18091810if(llen ==sizeof(git_binary) -1&&1811!memcmp(git_binary, buffer + hd, llen)) {1812int used;1813 linenr++;1814 used =parse_binary(buffer + hd + llen,1815 size - hd - llen, patch);1816if(used)1817 patchsize = used + llen;1818else1819 patchsize =0;1820}1821else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1822for(i =0; binhdr[i]; i++) {1823int len =strlen(binhdr[i]);1824if(len < size - hd &&1825!memcmp(binhdr[i], buffer + hd, len)) {1826 linenr++;1827 patch->is_binary =1;1828 patchsize = llen;1829break;1830}1831}1832}18331834/* Empty patch cannot be applied if it is a text patch1835 * without metadata change. A binary patch appears1836 * empty to us here.1837 */1838if((apply || check) &&1839(!patch->is_binary && !metadata_changes(patch)))1840die("patch with only garbage at line%d", linenr);1841}18421843return offset + hdrsize + patchsize;1844}18451846#define swap(a,b) myswap((a),(b),sizeof(a))18471848#define myswap(a, b, size) do { \1849 unsigned char mytmp[size]; \1850 memcpy(mytmp, &a, size); \1851 memcpy(&a, &b, size); \1852 memcpy(&b, mytmp, size); \1853} while (0)18541855static voidreverse_patches(struct patch *p)1856{1857for(; p; p = p->next) {1858struct fragment *frag = p->fragments;18591860swap(p->new_name, p->old_name);1861swap(p->new_mode, p->old_mode);1862swap(p->is_new, p->is_delete);1863swap(p->lines_added, p->lines_deleted);1864swap(p->old_sha1_prefix, p->new_sha1_prefix);18651866for(; frag; frag = frag->next) {1867swap(frag->newpos, frag->oldpos);1868swap(frag->newlines, frag->oldlines);1869}1870}1871}18721873static const char pluses[] =1874"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";1875static const char minuses[]=1876"----------------------------------------------------------------------";18771878static voidshow_stats(struct patch *patch)1879{1880struct strbuf qname = STRBUF_INIT;1881char*cp = patch->new_name ? patch->new_name : patch->old_name;1882int max, add, del;18831884quote_c_style(cp, &qname, NULL,0);18851886/*1887 * "scale" the filename1888 */1889 max = max_len;1890if(max >50)1891 max =50;18921893if(qname.len > max) {1894 cp =strchr(qname.buf + qname.len +3- max,'/');1895if(!cp)1896 cp = qname.buf + qname.len +3- max;1897strbuf_splice(&qname,0, cp - qname.buf,"...",3);1898}18991900if(patch->is_binary) {1901printf(" %-*s | Bin\n", max, qname.buf);1902strbuf_release(&qname);1903return;1904}19051906printf(" %-*s |", max, qname.buf);1907strbuf_release(&qname);19081909/*1910 * scale the add/delete1911 */1912 max = max + max_change >70?70- max : max_change;1913 add = patch->lines_added;1914 del = patch->lines_deleted;19151916if(max_change >0) {1917int total = ((add + del) * max + max_change /2) / max_change;1918 add = (add * max + max_change /2) / max_change;1919 del = total - add;1920}1921printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,1922 add, pluses, del, minuses);1923}19241925static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)1926{1927switch(st->st_mode & S_IFMT) {1928case S_IFLNK:1929if(strbuf_readlink(buf, path, st->st_size) <0)1930returnerror("unable to read symlink%s", path);1931return0;1932case S_IFREG:1933if(strbuf_read_file(buf, path, st->st_size) != st->st_size)1934returnerror("unable to open or read%s", path);1935convert_to_git(path, buf->buf, buf->len, buf,0);1936return0;1937default:1938return-1;1939}1940}19411942/*1943 * Update the preimage, and the common lines in postimage,1944 * from buffer buf of length len. If postlen is 0 the postimage1945 * is updated in place, otherwise it's updated on a new buffer1946 * of length postlen1947 */19481949static voidupdate_pre_post_images(struct image *preimage,1950struct image *postimage,1951char*buf,1952size_t len,size_t postlen)1953{1954int i, ctx;1955char*new, *old, *fixed;1956struct image fixed_preimage;19571958/*1959 * Update the preimage with whitespace fixes. Note that we1960 * are not losing preimage->buf -- apply_one_fragment() will1961 * free "oldlines".1962 */1963prepare_image(&fixed_preimage, buf, len,1);1964assert(fixed_preimage.nr == preimage->nr);1965for(i =0; i < preimage->nr; i++)1966 fixed_preimage.line[i].flag = preimage->line[i].flag;1967free(preimage->line_allocated);1968*preimage = fixed_preimage;19691970/*1971 * Adjust the common context lines in postimage. This can be1972 * done in-place when we are just doing whitespace fixing,1973 * which does not make the string grow, but needs a new buffer1974 * when ignoring whitespace causes the update, since in this case1975 * we could have e.g. tabs converted to multiple spaces.1976 * We trust the caller to tell us if the update can be done1977 * in place (postlen==0) or not.1978 */1979 old = postimage->buf;1980if(postlen)1981new= postimage->buf =xmalloc(postlen);1982else1983new= old;1984 fixed = preimage->buf;1985for(i = ctx =0; i < postimage->nr; i++) {1986size_t len = postimage->line[i].len;1987if(!(postimage->line[i].flag & LINE_COMMON)) {1988/* an added line -- no counterparts in preimage */1989memmove(new, old, len);1990 old += len;1991new+= len;1992continue;1993}19941995/* a common context -- skip it in the original postimage */1996 old += len;19971998/* and find the corresponding one in the fixed preimage */1999while(ctx < preimage->nr &&2000!(preimage->line[ctx].flag & LINE_COMMON)) {2001 fixed += preimage->line[ctx].len;2002 ctx++;2003}2004if(preimage->nr <= ctx)2005die("oops");20062007/* and copy it in, while fixing the line length */2008 len = preimage->line[ctx].len;2009memcpy(new, fixed, len);2010new+= len;2011 fixed += len;2012 postimage->line[i].len = len;2013 ctx++;2014}20152016/* Fix the length of the whole thing */2017 postimage->len =new- postimage->buf;2018}20192020static intmatch_fragment(struct image *img,2021struct image *preimage,2022struct image *postimage,2023unsigned longtry,2024int try_lno,2025unsigned ws_rule,2026int match_beginning,int match_end)2027{2028int i;2029char*fixed_buf, *buf, *orig, *target;2030struct strbuf fixed;2031size_t fixed_len;2032int preimage_limit;20332034if(preimage->nr + try_lno <= img->nr) {2035/*2036 * The hunk falls within the boundaries of img.2037 */2038 preimage_limit = preimage->nr;2039if(match_end && (preimage->nr + try_lno != img->nr))2040return0;2041}else if(ws_error_action == correct_ws_error &&2042(ws_rule & WS_BLANK_AT_EOF)) {2043/*2044 * This hunk extends beyond the end of img, and we are2045 * removing blank lines at the end of the file. This2046 * many lines from the beginning of the preimage must2047 * match with img, and the remainder of the preimage2048 * must be blank.2049 */2050 preimage_limit = img->nr - try_lno;2051}else{2052/*2053 * The hunk extends beyond the end of the img and2054 * we are not removing blanks at the end, so we2055 * should reject the hunk at this position.2056 */2057return0;2058}20592060if(match_beginning && try_lno)2061return0;20622063/* Quick hash check */2064for(i =0; i < preimage_limit; i++)2065if(preimage->line[i].hash != img->line[try_lno + i].hash)2066return0;20672068if(preimage_limit == preimage->nr) {2069/*2070 * Do we have an exact match? If we were told to match2071 * at the end, size must be exactly at try+fragsize,2072 * otherwise try+fragsize must be still within the preimage,2073 * and either case, the old piece should match the preimage2074 * exactly.2075 */2076if((match_end2077? (try+ preimage->len == img->len)2078: (try+ preimage->len <= img->len)) &&2079!memcmp(img->buf +try, preimage->buf, preimage->len))2080return1;2081}else{2082/*2083 * The preimage extends beyond the end of img, so2084 * there cannot be an exact match.2085 *2086 * There must be one non-blank context line that match2087 * a line before the end of img.2088 */2089char*buf_end;20902091 buf = preimage->buf;2092 buf_end = buf;2093for(i =0; i < preimage_limit; i++)2094 buf_end += preimage->line[i].len;20952096for( ; buf < buf_end; buf++)2097if(!isspace(*buf))2098break;2099if(buf == buf_end)2100return0;2101}21022103/*2104 * No exact match. If we are ignoring whitespace, run a line-by-line2105 * fuzzy matching. We collect all the line length information because2106 * we need it to adjust whitespace if we match.2107 */2108if(ws_ignore_action == ignore_ws_change) {2109size_t imgoff =0;2110size_t preoff =0;2111size_t postlen = postimage->len;2112size_t extra_chars;2113char*preimage_eof;2114char*preimage_end;2115for(i =0; i < preimage_limit; i++) {2116size_t prelen = preimage->line[i].len;2117size_t imglen = img->line[try_lno+i].len;21182119if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2120 preimage->buf + preoff, prelen))2121return0;2122if(preimage->line[i].flag & LINE_COMMON)2123 postlen += imglen - prelen;2124 imgoff += imglen;2125 preoff += prelen;2126}21272128/*2129 * Ok, the preimage matches with whitespace fuzz.2130 *2131 * imgoff now holds the true length of the target that2132 * matches the preimage before the end of the file.2133 *2134 * Count the number of characters in the preimage that fall2135 * beyond the end of the file and make sure that all of them2136 * are whitespace characters. (This can only happen if2137 * we are removing blank lines at the end of the file.)2138 */2139 buf = preimage_eof = preimage->buf + preoff;2140for( ; i < preimage->nr; i++)2141 preoff += preimage->line[i].len;2142 preimage_end = preimage->buf + preoff;2143for( ; buf < preimage_end; buf++)2144if(!isspace(*buf))2145return0;21462147/*2148 * Update the preimage and the common postimage context2149 * lines to use the same whitespace as the target.2150 * If whitespace is missing in the target (i.e.2151 * if the preimage extends beyond the end of the file),2152 * use the whitespace from the preimage.2153 */2154 extra_chars = preimage_end - preimage_eof;2155strbuf_init(&fixed, imgoff + extra_chars);2156strbuf_add(&fixed, img->buf +try, imgoff);2157strbuf_add(&fixed, preimage_eof, extra_chars);2158 fixed_buf =strbuf_detach(&fixed, &fixed_len);2159update_pre_post_images(preimage, postimage,2160 fixed_buf, fixed_len, postlen);2161return1;2162}21632164if(ws_error_action != correct_ws_error)2165return0;21662167/*2168 * The hunk does not apply byte-by-byte, but the hash says2169 * it might with whitespace fuzz. We haven't been asked to2170 * ignore whitespace, we were asked to correct whitespace2171 * errors, so let's try matching after whitespace correction.2172 *2173 * The preimage may extend beyond the end of the file,2174 * but in this loop we will only handle the part of the2175 * preimage that falls within the file.2176 */2177strbuf_init(&fixed, preimage->len +1);2178 orig = preimage->buf;2179 target = img->buf +try;2180for(i =0; i < preimage_limit; i++) {2181size_t oldlen = preimage->line[i].len;2182size_t tgtlen = img->line[try_lno + i].len;2183size_t fixstart = fixed.len;2184struct strbuf tgtfix;2185int match;21862187/* Try fixing the line in the preimage */2188ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);21892190/* Try fixing the line in the target */2191strbuf_init(&tgtfix, tgtlen);2192ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);21932194/*2195 * If they match, either the preimage was based on2196 * a version before our tree fixed whitespace breakage,2197 * or we are lacking a whitespace-fix patch the tree2198 * the preimage was based on already had (i.e. target2199 * has whitespace breakage, the preimage doesn't).2200 * In either case, we are fixing the whitespace breakages2201 * so we might as well take the fix together with their2202 * real change.2203 */2204 match = (tgtfix.len == fixed.len - fixstart &&2205!memcmp(tgtfix.buf, fixed.buf + fixstart,2206 fixed.len - fixstart));22072208strbuf_release(&tgtfix);2209if(!match)2210goto unmatch_exit;22112212 orig += oldlen;2213 target += tgtlen;2214}221522162217/*2218 * Now handle the lines in the preimage that falls beyond the2219 * end of the file (if any). They will only match if they are2220 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2221 * false).2222 */2223for( ; i < preimage->nr; i++) {2224size_t fixstart = fixed.len;/* start of the fixed preimage */2225size_t oldlen = preimage->line[i].len;2226int j;22272228/* Try fixing the line in the preimage */2229ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);22302231for(j = fixstart; j < fixed.len; j++)2232if(!isspace(fixed.buf[j]))2233goto unmatch_exit;22342235 orig += oldlen;2236}22372238/*2239 * Yes, the preimage is based on an older version that still2240 * has whitespace breakages unfixed, and fixing them makes the2241 * hunk match. Update the context lines in the postimage.2242 */2243 fixed_buf =strbuf_detach(&fixed, &fixed_len);2244update_pre_post_images(preimage, postimage,2245 fixed_buf, fixed_len,0);2246return1;22472248 unmatch_exit:2249strbuf_release(&fixed);2250return0;2251}22522253static intfind_pos(struct image *img,2254struct image *preimage,2255struct image *postimage,2256int line,2257unsigned ws_rule,2258int match_beginning,int match_end)2259{2260int i;2261unsigned long backwards, forwards,try;2262int backwards_lno, forwards_lno, try_lno;22632264/*2265 * If match_beginning or match_end is specified, there is no2266 * point starting from a wrong line that will never match and2267 * wander around and wait for a match at the specified end.2268 */2269if(match_beginning)2270 line =0;2271else if(match_end)2272 line = img->nr - preimage->nr;22732274/*2275 * Because the comparison is unsigned, the following test2276 * will also take care of a negative line number that can2277 * result when match_end and preimage is larger than the target.2278 */2279if((size_t) line > img->nr)2280 line = img->nr;22812282try=0;2283for(i =0; i < line; i++)2284try+= img->line[i].len;22852286/*2287 * There's probably some smart way to do this, but I'll leave2288 * that to the smart and beautiful people. I'm simple and stupid.2289 */2290 backwards =try;2291 backwards_lno = line;2292 forwards =try;2293 forwards_lno = line;2294 try_lno = line;22952296for(i =0; ; i++) {2297if(match_fragment(img, preimage, postimage,2298try, try_lno, ws_rule,2299 match_beginning, match_end))2300return try_lno;23012302 again:2303if(backwards_lno ==0&& forwards_lno == img->nr)2304break;23052306if(i &1) {2307if(backwards_lno ==0) {2308 i++;2309goto again;2310}2311 backwards_lno--;2312 backwards -= img->line[backwards_lno].len;2313try= backwards;2314 try_lno = backwards_lno;2315}else{2316if(forwards_lno == img->nr) {2317 i++;2318goto again;2319}2320 forwards += img->line[forwards_lno].len;2321 forwards_lno++;2322try= forwards;2323 try_lno = forwards_lno;2324}23252326}2327return-1;2328}23292330static voidremove_first_line(struct image *img)2331{2332 img->buf += img->line[0].len;2333 img->len -= img->line[0].len;2334 img->line++;2335 img->nr--;2336}23372338static voidremove_last_line(struct image *img)2339{2340 img->len -= img->line[--img->nr].len;2341}23422343static voidupdate_image(struct image *img,2344int applied_pos,2345struct image *preimage,2346struct image *postimage)2347{2348/*2349 * remove the copy of preimage at offset in img2350 * and replace it with postimage2351 */2352int i, nr;2353size_t remove_count, insert_count, applied_at =0;2354char*result;2355int preimage_limit;23562357/*2358 * If we are removing blank lines at the end of img,2359 * the preimage may extend beyond the end.2360 * If that is the case, we must be careful only to2361 * remove the part of the preimage that falls within2362 * the boundaries of img. Initialize preimage_limit2363 * to the number of lines in the preimage that falls2364 * within the boundaries.2365 */2366 preimage_limit = preimage->nr;2367if(preimage_limit > img->nr - applied_pos)2368 preimage_limit = img->nr - applied_pos;23692370for(i =0; i < applied_pos; i++)2371 applied_at += img->line[i].len;23722373 remove_count =0;2374for(i =0; i < preimage_limit; i++)2375 remove_count += img->line[applied_pos + i].len;2376 insert_count = postimage->len;23772378/* Adjust the contents */2379 result =xmalloc(img->len + insert_count - remove_count +1);2380memcpy(result, img->buf, applied_at);2381memcpy(result + applied_at, postimage->buf, postimage->len);2382memcpy(result + applied_at + postimage->len,2383 img->buf + (applied_at + remove_count),2384 img->len - (applied_at + remove_count));2385free(img->buf);2386 img->buf = result;2387 img->len += insert_count - remove_count;2388 result[img->len] ='\0';23892390/* Adjust the line table */2391 nr = img->nr + postimage->nr - preimage_limit;2392if(preimage_limit < postimage->nr) {2393/*2394 * NOTE: this knows that we never call remove_first_line()2395 * on anything other than pre/post image.2396 */2397 img->line =xrealloc(img->line, nr *sizeof(*img->line));2398 img->line_allocated = img->line;2399}2400if(preimage_limit != postimage->nr)2401memmove(img->line + applied_pos + postimage->nr,2402 img->line + applied_pos + preimage_limit,2403(img->nr - (applied_pos + preimage_limit)) *2404sizeof(*img->line));2405memcpy(img->line + applied_pos,2406 postimage->line,2407 postimage->nr *sizeof(*img->line));2408 img->nr = nr;2409}24102411static intapply_one_fragment(struct image *img,struct fragment *frag,2412int inaccurate_eof,unsigned ws_rule)2413{2414int match_beginning, match_end;2415const char*patch = frag->patch;2416int size = frag->size;2417char*old, *oldlines;2418struct strbuf newlines;2419int new_blank_lines_at_end =0;2420unsigned long leading, trailing;2421int pos, applied_pos;2422struct image preimage;2423struct image postimage;24242425memset(&preimage,0,sizeof(preimage));2426memset(&postimage,0,sizeof(postimage));2427 oldlines =xmalloc(size);2428strbuf_init(&newlines, size);24292430 old = oldlines;2431while(size >0) {2432char first;2433int len =linelen(patch, size);2434int plen;2435int added_blank_line =0;2436int is_blank_context =0;2437size_t start;24382439if(!len)2440break;24412442/*2443 * "plen" is how much of the line we should use for2444 * the actual patch data. Normally we just remove the2445 * first character on the line, but if the line is2446 * followed by "\ No newline", then we also remove the2447 * last one (which is the newline, of course).2448 */2449 plen = len -1;2450if(len < size && patch[len] =='\\')2451 plen--;2452 first = *patch;2453if(apply_in_reverse) {2454if(first =='-')2455 first ='+';2456else if(first =='+')2457 first ='-';2458}24592460switch(first) {2461case'\n':2462/* Newer GNU diff, empty context line */2463if(plen <0)2464/* ... followed by '\No newline'; nothing */2465break;2466*old++ ='\n';2467strbuf_addch(&newlines,'\n');2468add_line_info(&preimage,"\n",1, LINE_COMMON);2469add_line_info(&postimage,"\n",1, LINE_COMMON);2470 is_blank_context =1;2471break;2472case' ':2473if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2474ws_blank_line(patch +1, plen, ws_rule))2475 is_blank_context =1;2476case'-':2477memcpy(old, patch +1, plen);2478add_line_info(&preimage, old, plen,2479(first ==' '? LINE_COMMON :0));2480 old += plen;2481if(first =='-')2482break;2483/* Fall-through for ' ' */2484case'+':2485/* --no-add does not add new lines */2486if(first =='+'&& no_add)2487break;24882489 start = newlines.len;2490if(first !='+'||2491!whitespace_error ||2492 ws_error_action != correct_ws_error) {2493strbuf_add(&newlines, patch +1, plen);2494}2495else{2496ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2497}2498add_line_info(&postimage, newlines.buf + start, newlines.len - start,2499(first =='+'?0: LINE_COMMON));2500if(first =='+'&&2501(ws_rule & WS_BLANK_AT_EOF) &&2502ws_blank_line(patch +1, plen, ws_rule))2503 added_blank_line =1;2504break;2505case'@':case'\\':2506/* Ignore it, we already handled it */2507break;2508default:2509if(apply_verbosely)2510error("invalid start of line: '%c'", first);2511return-1;2512}2513if(added_blank_line)2514 new_blank_lines_at_end++;2515else if(is_blank_context)2516;2517else2518 new_blank_lines_at_end =0;2519 patch += len;2520 size -= len;2521}2522if(inaccurate_eof &&2523 old > oldlines && old[-1] =='\n'&&2524 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2525 old--;2526strbuf_setlen(&newlines, newlines.len -1);2527}25282529 leading = frag->leading;2530 trailing = frag->trailing;25312532/*2533 * A hunk to change lines at the beginning would begin with2534 * @@ -1,L +N,M @@2535 * but we need to be careful. -U0 that inserts before the second2536 * line also has this pattern.2537 *2538 * And a hunk to add to an empty file would begin with2539 * @@ -0,0 +N,M @@2540 *2541 * In other words, a hunk that is (frag->oldpos <= 1) with or2542 * without leading context must match at the beginning.2543 */2544 match_beginning = (!frag->oldpos ||2545(frag->oldpos ==1&& !unidiff_zero));25462547/*2548 * A hunk without trailing lines must match at the end.2549 * However, we simply cannot tell if a hunk must match end2550 * from the lack of trailing lines if the patch was generated2551 * with unidiff without any context.2552 */2553 match_end = !unidiff_zero && !trailing;25542555 pos = frag->newpos ? (frag->newpos -1) :0;2556 preimage.buf = oldlines;2557 preimage.len = old - oldlines;2558 postimage.buf = newlines.buf;2559 postimage.len = newlines.len;2560 preimage.line = preimage.line_allocated;2561 postimage.line = postimage.line_allocated;25622563for(;;) {25642565 applied_pos =find_pos(img, &preimage, &postimage, pos,2566 ws_rule, match_beginning, match_end);25672568if(applied_pos >=0)2569break;25702571/* Am I at my context limits? */2572if((leading <= p_context) && (trailing <= p_context))2573break;2574if(match_beginning || match_end) {2575 match_beginning = match_end =0;2576continue;2577}25782579/*2580 * Reduce the number of context lines; reduce both2581 * leading and trailing if they are equal otherwise2582 * just reduce the larger context.2583 */2584if(leading >= trailing) {2585remove_first_line(&preimage);2586remove_first_line(&postimage);2587 pos--;2588 leading--;2589}2590if(trailing > leading) {2591remove_last_line(&preimage);2592remove_last_line(&postimage);2593 trailing--;2594}2595}25962597if(applied_pos >=0) {2598if(new_blank_lines_at_end &&2599 preimage.nr + applied_pos >= img->nr &&2600(ws_rule & WS_BLANK_AT_EOF) &&2601 ws_error_action != nowarn_ws_error) {2602record_ws_error(WS_BLANK_AT_EOF,"+",1, frag->linenr);2603if(ws_error_action == correct_ws_error) {2604while(new_blank_lines_at_end--)2605remove_last_line(&postimage);2606}2607/*2608 * We would want to prevent write_out_results()2609 * from taking place in apply_patch() that follows2610 * the callchain led us here, which is:2611 * apply_patch->check_patch_list->check_patch->2612 * apply_data->apply_fragments->apply_one_fragment2613 */2614if(ws_error_action == die_on_ws_error)2615 apply =0;2616}26172618/*2619 * Warn if it was necessary to reduce the number2620 * of context lines.2621 */2622if((leading != frag->leading) ||2623(trailing != frag->trailing))2624fprintf(stderr,"Context reduced to (%ld/%ld)"2625" to apply fragment at%d\n",2626 leading, trailing, applied_pos+1);2627update_image(img, applied_pos, &preimage, &postimage);2628}else{2629if(apply_verbosely)2630error("while searching for:\n%.*s",2631(int)(old - oldlines), oldlines);2632}26332634free(oldlines);2635strbuf_release(&newlines);2636free(preimage.line_allocated);2637free(postimage.line_allocated);26382639return(applied_pos <0);2640}26412642static intapply_binary_fragment(struct image *img,struct patch *patch)2643{2644struct fragment *fragment = patch->fragments;2645unsigned long len;2646void*dst;26472648/* Binary patch is irreversible without the optional second hunk */2649if(apply_in_reverse) {2650if(!fragment->next)2651returnerror("cannot reverse-apply a binary patch "2652"without the reverse hunk to '%s'",2653 patch->new_name2654? patch->new_name : patch->old_name);2655 fragment = fragment->next;2656}2657switch(fragment->binary_patch_method) {2658case BINARY_DELTA_DEFLATED:2659 dst =patch_delta(img->buf, img->len, fragment->patch,2660 fragment->size, &len);2661if(!dst)2662return-1;2663clear_image(img);2664 img->buf = dst;2665 img->len = len;2666return0;2667case BINARY_LITERAL_DEFLATED:2668clear_image(img);2669 img->len = fragment->size;2670 img->buf =xmalloc(img->len+1);2671memcpy(img->buf, fragment->patch, img->len);2672 img->buf[img->len] ='\0';2673return0;2674}2675return-1;2676}26772678static intapply_binary(struct image *img,struct patch *patch)2679{2680const char*name = patch->old_name ? patch->old_name : patch->new_name;2681unsigned char sha1[20];26822683/*2684 * For safety, we require patch index line to contain2685 * full 40-byte textual SHA1 for old and new, at least for now.2686 */2687if(strlen(patch->old_sha1_prefix) !=40||2688strlen(patch->new_sha1_prefix) !=40||2689get_sha1_hex(patch->old_sha1_prefix, sha1) ||2690get_sha1_hex(patch->new_sha1_prefix, sha1))2691returnerror("cannot apply binary patch to '%s' "2692"without full index line", name);26932694if(patch->old_name) {2695/*2696 * See if the old one matches what the patch2697 * applies to.2698 */2699hash_sha1_file(img->buf, img->len, blob_type, sha1);2700if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2701returnerror("the patch applies to '%s' (%s), "2702"which does not match the "2703"current contents.",2704 name,sha1_to_hex(sha1));2705}2706else{2707/* Otherwise, the old one must be empty. */2708if(img->len)2709returnerror("the patch applies to an empty "2710"'%s' but it is not empty", name);2711}27122713get_sha1_hex(patch->new_sha1_prefix, sha1);2714if(is_null_sha1(sha1)) {2715clear_image(img);2716return0;/* deletion patch */2717}27182719if(has_sha1_file(sha1)) {2720/* We already have the postimage */2721enum object_type type;2722unsigned long size;2723char*result;27242725 result =read_sha1_file(sha1, &type, &size);2726if(!result)2727returnerror("the necessary postimage%sfor "2728"'%s' cannot be read",2729 patch->new_sha1_prefix, name);2730clear_image(img);2731 img->buf = result;2732 img->len = size;2733}else{2734/*2735 * We have verified buf matches the preimage;2736 * apply the patch data to it, which is stored2737 * in the patch->fragments->{patch,size}.2738 */2739if(apply_binary_fragment(img, patch))2740returnerror("binary patch does not apply to '%s'",2741 name);27422743/* verify that the result matches */2744hash_sha1_file(img->buf, img->len, blob_type, sha1);2745if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2746returnerror("binary patch to '%s' creates incorrect result (expecting%s, got%s)",2747 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2748}27492750return0;2751}27522753static intapply_fragments(struct image *img,struct patch *patch)2754{2755struct fragment *frag = patch->fragments;2756const char*name = patch->old_name ? patch->old_name : patch->new_name;2757unsigned ws_rule = patch->ws_rule;2758unsigned inaccurate_eof = patch->inaccurate_eof;27592760if(patch->is_binary)2761returnapply_binary(img, patch);27622763while(frag) {2764if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule)) {2765error("patch failed:%s:%ld", name, frag->oldpos);2766if(!apply_with_reject)2767return-1;2768 frag->rejected =1;2769}2770 frag = frag->next;2771}2772return0;2773}27742775static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2776{2777if(!ce)2778return0;27792780if(S_ISGITLINK(ce->ce_mode)) {2781strbuf_grow(buf,100);2782strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2783}else{2784enum object_type type;2785unsigned long sz;2786char*result;27872788 result =read_sha1_file(ce->sha1, &type, &sz);2789if(!result)2790return-1;2791/* XXX read_sha1_file NUL-terminates */2792strbuf_attach(buf, result, sz, sz +1);2793}2794return0;2795}27962797static struct patch *in_fn_table(const char*name)2798{2799struct string_list_item *item;28002801if(name == NULL)2802return NULL;28032804 item =string_list_lookup(&fn_table, name);2805if(item != NULL)2806return(struct patch *)item->util;28072808return NULL;2809}28102811/*2812 * item->util in the filename table records the status of the path.2813 * Usually it points at a patch (whose result records the contents2814 * of it after applying it), but it could be PATH_WAS_DELETED for a2815 * path that a previously applied patch has already removed.2816 */2817#define PATH_TO_BE_DELETED ((struct patch *) -2)2818#define PATH_WAS_DELETED ((struct patch *) -1)28192820static intto_be_deleted(struct patch *patch)2821{2822return patch == PATH_TO_BE_DELETED;2823}28242825static intwas_deleted(struct patch *patch)2826{2827return patch == PATH_WAS_DELETED;2828}28292830static voidadd_to_fn_table(struct patch *patch)2831{2832struct string_list_item *item;28332834/*2835 * Always add new_name unless patch is a deletion2836 * This should cover the cases for normal diffs,2837 * file creations and copies2838 */2839if(patch->new_name != NULL) {2840 item =string_list_insert(&fn_table, patch->new_name);2841 item->util = patch;2842}28432844/*2845 * store a failure on rename/deletion cases because2846 * later chunks shouldn't patch old names2847 */2848if((patch->new_name == NULL) || (patch->is_rename)) {2849 item =string_list_insert(&fn_table, patch->old_name);2850 item->util = PATH_WAS_DELETED;2851}2852}28532854static voidprepare_fn_table(struct patch *patch)2855{2856/*2857 * store information about incoming file deletion2858 */2859while(patch) {2860if((patch->new_name == NULL) || (patch->is_rename)) {2861struct string_list_item *item;2862 item =string_list_insert(&fn_table, patch->old_name);2863 item->util = PATH_TO_BE_DELETED;2864}2865 patch = patch->next;2866}2867}28682869static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)2870{2871struct strbuf buf = STRBUF_INIT;2872struct image image;2873size_t len;2874char*img;2875struct patch *tpatch;28762877if(!(patch->is_copy || patch->is_rename) &&2878(tpatch =in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {2879if(was_deleted(tpatch)) {2880returnerror("patch%shas been renamed/deleted",2881 patch->old_name);2882}2883/* We have a patched copy in memory use that */2884strbuf_add(&buf, tpatch->result, tpatch->resultsize);2885}else if(cached) {2886if(read_file_or_gitlink(ce, &buf))2887returnerror("read of%sfailed", patch->old_name);2888}else if(patch->old_name) {2889if(S_ISGITLINK(patch->old_mode)) {2890if(ce) {2891read_file_or_gitlink(ce, &buf);2892}else{2893/*2894 * There is no way to apply subproject2895 * patch without looking at the index.2896 */2897 patch->fragments = NULL;2898}2899}else{2900if(read_old_data(st, patch->old_name, &buf))2901returnerror("read of%sfailed", patch->old_name);2902}2903}29042905 img =strbuf_detach(&buf, &len);2906prepare_image(&image, img, len, !patch->is_binary);29072908if(apply_fragments(&image, patch) <0)2909return-1;/* note with --reject this succeeds. */2910 patch->result = image.buf;2911 patch->resultsize = image.len;2912add_to_fn_table(patch);2913free(image.line_allocated);29142915if(0< patch->is_delete && patch->resultsize)2916returnerror("removal patch leaves file contents");29172918return0;2919}29202921static intcheck_to_create_blob(const char*new_name,int ok_if_exists)2922{2923struct stat nst;2924if(!lstat(new_name, &nst)) {2925if(S_ISDIR(nst.st_mode) || ok_if_exists)2926return0;2927/*2928 * A leading component of new_name might be a symlink2929 * that is going to be removed with this patch, but2930 * still pointing at somewhere that has the path.2931 * In such a case, path "new_name" does not exist as2932 * far as git is concerned.2933 */2934if(has_symlink_leading_path(new_name,strlen(new_name)))2935return0;29362937returnerror("%s: already exists in working directory", new_name);2938}2939else if((errno != ENOENT) && (errno != ENOTDIR))2940returnerror("%s:%s", new_name,strerror(errno));2941return0;2942}29432944static intverify_index_match(struct cache_entry *ce,struct stat *st)2945{2946if(S_ISGITLINK(ce->ce_mode)) {2947if(!S_ISDIR(st->st_mode))2948return-1;2949return0;2950}2951returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);2952}29532954static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)2955{2956const char*old_name = patch->old_name;2957struct patch *tpatch = NULL;2958int stat_ret =0;2959unsigned st_mode =0;29602961/*2962 * Make sure that we do not have local modifications from the2963 * index when we are looking at the index. Also make sure2964 * we have the preimage file to be patched in the work tree,2965 * unless --cached, which tells git to apply only in the index.2966 */2967if(!old_name)2968return0;29692970assert(patch->is_new <=0);29712972if(!(patch->is_copy || patch->is_rename) &&2973(tpatch =in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {2974if(was_deleted(tpatch))2975returnerror("%s: has been deleted/renamed", old_name);2976 st_mode = tpatch->new_mode;2977}else if(!cached) {2978 stat_ret =lstat(old_name, st);2979if(stat_ret && errno != ENOENT)2980returnerror("%s:%s", old_name,strerror(errno));2981}29822983if(to_be_deleted(tpatch))2984 tpatch = NULL;29852986if(check_index && !tpatch) {2987int pos =cache_name_pos(old_name,strlen(old_name));2988if(pos <0) {2989if(patch->is_new <0)2990goto is_new;2991returnerror("%s: does not exist in index", old_name);2992}2993*ce = active_cache[pos];2994if(stat_ret <0) {2995struct checkout costate;2996/* checkout */2997memset(&costate,0,sizeof(costate));2998 costate.base_dir ="";2999 costate.refresh_cache =1;3000if(checkout_entry(*ce, &costate, NULL) ||3001lstat(old_name, st))3002return-1;3003}3004if(!cached &&verify_index_match(*ce, st))3005returnerror("%s: does not match index", old_name);3006if(cached)3007 st_mode = (*ce)->ce_mode;3008}else if(stat_ret <0) {3009if(patch->is_new <0)3010goto is_new;3011returnerror("%s:%s", old_name,strerror(errno));3012}30133014if(!cached && !tpatch)3015 st_mode =ce_mode_from_stat(*ce, st->st_mode);30163017if(patch->is_new <0)3018 patch->is_new =0;3019if(!patch->old_mode)3020 patch->old_mode = st_mode;3021if((st_mode ^ patch->old_mode) & S_IFMT)3022returnerror("%s: wrong type", old_name);3023if(st_mode != patch->old_mode)3024warning("%shas type%o, expected%o",3025 old_name, st_mode, patch->old_mode);3026if(!patch->new_mode && !patch->is_delete)3027 patch->new_mode = st_mode;3028return0;30293030 is_new:3031 patch->is_new =1;3032 patch->is_delete =0;3033 patch->old_name = NULL;3034return0;3035}30363037static intcheck_patch(struct patch *patch)3038{3039struct stat st;3040const char*old_name = patch->old_name;3041const char*new_name = patch->new_name;3042const char*name = old_name ? old_name : new_name;3043struct cache_entry *ce = NULL;3044struct patch *tpatch;3045int ok_if_exists;3046int status;30473048 patch->rejected =1;/* we will drop this after we succeed */30493050 status =check_preimage(patch, &ce, &st);3051if(status)3052return status;3053 old_name = patch->old_name;30543055if((tpatch =in_fn_table(new_name)) &&3056(was_deleted(tpatch) ||to_be_deleted(tpatch)))3057/*3058 * A type-change diff is always split into a patch to3059 * delete old, immediately followed by a patch to3060 * create new (see diff.c::run_diff()); in such a case3061 * it is Ok that the entry to be deleted by the3062 * previous patch is still in the working tree and in3063 * the index.3064 */3065 ok_if_exists =1;3066else3067 ok_if_exists =0;30683069if(new_name &&3070((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {3071if(check_index &&3072cache_name_pos(new_name,strlen(new_name)) >=0&&3073!ok_if_exists)3074returnerror("%s: already exists in index", new_name);3075if(!cached) {3076int err =check_to_create_blob(new_name, ok_if_exists);3077if(err)3078return err;3079}3080if(!patch->new_mode) {3081if(0< patch->is_new)3082 patch->new_mode = S_IFREG |0644;3083else3084 patch->new_mode = patch->old_mode;3085}3086}30873088if(new_name && old_name) {3089int same = !strcmp(old_name, new_name);3090if(!patch->new_mode)3091 patch->new_mode = patch->old_mode;3092if((patch->old_mode ^ patch->new_mode) & S_IFMT)3093returnerror("new mode (%o) of%sdoes not match old mode (%o)%s%s",3094 patch->new_mode, new_name, patch->old_mode,3095 same ?"":" of ", same ?"": old_name);3096}30973098if(apply_data(patch, &st, ce) <0)3099returnerror("%s: patch does not apply", name);3100 patch->rejected =0;3101return0;3102}31033104static intcheck_patch_list(struct patch *patch)3105{3106int err =0;31073108prepare_fn_table(patch);3109while(patch) {3110if(apply_verbosely)3111say_patch_name(stderr,3112"Checking patch ", patch,"...\n");3113 err |=check_patch(patch);3114 patch = patch->next;3115}3116return err;3117}31183119/* This function tries to read the sha1 from the current index */3120static intget_current_sha1(const char*path,unsigned char*sha1)3121{3122int pos;31233124if(read_cache() <0)3125return-1;3126 pos =cache_name_pos(path,strlen(path));3127if(pos <0)3128return-1;3129hashcpy(sha1, active_cache[pos]->sha1);3130return0;3131}31323133/* Build an index that contains the just the files needed for a 3way merge */3134static voidbuild_fake_ancestor(struct patch *list,const char*filename)3135{3136struct patch *patch;3137struct index_state result = { NULL };3138int fd;31393140/* Once we start supporting the reverse patch, it may be3141 * worth showing the new sha1 prefix, but until then...3142 */3143for(patch = list; patch; patch = patch->next) {3144const unsigned char*sha1_ptr;3145unsigned char sha1[20];3146struct cache_entry *ce;3147const char*name;31483149 name = patch->old_name ? patch->old_name : patch->new_name;3150if(0< patch->is_new)3151continue;3152else if(get_sha1(patch->old_sha1_prefix, sha1))3153/* git diff has no index line for mode/type changes */3154if(!patch->lines_added && !patch->lines_deleted) {3155if(get_current_sha1(patch->old_name, sha1))3156die("mode change for%s, which is not "3157"in current HEAD", name);3158 sha1_ptr = sha1;3159}else3160die("sha1 information is lacking or useless "3161"(%s).", name);3162else3163 sha1_ptr = sha1;31643165 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);3166if(!ce)3167die("make_cache_entry failed for path '%s'", name);3168if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3169die("Could not add%sto temporary index", name);3170}31713172 fd =open(filename, O_WRONLY | O_CREAT,0666);3173if(fd <0||write_index(&result, fd) ||close(fd))3174die("Could not write temporary index to%s", filename);31753176discard_index(&result);3177}31783179static voidstat_patch_list(struct patch *patch)3180{3181int files, adds, dels;31823183for(files = adds = dels =0; patch ; patch = patch->next) {3184 files++;3185 adds += patch->lines_added;3186 dels += patch->lines_deleted;3187show_stats(patch);3188}31893190printf("%dfiles changed,%dinsertions(+),%ddeletions(-)\n", files, adds, dels);3191}31923193static voidnumstat_patch_list(struct patch *patch)3194{3195for( ; patch; patch = patch->next) {3196const char*name;3197 name = patch->new_name ? patch->new_name : patch->old_name;3198if(patch->is_binary)3199printf("-\t-\t");3200else3201printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3202write_name_quoted(name, stdout, line_termination);3203}3204}32053206static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3207{3208if(mode)3209printf("%smode%06o%s\n", newdelete, mode, name);3210else3211printf("%s %s\n", newdelete, name);3212}32133214static voidshow_mode_change(struct patch *p,int show_name)3215{3216if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3217if(show_name)3218printf(" mode change%06o =>%06o%s\n",3219 p->old_mode, p->new_mode, p->new_name);3220else3221printf(" mode change%06o =>%06o\n",3222 p->old_mode, p->new_mode);3223}3224}32253226static voidshow_rename_copy(struct patch *p)3227{3228const char*renamecopy = p->is_rename ?"rename":"copy";3229const char*old, *new;32303231/* Find common prefix */3232 old = p->old_name;3233new= p->new_name;3234while(1) {3235const char*slash_old, *slash_new;3236 slash_old =strchr(old,'/');3237 slash_new =strchr(new,'/');3238if(!slash_old ||3239!slash_new ||3240 slash_old - old != slash_new -new||3241memcmp(old,new, slash_new -new))3242break;3243 old = slash_old +1;3244new= slash_new +1;3245}3246/* p->old_name thru old is the common prefix, and old and new3247 * through the end of names are renames3248 */3249if(old != p->old_name)3250printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,3251(int)(old - p->old_name), p->old_name,3252 old,new, p->score);3253else3254printf("%s %s=>%s(%d%%)\n", renamecopy,3255 p->old_name, p->new_name, p->score);3256show_mode_change(p,0);3257}32583259static voidsummary_patch_list(struct patch *patch)3260{3261struct patch *p;32623263for(p = patch; p; p = p->next) {3264if(p->is_new)3265show_file_mode_name("create", p->new_mode, p->new_name);3266else if(p->is_delete)3267show_file_mode_name("delete", p->old_mode, p->old_name);3268else{3269if(p->is_rename || p->is_copy)3270show_rename_copy(p);3271else{3272if(p->score) {3273printf(" rewrite%s(%d%%)\n",3274 p->new_name, p->score);3275show_mode_change(p,0);3276}3277else3278show_mode_change(p,1);3279}3280}3281}3282}32833284static voidpatch_stats(struct patch *patch)3285{3286int lines = patch->lines_added + patch->lines_deleted;32873288if(lines > max_change)3289 max_change = lines;3290if(patch->old_name) {3291int len =quote_c_style(patch->old_name, NULL, NULL,0);3292if(!len)3293 len =strlen(patch->old_name);3294if(len > max_len)3295 max_len = len;3296}3297if(patch->new_name) {3298int len =quote_c_style(patch->new_name, NULL, NULL,0);3299if(!len)3300 len =strlen(patch->new_name);3301if(len > max_len)3302 max_len = len;3303}3304}33053306static voidremove_file(struct patch *patch,int rmdir_empty)3307{3308if(update_index) {3309if(remove_file_from_cache(patch->old_name) <0)3310die("unable to remove%sfrom index", patch->old_name);3311}3312if(!cached) {3313if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {3314remove_path(patch->old_name);3315}3316}3317}33183319static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)3320{3321struct stat st;3322struct cache_entry *ce;3323int namelen =strlen(path);3324unsigned ce_size =cache_entry_size(namelen);33253326if(!update_index)3327return;33283329 ce =xcalloc(1, ce_size);3330memcpy(ce->name, path, namelen);3331 ce->ce_mode =create_ce_mode(mode);3332 ce->ce_flags = namelen;3333if(S_ISGITLINK(mode)) {3334const char*s = buf;33353336if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))3337die("corrupt patch for subproject%s", path);3338}else{3339if(!cached) {3340if(lstat(path, &st) <0)3341die_errno("unable to stat newly created file '%s'",3342 path);3343fill_stat_cache_info(ce, &st);3344}3345if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)3346die("unable to create backing store for newly created file%s", path);3347}3348if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3349die("unable to add cache entry for%s", path);3350}33513352static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)3353{3354int fd;3355struct strbuf nbuf = STRBUF_INIT;33563357if(S_ISGITLINK(mode)) {3358struct stat st;3359if(!lstat(path, &st) &&S_ISDIR(st.st_mode))3360return0;3361returnmkdir(path,0777);3362}33633364if(has_symlinks &&S_ISLNK(mode))3365/* Although buf:size is counted string, it also is NUL3366 * terminated.3367 */3368returnsymlink(buf, path);33693370 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);3371if(fd <0)3372return-1;33733374if(convert_to_working_tree(path, buf, size, &nbuf)) {3375 size = nbuf.len;3376 buf = nbuf.buf;3377}3378write_or_die(fd, buf, size);3379strbuf_release(&nbuf);33803381if(close(fd) <0)3382die_errno("closing file '%s'", path);3383return0;3384}33853386/*3387 * We optimistically assume that the directories exist,3388 * which is true 99% of the time anyway. If they don't,3389 * we create them and try again.3390 */3391static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)3392{3393if(cached)3394return;3395if(!try_create_file(path, mode, buf, size))3396return;33973398if(errno == ENOENT) {3399if(safe_create_leading_directories(path))3400return;3401if(!try_create_file(path, mode, buf, size))3402return;3403}34043405if(errno == EEXIST || errno == EACCES) {3406/* We may be trying to create a file where a directory3407 * used to be.3408 */3409struct stat st;3410if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))3411 errno = EEXIST;3412}34133414if(errno == EEXIST) {3415unsigned int nr =getpid();34163417for(;;) {3418char newpath[PATH_MAX];3419mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);3420if(!try_create_file(newpath, mode, buf, size)) {3421if(!rename(newpath, path))3422return;3423unlink_or_warn(newpath);3424break;3425}3426if(errno != EEXIST)3427break;3428++nr;3429}3430}3431die_errno("unable to write file '%s' mode%o", path, mode);3432}34333434static voidcreate_file(struct patch *patch)3435{3436char*path = patch->new_name;3437unsigned mode = patch->new_mode;3438unsigned long size = patch->resultsize;3439char*buf = patch->result;34403441if(!mode)3442 mode = S_IFREG |0644;3443create_one_file(path, mode, buf, size);3444add_index_file(path, mode, buf, size);3445}34463447/* phase zero is to remove, phase one is to create */3448static voidwrite_out_one_result(struct patch *patch,int phase)3449{3450if(patch->is_delete >0) {3451if(phase ==0)3452remove_file(patch,1);3453return;3454}3455if(patch->is_new >0|| patch->is_copy) {3456if(phase ==1)3457create_file(patch);3458return;3459}3460/*3461 * Rename or modification boils down to the same3462 * thing: remove the old, write the new3463 */3464if(phase ==0)3465remove_file(patch, patch->is_rename);3466if(phase ==1)3467create_file(patch);3468}34693470static intwrite_out_one_reject(struct patch *patch)3471{3472FILE*rej;3473char namebuf[PATH_MAX];3474struct fragment *frag;3475int cnt =0;34763477for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {3478if(!frag->rejected)3479continue;3480 cnt++;3481}34823483if(!cnt) {3484if(apply_verbosely)3485say_patch_name(stderr,3486"Applied patch ", patch," cleanly.\n");3487return0;3488}34893490/* This should not happen, because a removal patch that leaves3491 * contents are marked "rejected" at the patch level.3492 */3493if(!patch->new_name)3494die("internal error");34953496/* Say this even without --verbose */3497say_patch_name(stderr,"Applying patch ", patch," with");3498fprintf(stderr,"%drejects...\n", cnt);34993500 cnt =strlen(patch->new_name);3501if(ARRAY_SIZE(namebuf) <= cnt +5) {3502 cnt =ARRAY_SIZE(namebuf) -5;3503warning("truncating .rej filename to %.*s.rej",3504 cnt -1, patch->new_name);3505}3506memcpy(namebuf, patch->new_name, cnt);3507memcpy(namebuf + cnt,".rej",5);35083509 rej =fopen(namebuf,"w");3510if(!rej)3511returnerror("cannot open%s:%s", namebuf,strerror(errno));35123513/* Normal git tools never deal with .rej, so do not pretend3514 * this is a git patch by saying --git nor give extended3515 * headers. While at it, maybe please "kompare" that wants3516 * the trailing TAB and some garbage at the end of line ;-).3517 */3518fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",3519 patch->new_name, patch->new_name);3520for(cnt =1, frag = patch->fragments;3521 frag;3522 cnt++, frag = frag->next) {3523if(!frag->rejected) {3524fprintf(stderr,"Hunk #%dapplied cleanly.\n", cnt);3525continue;3526}3527fprintf(stderr,"Rejected hunk #%d.\n", cnt);3528fprintf(rej,"%.*s", frag->size, frag->patch);3529if(frag->patch[frag->size-1] !='\n')3530fputc('\n', rej);3531}3532fclose(rej);3533return-1;3534}35353536static intwrite_out_results(struct patch *list,int skipped_patch)3537{3538int phase;3539int errs =0;3540struct patch *l;35413542if(!list && !skipped_patch)3543returnerror("No changes");35443545for(phase =0; phase <2; phase++) {3546 l = list;3547while(l) {3548if(l->rejected)3549 errs =1;3550else{3551write_out_one_result(l, phase);3552if(phase ==1&&write_out_one_reject(l))3553 errs =1;3554}3555 l = l->next;3556}3557}3558return errs;3559}35603561static struct lock_file lock_file;35623563static struct string_list limit_by_name;3564static int has_include;3565static voidadd_name_limit(const char*name,int exclude)3566{3567struct string_list_item *it;35683569 it =string_list_append(&limit_by_name, name);3570 it->util = exclude ? NULL : (void*)1;3571}35723573static intuse_patch(struct patch *p)3574{3575const char*pathname = p->new_name ? p->new_name : p->old_name;3576int i;35773578/* Paths outside are not touched regardless of "--include" */3579if(0< prefix_length) {3580int pathlen =strlen(pathname);3581if(pathlen <= prefix_length ||3582memcmp(prefix, pathname, prefix_length))3583return0;3584}35853586/* See if it matches any of exclude/include rule */3587for(i =0; i < limit_by_name.nr; i++) {3588struct string_list_item *it = &limit_by_name.items[i];3589if(!fnmatch(it->string, pathname,0))3590return(it->util != NULL);3591}35923593/*3594 * If we had any include, a path that does not match any rule is3595 * not used. Otherwise, we saw bunch of exclude rules (or none)3596 * and such a path is used.3597 */3598return!has_include;3599}360036013602static voidprefix_one(char**name)3603{3604char*old_name = *name;3605if(!old_name)3606return;3607*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3608free(old_name);3609}36103611static voidprefix_patches(struct patch *p)3612{3613if(!prefix || p->is_toplevel_relative)3614return;3615for( ; p; p = p->next) {3616if(p->new_name == p->old_name) {3617char*prefixed = p->new_name;3618prefix_one(&prefixed);3619 p->new_name = p->old_name = prefixed;3620}3621else{3622prefix_one(&p->new_name);3623prefix_one(&p->old_name);3624}3625}3626}36273628#define INACCURATE_EOF (1<<0)3629#define RECOUNT (1<<1)36303631static intapply_patch(int fd,const char*filename,int options)3632{3633size_t offset;3634struct strbuf buf = STRBUF_INIT;3635struct patch *list = NULL, **listp = &list;3636int skipped_patch =0;36373638/* FIXME - memory leak when using multiple patch files as inputs */3639memset(&fn_table,0,sizeof(struct string_list));3640 patch_input_file = filename;3641read_patch_file(&buf, fd);3642 offset =0;3643while(offset < buf.len) {3644struct patch *patch;3645int nr;36463647 patch =xcalloc(1,sizeof(*patch));3648 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3649 patch->recount = !!(options & RECOUNT);3650 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3651if(nr <0)3652break;3653if(apply_in_reverse)3654reverse_patches(patch);3655if(prefix)3656prefix_patches(patch);3657if(use_patch(patch)) {3658patch_stats(patch);3659*listp = patch;3660 listp = &patch->next;3661}3662else{3663/* perhaps free it a bit better? */3664free(patch);3665 skipped_patch++;3666}3667 offset += nr;3668}36693670if(whitespace_error && (ws_error_action == die_on_ws_error))3671 apply =0;36723673 update_index = check_index && apply;3674if(update_index && newfd <0)3675 newfd =hold_locked_index(&lock_file,1);36763677if(check_index) {3678if(read_cache() <0)3679die("unable to read index file");3680}36813682if((check || apply) &&3683check_patch_list(list) <0&&3684!apply_with_reject)3685exit(1);36863687if(apply &&write_out_results(list, skipped_patch))3688exit(1);36893690if(fake_ancestor)3691build_fake_ancestor(list, fake_ancestor);36923693if(diffstat)3694stat_patch_list(list);36953696if(numstat)3697numstat_patch_list(list);36983699if(summary)3700summary_patch_list(list);37013702strbuf_release(&buf);3703return0;3704}37053706static intgit_apply_config(const char*var,const char*value,void*cb)3707{3708if(!strcmp(var,"apply.whitespace"))3709returngit_config_string(&apply_default_whitespace, var, value);3710else if(!strcmp(var,"apply.ignorewhitespace"))3711returngit_config_string(&apply_default_ignorewhitespace, var, value);3712returngit_default_config(var, value, cb);3713}37143715static intoption_parse_exclude(const struct option *opt,3716const char*arg,int unset)3717{3718add_name_limit(arg,1);3719return0;3720}37213722static intoption_parse_include(const struct option *opt,3723const char*arg,int unset)3724{3725add_name_limit(arg,0);3726 has_include =1;3727return0;3728}37293730static intoption_parse_p(const struct option *opt,3731const char*arg,int unset)3732{3733 p_value =atoi(arg);3734 p_value_known =1;3735return0;3736}37373738static intoption_parse_z(const struct option *opt,3739const char*arg,int unset)3740{3741if(unset)3742 line_termination ='\n';3743else3744 line_termination =0;3745return0;3746}37473748static intoption_parse_space_change(const struct option *opt,3749const char*arg,int unset)3750{3751if(unset)3752 ws_ignore_action = ignore_ws_none;3753else3754 ws_ignore_action = ignore_ws_change;3755return0;3756}37573758static intoption_parse_whitespace(const struct option *opt,3759const char*arg,int unset)3760{3761const char**whitespace_option = opt->value;37623763*whitespace_option = arg;3764parse_whitespace_option(arg);3765return0;3766}37673768static intoption_parse_directory(const struct option *opt,3769const char*arg,int unset)3770{3771 root_len =strlen(arg);3772if(root_len && arg[root_len -1] !='/') {3773char*new_root;3774 root = new_root =xmalloc(root_len +2);3775strcpy(new_root, arg);3776strcpy(new_root + root_len++,"/");3777}else3778 root = arg;3779return0;3780}37813782intcmd_apply(int argc,const char**argv,const char*prefix_)3783{3784int i;3785int errs =0;3786int is_not_gitdir = !startup_info->have_repository;3787int binary;3788int force_apply =0;37893790const char*whitespace_option = NULL;37913792struct option builtin_apply_options[] = {3793{ OPTION_CALLBACK,0,"exclude", NULL,"path",3794"don't apply changes matching the given path",37950, option_parse_exclude },3796{ OPTION_CALLBACK,0,"include", NULL,"path",3797"apply changes matching the given path",37980, option_parse_include },3799{ OPTION_CALLBACK,'p', NULL, NULL,"num",3800"remove <num> leading slashes from traditional diff paths",38010, option_parse_p },3802OPT_BOOLEAN(0,"no-add", &no_add,3803"ignore additions made by the patch"),3804OPT_BOOLEAN(0,"stat", &diffstat,3805"instead of applying the patch, output diffstat for the input"),3806{ OPTION_BOOLEAN,0,"allow-binary-replacement", &binary,3807 NULL,"old option, now no-op",3808 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3809{ OPTION_BOOLEAN,0,"binary", &binary,3810 NULL,"old option, now no-op",3811 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3812OPT_BOOLEAN(0,"numstat", &numstat,3813"shows number of added and deleted lines in decimal notation"),3814OPT_BOOLEAN(0,"summary", &summary,3815"instead of applying the patch, output a summary for the input"),3816OPT_BOOLEAN(0,"check", &check,3817"instead of applying the patch, see if the patch is applicable"),3818OPT_BOOLEAN(0,"index", &check_index,3819"make sure the patch is applicable to the current index"),3820OPT_BOOLEAN(0,"cached", &cached,3821"apply a patch without touching the working tree"),3822OPT_BOOLEAN(0,"apply", &force_apply,3823"also apply the patch (use with --stat/--summary/--check)"),3824OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,3825"build a temporary index based on embedded index information"),3826{ OPTION_CALLBACK,'z', NULL, NULL, NULL,3827"paths are separated with NUL character",3828 PARSE_OPT_NOARG, option_parse_z },3829OPT_INTEGER('C', NULL, &p_context,3830"ensure at least <n> lines of context match"),3831{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,"action",3832"detect new or modified lines that have whitespace errors",38330, option_parse_whitespace },3834{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,3835"ignore changes in whitespace when finding context",3836 PARSE_OPT_NOARG, option_parse_space_change },3837{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,3838"ignore changes in whitespace when finding context",3839 PARSE_OPT_NOARG, option_parse_space_change },3840OPT_BOOLEAN('R',"reverse", &apply_in_reverse,3841"apply the patch in reverse"),3842OPT_BOOLEAN(0,"unidiff-zero", &unidiff_zero,3843"don't expect at least one line of context"),3844OPT_BOOLEAN(0,"reject", &apply_with_reject,3845"leave the rejected hunks in corresponding *.rej files"),3846OPT__VERBOSE(&apply_verbosely),3847OPT_BIT(0,"inaccurate-eof", &options,3848"tolerate incorrectly detected missing new-line at the end of file",3849 INACCURATE_EOF),3850OPT_BIT(0,"recount", &options,3851"do not trust the line counts in the hunk headers",3852 RECOUNT),3853{ OPTION_CALLBACK,0,"directory", NULL,"root",3854"prepend <root> to all filenames",38550, option_parse_directory },3856OPT_END()3857};38583859 prefix = prefix_;3860 prefix_length = prefix ?strlen(prefix) :0;3861git_config(git_apply_config, NULL);3862if(apply_default_whitespace)3863parse_whitespace_option(apply_default_whitespace);3864if(apply_default_ignorewhitespace)3865parse_ignorewhitespace_option(apply_default_ignorewhitespace);38663867 argc =parse_options(argc, argv, prefix, builtin_apply_options,3868 apply_usage,0);38693870if(apply_with_reject)3871 apply = apply_verbosely =1;3872if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))3873 apply =0;3874if(check_index && is_not_gitdir)3875die("--index outside a repository");3876if(cached) {3877if(is_not_gitdir)3878die("--cached outside a repository");3879 check_index =1;3880}3881for(i =0; i < argc; i++) {3882const char*arg = argv[i];3883int fd;38843885if(!strcmp(arg,"-")) {3886 errs |=apply_patch(0,"<stdin>", options);3887 read_stdin =0;3888continue;3889}else if(0< prefix_length)3890 arg =prefix_filename(prefix, prefix_length, arg);38913892 fd =open(arg, O_RDONLY);3893if(fd <0)3894die_errno("can't open patch '%s'", arg);3895 read_stdin =0;3896set_default_whitespace_mode(whitespace_option);3897 errs |=apply_patch(fd, arg, options);3898close(fd);3899}3900set_default_whitespace_mode(whitespace_option);3901if(read_stdin)3902 errs |=apply_patch(0,"<stdin>", options);3903if(whitespace_error) {3904if(squelch_whitespace_errors &&3905 squelch_whitespace_errors < whitespace_error) {3906int squelched =3907 whitespace_error - squelch_whitespace_errors;3908warning("squelched%d"3909"whitespace error%s",3910 squelched,3911 squelched ==1?"":"s");3912}3913if(ws_error_action == die_on_ws_error)3914die("%dline%sadd%swhitespace errors.",3915 whitespace_error,3916 whitespace_error ==1?"":"s",3917 whitespace_error ==1?"s":"");3918if(applied_after_fixing_ws && apply)3919warning("%dline%sapplied after"3920" fixing whitespace errors.",3921 applied_after_fixing_ws,3922 applied_after_fixing_ws ==1?"":"s");3923else if(whitespace_error)3924warning("%dline%sadd%swhitespace errors.",3925 whitespace_error,3926 whitespace_error ==1?"":"s",3927 whitespace_error ==1?"s":"");3928}39293930if(update_index) {3931if(write_cache(newfd, active_cache, active_nr) ||3932commit_locked_index(&lock_file))3933die("Unable to write new index file");3934}39353936return!!errs;3937}