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, *colon; 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, (char**) &colon,10); 768if(*colon ==':') 769 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 770else 771 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 772if(timestamp[m[3].rm_so] =='-') 773 zoneoffset = -zoneoffset; 774 775/* 776 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 777 * (west of GMT) or 1970-01-01 (east of GMT) 778 */ 779if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 780(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 781return0; 782 783 hourminute = (strtol(timestamp +11, NULL,10) *60+ 784strtol(timestamp +14, NULL,10) - 785 zoneoffset); 786 787return((zoneoffset <0&& hourminute ==1440) || 788(0<= zoneoffset && !hourminute)); 789} 790 791/* 792 * Get the name etc info from the ---/+++ lines of a traditional patch header 793 * 794 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 795 * files, we can happily check the index for a match, but for creating a 796 * new file we should try to match whatever "patch" does. I have no idea. 797 */ 798static voidparse_traditional_patch(const char*first,const char*second,struct patch *patch) 799{ 800char*name; 801 802 first +=4;/* skip "--- " */ 803 second +=4;/* skip "+++ " */ 804if(!p_value_known) { 805int p, q; 806 p =guess_p_value(first); 807 q =guess_p_value(second); 808if(p <0) p = q; 809if(0<= p && p == q) { 810 p_value = p; 811 p_value_known =1; 812} 813} 814if(is_dev_null(first)) { 815 patch->is_new =1; 816 patch->is_delete =0; 817 name =find_name_traditional(second, NULL, p_value); 818 patch->new_name = name; 819}else if(is_dev_null(second)) { 820 patch->is_new =0; 821 patch->is_delete =1; 822 name =find_name_traditional(first, NULL, p_value); 823 patch->old_name = name; 824}else{ 825 name =find_name_traditional(first, NULL, p_value); 826 name =find_name_traditional(second, name, p_value); 827if(has_epoch_timestamp(first)) { 828 patch->is_new =1; 829 patch->is_delete =0; 830 patch->new_name = name; 831}else if(has_epoch_timestamp(second)) { 832 patch->is_new =0; 833 patch->is_delete =1; 834 patch->old_name = name; 835}else{ 836 patch->old_name = patch->new_name = name; 837} 838} 839if(!name) 840die("unable to find filename in patch at line%d", linenr); 841} 842 843static intgitdiff_hdrend(const char*line,struct patch *patch) 844{ 845return-1; 846} 847 848/* 849 * We're anal about diff header consistency, to make 850 * sure that we don't end up having strange ambiguous 851 * patches floating around. 852 * 853 * As a result, gitdiff_{old|new}name() will check 854 * their names against any previous information, just 855 * to make sure.. 856 */ 857static char*gitdiff_verify_name(const char*line,int isnull,char*orig_name,const char*oldnew) 858{ 859if(!orig_name && !isnull) 860returnfind_name(line, NULL, p_value, TERM_TAB); 861 862if(orig_name) { 863int len; 864const char*name; 865char*another; 866 name = orig_name; 867 len =strlen(name); 868if(isnull) 869die("git apply: bad git-diff - expected /dev/null, got%son line%d", name, linenr); 870 another =find_name(line, NULL, p_value, TERM_TAB); 871if(!another ||memcmp(another, name, len +1)) 872die("git apply: bad git-diff - inconsistent%sfilename on line%d", oldnew, linenr); 873free(another); 874return orig_name; 875} 876else{ 877/* expect "/dev/null" */ 878if(memcmp("/dev/null", line,9) || line[9] !='\n') 879die("git apply: bad git-diff - expected /dev/null on line%d", linenr); 880return NULL; 881} 882} 883 884static intgitdiff_oldname(const char*line,struct patch *patch) 885{ 886 patch->old_name =gitdiff_verify_name(line, patch->is_new, patch->old_name,"old"); 887return0; 888} 889 890static intgitdiff_newname(const char*line,struct patch *patch) 891{ 892 patch->new_name =gitdiff_verify_name(line, patch->is_delete, patch->new_name,"new"); 893return0; 894} 895 896static intgitdiff_oldmode(const char*line,struct patch *patch) 897{ 898 patch->old_mode =strtoul(line, NULL,8); 899return0; 900} 901 902static intgitdiff_newmode(const char*line,struct patch *patch) 903{ 904 patch->new_mode =strtoul(line, NULL,8); 905return0; 906} 907 908static intgitdiff_delete(const char*line,struct patch *patch) 909{ 910 patch->is_delete =1; 911 patch->old_name = patch->def_name; 912returngitdiff_oldmode(line, patch); 913} 914 915static intgitdiff_newfile(const char*line,struct patch *patch) 916{ 917 patch->is_new =1; 918 patch->new_name = patch->def_name; 919returngitdiff_newmode(line, patch); 920} 921 922static intgitdiff_copysrc(const char*line,struct patch *patch) 923{ 924 patch->is_copy =1; 925 patch->old_name =find_name(line, NULL,0,0); 926return0; 927} 928 929static intgitdiff_copydst(const char*line,struct patch *patch) 930{ 931 patch->is_copy =1; 932 patch->new_name =find_name(line, NULL,0,0); 933return0; 934} 935 936static intgitdiff_renamesrc(const char*line,struct patch *patch) 937{ 938 patch->is_rename =1; 939 patch->old_name =find_name(line, NULL,0,0); 940return0; 941} 942 943static intgitdiff_renamedst(const char*line,struct patch *patch) 944{ 945 patch->is_rename =1; 946 patch->new_name =find_name(line, NULL,0,0); 947return0; 948} 949 950static intgitdiff_similarity(const char*line,struct patch *patch) 951{ 952if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 953 patch->score =0; 954return0; 955} 956 957static intgitdiff_dissimilarity(const char*line,struct patch *patch) 958{ 959if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 960 patch->score =0; 961return0; 962} 963 964static intgitdiff_index(const char*line,struct patch *patch) 965{ 966/* 967 * index line is N hexadecimal, "..", N hexadecimal, 968 * and optional space with octal mode. 969 */ 970const char*ptr, *eol; 971int len; 972 973 ptr =strchr(line,'.'); 974if(!ptr || ptr[1] !='.'||40< ptr - line) 975return0; 976 len = ptr - line; 977memcpy(patch->old_sha1_prefix, line, len); 978 patch->old_sha1_prefix[len] =0; 979 980 line = ptr +2; 981 ptr =strchr(line,' '); 982 eol =strchr(line,'\n'); 983 984if(!ptr || eol < ptr) 985 ptr = eol; 986 len = ptr - line; 987 988if(40< len) 989return0; 990memcpy(patch->new_sha1_prefix, line, len); 991 patch->new_sha1_prefix[len] =0; 992if(*ptr ==' ') 993 patch->old_mode =strtoul(ptr+1, NULL,8); 994return0; 995} 996 997/* 998 * This is normal for a diff that doesn't change anything: we'll fall through 999 * into the next diff. Tell the parser to break out.1000 */1001static intgitdiff_unrecognized(const char*line,struct patch *patch)1002{1003return-1;1004}10051006static const char*stop_at_slash(const char*line,int llen)1007{1008int nslash = p_value;1009int i;10101011for(i =0; i < llen; i++) {1012int ch = line[i];1013if(ch =='/'&& --nslash <=0)1014return&line[i];1015}1016return NULL;1017}10181019/*1020 * This is to extract the same name that appears on "diff --git"1021 * line. We do not find and return anything if it is a rename1022 * patch, and it is OK because we will find the name elsewhere.1023 * We need to reliably find name only when it is mode-change only,1024 * creation or deletion of an empty file. In any of these cases,1025 * both sides are the same name under a/ and b/ respectively.1026 */1027static char*git_header_name(char*line,int llen)1028{1029const char*name;1030const char*second = NULL;1031size_t len;10321033 line +=strlen("diff --git ");1034 llen -=strlen("diff --git ");10351036if(*line =='"') {1037const char*cp;1038struct strbuf first = STRBUF_INIT;1039struct strbuf sp = STRBUF_INIT;10401041if(unquote_c_style(&first, line, &second))1042goto free_and_fail1;10431044/* advance to the first slash */1045 cp =stop_at_slash(first.buf, first.len);1046/* we do not accept absolute paths */1047if(!cp || cp == first.buf)1048goto free_and_fail1;1049strbuf_remove(&first,0, cp +1- first.buf);10501051/*1052 * second points at one past closing dq of name.1053 * find the second name.1054 */1055while((second < line + llen) &&isspace(*second))1056 second++;10571058if(line + llen <= second)1059goto free_and_fail1;1060if(*second =='"') {1061if(unquote_c_style(&sp, second, NULL))1062goto free_and_fail1;1063 cp =stop_at_slash(sp.buf, sp.len);1064if(!cp || cp == sp.buf)1065goto free_and_fail1;1066/* They must match, otherwise ignore */1067if(strcmp(cp +1, first.buf))1068goto free_and_fail1;1069strbuf_release(&sp);1070returnstrbuf_detach(&first, NULL);1071}10721073/* unquoted second */1074 cp =stop_at_slash(second, line + llen - second);1075if(!cp || cp == second)1076goto free_and_fail1;1077 cp++;1078if(line + llen - cp != first.len +1||1079memcmp(first.buf, cp, first.len))1080goto free_and_fail1;1081returnstrbuf_detach(&first, NULL);10821083 free_and_fail1:1084strbuf_release(&first);1085strbuf_release(&sp);1086return NULL;1087}10881089/* unquoted first name */1090 name =stop_at_slash(line, llen);1091if(!name || name == line)1092return NULL;1093 name++;10941095/*1096 * since the first name is unquoted, a dq if exists must be1097 * the beginning of the second name.1098 */1099for(second = name; second < line + llen; second++) {1100if(*second =='"') {1101struct strbuf sp = STRBUF_INIT;1102const char*np;11031104if(unquote_c_style(&sp, second, NULL))1105goto free_and_fail2;11061107 np =stop_at_slash(sp.buf, sp.len);1108if(!np || np == sp.buf)1109goto free_and_fail2;1110 np++;11111112 len = sp.buf + sp.len - np;1113if(len < second - name &&1114!strncmp(np, name, len) &&1115isspace(name[len])) {1116/* Good */1117strbuf_remove(&sp,0, np - sp.buf);1118returnstrbuf_detach(&sp, NULL);1119}11201121 free_and_fail2:1122strbuf_release(&sp);1123return NULL;1124}1125}11261127/*1128 * Accept a name only if it shows up twice, exactly the same1129 * form.1130 */1131for(len =0; ; len++) {1132switch(name[len]) {1133default:1134continue;1135case'\n':1136return NULL;1137case'\t':case' ':1138 second = name+len;1139for(;;) {1140char c = *second++;1141if(c =='\n')1142return NULL;1143if(c =='/')1144break;1145}1146if(second[len] =='\n'&& !memcmp(name, second, len)) {1147returnxmemdupz(name, len);1148}1149}1150}1151}11521153/* Verify that we recognize the lines following a git header */1154static intparse_git_header(char*line,int len,unsigned int size,struct patch *patch)1155{1156unsigned long offset;11571158/* A git diff has explicit new/delete information, so we don't guess */1159 patch->is_new =0;1160 patch->is_delete =0;11611162/*1163 * Some things may not have the old name in the1164 * rest of the headers anywhere (pure mode changes,1165 * or removing or adding empty files), so we get1166 * the default name from the header.1167 */1168 patch->def_name =git_header_name(line, len);1169if(patch->def_name && root) {1170char*s =xmalloc(root_len +strlen(patch->def_name) +1);1171strcpy(s, root);1172strcpy(s + root_len, patch->def_name);1173free(patch->def_name);1174 patch->def_name = s;1175}11761177 line += len;1178 size -= len;1179 linenr++;1180for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) {1181static const struct opentry {1182const char*str;1183int(*fn)(const char*,struct patch *);1184} optable[] = {1185{"@@ -", gitdiff_hdrend },1186{"--- ", gitdiff_oldname },1187{"+++ ", gitdiff_newname },1188{"old mode ", gitdiff_oldmode },1189{"new mode ", gitdiff_newmode },1190{"deleted file mode ", gitdiff_delete },1191{"new file mode ", gitdiff_newfile },1192{"copy from ", gitdiff_copysrc },1193{"copy to ", gitdiff_copydst },1194{"rename old ", gitdiff_renamesrc },1195{"rename new ", gitdiff_renamedst },1196{"rename from ", gitdiff_renamesrc },1197{"rename to ", gitdiff_renamedst },1198{"similarity index ", gitdiff_similarity },1199{"dissimilarity index ", gitdiff_dissimilarity },1200{"index ", gitdiff_index },1201{"", gitdiff_unrecognized },1202};1203int i;12041205 len =linelen(line, size);1206if(!len || line[len-1] !='\n')1207break;1208for(i =0; i <ARRAY_SIZE(optable); i++) {1209const struct opentry *p = optable + i;1210int oplen =strlen(p->str);1211if(len < oplen ||memcmp(p->str, line, oplen))1212continue;1213if(p->fn(line + oplen, patch) <0)1214return offset;1215break;1216}1217}12181219return offset;1220}12211222static intparse_num(const char*line,unsigned long*p)1223{1224char*ptr;12251226if(!isdigit(*line))1227return0;1228*p =strtoul(line, &ptr,10);1229return ptr - line;1230}12311232static intparse_range(const char*line,int len,int offset,const char*expect,1233unsigned long*p1,unsigned long*p2)1234{1235int digits, ex;12361237if(offset <0|| offset >= len)1238return-1;1239 line += offset;1240 len -= offset;12411242 digits =parse_num(line, p1);1243if(!digits)1244return-1;12451246 offset += digits;1247 line += digits;1248 len -= digits;12491250*p2 =1;1251if(*line ==',') {1252 digits =parse_num(line+1, p2);1253if(!digits)1254return-1;12551256 offset += digits+1;1257 line += digits+1;1258 len -= digits+1;1259}12601261 ex =strlen(expect);1262if(ex > len)1263return-1;1264if(memcmp(line, expect, ex))1265return-1;12661267return offset + ex;1268}12691270static voidrecount_diff(char*line,int size,struct fragment *fragment)1271{1272int oldlines =0, newlines =0, ret =0;12731274if(size <1) {1275warning("recount: ignore empty hunk");1276return;1277}12781279for(;;) {1280int len =linelen(line, size);1281 size -= len;1282 line += len;12831284if(size <1)1285break;12861287switch(*line) {1288case' ':case'\n':1289 newlines++;1290/* fall through */1291case'-':1292 oldlines++;1293continue;1294case'+':1295 newlines++;1296continue;1297case'\\':1298continue;1299case'@':1300 ret = size <3||prefixcmp(line,"@@ ");1301break;1302case'd':1303 ret = size <5||prefixcmp(line,"diff ");1304break;1305default:1306 ret = -1;1307break;1308}1309if(ret) {1310warning("recount: unexpected line: %.*s",1311(int)linelen(line, size), line);1312return;1313}1314break;1315}1316 fragment->oldlines = oldlines;1317 fragment->newlines = newlines;1318}13191320/*1321 * Parse a unified diff fragment header of the1322 * form "@@ -a,b +c,d @@"1323 */1324static intparse_fragment_header(char*line,int len,struct fragment *fragment)1325{1326int offset;13271328if(!len || line[len-1] !='\n')1329return-1;13301331/* Figure out the number of lines in a fragment */1332 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1333 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);13341335return offset;1336}13371338static intfind_header(char*line,unsigned long size,int*hdrsize,struct patch *patch)1339{1340unsigned long offset, len;13411342 patch->is_toplevel_relative =0;1343 patch->is_rename = patch->is_copy =0;1344 patch->is_new = patch->is_delete = -1;1345 patch->old_mode = patch->new_mode =0;1346 patch->old_name = patch->new_name = NULL;1347for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) {1348unsigned long nextlen;13491350 len =linelen(line, size);1351if(!len)1352break;13531354/* Testing this early allows us to take a few shortcuts.. */1355if(len <6)1356continue;13571358/*1359 * Make sure we don't find any unconnected patch fragments.1360 * That's a sign that we didn't find a header, and that a1361 * patch has become corrupted/broken up.1362 */1363if(!memcmp("@@ -", line,4)) {1364struct fragment dummy;1365if(parse_fragment_header(line, len, &dummy) <0)1366continue;1367die("patch fragment without header at line%d: %.*s",1368 linenr, (int)len-1, line);1369}13701371if(size < len +6)1372break;13731374/*1375 * Git patch? It might not have a real patch, just a rename1376 * or mode change, so we handle that specially1377 */1378if(!memcmp("diff --git ", line,11)) {1379int git_hdr_len =parse_git_header(line, len, size, patch);1380if(git_hdr_len <= len)1381continue;1382if(!patch->old_name && !patch->new_name) {1383if(!patch->def_name)1384die("git diff header lacks filename information when removing "1385"%dleading pathname components (line%d)", p_value, linenr);1386 patch->old_name = patch->new_name = patch->def_name;1387}1388 patch->is_toplevel_relative =1;1389*hdrsize = git_hdr_len;1390return offset;1391}13921393/* --- followed by +++ ? */1394if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1395continue;13961397/*1398 * We only accept unified patches, so we want it to1399 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1400 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1401 */1402 nextlen =linelen(line + len, size - len);1403if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1404continue;14051406/* Ok, we'll consider it a patch */1407parse_traditional_patch(line, line+len, patch);1408*hdrsize = len + nextlen;1409 linenr +=2;1410return offset;1411}1412return-1;1413}14141415static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1416{1417char*err;14181419if(!result)1420return;14211422 whitespace_error++;1423if(squelch_whitespace_errors &&1424 squelch_whitespace_errors < whitespace_error)1425return;14261427 err =whitespace_error_string(result);1428fprintf(stderr,"%s:%d:%s.\n%.*s\n",1429 patch_input_file, linenr, err, len, line);1430free(err);1431}14321433static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1434{1435unsigned result =ws_check(line +1, len -1, ws_rule);14361437record_ws_error(result, line +1, len -2, linenr);1438}14391440/*1441 * Parse a unified diff. Note that this really needs to parse each1442 * fragment separately, since the only way to know the difference1443 * between a "---" that is part of a patch, and a "---" that starts1444 * the next patch is to look at the line counts..1445 */1446static intparse_fragment(char*line,unsigned long size,1447struct patch *patch,struct fragment *fragment)1448{1449int added, deleted;1450int len =linelen(line, size), offset;1451unsigned long oldlines, newlines;1452unsigned long leading, trailing;14531454 offset =parse_fragment_header(line, len, fragment);1455if(offset <0)1456return-1;1457if(offset >0&& patch->recount)1458recount_diff(line + offset, size - offset, fragment);1459 oldlines = fragment->oldlines;1460 newlines = fragment->newlines;1461 leading =0;1462 trailing =0;14631464/* Parse the thing.. */1465 line += len;1466 size -= len;1467 linenr++;1468 added = deleted =0;1469for(offset = len;14700< size;1471 offset += len, size -= len, line += len, linenr++) {1472if(!oldlines && !newlines)1473break;1474 len =linelen(line, size);1475if(!len || line[len-1] !='\n')1476return-1;1477switch(*line) {1478default:1479return-1;1480case'\n':/* newer GNU diff, an empty context line */1481case' ':1482 oldlines--;1483 newlines--;1484if(!deleted && !added)1485 leading++;1486 trailing++;1487break;1488case'-':1489if(apply_in_reverse &&1490 ws_error_action != nowarn_ws_error)1491check_whitespace(line, len, patch->ws_rule);1492 deleted++;1493 oldlines--;1494 trailing =0;1495break;1496case'+':1497if(!apply_in_reverse &&1498 ws_error_action != nowarn_ws_error)1499check_whitespace(line, len, patch->ws_rule);1500 added++;1501 newlines--;1502 trailing =0;1503break;15041505/*1506 * We allow "\ No newline at end of file". Depending1507 * on locale settings when the patch was produced we1508 * don't know what this line looks like. The only1509 * thing we do know is that it begins with "\ ".1510 * Checking for 12 is just for sanity check -- any1511 * l10n of "\ No newline..." is at least that long.1512 */1513case'\\':1514if(len <12||memcmp(line,"\\",2))1515return-1;1516break;1517}1518}1519if(oldlines || newlines)1520return-1;1521 fragment->leading = leading;1522 fragment->trailing = trailing;15231524/*1525 * If a fragment ends with an incomplete line, we failed to include1526 * it in the above loop because we hit oldlines == newlines == 01527 * before seeing it.1528 */1529if(12< size && !memcmp(line,"\\",2))1530 offset +=linelen(line, size);15311532 patch->lines_added += added;1533 patch->lines_deleted += deleted;15341535if(0< patch->is_new && oldlines)1536returnerror("new file depends on old contents");1537if(0< patch->is_delete && newlines)1538returnerror("deleted file still has contents");1539return offset;1540}15411542static intparse_single_patch(char*line,unsigned long size,struct patch *patch)1543{1544unsigned long offset =0;1545unsigned long oldlines =0, newlines =0, context =0;1546struct fragment **fragp = &patch->fragments;15471548while(size >4&& !memcmp(line,"@@ -",4)) {1549struct fragment *fragment;1550int len;15511552 fragment =xcalloc(1,sizeof(*fragment));1553 fragment->linenr = linenr;1554 len =parse_fragment(line, size, patch, fragment);1555if(len <=0)1556die("corrupt patch at line%d", linenr);1557 fragment->patch = line;1558 fragment->size = len;1559 oldlines += fragment->oldlines;1560 newlines += fragment->newlines;1561 context += fragment->leading + fragment->trailing;15621563*fragp = fragment;1564 fragp = &fragment->next;15651566 offset += len;1567 line += len;1568 size -= len;1569}15701571/*1572 * If something was removed (i.e. we have old-lines) it cannot1573 * be creation, and if something was added it cannot be1574 * deletion. However, the reverse is not true; --unified=01575 * patches that only add are not necessarily creation even1576 * though they do not have any old lines, and ones that only1577 * delete are not necessarily deletion.1578 *1579 * Unfortunately, a real creation/deletion patch do _not_ have1580 * any context line by definition, so we cannot safely tell it1581 * apart with --unified=0 insanity. At least if the patch has1582 * more than one hunk it is not creation or deletion.1583 */1584if(patch->is_new <0&&1585(oldlines || (patch->fragments && patch->fragments->next)))1586 patch->is_new =0;1587if(patch->is_delete <0&&1588(newlines || (patch->fragments && patch->fragments->next)))1589 patch->is_delete =0;15901591if(0< patch->is_new && oldlines)1592die("new file%sdepends on old contents", patch->new_name);1593if(0< patch->is_delete && newlines)1594die("deleted file%sstill has contents", patch->old_name);1595if(!patch->is_delete && !newlines && context)1596fprintf(stderr,"** warning: file%sbecomes empty but "1597"is not deleted\n", patch->new_name);15981599return offset;1600}16011602staticinlineintmetadata_changes(struct patch *patch)1603{1604return patch->is_rename >0||1605 patch->is_copy >0||1606 patch->is_new >0||1607 patch->is_delete ||1608(patch->old_mode && patch->new_mode &&1609 patch->old_mode != patch->new_mode);1610}16111612static char*inflate_it(const void*data,unsigned long size,1613unsigned long inflated_size)1614{1615 z_stream stream;1616void*out;1617int st;16181619memset(&stream,0,sizeof(stream));16201621 stream.next_in = (unsigned char*)data;1622 stream.avail_in = size;1623 stream.next_out = out =xmalloc(inflated_size);1624 stream.avail_out = inflated_size;1625git_inflate_init(&stream);1626 st =git_inflate(&stream, Z_FINISH);1627git_inflate_end(&stream);1628if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1629free(out);1630return NULL;1631}1632return out;1633}16341635static struct fragment *parse_binary_hunk(char**buf_p,1636unsigned long*sz_p,1637int*status_p,1638int*used_p)1639{1640/*1641 * Expect a line that begins with binary patch method ("literal"1642 * or "delta"), followed by the length of data before deflating.1643 * a sequence of 'length-byte' followed by base-85 encoded data1644 * should follow, terminated by a newline.1645 *1646 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1647 * and we would limit the patch line to 66 characters,1648 * so one line can fit up to 13 groups that would decode1649 * to 52 bytes max. The length byte 'A'-'Z' corresponds1650 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1651 */1652int llen, used;1653unsigned long size = *sz_p;1654char*buffer = *buf_p;1655int patch_method;1656unsigned long origlen;1657char*data = NULL;1658int hunk_size =0;1659struct fragment *frag;16601661 llen =linelen(buffer, size);1662 used = llen;16631664*status_p =0;16651666if(!prefixcmp(buffer,"delta ")) {1667 patch_method = BINARY_DELTA_DEFLATED;1668 origlen =strtoul(buffer +6, NULL,10);1669}1670else if(!prefixcmp(buffer,"literal ")) {1671 patch_method = BINARY_LITERAL_DEFLATED;1672 origlen =strtoul(buffer +8, NULL,10);1673}1674else1675return NULL;16761677 linenr++;1678 buffer += llen;1679while(1) {1680int byte_length, max_byte_length, newsize;1681 llen =linelen(buffer, size);1682 used += llen;1683 linenr++;1684if(llen ==1) {1685/* consume the blank line */1686 buffer++;1687 size--;1688break;1689}1690/*1691 * Minimum line is "A00000\n" which is 7-byte long,1692 * and the line length must be multiple of 5 plus 2.1693 */1694if((llen <7) || (llen-2) %5)1695goto corrupt;1696 max_byte_length = (llen -2) /5*4;1697 byte_length = *buffer;1698if('A'<= byte_length && byte_length <='Z')1699 byte_length = byte_length -'A'+1;1700else if('a'<= byte_length && byte_length <='z')1701 byte_length = byte_length -'a'+27;1702else1703goto corrupt;1704/* if the input length was not multiple of 4, we would1705 * have filler at the end but the filler should never1706 * exceed 3 bytes1707 */1708if(max_byte_length < byte_length ||1709 byte_length <= max_byte_length -4)1710goto corrupt;1711 newsize = hunk_size + byte_length;1712 data =xrealloc(data, newsize);1713if(decode_85(data + hunk_size, buffer +1, byte_length))1714goto corrupt;1715 hunk_size = newsize;1716 buffer += llen;1717 size -= llen;1718}17191720 frag =xcalloc(1,sizeof(*frag));1721 frag->patch =inflate_it(data, hunk_size, origlen);1722if(!frag->patch)1723goto corrupt;1724free(data);1725 frag->size = origlen;1726*buf_p = buffer;1727*sz_p = size;1728*used_p = used;1729 frag->binary_patch_method = patch_method;1730return frag;17311732 corrupt:1733free(data);1734*status_p = -1;1735error("corrupt binary patch at line%d: %.*s",1736 linenr-1, llen-1, buffer);1737return NULL;1738}17391740static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1741{1742/*1743 * We have read "GIT binary patch\n"; what follows is a line1744 * that says the patch method (currently, either "literal" or1745 * "delta") and the length of data before deflating; a1746 * sequence of 'length-byte' followed by base-85 encoded data1747 * follows.1748 *1749 * When a binary patch is reversible, there is another binary1750 * hunk in the same format, starting with patch method (either1751 * "literal" or "delta") with the length of data, and a sequence1752 * of length-byte + base-85 encoded data, terminated with another1753 * empty line. This data, when applied to the postimage, produces1754 * the preimage.1755 */1756struct fragment *forward;1757struct fragment *reverse;1758int status;1759int used, used_1;17601761 forward =parse_binary_hunk(&buffer, &size, &status, &used);1762if(!forward && !status)1763/* there has to be one hunk (forward hunk) */1764returnerror("unrecognized binary patch at line%d", linenr-1);1765if(status)1766/* otherwise we already gave an error message */1767return status;17681769 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1770if(reverse)1771 used += used_1;1772else if(status) {1773/*1774 * Not having reverse hunk is not an error, but having1775 * a corrupt reverse hunk is.1776 */1777free((void*) forward->patch);1778free(forward);1779return status;1780}1781 forward->next = reverse;1782 patch->fragments = forward;1783 patch->is_binary =1;1784return used;1785}17861787static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1788{1789int hdrsize, patchsize;1790int offset =find_header(buffer, size, &hdrsize, patch);17911792if(offset <0)1793return offset;17941795 patch->ws_rule =whitespace_rule(patch->new_name1796? patch->new_name1797: patch->old_name);17981799 patchsize =parse_single_patch(buffer + offset + hdrsize,1800 size - offset - hdrsize, patch);18011802if(!patchsize) {1803static const char*binhdr[] = {1804"Binary files ",1805"Files ",1806 NULL,1807};1808static const char git_binary[] ="GIT binary patch\n";1809int i;1810int hd = hdrsize + offset;1811unsigned long llen =linelen(buffer + hd, size - hd);18121813if(llen ==sizeof(git_binary) -1&&1814!memcmp(git_binary, buffer + hd, llen)) {1815int used;1816 linenr++;1817 used =parse_binary(buffer + hd + llen,1818 size - hd - llen, patch);1819if(used)1820 patchsize = used + llen;1821else1822 patchsize =0;1823}1824else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1825for(i =0; binhdr[i]; i++) {1826int len =strlen(binhdr[i]);1827if(len < size - hd &&1828!memcmp(binhdr[i], buffer + hd, len)) {1829 linenr++;1830 patch->is_binary =1;1831 patchsize = llen;1832break;1833}1834}1835}18361837/* Empty patch cannot be applied if it is a text patch1838 * without metadata change. A binary patch appears1839 * empty to us here.1840 */1841if((apply || check) &&1842(!patch->is_binary && !metadata_changes(patch)))1843die("patch with only garbage at line%d", linenr);1844}18451846return offset + hdrsize + patchsize;1847}18481849#define swap(a,b) myswap((a),(b),sizeof(a))18501851#define myswap(a, b, size) do { \1852 unsigned char mytmp[size]; \1853 memcpy(mytmp, &a, size); \1854 memcpy(&a, &b, size); \1855 memcpy(&b, mytmp, size); \1856} while (0)18571858static voidreverse_patches(struct patch *p)1859{1860for(; p; p = p->next) {1861struct fragment *frag = p->fragments;18621863swap(p->new_name, p->old_name);1864swap(p->new_mode, p->old_mode);1865swap(p->is_new, p->is_delete);1866swap(p->lines_added, p->lines_deleted);1867swap(p->old_sha1_prefix, p->new_sha1_prefix);18681869for(; frag; frag = frag->next) {1870swap(frag->newpos, frag->oldpos);1871swap(frag->newlines, frag->oldlines);1872}1873}1874}18751876static const char pluses[] =1877"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";1878static const char minuses[]=1879"----------------------------------------------------------------------";18801881static voidshow_stats(struct patch *patch)1882{1883struct strbuf qname = STRBUF_INIT;1884char*cp = patch->new_name ? patch->new_name : patch->old_name;1885int max, add, del;18861887quote_c_style(cp, &qname, NULL,0);18881889/*1890 * "scale" the filename1891 */1892 max = max_len;1893if(max >50)1894 max =50;18951896if(qname.len > max) {1897 cp =strchr(qname.buf + qname.len +3- max,'/');1898if(!cp)1899 cp = qname.buf + qname.len +3- max;1900strbuf_splice(&qname,0, cp - qname.buf,"...",3);1901}19021903if(patch->is_binary) {1904printf(" %-*s | Bin\n", max, qname.buf);1905strbuf_release(&qname);1906return;1907}19081909printf(" %-*s |", max, qname.buf);1910strbuf_release(&qname);19111912/*1913 * scale the add/delete1914 */1915 max = max + max_change >70?70- max : max_change;1916 add = patch->lines_added;1917 del = patch->lines_deleted;19181919if(max_change >0) {1920int total = ((add + del) * max + max_change /2) / max_change;1921 add = (add * max + max_change /2) / max_change;1922 del = total - add;1923}1924printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,1925 add, pluses, del, minuses);1926}19271928static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)1929{1930switch(st->st_mode & S_IFMT) {1931case S_IFLNK:1932if(strbuf_readlink(buf, path, st->st_size) <0)1933returnerror("unable to read symlink%s", path);1934return0;1935case S_IFREG:1936if(strbuf_read_file(buf, path, st->st_size) != st->st_size)1937returnerror("unable to open or read%s", path);1938convert_to_git(path, buf->buf, buf->len, buf,0);1939return0;1940default:1941return-1;1942}1943}19441945/*1946 * Update the preimage, and the common lines in postimage,1947 * from buffer buf of length len. If postlen is 0 the postimage1948 * is updated in place, otherwise it's updated on a new buffer1949 * of length postlen1950 */19511952static voidupdate_pre_post_images(struct image *preimage,1953struct image *postimage,1954char*buf,1955size_t len,size_t postlen)1956{1957int i, ctx;1958char*new, *old, *fixed;1959struct image fixed_preimage;19601961/*1962 * Update the preimage with whitespace fixes. Note that we1963 * are not losing preimage->buf -- apply_one_fragment() will1964 * free "oldlines".1965 */1966prepare_image(&fixed_preimage, buf, len,1);1967assert(fixed_preimage.nr == preimage->nr);1968for(i =0; i < preimage->nr; i++)1969 fixed_preimage.line[i].flag = preimage->line[i].flag;1970free(preimage->line_allocated);1971*preimage = fixed_preimage;19721973/*1974 * Adjust the common context lines in postimage. This can be1975 * done in-place when we are just doing whitespace fixing,1976 * which does not make the string grow, but needs a new buffer1977 * when ignoring whitespace causes the update, since in this case1978 * we could have e.g. tabs converted to multiple spaces.1979 * We trust the caller to tell us if the update can be done1980 * in place (postlen==0) or not.1981 */1982 old = postimage->buf;1983if(postlen)1984new= postimage->buf =xmalloc(postlen);1985else1986new= old;1987 fixed = preimage->buf;1988for(i = ctx =0; i < postimage->nr; i++) {1989size_t len = postimage->line[i].len;1990if(!(postimage->line[i].flag & LINE_COMMON)) {1991/* an added line -- no counterparts in preimage */1992memmove(new, old, len);1993 old += len;1994new+= len;1995continue;1996}19971998/* a common context -- skip it in the original postimage */1999 old += len;20002001/* and find the corresponding one in the fixed preimage */2002while(ctx < preimage->nr &&2003!(preimage->line[ctx].flag & LINE_COMMON)) {2004 fixed += preimage->line[ctx].len;2005 ctx++;2006}2007if(preimage->nr <= ctx)2008die("oops");20092010/* and copy it in, while fixing the line length */2011 len = preimage->line[ctx].len;2012memcpy(new, fixed, len);2013new+= len;2014 fixed += len;2015 postimage->line[i].len = len;2016 ctx++;2017}20182019/* Fix the length of the whole thing */2020 postimage->len =new- postimage->buf;2021}20222023static intmatch_fragment(struct image *img,2024struct image *preimage,2025struct image *postimage,2026unsigned longtry,2027int try_lno,2028unsigned ws_rule,2029int match_beginning,int match_end)2030{2031int i;2032char*fixed_buf, *buf, *orig, *target;2033struct strbuf fixed;2034size_t fixed_len;2035int preimage_limit;20362037if(preimage->nr + try_lno <= img->nr) {2038/*2039 * The hunk falls within the boundaries of img.2040 */2041 preimage_limit = preimage->nr;2042if(match_end && (preimage->nr + try_lno != img->nr))2043return0;2044}else if(ws_error_action == correct_ws_error &&2045(ws_rule & WS_BLANK_AT_EOF)) {2046/*2047 * This hunk extends beyond the end of img, and we are2048 * removing blank lines at the end of the file. This2049 * many lines from the beginning of the preimage must2050 * match with img, and the remainder of the preimage2051 * must be blank.2052 */2053 preimage_limit = img->nr - try_lno;2054}else{2055/*2056 * The hunk extends beyond the end of the img and2057 * we are not removing blanks at the end, so we2058 * should reject the hunk at this position.2059 */2060return0;2061}20622063if(match_beginning && try_lno)2064return0;20652066/* Quick hash check */2067for(i =0; i < preimage_limit; i++)2068if(preimage->line[i].hash != img->line[try_lno + i].hash)2069return0;20702071if(preimage_limit == preimage->nr) {2072/*2073 * Do we have an exact match? If we were told to match2074 * at the end, size must be exactly at try+fragsize,2075 * otherwise try+fragsize must be still within the preimage,2076 * and either case, the old piece should match the preimage2077 * exactly.2078 */2079if((match_end2080? (try+ preimage->len == img->len)2081: (try+ preimage->len <= img->len)) &&2082!memcmp(img->buf +try, preimage->buf, preimage->len))2083return1;2084}else{2085/*2086 * The preimage extends beyond the end of img, so2087 * there cannot be an exact match.2088 *2089 * There must be one non-blank context line that match2090 * a line before the end of img.2091 */2092char*buf_end;20932094 buf = preimage->buf;2095 buf_end = buf;2096for(i =0; i < preimage_limit; i++)2097 buf_end += preimage->line[i].len;20982099for( ; buf < buf_end; buf++)2100if(!isspace(*buf))2101break;2102if(buf == buf_end)2103return0;2104}21052106/*2107 * No exact match. If we are ignoring whitespace, run a line-by-line2108 * fuzzy matching. We collect all the line length information because2109 * we need it to adjust whitespace if we match.2110 */2111if(ws_ignore_action == ignore_ws_change) {2112size_t imgoff =0;2113size_t preoff =0;2114size_t postlen = postimage->len;2115size_t extra_chars;2116char*preimage_eof;2117char*preimage_end;2118for(i =0; i < preimage_limit; i++) {2119size_t prelen = preimage->line[i].len;2120size_t imglen = img->line[try_lno+i].len;21212122if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2123 preimage->buf + preoff, prelen))2124return0;2125if(preimage->line[i].flag & LINE_COMMON)2126 postlen += imglen - prelen;2127 imgoff += imglen;2128 preoff += prelen;2129}21302131/*2132 * Ok, the preimage matches with whitespace fuzz.2133 *2134 * imgoff now holds the true length of the target that2135 * matches the preimage before the end of the file.2136 *2137 * Count the number of characters in the preimage that fall2138 * beyond the end of the file and make sure that all of them2139 * are whitespace characters. (This can only happen if2140 * we are removing blank lines at the end of the file.)2141 */2142 buf = preimage_eof = preimage->buf + preoff;2143for( ; i < preimage->nr; i++)2144 preoff += preimage->line[i].len;2145 preimage_end = preimage->buf + preoff;2146for( ; buf < preimage_end; buf++)2147if(!isspace(*buf))2148return0;21492150/*2151 * Update the preimage and the common postimage context2152 * lines to use the same whitespace as the target.2153 * If whitespace is missing in the target (i.e.2154 * if the preimage extends beyond the end of the file),2155 * use the whitespace from the preimage.2156 */2157 extra_chars = preimage_end - preimage_eof;2158strbuf_init(&fixed, imgoff + extra_chars);2159strbuf_add(&fixed, img->buf +try, imgoff);2160strbuf_add(&fixed, preimage_eof, extra_chars);2161 fixed_buf =strbuf_detach(&fixed, &fixed_len);2162update_pre_post_images(preimage, postimage,2163 fixed_buf, fixed_len, postlen);2164return1;2165}21662167if(ws_error_action != correct_ws_error)2168return0;21692170/*2171 * The hunk does not apply byte-by-byte, but the hash says2172 * it might with whitespace fuzz. We haven't been asked to2173 * ignore whitespace, we were asked to correct whitespace2174 * errors, so let's try matching after whitespace correction.2175 *2176 * The preimage may extend beyond the end of the file,2177 * but in this loop we will only handle the part of the2178 * preimage that falls within the file.2179 */2180strbuf_init(&fixed, preimage->len +1);2181 orig = preimage->buf;2182 target = img->buf +try;2183for(i =0; i < preimage_limit; i++) {2184size_t oldlen = preimage->line[i].len;2185size_t tgtlen = img->line[try_lno + i].len;2186size_t fixstart = fixed.len;2187struct strbuf tgtfix;2188int match;21892190/* Try fixing the line in the preimage */2191ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);21922193/* Try fixing the line in the target */2194strbuf_init(&tgtfix, tgtlen);2195ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);21962197/*2198 * If they match, either the preimage was based on2199 * a version before our tree fixed whitespace breakage,2200 * or we are lacking a whitespace-fix patch the tree2201 * the preimage was based on already had (i.e. target2202 * has whitespace breakage, the preimage doesn't).2203 * In either case, we are fixing the whitespace breakages2204 * so we might as well take the fix together with their2205 * real change.2206 */2207 match = (tgtfix.len == fixed.len - fixstart &&2208!memcmp(tgtfix.buf, fixed.buf + fixstart,2209 fixed.len - fixstart));22102211strbuf_release(&tgtfix);2212if(!match)2213goto unmatch_exit;22142215 orig += oldlen;2216 target += tgtlen;2217}221822192220/*2221 * Now handle the lines in the preimage that falls beyond the2222 * end of the file (if any). They will only match if they are2223 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2224 * false).2225 */2226for( ; i < preimage->nr; i++) {2227size_t fixstart = fixed.len;/* start of the fixed preimage */2228size_t oldlen = preimage->line[i].len;2229int j;22302231/* Try fixing the line in the preimage */2232ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);22332234for(j = fixstart; j < fixed.len; j++)2235if(!isspace(fixed.buf[j]))2236goto unmatch_exit;22372238 orig += oldlen;2239}22402241/*2242 * Yes, the preimage is based on an older version that still2243 * has whitespace breakages unfixed, and fixing them makes the2244 * hunk match. Update the context lines in the postimage.2245 */2246 fixed_buf =strbuf_detach(&fixed, &fixed_len);2247update_pre_post_images(preimage, postimage,2248 fixed_buf, fixed_len,0);2249return1;22502251 unmatch_exit:2252strbuf_release(&fixed);2253return0;2254}22552256static intfind_pos(struct image *img,2257struct image *preimage,2258struct image *postimage,2259int line,2260unsigned ws_rule,2261int match_beginning,int match_end)2262{2263int i;2264unsigned long backwards, forwards,try;2265int backwards_lno, forwards_lno, try_lno;22662267/*2268 * If match_beginning or match_end is specified, there is no2269 * point starting from a wrong line that will never match and2270 * wander around and wait for a match at the specified end.2271 */2272if(match_beginning)2273 line =0;2274else if(match_end)2275 line = img->nr - preimage->nr;22762277/*2278 * Because the comparison is unsigned, the following test2279 * will also take care of a negative line number that can2280 * result when match_end and preimage is larger than the target.2281 */2282if((size_t) line > img->nr)2283 line = img->nr;22842285try=0;2286for(i =0; i < line; i++)2287try+= img->line[i].len;22882289/*2290 * There's probably some smart way to do this, but I'll leave2291 * that to the smart and beautiful people. I'm simple and stupid.2292 */2293 backwards =try;2294 backwards_lno = line;2295 forwards =try;2296 forwards_lno = line;2297 try_lno = line;22982299for(i =0; ; i++) {2300if(match_fragment(img, preimage, postimage,2301try, try_lno, ws_rule,2302 match_beginning, match_end))2303return try_lno;23042305 again:2306if(backwards_lno ==0&& forwards_lno == img->nr)2307break;23082309if(i &1) {2310if(backwards_lno ==0) {2311 i++;2312goto again;2313}2314 backwards_lno--;2315 backwards -= img->line[backwards_lno].len;2316try= backwards;2317 try_lno = backwards_lno;2318}else{2319if(forwards_lno == img->nr) {2320 i++;2321goto again;2322}2323 forwards += img->line[forwards_lno].len;2324 forwards_lno++;2325try= forwards;2326 try_lno = forwards_lno;2327}23282329}2330return-1;2331}23322333static voidremove_first_line(struct image *img)2334{2335 img->buf += img->line[0].len;2336 img->len -= img->line[0].len;2337 img->line++;2338 img->nr--;2339}23402341static voidremove_last_line(struct image *img)2342{2343 img->len -= img->line[--img->nr].len;2344}23452346static voidupdate_image(struct image *img,2347int applied_pos,2348struct image *preimage,2349struct image *postimage)2350{2351/*2352 * remove the copy of preimage at offset in img2353 * and replace it with postimage2354 */2355int i, nr;2356size_t remove_count, insert_count, applied_at =0;2357char*result;2358int preimage_limit;23592360/*2361 * If we are removing blank lines at the end of img,2362 * the preimage may extend beyond the end.2363 * If that is the case, we must be careful only to2364 * remove the part of the preimage that falls within2365 * the boundaries of img. Initialize preimage_limit2366 * to the number of lines in the preimage that falls2367 * within the boundaries.2368 */2369 preimage_limit = preimage->nr;2370if(preimage_limit > img->nr - applied_pos)2371 preimage_limit = img->nr - applied_pos;23722373for(i =0; i < applied_pos; i++)2374 applied_at += img->line[i].len;23752376 remove_count =0;2377for(i =0; i < preimage_limit; i++)2378 remove_count += img->line[applied_pos + i].len;2379 insert_count = postimage->len;23802381/* Adjust the contents */2382 result =xmalloc(img->len + insert_count - remove_count +1);2383memcpy(result, img->buf, applied_at);2384memcpy(result + applied_at, postimage->buf, postimage->len);2385memcpy(result + applied_at + postimage->len,2386 img->buf + (applied_at + remove_count),2387 img->len - (applied_at + remove_count));2388free(img->buf);2389 img->buf = result;2390 img->len += insert_count - remove_count;2391 result[img->len] ='\0';23922393/* Adjust the line table */2394 nr = img->nr + postimage->nr - preimage_limit;2395if(preimage_limit < postimage->nr) {2396/*2397 * NOTE: this knows that we never call remove_first_line()2398 * on anything other than pre/post image.2399 */2400 img->line =xrealloc(img->line, nr *sizeof(*img->line));2401 img->line_allocated = img->line;2402}2403if(preimage_limit != postimage->nr)2404memmove(img->line + applied_pos + postimage->nr,2405 img->line + applied_pos + preimage_limit,2406(img->nr - (applied_pos + preimage_limit)) *2407sizeof(*img->line));2408memcpy(img->line + applied_pos,2409 postimage->line,2410 postimage->nr *sizeof(*img->line));2411 img->nr = nr;2412}24132414static intapply_one_fragment(struct image *img,struct fragment *frag,2415int inaccurate_eof,unsigned ws_rule)2416{2417int match_beginning, match_end;2418const char*patch = frag->patch;2419int size = frag->size;2420char*old, *oldlines;2421struct strbuf newlines;2422int new_blank_lines_at_end =0;2423unsigned long leading, trailing;2424int pos, applied_pos;2425struct image preimage;2426struct image postimage;24272428memset(&preimage,0,sizeof(preimage));2429memset(&postimage,0,sizeof(postimage));2430 oldlines =xmalloc(size);2431strbuf_init(&newlines, size);24322433 old = oldlines;2434while(size >0) {2435char first;2436int len =linelen(patch, size);2437int plen;2438int added_blank_line =0;2439int is_blank_context =0;2440size_t start;24412442if(!len)2443break;24442445/*2446 * "plen" is how much of the line we should use for2447 * the actual patch data. Normally we just remove the2448 * first character on the line, but if the line is2449 * followed by "\ No newline", then we also remove the2450 * last one (which is the newline, of course).2451 */2452 plen = len -1;2453if(len < size && patch[len] =='\\')2454 plen--;2455 first = *patch;2456if(apply_in_reverse) {2457if(first =='-')2458 first ='+';2459else if(first =='+')2460 first ='-';2461}24622463switch(first) {2464case'\n':2465/* Newer GNU diff, empty context line */2466if(plen <0)2467/* ... followed by '\No newline'; nothing */2468break;2469*old++ ='\n';2470strbuf_addch(&newlines,'\n');2471add_line_info(&preimage,"\n",1, LINE_COMMON);2472add_line_info(&postimage,"\n",1, LINE_COMMON);2473 is_blank_context =1;2474break;2475case' ':2476if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2477ws_blank_line(patch +1, plen, ws_rule))2478 is_blank_context =1;2479case'-':2480memcpy(old, patch +1, plen);2481add_line_info(&preimage, old, plen,2482(first ==' '? LINE_COMMON :0));2483 old += plen;2484if(first =='-')2485break;2486/* Fall-through for ' ' */2487case'+':2488/* --no-add does not add new lines */2489if(first =='+'&& no_add)2490break;24912492 start = newlines.len;2493if(first !='+'||2494!whitespace_error ||2495 ws_error_action != correct_ws_error) {2496strbuf_add(&newlines, patch +1, plen);2497}2498else{2499ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2500}2501add_line_info(&postimage, newlines.buf + start, newlines.len - start,2502(first =='+'?0: LINE_COMMON));2503if(first =='+'&&2504(ws_rule & WS_BLANK_AT_EOF) &&2505ws_blank_line(patch +1, plen, ws_rule))2506 added_blank_line =1;2507break;2508case'@':case'\\':2509/* Ignore it, we already handled it */2510break;2511default:2512if(apply_verbosely)2513error("invalid start of line: '%c'", first);2514return-1;2515}2516if(added_blank_line)2517 new_blank_lines_at_end++;2518else if(is_blank_context)2519;2520else2521 new_blank_lines_at_end =0;2522 patch += len;2523 size -= len;2524}2525if(inaccurate_eof &&2526 old > oldlines && old[-1] =='\n'&&2527 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2528 old--;2529strbuf_setlen(&newlines, newlines.len -1);2530}25312532 leading = frag->leading;2533 trailing = frag->trailing;25342535/*2536 * A hunk to change lines at the beginning would begin with2537 * @@ -1,L +N,M @@2538 * but we need to be careful. -U0 that inserts before the second2539 * line also has this pattern.2540 *2541 * And a hunk to add to an empty file would begin with2542 * @@ -0,0 +N,M @@2543 *2544 * In other words, a hunk that is (frag->oldpos <= 1) with or2545 * without leading context must match at the beginning.2546 */2547 match_beginning = (!frag->oldpos ||2548(frag->oldpos ==1&& !unidiff_zero));25492550/*2551 * A hunk without trailing lines must match at the end.2552 * However, we simply cannot tell if a hunk must match end2553 * from the lack of trailing lines if the patch was generated2554 * with unidiff without any context.2555 */2556 match_end = !unidiff_zero && !trailing;25572558 pos = frag->newpos ? (frag->newpos -1) :0;2559 preimage.buf = oldlines;2560 preimage.len = old - oldlines;2561 postimage.buf = newlines.buf;2562 postimage.len = newlines.len;2563 preimage.line = preimage.line_allocated;2564 postimage.line = postimage.line_allocated;25652566for(;;) {25672568 applied_pos =find_pos(img, &preimage, &postimage, pos,2569 ws_rule, match_beginning, match_end);25702571if(applied_pos >=0)2572break;25732574/* Am I at my context limits? */2575if((leading <= p_context) && (trailing <= p_context))2576break;2577if(match_beginning || match_end) {2578 match_beginning = match_end =0;2579continue;2580}25812582/*2583 * Reduce the number of context lines; reduce both2584 * leading and trailing if they are equal otherwise2585 * just reduce the larger context.2586 */2587if(leading >= trailing) {2588remove_first_line(&preimage);2589remove_first_line(&postimage);2590 pos--;2591 leading--;2592}2593if(trailing > leading) {2594remove_last_line(&preimage);2595remove_last_line(&postimage);2596 trailing--;2597}2598}25992600if(applied_pos >=0) {2601if(new_blank_lines_at_end &&2602 preimage.nr + applied_pos >= img->nr &&2603(ws_rule & WS_BLANK_AT_EOF) &&2604 ws_error_action != nowarn_ws_error) {2605record_ws_error(WS_BLANK_AT_EOF,"+",1, frag->linenr);2606if(ws_error_action == correct_ws_error) {2607while(new_blank_lines_at_end--)2608remove_last_line(&postimage);2609}2610/*2611 * We would want to prevent write_out_results()2612 * from taking place in apply_patch() that follows2613 * the callchain led us here, which is:2614 * apply_patch->check_patch_list->check_patch->2615 * apply_data->apply_fragments->apply_one_fragment2616 */2617if(ws_error_action == die_on_ws_error)2618 apply =0;2619}26202621/*2622 * Warn if it was necessary to reduce the number2623 * of context lines.2624 */2625if((leading != frag->leading) ||2626(trailing != frag->trailing))2627fprintf(stderr,"Context reduced to (%ld/%ld)"2628" to apply fragment at%d\n",2629 leading, trailing, applied_pos+1);2630update_image(img, applied_pos, &preimage, &postimage);2631}else{2632if(apply_verbosely)2633error("while searching for:\n%.*s",2634(int)(old - oldlines), oldlines);2635}26362637free(oldlines);2638strbuf_release(&newlines);2639free(preimage.line_allocated);2640free(postimage.line_allocated);26412642return(applied_pos <0);2643}26442645static intapply_binary_fragment(struct image *img,struct patch *patch)2646{2647struct fragment *fragment = patch->fragments;2648unsigned long len;2649void*dst;26502651/* Binary patch is irreversible without the optional second hunk */2652if(apply_in_reverse) {2653if(!fragment->next)2654returnerror("cannot reverse-apply a binary patch "2655"without the reverse hunk to '%s'",2656 patch->new_name2657? patch->new_name : patch->old_name);2658 fragment = fragment->next;2659}2660switch(fragment->binary_patch_method) {2661case BINARY_DELTA_DEFLATED:2662 dst =patch_delta(img->buf, img->len, fragment->patch,2663 fragment->size, &len);2664if(!dst)2665return-1;2666clear_image(img);2667 img->buf = dst;2668 img->len = len;2669return0;2670case BINARY_LITERAL_DEFLATED:2671clear_image(img);2672 img->len = fragment->size;2673 img->buf =xmalloc(img->len+1);2674memcpy(img->buf, fragment->patch, img->len);2675 img->buf[img->len] ='\0';2676return0;2677}2678return-1;2679}26802681static intapply_binary(struct image *img,struct patch *patch)2682{2683const char*name = patch->old_name ? patch->old_name : patch->new_name;2684unsigned char sha1[20];26852686/*2687 * For safety, we require patch index line to contain2688 * full 40-byte textual SHA1 for old and new, at least for now.2689 */2690if(strlen(patch->old_sha1_prefix) !=40||2691strlen(patch->new_sha1_prefix) !=40||2692get_sha1_hex(patch->old_sha1_prefix, sha1) ||2693get_sha1_hex(patch->new_sha1_prefix, sha1))2694returnerror("cannot apply binary patch to '%s' "2695"without full index line", name);26962697if(patch->old_name) {2698/*2699 * See if the old one matches what the patch2700 * applies to.2701 */2702hash_sha1_file(img->buf, img->len, blob_type, sha1);2703if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2704returnerror("the patch applies to '%s' (%s), "2705"which does not match the "2706"current contents.",2707 name,sha1_to_hex(sha1));2708}2709else{2710/* Otherwise, the old one must be empty. */2711if(img->len)2712returnerror("the patch applies to an empty "2713"'%s' but it is not empty", name);2714}27152716get_sha1_hex(patch->new_sha1_prefix, sha1);2717if(is_null_sha1(sha1)) {2718clear_image(img);2719return0;/* deletion patch */2720}27212722if(has_sha1_file(sha1)) {2723/* We already have the postimage */2724enum object_type type;2725unsigned long size;2726char*result;27272728 result =read_sha1_file(sha1, &type, &size);2729if(!result)2730returnerror("the necessary postimage%sfor "2731"'%s' cannot be read",2732 patch->new_sha1_prefix, name);2733clear_image(img);2734 img->buf = result;2735 img->len = size;2736}else{2737/*2738 * We have verified buf matches the preimage;2739 * apply the patch data to it, which is stored2740 * in the patch->fragments->{patch,size}.2741 */2742if(apply_binary_fragment(img, patch))2743returnerror("binary patch does not apply to '%s'",2744 name);27452746/* verify that the result matches */2747hash_sha1_file(img->buf, img->len, blob_type, sha1);2748if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2749returnerror("binary patch to '%s' creates incorrect result (expecting%s, got%s)",2750 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2751}27522753return0;2754}27552756static intapply_fragments(struct image *img,struct patch *patch)2757{2758struct fragment *frag = patch->fragments;2759const char*name = patch->old_name ? patch->old_name : patch->new_name;2760unsigned ws_rule = patch->ws_rule;2761unsigned inaccurate_eof = patch->inaccurate_eof;27622763if(patch->is_binary)2764returnapply_binary(img, patch);27652766while(frag) {2767if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule)) {2768error("patch failed:%s:%ld", name, frag->oldpos);2769if(!apply_with_reject)2770return-1;2771 frag->rejected =1;2772}2773 frag = frag->next;2774}2775return0;2776}27772778static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2779{2780if(!ce)2781return0;27822783if(S_ISGITLINK(ce->ce_mode)) {2784strbuf_grow(buf,100);2785strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2786}else{2787enum object_type type;2788unsigned long sz;2789char*result;27902791 result =read_sha1_file(ce->sha1, &type, &sz);2792if(!result)2793return-1;2794/* XXX read_sha1_file NUL-terminates */2795strbuf_attach(buf, result, sz, sz +1);2796}2797return0;2798}27992800static struct patch *in_fn_table(const char*name)2801{2802struct string_list_item *item;28032804if(name == NULL)2805return NULL;28062807 item =string_list_lookup(&fn_table, name);2808if(item != NULL)2809return(struct patch *)item->util;28102811return NULL;2812}28132814/*2815 * item->util in the filename table records the status of the path.2816 * Usually it points at a patch (whose result records the contents2817 * of it after applying it), but it could be PATH_WAS_DELETED for a2818 * path that a previously applied patch has already removed.2819 */2820#define PATH_TO_BE_DELETED ((struct patch *) -2)2821#define PATH_WAS_DELETED ((struct patch *) -1)28222823static intto_be_deleted(struct patch *patch)2824{2825return patch == PATH_TO_BE_DELETED;2826}28272828static intwas_deleted(struct patch *patch)2829{2830return patch == PATH_WAS_DELETED;2831}28322833static voidadd_to_fn_table(struct patch *patch)2834{2835struct string_list_item *item;28362837/*2838 * Always add new_name unless patch is a deletion2839 * This should cover the cases for normal diffs,2840 * file creations and copies2841 */2842if(patch->new_name != NULL) {2843 item =string_list_insert(&fn_table, patch->new_name);2844 item->util = patch;2845}28462847/*2848 * store a failure on rename/deletion cases because2849 * later chunks shouldn't patch old names2850 */2851if((patch->new_name == NULL) || (patch->is_rename)) {2852 item =string_list_insert(&fn_table, patch->old_name);2853 item->util = PATH_WAS_DELETED;2854}2855}28562857static voidprepare_fn_table(struct patch *patch)2858{2859/*2860 * store information about incoming file deletion2861 */2862while(patch) {2863if((patch->new_name == NULL) || (patch->is_rename)) {2864struct string_list_item *item;2865 item =string_list_insert(&fn_table, patch->old_name);2866 item->util = PATH_TO_BE_DELETED;2867}2868 patch = patch->next;2869}2870}28712872static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)2873{2874struct strbuf buf = STRBUF_INIT;2875struct image image;2876size_t len;2877char*img;2878struct patch *tpatch;28792880if(!(patch->is_copy || patch->is_rename) &&2881(tpatch =in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {2882if(was_deleted(tpatch)) {2883returnerror("patch%shas been renamed/deleted",2884 patch->old_name);2885}2886/* We have a patched copy in memory use that */2887strbuf_add(&buf, tpatch->result, tpatch->resultsize);2888}else if(cached) {2889if(read_file_or_gitlink(ce, &buf))2890returnerror("read of%sfailed", patch->old_name);2891}else if(patch->old_name) {2892if(S_ISGITLINK(patch->old_mode)) {2893if(ce) {2894read_file_or_gitlink(ce, &buf);2895}else{2896/*2897 * There is no way to apply subproject2898 * patch without looking at the index.2899 */2900 patch->fragments = NULL;2901}2902}else{2903if(read_old_data(st, patch->old_name, &buf))2904returnerror("read of%sfailed", patch->old_name);2905}2906}29072908 img =strbuf_detach(&buf, &len);2909prepare_image(&image, img, len, !patch->is_binary);29102911if(apply_fragments(&image, patch) <0)2912return-1;/* note with --reject this succeeds. */2913 patch->result = image.buf;2914 patch->resultsize = image.len;2915add_to_fn_table(patch);2916free(image.line_allocated);29172918if(0< patch->is_delete && patch->resultsize)2919returnerror("removal patch leaves file contents");29202921return0;2922}29232924static intcheck_to_create_blob(const char*new_name,int ok_if_exists)2925{2926struct stat nst;2927if(!lstat(new_name, &nst)) {2928if(S_ISDIR(nst.st_mode) || ok_if_exists)2929return0;2930/*2931 * A leading component of new_name might be a symlink2932 * that is going to be removed with this patch, but2933 * still pointing at somewhere that has the path.2934 * In such a case, path "new_name" does not exist as2935 * far as git is concerned.2936 */2937if(has_symlink_leading_path(new_name,strlen(new_name)))2938return0;29392940returnerror("%s: already exists in working directory", new_name);2941}2942else if((errno != ENOENT) && (errno != ENOTDIR))2943returnerror("%s:%s", new_name,strerror(errno));2944return0;2945}29462947static intverify_index_match(struct cache_entry *ce,struct stat *st)2948{2949if(S_ISGITLINK(ce->ce_mode)) {2950if(!S_ISDIR(st->st_mode))2951return-1;2952return0;2953}2954returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);2955}29562957static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)2958{2959const char*old_name = patch->old_name;2960struct patch *tpatch = NULL;2961int stat_ret =0;2962unsigned st_mode =0;29632964/*2965 * Make sure that we do not have local modifications from the2966 * index when we are looking at the index. Also make sure2967 * we have the preimage file to be patched in the work tree,2968 * unless --cached, which tells git to apply only in the index.2969 */2970if(!old_name)2971return0;29722973assert(patch->is_new <=0);29742975if(!(patch->is_copy || patch->is_rename) &&2976(tpatch =in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {2977if(was_deleted(tpatch))2978returnerror("%s: has been deleted/renamed", old_name);2979 st_mode = tpatch->new_mode;2980}else if(!cached) {2981 stat_ret =lstat(old_name, st);2982if(stat_ret && errno != ENOENT)2983returnerror("%s:%s", old_name,strerror(errno));2984}29852986if(to_be_deleted(tpatch))2987 tpatch = NULL;29882989if(check_index && !tpatch) {2990int pos =cache_name_pos(old_name,strlen(old_name));2991if(pos <0) {2992if(patch->is_new <0)2993goto is_new;2994returnerror("%s: does not exist in index", old_name);2995}2996*ce = active_cache[pos];2997if(stat_ret <0) {2998struct checkout costate;2999/* checkout */3000memset(&costate,0,sizeof(costate));3001 costate.base_dir ="";3002 costate.refresh_cache =1;3003if(checkout_entry(*ce, &costate, NULL) ||3004lstat(old_name, st))3005return-1;3006}3007if(!cached &&verify_index_match(*ce, st))3008returnerror("%s: does not match index", old_name);3009if(cached)3010 st_mode = (*ce)->ce_mode;3011}else if(stat_ret <0) {3012if(patch->is_new <0)3013goto is_new;3014returnerror("%s:%s", old_name,strerror(errno));3015}30163017if(!cached && !tpatch)3018 st_mode =ce_mode_from_stat(*ce, st->st_mode);30193020if(patch->is_new <0)3021 patch->is_new =0;3022if(!patch->old_mode)3023 patch->old_mode = st_mode;3024if((st_mode ^ patch->old_mode) & S_IFMT)3025returnerror("%s: wrong type", old_name);3026if(st_mode != patch->old_mode)3027warning("%shas type%o, expected%o",3028 old_name, st_mode, patch->old_mode);3029if(!patch->new_mode && !patch->is_delete)3030 patch->new_mode = st_mode;3031return0;30323033 is_new:3034 patch->is_new =1;3035 patch->is_delete =0;3036 patch->old_name = NULL;3037return0;3038}30393040static intcheck_patch(struct patch *patch)3041{3042struct stat st;3043const char*old_name = patch->old_name;3044const char*new_name = patch->new_name;3045const char*name = old_name ? old_name : new_name;3046struct cache_entry *ce = NULL;3047struct patch *tpatch;3048int ok_if_exists;3049int status;30503051 patch->rejected =1;/* we will drop this after we succeed */30523053 status =check_preimage(patch, &ce, &st);3054if(status)3055return status;3056 old_name = patch->old_name;30573058if((tpatch =in_fn_table(new_name)) &&3059(was_deleted(tpatch) ||to_be_deleted(tpatch)))3060/*3061 * A type-change diff is always split into a patch to3062 * delete old, immediately followed by a patch to3063 * create new (see diff.c::run_diff()); in such a case3064 * it is Ok that the entry to be deleted by the3065 * previous patch is still in the working tree and in3066 * the index.3067 */3068 ok_if_exists =1;3069else3070 ok_if_exists =0;30713072if(new_name &&3073((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {3074if(check_index &&3075cache_name_pos(new_name,strlen(new_name)) >=0&&3076!ok_if_exists)3077returnerror("%s: already exists in index", new_name);3078if(!cached) {3079int err =check_to_create_blob(new_name, ok_if_exists);3080if(err)3081return err;3082}3083if(!patch->new_mode) {3084if(0< patch->is_new)3085 patch->new_mode = S_IFREG |0644;3086else3087 patch->new_mode = patch->old_mode;3088}3089}30903091if(new_name && old_name) {3092int same = !strcmp(old_name, new_name);3093if(!patch->new_mode)3094 patch->new_mode = patch->old_mode;3095if((patch->old_mode ^ patch->new_mode) & S_IFMT)3096returnerror("new mode (%o) of%sdoes not match old mode (%o)%s%s",3097 patch->new_mode, new_name, patch->old_mode,3098 same ?"":" of ", same ?"": old_name);3099}31003101if(apply_data(patch, &st, ce) <0)3102returnerror("%s: patch does not apply", name);3103 patch->rejected =0;3104return0;3105}31063107static intcheck_patch_list(struct patch *patch)3108{3109int err =0;31103111prepare_fn_table(patch);3112while(patch) {3113if(apply_verbosely)3114say_patch_name(stderr,3115"Checking patch ", patch,"...\n");3116 err |=check_patch(patch);3117 patch = patch->next;3118}3119return err;3120}31213122/* This function tries to read the sha1 from the current index */3123static intget_current_sha1(const char*path,unsigned char*sha1)3124{3125int pos;31263127if(read_cache() <0)3128return-1;3129 pos =cache_name_pos(path,strlen(path));3130if(pos <0)3131return-1;3132hashcpy(sha1, active_cache[pos]->sha1);3133return0;3134}31353136/* Build an index that contains the just the files needed for a 3way merge */3137static voidbuild_fake_ancestor(struct patch *list,const char*filename)3138{3139struct patch *patch;3140struct index_state result = { NULL };3141int fd;31423143/* Once we start supporting the reverse patch, it may be3144 * worth showing the new sha1 prefix, but until then...3145 */3146for(patch = list; patch; patch = patch->next) {3147const unsigned char*sha1_ptr;3148unsigned char sha1[20];3149struct cache_entry *ce;3150const char*name;31513152 name = patch->old_name ? patch->old_name : patch->new_name;3153if(0< patch->is_new)3154continue;3155else if(get_sha1(patch->old_sha1_prefix, sha1))3156/* git diff has no index line for mode/type changes */3157if(!patch->lines_added && !patch->lines_deleted) {3158if(get_current_sha1(patch->old_name, sha1))3159die("mode change for%s, which is not "3160"in current HEAD", name);3161 sha1_ptr = sha1;3162}else3163die("sha1 information is lacking or useless "3164"(%s).", name);3165else3166 sha1_ptr = sha1;31673168 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);3169if(!ce)3170die("make_cache_entry failed for path '%s'", name);3171if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3172die("Could not add%sto temporary index", name);3173}31743175 fd =open(filename, O_WRONLY | O_CREAT,0666);3176if(fd <0||write_index(&result, fd) ||close(fd))3177die("Could not write temporary index to%s", filename);31783179discard_index(&result);3180}31813182static voidstat_patch_list(struct patch *patch)3183{3184int files, adds, dels;31853186for(files = adds = dels =0; patch ; patch = patch->next) {3187 files++;3188 adds += patch->lines_added;3189 dels += patch->lines_deleted;3190show_stats(patch);3191}31923193printf("%dfiles changed,%dinsertions(+),%ddeletions(-)\n", files, adds, dels);3194}31953196static voidnumstat_patch_list(struct patch *patch)3197{3198for( ; patch; patch = patch->next) {3199const char*name;3200 name = patch->new_name ? patch->new_name : patch->old_name;3201if(patch->is_binary)3202printf("-\t-\t");3203else3204printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3205write_name_quoted(name, stdout, line_termination);3206}3207}32083209static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3210{3211if(mode)3212printf("%smode%06o%s\n", newdelete, mode, name);3213else3214printf("%s %s\n", newdelete, name);3215}32163217static voidshow_mode_change(struct patch *p,int show_name)3218{3219if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3220if(show_name)3221printf(" mode change%06o =>%06o%s\n",3222 p->old_mode, p->new_mode, p->new_name);3223else3224printf(" mode change%06o =>%06o\n",3225 p->old_mode, p->new_mode);3226}3227}32283229static voidshow_rename_copy(struct patch *p)3230{3231const char*renamecopy = p->is_rename ?"rename":"copy";3232const char*old, *new;32333234/* Find common prefix */3235 old = p->old_name;3236new= p->new_name;3237while(1) {3238const char*slash_old, *slash_new;3239 slash_old =strchr(old,'/');3240 slash_new =strchr(new,'/');3241if(!slash_old ||3242!slash_new ||3243 slash_old - old != slash_new -new||3244memcmp(old,new, slash_new -new))3245break;3246 old = slash_old +1;3247new= slash_new +1;3248}3249/* p->old_name thru old is the common prefix, and old and new3250 * through the end of names are renames3251 */3252if(old != p->old_name)3253printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,3254(int)(old - p->old_name), p->old_name,3255 old,new, p->score);3256else3257printf("%s %s=>%s(%d%%)\n", renamecopy,3258 p->old_name, p->new_name, p->score);3259show_mode_change(p,0);3260}32613262static voidsummary_patch_list(struct patch *patch)3263{3264struct patch *p;32653266for(p = patch; p; p = p->next) {3267if(p->is_new)3268show_file_mode_name("create", p->new_mode, p->new_name);3269else if(p->is_delete)3270show_file_mode_name("delete", p->old_mode, p->old_name);3271else{3272if(p->is_rename || p->is_copy)3273show_rename_copy(p);3274else{3275if(p->score) {3276printf(" rewrite%s(%d%%)\n",3277 p->new_name, p->score);3278show_mode_change(p,0);3279}3280else3281show_mode_change(p,1);3282}3283}3284}3285}32863287static voidpatch_stats(struct patch *patch)3288{3289int lines = patch->lines_added + patch->lines_deleted;32903291if(lines > max_change)3292 max_change = lines;3293if(patch->old_name) {3294int len =quote_c_style(patch->old_name, NULL, NULL,0);3295if(!len)3296 len =strlen(patch->old_name);3297if(len > max_len)3298 max_len = len;3299}3300if(patch->new_name) {3301int len =quote_c_style(patch->new_name, NULL, NULL,0);3302if(!len)3303 len =strlen(patch->new_name);3304if(len > max_len)3305 max_len = len;3306}3307}33083309static voidremove_file(struct patch *patch,int rmdir_empty)3310{3311if(update_index) {3312if(remove_file_from_cache(patch->old_name) <0)3313die("unable to remove%sfrom index", patch->old_name);3314}3315if(!cached) {3316if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {3317remove_path(patch->old_name);3318}3319}3320}33213322static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)3323{3324struct stat st;3325struct cache_entry *ce;3326int namelen =strlen(path);3327unsigned ce_size =cache_entry_size(namelen);33283329if(!update_index)3330return;33313332 ce =xcalloc(1, ce_size);3333memcpy(ce->name, path, namelen);3334 ce->ce_mode =create_ce_mode(mode);3335 ce->ce_flags = namelen;3336if(S_ISGITLINK(mode)) {3337const char*s = buf;33383339if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))3340die("corrupt patch for subproject%s", path);3341}else{3342if(!cached) {3343if(lstat(path, &st) <0)3344die_errno("unable to stat newly created file '%s'",3345 path);3346fill_stat_cache_info(ce, &st);3347}3348if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)3349die("unable to create backing store for newly created file%s", path);3350}3351if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3352die("unable to add cache entry for%s", path);3353}33543355static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)3356{3357int fd;3358struct strbuf nbuf = STRBUF_INIT;33593360if(S_ISGITLINK(mode)) {3361struct stat st;3362if(!lstat(path, &st) &&S_ISDIR(st.st_mode))3363return0;3364returnmkdir(path,0777);3365}33663367if(has_symlinks &&S_ISLNK(mode))3368/* Although buf:size is counted string, it also is NUL3369 * terminated.3370 */3371returnsymlink(buf, path);33723373 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);3374if(fd <0)3375return-1;33763377if(convert_to_working_tree(path, buf, size, &nbuf)) {3378 size = nbuf.len;3379 buf = nbuf.buf;3380}3381write_or_die(fd, buf, size);3382strbuf_release(&nbuf);33833384if(close(fd) <0)3385die_errno("closing file '%s'", path);3386return0;3387}33883389/*3390 * We optimistically assume that the directories exist,3391 * which is true 99% of the time anyway. If they don't,3392 * we create them and try again.3393 */3394static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)3395{3396if(cached)3397return;3398if(!try_create_file(path, mode, buf, size))3399return;34003401if(errno == ENOENT) {3402if(safe_create_leading_directories(path))3403return;3404if(!try_create_file(path, mode, buf, size))3405return;3406}34073408if(errno == EEXIST || errno == EACCES) {3409/* We may be trying to create a file where a directory3410 * used to be.3411 */3412struct stat st;3413if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))3414 errno = EEXIST;3415}34163417if(errno == EEXIST) {3418unsigned int nr =getpid();34193420for(;;) {3421char newpath[PATH_MAX];3422mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);3423if(!try_create_file(newpath, mode, buf, size)) {3424if(!rename(newpath, path))3425return;3426unlink_or_warn(newpath);3427break;3428}3429if(errno != EEXIST)3430break;3431++nr;3432}3433}3434die_errno("unable to write file '%s' mode%o", path, mode);3435}34363437static voidcreate_file(struct patch *patch)3438{3439char*path = patch->new_name;3440unsigned mode = patch->new_mode;3441unsigned long size = patch->resultsize;3442char*buf = patch->result;34433444if(!mode)3445 mode = S_IFREG |0644;3446create_one_file(path, mode, buf, size);3447add_index_file(path, mode, buf, size);3448}34493450/* phase zero is to remove, phase one is to create */3451static voidwrite_out_one_result(struct patch *patch,int phase)3452{3453if(patch->is_delete >0) {3454if(phase ==0)3455remove_file(patch,1);3456return;3457}3458if(patch->is_new >0|| patch->is_copy) {3459if(phase ==1)3460create_file(patch);3461return;3462}3463/*3464 * Rename or modification boils down to the same3465 * thing: remove the old, write the new3466 */3467if(phase ==0)3468remove_file(patch, patch->is_rename);3469if(phase ==1)3470create_file(patch);3471}34723473static intwrite_out_one_reject(struct patch *patch)3474{3475FILE*rej;3476char namebuf[PATH_MAX];3477struct fragment *frag;3478int cnt =0;34793480for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {3481if(!frag->rejected)3482continue;3483 cnt++;3484}34853486if(!cnt) {3487if(apply_verbosely)3488say_patch_name(stderr,3489"Applied patch ", patch," cleanly.\n");3490return0;3491}34923493/* This should not happen, because a removal patch that leaves3494 * contents are marked "rejected" at the patch level.3495 */3496if(!patch->new_name)3497die("internal error");34983499/* Say this even without --verbose */3500say_patch_name(stderr,"Applying patch ", patch," with");3501fprintf(stderr,"%drejects...\n", cnt);35023503 cnt =strlen(patch->new_name);3504if(ARRAY_SIZE(namebuf) <= cnt +5) {3505 cnt =ARRAY_SIZE(namebuf) -5;3506warning("truncating .rej filename to %.*s.rej",3507 cnt -1, patch->new_name);3508}3509memcpy(namebuf, patch->new_name, cnt);3510memcpy(namebuf + cnt,".rej",5);35113512 rej =fopen(namebuf,"w");3513if(!rej)3514returnerror("cannot open%s:%s", namebuf,strerror(errno));35153516/* Normal git tools never deal with .rej, so do not pretend3517 * this is a git patch by saying --git nor give extended3518 * headers. While at it, maybe please "kompare" that wants3519 * the trailing TAB and some garbage at the end of line ;-).3520 */3521fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",3522 patch->new_name, patch->new_name);3523for(cnt =1, frag = patch->fragments;3524 frag;3525 cnt++, frag = frag->next) {3526if(!frag->rejected) {3527fprintf(stderr,"Hunk #%dapplied cleanly.\n", cnt);3528continue;3529}3530fprintf(stderr,"Rejected hunk #%d.\n", cnt);3531fprintf(rej,"%.*s", frag->size, frag->patch);3532if(frag->patch[frag->size-1] !='\n')3533fputc('\n', rej);3534}3535fclose(rej);3536return-1;3537}35383539static intwrite_out_results(struct patch *list,int skipped_patch)3540{3541int phase;3542int errs =0;3543struct patch *l;35443545if(!list && !skipped_patch)3546returnerror("No changes");35473548for(phase =0; phase <2; phase++) {3549 l = list;3550while(l) {3551if(l->rejected)3552 errs =1;3553else{3554write_out_one_result(l, phase);3555if(phase ==1&&write_out_one_reject(l))3556 errs =1;3557}3558 l = l->next;3559}3560}3561return errs;3562}35633564static struct lock_file lock_file;35653566static struct string_list limit_by_name;3567static int has_include;3568static voidadd_name_limit(const char*name,int exclude)3569{3570struct string_list_item *it;35713572 it =string_list_append(&limit_by_name, name);3573 it->util = exclude ? NULL : (void*)1;3574}35753576static intuse_patch(struct patch *p)3577{3578const char*pathname = p->new_name ? p->new_name : p->old_name;3579int i;35803581/* Paths outside are not touched regardless of "--include" */3582if(0< prefix_length) {3583int pathlen =strlen(pathname);3584if(pathlen <= prefix_length ||3585memcmp(prefix, pathname, prefix_length))3586return0;3587}35883589/* See if it matches any of exclude/include rule */3590for(i =0; i < limit_by_name.nr; i++) {3591struct string_list_item *it = &limit_by_name.items[i];3592if(!fnmatch(it->string, pathname,0))3593return(it->util != NULL);3594}35953596/*3597 * If we had any include, a path that does not match any rule is3598 * not used. Otherwise, we saw bunch of exclude rules (or none)3599 * and such a path is used.3600 */3601return!has_include;3602}360336043605static voidprefix_one(char**name)3606{3607char*old_name = *name;3608if(!old_name)3609return;3610*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3611free(old_name);3612}36133614static voidprefix_patches(struct patch *p)3615{3616if(!prefix || p->is_toplevel_relative)3617return;3618for( ; p; p = p->next) {3619if(p->new_name == p->old_name) {3620char*prefixed = p->new_name;3621prefix_one(&prefixed);3622 p->new_name = p->old_name = prefixed;3623}3624else{3625prefix_one(&p->new_name);3626prefix_one(&p->old_name);3627}3628}3629}36303631#define INACCURATE_EOF (1<<0)3632#define RECOUNT (1<<1)36333634static intapply_patch(int fd,const char*filename,int options)3635{3636size_t offset;3637struct strbuf buf = STRBUF_INIT;3638struct patch *list = NULL, **listp = &list;3639int skipped_patch =0;36403641/* FIXME - memory leak when using multiple patch files as inputs */3642memset(&fn_table,0,sizeof(struct string_list));3643 patch_input_file = filename;3644read_patch_file(&buf, fd);3645 offset =0;3646while(offset < buf.len) {3647struct patch *patch;3648int nr;36493650 patch =xcalloc(1,sizeof(*patch));3651 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3652 patch->recount = !!(options & RECOUNT);3653 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3654if(nr <0)3655break;3656if(apply_in_reverse)3657reverse_patches(patch);3658if(prefix)3659prefix_patches(patch);3660if(use_patch(patch)) {3661patch_stats(patch);3662*listp = patch;3663 listp = &patch->next;3664}3665else{3666/* perhaps free it a bit better? */3667free(patch);3668 skipped_patch++;3669}3670 offset += nr;3671}36723673if(whitespace_error && (ws_error_action == die_on_ws_error))3674 apply =0;36753676 update_index = check_index && apply;3677if(update_index && newfd <0)3678 newfd =hold_locked_index(&lock_file,1);36793680if(check_index) {3681if(read_cache() <0)3682die("unable to read index file");3683}36843685if((check || apply) &&3686check_patch_list(list) <0&&3687!apply_with_reject)3688exit(1);36893690if(apply &&write_out_results(list, skipped_patch))3691exit(1);36923693if(fake_ancestor)3694build_fake_ancestor(list, fake_ancestor);36953696if(diffstat)3697stat_patch_list(list);36983699if(numstat)3700numstat_patch_list(list);37013702if(summary)3703summary_patch_list(list);37043705strbuf_release(&buf);3706return0;3707}37083709static intgit_apply_config(const char*var,const char*value,void*cb)3710{3711if(!strcmp(var,"apply.whitespace"))3712returngit_config_string(&apply_default_whitespace, var, value);3713else if(!strcmp(var,"apply.ignorewhitespace"))3714returngit_config_string(&apply_default_ignorewhitespace, var, value);3715returngit_default_config(var, value, cb);3716}37173718static intoption_parse_exclude(const struct option *opt,3719const char*arg,int unset)3720{3721add_name_limit(arg,1);3722return0;3723}37243725static intoption_parse_include(const struct option *opt,3726const char*arg,int unset)3727{3728add_name_limit(arg,0);3729 has_include =1;3730return0;3731}37323733static intoption_parse_p(const struct option *opt,3734const char*arg,int unset)3735{3736 p_value =atoi(arg);3737 p_value_known =1;3738return0;3739}37403741static intoption_parse_z(const struct option *opt,3742const char*arg,int unset)3743{3744if(unset)3745 line_termination ='\n';3746else3747 line_termination =0;3748return0;3749}37503751static intoption_parse_space_change(const struct option *opt,3752const char*arg,int unset)3753{3754if(unset)3755 ws_ignore_action = ignore_ws_none;3756else3757 ws_ignore_action = ignore_ws_change;3758return0;3759}37603761static intoption_parse_whitespace(const struct option *opt,3762const char*arg,int unset)3763{3764const char**whitespace_option = opt->value;37653766*whitespace_option = arg;3767parse_whitespace_option(arg);3768return0;3769}37703771static intoption_parse_directory(const struct option *opt,3772const char*arg,int unset)3773{3774 root_len =strlen(arg);3775if(root_len && arg[root_len -1] !='/') {3776char*new_root;3777 root = new_root =xmalloc(root_len +2);3778strcpy(new_root, arg);3779strcpy(new_root + root_len++,"/");3780}else3781 root = arg;3782return0;3783}37843785intcmd_apply(int argc,const char**argv,const char*prefix_)3786{3787int i;3788int errs =0;3789int is_not_gitdir = !startup_info->have_repository;3790int binary;3791int force_apply =0;37923793const char*whitespace_option = NULL;37943795struct option builtin_apply_options[] = {3796{ OPTION_CALLBACK,0,"exclude", NULL,"path",3797"don't apply changes matching the given path",37980, option_parse_exclude },3799{ OPTION_CALLBACK,0,"include", NULL,"path",3800"apply changes matching the given path",38010, option_parse_include },3802{ OPTION_CALLBACK,'p', NULL, NULL,"num",3803"remove <num> leading slashes from traditional diff paths",38040, option_parse_p },3805OPT_BOOLEAN(0,"no-add", &no_add,3806"ignore additions made by the patch"),3807OPT_BOOLEAN(0,"stat", &diffstat,3808"instead of applying the patch, output diffstat for the input"),3809{ OPTION_BOOLEAN,0,"allow-binary-replacement", &binary,3810 NULL,"old option, now no-op",3811 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3812{ OPTION_BOOLEAN,0,"binary", &binary,3813 NULL,"old option, now no-op",3814 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3815OPT_BOOLEAN(0,"numstat", &numstat,3816"shows number of added and deleted lines in decimal notation"),3817OPT_BOOLEAN(0,"summary", &summary,3818"instead of applying the patch, output a summary for the input"),3819OPT_BOOLEAN(0,"check", &check,3820"instead of applying the patch, see if the patch is applicable"),3821OPT_BOOLEAN(0,"index", &check_index,3822"make sure the patch is applicable to the current index"),3823OPT_BOOLEAN(0,"cached", &cached,3824"apply a patch without touching the working tree"),3825OPT_BOOLEAN(0,"apply", &force_apply,3826"also apply the patch (use with --stat/--summary/--check)"),3827OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,3828"build a temporary index based on embedded index information"),3829{ OPTION_CALLBACK,'z', NULL, NULL, NULL,3830"paths are separated with NUL character",3831 PARSE_OPT_NOARG, option_parse_z },3832OPT_INTEGER('C', NULL, &p_context,3833"ensure at least <n> lines of context match"),3834{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,"action",3835"detect new or modified lines that have whitespace errors",38360, option_parse_whitespace },3837{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,3838"ignore changes in whitespace when finding context",3839 PARSE_OPT_NOARG, option_parse_space_change },3840{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,3841"ignore changes in whitespace when finding context",3842 PARSE_OPT_NOARG, option_parse_space_change },3843OPT_BOOLEAN('R',"reverse", &apply_in_reverse,3844"apply the patch in reverse"),3845OPT_BOOLEAN(0,"unidiff-zero", &unidiff_zero,3846"don't expect at least one line of context"),3847OPT_BOOLEAN(0,"reject", &apply_with_reject,3848"leave the rejected hunks in corresponding *.rej files"),3849OPT__VERBOSE(&apply_verbosely),3850OPT_BIT(0,"inaccurate-eof", &options,3851"tolerate incorrectly detected missing new-line at the end of file",3852 INACCURATE_EOF),3853OPT_BIT(0,"recount", &options,3854"do not trust the line counts in the hunk headers",3855 RECOUNT),3856{ OPTION_CALLBACK,0,"directory", NULL,"root",3857"prepend <root> to all filenames",38580, option_parse_directory },3859OPT_END()3860};38613862 prefix = prefix_;3863 prefix_length = prefix ?strlen(prefix) :0;3864git_config(git_apply_config, NULL);3865if(apply_default_whitespace)3866parse_whitespace_option(apply_default_whitespace);3867if(apply_default_ignorewhitespace)3868parse_ignorewhitespace_option(apply_default_ignorewhitespace);38693870 argc =parse_options(argc, argv, prefix, builtin_apply_options,3871 apply_usage,0);38723873if(apply_with_reject)3874 apply = apply_verbosely =1;3875if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))3876 apply =0;3877if(check_index && is_not_gitdir)3878die("--index outside a repository");3879if(cached) {3880if(is_not_gitdir)3881die("--cached outside a repository");3882 check_index =1;3883}3884for(i =0; i < argc; i++) {3885const char*arg = argv[i];3886int fd;38873888if(!strcmp(arg,"-")) {3889 errs |=apply_patch(0,"<stdin>", options);3890 read_stdin =0;3891continue;3892}else if(0< prefix_length)3893 arg =prefix_filename(prefix, prefix_length, arg);38943895 fd =open(arg, O_RDONLY);3896if(fd <0)3897die_errno("can't open patch '%s'", arg);3898 read_stdin =0;3899set_default_whitespace_mode(whitespace_option);3900 errs |=apply_patch(fd, arg, options);3901close(fd);3902}3903set_default_whitespace_mode(whitespace_option);3904if(read_stdin)3905 errs |=apply_patch(0,"<stdin>", options);3906if(whitespace_error) {3907if(squelch_whitespace_errors &&3908 squelch_whitespace_errors < whitespace_error) {3909int squelched =3910 whitespace_error - squelch_whitespace_errors;3911warning("squelched%d"3912"whitespace error%s",3913 squelched,3914 squelched ==1?"":"s");3915}3916if(ws_error_action == die_on_ws_error)3917die("%dline%sadd%swhitespace errors.",3918 whitespace_error,3919 whitespace_error ==1?"":"s",3920 whitespace_error ==1?"s":"");3921if(applied_after_fixing_ws && apply)3922warning("%dline%sapplied after"3923" fixing whitespace errors.",3924 applied_after_fixing_ws,3925 applied_after_fixing_ws ==1?"":"s");3926else if(whitespace_error)3927warning("%dline%sadd%swhitespace errors.",3928 whitespace_error,3929 whitespace_error ==1?"":"s",3930 whitespace_error ==1?"s":"");3931}39323933if(update_index) {3934if(write_cache(newfd, active_cache, active_nr) ||3935commit_locked_index(&lock_file))3936die("Unable to write new index file");3937}39383939return!!errs;3940}