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; 155unsigned free_patch:1, 156 rejected:1; 157int size; 158int linenr; 159struct fragment *next; 160}; 161 162/* 163 * When dealing with a binary patch, we reuse "leading" field 164 * to store the type of the binary hunk, either deflated "delta" 165 * or deflated "literal". 166 */ 167#define binary_patch_method leading 168#define BINARY_DELTA_DEFLATED 1 169#define BINARY_LITERAL_DEFLATED 2 170 171/* 172 * This represents a "patch" to a file, both metainfo changes 173 * such as creation/deletion, filemode and content changes represented 174 * as a series of fragments. 175 */ 176struct patch { 177char*new_name, *old_name, *def_name; 178unsigned int old_mode, new_mode; 179int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 180int rejected; 181unsigned ws_rule; 182unsigned long deflate_origlen; 183int lines_added, lines_deleted; 184int score; 185unsigned int is_toplevel_relative:1; 186unsigned int inaccurate_eof:1; 187unsigned int is_binary:1; 188unsigned int is_copy:1; 189unsigned int is_rename:1; 190unsigned int recount:1; 191struct fragment *fragments; 192char*result; 193size_t resultsize; 194char old_sha1_prefix[41]; 195char new_sha1_prefix[41]; 196struct patch *next; 197}; 198 199static voidfree_patch(struct patch *patch) 200{ 201struct fragment *fragment = patch->fragments; 202 203while(fragment) { 204struct fragment *fragment_next = fragment->next; 205if(fragment->patch != NULL && fragment->free_patch) 206free((char*)fragment->patch); 207free(fragment); 208 fragment = fragment_next; 209} 210free(patch->def_name); 211free(patch->old_name); 212free(patch->new_name); 213free(patch); 214} 215 216static voidfree_patch_list(struct patch *list) 217{ 218while(list) { 219struct patch *next = list->next; 220free_patch(list); 221 list = next; 222} 223} 224 225/* 226 * A line in a file, len-bytes long (includes the terminating LF, 227 * except for an incomplete line at the end if the file ends with 228 * one), and its contents hashes to 'hash'. 229 */ 230struct line { 231size_t len; 232unsigned hash :24; 233unsigned flag :8; 234#define LINE_COMMON 1 235#define LINE_PATCHED 2 236}; 237 238/* 239 * This represents a "file", which is an array of "lines". 240 */ 241struct image { 242char*buf; 243size_t len; 244size_t nr; 245size_t alloc; 246struct line *line_allocated; 247struct line *line; 248}; 249 250/* 251 * Records filenames that have been touched, in order to handle 252 * the case where more than one patches touch the same file. 253 */ 254 255static struct string_list fn_table; 256 257static uint32_thash_line(const char*cp,size_t len) 258{ 259size_t i; 260uint32_t h; 261for(i =0, h =0; i < len; i++) { 262if(!isspace(cp[i])) { 263 h = h *3+ (cp[i] &0xff); 264} 265} 266return h; 267} 268 269/* 270 * Compare lines s1 of length n1 and s2 of length n2, ignoring 271 * whitespace difference. Returns 1 if they match, 0 otherwise 272 */ 273static intfuzzy_matchlines(const char*s1,size_t n1, 274const char*s2,size_t n2) 275{ 276const char*last1 = s1 + n1 -1; 277const char*last2 = s2 + n2 -1; 278int result =0; 279 280/* ignore line endings */ 281while((*last1 =='\r') || (*last1 =='\n')) 282 last1--; 283while((*last2 =='\r') || (*last2 =='\n')) 284 last2--; 285 286/* skip leading whitespace */ 287while(isspace(*s1) && (s1 <= last1)) 288 s1++; 289while(isspace(*s2) && (s2 <= last2)) 290 s2++; 291/* early return if both lines are empty */ 292if((s1 > last1) && (s2 > last2)) 293return1; 294while(!result) { 295 result = *s1++ - *s2++; 296/* 297 * Skip whitespace inside. We check for whitespace on 298 * both buffers because we don't want "a b" to match 299 * "ab" 300 */ 301if(isspace(*s1) &&isspace(*s2)) { 302while(isspace(*s1) && s1 <= last1) 303 s1++; 304while(isspace(*s2) && s2 <= last2) 305 s2++; 306} 307/* 308 * If we reached the end on one side only, 309 * lines don't match 310 */ 311if( 312((s2 > last2) && (s1 <= last1)) || 313((s1 > last1) && (s2 <= last2))) 314return0; 315if((s1 > last1) && (s2 > last2)) 316break; 317} 318 319return!result; 320} 321 322static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 323{ 324ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 325 img->line_allocated[img->nr].len = len; 326 img->line_allocated[img->nr].hash =hash_line(bol, len); 327 img->line_allocated[img->nr].flag = flag; 328 img->nr++; 329} 330 331static voidprepare_image(struct image *image,char*buf,size_t len, 332int prepare_linetable) 333{ 334const char*cp, *ep; 335 336memset(image,0,sizeof(*image)); 337 image->buf = buf; 338 image->len = len; 339 340if(!prepare_linetable) 341return; 342 343 ep = image->buf + image->len; 344 cp = image->buf; 345while(cp < ep) { 346const char*next; 347for(next = cp; next < ep && *next !='\n'; next++) 348; 349if(next < ep) 350 next++; 351add_line_info(image, cp, next - cp,0); 352 cp = next; 353} 354 image->line = image->line_allocated; 355} 356 357static voidclear_image(struct image *image) 358{ 359free(image->buf); 360 image->buf = NULL; 361 image->len =0; 362} 363 364static voidsay_patch_name(FILE*output,const char*pre, 365struct patch *patch,const char*post) 366{ 367fputs(pre, output); 368if(patch->old_name && patch->new_name && 369strcmp(patch->old_name, patch->new_name)) { 370quote_c_style(patch->old_name, NULL, output,0); 371fputs(" => ", output); 372quote_c_style(patch->new_name, NULL, output,0); 373}else{ 374const char*n = patch->new_name; 375if(!n) 376 n = patch->old_name; 377quote_c_style(n, NULL, output,0); 378} 379fputs(post, output); 380} 381 382#define CHUNKSIZE (8192) 383#define SLOP (16) 384 385static voidread_patch_file(struct strbuf *sb,int fd) 386{ 387if(strbuf_read(sb, fd,0) <0) 388die_errno("git apply: failed to read"); 389 390/* 391 * Make sure that we have some slop in the buffer 392 * so that we can do speculative "memcmp" etc, and 393 * see to it that it is NUL-filled. 394 */ 395strbuf_grow(sb, SLOP); 396memset(sb->buf + sb->len,0, SLOP); 397} 398 399static unsigned longlinelen(const char*buffer,unsigned long size) 400{ 401unsigned long len =0; 402while(size--) { 403 len++; 404if(*buffer++ =='\n') 405break; 406} 407return len; 408} 409 410static intis_dev_null(const char*str) 411{ 412return!memcmp("/dev/null", str,9) &&isspace(str[9]); 413} 414 415#define TERM_SPACE 1 416#define TERM_TAB 2 417 418static intname_terminate(const char*name,int namelen,int c,int terminate) 419{ 420if(c ==' '&& !(terminate & TERM_SPACE)) 421return0; 422if(c =='\t'&& !(terminate & TERM_TAB)) 423return0; 424 425return1; 426} 427 428/* remove double slashes to make --index work with such filenames */ 429static char*squash_slash(char*name) 430{ 431int i =0, j =0; 432 433if(!name) 434return NULL; 435 436while(name[i]) { 437if((name[j++] = name[i++]) =='/') 438while(name[i] =='/') 439 i++; 440} 441 name[j] ='\0'; 442return name; 443} 444 445static char*find_name_gnu(const char*line,const char*def,int p_value) 446{ 447struct strbuf name = STRBUF_INIT; 448char*cp; 449 450/* 451 * Proposed "new-style" GNU patch/diff format; see 452 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2 453 */ 454if(unquote_c_style(&name, line, NULL)) { 455strbuf_release(&name); 456return NULL; 457} 458 459for(cp = name.buf; p_value; p_value--) { 460 cp =strchr(cp,'/'); 461if(!cp) { 462strbuf_release(&name); 463return NULL; 464} 465 cp++; 466} 467 468strbuf_remove(&name,0, cp - name.buf); 469if(root) 470strbuf_insert(&name,0, root, root_len); 471returnsquash_slash(strbuf_detach(&name, NULL)); 472} 473 474static size_tsane_tz_len(const char*line,size_t len) 475{ 476const char*tz, *p; 477 478if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 479return0; 480 tz = line + len -strlen(" +0500"); 481 482if(tz[1] !='+'&& tz[1] !='-') 483return0; 484 485for(p = tz +2; p != line + len; p++) 486if(!isdigit(*p)) 487return0; 488 489return line + len - tz; 490} 491 492static size_ttz_with_colon_len(const char*line,size_t len) 493{ 494const char*tz, *p; 495 496if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 497return0; 498 tz = line + len -strlen(" +08:00"); 499 500if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 501return0; 502 p = tz +2; 503if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 504!isdigit(*p++) || !isdigit(*p++)) 505return0; 506 507return line + len - tz; 508} 509 510static size_tdate_len(const char*line,size_t len) 511{ 512const char*date, *p; 513 514if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 515return0; 516 p = date = line + len -strlen("72-02-05"); 517 518if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 519!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 520!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 521return0; 522 523if(date - line >=strlen("19") && 524isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 525 date -=strlen("19"); 526 527return line + len - date; 528} 529 530static size_tshort_time_len(const char*line,size_t len) 531{ 532const char*time, *p; 533 534if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 535return0; 536 p = time = line + len -strlen(" 07:01:32"); 537 538/* Permit 1-digit hours? */ 539if(*p++ !=' '|| 540!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 541!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 542!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 543return0; 544 545return line + len - time; 546} 547 548static size_tfractional_time_len(const char*line,size_t len) 549{ 550const char*p; 551size_t n; 552 553/* Expected format: 19:41:17.620000023 */ 554if(!len || !isdigit(line[len -1])) 555return0; 556 p = line + len -1; 557 558/* Fractional seconds. */ 559while(p > line &&isdigit(*p)) 560 p--; 561if(*p !='.') 562return0; 563 564/* Hours, minutes, and whole seconds. */ 565 n =short_time_len(line, p - line); 566if(!n) 567return0; 568 569return line + len - p + n; 570} 571 572static size_ttrailing_spaces_len(const char*line,size_t len) 573{ 574const char*p; 575 576/* Expected format: ' ' x (1 or more) */ 577if(!len || line[len -1] !=' ') 578return0; 579 580 p = line + len; 581while(p != line) { 582 p--; 583if(*p !=' ') 584return line + len - (p +1); 585} 586 587/* All spaces! */ 588return len; 589} 590 591static size_tdiff_timestamp_len(const char*line,size_t len) 592{ 593const char*end = line + len; 594size_t n; 595 596/* 597 * Posix: 2010-07-05 19:41:17 598 * GNU: 2010-07-05 19:41:17.620000023 -0500 599 */ 600 601if(!isdigit(end[-1])) 602return0; 603 604 n =sane_tz_len(line, end - line); 605if(!n) 606 n =tz_with_colon_len(line, end - line); 607 end -= n; 608 609 n =short_time_len(line, end - line); 610if(!n) 611 n =fractional_time_len(line, end - line); 612 end -= n; 613 614 n =date_len(line, end - line); 615if(!n)/* No date. Too bad. */ 616return0; 617 end -= n; 618 619if(end == line)/* No space before date. */ 620return0; 621if(end[-1] =='\t') {/* Success! */ 622 end--; 623return line + len - end; 624} 625if(end[-1] !=' ')/* No space before date. */ 626return0; 627 628/* Whitespace damage. */ 629 end -=trailing_spaces_len(line, end - line); 630return line + len - end; 631} 632 633static char*null_strdup(const char*s) 634{ 635return s ?xstrdup(s) : NULL; 636} 637 638static char*find_name_common(const char*line,const char*def, 639int p_value,const char*end,int terminate) 640{ 641int len; 642const char*start = NULL; 643 644if(p_value ==0) 645 start = line; 646while(line != end) { 647char c = *line; 648 649if(!end &&isspace(c)) { 650if(c =='\n') 651break; 652if(name_terminate(start, line-start, c, terminate)) 653break; 654} 655 line++; 656if(c =='/'&& !--p_value) 657 start = line; 658} 659if(!start) 660returnsquash_slash(null_strdup(def)); 661 len = line - start; 662if(!len) 663returnsquash_slash(null_strdup(def)); 664 665/* 666 * Generally we prefer the shorter name, especially 667 * if the other one is just a variation of that with 668 * something else tacked on to the end (ie "file.orig" 669 * or "file~"). 670 */ 671if(def) { 672int deflen =strlen(def); 673if(deflen < len && !strncmp(start, def, deflen)) 674returnsquash_slash(xstrdup(def)); 675} 676 677if(root) { 678char*ret =xmalloc(root_len + len +1); 679strcpy(ret, root); 680memcpy(ret + root_len, start, len); 681 ret[root_len + len] ='\0'; 682returnsquash_slash(ret); 683} 684 685returnsquash_slash(xmemdupz(start, len)); 686} 687 688static char*find_name(const char*line,char*def,int p_value,int terminate) 689{ 690if(*line =='"') { 691char*name =find_name_gnu(line, def, p_value); 692if(name) 693return name; 694} 695 696returnfind_name_common(line, def, p_value, NULL, terminate); 697} 698 699static char*find_name_traditional(const char*line,char*def,int p_value) 700{ 701size_t len =strlen(line); 702size_t date_len; 703 704if(*line =='"') { 705char*name =find_name_gnu(line, def, p_value); 706if(name) 707return name; 708} 709 710 len =strchrnul(line,'\n') - line; 711 date_len =diff_timestamp_len(line, len); 712if(!date_len) 713returnfind_name_common(line, def, p_value, NULL, TERM_TAB); 714 len -= date_len; 715 716returnfind_name_common(line, def, p_value, line + len,0); 717} 718 719static intcount_slashes(const char*cp) 720{ 721int cnt =0; 722char ch; 723 724while((ch = *cp++)) 725if(ch =='/') 726 cnt++; 727return cnt; 728} 729 730/* 731 * Given the string after "--- " or "+++ ", guess the appropriate 732 * p_value for the given patch. 733 */ 734static intguess_p_value(const char*nameline) 735{ 736char*name, *cp; 737int val = -1; 738 739if(is_dev_null(nameline)) 740return-1; 741 name =find_name_traditional(nameline, NULL,0); 742if(!name) 743return-1; 744 cp =strchr(name,'/'); 745if(!cp) 746 val =0; 747else if(prefix) { 748/* 749 * Does it begin with "a/$our-prefix" and such? Then this is 750 * very likely to apply to our directory. 751 */ 752if(!strncmp(name, prefix, prefix_length)) 753 val =count_slashes(prefix); 754else{ 755 cp++; 756if(!strncmp(cp, prefix, prefix_length)) 757 val =count_slashes(prefix) +1; 758} 759} 760free(name); 761return val; 762} 763 764/* 765 * Does the ---/+++ line has the POSIX timestamp after the last HT? 766 * GNU diff puts epoch there to signal a creation/deletion event. Is 767 * this such a timestamp? 768 */ 769static inthas_epoch_timestamp(const char*nameline) 770{ 771/* 772 * We are only interested in epoch timestamp; any non-zero 773 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 774 * For the same reason, the date must be either 1969-12-31 or 775 * 1970-01-01, and the seconds part must be "00". 776 */ 777const char stamp_regexp[] = 778"^(1969-12-31|1970-01-01)" 779" " 780"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 781" " 782"([-+][0-2][0-9]:?[0-5][0-9])\n"; 783const char*timestamp = NULL, *cp, *colon; 784static regex_t *stamp; 785 regmatch_t m[10]; 786int zoneoffset; 787int hourminute; 788int status; 789 790for(cp = nameline; *cp !='\n'; cp++) { 791if(*cp =='\t') 792 timestamp = cp +1; 793} 794if(!timestamp) 795return0; 796if(!stamp) { 797 stamp =xmalloc(sizeof(*stamp)); 798if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 799warning("Cannot prepare timestamp regexp%s", 800 stamp_regexp); 801return0; 802} 803} 804 805 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 806if(status) { 807if(status != REG_NOMATCH) 808warning("regexec returned%dfor input:%s", 809 status, timestamp); 810return0; 811} 812 813 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 814if(*colon ==':') 815 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 816else 817 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 818if(timestamp[m[3].rm_so] =='-') 819 zoneoffset = -zoneoffset; 820 821/* 822 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 823 * (west of GMT) or 1970-01-01 (east of GMT) 824 */ 825if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 826(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 827return0; 828 829 hourminute = (strtol(timestamp +11, NULL,10) *60+ 830strtol(timestamp +14, NULL,10) - 831 zoneoffset); 832 833return((zoneoffset <0&& hourminute ==1440) || 834(0<= zoneoffset && !hourminute)); 835} 836 837/* 838 * Get the name etc info from the ---/+++ lines of a traditional patch header 839 * 840 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 841 * files, we can happily check the index for a match, but for creating a 842 * new file we should try to match whatever "patch" does. I have no idea. 843 */ 844static voidparse_traditional_patch(const char*first,const char*second,struct patch *patch) 845{ 846char*name; 847 848 first +=4;/* skip "--- " */ 849 second +=4;/* skip "+++ " */ 850if(!p_value_known) { 851int p, q; 852 p =guess_p_value(first); 853 q =guess_p_value(second); 854if(p <0) p = q; 855if(0<= p && p == q) { 856 p_value = p; 857 p_value_known =1; 858} 859} 860if(is_dev_null(first)) { 861 patch->is_new =1; 862 patch->is_delete =0; 863 name =find_name_traditional(second, NULL, p_value); 864 patch->new_name = name; 865}else if(is_dev_null(second)) { 866 patch->is_new =0; 867 patch->is_delete =1; 868 name =find_name_traditional(first, NULL, p_value); 869 patch->old_name = name; 870}else{ 871char*first_name; 872 first_name =find_name_traditional(first, NULL, p_value); 873 name =find_name_traditional(second, first_name, p_value); 874free(first_name); 875if(has_epoch_timestamp(first)) { 876 patch->is_new =1; 877 patch->is_delete =0; 878 patch->new_name = name; 879}else if(has_epoch_timestamp(second)) { 880 patch->is_new =0; 881 patch->is_delete =1; 882 patch->old_name = name; 883}else{ 884 patch->old_name = name; 885 patch->new_name =xstrdup(name); 886} 887} 888if(!name) 889die("unable to find filename in patch at line%d", linenr); 890} 891 892static intgitdiff_hdrend(const char*line,struct patch *patch) 893{ 894return-1; 895} 896 897/* 898 * We're anal about diff header consistency, to make 899 * sure that we don't end up having strange ambiguous 900 * patches floating around. 901 * 902 * As a result, gitdiff_{old|new}name() will check 903 * their names against any previous information, just 904 * to make sure.. 905 */ 906static char*gitdiff_verify_name(const char*line,int isnull,char*orig_name,const char*oldnew) 907{ 908if(!orig_name && !isnull) 909returnfind_name(line, NULL, p_value, TERM_TAB); 910 911if(orig_name) { 912int len; 913const char*name; 914char*another; 915 name = orig_name; 916 len =strlen(name); 917if(isnull) 918die("git apply: bad git-diff - expected /dev/null, got%son line%d", name, linenr); 919 another =find_name(line, NULL, p_value, TERM_TAB); 920if(!another ||memcmp(another, name, len +1)) 921die("git apply: bad git-diff - inconsistent%sfilename on line%d", oldnew, linenr); 922free(another); 923return orig_name; 924} 925else{ 926/* expect "/dev/null" */ 927if(memcmp("/dev/null", line,9) || line[9] !='\n') 928die("git apply: bad git-diff - expected /dev/null on line%d", linenr); 929return NULL; 930} 931} 932 933static intgitdiff_oldname(const char*line,struct patch *patch) 934{ 935char*orig = patch->old_name; 936 patch->old_name =gitdiff_verify_name(line, patch->is_new, patch->old_name,"old"); 937if(orig != patch->old_name) 938free(orig); 939return0; 940} 941 942static intgitdiff_newname(const char*line,struct patch *patch) 943{ 944char*orig = patch->new_name; 945 patch->new_name =gitdiff_verify_name(line, patch->is_delete, patch->new_name,"new"); 946if(orig != patch->new_name) 947free(orig); 948return0; 949} 950 951static intgitdiff_oldmode(const char*line,struct patch *patch) 952{ 953 patch->old_mode =strtoul(line, NULL,8); 954return0; 955} 956 957static intgitdiff_newmode(const char*line,struct patch *patch) 958{ 959 patch->new_mode =strtoul(line, NULL,8); 960return0; 961} 962 963static intgitdiff_delete(const char*line,struct patch *patch) 964{ 965 patch->is_delete =1; 966free(patch->old_name); 967 patch->old_name =null_strdup(patch->def_name); 968returngitdiff_oldmode(line, patch); 969} 970 971static intgitdiff_newfile(const char*line,struct patch *patch) 972{ 973 patch->is_new =1; 974free(patch->new_name); 975 patch->new_name =null_strdup(patch->def_name); 976returngitdiff_newmode(line, patch); 977} 978 979static intgitdiff_copysrc(const char*line,struct patch *patch) 980{ 981 patch->is_copy =1; 982free(patch->old_name); 983 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0); 984return0; 985} 986 987static intgitdiff_copydst(const char*line,struct patch *patch) 988{ 989 patch->is_copy =1; 990free(patch->new_name); 991 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0); 992return0; 993} 994 995static intgitdiff_renamesrc(const char*line,struct patch *patch) 996{ 997 patch->is_rename =1; 998free(patch->old_name); 999 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0);1000return0;1001}10021003static intgitdiff_renamedst(const char*line,struct patch *patch)1004{1005 patch->is_rename =1;1006free(patch->new_name);1007 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0);1008return0;1009}10101011static intgitdiff_similarity(const char*line,struct patch *patch)1012{1013if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX)1014 patch->score =0;1015return0;1016}10171018static intgitdiff_dissimilarity(const char*line,struct patch *patch)1019{1020if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX)1021 patch->score =0;1022return0;1023}10241025static intgitdiff_index(const char*line,struct patch *patch)1026{1027/*1028 * index line is N hexadecimal, "..", N hexadecimal,1029 * and optional space with octal mode.1030 */1031const char*ptr, *eol;1032int len;10331034 ptr =strchr(line,'.');1035if(!ptr || ptr[1] !='.'||40< ptr - line)1036return0;1037 len = ptr - line;1038memcpy(patch->old_sha1_prefix, line, len);1039 patch->old_sha1_prefix[len] =0;10401041 line = ptr +2;1042 ptr =strchr(line,' ');1043 eol =strchr(line,'\n');10441045if(!ptr || eol < ptr)1046 ptr = eol;1047 len = ptr - line;10481049if(40< len)1050return0;1051memcpy(patch->new_sha1_prefix, line, len);1052 patch->new_sha1_prefix[len] =0;1053if(*ptr ==' ')1054 patch->old_mode =strtoul(ptr+1, NULL,8);1055return0;1056}10571058/*1059 * This is normal for a diff that doesn't change anything: we'll fall through1060 * into the next diff. Tell the parser to break out.1061 */1062static intgitdiff_unrecognized(const char*line,struct patch *patch)1063{1064return-1;1065}10661067static const char*stop_at_slash(const char*line,int llen)1068{1069int nslash = p_value;1070int i;10711072for(i =0; i < llen; i++) {1073int ch = line[i];1074if(ch =='/'&& --nslash <=0)1075return&line[i];1076}1077return NULL;1078}10791080/*1081 * This is to extract the same name that appears on "diff --git"1082 * line. We do not find and return anything if it is a rename1083 * patch, and it is OK because we will find the name elsewhere.1084 * We need to reliably find name only when it is mode-change only,1085 * creation or deletion of an empty file. In any of these cases,1086 * both sides are the same name under a/ and b/ respectively.1087 */1088static char*git_header_name(char*line,int llen)1089{1090const char*name;1091const char*second = NULL;1092size_t len, line_len;10931094 line +=strlen("diff --git ");1095 llen -=strlen("diff --git ");10961097if(*line =='"') {1098const char*cp;1099struct strbuf first = STRBUF_INIT;1100struct strbuf sp = STRBUF_INIT;11011102if(unquote_c_style(&first, line, &second))1103goto free_and_fail1;11041105/* advance to the first slash */1106 cp =stop_at_slash(first.buf, first.len);1107/* we do not accept absolute paths */1108if(!cp || cp == first.buf)1109goto free_and_fail1;1110strbuf_remove(&first,0, cp +1- first.buf);11111112/*1113 * second points at one past closing dq of name.1114 * find the second name.1115 */1116while((second < line + llen) &&isspace(*second))1117 second++;11181119if(line + llen <= second)1120goto free_and_fail1;1121if(*second =='"') {1122if(unquote_c_style(&sp, second, NULL))1123goto free_and_fail1;1124 cp =stop_at_slash(sp.buf, sp.len);1125if(!cp || cp == sp.buf)1126goto free_and_fail1;1127/* They must match, otherwise ignore */1128if(strcmp(cp +1, first.buf))1129goto free_and_fail1;1130strbuf_release(&sp);1131returnstrbuf_detach(&first, NULL);1132}11331134/* unquoted second */1135 cp =stop_at_slash(second, line + llen - second);1136if(!cp || cp == second)1137goto free_and_fail1;1138 cp++;1139if(line + llen - cp != first.len +1||1140memcmp(first.buf, cp, first.len))1141goto free_and_fail1;1142returnstrbuf_detach(&first, NULL);11431144 free_and_fail1:1145strbuf_release(&first);1146strbuf_release(&sp);1147return NULL;1148}11491150/* unquoted first name */1151 name =stop_at_slash(line, llen);1152if(!name || name == line)1153return NULL;1154 name++;11551156/*1157 * since the first name is unquoted, a dq if exists must be1158 * the beginning of the second name.1159 */1160for(second = name; second < line + llen; second++) {1161if(*second =='"') {1162struct strbuf sp = STRBUF_INIT;1163const char*np;11641165if(unquote_c_style(&sp, second, NULL))1166goto free_and_fail2;11671168 np =stop_at_slash(sp.buf, sp.len);1169if(!np || np == sp.buf)1170goto free_and_fail2;1171 np++;11721173 len = sp.buf + sp.len - np;1174if(len < second - name &&1175!strncmp(np, name, len) &&1176isspace(name[len])) {1177/* Good */1178strbuf_remove(&sp,0, np - sp.buf);1179returnstrbuf_detach(&sp, NULL);1180}11811182 free_and_fail2:1183strbuf_release(&sp);1184return NULL;1185}1186}11871188/*1189 * Accept a name only if it shows up twice, exactly the same1190 * form.1191 */1192 second =strchr(name,'\n');1193if(!second)1194return NULL;1195 line_len = second - name;1196for(len =0; ; len++) {1197switch(name[len]) {1198default:1199continue;1200case'\n':1201return NULL;1202case'\t':case' ':1203 second =stop_at_slash(name + len, line_len - len);1204if(!second)1205return NULL;1206 second++;1207if(second[len] =='\n'&& !strncmp(name, second, len)) {1208returnxmemdupz(name, len);1209}1210}1211}1212}12131214/* Verify that we recognize the lines following a git header */1215static intparse_git_header(char*line,int len,unsigned int size,struct patch *patch)1216{1217unsigned long offset;12181219/* A git diff has explicit new/delete information, so we don't guess */1220 patch->is_new =0;1221 patch->is_delete =0;12221223/*1224 * Some things may not have the old name in the1225 * rest of the headers anywhere (pure mode changes,1226 * or removing or adding empty files), so we get1227 * the default name from the header.1228 */1229 patch->def_name =git_header_name(line, len);1230if(patch->def_name && root) {1231char*s =xmalloc(root_len +strlen(patch->def_name) +1);1232strcpy(s, root);1233strcpy(s + root_len, patch->def_name);1234free(patch->def_name);1235 patch->def_name = s;1236}12371238 line += len;1239 size -= len;1240 linenr++;1241for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) {1242static const struct opentry {1243const char*str;1244int(*fn)(const char*,struct patch *);1245} optable[] = {1246{"@@ -", gitdiff_hdrend },1247{"--- ", gitdiff_oldname },1248{"+++ ", gitdiff_newname },1249{"old mode ", gitdiff_oldmode },1250{"new mode ", gitdiff_newmode },1251{"deleted file mode ", gitdiff_delete },1252{"new file mode ", gitdiff_newfile },1253{"copy from ", gitdiff_copysrc },1254{"copy to ", gitdiff_copydst },1255{"rename old ", gitdiff_renamesrc },1256{"rename new ", gitdiff_renamedst },1257{"rename from ", gitdiff_renamesrc },1258{"rename to ", gitdiff_renamedst },1259{"similarity index ", gitdiff_similarity },1260{"dissimilarity index ", gitdiff_dissimilarity },1261{"index ", gitdiff_index },1262{"", gitdiff_unrecognized },1263};1264int i;12651266 len =linelen(line, size);1267if(!len || line[len-1] !='\n')1268break;1269for(i =0; i <ARRAY_SIZE(optable); i++) {1270const struct opentry *p = optable + i;1271int oplen =strlen(p->str);1272if(len < oplen ||memcmp(p->str, line, oplen))1273continue;1274if(p->fn(line + oplen, patch) <0)1275return offset;1276break;1277}1278}12791280return offset;1281}12821283static intparse_num(const char*line,unsigned long*p)1284{1285char*ptr;12861287if(!isdigit(*line))1288return0;1289*p =strtoul(line, &ptr,10);1290return ptr - line;1291}12921293static intparse_range(const char*line,int len,int offset,const char*expect,1294unsigned long*p1,unsigned long*p2)1295{1296int digits, ex;12971298if(offset <0|| offset >= len)1299return-1;1300 line += offset;1301 len -= offset;13021303 digits =parse_num(line, p1);1304if(!digits)1305return-1;13061307 offset += digits;1308 line += digits;1309 len -= digits;13101311*p2 =1;1312if(*line ==',') {1313 digits =parse_num(line+1, p2);1314if(!digits)1315return-1;13161317 offset += digits+1;1318 line += digits+1;1319 len -= digits+1;1320}13211322 ex =strlen(expect);1323if(ex > len)1324return-1;1325if(memcmp(line, expect, ex))1326return-1;13271328return offset + ex;1329}13301331static voidrecount_diff(char*line,int size,struct fragment *fragment)1332{1333int oldlines =0, newlines =0, ret =0;13341335if(size <1) {1336warning("recount: ignore empty hunk");1337return;1338}13391340for(;;) {1341int len =linelen(line, size);1342 size -= len;1343 line += len;13441345if(size <1)1346break;13471348switch(*line) {1349case' ':case'\n':1350 newlines++;1351/* fall through */1352case'-':1353 oldlines++;1354continue;1355case'+':1356 newlines++;1357continue;1358case'\\':1359continue;1360case'@':1361 ret = size <3||prefixcmp(line,"@@ ");1362break;1363case'd':1364 ret = size <5||prefixcmp(line,"diff ");1365break;1366default:1367 ret = -1;1368break;1369}1370if(ret) {1371warning("recount: unexpected line: %.*s",1372(int)linelen(line, size), line);1373return;1374}1375break;1376}1377 fragment->oldlines = oldlines;1378 fragment->newlines = newlines;1379}13801381/*1382 * Parse a unified diff fragment header of the1383 * form "@@ -a,b +c,d @@"1384 */1385static intparse_fragment_header(char*line,int len,struct fragment *fragment)1386{1387int offset;13881389if(!len || line[len-1] !='\n')1390return-1;13911392/* Figure out the number of lines in a fragment */1393 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1394 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);13951396return offset;1397}13981399static intfind_header(char*line,unsigned long size,int*hdrsize,struct patch *patch)1400{1401unsigned long offset, len;14021403 patch->is_toplevel_relative =0;1404 patch->is_rename = patch->is_copy =0;1405 patch->is_new = patch->is_delete = -1;1406 patch->old_mode = patch->new_mode =0;1407 patch->old_name = patch->new_name = NULL;1408for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) {1409unsigned long nextlen;14101411 len =linelen(line, size);1412if(!len)1413break;14141415/* Testing this early allows us to take a few shortcuts.. */1416if(len <6)1417continue;14181419/*1420 * Make sure we don't find any unconnected patch fragments.1421 * That's a sign that we didn't find a header, and that a1422 * patch has become corrupted/broken up.1423 */1424if(!memcmp("@@ -", line,4)) {1425struct fragment dummy;1426if(parse_fragment_header(line, len, &dummy) <0)1427continue;1428die("patch fragment without header at line%d: %.*s",1429 linenr, (int)len-1, line);1430}14311432if(size < len +6)1433break;14341435/*1436 * Git patch? It might not have a real patch, just a rename1437 * or mode change, so we handle that specially1438 */1439if(!memcmp("diff --git ", line,11)) {1440int git_hdr_len =parse_git_header(line, len, size, patch);1441if(git_hdr_len <= len)1442continue;1443if(!patch->old_name && !patch->new_name) {1444if(!patch->def_name)1445die("git diff header lacks filename information when removing "1446"%dleading pathname components (line%d)", p_value, linenr);1447 patch->old_name =xstrdup(patch->def_name);1448 patch->new_name =xstrdup(patch->def_name);1449}1450if(!patch->is_delete && !patch->new_name)1451die("git diff header lacks filename information "1452"(line%d)", linenr);1453 patch->is_toplevel_relative =1;1454*hdrsize = git_hdr_len;1455return offset;1456}14571458/* --- followed by +++ ? */1459if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1460continue;14611462/*1463 * We only accept unified patches, so we want it to1464 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1465 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1466 */1467 nextlen =linelen(line + len, size - len);1468if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1469continue;14701471/* Ok, we'll consider it a patch */1472parse_traditional_patch(line, line+len, patch);1473*hdrsize = len + nextlen;1474 linenr +=2;1475return offset;1476}1477return-1;1478}14791480static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1481{1482char*err;14831484if(!result)1485return;14861487 whitespace_error++;1488if(squelch_whitespace_errors &&1489 squelch_whitespace_errors < whitespace_error)1490return;14911492 err =whitespace_error_string(result);1493fprintf(stderr,"%s:%d:%s.\n%.*s\n",1494 patch_input_file, linenr, err, len, line);1495free(err);1496}14971498static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1499{1500unsigned result =ws_check(line +1, len -1, ws_rule);15011502record_ws_error(result, line +1, len -2, linenr);1503}15041505/*1506 * Parse a unified diff. Note that this really needs to parse each1507 * fragment separately, since the only way to know the difference1508 * between a "---" that is part of a patch, and a "---" that starts1509 * the next patch is to look at the line counts..1510 */1511static intparse_fragment(char*line,unsigned long size,1512struct patch *patch,struct fragment *fragment)1513{1514int added, deleted;1515int len =linelen(line, size), offset;1516unsigned long oldlines, newlines;1517unsigned long leading, trailing;15181519 offset =parse_fragment_header(line, len, fragment);1520if(offset <0)1521return-1;1522if(offset >0&& patch->recount)1523recount_diff(line + offset, size - offset, fragment);1524 oldlines = fragment->oldlines;1525 newlines = fragment->newlines;1526 leading =0;1527 trailing =0;15281529/* Parse the thing.. */1530 line += len;1531 size -= len;1532 linenr++;1533 added = deleted =0;1534for(offset = len;15350< size;1536 offset += len, size -= len, line += len, linenr++) {1537if(!oldlines && !newlines)1538break;1539 len =linelen(line, size);1540if(!len || line[len-1] !='\n')1541return-1;1542switch(*line) {1543default:1544return-1;1545case'\n':/* newer GNU diff, an empty context line */1546case' ':1547 oldlines--;1548 newlines--;1549if(!deleted && !added)1550 leading++;1551 trailing++;1552break;1553case'-':1554if(apply_in_reverse &&1555 ws_error_action != nowarn_ws_error)1556check_whitespace(line, len, patch->ws_rule);1557 deleted++;1558 oldlines--;1559 trailing =0;1560break;1561case'+':1562if(!apply_in_reverse &&1563 ws_error_action != nowarn_ws_error)1564check_whitespace(line, len, patch->ws_rule);1565 added++;1566 newlines--;1567 trailing =0;1568break;15691570/*1571 * We allow "\ No newline at end of file". Depending1572 * on locale settings when the patch was produced we1573 * don't know what this line looks like. The only1574 * thing we do know is that it begins with "\ ".1575 * Checking for 12 is just for sanity check -- any1576 * l10n of "\ No newline..." is at least that long.1577 */1578case'\\':1579if(len <12||memcmp(line,"\\",2))1580return-1;1581break;1582}1583}1584if(oldlines || newlines)1585return-1;1586 fragment->leading = leading;1587 fragment->trailing = trailing;15881589/*1590 * If a fragment ends with an incomplete line, we failed to include1591 * it in the above loop because we hit oldlines == newlines == 01592 * before seeing it.1593 */1594if(12< size && !memcmp(line,"\\",2))1595 offset +=linelen(line, size);15961597 patch->lines_added += added;1598 patch->lines_deleted += deleted;15991600if(0< patch->is_new && oldlines)1601returnerror("new file depends on old contents");1602if(0< patch->is_delete && newlines)1603returnerror("deleted file still has contents");1604return offset;1605}16061607static intparse_single_patch(char*line,unsigned long size,struct patch *patch)1608{1609unsigned long offset =0;1610unsigned long oldlines =0, newlines =0, context =0;1611struct fragment **fragp = &patch->fragments;16121613while(size >4&& !memcmp(line,"@@ -",4)) {1614struct fragment *fragment;1615int len;16161617 fragment =xcalloc(1,sizeof(*fragment));1618 fragment->linenr = linenr;1619 len =parse_fragment(line, size, patch, fragment);1620if(len <=0)1621die("corrupt patch at line%d", linenr);1622 fragment->patch = line;1623 fragment->size = len;1624 oldlines += fragment->oldlines;1625 newlines += fragment->newlines;1626 context += fragment->leading + fragment->trailing;16271628*fragp = fragment;1629 fragp = &fragment->next;16301631 offset += len;1632 line += len;1633 size -= len;1634}16351636/*1637 * If something was removed (i.e. we have old-lines) it cannot1638 * be creation, and if something was added it cannot be1639 * deletion. However, the reverse is not true; --unified=01640 * patches that only add are not necessarily creation even1641 * though they do not have any old lines, and ones that only1642 * delete are not necessarily deletion.1643 *1644 * Unfortunately, a real creation/deletion patch do _not_ have1645 * any context line by definition, so we cannot safely tell it1646 * apart with --unified=0 insanity. At least if the patch has1647 * more than one hunk it is not creation or deletion.1648 */1649if(patch->is_new <0&&1650(oldlines || (patch->fragments && patch->fragments->next)))1651 patch->is_new =0;1652if(patch->is_delete <0&&1653(newlines || (patch->fragments && patch->fragments->next)))1654 patch->is_delete =0;16551656if(0< patch->is_new && oldlines)1657die("new file%sdepends on old contents", patch->new_name);1658if(0< patch->is_delete && newlines)1659die("deleted file%sstill has contents", patch->old_name);1660if(!patch->is_delete && !newlines && context)1661fprintf(stderr,"** warning: file%sbecomes empty but "1662"is not deleted\n", patch->new_name);16631664return offset;1665}16661667staticinlineintmetadata_changes(struct patch *patch)1668{1669return patch->is_rename >0||1670 patch->is_copy >0||1671 patch->is_new >0||1672 patch->is_delete ||1673(patch->old_mode && patch->new_mode &&1674 patch->old_mode != patch->new_mode);1675}16761677static char*inflate_it(const void*data,unsigned long size,1678unsigned long inflated_size)1679{1680 git_zstream stream;1681void*out;1682int st;16831684memset(&stream,0,sizeof(stream));16851686 stream.next_in = (unsigned char*)data;1687 stream.avail_in = size;1688 stream.next_out = out =xmalloc(inflated_size);1689 stream.avail_out = inflated_size;1690git_inflate_init(&stream);1691 st =git_inflate(&stream, Z_FINISH);1692git_inflate_end(&stream);1693if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1694free(out);1695return NULL;1696}1697return out;1698}16991700static struct fragment *parse_binary_hunk(char**buf_p,1701unsigned long*sz_p,1702int*status_p,1703int*used_p)1704{1705/*1706 * Expect a line that begins with binary patch method ("literal"1707 * or "delta"), followed by the length of data before deflating.1708 * a sequence of 'length-byte' followed by base-85 encoded data1709 * should follow, terminated by a newline.1710 *1711 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1712 * and we would limit the patch line to 66 characters,1713 * so one line can fit up to 13 groups that would decode1714 * to 52 bytes max. The length byte 'A'-'Z' corresponds1715 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1716 */1717int llen, used;1718unsigned long size = *sz_p;1719char*buffer = *buf_p;1720int patch_method;1721unsigned long origlen;1722char*data = NULL;1723int hunk_size =0;1724struct fragment *frag;17251726 llen =linelen(buffer, size);1727 used = llen;17281729*status_p =0;17301731if(!prefixcmp(buffer,"delta ")) {1732 patch_method = BINARY_DELTA_DEFLATED;1733 origlen =strtoul(buffer +6, NULL,10);1734}1735else if(!prefixcmp(buffer,"literal ")) {1736 patch_method = BINARY_LITERAL_DEFLATED;1737 origlen =strtoul(buffer +8, NULL,10);1738}1739else1740return NULL;17411742 linenr++;1743 buffer += llen;1744while(1) {1745int byte_length, max_byte_length, newsize;1746 llen =linelen(buffer, size);1747 used += llen;1748 linenr++;1749if(llen ==1) {1750/* consume the blank line */1751 buffer++;1752 size--;1753break;1754}1755/*1756 * Minimum line is "A00000\n" which is 7-byte long,1757 * and the line length must be multiple of 5 plus 2.1758 */1759if((llen <7) || (llen-2) %5)1760goto corrupt;1761 max_byte_length = (llen -2) /5*4;1762 byte_length = *buffer;1763if('A'<= byte_length && byte_length <='Z')1764 byte_length = byte_length -'A'+1;1765else if('a'<= byte_length && byte_length <='z')1766 byte_length = byte_length -'a'+27;1767else1768goto corrupt;1769/* if the input length was not multiple of 4, we would1770 * have filler at the end but the filler should never1771 * exceed 3 bytes1772 */1773if(max_byte_length < byte_length ||1774 byte_length <= max_byte_length -4)1775goto corrupt;1776 newsize = hunk_size + byte_length;1777 data =xrealloc(data, newsize);1778if(decode_85(data + hunk_size, buffer +1, byte_length))1779goto corrupt;1780 hunk_size = newsize;1781 buffer += llen;1782 size -= llen;1783}17841785 frag =xcalloc(1,sizeof(*frag));1786 frag->patch =inflate_it(data, hunk_size, origlen);1787 frag->free_patch =1;1788if(!frag->patch)1789goto corrupt;1790free(data);1791 frag->size = origlen;1792*buf_p = buffer;1793*sz_p = size;1794*used_p = used;1795 frag->binary_patch_method = patch_method;1796return frag;17971798 corrupt:1799free(data);1800*status_p = -1;1801error("corrupt binary patch at line%d: %.*s",1802 linenr-1, llen-1, buffer);1803return NULL;1804}18051806static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1807{1808/*1809 * We have read "GIT binary patch\n"; what follows is a line1810 * that says the patch method (currently, either "literal" or1811 * "delta") and the length of data before deflating; a1812 * sequence of 'length-byte' followed by base-85 encoded data1813 * follows.1814 *1815 * When a binary patch is reversible, there is another binary1816 * hunk in the same format, starting with patch method (either1817 * "literal" or "delta") with the length of data, and a sequence1818 * of length-byte + base-85 encoded data, terminated with another1819 * empty line. This data, when applied to the postimage, produces1820 * the preimage.1821 */1822struct fragment *forward;1823struct fragment *reverse;1824int status;1825int used, used_1;18261827 forward =parse_binary_hunk(&buffer, &size, &status, &used);1828if(!forward && !status)1829/* there has to be one hunk (forward hunk) */1830returnerror("unrecognized binary patch at line%d", linenr-1);1831if(status)1832/* otherwise we already gave an error message */1833return status;18341835 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1836if(reverse)1837 used += used_1;1838else if(status) {1839/*1840 * Not having reverse hunk is not an error, but having1841 * a corrupt reverse hunk is.1842 */1843free((void*) forward->patch);1844free(forward);1845return status;1846}1847 forward->next = reverse;1848 patch->fragments = forward;1849 patch->is_binary =1;1850return used;1851}18521853static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1854{1855int hdrsize, patchsize;1856int offset =find_header(buffer, size, &hdrsize, patch);18571858if(offset <0)1859return offset;18601861 patch->ws_rule =whitespace_rule(patch->new_name1862? patch->new_name1863: patch->old_name);18641865 patchsize =parse_single_patch(buffer + offset + hdrsize,1866 size - offset - hdrsize, patch);18671868if(!patchsize) {1869static const char*binhdr[] = {1870"Binary files ",1871"Files ",1872 NULL,1873};1874static const char git_binary[] ="GIT binary patch\n";1875int i;1876int hd = hdrsize + offset;1877unsigned long llen =linelen(buffer + hd, size - hd);18781879if(llen ==sizeof(git_binary) -1&&1880!memcmp(git_binary, buffer + hd, llen)) {1881int used;1882 linenr++;1883 used =parse_binary(buffer + hd + llen,1884 size - hd - llen, patch);1885if(used)1886 patchsize = used + llen;1887else1888 patchsize =0;1889}1890else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1891for(i =0; binhdr[i]; i++) {1892int len =strlen(binhdr[i]);1893if(len < size - hd &&1894!memcmp(binhdr[i], buffer + hd, len)) {1895 linenr++;1896 patch->is_binary =1;1897 patchsize = llen;1898break;1899}1900}1901}19021903/* Empty patch cannot be applied if it is a text patch1904 * without metadata change. A binary patch appears1905 * empty to us here.1906 */1907if((apply || check) &&1908(!patch->is_binary && !metadata_changes(patch)))1909die("patch with only garbage at line%d", linenr);1910}19111912return offset + hdrsize + patchsize;1913}19141915#define swap(a,b) myswap((a),(b),sizeof(a))19161917#define myswap(a, b, size) do { \1918 unsigned char mytmp[size]; \1919 memcpy(mytmp, &a, size); \1920 memcpy(&a, &b, size); \1921 memcpy(&b, mytmp, size); \1922} while (0)19231924static voidreverse_patches(struct patch *p)1925{1926for(; p; p = p->next) {1927struct fragment *frag = p->fragments;19281929swap(p->new_name, p->old_name);1930swap(p->new_mode, p->old_mode);1931swap(p->is_new, p->is_delete);1932swap(p->lines_added, p->lines_deleted);1933swap(p->old_sha1_prefix, p->new_sha1_prefix);19341935for(; frag; frag = frag->next) {1936swap(frag->newpos, frag->oldpos);1937swap(frag->newlines, frag->oldlines);1938}1939}1940}19411942static const char pluses[] =1943"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";1944static const char minuses[]=1945"----------------------------------------------------------------------";19461947static voidshow_stats(struct patch *patch)1948{1949struct strbuf qname = STRBUF_INIT;1950char*cp = patch->new_name ? patch->new_name : patch->old_name;1951int max, add, del;19521953quote_c_style(cp, &qname, NULL,0);19541955/*1956 * "scale" the filename1957 */1958 max = max_len;1959if(max >50)1960 max =50;19611962if(qname.len > max) {1963 cp =strchr(qname.buf + qname.len +3- max,'/');1964if(!cp)1965 cp = qname.buf + qname.len +3- max;1966strbuf_splice(&qname,0, cp - qname.buf,"...",3);1967}19681969if(patch->is_binary) {1970printf(" %-*s | Bin\n", max, qname.buf);1971strbuf_release(&qname);1972return;1973}19741975printf(" %-*s |", max, qname.buf);1976strbuf_release(&qname);19771978/*1979 * scale the add/delete1980 */1981 max = max + max_change >70?70- max : max_change;1982 add = patch->lines_added;1983 del = patch->lines_deleted;19841985if(max_change >0) {1986int total = ((add + del) * max + max_change /2) / max_change;1987 add = (add * max + max_change /2) / max_change;1988 del = total - add;1989}1990printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,1991 add, pluses, del, minuses);1992}19931994static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)1995{1996switch(st->st_mode & S_IFMT) {1997case S_IFLNK:1998if(strbuf_readlink(buf, path, st->st_size) <0)1999returnerror("unable to read symlink%s", path);2000return0;2001case S_IFREG:2002if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2003returnerror("unable to open or read%s", path);2004convert_to_git(path, buf->buf, buf->len, buf,0);2005return0;2006default:2007return-1;2008}2009}20102011/*2012 * Update the preimage, and the common lines in postimage,2013 * from buffer buf of length len. If postlen is 0 the postimage2014 * is updated in place, otherwise it's updated on a new buffer2015 * of length postlen2016 */20172018static voidupdate_pre_post_images(struct image *preimage,2019struct image *postimage,2020char*buf,2021size_t len,size_t postlen)2022{2023int i, ctx;2024char*new, *old, *fixed;2025struct image fixed_preimage;20262027/*2028 * Update the preimage with whitespace fixes. Note that we2029 * are not losing preimage->buf -- apply_one_fragment() will2030 * free "oldlines".2031 */2032prepare_image(&fixed_preimage, buf, len,1);2033assert(fixed_preimage.nr == preimage->nr);2034for(i =0; i < preimage->nr; i++)2035 fixed_preimage.line[i].flag = preimage->line[i].flag;2036free(preimage->line_allocated);2037*preimage = fixed_preimage;20382039/*2040 * Adjust the common context lines in postimage. This can be2041 * done in-place when we are just doing whitespace fixing,2042 * which does not make the string grow, but needs a new buffer2043 * when ignoring whitespace causes the update, since in this case2044 * we could have e.g. tabs converted to multiple spaces.2045 * We trust the caller to tell us if the update can be done2046 * in place (postlen==0) or not.2047 */2048 old = postimage->buf;2049if(postlen)2050new= postimage->buf =xmalloc(postlen);2051else2052new= old;2053 fixed = preimage->buf;2054for(i = ctx =0; i < postimage->nr; i++) {2055size_t len = postimage->line[i].len;2056if(!(postimage->line[i].flag & LINE_COMMON)) {2057/* an added line -- no counterparts in preimage */2058memmove(new, old, len);2059 old += len;2060new+= len;2061continue;2062}20632064/* a common context -- skip it in the original postimage */2065 old += len;20662067/* and find the corresponding one in the fixed preimage */2068while(ctx < preimage->nr &&2069!(preimage->line[ctx].flag & LINE_COMMON)) {2070 fixed += preimage->line[ctx].len;2071 ctx++;2072}2073if(preimage->nr <= ctx)2074die("oops");20752076/* and copy it in, while fixing the line length */2077 len = preimage->line[ctx].len;2078memcpy(new, fixed, len);2079new+= len;2080 fixed += len;2081 postimage->line[i].len = len;2082 ctx++;2083}20842085/* Fix the length of the whole thing */2086 postimage->len =new- postimage->buf;2087}20882089static intmatch_fragment(struct image *img,2090struct image *preimage,2091struct image *postimage,2092unsigned longtry,2093int try_lno,2094unsigned ws_rule,2095int match_beginning,int match_end)2096{2097int i;2098char*fixed_buf, *buf, *orig, *target;2099struct strbuf fixed;2100size_t fixed_len;2101int preimage_limit;21022103if(preimage->nr + try_lno <= img->nr) {2104/*2105 * The hunk falls within the boundaries of img.2106 */2107 preimage_limit = preimage->nr;2108if(match_end && (preimage->nr + try_lno != img->nr))2109return0;2110}else if(ws_error_action == correct_ws_error &&2111(ws_rule & WS_BLANK_AT_EOF)) {2112/*2113 * This hunk extends beyond the end of img, and we are2114 * removing blank lines at the end of the file. This2115 * many lines from the beginning of the preimage must2116 * match with img, and the remainder of the preimage2117 * must be blank.2118 */2119 preimage_limit = img->nr - try_lno;2120}else{2121/*2122 * The hunk extends beyond the end of the img and2123 * we are not removing blanks at the end, so we2124 * should reject the hunk at this position.2125 */2126return0;2127}21282129if(match_beginning && try_lno)2130return0;21312132/* Quick hash check */2133for(i =0; i < preimage_limit; i++)2134if((img->line[try_lno + i].flag & LINE_PATCHED) ||2135(preimage->line[i].hash != img->line[try_lno + i].hash))2136return0;21372138if(preimage_limit == preimage->nr) {2139/*2140 * Do we have an exact match? If we were told to match2141 * at the end, size must be exactly at try+fragsize,2142 * otherwise try+fragsize must be still within the preimage,2143 * and either case, the old piece should match the preimage2144 * exactly.2145 */2146if((match_end2147? (try+ preimage->len == img->len)2148: (try+ preimage->len <= img->len)) &&2149!memcmp(img->buf +try, preimage->buf, preimage->len))2150return1;2151}else{2152/*2153 * The preimage extends beyond the end of img, so2154 * there cannot be an exact match.2155 *2156 * There must be one non-blank context line that match2157 * a line before the end of img.2158 */2159char*buf_end;21602161 buf = preimage->buf;2162 buf_end = buf;2163for(i =0; i < preimage_limit; i++)2164 buf_end += preimage->line[i].len;21652166for( ; buf < buf_end; buf++)2167if(!isspace(*buf))2168break;2169if(buf == buf_end)2170return0;2171}21722173/*2174 * No exact match. If we are ignoring whitespace, run a line-by-line2175 * fuzzy matching. We collect all the line length information because2176 * we need it to adjust whitespace if we match.2177 */2178if(ws_ignore_action == ignore_ws_change) {2179size_t imgoff =0;2180size_t preoff =0;2181size_t postlen = postimage->len;2182size_t extra_chars;2183char*preimage_eof;2184char*preimage_end;2185for(i =0; i < preimage_limit; i++) {2186size_t prelen = preimage->line[i].len;2187size_t imglen = img->line[try_lno+i].len;21882189if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2190 preimage->buf + preoff, prelen))2191return0;2192if(preimage->line[i].flag & LINE_COMMON)2193 postlen += imglen - prelen;2194 imgoff += imglen;2195 preoff += prelen;2196}21972198/*2199 * Ok, the preimage matches with whitespace fuzz.2200 *2201 * imgoff now holds the true length of the target that2202 * matches the preimage before the end of the file.2203 *2204 * Count the number of characters in the preimage that fall2205 * beyond the end of the file and make sure that all of them2206 * are whitespace characters. (This can only happen if2207 * we are removing blank lines at the end of the file.)2208 */2209 buf = preimage_eof = preimage->buf + preoff;2210for( ; i < preimage->nr; i++)2211 preoff += preimage->line[i].len;2212 preimage_end = preimage->buf + preoff;2213for( ; buf < preimage_end; buf++)2214if(!isspace(*buf))2215return0;22162217/*2218 * Update the preimage and the common postimage context2219 * lines to use the same whitespace as the target.2220 * If whitespace is missing in the target (i.e.2221 * if the preimage extends beyond the end of the file),2222 * use the whitespace from the preimage.2223 */2224 extra_chars = preimage_end - preimage_eof;2225strbuf_init(&fixed, imgoff + extra_chars);2226strbuf_add(&fixed, img->buf +try, imgoff);2227strbuf_add(&fixed, preimage_eof, extra_chars);2228 fixed_buf =strbuf_detach(&fixed, &fixed_len);2229update_pre_post_images(preimage, postimage,2230 fixed_buf, fixed_len, postlen);2231return1;2232}22332234if(ws_error_action != correct_ws_error)2235return0;22362237/*2238 * The hunk does not apply byte-by-byte, but the hash says2239 * it might with whitespace fuzz. We haven't been asked to2240 * ignore whitespace, we were asked to correct whitespace2241 * errors, so let's try matching after whitespace correction.2242 *2243 * The preimage may extend beyond the end of the file,2244 * but in this loop we will only handle the part of the2245 * preimage that falls within the file.2246 */2247strbuf_init(&fixed, preimage->len +1);2248 orig = preimage->buf;2249 target = img->buf +try;2250for(i =0; i < preimage_limit; i++) {2251size_t oldlen = preimage->line[i].len;2252size_t tgtlen = img->line[try_lno + i].len;2253size_t fixstart = fixed.len;2254struct strbuf tgtfix;2255int match;22562257/* Try fixing the line in the preimage */2258ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);22592260/* Try fixing the line in the target */2261strbuf_init(&tgtfix, tgtlen);2262ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);22632264/*2265 * If they match, either the preimage was based on2266 * a version before our tree fixed whitespace breakage,2267 * or we are lacking a whitespace-fix patch the tree2268 * the preimage was based on already had (i.e. target2269 * has whitespace breakage, the preimage doesn't).2270 * In either case, we are fixing the whitespace breakages2271 * so we might as well take the fix together with their2272 * real change.2273 */2274 match = (tgtfix.len == fixed.len - fixstart &&2275!memcmp(tgtfix.buf, fixed.buf + fixstart,2276 fixed.len - fixstart));22772278strbuf_release(&tgtfix);2279if(!match)2280goto unmatch_exit;22812282 orig += oldlen;2283 target += tgtlen;2284}228522862287/*2288 * Now handle the lines in the preimage that falls beyond the2289 * end of the file (if any). They will only match if they are2290 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2291 * false).2292 */2293for( ; i < preimage->nr; i++) {2294size_t fixstart = fixed.len;/* start of the fixed preimage */2295size_t oldlen = preimage->line[i].len;2296int j;22972298/* Try fixing the line in the preimage */2299ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);23002301for(j = fixstart; j < fixed.len; j++)2302if(!isspace(fixed.buf[j]))2303goto unmatch_exit;23042305 orig += oldlen;2306}23072308/*2309 * Yes, the preimage is based on an older version that still2310 * has whitespace breakages unfixed, and fixing them makes the2311 * hunk match. Update the context lines in the postimage.2312 */2313 fixed_buf =strbuf_detach(&fixed, &fixed_len);2314update_pre_post_images(preimage, postimage,2315 fixed_buf, fixed_len,0);2316return1;23172318 unmatch_exit:2319strbuf_release(&fixed);2320return0;2321}23222323static intfind_pos(struct image *img,2324struct image *preimage,2325struct image *postimage,2326int line,2327unsigned ws_rule,2328int match_beginning,int match_end)2329{2330int i;2331unsigned long backwards, forwards,try;2332int backwards_lno, forwards_lno, try_lno;23332334/*2335 * If match_beginning or match_end is specified, there is no2336 * point starting from a wrong line that will never match and2337 * wander around and wait for a match at the specified end.2338 */2339if(match_beginning)2340 line =0;2341else if(match_end)2342 line = img->nr - preimage->nr;23432344/*2345 * Because the comparison is unsigned, the following test2346 * will also take care of a negative line number that can2347 * result when match_end and preimage is larger than the target.2348 */2349if((size_t) line > img->nr)2350 line = img->nr;23512352try=0;2353for(i =0; i < line; i++)2354try+= img->line[i].len;23552356/*2357 * There's probably some smart way to do this, but I'll leave2358 * that to the smart and beautiful people. I'm simple and stupid.2359 */2360 backwards =try;2361 backwards_lno = line;2362 forwards =try;2363 forwards_lno = line;2364 try_lno = line;23652366for(i =0; ; i++) {2367if(match_fragment(img, preimage, postimage,2368try, try_lno, ws_rule,2369 match_beginning, match_end))2370return try_lno;23712372 again:2373if(backwards_lno ==0&& forwards_lno == img->nr)2374break;23752376if(i &1) {2377if(backwards_lno ==0) {2378 i++;2379goto again;2380}2381 backwards_lno--;2382 backwards -= img->line[backwards_lno].len;2383try= backwards;2384 try_lno = backwards_lno;2385}else{2386if(forwards_lno == img->nr) {2387 i++;2388goto again;2389}2390 forwards += img->line[forwards_lno].len;2391 forwards_lno++;2392try= forwards;2393 try_lno = forwards_lno;2394}23952396}2397return-1;2398}23992400static voidremove_first_line(struct image *img)2401{2402 img->buf += img->line[0].len;2403 img->len -= img->line[0].len;2404 img->line++;2405 img->nr--;2406}24072408static voidremove_last_line(struct image *img)2409{2410 img->len -= img->line[--img->nr].len;2411}24122413static voidupdate_image(struct image *img,2414int applied_pos,2415struct image *preimage,2416struct image *postimage)2417{2418/*2419 * remove the copy of preimage at offset in img2420 * and replace it with postimage2421 */2422int i, nr;2423size_t remove_count, insert_count, applied_at =0;2424char*result;2425int preimage_limit;24262427/*2428 * If we are removing blank lines at the end of img,2429 * the preimage may extend beyond the end.2430 * If that is the case, we must be careful only to2431 * remove the part of the preimage that falls within2432 * the boundaries of img. Initialize preimage_limit2433 * to the number of lines in the preimage that falls2434 * within the boundaries.2435 */2436 preimage_limit = preimage->nr;2437if(preimage_limit > img->nr - applied_pos)2438 preimage_limit = img->nr - applied_pos;24392440for(i =0; i < applied_pos; i++)2441 applied_at += img->line[i].len;24422443 remove_count =0;2444for(i =0; i < preimage_limit; i++)2445 remove_count += img->line[applied_pos + i].len;2446 insert_count = postimage->len;24472448/* Adjust the contents */2449 result =xmalloc(img->len + insert_count - remove_count +1);2450memcpy(result, img->buf, applied_at);2451memcpy(result + applied_at, postimage->buf, postimage->len);2452memcpy(result + applied_at + postimage->len,2453 img->buf + (applied_at + remove_count),2454 img->len - (applied_at + remove_count));2455free(img->buf);2456 img->buf = result;2457 img->len += insert_count - remove_count;2458 result[img->len] ='\0';24592460/* Adjust the line table */2461 nr = img->nr + postimage->nr - preimage_limit;2462if(preimage_limit < postimage->nr) {2463/*2464 * NOTE: this knows that we never call remove_first_line()2465 * on anything other than pre/post image.2466 */2467 img->line =xrealloc(img->line, nr *sizeof(*img->line));2468 img->line_allocated = img->line;2469}2470if(preimage_limit != postimage->nr)2471memmove(img->line + applied_pos + postimage->nr,2472 img->line + applied_pos + preimage_limit,2473(img->nr - (applied_pos + preimage_limit)) *2474sizeof(*img->line));2475memcpy(img->line + applied_pos,2476 postimage->line,2477 postimage->nr *sizeof(*img->line));2478if(!allow_overlap)2479for(i =0; i < postimage->nr; i++)2480 img->line[applied_pos + i].flag |= LINE_PATCHED;2481 img->nr = nr;2482}24832484static intapply_one_fragment(struct image *img,struct fragment *frag,2485int inaccurate_eof,unsigned ws_rule,2486int nth_fragment)2487{2488int match_beginning, match_end;2489const char*patch = frag->patch;2490int size = frag->size;2491char*old, *oldlines;2492struct strbuf newlines;2493int new_blank_lines_at_end =0;2494int found_new_blank_lines_at_end =0;2495int hunk_linenr = frag->linenr;2496unsigned long leading, trailing;2497int pos, applied_pos;2498struct image preimage;2499struct image postimage;25002501memset(&preimage,0,sizeof(preimage));2502memset(&postimage,0,sizeof(postimage));2503 oldlines =xmalloc(size);2504strbuf_init(&newlines, size);25052506 old = oldlines;2507while(size >0) {2508char first;2509int len =linelen(patch, size);2510int plen;2511int added_blank_line =0;2512int is_blank_context =0;2513size_t start;25142515if(!len)2516break;25172518/*2519 * "plen" is how much of the line we should use for2520 * the actual patch data. Normally we just remove the2521 * first character on the line, but if the line is2522 * followed by "\ No newline", then we also remove the2523 * last one (which is the newline, of course).2524 */2525 plen = len -1;2526if(len < size && patch[len] =='\\')2527 plen--;2528 first = *patch;2529if(apply_in_reverse) {2530if(first =='-')2531 first ='+';2532else if(first =='+')2533 first ='-';2534}25352536switch(first) {2537case'\n':2538/* Newer GNU diff, empty context line */2539if(plen <0)2540/* ... followed by '\No newline'; nothing */2541break;2542*old++ ='\n';2543strbuf_addch(&newlines,'\n');2544add_line_info(&preimage,"\n",1, LINE_COMMON);2545add_line_info(&postimage,"\n",1, LINE_COMMON);2546 is_blank_context =1;2547break;2548case' ':2549if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2550ws_blank_line(patch +1, plen, ws_rule))2551 is_blank_context =1;2552case'-':2553memcpy(old, patch +1, plen);2554add_line_info(&preimage, old, plen,2555(first ==' '? LINE_COMMON :0));2556 old += plen;2557if(first =='-')2558break;2559/* Fall-through for ' ' */2560case'+':2561/* --no-add does not add new lines */2562if(first =='+'&& no_add)2563break;25642565 start = newlines.len;2566if(first !='+'||2567!whitespace_error ||2568 ws_error_action != correct_ws_error) {2569strbuf_add(&newlines, patch +1, plen);2570}2571else{2572ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2573}2574add_line_info(&postimage, newlines.buf + start, newlines.len - start,2575(first =='+'?0: LINE_COMMON));2576if(first =='+'&&2577(ws_rule & WS_BLANK_AT_EOF) &&2578ws_blank_line(patch +1, plen, ws_rule))2579 added_blank_line =1;2580break;2581case'@':case'\\':2582/* Ignore it, we already handled it */2583break;2584default:2585if(apply_verbosely)2586error("invalid start of line: '%c'", first);2587return-1;2588}2589if(added_blank_line) {2590if(!new_blank_lines_at_end)2591 found_new_blank_lines_at_end = hunk_linenr;2592 new_blank_lines_at_end++;2593}2594else if(is_blank_context)2595;2596else2597 new_blank_lines_at_end =0;2598 patch += len;2599 size -= len;2600 hunk_linenr++;2601}2602if(inaccurate_eof &&2603 old > oldlines && old[-1] =='\n'&&2604 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2605 old--;2606strbuf_setlen(&newlines, newlines.len -1);2607}26082609 leading = frag->leading;2610 trailing = frag->trailing;26112612/*2613 * A hunk to change lines at the beginning would begin with2614 * @@ -1,L +N,M @@2615 * but we need to be careful. -U0 that inserts before the second2616 * line also has this pattern.2617 *2618 * And a hunk to add to an empty file would begin with2619 * @@ -0,0 +N,M @@2620 *2621 * In other words, a hunk that is (frag->oldpos <= 1) with or2622 * without leading context must match at the beginning.2623 */2624 match_beginning = (!frag->oldpos ||2625(frag->oldpos ==1&& !unidiff_zero));26262627/*2628 * A hunk without trailing lines must match at the end.2629 * However, we simply cannot tell if a hunk must match end2630 * from the lack of trailing lines if the patch was generated2631 * with unidiff without any context.2632 */2633 match_end = !unidiff_zero && !trailing;26342635 pos = frag->newpos ? (frag->newpos -1) :0;2636 preimage.buf = oldlines;2637 preimage.len = old - oldlines;2638 postimage.buf = newlines.buf;2639 postimage.len = newlines.len;2640 preimage.line = preimage.line_allocated;2641 postimage.line = postimage.line_allocated;26422643for(;;) {26442645 applied_pos =find_pos(img, &preimage, &postimage, pos,2646 ws_rule, match_beginning, match_end);26472648if(applied_pos >=0)2649break;26502651/* Am I at my context limits? */2652if((leading <= p_context) && (trailing <= p_context))2653break;2654if(match_beginning || match_end) {2655 match_beginning = match_end =0;2656continue;2657}26582659/*2660 * Reduce the number of context lines; reduce both2661 * leading and trailing if they are equal otherwise2662 * just reduce the larger context.2663 */2664if(leading >= trailing) {2665remove_first_line(&preimage);2666remove_first_line(&postimage);2667 pos--;2668 leading--;2669}2670if(trailing > leading) {2671remove_last_line(&preimage);2672remove_last_line(&postimage);2673 trailing--;2674}2675}26762677if(applied_pos >=0) {2678if(new_blank_lines_at_end &&2679 preimage.nr + applied_pos >= img->nr &&2680(ws_rule & WS_BLANK_AT_EOF) &&2681 ws_error_action != nowarn_ws_error) {2682record_ws_error(WS_BLANK_AT_EOF,"+",1,2683 found_new_blank_lines_at_end);2684if(ws_error_action == correct_ws_error) {2685while(new_blank_lines_at_end--)2686remove_last_line(&postimage);2687}2688/*2689 * We would want to prevent write_out_results()2690 * from taking place in apply_patch() that follows2691 * the callchain led us here, which is:2692 * apply_patch->check_patch_list->check_patch->2693 * apply_data->apply_fragments->apply_one_fragment2694 */2695if(ws_error_action == die_on_ws_error)2696 apply =0;2697}26982699if(apply_verbosely && applied_pos != pos) {2700int offset = applied_pos - pos;2701if(apply_in_reverse)2702 offset =0- offset;2703fprintf(stderr,2704"Hunk #%dsucceeded at%d(offset%dlines).\n",2705 nth_fragment, applied_pos +1, offset);2706}27072708/*2709 * Warn if it was necessary to reduce the number2710 * of context lines.2711 */2712if((leading != frag->leading) ||2713(trailing != frag->trailing))2714fprintf(stderr,"Context reduced to (%ld/%ld)"2715" to apply fragment at%d\n",2716 leading, trailing, applied_pos+1);2717update_image(img, applied_pos, &preimage, &postimage);2718}else{2719if(apply_verbosely)2720error("while searching for:\n%.*s",2721(int)(old - oldlines), oldlines);2722}27232724free(oldlines);2725strbuf_release(&newlines);2726free(preimage.line_allocated);2727free(postimage.line_allocated);27282729return(applied_pos <0);2730}27312732static intapply_binary_fragment(struct image *img,struct patch *patch)2733{2734struct fragment *fragment = patch->fragments;2735unsigned long len;2736void*dst;27372738if(!fragment)2739returnerror("missing binary patch data for '%s'",2740 patch->new_name ?2741 patch->new_name :2742 patch->old_name);27432744/* Binary patch is irreversible without the optional second hunk */2745if(apply_in_reverse) {2746if(!fragment->next)2747returnerror("cannot reverse-apply a binary patch "2748"without the reverse hunk to '%s'",2749 patch->new_name2750? patch->new_name : patch->old_name);2751 fragment = fragment->next;2752}2753switch(fragment->binary_patch_method) {2754case BINARY_DELTA_DEFLATED:2755 dst =patch_delta(img->buf, img->len, fragment->patch,2756 fragment->size, &len);2757if(!dst)2758return-1;2759clear_image(img);2760 img->buf = dst;2761 img->len = len;2762return0;2763case BINARY_LITERAL_DEFLATED:2764clear_image(img);2765 img->len = fragment->size;2766 img->buf =xmalloc(img->len+1);2767memcpy(img->buf, fragment->patch, img->len);2768 img->buf[img->len] ='\0';2769return0;2770}2771return-1;2772}27732774static intapply_binary(struct image *img,struct patch *patch)2775{2776const char*name = patch->old_name ? patch->old_name : patch->new_name;2777unsigned char sha1[20];27782779/*2780 * For safety, we require patch index line to contain2781 * full 40-byte textual SHA1 for old and new, at least for now.2782 */2783if(strlen(patch->old_sha1_prefix) !=40||2784strlen(patch->new_sha1_prefix) !=40||2785get_sha1_hex(patch->old_sha1_prefix, sha1) ||2786get_sha1_hex(patch->new_sha1_prefix, sha1))2787returnerror("cannot apply binary patch to '%s' "2788"without full index line", name);27892790if(patch->old_name) {2791/*2792 * See if the old one matches what the patch2793 * applies to.2794 */2795hash_sha1_file(img->buf, img->len, blob_type, sha1);2796if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2797returnerror("the patch applies to '%s' (%s), "2798"which does not match the "2799"current contents.",2800 name,sha1_to_hex(sha1));2801}2802else{2803/* Otherwise, the old one must be empty. */2804if(img->len)2805returnerror("the patch applies to an empty "2806"'%s' but it is not empty", name);2807}28082809get_sha1_hex(patch->new_sha1_prefix, sha1);2810if(is_null_sha1(sha1)) {2811clear_image(img);2812return0;/* deletion patch */2813}28142815if(has_sha1_file(sha1)) {2816/* We already have the postimage */2817enum object_type type;2818unsigned long size;2819char*result;28202821 result =read_sha1_file(sha1, &type, &size);2822if(!result)2823returnerror("the necessary postimage%sfor "2824"'%s' cannot be read",2825 patch->new_sha1_prefix, name);2826clear_image(img);2827 img->buf = result;2828 img->len = size;2829}else{2830/*2831 * We have verified buf matches the preimage;2832 * apply the patch data to it, which is stored2833 * in the patch->fragments->{patch,size}.2834 */2835if(apply_binary_fragment(img, patch))2836returnerror("binary patch does not apply to '%s'",2837 name);28382839/* verify that the result matches */2840hash_sha1_file(img->buf, img->len, blob_type, sha1);2841if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2842returnerror("binary patch to '%s' creates incorrect result (expecting%s, got%s)",2843 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2844}28452846return0;2847}28482849static intapply_fragments(struct image *img,struct patch *patch)2850{2851struct fragment *frag = patch->fragments;2852const char*name = patch->old_name ? patch->old_name : patch->new_name;2853unsigned ws_rule = patch->ws_rule;2854unsigned inaccurate_eof = patch->inaccurate_eof;2855int nth =0;28562857if(patch->is_binary)2858returnapply_binary(img, patch);28592860while(frag) {2861 nth++;2862if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {2863error("patch failed:%s:%ld", name, frag->oldpos);2864if(!apply_with_reject)2865return-1;2866 frag->rejected =1;2867}2868 frag = frag->next;2869}2870return0;2871}28722873static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2874{2875if(!ce)2876return0;28772878if(S_ISGITLINK(ce->ce_mode)) {2879strbuf_grow(buf,100);2880strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2881}else{2882enum object_type type;2883unsigned long sz;2884char*result;28852886 result =read_sha1_file(ce->sha1, &type, &sz);2887if(!result)2888return-1;2889/* XXX read_sha1_file NUL-terminates */2890strbuf_attach(buf, result, sz, sz +1);2891}2892return0;2893}28942895static struct patch *in_fn_table(const char*name)2896{2897struct string_list_item *item;28982899if(name == NULL)2900return NULL;29012902 item =string_list_lookup(&fn_table, name);2903if(item != NULL)2904return(struct patch *)item->util;29052906return NULL;2907}29082909/*2910 * item->util in the filename table records the status of the path.2911 * Usually it points at a patch (whose result records the contents2912 * of it after applying it), but it could be PATH_WAS_DELETED for a2913 * path that a previously applied patch has already removed.2914 */2915#define PATH_TO_BE_DELETED ((struct patch *) -2)2916#define PATH_WAS_DELETED ((struct patch *) -1)29172918static intto_be_deleted(struct patch *patch)2919{2920return patch == PATH_TO_BE_DELETED;2921}29222923static intwas_deleted(struct patch *patch)2924{2925return patch == PATH_WAS_DELETED;2926}29272928static voidadd_to_fn_table(struct patch *patch)2929{2930struct string_list_item *item;29312932/*2933 * Always add new_name unless patch is a deletion2934 * This should cover the cases for normal diffs,2935 * file creations and copies2936 */2937if(patch->new_name != NULL) {2938 item =string_list_insert(&fn_table, patch->new_name);2939 item->util = patch;2940}29412942/*2943 * store a failure on rename/deletion cases because2944 * later chunks shouldn't patch old names2945 */2946if((patch->new_name == NULL) || (patch->is_rename)) {2947 item =string_list_insert(&fn_table, patch->old_name);2948 item->util = PATH_WAS_DELETED;2949}2950}29512952static voidprepare_fn_table(struct patch *patch)2953{2954/*2955 * store information about incoming file deletion2956 */2957while(patch) {2958if((patch->new_name == NULL) || (patch->is_rename)) {2959struct string_list_item *item;2960 item =string_list_insert(&fn_table, patch->old_name);2961 item->util = PATH_TO_BE_DELETED;2962}2963 patch = patch->next;2964}2965}29662967static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)2968{2969struct strbuf buf = STRBUF_INIT;2970struct image image;2971size_t len;2972char*img;2973struct patch *tpatch;29742975if(!(patch->is_copy || patch->is_rename) &&2976(tpatch =in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {2977if(was_deleted(tpatch)) {2978returnerror("patch%shas been renamed/deleted",2979 patch->old_name);2980}2981/* We have a patched copy in memory use that */2982strbuf_add(&buf, tpatch->result, tpatch->resultsize);2983}else if(cached) {2984if(read_file_or_gitlink(ce, &buf))2985returnerror("read of%sfailed", patch->old_name);2986}else if(patch->old_name) {2987if(S_ISGITLINK(patch->old_mode)) {2988if(ce) {2989read_file_or_gitlink(ce, &buf);2990}else{2991/*2992 * There is no way to apply subproject2993 * patch without looking at the index.2994 */2995 patch->fragments = NULL;2996}2997}else{2998if(read_old_data(st, patch->old_name, &buf))2999returnerror("read of%sfailed", patch->old_name);3000}3001}30023003 img =strbuf_detach(&buf, &len);3004prepare_image(&image, img, len, !patch->is_binary);30053006if(apply_fragments(&image, patch) <0)3007return-1;/* note with --reject this succeeds. */3008 patch->result = image.buf;3009 patch->resultsize = image.len;3010add_to_fn_table(patch);3011free(image.line_allocated);30123013if(0< patch->is_delete && patch->resultsize)3014returnerror("removal patch leaves file contents");30153016return0;3017}30183019static intcheck_to_create_blob(const char*new_name,int ok_if_exists)3020{3021struct stat nst;3022if(!lstat(new_name, &nst)) {3023if(S_ISDIR(nst.st_mode) || ok_if_exists)3024return0;3025/*3026 * A leading component of new_name might be a symlink3027 * that is going to be removed with this patch, but3028 * still pointing at somewhere that has the path.3029 * In such a case, path "new_name" does not exist as3030 * far as git is concerned.3031 */3032if(has_symlink_leading_path(new_name,strlen(new_name)))3033return0;30343035returnerror("%s: already exists in working directory", new_name);3036}3037else if((errno != ENOENT) && (errno != ENOTDIR))3038returnerror("%s:%s", new_name,strerror(errno));3039return0;3040}30413042static intverify_index_match(struct cache_entry *ce,struct stat *st)3043{3044if(S_ISGITLINK(ce->ce_mode)) {3045if(!S_ISDIR(st->st_mode))3046return-1;3047return0;3048}3049returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3050}30513052static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)3053{3054const char*old_name = patch->old_name;3055struct patch *tpatch = NULL;3056int stat_ret =0;3057unsigned st_mode =0;30583059/*3060 * Make sure that we do not have local modifications from the3061 * index when we are looking at the index. Also make sure3062 * we have the preimage file to be patched in the work tree,3063 * unless --cached, which tells git to apply only in the index.3064 */3065if(!old_name)3066return0;30673068assert(patch->is_new <=0);30693070if(!(patch->is_copy || patch->is_rename) &&3071(tpatch =in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {3072if(was_deleted(tpatch))3073returnerror("%s: has been deleted/renamed", old_name);3074 st_mode = tpatch->new_mode;3075}else if(!cached) {3076 stat_ret =lstat(old_name, st);3077if(stat_ret && errno != ENOENT)3078returnerror("%s:%s", old_name,strerror(errno));3079}30803081if(to_be_deleted(tpatch))3082 tpatch = NULL;30833084if(check_index && !tpatch) {3085int pos =cache_name_pos(old_name,strlen(old_name));3086if(pos <0) {3087if(patch->is_new <0)3088goto is_new;3089returnerror("%s: does not exist in index", old_name);3090}3091*ce = active_cache[pos];3092if(stat_ret <0) {3093struct checkout costate;3094/* checkout */3095memset(&costate,0,sizeof(costate));3096 costate.base_dir ="";3097 costate.refresh_cache =1;3098if(checkout_entry(*ce, &costate, NULL) ||3099lstat(old_name, st))3100return-1;3101}3102if(!cached &&verify_index_match(*ce, st))3103returnerror("%s: does not match index", old_name);3104if(cached)3105 st_mode = (*ce)->ce_mode;3106}else if(stat_ret <0) {3107if(patch->is_new <0)3108goto is_new;3109returnerror("%s:%s", old_name,strerror(errno));3110}31113112if(!cached && !tpatch)3113 st_mode =ce_mode_from_stat(*ce, st->st_mode);31143115if(patch->is_new <0)3116 patch->is_new =0;3117if(!patch->old_mode)3118 patch->old_mode = st_mode;3119if((st_mode ^ patch->old_mode) & S_IFMT)3120returnerror("%s: wrong type", old_name);3121if(st_mode != patch->old_mode)3122warning("%shas type%o, expected%o",3123 old_name, st_mode, patch->old_mode);3124if(!patch->new_mode && !patch->is_delete)3125 patch->new_mode = st_mode;3126return0;31273128 is_new:3129 patch->is_new =1;3130 patch->is_delete =0;3131free(patch->old_name);3132 patch->old_name = NULL;3133return0;3134}31353136static intcheck_patch(struct patch *patch)3137{3138struct stat st;3139const char*old_name = patch->old_name;3140const char*new_name = patch->new_name;3141const char*name = old_name ? old_name : new_name;3142struct cache_entry *ce = NULL;3143struct patch *tpatch;3144int ok_if_exists;3145int status;31463147 patch->rejected =1;/* we will drop this after we succeed */31483149 status =check_preimage(patch, &ce, &st);3150if(status)3151return status;3152 old_name = patch->old_name;31533154if((tpatch =in_fn_table(new_name)) &&3155(was_deleted(tpatch) ||to_be_deleted(tpatch)))3156/*3157 * A type-change diff is always split into a patch to3158 * delete old, immediately followed by a patch to3159 * create new (see diff.c::run_diff()); in such a case3160 * it is Ok that the entry to be deleted by the3161 * previous patch is still in the working tree and in3162 * the index.3163 */3164 ok_if_exists =1;3165else3166 ok_if_exists =0;31673168if(new_name &&3169((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {3170if(check_index &&3171cache_name_pos(new_name,strlen(new_name)) >=0&&3172!ok_if_exists)3173returnerror("%s: already exists in index", new_name);3174if(!cached) {3175int err =check_to_create_blob(new_name, ok_if_exists);3176if(err)3177return err;3178}3179if(!patch->new_mode) {3180if(0< patch->is_new)3181 patch->new_mode = S_IFREG |0644;3182else3183 patch->new_mode = patch->old_mode;3184}3185}31863187if(new_name && old_name) {3188int same = !strcmp(old_name, new_name);3189if(!patch->new_mode)3190 patch->new_mode = patch->old_mode;3191if((patch->old_mode ^ patch->new_mode) & S_IFMT)3192returnerror("new mode (%o) of%sdoes not match old mode (%o)%s%s",3193 patch->new_mode, new_name, patch->old_mode,3194 same ?"":" of ", same ?"": old_name);3195}31963197if(apply_data(patch, &st, ce) <0)3198returnerror("%s: patch does not apply", name);3199 patch->rejected =0;3200return0;3201}32023203static intcheck_patch_list(struct patch *patch)3204{3205int err =0;32063207prepare_fn_table(patch);3208while(patch) {3209if(apply_verbosely)3210say_patch_name(stderr,3211"Checking patch ", patch,"...\n");3212 err |=check_patch(patch);3213 patch = patch->next;3214}3215return err;3216}32173218/* This function tries to read the sha1 from the current index */3219static intget_current_sha1(const char*path,unsigned char*sha1)3220{3221int pos;32223223if(read_cache() <0)3224return-1;3225 pos =cache_name_pos(path,strlen(path));3226if(pos <0)3227return-1;3228hashcpy(sha1, active_cache[pos]->sha1);3229return0;3230}32313232/* Build an index that contains the just the files needed for a 3way merge */3233static voidbuild_fake_ancestor(struct patch *list,const char*filename)3234{3235struct patch *patch;3236struct index_state result = { NULL };3237int fd;32383239/* Once we start supporting the reverse patch, it may be3240 * worth showing the new sha1 prefix, but until then...3241 */3242for(patch = list; patch; patch = patch->next) {3243const unsigned char*sha1_ptr;3244unsigned char sha1[20];3245struct cache_entry *ce;3246const char*name;32473248 name = patch->old_name ? patch->old_name : patch->new_name;3249if(0< patch->is_new)3250continue;3251else if(get_sha1(patch->old_sha1_prefix, sha1))3252/* git diff has no index line for mode/type changes */3253if(!patch->lines_added && !patch->lines_deleted) {3254if(get_current_sha1(patch->old_name, sha1))3255die("mode change for%s, which is not "3256"in current HEAD", name);3257 sha1_ptr = sha1;3258}else3259die("sha1 information is lacking or useless "3260"(%s).", name);3261else3262 sha1_ptr = sha1;32633264 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);3265if(!ce)3266die("make_cache_entry failed for path '%s'", name);3267if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3268die("Could not add%sto temporary index", name);3269}32703271 fd =open(filename, O_WRONLY | O_CREAT,0666);3272if(fd <0||write_index(&result, fd) ||close(fd))3273die("Could not write temporary index to%s", filename);32743275discard_index(&result);3276}32773278static voidstat_patch_list(struct patch *patch)3279{3280int files, adds, dels;32813282for(files = adds = dels =0; patch ; patch = patch->next) {3283 files++;3284 adds += patch->lines_added;3285 dels += patch->lines_deleted;3286show_stats(patch);3287}32883289printf("%dfiles changed,%dinsertions(+),%ddeletions(-)\n", files, adds, dels);3290}32913292static voidnumstat_patch_list(struct patch *patch)3293{3294for( ; patch; patch = patch->next) {3295const char*name;3296 name = patch->new_name ? patch->new_name : patch->old_name;3297if(patch->is_binary)3298printf("-\t-\t");3299else3300printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3301write_name_quoted(name, stdout, line_termination);3302}3303}33043305static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3306{3307if(mode)3308printf("%smode%06o%s\n", newdelete, mode, name);3309else3310printf("%s %s\n", newdelete, name);3311}33123313static voidshow_mode_change(struct patch *p,int show_name)3314{3315if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3316if(show_name)3317printf(" mode change%06o =>%06o%s\n",3318 p->old_mode, p->new_mode, p->new_name);3319else3320printf(" mode change%06o =>%06o\n",3321 p->old_mode, p->new_mode);3322}3323}33243325static voidshow_rename_copy(struct patch *p)3326{3327const char*renamecopy = p->is_rename ?"rename":"copy";3328const char*old, *new;33293330/* Find common prefix */3331 old = p->old_name;3332new= p->new_name;3333while(1) {3334const char*slash_old, *slash_new;3335 slash_old =strchr(old,'/');3336 slash_new =strchr(new,'/');3337if(!slash_old ||3338!slash_new ||3339 slash_old - old != slash_new -new||3340memcmp(old,new, slash_new -new))3341break;3342 old = slash_old +1;3343new= slash_new +1;3344}3345/* p->old_name thru old is the common prefix, and old and new3346 * through the end of names are renames3347 */3348if(old != p->old_name)3349printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,3350(int)(old - p->old_name), p->old_name,3351 old,new, p->score);3352else3353printf("%s %s=>%s(%d%%)\n", renamecopy,3354 p->old_name, p->new_name, p->score);3355show_mode_change(p,0);3356}33573358static voidsummary_patch_list(struct patch *patch)3359{3360struct patch *p;33613362for(p = patch; p; p = p->next) {3363if(p->is_new)3364show_file_mode_name("create", p->new_mode, p->new_name);3365else if(p->is_delete)3366show_file_mode_name("delete", p->old_mode, p->old_name);3367else{3368if(p->is_rename || p->is_copy)3369show_rename_copy(p);3370else{3371if(p->score) {3372printf(" rewrite%s(%d%%)\n",3373 p->new_name, p->score);3374show_mode_change(p,0);3375}3376else3377show_mode_change(p,1);3378}3379}3380}3381}33823383static voidpatch_stats(struct patch *patch)3384{3385int lines = patch->lines_added + patch->lines_deleted;33863387if(lines > max_change)3388 max_change = lines;3389if(patch->old_name) {3390int len =quote_c_style(patch->old_name, NULL, NULL,0);3391if(!len)3392 len =strlen(patch->old_name);3393if(len > max_len)3394 max_len = len;3395}3396if(patch->new_name) {3397int len =quote_c_style(patch->new_name, NULL, NULL,0);3398if(!len)3399 len =strlen(patch->new_name);3400if(len > max_len)3401 max_len = len;3402}3403}34043405static voidremove_file(struct patch *patch,int rmdir_empty)3406{3407if(update_index) {3408if(remove_file_from_cache(patch->old_name) <0)3409die("unable to remove%sfrom index", patch->old_name);3410}3411if(!cached) {3412if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {3413remove_path(patch->old_name);3414}3415}3416}34173418static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)3419{3420struct stat st;3421struct cache_entry *ce;3422int namelen =strlen(path);3423unsigned ce_size =cache_entry_size(namelen);34243425if(!update_index)3426return;34273428 ce =xcalloc(1, ce_size);3429memcpy(ce->name, path, namelen);3430 ce->ce_mode =create_ce_mode(mode);3431 ce->ce_flags = namelen;3432if(S_ISGITLINK(mode)) {3433const char*s = buf;34343435if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))3436die("corrupt patch for subproject%s", path);3437}else{3438if(!cached) {3439if(lstat(path, &st) <0)3440die_errno("unable to stat newly created file '%s'",3441 path);3442fill_stat_cache_info(ce, &st);3443}3444if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)3445die("unable to create backing store for newly created file%s", path);3446}3447if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3448die("unable to add cache entry for%s", path);3449}34503451static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)3452{3453int fd;3454struct strbuf nbuf = STRBUF_INIT;34553456if(S_ISGITLINK(mode)) {3457struct stat st;3458if(!lstat(path, &st) &&S_ISDIR(st.st_mode))3459return0;3460returnmkdir(path,0777);3461}34623463if(has_symlinks &&S_ISLNK(mode))3464/* Although buf:size is counted string, it also is NUL3465 * terminated.3466 */3467returnsymlink(buf, path);34683469 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);3470if(fd <0)3471return-1;34723473if(convert_to_working_tree(path, buf, size, &nbuf)) {3474 size = nbuf.len;3475 buf = nbuf.buf;3476}3477write_or_die(fd, buf, size);3478strbuf_release(&nbuf);34793480if(close(fd) <0)3481die_errno("closing file '%s'", path);3482return0;3483}34843485/*3486 * We optimistically assume that the directories exist,3487 * which is true 99% of the time anyway. If they don't,3488 * we create them and try again.3489 */3490static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)3491{3492if(cached)3493return;3494if(!try_create_file(path, mode, buf, size))3495return;34963497if(errno == ENOENT) {3498if(safe_create_leading_directories(path))3499return;3500if(!try_create_file(path, mode, buf, size))3501return;3502}35033504if(errno == EEXIST || errno == EACCES) {3505/* We may be trying to create a file where a directory3506 * used to be.3507 */3508struct stat st;3509if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))3510 errno = EEXIST;3511}35123513if(errno == EEXIST) {3514unsigned int nr =getpid();35153516for(;;) {3517char newpath[PATH_MAX];3518mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);3519if(!try_create_file(newpath, mode, buf, size)) {3520if(!rename(newpath, path))3521return;3522unlink_or_warn(newpath);3523break;3524}3525if(errno != EEXIST)3526break;3527++nr;3528}3529}3530die_errno("unable to write file '%s' mode%o", path, mode);3531}35323533static voidcreate_file(struct patch *patch)3534{3535char*path = patch->new_name;3536unsigned mode = patch->new_mode;3537unsigned long size = patch->resultsize;3538char*buf = patch->result;35393540if(!mode)3541 mode = S_IFREG |0644;3542create_one_file(path, mode, buf, size);3543add_index_file(path, mode, buf, size);3544}35453546/* phase zero is to remove, phase one is to create */3547static voidwrite_out_one_result(struct patch *patch,int phase)3548{3549if(patch->is_delete >0) {3550if(phase ==0)3551remove_file(patch,1);3552return;3553}3554if(patch->is_new >0|| patch->is_copy) {3555if(phase ==1)3556create_file(patch);3557return;3558}3559/*3560 * Rename or modification boils down to the same3561 * thing: remove the old, write the new3562 */3563if(phase ==0)3564remove_file(patch, patch->is_rename);3565if(phase ==1)3566create_file(patch);3567}35683569static intwrite_out_one_reject(struct patch *patch)3570{3571FILE*rej;3572char namebuf[PATH_MAX];3573struct fragment *frag;3574int cnt =0;35753576for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {3577if(!frag->rejected)3578continue;3579 cnt++;3580}35813582if(!cnt) {3583if(apply_verbosely)3584say_patch_name(stderr,3585"Applied patch ", patch," cleanly.\n");3586return0;3587}35883589/* This should not happen, because a removal patch that leaves3590 * contents are marked "rejected" at the patch level.3591 */3592if(!patch->new_name)3593die("internal error");35943595/* Say this even without --verbose */3596say_patch_name(stderr,"Applying patch ", patch," with");3597fprintf(stderr,"%drejects...\n", cnt);35983599 cnt =strlen(patch->new_name);3600if(ARRAY_SIZE(namebuf) <= cnt +5) {3601 cnt =ARRAY_SIZE(namebuf) -5;3602warning("truncating .rej filename to %.*s.rej",3603 cnt -1, patch->new_name);3604}3605memcpy(namebuf, patch->new_name, cnt);3606memcpy(namebuf + cnt,".rej",5);36073608 rej =fopen(namebuf,"w");3609if(!rej)3610returnerror("cannot open%s:%s", namebuf,strerror(errno));36113612/* Normal git tools never deal with .rej, so do not pretend3613 * this is a git patch by saying --git nor give extended3614 * headers. While at it, maybe please "kompare" that wants3615 * the trailing TAB and some garbage at the end of line ;-).3616 */3617fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",3618 patch->new_name, patch->new_name);3619for(cnt =1, frag = patch->fragments;3620 frag;3621 cnt++, frag = frag->next) {3622if(!frag->rejected) {3623fprintf(stderr,"Hunk #%dapplied cleanly.\n", cnt);3624continue;3625}3626fprintf(stderr,"Rejected hunk #%d.\n", cnt);3627fprintf(rej,"%.*s", frag->size, frag->patch);3628if(frag->patch[frag->size-1] !='\n')3629fputc('\n', rej);3630}3631fclose(rej);3632return-1;3633}36343635static intwrite_out_results(struct patch *list)3636{3637int phase;3638int errs =0;3639struct patch *l;36403641for(phase =0; phase <2; phase++) {3642 l = list;3643while(l) {3644if(l->rejected)3645 errs =1;3646else{3647write_out_one_result(l, phase);3648if(phase ==1&&write_out_one_reject(l))3649 errs =1;3650}3651 l = l->next;3652}3653}3654return errs;3655}36563657static struct lock_file lock_file;36583659static struct string_list limit_by_name;3660static int has_include;3661static voidadd_name_limit(const char*name,int exclude)3662{3663struct string_list_item *it;36643665 it =string_list_append(&limit_by_name, name);3666 it->util = exclude ? NULL : (void*)1;3667}36683669static intuse_patch(struct patch *p)3670{3671const char*pathname = p->new_name ? p->new_name : p->old_name;3672int i;36733674/* Paths outside are not touched regardless of "--include" */3675if(0< prefix_length) {3676int pathlen =strlen(pathname);3677if(pathlen <= prefix_length ||3678memcmp(prefix, pathname, prefix_length))3679return0;3680}36813682/* See if it matches any of exclude/include rule */3683for(i =0; i < limit_by_name.nr; i++) {3684struct string_list_item *it = &limit_by_name.items[i];3685if(!fnmatch(it->string, pathname,0))3686return(it->util != NULL);3687}36883689/*3690 * If we had any include, a path that does not match any rule is3691 * not used. Otherwise, we saw bunch of exclude rules (or none)3692 * and such a path is used.3693 */3694return!has_include;3695}369636973698static voidprefix_one(char**name)3699{3700char*old_name = *name;3701if(!old_name)3702return;3703*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3704free(old_name);3705}37063707static voidprefix_patches(struct patch *p)3708{3709if(!prefix || p->is_toplevel_relative)3710return;3711for( ; p; p = p->next) {3712prefix_one(&p->new_name);3713prefix_one(&p->old_name);3714}3715}37163717#define INACCURATE_EOF (1<<0)3718#define RECOUNT (1<<1)37193720static intapply_patch(int fd,const char*filename,int options)3721{3722size_t offset;3723struct strbuf buf = STRBUF_INIT;3724struct patch *list = NULL, **listp = &list;3725int skipped_patch =0;37263727memset(&fn_table,0,sizeof(struct string_list));3728 patch_input_file = filename;3729read_patch_file(&buf, fd);3730 offset =0;3731while(offset < buf.len) {3732struct patch *patch;3733int nr;37343735 patch =xcalloc(1,sizeof(*patch));3736 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3737 patch->recount = !!(options & RECOUNT);3738 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3739if(nr <0)3740break;3741if(apply_in_reverse)3742reverse_patches(patch);3743if(prefix)3744prefix_patches(patch);3745if(use_patch(patch)) {3746patch_stats(patch);3747*listp = patch;3748 listp = &patch->next;3749}3750else{3751free_patch(patch);3752 skipped_patch++;3753}3754 offset += nr;3755}37563757if(!list && !skipped_patch)3758die("unrecognized input");37593760if(whitespace_error && (ws_error_action == die_on_ws_error))3761 apply =0;37623763 update_index = check_index && apply;3764if(update_index && newfd <0)3765 newfd =hold_locked_index(&lock_file,1);37663767if(check_index) {3768if(read_cache() <0)3769die("unable to read index file");3770}37713772if((check || apply) &&3773check_patch_list(list) <0&&3774!apply_with_reject)3775exit(1);37763777if(apply &&write_out_results(list))3778exit(1);37793780if(fake_ancestor)3781build_fake_ancestor(list, fake_ancestor);37823783if(diffstat)3784stat_patch_list(list);37853786if(numstat)3787numstat_patch_list(list);37883789if(summary)3790summary_patch_list(list);37913792free_patch_list(list);3793strbuf_release(&buf);3794return0;3795}37963797static intgit_apply_config(const char*var,const char*value,void*cb)3798{3799if(!strcmp(var,"apply.whitespace"))3800returngit_config_string(&apply_default_whitespace, var, value);3801else if(!strcmp(var,"apply.ignorewhitespace"))3802returngit_config_string(&apply_default_ignorewhitespace, var, value);3803returngit_default_config(var, value, cb);3804}38053806static intoption_parse_exclude(const struct option *opt,3807const char*arg,int unset)3808{3809add_name_limit(arg,1);3810return0;3811}38123813static intoption_parse_include(const struct option *opt,3814const char*arg,int unset)3815{3816add_name_limit(arg,0);3817 has_include =1;3818return0;3819}38203821static intoption_parse_p(const struct option *opt,3822const char*arg,int unset)3823{3824 p_value =atoi(arg);3825 p_value_known =1;3826return0;3827}38283829static intoption_parse_z(const struct option *opt,3830const char*arg,int unset)3831{3832if(unset)3833 line_termination ='\n';3834else3835 line_termination =0;3836return0;3837}38383839static intoption_parse_space_change(const struct option *opt,3840const char*arg,int unset)3841{3842if(unset)3843 ws_ignore_action = ignore_ws_none;3844else3845 ws_ignore_action = ignore_ws_change;3846return0;3847}38483849static intoption_parse_whitespace(const struct option *opt,3850const char*arg,int unset)3851{3852const char**whitespace_option = opt->value;38533854*whitespace_option = arg;3855parse_whitespace_option(arg);3856return0;3857}38583859static intoption_parse_directory(const struct option *opt,3860const char*arg,int unset)3861{3862 root_len =strlen(arg);3863if(root_len && arg[root_len -1] !='/') {3864char*new_root;3865 root = new_root =xmalloc(root_len +2);3866strcpy(new_root, arg);3867strcpy(new_root + root_len++,"/");3868}else3869 root = arg;3870return0;3871}38723873intcmd_apply(int argc,const char**argv,const char*prefix_)3874{3875int i;3876int errs =0;3877int is_not_gitdir = !startup_info->have_repository;3878int force_apply =0;38793880const char*whitespace_option = NULL;38813882struct option builtin_apply_options[] = {3883{ OPTION_CALLBACK,0,"exclude", NULL,"path",3884"don't apply changes matching the given path",38850, option_parse_exclude },3886{ OPTION_CALLBACK,0,"include", NULL,"path",3887"apply changes matching the given path",38880, option_parse_include },3889{ OPTION_CALLBACK,'p', NULL, NULL,"num",3890"remove <num> leading slashes from traditional diff paths",38910, option_parse_p },3892OPT_BOOLEAN(0,"no-add", &no_add,3893"ignore additions made by the patch"),3894OPT_BOOLEAN(0,"stat", &diffstat,3895"instead of applying the patch, output diffstat for the input"),3896OPT_NOOP_NOARG(0,"allow-binary-replacement"),3897OPT_NOOP_NOARG(0,"binary"),3898OPT_BOOLEAN(0,"numstat", &numstat,3899"shows number of added and deleted lines in decimal notation"),3900OPT_BOOLEAN(0,"summary", &summary,3901"instead of applying the patch, output a summary for the input"),3902OPT_BOOLEAN(0,"check", &check,3903"instead of applying the patch, see if the patch is applicable"),3904OPT_BOOLEAN(0,"index", &check_index,3905"make sure the patch is applicable to the current index"),3906OPT_BOOLEAN(0,"cached", &cached,3907"apply a patch without touching the working tree"),3908OPT_BOOLEAN(0,"apply", &force_apply,3909"also apply the patch (use with --stat/--summary/--check)"),3910OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,3911"build a temporary index based on embedded index information"),3912{ OPTION_CALLBACK,'z', NULL, NULL, NULL,3913"paths are separated with NUL character",3914 PARSE_OPT_NOARG, option_parse_z },3915OPT_INTEGER('C', NULL, &p_context,3916"ensure at least <n> lines of context match"),3917{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,"action",3918"detect new or modified lines that have whitespace errors",39190, option_parse_whitespace },3920{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,3921"ignore changes in whitespace when finding context",3922 PARSE_OPT_NOARG, option_parse_space_change },3923{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,3924"ignore changes in whitespace when finding context",3925 PARSE_OPT_NOARG, option_parse_space_change },3926OPT_BOOLEAN('R',"reverse", &apply_in_reverse,3927"apply the patch in reverse"),3928OPT_BOOLEAN(0,"unidiff-zero", &unidiff_zero,3929"don't expect at least one line of context"),3930OPT_BOOLEAN(0,"reject", &apply_with_reject,3931"leave the rejected hunks in corresponding *.rej files"),3932OPT_BOOLEAN(0,"allow-overlap", &allow_overlap,3933"allow overlapping hunks"),3934OPT__VERBOSE(&apply_verbosely,"be verbose"),3935OPT_BIT(0,"inaccurate-eof", &options,3936"tolerate incorrectly detected missing new-line at the end of file",3937 INACCURATE_EOF),3938OPT_BIT(0,"recount", &options,3939"do not trust the line counts in the hunk headers",3940 RECOUNT),3941{ OPTION_CALLBACK,0,"directory", NULL,"root",3942"prepend <root> to all filenames",39430, option_parse_directory },3944OPT_END()3945};39463947 prefix = prefix_;3948 prefix_length = prefix ?strlen(prefix) :0;3949git_config(git_apply_config, NULL);3950if(apply_default_whitespace)3951parse_whitespace_option(apply_default_whitespace);3952if(apply_default_ignorewhitespace)3953parse_ignorewhitespace_option(apply_default_ignorewhitespace);39543955 argc =parse_options(argc, argv, prefix, builtin_apply_options,3956 apply_usage,0);39573958if(apply_with_reject)3959 apply = apply_verbosely =1;3960if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))3961 apply =0;3962if(check_index && is_not_gitdir)3963die("--index outside a repository");3964if(cached) {3965if(is_not_gitdir)3966die("--cached outside a repository");3967 check_index =1;3968}3969for(i =0; i < argc; i++) {3970const char*arg = argv[i];3971int fd;39723973if(!strcmp(arg,"-")) {3974 errs |=apply_patch(0,"<stdin>", options);3975 read_stdin =0;3976continue;3977}else if(0< prefix_length)3978 arg =prefix_filename(prefix, prefix_length, arg);39793980 fd =open(arg, O_RDONLY);3981if(fd <0)3982die_errno("can't open patch '%s'", arg);3983 read_stdin =0;3984set_default_whitespace_mode(whitespace_option);3985 errs |=apply_patch(fd, arg, options);3986close(fd);3987}3988set_default_whitespace_mode(whitespace_option);3989if(read_stdin)3990 errs |=apply_patch(0,"<stdin>", options);3991if(whitespace_error) {3992if(squelch_whitespace_errors &&3993 squelch_whitespace_errors < whitespace_error) {3994int squelched =3995 whitespace_error - squelch_whitespace_errors;3996warning("squelched%d"3997"whitespace error%s",3998 squelched,3999 squelched ==1?"":"s");4000}4001if(ws_error_action == die_on_ws_error)4002die("%dline%sadd%swhitespace errors.",4003 whitespace_error,4004 whitespace_error ==1?"":"s",4005 whitespace_error ==1?"s":"");4006if(applied_after_fixing_ws && apply)4007warning("%dline%sapplied after"4008" fixing whitespace errors.",4009 applied_after_fixing_ws,4010 applied_after_fixing_ws ==1?"":"s");4011else if(whitespace_error)4012warning("%dline%sadd%swhitespace errors.",4013 whitespace_error,4014 whitespace_error ==1?"":"s",4015 whitespace_error ==1?"s":"");4016}40174018if(update_index) {4019if(write_cache(newfd, active_cache, active_nr) ||4020commit_locked_index(&lock_file))4021die("Unable to write new index file");4022}40234024return!!errs;4025}