1/* 2 * apply.c 3 * 4 * Copyright (C) Linus Torvalds, 2005 5 * 6 * This applies patches on top of some (arbitrary) version of the SCM. 7 * 8 */ 9#include"cache.h" 10#include"cache-tree.h" 11#include"quote.h" 12#include"blob.h" 13#include"delta.h" 14#include"builtin.h" 15#include"string-list.h" 16#include"dir.h" 17#include"parse-options.h" 18 19/* 20 * --check turns on checking that the working tree matches the 21 * files that are being modified, but doesn't apply the patch 22 * --stat does just a diffstat, and doesn't actually apply 23 * --numstat does numeric diffstat, and doesn't actually apply 24 * --index-info shows the old and new index info for paths if available. 25 * --index updates the cache as well. 26 * --cached updates only the cache without ever touching the working tree. 27 */ 28static const char*prefix; 29static int prefix_length = -1; 30static int newfd = -1; 31 32static int unidiff_zero; 33static int p_value =1; 34static int p_value_known; 35static int check_index; 36static int update_index; 37static int cached; 38static int diffstat; 39static int numstat; 40static int summary; 41static int check; 42static int apply =1; 43static int apply_in_reverse; 44static int apply_with_reject; 45static int apply_verbosely; 46static int allow_overlap; 47static int no_add; 48static const char*fake_ancestor; 49static int line_termination ='\n'; 50static unsigned int p_context = UINT_MAX; 51static const char*const apply_usage[] = { 52"git apply [options] [<patch>...]", 53 NULL 54}; 55 56static enum ws_error_action { 57 nowarn_ws_error, 58 warn_on_ws_error, 59 die_on_ws_error, 60 correct_ws_error 61} ws_error_action = warn_on_ws_error; 62static int whitespace_error; 63static int squelch_whitespace_errors =5; 64static int applied_after_fixing_ws; 65 66static enum ws_ignore { 67 ignore_ws_none, 68 ignore_ws_change 69} ws_ignore_action = ignore_ws_none; 70 71 72static const char*patch_input_file; 73static const char*root; 74static int root_len; 75static int read_stdin =1; 76static int options; 77 78static voidparse_whitespace_option(const char*option) 79{ 80if(!option) { 81 ws_error_action = warn_on_ws_error; 82return; 83} 84if(!strcmp(option,"warn")) { 85 ws_error_action = warn_on_ws_error; 86return; 87} 88if(!strcmp(option,"nowarn")) { 89 ws_error_action = nowarn_ws_error; 90return; 91} 92if(!strcmp(option,"error")) { 93 ws_error_action = die_on_ws_error; 94return; 95} 96if(!strcmp(option,"error-all")) { 97 ws_error_action = die_on_ws_error; 98 squelch_whitespace_errors =0; 99return; 100} 101if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 102 ws_error_action = correct_ws_error; 103return; 104} 105die("unrecognized whitespace option '%s'", option); 106} 107 108static voidparse_ignorewhitespace_option(const char*option) 109{ 110if(!option || !strcmp(option,"no") || 111!strcmp(option,"false") || !strcmp(option,"never") || 112!strcmp(option,"none")) { 113 ws_ignore_action = ignore_ws_none; 114return; 115} 116if(!strcmp(option,"change")) { 117 ws_ignore_action = ignore_ws_change; 118return; 119} 120die("unrecognized whitespace ignore option '%s'", option); 121} 122 123static voidset_default_whitespace_mode(const char*whitespace_option) 124{ 125if(!whitespace_option && !apply_default_whitespace) 126 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 127} 128 129/* 130 * For "diff-stat" like behaviour, we keep track of the biggest change 131 * we've seen, and the longest filename. That allows us to do simple 132 * scaling. 133 */ 134static int max_change, max_len; 135 136/* 137 * Various "current state", notably line numbers and what 138 * file (and how) we're patching right now.. The "is_xxxx" 139 * things are flags, where -1 means "don't know yet". 140 */ 141static int linenr =1; 142 143/* 144 * This represents one "hunk" from a patch, starting with 145 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 146 * patch text is pointed at by patch, and its byte length 147 * is stored in size. leading and trailing are the number 148 * of context lines. 149 */ 150struct fragment { 151unsigned long leading, trailing; 152unsigned long oldpos, oldlines; 153unsigned long newpos, newlines; 154const char*patch; 155int size; 156int rejected; 157int linenr; 158struct fragment *next; 159}; 160 161/* 162 * When dealing with a binary patch, we reuse "leading" field 163 * to store the type of the binary hunk, either deflated "delta" 164 * or deflated "literal". 165 */ 166#define binary_patch_method leading 167#define BINARY_DELTA_DEFLATED 1 168#define BINARY_LITERAL_DEFLATED 2 169 170/* 171 * This represents a "patch" to a file, both metainfo changes 172 * such as creation/deletion, filemode and content changes represented 173 * as a series of fragments. 174 */ 175struct patch { 176char*new_name, *old_name, *def_name; 177unsigned int old_mode, new_mode; 178int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 179int rejected; 180unsigned ws_rule; 181unsigned long deflate_origlen; 182int lines_added, lines_deleted; 183int score; 184unsigned int is_toplevel_relative:1; 185unsigned int inaccurate_eof:1; 186unsigned int is_binary:1; 187unsigned int is_copy:1; 188unsigned int is_rename:1; 189unsigned int recount:1; 190struct fragment *fragments; 191char*result; 192size_t resultsize; 193char old_sha1_prefix[41]; 194char new_sha1_prefix[41]; 195struct patch *next; 196}; 197 198/* 199 * A line in a file, len-bytes long (includes the terminating LF, 200 * except for an incomplete line at the end if the file ends with 201 * one), and its contents hashes to 'hash'. 202 */ 203struct line { 204size_t len; 205unsigned hash :24; 206unsigned flag :8; 207#define LINE_COMMON 1 208#define LINE_PATCHED 2 209}; 210 211/* 212 * This represents a "file", which is an array of "lines". 213 */ 214struct image { 215char*buf; 216size_t len; 217size_t nr; 218size_t alloc; 219struct line *line_allocated; 220struct line *line; 221}; 222 223/* 224 * Records filenames that have been touched, in order to handle 225 * the case where more than one patches touch the same file. 226 */ 227 228static struct string_list fn_table; 229 230static uint32_thash_line(const char*cp,size_t len) 231{ 232size_t i; 233uint32_t h; 234for(i =0, h =0; i < len; i++) { 235if(!isspace(cp[i])) { 236 h = h *3+ (cp[i] &0xff); 237} 238} 239return h; 240} 241 242/* 243 * Compare lines s1 of length n1 and s2 of length n2, ignoring 244 * whitespace difference. Returns 1 if they match, 0 otherwise 245 */ 246static intfuzzy_matchlines(const char*s1,size_t n1, 247const char*s2,size_t n2) 248{ 249const char*last1 = s1 + n1 -1; 250const char*last2 = s2 + n2 -1; 251int result =0; 252 253if(n1 <0|| n2 <0) 254return0; 255 256/* ignore line endings */ 257while((*last1 =='\r') || (*last1 =='\n')) 258 last1--; 259while((*last2 =='\r') || (*last2 =='\n')) 260 last2--; 261 262/* skip leading whitespace */ 263while(isspace(*s1) && (s1 <= last1)) 264 s1++; 265while(isspace(*s2) && (s2 <= last2)) 266 s2++; 267/* early return if both lines are empty */ 268if((s1 > last1) && (s2 > last2)) 269return1; 270while(!result) { 271 result = *s1++ - *s2++; 272/* 273 * Skip whitespace inside. We check for whitespace on 274 * both buffers because we don't want "a b" to match 275 * "ab" 276 */ 277if(isspace(*s1) &&isspace(*s2)) { 278while(isspace(*s1) && s1 <= last1) 279 s1++; 280while(isspace(*s2) && s2 <= last2) 281 s2++; 282} 283/* 284 * If we reached the end on one side only, 285 * lines don't match 286 */ 287if( 288((s2 > last2) && (s1 <= last1)) || 289((s1 > last1) && (s2 <= last2))) 290return0; 291if((s1 > last1) && (s2 > last2)) 292break; 293} 294 295return!result; 296} 297 298static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 299{ 300ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 301 img->line_allocated[img->nr].len = len; 302 img->line_allocated[img->nr].hash =hash_line(bol, len); 303 img->line_allocated[img->nr].flag = flag; 304 img->nr++; 305} 306 307static voidprepare_image(struct image *image,char*buf,size_t len, 308int prepare_linetable) 309{ 310const char*cp, *ep; 311 312memset(image,0,sizeof(*image)); 313 image->buf = buf; 314 image->len = len; 315 316if(!prepare_linetable) 317return; 318 319 ep = image->buf + image->len; 320 cp = image->buf; 321while(cp < ep) { 322const char*next; 323for(next = cp; next < ep && *next !='\n'; next++) 324; 325if(next < ep) 326 next++; 327add_line_info(image, cp, next - cp,0); 328 cp = next; 329} 330 image->line = image->line_allocated; 331} 332 333static voidclear_image(struct image *image) 334{ 335free(image->buf); 336 image->buf = NULL; 337 image->len =0; 338} 339 340static voidsay_patch_name(FILE*output,const char*pre, 341struct patch *patch,const char*post) 342{ 343fputs(pre, output); 344if(patch->old_name && patch->new_name && 345strcmp(patch->old_name, patch->new_name)) { 346quote_c_style(patch->old_name, NULL, output,0); 347fputs(" => ", output); 348quote_c_style(patch->new_name, NULL, output,0); 349}else{ 350const char*n = patch->new_name; 351if(!n) 352 n = patch->old_name; 353quote_c_style(n, NULL, output,0); 354} 355fputs(post, output); 356} 357 358#define CHUNKSIZE (8192) 359#define SLOP (16) 360 361static voidread_patch_file(struct strbuf *sb,int fd) 362{ 363if(strbuf_read(sb, fd,0) <0) 364die_errno("git apply: failed to read"); 365 366/* 367 * Make sure that we have some slop in the buffer 368 * so that we can do speculative "memcmp" etc, and 369 * see to it that it is NUL-filled. 370 */ 371strbuf_grow(sb, SLOP); 372memset(sb->buf + sb->len,0, SLOP); 373} 374 375static unsigned longlinelen(const char*buffer,unsigned long size) 376{ 377unsigned long len =0; 378while(size--) { 379 len++; 380if(*buffer++ =='\n') 381break; 382} 383return len; 384} 385 386static intis_dev_null(const char*str) 387{ 388return!memcmp("/dev/null", str,9) &&isspace(str[9]); 389} 390 391#define TERM_SPACE 1 392#define TERM_TAB 2 393 394static intname_terminate(const char*name,int namelen,int c,int terminate) 395{ 396if(c ==' '&& !(terminate & TERM_SPACE)) 397return0; 398if(c =='\t'&& !(terminate & TERM_TAB)) 399return0; 400 401return1; 402} 403 404/* remove double slashes to make --index work with such filenames */ 405static char*squash_slash(char*name) 406{ 407int i =0, j =0; 408 409if(!name) 410return NULL; 411 412while(name[i]) { 413if((name[j++] = name[i++]) =='/') 414while(name[i] =='/') 415 i++; 416} 417 name[j] ='\0'; 418return name; 419} 420 421static char*find_name_gnu(const char*line,char*def,int p_value) 422{ 423struct strbuf name = STRBUF_INIT; 424char*cp; 425 426/* 427 * Proposed "new-style" GNU patch/diff format; see 428 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2 429 */ 430if(unquote_c_style(&name, line, NULL)) { 431strbuf_release(&name); 432return NULL; 433} 434 435for(cp = name.buf; p_value; p_value--) { 436 cp =strchr(cp,'/'); 437if(!cp) { 438strbuf_release(&name); 439return NULL; 440} 441 cp++; 442} 443 444/* name can later be freed, so we need 445 * to memmove, not just return cp 446 */ 447strbuf_remove(&name,0, cp - name.buf); 448free(def); 449if(root) 450strbuf_insert(&name,0, root, root_len); 451returnsquash_slash(strbuf_detach(&name, NULL)); 452} 453 454static size_tsane_tz_len(const char*line,size_t len) 455{ 456const char*tz, *p; 457 458if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 459return0; 460 tz = line + len -strlen(" +0500"); 461 462if(tz[1] !='+'&& tz[1] !='-') 463return0; 464 465for(p = tz +2; p != line + len; p++) 466if(!isdigit(*p)) 467return0; 468 469return line + len - tz; 470} 471 472static size_ttz_with_colon_len(const char*line,size_t len) 473{ 474const char*tz, *p; 475 476if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 477return0; 478 tz = line + len -strlen(" +08:00"); 479 480if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 481return0; 482 p = tz +2; 483if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 484!isdigit(*p++) || !isdigit(*p++)) 485return0; 486 487return line + len - tz; 488} 489 490static size_tdate_len(const char*line,size_t len) 491{ 492const char*date, *p; 493 494if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 495return0; 496 p = date = line + len -strlen("72-02-05"); 497 498if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 499!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 500!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 501return0; 502 503if(date - line >=strlen("19") && 504isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 505 date -=strlen("19"); 506 507return line + len - date; 508} 509 510static size_tshort_time_len(const char*line,size_t len) 511{ 512const char*time, *p; 513 514if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 515return0; 516 p = time = line + len -strlen(" 07:01:32"); 517 518/* Permit 1-digit hours? */ 519if(*p++ !=' '|| 520!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 521!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 522!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 523return0; 524 525return line + len - time; 526} 527 528static size_tfractional_time_len(const char*line,size_t len) 529{ 530const char*p; 531size_t n; 532 533/* Expected format: 19:41:17.620000023 */ 534if(!len || !isdigit(line[len -1])) 535return0; 536 p = line + len -1; 537 538/* Fractional seconds. */ 539while(p > line &&isdigit(*p)) 540 p--; 541if(*p !='.') 542return0; 543 544/* Hours, minutes, and whole seconds. */ 545 n =short_time_len(line, p - line); 546if(!n) 547return0; 548 549return line + len - p + n; 550} 551 552static size_ttrailing_spaces_len(const char*line,size_t len) 553{ 554const char*p; 555 556/* Expected format: ' ' x (1 or more) */ 557if(!len || line[len -1] !=' ') 558return0; 559 560 p = line + len; 561while(p != line) { 562 p--; 563if(*p !=' ') 564return line + len - (p +1); 565} 566 567/* All spaces! */ 568return len; 569} 570 571static size_tdiff_timestamp_len(const char*line,size_t len) 572{ 573const char*end = line + len; 574size_t n; 575 576/* 577 * Posix: 2010-07-05 19:41:17 578 * GNU: 2010-07-05 19:41:17.620000023 -0500 579 */ 580 581if(!isdigit(end[-1])) 582return0; 583 584 n =sane_tz_len(line, end - line); 585if(!n) 586 n =tz_with_colon_len(line, end - line); 587 end -= n; 588 589 n =short_time_len(line, end - line); 590if(!n) 591 n =fractional_time_len(line, end - line); 592 end -= n; 593 594 n =date_len(line, end - line); 595if(!n)/* No date. Too bad. */ 596return0; 597 end -= n; 598 599if(end == line)/* No space before date. */ 600return0; 601if(end[-1] =='\t') {/* Success! */ 602 end--; 603return line + len - end; 604} 605if(end[-1] !=' ')/* No space before date. */ 606return0; 607 608/* Whitespace damage. */ 609 end -=trailing_spaces_len(line, end - line); 610return line + len - end; 611} 612 613static char*find_name_common(const char*line,char*def,int p_value, 614const char*end,int terminate) 615{ 616int len; 617const char*start = NULL; 618 619if(p_value ==0) 620 start = line; 621while(line != end) { 622char c = *line; 623 624if(!end &&isspace(c)) { 625if(c =='\n') 626break; 627if(name_terminate(start, line-start, c, terminate)) 628break; 629} 630 line++; 631if(c =='/'&& !--p_value) 632 start = line; 633} 634if(!start) 635returnsquash_slash(def); 636 len = line - start; 637if(!len) 638returnsquash_slash(def); 639 640/* 641 * Generally we prefer the shorter name, especially 642 * if the other one is just a variation of that with 643 * something else tacked on to the end (ie "file.orig" 644 * or "file~"). 645 */ 646if(def) { 647int deflen =strlen(def); 648if(deflen < len && !strncmp(start, def, deflen)) 649returnsquash_slash(def); 650free(def); 651} 652 653if(root) { 654char*ret =xmalloc(root_len + len +1); 655strcpy(ret, root); 656memcpy(ret + root_len, start, len); 657 ret[root_len + len] ='\0'; 658returnsquash_slash(ret); 659} 660 661returnsquash_slash(xmemdupz(start, len)); 662} 663 664static char*find_name(const char*line,char*def,int p_value,int terminate) 665{ 666if(*line =='"') { 667char*name =find_name_gnu(line, def, p_value); 668if(name) 669return name; 670} 671 672returnfind_name_common(line, def, p_value, NULL, terminate); 673} 674 675static char*find_name_traditional(const char*line,char*def,int p_value) 676{ 677size_t len =strlen(line); 678size_t date_len; 679 680if(*line =='"') { 681char*name =find_name_gnu(line, def, p_value); 682if(name) 683return name; 684} 685 686 len =strchrnul(line,'\n') - line; 687 date_len =diff_timestamp_len(line, len); 688if(!date_len) 689returnfind_name_common(line, def, p_value, NULL, TERM_TAB); 690 len -= date_len; 691 692returnfind_name_common(line, def, p_value, line + len,0); 693} 694 695static intcount_slashes(const char*cp) 696{ 697int cnt =0; 698char ch; 699 700while((ch = *cp++)) 701if(ch =='/') 702 cnt++; 703return cnt; 704} 705 706/* 707 * Given the string after "--- " or "+++ ", guess the appropriate 708 * p_value for the given patch. 709 */ 710static intguess_p_value(const char*nameline) 711{ 712char*name, *cp; 713int val = -1; 714 715if(is_dev_null(nameline)) 716return-1; 717 name =find_name_traditional(nameline, NULL,0); 718if(!name) 719return-1; 720 cp =strchr(name,'/'); 721if(!cp) 722 val =0; 723else if(prefix) { 724/* 725 * Does it begin with "a/$our-prefix" and such? Then this is 726 * very likely to apply to our directory. 727 */ 728if(!strncmp(name, prefix, prefix_length)) 729 val =count_slashes(prefix); 730else{ 731 cp++; 732if(!strncmp(cp, prefix, prefix_length)) 733 val =count_slashes(prefix) +1; 734} 735} 736free(name); 737return val; 738} 739 740/* 741 * Does the ---/+++ line has the POSIX timestamp after the last HT? 742 * GNU diff puts epoch there to signal a creation/deletion event. Is 743 * this such a timestamp? 744 */ 745static inthas_epoch_timestamp(const char*nameline) 746{ 747/* 748 * We are only interested in epoch timestamp; any non-zero 749 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 750 * For the same reason, the date must be either 1969-12-31 or 751 * 1970-01-01, and the seconds part must be "00". 752 */ 753const char stamp_regexp[] = 754"^(1969-12-31|1970-01-01)" 755" " 756"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 757" " 758"([-+][0-2][0-9]:?[0-5][0-9])\n"; 759const char*timestamp = NULL, *cp, *colon; 760static regex_t *stamp; 761 regmatch_t m[10]; 762int zoneoffset; 763int hourminute; 764int status; 765 766for(cp = nameline; *cp !='\n'; cp++) { 767if(*cp =='\t') 768 timestamp = cp +1; 769} 770if(!timestamp) 771return0; 772if(!stamp) { 773 stamp =xmalloc(sizeof(*stamp)); 774if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 775warning("Cannot prepare timestamp regexp%s", 776 stamp_regexp); 777return0; 778} 779} 780 781 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 782if(status) { 783if(status != REG_NOMATCH) 784warning("regexec returned%dfor input:%s", 785 status, timestamp); 786return0; 787} 788 789 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 790if(*colon ==':') 791 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 792else 793 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 794if(timestamp[m[3].rm_so] =='-') 795 zoneoffset = -zoneoffset; 796 797/* 798 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 799 * (west of GMT) or 1970-01-01 (east of GMT) 800 */ 801if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 802(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 803return0; 804 805 hourminute = (strtol(timestamp +11, NULL,10) *60+ 806strtol(timestamp +14, NULL,10) - 807 zoneoffset); 808 809return((zoneoffset <0&& hourminute ==1440) || 810(0<= zoneoffset && !hourminute)); 811} 812 813/* 814 * Get the name etc info from the ---/+++ lines of a traditional patch header 815 * 816 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 817 * files, we can happily check the index for a match, but for creating a 818 * new file we should try to match whatever "patch" does. I have no idea. 819 */ 820static voidparse_traditional_patch(const char*first,const char*second,struct patch *patch) 821{ 822char*name; 823 824 first +=4;/* skip "--- " */ 825 second +=4;/* skip "+++ " */ 826if(!p_value_known) { 827int p, q; 828 p =guess_p_value(first); 829 q =guess_p_value(second); 830if(p <0) p = q; 831if(0<= p && p == q) { 832 p_value = p; 833 p_value_known =1; 834} 835} 836if(is_dev_null(first)) { 837 patch->is_new =1; 838 patch->is_delete =0; 839 name =find_name_traditional(second, NULL, p_value); 840 patch->new_name = name; 841}else if(is_dev_null(second)) { 842 patch->is_new =0; 843 patch->is_delete =1; 844 name =find_name_traditional(first, NULL, p_value); 845 patch->old_name = name; 846}else{ 847 name =find_name_traditional(first, NULL, p_value); 848 name =find_name_traditional(second, name, p_value); 849if(has_epoch_timestamp(first)) { 850 patch->is_new =1; 851 patch->is_delete =0; 852 patch->new_name = name; 853}else if(has_epoch_timestamp(second)) { 854 patch->is_new =0; 855 patch->is_delete =1; 856 patch->old_name = name; 857}else{ 858 patch->old_name = patch->new_name = name; 859} 860} 861if(!name) 862die("unable to find filename in patch at line%d", linenr); 863} 864 865static intgitdiff_hdrend(const char*line,struct patch *patch) 866{ 867return-1; 868} 869 870/* 871 * We're anal about diff header consistency, to make 872 * sure that we don't end up having strange ambiguous 873 * patches floating around. 874 * 875 * As a result, gitdiff_{old|new}name() will check 876 * their names against any previous information, just 877 * to make sure.. 878 */ 879static char*gitdiff_verify_name(const char*line,int isnull,char*orig_name,const char*oldnew) 880{ 881if(!orig_name && !isnull) 882returnfind_name(line, NULL, p_value, TERM_TAB); 883 884if(orig_name) { 885int len; 886const char*name; 887char*another; 888 name = orig_name; 889 len =strlen(name); 890if(isnull) 891die("git apply: bad git-diff - expected /dev/null, got%son line%d", name, linenr); 892 another =find_name(line, NULL, p_value, TERM_TAB); 893if(!another ||memcmp(another, name, len +1)) 894die("git apply: bad git-diff - inconsistent%sfilename on line%d", oldnew, linenr); 895free(another); 896return orig_name; 897} 898else{ 899/* expect "/dev/null" */ 900if(memcmp("/dev/null", line,9) || line[9] !='\n') 901die("git apply: bad git-diff - expected /dev/null on line%d", linenr); 902return NULL; 903} 904} 905 906static intgitdiff_oldname(const char*line,struct patch *patch) 907{ 908 patch->old_name =gitdiff_verify_name(line, patch->is_new, patch->old_name,"old"); 909return0; 910} 911 912static intgitdiff_newname(const char*line,struct patch *patch) 913{ 914 patch->new_name =gitdiff_verify_name(line, patch->is_delete, patch->new_name,"new"); 915return0; 916} 917 918static intgitdiff_oldmode(const char*line,struct patch *patch) 919{ 920 patch->old_mode =strtoul(line, NULL,8); 921return0; 922} 923 924static intgitdiff_newmode(const char*line,struct patch *patch) 925{ 926 patch->new_mode =strtoul(line, NULL,8); 927return0; 928} 929 930static intgitdiff_delete(const char*line,struct patch *patch) 931{ 932 patch->is_delete =1; 933 patch->old_name = patch->def_name; 934returngitdiff_oldmode(line, patch); 935} 936 937static intgitdiff_newfile(const char*line,struct patch *patch) 938{ 939 patch->is_new =1; 940 patch->new_name = patch->def_name; 941returngitdiff_newmode(line, patch); 942} 943 944static intgitdiff_copysrc(const char*line,struct patch *patch) 945{ 946 patch->is_copy =1; 947 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0); 948return0; 949} 950 951static intgitdiff_copydst(const char*line,struct patch *patch) 952{ 953 patch->is_copy =1; 954 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0); 955return0; 956} 957 958static intgitdiff_renamesrc(const char*line,struct patch *patch) 959{ 960 patch->is_rename =1; 961 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0); 962return0; 963} 964 965static intgitdiff_renamedst(const char*line,struct patch *patch) 966{ 967 patch->is_rename =1; 968 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0); 969return0; 970} 971 972static intgitdiff_similarity(const char*line,struct patch *patch) 973{ 974if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 975 patch->score =0; 976return0; 977} 978 979static intgitdiff_dissimilarity(const char*line,struct patch *patch) 980{ 981if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 982 patch->score =0; 983return0; 984} 985 986static intgitdiff_index(const char*line,struct patch *patch) 987{ 988/* 989 * index line is N hexadecimal, "..", N hexadecimal, 990 * and optional space with octal mode. 991 */ 992const char*ptr, *eol; 993int len; 994 995 ptr =strchr(line,'.'); 996if(!ptr || ptr[1] !='.'||40< ptr - line) 997return0; 998 len = ptr - line; 999memcpy(patch->old_sha1_prefix, line, len);1000 patch->old_sha1_prefix[len] =0;10011002 line = ptr +2;1003 ptr =strchr(line,' ');1004 eol =strchr(line,'\n');10051006if(!ptr || eol < ptr)1007 ptr = eol;1008 len = ptr - line;10091010if(40< len)1011return0;1012memcpy(patch->new_sha1_prefix, line, len);1013 patch->new_sha1_prefix[len] =0;1014if(*ptr ==' ')1015 patch->old_mode =strtoul(ptr+1, NULL,8);1016return0;1017}10181019/*1020 * This is normal for a diff that doesn't change anything: we'll fall through1021 * into the next diff. Tell the parser to break out.1022 */1023static intgitdiff_unrecognized(const char*line,struct patch *patch)1024{1025return-1;1026}10271028static const char*stop_at_slash(const char*line,int llen)1029{1030int nslash = p_value;1031int i;10321033for(i =0; i < llen; i++) {1034int ch = line[i];1035if(ch =='/'&& --nslash <=0)1036return&line[i];1037}1038return NULL;1039}10401041/*1042 * This is to extract the same name that appears on "diff --git"1043 * line. We do not find and return anything if it is a rename1044 * patch, and it is OK because we will find the name elsewhere.1045 * We need to reliably find name only when it is mode-change only,1046 * creation or deletion of an empty file. In any of these cases,1047 * both sides are the same name under a/ and b/ respectively.1048 */1049static char*git_header_name(char*line,int llen)1050{1051const char*name;1052const char*second = NULL;1053size_t len, line_len;10541055 line +=strlen("diff --git ");1056 llen -=strlen("diff --git ");10571058if(*line =='"') {1059const char*cp;1060struct strbuf first = STRBUF_INIT;1061struct strbuf sp = STRBUF_INIT;10621063if(unquote_c_style(&first, line, &second))1064goto free_and_fail1;10651066/* advance to the first slash */1067 cp =stop_at_slash(first.buf, first.len);1068/* we do not accept absolute paths */1069if(!cp || cp == first.buf)1070goto free_and_fail1;1071strbuf_remove(&first,0, cp +1- first.buf);10721073/*1074 * second points at one past closing dq of name.1075 * find the second name.1076 */1077while((second < line + llen) &&isspace(*second))1078 second++;10791080if(line + llen <= second)1081goto free_and_fail1;1082if(*second =='"') {1083if(unquote_c_style(&sp, second, NULL))1084goto free_and_fail1;1085 cp =stop_at_slash(sp.buf, sp.len);1086if(!cp || cp == sp.buf)1087goto free_and_fail1;1088/* They must match, otherwise ignore */1089if(strcmp(cp +1, first.buf))1090goto free_and_fail1;1091strbuf_release(&sp);1092returnstrbuf_detach(&first, NULL);1093}10941095/* unquoted second */1096 cp =stop_at_slash(second, line + llen - second);1097if(!cp || cp == second)1098goto free_and_fail1;1099 cp++;1100if(line + llen - cp != first.len +1||1101memcmp(first.buf, cp, first.len))1102goto free_and_fail1;1103returnstrbuf_detach(&first, NULL);11041105 free_and_fail1:1106strbuf_release(&first);1107strbuf_release(&sp);1108return NULL;1109}11101111/* unquoted first name */1112 name =stop_at_slash(line, llen);1113if(!name || name == line)1114return NULL;1115 name++;11161117/*1118 * since the first name is unquoted, a dq if exists must be1119 * the beginning of the second name.1120 */1121for(second = name; second < line + llen; second++) {1122if(*second =='"') {1123struct strbuf sp = STRBUF_INIT;1124const char*np;11251126if(unquote_c_style(&sp, second, NULL))1127goto free_and_fail2;11281129 np =stop_at_slash(sp.buf, sp.len);1130if(!np || np == sp.buf)1131goto free_and_fail2;1132 np++;11331134 len = sp.buf + sp.len - np;1135if(len < second - name &&1136!strncmp(np, name, len) &&1137isspace(name[len])) {1138/* Good */1139strbuf_remove(&sp,0, np - sp.buf);1140returnstrbuf_detach(&sp, NULL);1141}11421143 free_and_fail2:1144strbuf_release(&sp);1145return NULL;1146}1147}11481149/*1150 * Accept a name only if it shows up twice, exactly the same1151 * form.1152 */1153 second =strchr(name,'\n');1154if(!second)1155return NULL;1156 line_len = second - name;1157for(len =0; ; len++) {1158switch(name[len]) {1159default:1160continue;1161case'\n':1162return NULL;1163case'\t':case' ':1164 second =stop_at_slash(name + len, line_len - len);1165if(!second)1166return NULL;1167 second++;1168if(second[len] =='\n'&& !strncmp(name, second, len)) {1169returnxmemdupz(name, len);1170}1171}1172}1173}11741175/* Verify that we recognize the lines following a git header */1176static intparse_git_header(char*line,int len,unsigned int size,struct patch *patch)1177{1178unsigned long offset;11791180/* A git diff has explicit new/delete information, so we don't guess */1181 patch->is_new =0;1182 patch->is_delete =0;11831184/*1185 * Some things may not have the old name in the1186 * rest of the headers anywhere (pure mode changes,1187 * or removing or adding empty files), so we get1188 * the default name from the header.1189 */1190 patch->def_name =git_header_name(line, len);1191if(patch->def_name && root) {1192char*s =xmalloc(root_len +strlen(patch->def_name) +1);1193strcpy(s, root);1194strcpy(s + root_len, patch->def_name);1195free(patch->def_name);1196 patch->def_name = s;1197}11981199 line += len;1200 size -= len;1201 linenr++;1202for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) {1203static const struct opentry {1204const char*str;1205int(*fn)(const char*,struct patch *);1206} optable[] = {1207{"@@ -", gitdiff_hdrend },1208{"--- ", gitdiff_oldname },1209{"+++ ", gitdiff_newname },1210{"old mode ", gitdiff_oldmode },1211{"new mode ", gitdiff_newmode },1212{"deleted file mode ", gitdiff_delete },1213{"new file mode ", gitdiff_newfile },1214{"copy from ", gitdiff_copysrc },1215{"copy to ", gitdiff_copydst },1216{"rename old ", gitdiff_renamesrc },1217{"rename new ", gitdiff_renamedst },1218{"rename from ", gitdiff_renamesrc },1219{"rename to ", gitdiff_renamedst },1220{"similarity index ", gitdiff_similarity },1221{"dissimilarity index ", gitdiff_dissimilarity },1222{"index ", gitdiff_index },1223{"", gitdiff_unrecognized },1224};1225int i;12261227 len =linelen(line, size);1228if(!len || line[len-1] !='\n')1229break;1230for(i =0; i <ARRAY_SIZE(optable); i++) {1231const struct opentry *p = optable + i;1232int oplen =strlen(p->str);1233if(len < oplen ||memcmp(p->str, line, oplen))1234continue;1235if(p->fn(line + oplen, patch) <0)1236return offset;1237break;1238}1239}12401241return offset;1242}12431244static intparse_num(const char*line,unsigned long*p)1245{1246char*ptr;12471248if(!isdigit(*line))1249return0;1250*p =strtoul(line, &ptr,10);1251return ptr - line;1252}12531254static intparse_range(const char*line,int len,int offset,const char*expect,1255unsigned long*p1,unsigned long*p2)1256{1257int digits, ex;12581259if(offset <0|| offset >= len)1260return-1;1261 line += offset;1262 len -= offset;12631264 digits =parse_num(line, p1);1265if(!digits)1266return-1;12671268 offset += digits;1269 line += digits;1270 len -= digits;12711272*p2 =1;1273if(*line ==',') {1274 digits =parse_num(line+1, p2);1275if(!digits)1276return-1;12771278 offset += digits+1;1279 line += digits+1;1280 len -= digits+1;1281}12821283 ex =strlen(expect);1284if(ex > len)1285return-1;1286if(memcmp(line, expect, ex))1287return-1;12881289return offset + ex;1290}12911292static voidrecount_diff(char*line,int size,struct fragment *fragment)1293{1294int oldlines =0, newlines =0, ret =0;12951296if(size <1) {1297warning("recount: ignore empty hunk");1298return;1299}13001301for(;;) {1302int len =linelen(line, size);1303 size -= len;1304 line += len;13051306if(size <1)1307break;13081309switch(*line) {1310case' ':case'\n':1311 newlines++;1312/* fall through */1313case'-':1314 oldlines++;1315continue;1316case'+':1317 newlines++;1318continue;1319case'\\':1320continue;1321case'@':1322 ret = size <3||prefixcmp(line,"@@ ");1323break;1324case'd':1325 ret = size <5||prefixcmp(line,"diff ");1326break;1327default:1328 ret = -1;1329break;1330}1331if(ret) {1332warning("recount: unexpected line: %.*s",1333(int)linelen(line, size), line);1334return;1335}1336break;1337}1338 fragment->oldlines = oldlines;1339 fragment->newlines = newlines;1340}13411342/*1343 * Parse a unified diff fragment header of the1344 * form "@@ -a,b +c,d @@"1345 */1346static intparse_fragment_header(char*line,int len,struct fragment *fragment)1347{1348int offset;13491350if(!len || line[len-1] !='\n')1351return-1;13521353/* Figure out the number of lines in a fragment */1354 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1355 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);13561357return offset;1358}13591360static intfind_header(char*line,unsigned long size,int*hdrsize,struct patch *patch)1361{1362unsigned long offset, len;13631364 patch->is_toplevel_relative =0;1365 patch->is_rename = patch->is_copy =0;1366 patch->is_new = patch->is_delete = -1;1367 patch->old_mode = patch->new_mode =0;1368 patch->old_name = patch->new_name = NULL;1369for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) {1370unsigned long nextlen;13711372 len =linelen(line, size);1373if(!len)1374break;13751376/* Testing this early allows us to take a few shortcuts.. */1377if(len <6)1378continue;13791380/*1381 * Make sure we don't find any unconnected patch fragments.1382 * That's a sign that we didn't find a header, and that a1383 * patch has become corrupted/broken up.1384 */1385if(!memcmp("@@ -", line,4)) {1386struct fragment dummy;1387if(parse_fragment_header(line, len, &dummy) <0)1388continue;1389die("patch fragment without header at line%d: %.*s",1390 linenr, (int)len-1, line);1391}13921393if(size < len +6)1394break;13951396/*1397 * Git patch? It might not have a real patch, just a rename1398 * or mode change, so we handle that specially1399 */1400if(!memcmp("diff --git ", line,11)) {1401int git_hdr_len =parse_git_header(line, len, size, patch);1402if(git_hdr_len <= len)1403continue;1404if(!patch->old_name && !patch->new_name) {1405if(!patch->def_name)1406die("git diff header lacks filename information when removing "1407"%dleading pathname components (line%d)", p_value, linenr);1408 patch->old_name = patch->new_name = patch->def_name;1409}1410if(!patch->is_delete && !patch->new_name)1411die("git diff header lacks filename information "1412"(line%d)", linenr);1413 patch->is_toplevel_relative =1;1414*hdrsize = git_hdr_len;1415return offset;1416}14171418/* --- followed by +++ ? */1419if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1420continue;14211422/*1423 * We only accept unified patches, so we want it to1424 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1425 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1426 */1427 nextlen =linelen(line + len, size - len);1428if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1429continue;14301431/* Ok, we'll consider it a patch */1432parse_traditional_patch(line, line+len, patch);1433*hdrsize = len + nextlen;1434 linenr +=2;1435return offset;1436}1437return-1;1438}14391440static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1441{1442char*err;14431444if(!result)1445return;14461447 whitespace_error++;1448if(squelch_whitespace_errors &&1449 squelch_whitespace_errors < whitespace_error)1450return;14511452 err =whitespace_error_string(result);1453fprintf(stderr,"%s:%d:%s.\n%.*s\n",1454 patch_input_file, linenr, err, len, line);1455free(err);1456}14571458static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1459{1460unsigned result =ws_check(line +1, len -1, ws_rule);14611462record_ws_error(result, line +1, len -2, linenr);1463}14641465/*1466 * Parse a unified diff. Note that this really needs to parse each1467 * fragment separately, since the only way to know the difference1468 * between a "---" that is part of a patch, and a "---" that starts1469 * the next patch is to look at the line counts..1470 */1471static intparse_fragment(char*line,unsigned long size,1472struct patch *patch,struct fragment *fragment)1473{1474int added, deleted;1475int len =linelen(line, size), offset;1476unsigned long oldlines, newlines;1477unsigned long leading, trailing;14781479 offset =parse_fragment_header(line, len, fragment);1480if(offset <0)1481return-1;1482if(offset >0&& patch->recount)1483recount_diff(line + offset, size - offset, fragment);1484 oldlines = fragment->oldlines;1485 newlines = fragment->newlines;1486 leading =0;1487 trailing =0;14881489/* Parse the thing.. */1490 line += len;1491 size -= len;1492 linenr++;1493 added = deleted =0;1494for(offset = len;14950< size;1496 offset += len, size -= len, line += len, linenr++) {1497if(!oldlines && !newlines)1498break;1499 len =linelen(line, size);1500if(!len || line[len-1] !='\n')1501return-1;1502switch(*line) {1503default:1504return-1;1505case'\n':/* newer GNU diff, an empty context line */1506case' ':1507 oldlines--;1508 newlines--;1509if(!deleted && !added)1510 leading++;1511 trailing++;1512break;1513case'-':1514if(apply_in_reverse &&1515 ws_error_action != nowarn_ws_error)1516check_whitespace(line, len, patch->ws_rule);1517 deleted++;1518 oldlines--;1519 trailing =0;1520break;1521case'+':1522if(!apply_in_reverse &&1523 ws_error_action != nowarn_ws_error)1524check_whitespace(line, len, patch->ws_rule);1525 added++;1526 newlines--;1527 trailing =0;1528break;15291530/*1531 * We allow "\ No newline at end of file". Depending1532 * on locale settings when the patch was produced we1533 * don't know what this line looks like. The only1534 * thing we do know is that it begins with "\ ".1535 * Checking for 12 is just for sanity check -- any1536 * l10n of "\ No newline..." is at least that long.1537 */1538case'\\':1539if(len <12||memcmp(line,"\\",2))1540return-1;1541break;1542}1543}1544if(oldlines || newlines)1545return-1;1546 fragment->leading = leading;1547 fragment->trailing = trailing;15481549/*1550 * If a fragment ends with an incomplete line, we failed to include1551 * it in the above loop because we hit oldlines == newlines == 01552 * before seeing it.1553 */1554if(12< size && !memcmp(line,"\\",2))1555 offset +=linelen(line, size);15561557 patch->lines_added += added;1558 patch->lines_deleted += deleted;15591560if(0< patch->is_new && oldlines)1561returnerror("new file depends on old contents");1562if(0< patch->is_delete && newlines)1563returnerror("deleted file still has contents");1564return offset;1565}15661567static intparse_single_patch(char*line,unsigned long size,struct patch *patch)1568{1569unsigned long offset =0;1570unsigned long oldlines =0, newlines =0, context =0;1571struct fragment **fragp = &patch->fragments;15721573while(size >4&& !memcmp(line,"@@ -",4)) {1574struct fragment *fragment;1575int len;15761577 fragment =xcalloc(1,sizeof(*fragment));1578 fragment->linenr = linenr;1579 len =parse_fragment(line, size, patch, fragment);1580if(len <=0)1581die("corrupt patch at line%d", linenr);1582 fragment->patch = line;1583 fragment->size = len;1584 oldlines += fragment->oldlines;1585 newlines += fragment->newlines;1586 context += fragment->leading + fragment->trailing;15871588*fragp = fragment;1589 fragp = &fragment->next;15901591 offset += len;1592 line += len;1593 size -= len;1594}15951596/*1597 * If something was removed (i.e. we have old-lines) it cannot1598 * be creation, and if something was added it cannot be1599 * deletion. However, the reverse is not true; --unified=01600 * patches that only add are not necessarily creation even1601 * though they do not have any old lines, and ones that only1602 * delete are not necessarily deletion.1603 *1604 * Unfortunately, a real creation/deletion patch do _not_ have1605 * any context line by definition, so we cannot safely tell it1606 * apart with --unified=0 insanity. At least if the patch has1607 * more than one hunk it is not creation or deletion.1608 */1609if(patch->is_new <0&&1610(oldlines || (patch->fragments && patch->fragments->next)))1611 patch->is_new =0;1612if(patch->is_delete <0&&1613(newlines || (patch->fragments && patch->fragments->next)))1614 patch->is_delete =0;16151616if(0< patch->is_new && oldlines)1617die("new file%sdepends on old contents", patch->new_name);1618if(0< patch->is_delete && newlines)1619die("deleted file%sstill has contents", patch->old_name);1620if(!patch->is_delete && !newlines && context)1621fprintf(stderr,"** warning: file%sbecomes empty but "1622"is not deleted\n", patch->new_name);16231624return offset;1625}16261627staticinlineintmetadata_changes(struct patch *patch)1628{1629return patch->is_rename >0||1630 patch->is_copy >0||1631 patch->is_new >0||1632 patch->is_delete ||1633(patch->old_mode && patch->new_mode &&1634 patch->old_mode != patch->new_mode);1635}16361637static char*inflate_it(const void*data,unsigned long size,1638unsigned long inflated_size)1639{1640 git_zstream stream;1641void*out;1642int st;16431644memset(&stream,0,sizeof(stream));16451646 stream.next_in = (unsigned char*)data;1647 stream.avail_in = size;1648 stream.next_out = out =xmalloc(inflated_size);1649 stream.avail_out = inflated_size;1650git_inflate_init(&stream);1651 st =git_inflate(&stream, Z_FINISH);1652git_inflate_end(&stream);1653if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1654free(out);1655return NULL;1656}1657return out;1658}16591660static struct fragment *parse_binary_hunk(char**buf_p,1661unsigned long*sz_p,1662int*status_p,1663int*used_p)1664{1665/*1666 * Expect a line that begins with binary patch method ("literal"1667 * or "delta"), followed by the length of data before deflating.1668 * a sequence of 'length-byte' followed by base-85 encoded data1669 * should follow, terminated by a newline.1670 *1671 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1672 * and we would limit the patch line to 66 characters,1673 * so one line can fit up to 13 groups that would decode1674 * to 52 bytes max. The length byte 'A'-'Z' corresponds1675 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1676 */1677int llen, used;1678unsigned long size = *sz_p;1679char*buffer = *buf_p;1680int patch_method;1681unsigned long origlen;1682char*data = NULL;1683int hunk_size =0;1684struct fragment *frag;16851686 llen =linelen(buffer, size);1687 used = llen;16881689*status_p =0;16901691if(!prefixcmp(buffer,"delta ")) {1692 patch_method = BINARY_DELTA_DEFLATED;1693 origlen =strtoul(buffer +6, NULL,10);1694}1695else if(!prefixcmp(buffer,"literal ")) {1696 patch_method = BINARY_LITERAL_DEFLATED;1697 origlen =strtoul(buffer +8, NULL,10);1698}1699else1700return NULL;17011702 linenr++;1703 buffer += llen;1704while(1) {1705int byte_length, max_byte_length, newsize;1706 llen =linelen(buffer, size);1707 used += llen;1708 linenr++;1709if(llen ==1) {1710/* consume the blank line */1711 buffer++;1712 size--;1713break;1714}1715/*1716 * Minimum line is "A00000\n" which is 7-byte long,1717 * and the line length must be multiple of 5 plus 2.1718 */1719if((llen <7) || (llen-2) %5)1720goto corrupt;1721 max_byte_length = (llen -2) /5*4;1722 byte_length = *buffer;1723if('A'<= byte_length && byte_length <='Z')1724 byte_length = byte_length -'A'+1;1725else if('a'<= byte_length && byte_length <='z')1726 byte_length = byte_length -'a'+27;1727else1728goto corrupt;1729/* if the input length was not multiple of 4, we would1730 * have filler at the end but the filler should never1731 * exceed 3 bytes1732 */1733if(max_byte_length < byte_length ||1734 byte_length <= max_byte_length -4)1735goto corrupt;1736 newsize = hunk_size + byte_length;1737 data =xrealloc(data, newsize);1738if(decode_85(data + hunk_size, buffer +1, byte_length))1739goto corrupt;1740 hunk_size = newsize;1741 buffer += llen;1742 size -= llen;1743}17441745 frag =xcalloc(1,sizeof(*frag));1746 frag->patch =inflate_it(data, hunk_size, origlen);1747if(!frag->patch)1748goto corrupt;1749free(data);1750 frag->size = origlen;1751*buf_p = buffer;1752*sz_p = size;1753*used_p = used;1754 frag->binary_patch_method = patch_method;1755return frag;17561757 corrupt:1758free(data);1759*status_p = -1;1760error("corrupt binary patch at line%d: %.*s",1761 linenr-1, llen-1, buffer);1762return NULL;1763}17641765static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1766{1767/*1768 * We have read "GIT binary patch\n"; what follows is a line1769 * that says the patch method (currently, either "literal" or1770 * "delta") and the length of data before deflating; a1771 * sequence of 'length-byte' followed by base-85 encoded data1772 * follows.1773 *1774 * When a binary patch is reversible, there is another binary1775 * hunk in the same format, starting with patch method (either1776 * "literal" or "delta") with the length of data, and a sequence1777 * of length-byte + base-85 encoded data, terminated with another1778 * empty line. This data, when applied to the postimage, produces1779 * the preimage.1780 */1781struct fragment *forward;1782struct fragment *reverse;1783int status;1784int used, used_1;17851786 forward =parse_binary_hunk(&buffer, &size, &status, &used);1787if(!forward && !status)1788/* there has to be one hunk (forward hunk) */1789returnerror("unrecognized binary patch at line%d", linenr-1);1790if(status)1791/* otherwise we already gave an error message */1792return status;17931794 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1795if(reverse)1796 used += used_1;1797else if(status) {1798/*1799 * Not having reverse hunk is not an error, but having1800 * a corrupt reverse hunk is.1801 */1802free((void*) forward->patch);1803free(forward);1804return status;1805}1806 forward->next = reverse;1807 patch->fragments = forward;1808 patch->is_binary =1;1809return used;1810}18111812static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1813{1814int hdrsize, patchsize;1815int offset =find_header(buffer, size, &hdrsize, patch);18161817if(offset <0)1818return offset;18191820 patch->ws_rule =whitespace_rule(patch->new_name1821? patch->new_name1822: patch->old_name);18231824 patchsize =parse_single_patch(buffer + offset + hdrsize,1825 size - offset - hdrsize, patch);18261827if(!patchsize) {1828static const char*binhdr[] = {1829"Binary files ",1830"Files ",1831 NULL,1832};1833static const char git_binary[] ="GIT binary patch\n";1834int i;1835int hd = hdrsize + offset;1836unsigned long llen =linelen(buffer + hd, size - hd);18371838if(llen ==sizeof(git_binary) -1&&1839!memcmp(git_binary, buffer + hd, llen)) {1840int used;1841 linenr++;1842 used =parse_binary(buffer + hd + llen,1843 size - hd - llen, patch);1844if(used)1845 patchsize = used + llen;1846else1847 patchsize =0;1848}1849else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1850for(i =0; binhdr[i]; i++) {1851int len =strlen(binhdr[i]);1852if(len < size - hd &&1853!memcmp(binhdr[i], buffer + hd, len)) {1854 linenr++;1855 patch->is_binary =1;1856 patchsize = llen;1857break;1858}1859}1860}18611862/* Empty patch cannot be applied if it is a text patch1863 * without metadata change. A binary patch appears1864 * empty to us here.1865 */1866if((apply || check) &&1867(!patch->is_binary && !metadata_changes(patch)))1868die("patch with only garbage at line%d", linenr);1869}18701871return offset + hdrsize + patchsize;1872}18731874#define swap(a,b) myswap((a),(b),sizeof(a))18751876#define myswap(a, b, size) do { \1877 unsigned char mytmp[size]; \1878 memcpy(mytmp, &a, size); \1879 memcpy(&a, &b, size); \1880 memcpy(&b, mytmp, size); \1881} while (0)18821883static voidreverse_patches(struct patch *p)1884{1885for(; p; p = p->next) {1886struct fragment *frag = p->fragments;18871888swap(p->new_name, p->old_name);1889swap(p->new_mode, p->old_mode);1890swap(p->is_new, p->is_delete);1891swap(p->lines_added, p->lines_deleted);1892swap(p->old_sha1_prefix, p->new_sha1_prefix);18931894for(; frag; frag = frag->next) {1895swap(frag->newpos, frag->oldpos);1896swap(frag->newlines, frag->oldlines);1897}1898}1899}19001901static const char pluses[] =1902"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";1903static const char minuses[]=1904"----------------------------------------------------------------------";19051906static voidshow_stats(struct patch *patch)1907{1908struct strbuf qname = STRBUF_INIT;1909char*cp = patch->new_name ? patch->new_name : patch->old_name;1910int max, add, del;19111912quote_c_style(cp, &qname, NULL,0);19131914/*1915 * "scale" the filename1916 */1917 max = max_len;1918if(max >50)1919 max =50;19201921if(qname.len > max) {1922 cp =strchr(qname.buf + qname.len +3- max,'/');1923if(!cp)1924 cp = qname.buf + qname.len +3- max;1925strbuf_splice(&qname,0, cp - qname.buf,"...",3);1926}19271928if(patch->is_binary) {1929printf(" %-*s | Bin\n", max, qname.buf);1930strbuf_release(&qname);1931return;1932}19331934printf(" %-*s |", max, qname.buf);1935strbuf_release(&qname);19361937/*1938 * scale the add/delete1939 */1940 max = max + max_change >70?70- max : max_change;1941 add = patch->lines_added;1942 del = patch->lines_deleted;19431944if(max_change >0) {1945int total = ((add + del) * max + max_change /2) / max_change;1946 add = (add * max + max_change /2) / max_change;1947 del = total - add;1948}1949printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,1950 add, pluses, del, minuses);1951}19521953static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)1954{1955switch(st->st_mode & S_IFMT) {1956case S_IFLNK:1957if(strbuf_readlink(buf, path, st->st_size) <0)1958returnerror("unable to read symlink%s", path);1959return0;1960case S_IFREG:1961if(strbuf_read_file(buf, path, st->st_size) != st->st_size)1962returnerror("unable to open or read%s", path);1963convert_to_git(path, buf->buf, buf->len, buf,0);1964return0;1965default:1966return-1;1967}1968}19691970/*1971 * Update the preimage, and the common lines in postimage,1972 * from buffer buf of length len. If postlen is 0 the postimage1973 * is updated in place, otherwise it's updated on a new buffer1974 * of length postlen1975 */19761977static voidupdate_pre_post_images(struct image *preimage,1978struct image *postimage,1979char*buf,1980size_t len,size_t postlen)1981{1982int i, ctx;1983char*new, *old, *fixed;1984struct image fixed_preimage;19851986/*1987 * Update the preimage with whitespace fixes. Note that we1988 * are not losing preimage->buf -- apply_one_fragment() will1989 * free "oldlines".1990 */1991prepare_image(&fixed_preimage, buf, len,1);1992assert(fixed_preimage.nr == preimage->nr);1993for(i =0; i < preimage->nr; i++)1994 fixed_preimage.line[i].flag = preimage->line[i].flag;1995free(preimage->line_allocated);1996*preimage = fixed_preimage;19971998/*1999 * Adjust the common context lines in postimage. This can be2000 * done in-place when we are just doing whitespace fixing,2001 * which does not make the string grow, but needs a new buffer2002 * when ignoring whitespace causes the update, since in this case2003 * we could have e.g. tabs converted to multiple spaces.2004 * We trust the caller to tell us if the update can be done2005 * in place (postlen==0) or not.2006 */2007 old = postimage->buf;2008if(postlen)2009new= postimage->buf =xmalloc(postlen);2010else2011new= old;2012 fixed = preimage->buf;2013for(i = ctx =0; i < postimage->nr; i++) {2014size_t len = postimage->line[i].len;2015if(!(postimage->line[i].flag & LINE_COMMON)) {2016/* an added line -- no counterparts in preimage */2017memmove(new, old, len);2018 old += len;2019new+= len;2020continue;2021}20222023/* a common context -- skip it in the original postimage */2024 old += len;20252026/* and find the corresponding one in the fixed preimage */2027while(ctx < preimage->nr &&2028!(preimage->line[ctx].flag & LINE_COMMON)) {2029 fixed += preimage->line[ctx].len;2030 ctx++;2031}2032if(preimage->nr <= ctx)2033die("oops");20342035/* and copy it in, while fixing the line length */2036 len = preimage->line[ctx].len;2037memcpy(new, fixed, len);2038new+= len;2039 fixed += len;2040 postimage->line[i].len = len;2041 ctx++;2042}20432044/* Fix the length of the whole thing */2045 postimage->len =new- postimage->buf;2046}20472048static intmatch_fragment(struct image *img,2049struct image *preimage,2050struct image *postimage,2051unsigned longtry,2052int try_lno,2053unsigned ws_rule,2054int match_beginning,int match_end)2055{2056int i;2057char*fixed_buf, *buf, *orig, *target;2058struct strbuf fixed;2059size_t fixed_len;2060int preimage_limit;20612062if(preimage->nr + try_lno <= img->nr) {2063/*2064 * The hunk falls within the boundaries of img.2065 */2066 preimage_limit = preimage->nr;2067if(match_end && (preimage->nr + try_lno != img->nr))2068return0;2069}else if(ws_error_action == correct_ws_error &&2070(ws_rule & WS_BLANK_AT_EOF)) {2071/*2072 * This hunk extends beyond the end of img, and we are2073 * removing blank lines at the end of the file. This2074 * many lines from the beginning of the preimage must2075 * match with img, and the remainder of the preimage2076 * must be blank.2077 */2078 preimage_limit = img->nr - try_lno;2079}else{2080/*2081 * The hunk extends beyond the end of the img and2082 * we are not removing blanks at the end, so we2083 * should reject the hunk at this position.2084 */2085return0;2086}20872088if(match_beginning && try_lno)2089return0;20902091/* Quick hash check */2092for(i =0; i < preimage_limit; i++)2093if((img->line[try_lno + i].flag & LINE_PATCHED) ||2094(preimage->line[i].hash != img->line[try_lno + i].hash))2095return0;20962097if(preimage_limit == preimage->nr) {2098/*2099 * Do we have an exact match? If we were told to match2100 * at the end, size must be exactly at try+fragsize,2101 * otherwise try+fragsize must be still within the preimage,2102 * and either case, the old piece should match the preimage2103 * exactly.2104 */2105if((match_end2106? (try+ preimage->len == img->len)2107: (try+ preimage->len <= img->len)) &&2108!memcmp(img->buf +try, preimage->buf, preimage->len))2109return1;2110}else{2111/*2112 * The preimage extends beyond the end of img, so2113 * there cannot be an exact match.2114 *2115 * There must be one non-blank context line that match2116 * a line before the end of img.2117 */2118char*buf_end;21192120 buf = preimage->buf;2121 buf_end = buf;2122for(i =0; i < preimage_limit; i++)2123 buf_end += preimage->line[i].len;21242125for( ; buf < buf_end; buf++)2126if(!isspace(*buf))2127break;2128if(buf == buf_end)2129return0;2130}21312132/*2133 * No exact match. If we are ignoring whitespace, run a line-by-line2134 * fuzzy matching. We collect all the line length information because2135 * we need it to adjust whitespace if we match.2136 */2137if(ws_ignore_action == ignore_ws_change) {2138size_t imgoff =0;2139size_t preoff =0;2140size_t postlen = postimage->len;2141size_t extra_chars;2142char*preimage_eof;2143char*preimage_end;2144for(i =0; i < preimage_limit; i++) {2145size_t prelen = preimage->line[i].len;2146size_t imglen = img->line[try_lno+i].len;21472148if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2149 preimage->buf + preoff, prelen))2150return0;2151if(preimage->line[i].flag & LINE_COMMON)2152 postlen += imglen - prelen;2153 imgoff += imglen;2154 preoff += prelen;2155}21562157/*2158 * Ok, the preimage matches with whitespace fuzz.2159 *2160 * imgoff now holds the true length of the target that2161 * matches the preimage before the end of the file.2162 *2163 * Count the number of characters in the preimage that fall2164 * beyond the end of the file and make sure that all of them2165 * are whitespace characters. (This can only happen if2166 * we are removing blank lines at the end of the file.)2167 */2168 buf = preimage_eof = preimage->buf + preoff;2169for( ; i < preimage->nr; i++)2170 preoff += preimage->line[i].len;2171 preimage_end = preimage->buf + preoff;2172for( ; buf < preimage_end; buf++)2173if(!isspace(*buf))2174return0;21752176/*2177 * Update the preimage and the common postimage context2178 * lines to use the same whitespace as the target.2179 * If whitespace is missing in the target (i.e.2180 * if the preimage extends beyond the end of the file),2181 * use the whitespace from the preimage.2182 */2183 extra_chars = preimage_end - preimage_eof;2184strbuf_init(&fixed, imgoff + extra_chars);2185strbuf_add(&fixed, img->buf +try, imgoff);2186strbuf_add(&fixed, preimage_eof, extra_chars);2187 fixed_buf =strbuf_detach(&fixed, &fixed_len);2188update_pre_post_images(preimage, postimage,2189 fixed_buf, fixed_len, postlen);2190return1;2191}21922193if(ws_error_action != correct_ws_error)2194return0;21952196/*2197 * The hunk does not apply byte-by-byte, but the hash says2198 * it might with whitespace fuzz. We haven't been asked to2199 * ignore whitespace, we were asked to correct whitespace2200 * errors, so let's try matching after whitespace correction.2201 *2202 * The preimage may extend beyond the end of the file,2203 * but in this loop we will only handle the part of the2204 * preimage that falls within the file.2205 */2206strbuf_init(&fixed, preimage->len +1);2207 orig = preimage->buf;2208 target = img->buf +try;2209for(i =0; i < preimage_limit; i++) {2210size_t oldlen = preimage->line[i].len;2211size_t tgtlen = img->line[try_lno + i].len;2212size_t fixstart = fixed.len;2213struct strbuf tgtfix;2214int match;22152216/* Try fixing the line in the preimage */2217ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);22182219/* Try fixing the line in the target */2220strbuf_init(&tgtfix, tgtlen);2221ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);22222223/*2224 * If they match, either the preimage was based on2225 * a version before our tree fixed whitespace breakage,2226 * or we are lacking a whitespace-fix patch the tree2227 * the preimage was based on already had (i.e. target2228 * has whitespace breakage, the preimage doesn't).2229 * In either case, we are fixing the whitespace breakages2230 * so we might as well take the fix together with their2231 * real change.2232 */2233 match = (tgtfix.len == fixed.len - fixstart &&2234!memcmp(tgtfix.buf, fixed.buf + fixstart,2235 fixed.len - fixstart));22362237strbuf_release(&tgtfix);2238if(!match)2239goto unmatch_exit;22402241 orig += oldlen;2242 target += tgtlen;2243}224422452246/*2247 * Now handle the lines in the preimage that falls beyond the2248 * end of the file (if any). They will only match if they are2249 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2250 * false).2251 */2252for( ; i < preimage->nr; i++) {2253size_t fixstart = fixed.len;/* start of the fixed preimage */2254size_t oldlen = preimage->line[i].len;2255int j;22562257/* Try fixing the line in the preimage */2258ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);22592260for(j = fixstart; j < fixed.len; j++)2261if(!isspace(fixed.buf[j]))2262goto unmatch_exit;22632264 orig += oldlen;2265}22662267/*2268 * Yes, the preimage is based on an older version that still2269 * has whitespace breakages unfixed, and fixing them makes the2270 * hunk match. Update the context lines in the postimage.2271 */2272 fixed_buf =strbuf_detach(&fixed, &fixed_len);2273update_pre_post_images(preimage, postimage,2274 fixed_buf, fixed_len,0);2275return1;22762277 unmatch_exit:2278strbuf_release(&fixed);2279return0;2280}22812282static intfind_pos(struct image *img,2283struct image *preimage,2284struct image *postimage,2285int line,2286unsigned ws_rule,2287int match_beginning,int match_end)2288{2289int i;2290unsigned long backwards, forwards,try;2291int backwards_lno, forwards_lno, try_lno;22922293/*2294 * If match_beginning or match_end is specified, there is no2295 * point starting from a wrong line that will never match and2296 * wander around and wait for a match at the specified end.2297 */2298if(match_beginning)2299 line =0;2300else if(match_end)2301 line = img->nr - preimage->nr;23022303/*2304 * Because the comparison is unsigned, the following test2305 * will also take care of a negative line number that can2306 * result when match_end and preimage is larger than the target.2307 */2308if((size_t) line > img->nr)2309 line = img->nr;23102311try=0;2312for(i =0; i < line; i++)2313try+= img->line[i].len;23142315/*2316 * There's probably some smart way to do this, but I'll leave2317 * that to the smart and beautiful people. I'm simple and stupid.2318 */2319 backwards =try;2320 backwards_lno = line;2321 forwards =try;2322 forwards_lno = line;2323 try_lno = line;23242325for(i =0; ; i++) {2326if(match_fragment(img, preimage, postimage,2327try, try_lno, ws_rule,2328 match_beginning, match_end))2329return try_lno;23302331 again:2332if(backwards_lno ==0&& forwards_lno == img->nr)2333break;23342335if(i &1) {2336if(backwards_lno ==0) {2337 i++;2338goto again;2339}2340 backwards_lno--;2341 backwards -= img->line[backwards_lno].len;2342try= backwards;2343 try_lno = backwards_lno;2344}else{2345if(forwards_lno == img->nr) {2346 i++;2347goto again;2348}2349 forwards += img->line[forwards_lno].len;2350 forwards_lno++;2351try= forwards;2352 try_lno = forwards_lno;2353}23542355}2356return-1;2357}23582359static voidremove_first_line(struct image *img)2360{2361 img->buf += img->line[0].len;2362 img->len -= img->line[0].len;2363 img->line++;2364 img->nr--;2365}23662367static voidremove_last_line(struct image *img)2368{2369 img->len -= img->line[--img->nr].len;2370}23712372static voidupdate_image(struct image *img,2373int applied_pos,2374struct image *preimage,2375struct image *postimage)2376{2377/*2378 * remove the copy of preimage at offset in img2379 * and replace it with postimage2380 */2381int i, nr;2382size_t remove_count, insert_count, applied_at =0;2383char*result;2384int preimage_limit;23852386/*2387 * If we are removing blank lines at the end of img,2388 * the preimage may extend beyond the end.2389 * If that is the case, we must be careful only to2390 * remove the part of the preimage that falls within2391 * the boundaries of img. Initialize preimage_limit2392 * to the number of lines in the preimage that falls2393 * within the boundaries.2394 */2395 preimage_limit = preimage->nr;2396if(preimage_limit > img->nr - applied_pos)2397 preimage_limit = img->nr - applied_pos;23982399for(i =0; i < applied_pos; i++)2400 applied_at += img->line[i].len;24012402 remove_count =0;2403for(i =0; i < preimage_limit; i++)2404 remove_count += img->line[applied_pos + i].len;2405 insert_count = postimage->len;24062407/* Adjust the contents */2408 result =xmalloc(img->len + insert_count - remove_count +1);2409memcpy(result, img->buf, applied_at);2410memcpy(result + applied_at, postimage->buf, postimage->len);2411memcpy(result + applied_at + postimage->len,2412 img->buf + (applied_at + remove_count),2413 img->len - (applied_at + remove_count));2414free(img->buf);2415 img->buf = result;2416 img->len += insert_count - remove_count;2417 result[img->len] ='\0';24182419/* Adjust the line table */2420 nr = img->nr + postimage->nr - preimage_limit;2421if(preimage_limit < postimage->nr) {2422/*2423 * NOTE: this knows that we never call remove_first_line()2424 * on anything other than pre/post image.2425 */2426 img->line =xrealloc(img->line, nr *sizeof(*img->line));2427 img->line_allocated = img->line;2428}2429if(preimage_limit != postimage->nr)2430memmove(img->line + applied_pos + postimage->nr,2431 img->line + applied_pos + preimage_limit,2432(img->nr - (applied_pos + preimage_limit)) *2433sizeof(*img->line));2434memcpy(img->line + applied_pos,2435 postimage->line,2436 postimage->nr *sizeof(*img->line));2437if(!allow_overlap)2438for(i =0; i < postimage->nr; i++)2439 img->line[applied_pos + i].flag |= LINE_PATCHED;2440 img->nr = nr;2441}24422443static intapply_one_fragment(struct image *img,struct fragment *frag,2444int inaccurate_eof,unsigned ws_rule,2445int nth_fragment)2446{2447int match_beginning, match_end;2448const char*patch = frag->patch;2449int size = frag->size;2450char*old, *oldlines;2451struct strbuf newlines;2452int new_blank_lines_at_end =0;2453int found_new_blank_lines_at_end =0;2454int hunk_linenr = frag->linenr;2455unsigned long leading, trailing;2456int pos, applied_pos;2457struct image preimage;2458struct image postimage;24592460memset(&preimage,0,sizeof(preimage));2461memset(&postimage,0,sizeof(postimage));2462 oldlines =xmalloc(size);2463strbuf_init(&newlines, size);24642465 old = oldlines;2466while(size >0) {2467char first;2468int len =linelen(patch, size);2469int plen;2470int added_blank_line =0;2471int is_blank_context =0;2472size_t start;24732474if(!len)2475break;24762477/*2478 * "plen" is how much of the line we should use for2479 * the actual patch data. Normally we just remove the2480 * first character on the line, but if the line is2481 * followed by "\ No newline", then we also remove the2482 * last one (which is the newline, of course).2483 */2484 plen = len -1;2485if(len < size && patch[len] =='\\')2486 plen--;2487 first = *patch;2488if(apply_in_reverse) {2489if(first =='-')2490 first ='+';2491else if(first =='+')2492 first ='-';2493}24942495switch(first) {2496case'\n':2497/* Newer GNU diff, empty context line */2498if(plen <0)2499/* ... followed by '\No newline'; nothing */2500break;2501*old++ ='\n';2502strbuf_addch(&newlines,'\n');2503add_line_info(&preimage,"\n",1, LINE_COMMON);2504add_line_info(&postimage,"\n",1, LINE_COMMON);2505 is_blank_context =1;2506break;2507case' ':2508if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2509ws_blank_line(patch +1, plen, ws_rule))2510 is_blank_context =1;2511case'-':2512memcpy(old, patch +1, plen);2513add_line_info(&preimage, old, plen,2514(first ==' '? LINE_COMMON :0));2515 old += plen;2516if(first =='-')2517break;2518/* Fall-through for ' ' */2519case'+':2520/* --no-add does not add new lines */2521if(first =='+'&& no_add)2522break;25232524 start = newlines.len;2525if(first !='+'||2526!whitespace_error ||2527 ws_error_action != correct_ws_error) {2528strbuf_add(&newlines, patch +1, plen);2529}2530else{2531ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2532}2533add_line_info(&postimage, newlines.buf + start, newlines.len - start,2534(first =='+'?0: LINE_COMMON));2535if(first =='+'&&2536(ws_rule & WS_BLANK_AT_EOF) &&2537ws_blank_line(patch +1, plen, ws_rule))2538 added_blank_line =1;2539break;2540case'@':case'\\':2541/* Ignore it, we already handled it */2542break;2543default:2544if(apply_verbosely)2545error("invalid start of line: '%c'", first);2546return-1;2547}2548if(added_blank_line) {2549if(!new_blank_lines_at_end)2550 found_new_blank_lines_at_end = hunk_linenr;2551 new_blank_lines_at_end++;2552}2553else if(is_blank_context)2554;2555else2556 new_blank_lines_at_end =0;2557 patch += len;2558 size -= len;2559 hunk_linenr++;2560}2561if(inaccurate_eof &&2562 old > oldlines && old[-1] =='\n'&&2563 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2564 old--;2565strbuf_setlen(&newlines, newlines.len -1);2566}25672568 leading = frag->leading;2569 trailing = frag->trailing;25702571/*2572 * A hunk to change lines at the beginning would begin with2573 * @@ -1,L +N,M @@2574 * but we need to be careful. -U0 that inserts before the second2575 * line also has this pattern.2576 *2577 * And a hunk to add to an empty file would begin with2578 * @@ -0,0 +N,M @@2579 *2580 * In other words, a hunk that is (frag->oldpos <= 1) with or2581 * without leading context must match at the beginning.2582 */2583 match_beginning = (!frag->oldpos ||2584(frag->oldpos ==1&& !unidiff_zero));25852586/*2587 * A hunk without trailing lines must match at the end.2588 * However, we simply cannot tell if a hunk must match end2589 * from the lack of trailing lines if the patch was generated2590 * with unidiff without any context.2591 */2592 match_end = !unidiff_zero && !trailing;25932594 pos = frag->newpos ? (frag->newpos -1) :0;2595 preimage.buf = oldlines;2596 preimage.len = old - oldlines;2597 postimage.buf = newlines.buf;2598 postimage.len = newlines.len;2599 preimage.line = preimage.line_allocated;2600 postimage.line = postimage.line_allocated;26012602for(;;) {26032604 applied_pos =find_pos(img, &preimage, &postimage, pos,2605 ws_rule, match_beginning, match_end);26062607if(applied_pos >=0)2608break;26092610/* Am I at my context limits? */2611if((leading <= p_context) && (trailing <= p_context))2612break;2613if(match_beginning || match_end) {2614 match_beginning = match_end =0;2615continue;2616}26172618/*2619 * Reduce the number of context lines; reduce both2620 * leading and trailing if they are equal otherwise2621 * just reduce the larger context.2622 */2623if(leading >= trailing) {2624remove_first_line(&preimage);2625remove_first_line(&postimage);2626 pos--;2627 leading--;2628}2629if(trailing > leading) {2630remove_last_line(&preimage);2631remove_last_line(&postimage);2632 trailing--;2633}2634}26352636if(applied_pos >=0) {2637if(new_blank_lines_at_end &&2638 preimage.nr + applied_pos >= img->nr &&2639(ws_rule & WS_BLANK_AT_EOF) &&2640 ws_error_action != nowarn_ws_error) {2641record_ws_error(WS_BLANK_AT_EOF,"+",1,2642 found_new_blank_lines_at_end);2643if(ws_error_action == correct_ws_error) {2644while(new_blank_lines_at_end--)2645remove_last_line(&postimage);2646}2647/*2648 * We would want to prevent write_out_results()2649 * from taking place in apply_patch() that follows2650 * the callchain led us here, which is:2651 * apply_patch->check_patch_list->check_patch->2652 * apply_data->apply_fragments->apply_one_fragment2653 */2654if(ws_error_action == die_on_ws_error)2655 apply =0;2656}26572658if(apply_verbosely && applied_pos != pos) {2659int offset = applied_pos - pos;2660if(apply_in_reverse)2661 offset =0- offset;2662fprintf(stderr,2663"Hunk #%dsucceeded at%d(offset%dlines).\n",2664 nth_fragment, applied_pos +1, offset);2665}26662667/*2668 * Warn if it was necessary to reduce the number2669 * of context lines.2670 */2671if((leading != frag->leading) ||2672(trailing != frag->trailing))2673fprintf(stderr,"Context reduced to (%ld/%ld)"2674" to apply fragment at%d\n",2675 leading, trailing, applied_pos+1);2676update_image(img, applied_pos, &preimage, &postimage);2677}else{2678if(apply_verbosely)2679error("while searching for:\n%.*s",2680(int)(old - oldlines), oldlines);2681}26822683free(oldlines);2684strbuf_release(&newlines);2685free(preimage.line_allocated);2686free(postimage.line_allocated);26872688return(applied_pos <0);2689}26902691static intapply_binary_fragment(struct image *img,struct patch *patch)2692{2693struct fragment *fragment = patch->fragments;2694unsigned long len;2695void*dst;26962697if(!fragment)2698returnerror("missing binary patch data for '%s'",2699 patch->new_name ?2700 patch->new_name :2701 patch->old_name);27022703/* Binary patch is irreversible without the optional second hunk */2704if(apply_in_reverse) {2705if(!fragment->next)2706returnerror("cannot reverse-apply a binary patch "2707"without the reverse hunk to '%s'",2708 patch->new_name2709? patch->new_name : patch->old_name);2710 fragment = fragment->next;2711}2712switch(fragment->binary_patch_method) {2713case BINARY_DELTA_DEFLATED:2714 dst =patch_delta(img->buf, img->len, fragment->patch,2715 fragment->size, &len);2716if(!dst)2717return-1;2718clear_image(img);2719 img->buf = dst;2720 img->len = len;2721return0;2722case BINARY_LITERAL_DEFLATED:2723clear_image(img);2724 img->len = fragment->size;2725 img->buf =xmalloc(img->len+1);2726memcpy(img->buf, fragment->patch, img->len);2727 img->buf[img->len] ='\0';2728return0;2729}2730return-1;2731}27322733static intapply_binary(struct image *img,struct patch *patch)2734{2735const char*name = patch->old_name ? patch->old_name : patch->new_name;2736unsigned char sha1[20];27372738/*2739 * For safety, we require patch index line to contain2740 * full 40-byte textual SHA1 for old and new, at least for now.2741 */2742if(strlen(patch->old_sha1_prefix) !=40||2743strlen(patch->new_sha1_prefix) !=40||2744get_sha1_hex(patch->old_sha1_prefix, sha1) ||2745get_sha1_hex(patch->new_sha1_prefix, sha1))2746returnerror("cannot apply binary patch to '%s' "2747"without full index line", name);27482749if(patch->old_name) {2750/*2751 * See if the old one matches what the patch2752 * applies to.2753 */2754hash_sha1_file(img->buf, img->len, blob_type, sha1);2755if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2756returnerror("the patch applies to '%s' (%s), "2757"which does not match the "2758"current contents.",2759 name,sha1_to_hex(sha1));2760}2761else{2762/* Otherwise, the old one must be empty. */2763if(img->len)2764returnerror("the patch applies to an empty "2765"'%s' but it is not empty", name);2766}27672768get_sha1_hex(patch->new_sha1_prefix, sha1);2769if(is_null_sha1(sha1)) {2770clear_image(img);2771return0;/* deletion patch */2772}27732774if(has_sha1_file(sha1)) {2775/* We already have the postimage */2776enum object_type type;2777unsigned long size;2778char*result;27792780 result =read_sha1_file(sha1, &type, &size);2781if(!result)2782returnerror("the necessary postimage%sfor "2783"'%s' cannot be read",2784 patch->new_sha1_prefix, name);2785clear_image(img);2786 img->buf = result;2787 img->len = size;2788}else{2789/*2790 * We have verified buf matches the preimage;2791 * apply the patch data to it, which is stored2792 * in the patch->fragments->{patch,size}.2793 */2794if(apply_binary_fragment(img, patch))2795returnerror("binary patch does not apply to '%s'",2796 name);27972798/* verify that the result matches */2799hash_sha1_file(img->buf, img->len, blob_type, sha1);2800if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2801returnerror("binary patch to '%s' creates incorrect result (expecting%s, got%s)",2802 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2803}28042805return0;2806}28072808static intapply_fragments(struct image *img,struct patch *patch)2809{2810struct fragment *frag = patch->fragments;2811const char*name = patch->old_name ? patch->old_name : patch->new_name;2812unsigned ws_rule = patch->ws_rule;2813unsigned inaccurate_eof = patch->inaccurate_eof;2814int nth =0;28152816if(patch->is_binary)2817returnapply_binary(img, patch);28182819while(frag) {2820 nth++;2821if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {2822error("patch failed:%s:%ld", name, frag->oldpos);2823if(!apply_with_reject)2824return-1;2825 frag->rejected =1;2826}2827 frag = frag->next;2828}2829return0;2830}28312832static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2833{2834if(!ce)2835return0;28362837if(S_ISGITLINK(ce->ce_mode)) {2838strbuf_grow(buf,100);2839strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2840}else{2841enum object_type type;2842unsigned long sz;2843char*result;28442845 result =read_sha1_file(ce->sha1, &type, &sz);2846if(!result)2847return-1;2848/* XXX read_sha1_file NUL-terminates */2849strbuf_attach(buf, result, sz, sz +1);2850}2851return0;2852}28532854static struct patch *in_fn_table(const char*name)2855{2856struct string_list_item *item;28572858if(name == NULL)2859return NULL;28602861 item =string_list_lookup(&fn_table, name);2862if(item != NULL)2863return(struct patch *)item->util;28642865return NULL;2866}28672868/*2869 * item->util in the filename table records the status of the path.2870 * Usually it points at a patch (whose result records the contents2871 * of it after applying it), but it could be PATH_WAS_DELETED for a2872 * path that a previously applied patch has already removed.2873 */2874#define PATH_TO_BE_DELETED ((struct patch *) -2)2875#define PATH_WAS_DELETED ((struct patch *) -1)28762877static intto_be_deleted(struct patch *patch)2878{2879return patch == PATH_TO_BE_DELETED;2880}28812882static intwas_deleted(struct patch *patch)2883{2884return patch == PATH_WAS_DELETED;2885}28862887static voidadd_to_fn_table(struct patch *patch)2888{2889struct string_list_item *item;28902891/*2892 * Always add new_name unless patch is a deletion2893 * This should cover the cases for normal diffs,2894 * file creations and copies2895 */2896if(patch->new_name != NULL) {2897 item =string_list_insert(&fn_table, patch->new_name);2898 item->util = patch;2899}29002901/*2902 * store a failure on rename/deletion cases because2903 * later chunks shouldn't patch old names2904 */2905if((patch->new_name == NULL) || (patch->is_rename)) {2906 item =string_list_insert(&fn_table, patch->old_name);2907 item->util = PATH_WAS_DELETED;2908}2909}29102911static voidprepare_fn_table(struct patch *patch)2912{2913/*2914 * store information about incoming file deletion2915 */2916while(patch) {2917if((patch->new_name == NULL) || (patch->is_rename)) {2918struct string_list_item *item;2919 item =string_list_insert(&fn_table, patch->old_name);2920 item->util = PATH_TO_BE_DELETED;2921}2922 patch = patch->next;2923}2924}29252926static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)2927{2928struct strbuf buf = STRBUF_INIT;2929struct image image;2930size_t len;2931char*img;2932struct patch *tpatch;29332934if(!(patch->is_copy || patch->is_rename) &&2935(tpatch =in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {2936if(was_deleted(tpatch)) {2937returnerror("patch%shas been renamed/deleted",2938 patch->old_name);2939}2940/* We have a patched copy in memory use that */2941strbuf_add(&buf, tpatch->result, tpatch->resultsize);2942}else if(cached) {2943if(read_file_or_gitlink(ce, &buf))2944returnerror("read of%sfailed", patch->old_name);2945}else if(patch->old_name) {2946if(S_ISGITLINK(patch->old_mode)) {2947if(ce) {2948read_file_or_gitlink(ce, &buf);2949}else{2950/*2951 * There is no way to apply subproject2952 * patch without looking at the index.2953 */2954 patch->fragments = NULL;2955}2956}else{2957if(read_old_data(st, patch->old_name, &buf))2958returnerror("read of%sfailed", patch->old_name);2959}2960}29612962 img =strbuf_detach(&buf, &len);2963prepare_image(&image, img, len, !patch->is_binary);29642965if(apply_fragments(&image, patch) <0)2966return-1;/* note with --reject this succeeds. */2967 patch->result = image.buf;2968 patch->resultsize = image.len;2969add_to_fn_table(patch);2970free(image.line_allocated);29712972if(0< patch->is_delete && patch->resultsize)2973returnerror("removal patch leaves file contents");29742975return0;2976}29772978static intcheck_to_create_blob(const char*new_name,int ok_if_exists)2979{2980struct stat nst;2981if(!lstat(new_name, &nst)) {2982if(S_ISDIR(nst.st_mode) || ok_if_exists)2983return0;2984/*2985 * A leading component of new_name might be a symlink2986 * that is going to be removed with this patch, but2987 * still pointing at somewhere that has the path.2988 * In such a case, path "new_name" does not exist as2989 * far as git is concerned.2990 */2991if(has_symlink_leading_path(new_name,strlen(new_name)))2992return0;29932994returnerror("%s: already exists in working directory", new_name);2995}2996else if((errno != ENOENT) && (errno != ENOTDIR))2997returnerror("%s:%s", new_name,strerror(errno));2998return0;2999}30003001static intverify_index_match(struct cache_entry *ce,struct stat *st)3002{3003if(S_ISGITLINK(ce->ce_mode)) {3004if(!S_ISDIR(st->st_mode))3005return-1;3006return0;3007}3008returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3009}30103011static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)3012{3013const char*old_name = patch->old_name;3014struct patch *tpatch = NULL;3015int stat_ret =0;3016unsigned st_mode =0;30173018/*3019 * Make sure that we do not have local modifications from the3020 * index when we are looking at the index. Also make sure3021 * we have the preimage file to be patched in the work tree,3022 * unless --cached, which tells git to apply only in the index.3023 */3024if(!old_name)3025return0;30263027assert(patch->is_new <=0);30283029if(!(patch->is_copy || patch->is_rename) &&3030(tpatch =in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {3031if(was_deleted(tpatch))3032returnerror("%s: has been deleted/renamed", old_name);3033 st_mode = tpatch->new_mode;3034}else if(!cached) {3035 stat_ret =lstat(old_name, st);3036if(stat_ret && errno != ENOENT)3037returnerror("%s:%s", old_name,strerror(errno));3038}30393040if(to_be_deleted(tpatch))3041 tpatch = NULL;30423043if(check_index && !tpatch) {3044int pos =cache_name_pos(old_name,strlen(old_name));3045if(pos <0) {3046if(patch->is_new <0)3047goto is_new;3048returnerror("%s: does not exist in index", old_name);3049}3050*ce = active_cache[pos];3051if(stat_ret <0) {3052struct checkout costate;3053/* checkout */3054memset(&costate,0,sizeof(costate));3055 costate.base_dir ="";3056 costate.refresh_cache =1;3057if(checkout_entry(*ce, &costate, NULL) ||3058lstat(old_name, st))3059return-1;3060}3061if(!cached &&verify_index_match(*ce, st))3062returnerror("%s: does not match index", old_name);3063if(cached)3064 st_mode = (*ce)->ce_mode;3065}else if(stat_ret <0) {3066if(patch->is_new <0)3067goto is_new;3068returnerror("%s:%s", old_name,strerror(errno));3069}30703071if(!cached && !tpatch)3072 st_mode =ce_mode_from_stat(*ce, st->st_mode);30733074if(patch->is_new <0)3075 patch->is_new =0;3076if(!patch->old_mode)3077 patch->old_mode = st_mode;3078if((st_mode ^ patch->old_mode) & S_IFMT)3079returnerror("%s: wrong type", old_name);3080if(st_mode != patch->old_mode)3081warning("%shas type%o, expected%o",3082 old_name, st_mode, patch->old_mode);3083if(!patch->new_mode && !patch->is_delete)3084 patch->new_mode = st_mode;3085return0;30863087 is_new:3088 patch->is_new =1;3089 patch->is_delete =0;3090 patch->old_name = NULL;3091return0;3092}30933094static intcheck_patch(struct patch *patch)3095{3096struct stat st;3097const char*old_name = patch->old_name;3098const char*new_name = patch->new_name;3099const char*name = old_name ? old_name : new_name;3100struct cache_entry *ce = NULL;3101struct patch *tpatch;3102int ok_if_exists;3103int status;31043105 patch->rejected =1;/* we will drop this after we succeed */31063107 status =check_preimage(patch, &ce, &st);3108if(status)3109return status;3110 old_name = patch->old_name;31113112if((tpatch =in_fn_table(new_name)) &&3113(was_deleted(tpatch) ||to_be_deleted(tpatch)))3114/*3115 * A type-change diff is always split into a patch to3116 * delete old, immediately followed by a patch to3117 * create new (see diff.c::run_diff()); in such a case3118 * it is Ok that the entry to be deleted by the3119 * previous patch is still in the working tree and in3120 * the index.3121 */3122 ok_if_exists =1;3123else3124 ok_if_exists =0;31253126if(new_name &&3127((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {3128if(check_index &&3129cache_name_pos(new_name,strlen(new_name)) >=0&&3130!ok_if_exists)3131returnerror("%s: already exists in index", new_name);3132if(!cached) {3133int err =check_to_create_blob(new_name, ok_if_exists);3134if(err)3135return err;3136}3137if(!patch->new_mode) {3138if(0< patch->is_new)3139 patch->new_mode = S_IFREG |0644;3140else3141 patch->new_mode = patch->old_mode;3142}3143}31443145if(new_name && old_name) {3146int same = !strcmp(old_name, new_name);3147if(!patch->new_mode)3148 patch->new_mode = patch->old_mode;3149if((patch->old_mode ^ patch->new_mode) & S_IFMT)3150returnerror("new mode (%o) of%sdoes not match old mode (%o)%s%s",3151 patch->new_mode, new_name, patch->old_mode,3152 same ?"":" of ", same ?"": old_name);3153}31543155if(apply_data(patch, &st, ce) <0)3156returnerror("%s: patch does not apply", name);3157 patch->rejected =0;3158return0;3159}31603161static intcheck_patch_list(struct patch *patch)3162{3163int err =0;31643165prepare_fn_table(patch);3166while(patch) {3167if(apply_verbosely)3168say_patch_name(stderr,3169"Checking patch ", patch,"...\n");3170 err |=check_patch(patch);3171 patch = patch->next;3172}3173return err;3174}31753176/* This function tries to read the sha1 from the current index */3177static intget_current_sha1(const char*path,unsigned char*sha1)3178{3179int pos;31803181if(read_cache() <0)3182return-1;3183 pos =cache_name_pos(path,strlen(path));3184if(pos <0)3185return-1;3186hashcpy(sha1, active_cache[pos]->sha1);3187return0;3188}31893190/* Build an index that contains the just the files needed for a 3way merge */3191static voidbuild_fake_ancestor(struct patch *list,const char*filename)3192{3193struct patch *patch;3194struct index_state result = { NULL };3195int fd;31963197/* Once we start supporting the reverse patch, it may be3198 * worth showing the new sha1 prefix, but until then...3199 */3200for(patch = list; patch; patch = patch->next) {3201const unsigned char*sha1_ptr;3202unsigned char sha1[20];3203struct cache_entry *ce;3204const char*name;32053206 name = patch->old_name ? patch->old_name : patch->new_name;3207if(0< patch->is_new)3208continue;3209else if(get_sha1(patch->old_sha1_prefix, sha1))3210/* git diff has no index line for mode/type changes */3211if(!patch->lines_added && !patch->lines_deleted) {3212if(get_current_sha1(patch->old_name, sha1))3213die("mode change for%s, which is not "3214"in current HEAD", name);3215 sha1_ptr = sha1;3216}else3217die("sha1 information is lacking or useless "3218"(%s).", name);3219else3220 sha1_ptr = sha1;32213222 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);3223if(!ce)3224die("make_cache_entry failed for path '%s'", name);3225if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3226die("Could not add%sto temporary index", name);3227}32283229 fd =open(filename, O_WRONLY | O_CREAT,0666);3230if(fd <0||write_index(&result, fd) ||close(fd))3231die("Could not write temporary index to%s", filename);32323233discard_index(&result);3234}32353236static voidstat_patch_list(struct patch *patch)3237{3238int files, adds, dels;32393240for(files = adds = dels =0; patch ; patch = patch->next) {3241 files++;3242 adds += patch->lines_added;3243 dels += patch->lines_deleted;3244show_stats(patch);3245}32463247printf("%dfiles changed,%dinsertions(+),%ddeletions(-)\n", files, adds, dels);3248}32493250static voidnumstat_patch_list(struct patch *patch)3251{3252for( ; patch; patch = patch->next) {3253const char*name;3254 name = patch->new_name ? patch->new_name : patch->old_name;3255if(patch->is_binary)3256printf("-\t-\t");3257else3258printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3259write_name_quoted(name, stdout, line_termination);3260}3261}32623263static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3264{3265if(mode)3266printf("%smode%06o%s\n", newdelete, mode, name);3267else3268printf("%s %s\n", newdelete, name);3269}32703271static voidshow_mode_change(struct patch *p,int show_name)3272{3273if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3274if(show_name)3275printf(" mode change%06o =>%06o%s\n",3276 p->old_mode, p->new_mode, p->new_name);3277else3278printf(" mode change%06o =>%06o\n",3279 p->old_mode, p->new_mode);3280}3281}32823283static voidshow_rename_copy(struct patch *p)3284{3285const char*renamecopy = p->is_rename ?"rename":"copy";3286const char*old, *new;32873288/* Find common prefix */3289 old = p->old_name;3290new= p->new_name;3291while(1) {3292const char*slash_old, *slash_new;3293 slash_old =strchr(old,'/');3294 slash_new =strchr(new,'/');3295if(!slash_old ||3296!slash_new ||3297 slash_old - old != slash_new -new||3298memcmp(old,new, slash_new -new))3299break;3300 old = slash_old +1;3301new= slash_new +1;3302}3303/* p->old_name thru old is the common prefix, and old and new3304 * through the end of names are renames3305 */3306if(old != p->old_name)3307printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,3308(int)(old - p->old_name), p->old_name,3309 old,new, p->score);3310else3311printf("%s %s=>%s(%d%%)\n", renamecopy,3312 p->old_name, p->new_name, p->score);3313show_mode_change(p,0);3314}33153316static voidsummary_patch_list(struct patch *patch)3317{3318struct patch *p;33193320for(p = patch; p; p = p->next) {3321if(p->is_new)3322show_file_mode_name("create", p->new_mode, p->new_name);3323else if(p->is_delete)3324show_file_mode_name("delete", p->old_mode, p->old_name);3325else{3326if(p->is_rename || p->is_copy)3327show_rename_copy(p);3328else{3329if(p->score) {3330printf(" rewrite%s(%d%%)\n",3331 p->new_name, p->score);3332show_mode_change(p,0);3333}3334else3335show_mode_change(p,1);3336}3337}3338}3339}33403341static voidpatch_stats(struct patch *patch)3342{3343int lines = patch->lines_added + patch->lines_deleted;33443345if(lines > max_change)3346 max_change = lines;3347if(patch->old_name) {3348int len =quote_c_style(patch->old_name, NULL, NULL,0);3349if(!len)3350 len =strlen(patch->old_name);3351if(len > max_len)3352 max_len = len;3353}3354if(patch->new_name) {3355int len =quote_c_style(patch->new_name, NULL, NULL,0);3356if(!len)3357 len =strlen(patch->new_name);3358if(len > max_len)3359 max_len = len;3360}3361}33623363static voidremove_file(struct patch *patch,int rmdir_empty)3364{3365if(update_index) {3366if(remove_file_from_cache(patch->old_name) <0)3367die("unable to remove%sfrom index", patch->old_name);3368}3369if(!cached) {3370if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {3371remove_path(patch->old_name);3372}3373}3374}33753376static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)3377{3378struct stat st;3379struct cache_entry *ce;3380int namelen =strlen(path);3381unsigned ce_size =cache_entry_size(namelen);33823383if(!update_index)3384return;33853386 ce =xcalloc(1, ce_size);3387memcpy(ce->name, path, namelen);3388 ce->ce_mode =create_ce_mode(mode);3389 ce->ce_flags = namelen;3390if(S_ISGITLINK(mode)) {3391const char*s = buf;33923393if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))3394die("corrupt patch for subproject%s", path);3395}else{3396if(!cached) {3397if(lstat(path, &st) <0)3398die_errno("unable to stat newly created file '%s'",3399 path);3400fill_stat_cache_info(ce, &st);3401}3402if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)3403die("unable to create backing store for newly created file%s", path);3404}3405if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3406die("unable to add cache entry for%s", path);3407}34083409static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)3410{3411int fd;3412struct strbuf nbuf = STRBUF_INIT;34133414if(S_ISGITLINK(mode)) {3415struct stat st;3416if(!lstat(path, &st) &&S_ISDIR(st.st_mode))3417return0;3418returnmkdir(path,0777);3419}34203421if(has_symlinks &&S_ISLNK(mode))3422/* Although buf:size is counted string, it also is NUL3423 * terminated.3424 */3425returnsymlink(buf, path);34263427 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);3428if(fd <0)3429return-1;34303431if(convert_to_working_tree(path, buf, size, &nbuf)) {3432 size = nbuf.len;3433 buf = nbuf.buf;3434}3435write_or_die(fd, buf, size);3436strbuf_release(&nbuf);34373438if(close(fd) <0)3439die_errno("closing file '%s'", path);3440return0;3441}34423443/*3444 * We optimistically assume that the directories exist,3445 * which is true 99% of the time anyway. If they don't,3446 * we create them and try again.3447 */3448static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)3449{3450if(cached)3451return;3452if(!try_create_file(path, mode, buf, size))3453return;34543455if(errno == ENOENT) {3456if(safe_create_leading_directories(path))3457return;3458if(!try_create_file(path, mode, buf, size))3459return;3460}34613462if(errno == EEXIST || errno == EACCES) {3463/* We may be trying to create a file where a directory3464 * used to be.3465 */3466struct stat st;3467if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))3468 errno = EEXIST;3469}34703471if(errno == EEXIST) {3472unsigned int nr =getpid();34733474for(;;) {3475char newpath[PATH_MAX];3476mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);3477if(!try_create_file(newpath, mode, buf, size)) {3478if(!rename(newpath, path))3479return;3480unlink_or_warn(newpath);3481break;3482}3483if(errno != EEXIST)3484break;3485++nr;3486}3487}3488die_errno("unable to write file '%s' mode%o", path, mode);3489}34903491static voidcreate_file(struct patch *patch)3492{3493char*path = patch->new_name;3494unsigned mode = patch->new_mode;3495unsigned long size = patch->resultsize;3496char*buf = patch->result;34973498if(!mode)3499 mode = S_IFREG |0644;3500create_one_file(path, mode, buf, size);3501add_index_file(path, mode, buf, size);3502}35033504/* phase zero is to remove, phase one is to create */3505static voidwrite_out_one_result(struct patch *patch,int phase)3506{3507if(patch->is_delete >0) {3508if(phase ==0)3509remove_file(patch,1);3510return;3511}3512if(patch->is_new >0|| patch->is_copy) {3513if(phase ==1)3514create_file(patch);3515return;3516}3517/*3518 * Rename or modification boils down to the same3519 * thing: remove the old, write the new3520 */3521if(phase ==0)3522remove_file(patch, patch->is_rename);3523if(phase ==1)3524create_file(patch);3525}35263527static intwrite_out_one_reject(struct patch *patch)3528{3529FILE*rej;3530char namebuf[PATH_MAX];3531struct fragment *frag;3532int cnt =0;35333534for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {3535if(!frag->rejected)3536continue;3537 cnt++;3538}35393540if(!cnt) {3541if(apply_verbosely)3542say_patch_name(stderr,3543"Applied patch ", patch," cleanly.\n");3544return0;3545}35463547/* This should not happen, because a removal patch that leaves3548 * contents are marked "rejected" at the patch level.3549 */3550if(!patch->new_name)3551die("internal error");35523553/* Say this even without --verbose */3554say_patch_name(stderr,"Applying patch ", patch," with");3555fprintf(stderr,"%drejects...\n", cnt);35563557 cnt =strlen(patch->new_name);3558if(ARRAY_SIZE(namebuf) <= cnt +5) {3559 cnt =ARRAY_SIZE(namebuf) -5;3560warning("truncating .rej filename to %.*s.rej",3561 cnt -1, patch->new_name);3562}3563memcpy(namebuf, patch->new_name, cnt);3564memcpy(namebuf + cnt,".rej",5);35653566 rej =fopen(namebuf,"w");3567if(!rej)3568returnerror("cannot open%s:%s", namebuf,strerror(errno));35693570/* Normal git tools never deal with .rej, so do not pretend3571 * this is a git patch by saying --git nor give extended3572 * headers. While at it, maybe please "kompare" that wants3573 * the trailing TAB and some garbage at the end of line ;-).3574 */3575fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",3576 patch->new_name, patch->new_name);3577for(cnt =1, frag = patch->fragments;3578 frag;3579 cnt++, frag = frag->next) {3580if(!frag->rejected) {3581fprintf(stderr,"Hunk #%dapplied cleanly.\n", cnt);3582continue;3583}3584fprintf(stderr,"Rejected hunk #%d.\n", cnt);3585fprintf(rej,"%.*s", frag->size, frag->patch);3586if(frag->patch[frag->size-1] !='\n')3587fputc('\n', rej);3588}3589fclose(rej);3590return-1;3591}35923593static intwrite_out_results(struct patch *list,int skipped_patch)3594{3595int phase;3596int errs =0;3597struct patch *l;35983599if(!list && !skipped_patch)3600returnerror("No changes");36013602for(phase =0; phase <2; phase++) {3603 l = list;3604while(l) {3605if(l->rejected)3606 errs =1;3607else{3608write_out_one_result(l, phase);3609if(phase ==1&&write_out_one_reject(l))3610 errs =1;3611}3612 l = l->next;3613}3614}3615return errs;3616}36173618static struct lock_file lock_file;36193620static struct string_list limit_by_name;3621static int has_include;3622static voidadd_name_limit(const char*name,int exclude)3623{3624struct string_list_item *it;36253626 it =string_list_append(&limit_by_name, name);3627 it->util = exclude ? NULL : (void*)1;3628}36293630static intuse_patch(struct patch *p)3631{3632const char*pathname = p->new_name ? p->new_name : p->old_name;3633int i;36343635/* Paths outside are not touched regardless of "--include" */3636if(0< prefix_length) {3637int pathlen =strlen(pathname);3638if(pathlen <= prefix_length ||3639memcmp(prefix, pathname, prefix_length))3640return0;3641}36423643/* See if it matches any of exclude/include rule */3644for(i =0; i < limit_by_name.nr; i++) {3645struct string_list_item *it = &limit_by_name.items[i];3646if(!fnmatch(it->string, pathname,0))3647return(it->util != NULL);3648}36493650/*3651 * If we had any include, a path that does not match any rule is3652 * not used. Otherwise, we saw bunch of exclude rules (or none)3653 * and such a path is used.3654 */3655return!has_include;3656}365736583659static voidprefix_one(char**name)3660{3661char*old_name = *name;3662if(!old_name)3663return;3664*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3665free(old_name);3666}36673668static voidprefix_patches(struct patch *p)3669{3670if(!prefix || p->is_toplevel_relative)3671return;3672for( ; p; p = p->next) {3673if(p->new_name == p->old_name) {3674char*prefixed = p->new_name;3675prefix_one(&prefixed);3676 p->new_name = p->old_name = prefixed;3677}3678else{3679prefix_one(&p->new_name);3680prefix_one(&p->old_name);3681}3682}3683}36843685#define INACCURATE_EOF (1<<0)3686#define RECOUNT (1<<1)36873688static intapply_patch(int fd,const char*filename,int options)3689{3690size_t offset;3691struct strbuf buf = STRBUF_INIT;3692struct patch *list = NULL, **listp = &list;3693int skipped_patch =0;36943695/* FIXME - memory leak when using multiple patch files as inputs */3696memset(&fn_table,0,sizeof(struct string_list));3697 patch_input_file = filename;3698read_patch_file(&buf, fd);3699 offset =0;3700while(offset < buf.len) {3701struct patch *patch;3702int nr;37033704 patch =xcalloc(1,sizeof(*patch));3705 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3706 patch->recount = !!(options & RECOUNT);3707 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3708if(nr <0)3709break;3710if(apply_in_reverse)3711reverse_patches(patch);3712if(prefix)3713prefix_patches(patch);3714if(use_patch(patch)) {3715patch_stats(patch);3716*listp = patch;3717 listp = &patch->next;3718}3719else{3720/* perhaps free it a bit better? */3721free(patch);3722 skipped_patch++;3723}3724 offset += nr;3725}37263727if(whitespace_error && (ws_error_action == die_on_ws_error))3728 apply =0;37293730 update_index = check_index && apply;3731if(update_index && newfd <0)3732 newfd =hold_locked_index(&lock_file,1);37333734if(check_index) {3735if(read_cache() <0)3736die("unable to read index file");3737}37383739if((check || apply) &&3740check_patch_list(list) <0&&3741!apply_with_reject)3742exit(1);37433744if(apply &&write_out_results(list, skipped_patch))3745exit(1);37463747if(fake_ancestor)3748build_fake_ancestor(list, fake_ancestor);37493750if(diffstat)3751stat_patch_list(list);37523753if(numstat)3754numstat_patch_list(list);37553756if(summary)3757summary_patch_list(list);37583759strbuf_release(&buf);3760return0;3761}37623763static intgit_apply_config(const char*var,const char*value,void*cb)3764{3765if(!strcmp(var,"apply.whitespace"))3766returngit_config_string(&apply_default_whitespace, var, value);3767else if(!strcmp(var,"apply.ignorewhitespace"))3768returngit_config_string(&apply_default_ignorewhitespace, var, value);3769returngit_default_config(var, value, cb);3770}37713772static intoption_parse_exclude(const struct option *opt,3773const char*arg,int unset)3774{3775add_name_limit(arg,1);3776return0;3777}37783779static intoption_parse_include(const struct option *opt,3780const char*arg,int unset)3781{3782add_name_limit(arg,0);3783 has_include =1;3784return0;3785}37863787static intoption_parse_p(const struct option *opt,3788const char*arg,int unset)3789{3790 p_value =atoi(arg);3791 p_value_known =1;3792return0;3793}37943795static intoption_parse_z(const struct option *opt,3796const char*arg,int unset)3797{3798if(unset)3799 line_termination ='\n';3800else3801 line_termination =0;3802return0;3803}38043805static intoption_parse_space_change(const struct option *opt,3806const char*arg,int unset)3807{3808if(unset)3809 ws_ignore_action = ignore_ws_none;3810else3811 ws_ignore_action = ignore_ws_change;3812return0;3813}38143815static intoption_parse_whitespace(const struct option *opt,3816const char*arg,int unset)3817{3818const char**whitespace_option = opt->value;38193820*whitespace_option = arg;3821parse_whitespace_option(arg);3822return0;3823}38243825static intoption_parse_directory(const struct option *opt,3826const char*arg,int unset)3827{3828 root_len =strlen(arg);3829if(root_len && arg[root_len -1] !='/') {3830char*new_root;3831 root = new_root =xmalloc(root_len +2);3832strcpy(new_root, arg);3833strcpy(new_root + root_len++,"/");3834}else3835 root = arg;3836return0;3837}38383839intcmd_apply(int argc,const char**argv,const char*prefix_)3840{3841int i;3842int errs =0;3843int is_not_gitdir = !startup_info->have_repository;3844int force_apply =0;38453846const char*whitespace_option = NULL;38473848struct option builtin_apply_options[] = {3849{ OPTION_CALLBACK,0,"exclude", NULL,"path",3850"don't apply changes matching the given path",38510, option_parse_exclude },3852{ OPTION_CALLBACK,0,"include", NULL,"path",3853"apply changes matching the given path",38540, option_parse_include },3855{ OPTION_CALLBACK,'p', NULL, NULL,"num",3856"remove <num> leading slashes from traditional diff paths",38570, option_parse_p },3858OPT_BOOLEAN(0,"no-add", &no_add,3859"ignore additions made by the patch"),3860OPT_BOOLEAN(0,"stat", &diffstat,3861"instead of applying the patch, output diffstat for the input"),3862OPT_NOOP_NOARG(0,"allow-binary-replacement"),3863OPT_NOOP_NOARG(0,"binary"),3864OPT_BOOLEAN(0,"numstat", &numstat,3865"shows number of added and deleted lines in decimal notation"),3866OPT_BOOLEAN(0,"summary", &summary,3867"instead of applying the patch, output a summary for the input"),3868OPT_BOOLEAN(0,"check", &check,3869"instead of applying the patch, see if the patch is applicable"),3870OPT_BOOLEAN(0,"index", &check_index,3871"make sure the patch is applicable to the current index"),3872OPT_BOOLEAN(0,"cached", &cached,3873"apply a patch without touching the working tree"),3874OPT_BOOLEAN(0,"apply", &force_apply,3875"also apply the patch (use with --stat/--summary/--check)"),3876OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,3877"build a temporary index based on embedded index information"),3878{ OPTION_CALLBACK,'z', NULL, NULL, NULL,3879"paths are separated with NUL character",3880 PARSE_OPT_NOARG, option_parse_z },3881OPT_INTEGER('C', NULL, &p_context,3882"ensure at least <n> lines of context match"),3883{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,"action",3884"detect new or modified lines that have whitespace errors",38850, option_parse_whitespace },3886{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,3887"ignore changes in whitespace when finding context",3888 PARSE_OPT_NOARG, option_parse_space_change },3889{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,3890"ignore changes in whitespace when finding context",3891 PARSE_OPT_NOARG, option_parse_space_change },3892OPT_BOOLEAN('R',"reverse", &apply_in_reverse,3893"apply the patch in reverse"),3894OPT_BOOLEAN(0,"unidiff-zero", &unidiff_zero,3895"don't expect at least one line of context"),3896OPT_BOOLEAN(0,"reject", &apply_with_reject,3897"leave the rejected hunks in corresponding *.rej files"),3898OPT_BOOLEAN(0,"allow-overlap", &allow_overlap,3899"allow overlapping hunks"),3900OPT__VERBOSE(&apply_verbosely,"be verbose"),3901OPT_BIT(0,"inaccurate-eof", &options,3902"tolerate incorrectly detected missing new-line at the end of file",3903 INACCURATE_EOF),3904OPT_BIT(0,"recount", &options,3905"do not trust the line counts in the hunk headers",3906 RECOUNT),3907{ OPTION_CALLBACK,0,"directory", NULL,"root",3908"prepend <root> to all filenames",39090, option_parse_directory },3910OPT_END()3911};39123913 prefix = prefix_;3914 prefix_length = prefix ?strlen(prefix) :0;3915git_config(git_apply_config, NULL);3916if(apply_default_whitespace)3917parse_whitespace_option(apply_default_whitespace);3918if(apply_default_ignorewhitespace)3919parse_ignorewhitespace_option(apply_default_ignorewhitespace);39203921 argc =parse_options(argc, argv, prefix, builtin_apply_options,3922 apply_usage,0);39233924if(apply_with_reject)3925 apply = apply_verbosely =1;3926if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))3927 apply =0;3928if(check_index && is_not_gitdir)3929die("--index outside a repository");3930if(cached) {3931if(is_not_gitdir)3932die("--cached outside a repository");3933 check_index =1;3934}3935for(i =0; i < argc; i++) {3936const char*arg = argv[i];3937int fd;39383939if(!strcmp(arg,"-")) {3940 errs |=apply_patch(0,"<stdin>", options);3941 read_stdin =0;3942continue;3943}else if(0< prefix_length)3944 arg =prefix_filename(prefix, prefix_length, arg);39453946 fd =open(arg, O_RDONLY);3947if(fd <0)3948die_errno("can't open patch '%s'", arg);3949 read_stdin =0;3950set_default_whitespace_mode(whitespace_option);3951 errs |=apply_patch(fd, arg, options);3952close(fd);3953}3954set_default_whitespace_mode(whitespace_option);3955if(read_stdin)3956 errs |=apply_patch(0,"<stdin>", options);3957if(whitespace_error) {3958if(squelch_whitespace_errors &&3959 squelch_whitespace_errors < whitespace_error) {3960int squelched =3961 whitespace_error - squelch_whitespace_errors;3962warning("squelched%d"3963"whitespace error%s",3964 squelched,3965 squelched ==1?"":"s");3966}3967if(ws_error_action == die_on_ws_error)3968die("%dline%sadd%swhitespace errors.",3969 whitespace_error,3970 whitespace_error ==1?"":"s",3971 whitespace_error ==1?"s":"");3972if(applied_after_fixing_ws && apply)3973warning("%dline%sapplied after"3974" fixing whitespace errors.",3975 applied_after_fixing_ws,3976 applied_after_fixing_ws ==1?"":"s");3977else if(whitespace_error)3978warning("%dline%sadd%swhitespace errors.",3979 whitespace_error,3980 whitespace_error ==1?"":"s",3981 whitespace_error ==1?"s":"");3982}39833984if(update_index) {3985if(write_cache(newfd, active_cache, active_nr) ||3986commit_locked_index(&lock_file))3987die("Unable to write new index file");3988}39893990return!!errs;3991}