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;26472648if(!fragment)2649returnerror("missing binary patch data for '%s'",2650 patch->new_name ?2651 patch->new_name :2652 patch->old_name);26532654/* Binary patch is irreversible without the optional second hunk */2655if(apply_in_reverse) {2656if(!fragment->next)2657returnerror("cannot reverse-apply a binary patch "2658"without the reverse hunk to '%s'",2659 patch->new_name2660? patch->new_name : patch->old_name);2661 fragment = fragment->next;2662}2663switch(fragment->binary_patch_method) {2664case BINARY_DELTA_DEFLATED:2665 dst =patch_delta(img->buf, img->len, fragment->patch,2666 fragment->size, &len);2667if(!dst)2668return-1;2669clear_image(img);2670 img->buf = dst;2671 img->len = len;2672return0;2673case BINARY_LITERAL_DEFLATED:2674clear_image(img);2675 img->len = fragment->size;2676 img->buf =xmalloc(img->len+1);2677memcpy(img->buf, fragment->patch, img->len);2678 img->buf[img->len] ='\0';2679return0;2680}2681return-1;2682}26832684static intapply_binary(struct image *img,struct patch *patch)2685{2686const char*name = patch->old_name ? patch->old_name : patch->new_name;2687unsigned char sha1[20];26882689/*2690 * For safety, we require patch index line to contain2691 * full 40-byte textual SHA1 for old and new, at least for now.2692 */2693if(strlen(patch->old_sha1_prefix) !=40||2694strlen(patch->new_sha1_prefix) !=40||2695get_sha1_hex(patch->old_sha1_prefix, sha1) ||2696get_sha1_hex(patch->new_sha1_prefix, sha1))2697returnerror("cannot apply binary patch to '%s' "2698"without full index line", name);26992700if(patch->old_name) {2701/*2702 * See if the old one matches what the patch2703 * applies to.2704 */2705hash_sha1_file(img->buf, img->len, blob_type, sha1);2706if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2707returnerror("the patch applies to '%s' (%s), "2708"which does not match the "2709"current contents.",2710 name,sha1_to_hex(sha1));2711}2712else{2713/* Otherwise, the old one must be empty. */2714if(img->len)2715returnerror("the patch applies to an empty "2716"'%s' but it is not empty", name);2717}27182719get_sha1_hex(patch->new_sha1_prefix, sha1);2720if(is_null_sha1(sha1)) {2721clear_image(img);2722return0;/* deletion patch */2723}27242725if(has_sha1_file(sha1)) {2726/* We already have the postimage */2727enum object_type type;2728unsigned long size;2729char*result;27302731 result =read_sha1_file(sha1, &type, &size);2732if(!result)2733returnerror("the necessary postimage%sfor "2734"'%s' cannot be read",2735 patch->new_sha1_prefix, name);2736clear_image(img);2737 img->buf = result;2738 img->len = size;2739}else{2740/*2741 * We have verified buf matches the preimage;2742 * apply the patch data to it, which is stored2743 * in the patch->fragments->{patch,size}.2744 */2745if(apply_binary_fragment(img, patch))2746returnerror("binary patch does not apply to '%s'",2747 name);27482749/* verify that the result matches */2750hash_sha1_file(img->buf, img->len, blob_type, sha1);2751if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2752returnerror("binary patch to '%s' creates incorrect result (expecting%s, got%s)",2753 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2754}27552756return0;2757}27582759static intapply_fragments(struct image *img,struct patch *patch)2760{2761struct fragment *frag = patch->fragments;2762const char*name = patch->old_name ? patch->old_name : patch->new_name;2763unsigned ws_rule = patch->ws_rule;2764unsigned inaccurate_eof = patch->inaccurate_eof;27652766if(patch->is_binary)2767returnapply_binary(img, patch);27682769while(frag) {2770if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule)) {2771error("patch failed:%s:%ld", name, frag->oldpos);2772if(!apply_with_reject)2773return-1;2774 frag->rejected =1;2775}2776 frag = frag->next;2777}2778return0;2779}27802781static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2782{2783if(!ce)2784return0;27852786if(S_ISGITLINK(ce->ce_mode)) {2787strbuf_grow(buf,100);2788strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2789}else{2790enum object_type type;2791unsigned long sz;2792char*result;27932794 result =read_sha1_file(ce->sha1, &type, &sz);2795if(!result)2796return-1;2797/* XXX read_sha1_file NUL-terminates */2798strbuf_attach(buf, result, sz, sz +1);2799}2800return0;2801}28022803static struct patch *in_fn_table(const char*name)2804{2805struct string_list_item *item;28062807if(name == NULL)2808return NULL;28092810 item =string_list_lookup(&fn_table, name);2811if(item != NULL)2812return(struct patch *)item->util;28132814return NULL;2815}28162817/*2818 * item->util in the filename table records the status of the path.2819 * Usually it points at a patch (whose result records the contents2820 * of it after applying it), but it could be PATH_WAS_DELETED for a2821 * path that a previously applied patch has already removed.2822 */2823#define PATH_TO_BE_DELETED ((struct patch *) -2)2824#define PATH_WAS_DELETED ((struct patch *) -1)28252826static intto_be_deleted(struct patch *patch)2827{2828return patch == PATH_TO_BE_DELETED;2829}28302831static intwas_deleted(struct patch *patch)2832{2833return patch == PATH_WAS_DELETED;2834}28352836static voidadd_to_fn_table(struct patch *patch)2837{2838struct string_list_item *item;28392840/*2841 * Always add new_name unless patch is a deletion2842 * This should cover the cases for normal diffs,2843 * file creations and copies2844 */2845if(patch->new_name != NULL) {2846 item =string_list_insert(&fn_table, patch->new_name);2847 item->util = patch;2848}28492850/*2851 * store a failure on rename/deletion cases because2852 * later chunks shouldn't patch old names2853 */2854if((patch->new_name == NULL) || (patch->is_rename)) {2855 item =string_list_insert(&fn_table, patch->old_name);2856 item->util = PATH_WAS_DELETED;2857}2858}28592860static voidprepare_fn_table(struct patch *patch)2861{2862/*2863 * store information about incoming file deletion2864 */2865while(patch) {2866if((patch->new_name == NULL) || (patch->is_rename)) {2867struct string_list_item *item;2868 item =string_list_insert(&fn_table, patch->old_name);2869 item->util = PATH_TO_BE_DELETED;2870}2871 patch = patch->next;2872}2873}28742875static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)2876{2877struct strbuf buf = STRBUF_INIT;2878struct image image;2879size_t len;2880char*img;2881struct patch *tpatch;28822883if(!(patch->is_copy || patch->is_rename) &&2884(tpatch =in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {2885if(was_deleted(tpatch)) {2886returnerror("patch%shas been renamed/deleted",2887 patch->old_name);2888}2889/* We have a patched copy in memory use that */2890strbuf_add(&buf, tpatch->result, tpatch->resultsize);2891}else if(cached) {2892if(read_file_or_gitlink(ce, &buf))2893returnerror("read of%sfailed", patch->old_name);2894}else if(patch->old_name) {2895if(S_ISGITLINK(patch->old_mode)) {2896if(ce) {2897read_file_or_gitlink(ce, &buf);2898}else{2899/*2900 * There is no way to apply subproject2901 * patch without looking at the index.2902 */2903 patch->fragments = NULL;2904}2905}else{2906if(read_old_data(st, patch->old_name, &buf))2907returnerror("read of%sfailed", patch->old_name);2908}2909}29102911 img =strbuf_detach(&buf, &len);2912prepare_image(&image, img, len, !patch->is_binary);29132914if(apply_fragments(&image, patch) <0)2915return-1;/* note with --reject this succeeds. */2916 patch->result = image.buf;2917 patch->resultsize = image.len;2918add_to_fn_table(patch);2919free(image.line_allocated);29202921if(0< patch->is_delete && patch->resultsize)2922returnerror("removal patch leaves file contents");29232924return0;2925}29262927static intcheck_to_create_blob(const char*new_name,int ok_if_exists)2928{2929struct stat nst;2930if(!lstat(new_name, &nst)) {2931if(S_ISDIR(nst.st_mode) || ok_if_exists)2932return0;2933/*2934 * A leading component of new_name might be a symlink2935 * that is going to be removed with this patch, but2936 * still pointing at somewhere that has the path.2937 * In such a case, path "new_name" does not exist as2938 * far as git is concerned.2939 */2940if(has_symlink_leading_path(new_name,strlen(new_name)))2941return0;29422943returnerror("%s: already exists in working directory", new_name);2944}2945else if((errno != ENOENT) && (errno != ENOTDIR))2946returnerror("%s:%s", new_name,strerror(errno));2947return0;2948}29492950static intverify_index_match(struct cache_entry *ce,struct stat *st)2951{2952if(S_ISGITLINK(ce->ce_mode)) {2953if(!S_ISDIR(st->st_mode))2954return-1;2955return0;2956}2957returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);2958}29592960static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)2961{2962const char*old_name = patch->old_name;2963struct patch *tpatch = NULL;2964int stat_ret =0;2965unsigned st_mode =0;29662967/*2968 * Make sure that we do not have local modifications from the2969 * index when we are looking at the index. Also make sure2970 * we have the preimage file to be patched in the work tree,2971 * unless --cached, which tells git to apply only in the index.2972 */2973if(!old_name)2974return0;29752976assert(patch->is_new <=0);29772978if(!(patch->is_copy || patch->is_rename) &&2979(tpatch =in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {2980if(was_deleted(tpatch))2981returnerror("%s: has been deleted/renamed", old_name);2982 st_mode = tpatch->new_mode;2983}else if(!cached) {2984 stat_ret =lstat(old_name, st);2985if(stat_ret && errno != ENOENT)2986returnerror("%s:%s", old_name,strerror(errno));2987}29882989if(to_be_deleted(tpatch))2990 tpatch = NULL;29912992if(check_index && !tpatch) {2993int pos =cache_name_pos(old_name,strlen(old_name));2994if(pos <0) {2995if(patch->is_new <0)2996goto is_new;2997returnerror("%s: does not exist in index", old_name);2998}2999*ce = active_cache[pos];3000if(stat_ret <0) {3001struct checkout costate;3002/* checkout */3003memset(&costate,0,sizeof(costate));3004 costate.base_dir ="";3005 costate.refresh_cache =1;3006if(checkout_entry(*ce, &costate, NULL) ||3007lstat(old_name, st))3008return-1;3009}3010if(!cached &&verify_index_match(*ce, st))3011returnerror("%s: does not match index", old_name);3012if(cached)3013 st_mode = (*ce)->ce_mode;3014}else if(stat_ret <0) {3015if(patch->is_new <0)3016goto is_new;3017returnerror("%s:%s", old_name,strerror(errno));3018}30193020if(!cached && !tpatch)3021 st_mode =ce_mode_from_stat(*ce, st->st_mode);30223023if(patch->is_new <0)3024 patch->is_new =0;3025if(!patch->old_mode)3026 patch->old_mode = st_mode;3027if((st_mode ^ patch->old_mode) & S_IFMT)3028returnerror("%s: wrong type", old_name);3029if(st_mode != patch->old_mode)3030warning("%shas type%o, expected%o",3031 old_name, st_mode, patch->old_mode);3032if(!patch->new_mode && !patch->is_delete)3033 patch->new_mode = st_mode;3034return0;30353036 is_new:3037 patch->is_new =1;3038 patch->is_delete =0;3039 patch->old_name = NULL;3040return0;3041}30423043static intcheck_patch(struct patch *patch)3044{3045struct stat st;3046const char*old_name = patch->old_name;3047const char*new_name = patch->new_name;3048const char*name = old_name ? old_name : new_name;3049struct cache_entry *ce = NULL;3050struct patch *tpatch;3051int ok_if_exists;3052int status;30533054 patch->rejected =1;/* we will drop this after we succeed */30553056 status =check_preimage(patch, &ce, &st);3057if(status)3058return status;3059 old_name = patch->old_name;30603061if((tpatch =in_fn_table(new_name)) &&3062(was_deleted(tpatch) ||to_be_deleted(tpatch)))3063/*3064 * A type-change diff is always split into a patch to3065 * delete old, immediately followed by a patch to3066 * create new (see diff.c::run_diff()); in such a case3067 * it is Ok that the entry to be deleted by the3068 * previous patch is still in the working tree and in3069 * the index.3070 */3071 ok_if_exists =1;3072else3073 ok_if_exists =0;30743075if(new_name &&3076((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {3077if(check_index &&3078cache_name_pos(new_name,strlen(new_name)) >=0&&3079!ok_if_exists)3080returnerror("%s: already exists in index", new_name);3081if(!cached) {3082int err =check_to_create_blob(new_name, ok_if_exists);3083if(err)3084return err;3085}3086if(!patch->new_mode) {3087if(0< patch->is_new)3088 patch->new_mode = S_IFREG |0644;3089else3090 patch->new_mode = patch->old_mode;3091}3092}30933094if(new_name && old_name) {3095int same = !strcmp(old_name, new_name);3096if(!patch->new_mode)3097 patch->new_mode = patch->old_mode;3098if((patch->old_mode ^ patch->new_mode) & S_IFMT)3099returnerror("new mode (%o) of%sdoes not match old mode (%o)%s%s",3100 patch->new_mode, new_name, patch->old_mode,3101 same ?"":" of ", same ?"": old_name);3102}31033104if(apply_data(patch, &st, ce) <0)3105returnerror("%s: patch does not apply", name);3106 patch->rejected =0;3107return0;3108}31093110static intcheck_patch_list(struct patch *patch)3111{3112int err =0;31133114prepare_fn_table(patch);3115while(patch) {3116if(apply_verbosely)3117say_patch_name(stderr,3118"Checking patch ", patch,"...\n");3119 err |=check_patch(patch);3120 patch = patch->next;3121}3122return err;3123}31243125/* This function tries to read the sha1 from the current index */3126static intget_current_sha1(const char*path,unsigned char*sha1)3127{3128int pos;31293130if(read_cache() <0)3131return-1;3132 pos =cache_name_pos(path,strlen(path));3133if(pos <0)3134return-1;3135hashcpy(sha1, active_cache[pos]->sha1);3136return0;3137}31383139/* Build an index that contains the just the files needed for a 3way merge */3140static voidbuild_fake_ancestor(struct patch *list,const char*filename)3141{3142struct patch *patch;3143struct index_state result = { NULL };3144int fd;31453146/* Once we start supporting the reverse patch, it may be3147 * worth showing the new sha1 prefix, but until then...3148 */3149for(patch = list; patch; patch = patch->next) {3150const unsigned char*sha1_ptr;3151unsigned char sha1[20];3152struct cache_entry *ce;3153const char*name;31543155 name = patch->old_name ? patch->old_name : patch->new_name;3156if(0< patch->is_new)3157continue;3158else if(get_sha1(patch->old_sha1_prefix, sha1))3159/* git diff has no index line for mode/type changes */3160if(!patch->lines_added && !patch->lines_deleted) {3161if(get_current_sha1(patch->old_name, sha1))3162die("mode change for%s, which is not "3163"in current HEAD", name);3164 sha1_ptr = sha1;3165}else3166die("sha1 information is lacking or useless "3167"(%s).", name);3168else3169 sha1_ptr = sha1;31703171 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);3172if(!ce)3173die("make_cache_entry failed for path '%s'", name);3174if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3175die("Could not add%sto temporary index", name);3176}31773178 fd =open(filename, O_WRONLY | O_CREAT,0666);3179if(fd <0||write_index(&result, fd) ||close(fd))3180die("Could not write temporary index to%s", filename);31813182discard_index(&result);3183}31843185static voidstat_patch_list(struct patch *patch)3186{3187int files, adds, dels;31883189for(files = adds = dels =0; patch ; patch = patch->next) {3190 files++;3191 adds += patch->lines_added;3192 dels += patch->lines_deleted;3193show_stats(patch);3194}31953196printf("%dfiles changed,%dinsertions(+),%ddeletions(-)\n", files, adds, dels);3197}31983199static voidnumstat_patch_list(struct patch *patch)3200{3201for( ; patch; patch = patch->next) {3202const char*name;3203 name = patch->new_name ? patch->new_name : patch->old_name;3204if(patch->is_binary)3205printf("-\t-\t");3206else3207printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3208write_name_quoted(name, stdout, line_termination);3209}3210}32113212static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3213{3214if(mode)3215printf("%smode%06o%s\n", newdelete, mode, name);3216else3217printf("%s %s\n", newdelete, name);3218}32193220static voidshow_mode_change(struct patch *p,int show_name)3221{3222if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3223if(show_name)3224printf(" mode change%06o =>%06o%s\n",3225 p->old_mode, p->new_mode, p->new_name);3226else3227printf(" mode change%06o =>%06o\n",3228 p->old_mode, p->new_mode);3229}3230}32313232static voidshow_rename_copy(struct patch *p)3233{3234const char*renamecopy = p->is_rename ?"rename":"copy";3235const char*old, *new;32363237/* Find common prefix */3238 old = p->old_name;3239new= p->new_name;3240while(1) {3241const char*slash_old, *slash_new;3242 slash_old =strchr(old,'/');3243 slash_new =strchr(new,'/');3244if(!slash_old ||3245!slash_new ||3246 slash_old - old != slash_new -new||3247memcmp(old,new, slash_new -new))3248break;3249 old = slash_old +1;3250new= slash_new +1;3251}3252/* p->old_name thru old is the common prefix, and old and new3253 * through the end of names are renames3254 */3255if(old != p->old_name)3256printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,3257(int)(old - p->old_name), p->old_name,3258 old,new, p->score);3259else3260printf("%s %s=>%s(%d%%)\n", renamecopy,3261 p->old_name, p->new_name, p->score);3262show_mode_change(p,0);3263}32643265static voidsummary_patch_list(struct patch *patch)3266{3267struct patch *p;32683269for(p = patch; p; p = p->next) {3270if(p->is_new)3271show_file_mode_name("create", p->new_mode, p->new_name);3272else if(p->is_delete)3273show_file_mode_name("delete", p->old_mode, p->old_name);3274else{3275if(p->is_rename || p->is_copy)3276show_rename_copy(p);3277else{3278if(p->score) {3279printf(" rewrite%s(%d%%)\n",3280 p->new_name, p->score);3281show_mode_change(p,0);3282}3283else3284show_mode_change(p,1);3285}3286}3287}3288}32893290static voidpatch_stats(struct patch *patch)3291{3292int lines = patch->lines_added + patch->lines_deleted;32933294if(lines > max_change)3295 max_change = lines;3296if(patch->old_name) {3297int len =quote_c_style(patch->old_name, NULL, NULL,0);3298if(!len)3299 len =strlen(patch->old_name);3300if(len > max_len)3301 max_len = len;3302}3303if(patch->new_name) {3304int len =quote_c_style(patch->new_name, NULL, NULL,0);3305if(!len)3306 len =strlen(patch->new_name);3307if(len > max_len)3308 max_len = len;3309}3310}33113312static voidremove_file(struct patch *patch,int rmdir_empty)3313{3314if(update_index) {3315if(remove_file_from_cache(patch->old_name) <0)3316die("unable to remove%sfrom index", patch->old_name);3317}3318if(!cached) {3319if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {3320remove_path(patch->old_name);3321}3322}3323}33243325static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)3326{3327struct stat st;3328struct cache_entry *ce;3329int namelen =strlen(path);3330unsigned ce_size =cache_entry_size(namelen);33313332if(!update_index)3333return;33343335 ce =xcalloc(1, ce_size);3336memcpy(ce->name, path, namelen);3337 ce->ce_mode =create_ce_mode(mode);3338 ce->ce_flags = namelen;3339if(S_ISGITLINK(mode)) {3340const char*s = buf;33413342if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))3343die("corrupt patch for subproject%s", path);3344}else{3345if(!cached) {3346if(lstat(path, &st) <0)3347die_errno("unable to stat newly created file '%s'",3348 path);3349fill_stat_cache_info(ce, &st);3350}3351if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)3352die("unable to create backing store for newly created file%s", path);3353}3354if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3355die("unable to add cache entry for%s", path);3356}33573358static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)3359{3360int fd;3361struct strbuf nbuf = STRBUF_INIT;33623363if(S_ISGITLINK(mode)) {3364struct stat st;3365if(!lstat(path, &st) &&S_ISDIR(st.st_mode))3366return0;3367returnmkdir(path,0777);3368}33693370if(has_symlinks &&S_ISLNK(mode))3371/* Although buf:size is counted string, it also is NUL3372 * terminated.3373 */3374returnsymlink(buf, path);33753376 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);3377if(fd <0)3378return-1;33793380if(convert_to_working_tree(path, buf, size, &nbuf)) {3381 size = nbuf.len;3382 buf = nbuf.buf;3383}3384write_or_die(fd, buf, size);3385strbuf_release(&nbuf);33863387if(close(fd) <0)3388die_errno("closing file '%s'", path);3389return0;3390}33913392/*3393 * We optimistically assume that the directories exist,3394 * which is true 99% of the time anyway. If they don't,3395 * we create them and try again.3396 */3397static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)3398{3399if(cached)3400return;3401if(!try_create_file(path, mode, buf, size))3402return;34033404if(errno == ENOENT) {3405if(safe_create_leading_directories(path))3406return;3407if(!try_create_file(path, mode, buf, size))3408return;3409}34103411if(errno == EEXIST || errno == EACCES) {3412/* We may be trying to create a file where a directory3413 * used to be.3414 */3415struct stat st;3416if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))3417 errno = EEXIST;3418}34193420if(errno == EEXIST) {3421unsigned int nr =getpid();34223423for(;;) {3424char newpath[PATH_MAX];3425mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);3426if(!try_create_file(newpath, mode, buf, size)) {3427if(!rename(newpath, path))3428return;3429unlink_or_warn(newpath);3430break;3431}3432if(errno != EEXIST)3433break;3434++nr;3435}3436}3437die_errno("unable to write file '%s' mode%o", path, mode);3438}34393440static voidcreate_file(struct patch *patch)3441{3442char*path = patch->new_name;3443unsigned mode = patch->new_mode;3444unsigned long size = patch->resultsize;3445char*buf = patch->result;34463447if(!mode)3448 mode = S_IFREG |0644;3449create_one_file(path, mode, buf, size);3450add_index_file(path, mode, buf, size);3451}34523453/* phase zero is to remove, phase one is to create */3454static voidwrite_out_one_result(struct patch *patch,int phase)3455{3456if(patch->is_delete >0) {3457if(phase ==0)3458remove_file(patch,1);3459return;3460}3461if(patch->is_new >0|| patch->is_copy) {3462if(phase ==1)3463create_file(patch);3464return;3465}3466/*3467 * Rename or modification boils down to the same3468 * thing: remove the old, write the new3469 */3470if(phase ==0)3471remove_file(patch, patch->is_rename);3472if(phase ==1)3473create_file(patch);3474}34753476static intwrite_out_one_reject(struct patch *patch)3477{3478FILE*rej;3479char namebuf[PATH_MAX];3480struct fragment *frag;3481int cnt =0;34823483for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {3484if(!frag->rejected)3485continue;3486 cnt++;3487}34883489if(!cnt) {3490if(apply_verbosely)3491say_patch_name(stderr,3492"Applied patch ", patch," cleanly.\n");3493return0;3494}34953496/* This should not happen, because a removal patch that leaves3497 * contents are marked "rejected" at the patch level.3498 */3499if(!patch->new_name)3500die("internal error");35013502/* Say this even without --verbose */3503say_patch_name(stderr,"Applying patch ", patch," with");3504fprintf(stderr,"%drejects...\n", cnt);35053506 cnt =strlen(patch->new_name);3507if(ARRAY_SIZE(namebuf) <= cnt +5) {3508 cnt =ARRAY_SIZE(namebuf) -5;3509warning("truncating .rej filename to %.*s.rej",3510 cnt -1, patch->new_name);3511}3512memcpy(namebuf, patch->new_name, cnt);3513memcpy(namebuf + cnt,".rej",5);35143515 rej =fopen(namebuf,"w");3516if(!rej)3517returnerror("cannot open%s:%s", namebuf,strerror(errno));35183519/* Normal git tools never deal with .rej, so do not pretend3520 * this is a git patch by saying --git nor give extended3521 * headers. While at it, maybe please "kompare" that wants3522 * the trailing TAB and some garbage at the end of line ;-).3523 */3524fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",3525 patch->new_name, patch->new_name);3526for(cnt =1, frag = patch->fragments;3527 frag;3528 cnt++, frag = frag->next) {3529if(!frag->rejected) {3530fprintf(stderr,"Hunk #%dapplied cleanly.\n", cnt);3531continue;3532}3533fprintf(stderr,"Rejected hunk #%d.\n", cnt);3534fprintf(rej,"%.*s", frag->size, frag->patch);3535if(frag->patch[frag->size-1] !='\n')3536fputc('\n', rej);3537}3538fclose(rej);3539return-1;3540}35413542static intwrite_out_results(struct patch *list,int skipped_patch)3543{3544int phase;3545int errs =0;3546struct patch *l;35473548if(!list && !skipped_patch)3549returnerror("No changes");35503551for(phase =0; phase <2; phase++) {3552 l = list;3553while(l) {3554if(l->rejected)3555 errs =1;3556else{3557write_out_one_result(l, phase);3558if(phase ==1&&write_out_one_reject(l))3559 errs =1;3560}3561 l = l->next;3562}3563}3564return errs;3565}35663567static struct lock_file lock_file;35683569static struct string_list limit_by_name;3570static int has_include;3571static voidadd_name_limit(const char*name,int exclude)3572{3573struct string_list_item *it;35743575 it =string_list_append(&limit_by_name, name);3576 it->util = exclude ? NULL : (void*)1;3577}35783579static intuse_patch(struct patch *p)3580{3581const char*pathname = p->new_name ? p->new_name : p->old_name;3582int i;35833584/* Paths outside are not touched regardless of "--include" */3585if(0< prefix_length) {3586int pathlen =strlen(pathname);3587if(pathlen <= prefix_length ||3588memcmp(prefix, pathname, prefix_length))3589return0;3590}35913592/* See if it matches any of exclude/include rule */3593for(i =0; i < limit_by_name.nr; i++) {3594struct string_list_item *it = &limit_by_name.items[i];3595if(!fnmatch(it->string, pathname,0))3596return(it->util != NULL);3597}35983599/*3600 * If we had any include, a path that does not match any rule is3601 * not used. Otherwise, we saw bunch of exclude rules (or none)3602 * and such a path is used.3603 */3604return!has_include;3605}360636073608static voidprefix_one(char**name)3609{3610char*old_name = *name;3611if(!old_name)3612return;3613*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3614free(old_name);3615}36163617static voidprefix_patches(struct patch *p)3618{3619if(!prefix || p->is_toplevel_relative)3620return;3621for( ; p; p = p->next) {3622if(p->new_name == p->old_name) {3623char*prefixed = p->new_name;3624prefix_one(&prefixed);3625 p->new_name = p->old_name = prefixed;3626}3627else{3628prefix_one(&p->new_name);3629prefix_one(&p->old_name);3630}3631}3632}36333634#define INACCURATE_EOF (1<<0)3635#define RECOUNT (1<<1)36363637static intapply_patch(int fd,const char*filename,int options)3638{3639size_t offset;3640struct strbuf buf = STRBUF_INIT;3641struct patch *list = NULL, **listp = &list;3642int skipped_patch =0;36433644/* FIXME - memory leak when using multiple patch files as inputs */3645memset(&fn_table,0,sizeof(struct string_list));3646 patch_input_file = filename;3647read_patch_file(&buf, fd);3648 offset =0;3649while(offset < buf.len) {3650struct patch *patch;3651int nr;36523653 patch =xcalloc(1,sizeof(*patch));3654 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3655 patch->recount = !!(options & RECOUNT);3656 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3657if(nr <0)3658break;3659if(apply_in_reverse)3660reverse_patches(patch);3661if(prefix)3662prefix_patches(patch);3663if(use_patch(patch)) {3664patch_stats(patch);3665*listp = patch;3666 listp = &patch->next;3667}3668else{3669/* perhaps free it a bit better? */3670free(patch);3671 skipped_patch++;3672}3673 offset += nr;3674}36753676if(whitespace_error && (ws_error_action == die_on_ws_error))3677 apply =0;36783679 update_index = check_index && apply;3680if(update_index && newfd <0)3681 newfd =hold_locked_index(&lock_file,1);36823683if(check_index) {3684if(read_cache() <0)3685die("unable to read index file");3686}36873688if((check || apply) &&3689check_patch_list(list) <0&&3690!apply_with_reject)3691exit(1);36923693if(apply &&write_out_results(list, skipped_patch))3694exit(1);36953696if(fake_ancestor)3697build_fake_ancestor(list, fake_ancestor);36983699if(diffstat)3700stat_patch_list(list);37013702if(numstat)3703numstat_patch_list(list);37043705if(summary)3706summary_patch_list(list);37073708strbuf_release(&buf);3709return0;3710}37113712static intgit_apply_config(const char*var,const char*value,void*cb)3713{3714if(!strcmp(var,"apply.whitespace"))3715returngit_config_string(&apply_default_whitespace, var, value);3716else if(!strcmp(var,"apply.ignorewhitespace"))3717returngit_config_string(&apply_default_ignorewhitespace, var, value);3718returngit_default_config(var, value, cb);3719}37203721static intoption_parse_exclude(const struct option *opt,3722const char*arg,int unset)3723{3724add_name_limit(arg,1);3725return0;3726}37273728static intoption_parse_include(const struct option *opt,3729const char*arg,int unset)3730{3731add_name_limit(arg,0);3732 has_include =1;3733return0;3734}37353736static intoption_parse_p(const struct option *opt,3737const char*arg,int unset)3738{3739 p_value =atoi(arg);3740 p_value_known =1;3741return0;3742}37433744static intoption_parse_z(const struct option *opt,3745const char*arg,int unset)3746{3747if(unset)3748 line_termination ='\n';3749else3750 line_termination =0;3751return0;3752}37533754static intoption_parse_space_change(const struct option *opt,3755const char*arg,int unset)3756{3757if(unset)3758 ws_ignore_action = ignore_ws_none;3759else3760 ws_ignore_action = ignore_ws_change;3761return0;3762}37633764static intoption_parse_whitespace(const struct option *opt,3765const char*arg,int unset)3766{3767const char**whitespace_option = opt->value;37683769*whitespace_option = arg;3770parse_whitespace_option(arg);3771return0;3772}37733774static intoption_parse_directory(const struct option *opt,3775const char*arg,int unset)3776{3777 root_len =strlen(arg);3778if(root_len && arg[root_len -1] !='/') {3779char*new_root;3780 root = new_root =xmalloc(root_len +2);3781strcpy(new_root, arg);3782strcpy(new_root + root_len++,"/");3783}else3784 root = arg;3785return0;3786}37873788intcmd_apply(int argc,const char**argv,const char*prefix_)3789{3790int i;3791int errs =0;3792int is_not_gitdir = !startup_info->have_repository;3793int binary;3794int force_apply =0;37953796const char*whitespace_option = NULL;37973798struct option builtin_apply_options[] = {3799{ OPTION_CALLBACK,0,"exclude", NULL,"path",3800"don't apply changes matching the given path",38010, option_parse_exclude },3802{ OPTION_CALLBACK,0,"include", NULL,"path",3803"apply changes matching the given path",38040, option_parse_include },3805{ OPTION_CALLBACK,'p', NULL, NULL,"num",3806"remove <num> leading slashes from traditional diff paths",38070, option_parse_p },3808OPT_BOOLEAN(0,"no-add", &no_add,3809"ignore additions made by the patch"),3810OPT_BOOLEAN(0,"stat", &diffstat,3811"instead of applying the patch, output diffstat for the input"),3812{ OPTION_BOOLEAN,0,"allow-binary-replacement", &binary,3813 NULL,"old option, now no-op",3814 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3815{ OPTION_BOOLEAN,0,"binary", &binary,3816 NULL,"old option, now no-op",3817 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3818OPT_BOOLEAN(0,"numstat", &numstat,3819"shows number of added and deleted lines in decimal notation"),3820OPT_BOOLEAN(0,"summary", &summary,3821"instead of applying the patch, output a summary for the input"),3822OPT_BOOLEAN(0,"check", &check,3823"instead of applying the patch, see if the patch is applicable"),3824OPT_BOOLEAN(0,"index", &check_index,3825"make sure the patch is applicable to the current index"),3826OPT_BOOLEAN(0,"cached", &cached,3827"apply a patch without touching the working tree"),3828OPT_BOOLEAN(0,"apply", &force_apply,3829"also apply the patch (use with --stat/--summary/--check)"),3830OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,3831"build a temporary index based on embedded index information"),3832{ OPTION_CALLBACK,'z', NULL, NULL, NULL,3833"paths are separated with NUL character",3834 PARSE_OPT_NOARG, option_parse_z },3835OPT_INTEGER('C', NULL, &p_context,3836"ensure at least <n> lines of context match"),3837{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,"action",3838"detect new or modified lines that have whitespace errors",38390, option_parse_whitespace },3840{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,3841"ignore changes in whitespace when finding context",3842 PARSE_OPT_NOARG, option_parse_space_change },3843{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,3844"ignore changes in whitespace when finding context",3845 PARSE_OPT_NOARG, option_parse_space_change },3846OPT_BOOLEAN('R',"reverse", &apply_in_reverse,3847"apply the patch in reverse"),3848OPT_BOOLEAN(0,"unidiff-zero", &unidiff_zero,3849"don't expect at least one line of context"),3850OPT_BOOLEAN(0,"reject", &apply_with_reject,3851"leave the rejected hunks in corresponding *.rej files"),3852OPT__VERBOSE(&apply_verbosely),3853OPT_BIT(0,"inaccurate-eof", &options,3854"tolerate incorrectly detected missing new-line at the end of file",3855 INACCURATE_EOF),3856OPT_BIT(0,"recount", &options,3857"do not trust the line counts in the hunk headers",3858 RECOUNT),3859{ OPTION_CALLBACK,0,"directory", NULL,"root",3860"prepend <root> to all filenames",38610, option_parse_directory },3862OPT_END()3863};38643865 prefix = prefix_;3866 prefix_length = prefix ?strlen(prefix) :0;3867git_config(git_apply_config, NULL);3868if(apply_default_whitespace)3869parse_whitespace_option(apply_default_whitespace);3870if(apply_default_ignorewhitespace)3871parse_ignorewhitespace_option(apply_default_ignorewhitespace);38723873 argc =parse_options(argc, argv, prefix, builtin_apply_options,3874 apply_usage,0);38753876if(apply_with_reject)3877 apply = apply_verbosely =1;3878if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))3879 apply =0;3880if(check_index && is_not_gitdir)3881die("--index outside a repository");3882if(cached) {3883if(is_not_gitdir)3884die("--cached outside a repository");3885 check_index =1;3886}3887for(i =0; i < argc; i++) {3888const char*arg = argv[i];3889int fd;38903891if(!strcmp(arg,"-")) {3892 errs |=apply_patch(0,"<stdin>", options);3893 read_stdin =0;3894continue;3895}else if(0< prefix_length)3896 arg =prefix_filename(prefix, prefix_length, arg);38973898 fd =open(arg, O_RDONLY);3899if(fd <0)3900die_errno("can't open patch '%s'", arg);3901 read_stdin =0;3902set_default_whitespace_mode(whitespace_option);3903 errs |=apply_patch(fd, arg, options);3904close(fd);3905}3906set_default_whitespace_mode(whitespace_option);3907if(read_stdin)3908 errs |=apply_patch(0,"<stdin>", options);3909if(whitespace_error) {3910if(squelch_whitespace_errors &&3911 squelch_whitespace_errors < whitespace_error) {3912int squelched =3913 whitespace_error - squelch_whitespace_errors;3914warning("squelched%d"3915"whitespace error%s",3916 squelched,3917 squelched ==1?"":"s");3918}3919if(ws_error_action == die_on_ws_error)3920die("%dline%sadd%swhitespace errors.",3921 whitespace_error,3922 whitespace_error ==1?"":"s",3923 whitespace_error ==1?"s":"");3924if(applied_after_fixing_ws && apply)3925warning("%dline%sapplied after"3926" fixing whitespace errors.",3927 applied_after_fixing_ws,3928 applied_after_fixing_ws ==1?"":"s");3929else if(whitespace_error)3930warning("%dline%sadd%swhitespace errors.",3931 whitespace_error,3932 whitespace_error ==1?"":"s",3933 whitespace_error ==1?"s":"");3934}39353936if(update_index) {3937if(write_cache(newfd, active_cache, active_nr) ||3938commit_locked_index(&lock_file))3939die("Unable to write new index file");3940}39413942return!!errs;3943}