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"diff.h" 18#include"parse-options.h" 19 20/* 21 * --check turns on checking that the working tree matches the 22 * files that are being modified, but doesn't apply the patch 23 * --stat does just a diffstat, and doesn't actually apply 24 * --numstat does numeric diffstat, and doesn't actually apply 25 * --index-info shows the old and new index info for paths if available. 26 * --index updates the cache as well. 27 * --cached updates only the cache without ever touching the working tree. 28 */ 29static const char*prefix; 30static int prefix_length = -1; 31static int newfd = -1; 32 33static int unidiff_zero; 34static int p_value =1; 35static int p_value_known; 36static int check_index; 37static int update_index; 38static int cached; 39static int diffstat; 40static int numstat; 41static int summary; 42static int check; 43static int apply =1; 44static int apply_in_reverse; 45static int apply_with_reject; 46static int apply_verbosely; 47static int allow_overlap; 48static int no_add; 49static const char*fake_ancestor; 50static int line_termination ='\n'; 51static unsigned int p_context = UINT_MAX; 52static const char*const apply_usage[] = { 53"git apply [options] [<patch>...]", 54 NULL 55}; 56 57static enum ws_error_action { 58 nowarn_ws_error, 59 warn_on_ws_error, 60 die_on_ws_error, 61 correct_ws_error 62} ws_error_action = warn_on_ws_error; 63static int whitespace_error; 64static int squelch_whitespace_errors =5; 65static int applied_after_fixing_ws; 66 67static enum ws_ignore { 68 ignore_ws_none, 69 ignore_ws_change 70} ws_ignore_action = ignore_ws_none; 71 72 73static const char*patch_input_file; 74static const char*root; 75static int root_len; 76static int read_stdin =1; 77static int options; 78 79static voidparse_whitespace_option(const char*option) 80{ 81if(!option) { 82 ws_error_action = warn_on_ws_error; 83return; 84} 85if(!strcmp(option,"warn")) { 86 ws_error_action = warn_on_ws_error; 87return; 88} 89if(!strcmp(option,"nowarn")) { 90 ws_error_action = nowarn_ws_error; 91return; 92} 93if(!strcmp(option,"error")) { 94 ws_error_action = die_on_ws_error; 95return; 96} 97if(!strcmp(option,"error-all")) { 98 ws_error_action = die_on_ws_error; 99 squelch_whitespace_errors =0; 100return; 101} 102if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 103 ws_error_action = correct_ws_error; 104return; 105} 106die("unrecognized whitespace option '%s'", option); 107} 108 109static voidparse_ignorewhitespace_option(const char*option) 110{ 111if(!option || !strcmp(option,"no") || 112!strcmp(option,"false") || !strcmp(option,"never") || 113!strcmp(option,"none")) { 114 ws_ignore_action = ignore_ws_none; 115return; 116} 117if(!strcmp(option,"change")) { 118 ws_ignore_action = ignore_ws_change; 119return; 120} 121die("unrecognized whitespace ignore option '%s'", option); 122} 123 124static voidset_default_whitespace_mode(const char*whitespace_option) 125{ 126if(!whitespace_option && !apply_default_whitespace) 127 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 128} 129 130/* 131 * For "diff-stat" like behaviour, we keep track of the biggest change 132 * we've seen, and the longest filename. That allows us to do simple 133 * scaling. 134 */ 135static int max_change, max_len; 136 137/* 138 * Various "current state", notably line numbers and what 139 * file (and how) we're patching right now.. The "is_xxxx" 140 * things are flags, where -1 means "don't know yet". 141 */ 142static int linenr =1; 143 144/* 145 * This represents one "hunk" from a patch, starting with 146 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 147 * patch text is pointed at by patch, and its byte length 148 * is stored in size. leading and trailing are the number 149 * of context lines. 150 */ 151struct fragment { 152unsigned long leading, trailing; 153unsigned long oldpos, oldlines; 154unsigned long newpos, newlines; 155/* 156 * 'patch' is usually borrowed from buf in apply_patch(), 157 * but some codepaths store an allocated buffer. 158 */ 159const char*patch; 160unsigned free_patch:1, 161 rejected:1; 162int size; 163int linenr; 164struct fragment *next; 165}; 166 167/* 168 * When dealing with a binary patch, we reuse "leading" field 169 * to store the type of the binary hunk, either deflated "delta" 170 * or deflated "literal". 171 */ 172#define binary_patch_method leading 173#define BINARY_DELTA_DEFLATED 1 174#define BINARY_LITERAL_DEFLATED 2 175 176/* 177 * This represents a "patch" to a file, both metainfo changes 178 * such as creation/deletion, filemode and content changes represented 179 * as a series of fragments. 180 */ 181struct patch { 182char*new_name, *old_name, *def_name; 183unsigned int old_mode, new_mode; 184int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 185int rejected; 186unsigned ws_rule; 187unsigned long deflate_origlen; 188int lines_added, lines_deleted; 189int score; 190unsigned int is_toplevel_relative:1; 191unsigned int inaccurate_eof:1; 192unsigned int is_binary:1; 193unsigned int is_copy:1; 194unsigned int is_rename:1; 195unsigned int recount:1; 196struct fragment *fragments; 197char*result; 198size_t resultsize; 199char old_sha1_prefix[41]; 200char new_sha1_prefix[41]; 201struct patch *next; 202}; 203 204static voidfree_fragment_list(struct fragment *list) 205{ 206while(list) { 207struct fragment *next = list->next; 208if(list->free_patch) 209free((char*)list->patch); 210free(list); 211 list = next; 212} 213} 214 215static voidfree_patch(struct patch *patch) 216{ 217free_fragment_list(patch->fragments); 218free(patch->def_name); 219free(patch->old_name); 220free(patch->new_name); 221free(patch->result); 222free(patch); 223} 224 225static voidfree_patch_list(struct patch *list) 226{ 227while(list) { 228struct patch *next = list->next; 229free_patch(list); 230 list = next; 231} 232} 233 234/* 235 * A line in a file, len-bytes long (includes the terminating LF, 236 * except for an incomplete line at the end if the file ends with 237 * one), and its contents hashes to 'hash'. 238 */ 239struct line { 240size_t len; 241unsigned hash :24; 242unsigned flag :8; 243#define LINE_COMMON 1 244#define LINE_PATCHED 2 245}; 246 247/* 248 * This represents a "file", which is an array of "lines". 249 */ 250struct image { 251char*buf; 252size_t len; 253size_t nr; 254size_t alloc; 255struct line *line_allocated; 256struct line *line; 257}; 258 259/* 260 * Records filenames that have been touched, in order to handle 261 * the case where more than one patches touch the same file. 262 */ 263 264static struct string_list fn_table; 265 266static uint32_thash_line(const char*cp,size_t len) 267{ 268size_t i; 269uint32_t h; 270for(i =0, h =0; i < len; i++) { 271if(!isspace(cp[i])) { 272 h = h *3+ (cp[i] &0xff); 273} 274} 275return h; 276} 277 278/* 279 * Compare lines s1 of length n1 and s2 of length n2, ignoring 280 * whitespace difference. Returns 1 if they match, 0 otherwise 281 */ 282static intfuzzy_matchlines(const char*s1,size_t n1, 283const char*s2,size_t n2) 284{ 285const char*last1 = s1 + n1 -1; 286const char*last2 = s2 + n2 -1; 287int result =0; 288 289/* ignore line endings */ 290while((*last1 =='\r') || (*last1 =='\n')) 291 last1--; 292while((*last2 =='\r') || (*last2 =='\n')) 293 last2--; 294 295/* skip leading whitespace */ 296while(isspace(*s1) && (s1 <= last1)) 297 s1++; 298while(isspace(*s2) && (s2 <= last2)) 299 s2++; 300/* early return if both lines are empty */ 301if((s1 > last1) && (s2 > last2)) 302return1; 303while(!result) { 304 result = *s1++ - *s2++; 305/* 306 * Skip whitespace inside. We check for whitespace on 307 * both buffers because we don't want "a b" to match 308 * "ab" 309 */ 310if(isspace(*s1) &&isspace(*s2)) { 311while(isspace(*s1) && s1 <= last1) 312 s1++; 313while(isspace(*s2) && s2 <= last2) 314 s2++; 315} 316/* 317 * If we reached the end on one side only, 318 * lines don't match 319 */ 320if( 321((s2 > last2) && (s1 <= last1)) || 322((s1 > last1) && (s2 <= last2))) 323return0; 324if((s1 > last1) && (s2 > last2)) 325break; 326} 327 328return!result; 329} 330 331static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 332{ 333ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 334 img->line_allocated[img->nr].len = len; 335 img->line_allocated[img->nr].hash =hash_line(bol, len); 336 img->line_allocated[img->nr].flag = flag; 337 img->nr++; 338} 339 340/* 341 * "buf" has the file contents to be patched (read from various sources). 342 * attach it to "image" and add line-based index to it. 343 * "image" now owns the "buf". 344 */ 345static voidprepare_image(struct image *image,char*buf,size_t len, 346int prepare_linetable) 347{ 348const char*cp, *ep; 349 350memset(image,0,sizeof(*image)); 351 image->buf = buf; 352 image->len = len; 353 354if(!prepare_linetable) 355return; 356 357 ep = image->buf + image->len; 358 cp = image->buf; 359while(cp < ep) { 360const char*next; 361for(next = cp; next < ep && *next !='\n'; next++) 362; 363if(next < ep) 364 next++; 365add_line_info(image, cp, next - cp,0); 366 cp = next; 367} 368 image->line = image->line_allocated; 369} 370 371static voidclear_image(struct image *image) 372{ 373free(image->buf); 374 image->buf = NULL; 375 image->len =0; 376} 377 378static voidsay_patch_name(FILE*output,const char*pre, 379struct patch *patch,const char*post) 380{ 381fputs(pre, output); 382if(patch->old_name && patch->new_name && 383strcmp(patch->old_name, patch->new_name)) { 384quote_c_style(patch->old_name, NULL, output,0); 385fputs(" => ", output); 386quote_c_style(patch->new_name, NULL, output,0); 387}else{ 388const char*n = patch->new_name; 389if(!n) 390 n = patch->old_name; 391quote_c_style(n, NULL, output,0); 392} 393fputs(post, output); 394} 395 396#define SLOP (16) 397 398static voidread_patch_file(struct strbuf *sb,int fd) 399{ 400if(strbuf_read(sb, fd,0) <0) 401die_errno("git apply: failed to read"); 402 403/* 404 * Make sure that we have some slop in the buffer 405 * so that we can do speculative "memcmp" etc, and 406 * see to it that it is NUL-filled. 407 */ 408strbuf_grow(sb, SLOP); 409memset(sb->buf + sb->len,0, SLOP); 410} 411 412static unsigned longlinelen(const char*buffer,unsigned long size) 413{ 414unsigned long len =0; 415while(size--) { 416 len++; 417if(*buffer++ =='\n') 418break; 419} 420return len; 421} 422 423static intis_dev_null(const char*str) 424{ 425return!memcmp("/dev/null", str,9) &&isspace(str[9]); 426} 427 428#define TERM_SPACE 1 429#define TERM_TAB 2 430 431static intname_terminate(const char*name,int namelen,int c,int terminate) 432{ 433if(c ==' '&& !(terminate & TERM_SPACE)) 434return0; 435if(c =='\t'&& !(terminate & TERM_TAB)) 436return0; 437 438return1; 439} 440 441/* remove double slashes to make --index work with such filenames */ 442static char*squash_slash(char*name) 443{ 444int i =0, j =0; 445 446if(!name) 447return NULL; 448 449while(name[i]) { 450if((name[j++] = name[i++]) =='/') 451while(name[i] =='/') 452 i++; 453} 454 name[j] ='\0'; 455return name; 456} 457 458static char*find_name_gnu(const char*line,const char*def,int p_value) 459{ 460struct strbuf name = STRBUF_INIT; 461char*cp; 462 463/* 464 * Proposed "new-style" GNU patch/diff format; see 465 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2 466 */ 467if(unquote_c_style(&name, line, NULL)) { 468strbuf_release(&name); 469return NULL; 470} 471 472for(cp = name.buf; p_value; p_value--) { 473 cp =strchr(cp,'/'); 474if(!cp) { 475strbuf_release(&name); 476return NULL; 477} 478 cp++; 479} 480 481strbuf_remove(&name,0, cp - name.buf); 482if(root) 483strbuf_insert(&name,0, root, root_len); 484returnsquash_slash(strbuf_detach(&name, NULL)); 485} 486 487static size_tsane_tz_len(const char*line,size_t len) 488{ 489const char*tz, *p; 490 491if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 492return0; 493 tz = line + len -strlen(" +0500"); 494 495if(tz[1] !='+'&& tz[1] !='-') 496return0; 497 498for(p = tz +2; p != line + len; p++) 499if(!isdigit(*p)) 500return0; 501 502return line + len - tz; 503} 504 505static size_ttz_with_colon_len(const char*line,size_t len) 506{ 507const char*tz, *p; 508 509if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 510return0; 511 tz = line + len -strlen(" +08:00"); 512 513if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 514return0; 515 p = tz +2; 516if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 517!isdigit(*p++) || !isdigit(*p++)) 518return0; 519 520return line + len - tz; 521} 522 523static size_tdate_len(const char*line,size_t len) 524{ 525const char*date, *p; 526 527if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 528return0; 529 p = date = line + len -strlen("72-02-05"); 530 531if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 532!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 533!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 534return0; 535 536if(date - line >=strlen("19") && 537isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 538 date -=strlen("19"); 539 540return line + len - date; 541} 542 543static size_tshort_time_len(const char*line,size_t len) 544{ 545const char*time, *p; 546 547if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 548return0; 549 p = time = line + len -strlen(" 07:01:32"); 550 551/* Permit 1-digit hours? */ 552if(*p++ !=' '|| 553!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 554!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 555!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 556return0; 557 558return line + len - time; 559} 560 561static size_tfractional_time_len(const char*line,size_t len) 562{ 563const char*p; 564size_t n; 565 566/* Expected format: 19:41:17.620000023 */ 567if(!len || !isdigit(line[len -1])) 568return0; 569 p = line + len -1; 570 571/* Fractional seconds. */ 572while(p > line &&isdigit(*p)) 573 p--; 574if(*p !='.') 575return0; 576 577/* Hours, minutes, and whole seconds. */ 578 n =short_time_len(line, p - line); 579if(!n) 580return0; 581 582return line + len - p + n; 583} 584 585static size_ttrailing_spaces_len(const char*line,size_t len) 586{ 587const char*p; 588 589/* Expected format: ' ' x (1 or more) */ 590if(!len || line[len -1] !=' ') 591return0; 592 593 p = line + len; 594while(p != line) { 595 p--; 596if(*p !=' ') 597return line + len - (p +1); 598} 599 600/* All spaces! */ 601return len; 602} 603 604static size_tdiff_timestamp_len(const char*line,size_t len) 605{ 606const char*end = line + len; 607size_t n; 608 609/* 610 * Posix: 2010-07-05 19:41:17 611 * GNU: 2010-07-05 19:41:17.620000023 -0500 612 */ 613 614if(!isdigit(end[-1])) 615return0; 616 617 n =sane_tz_len(line, end - line); 618if(!n) 619 n =tz_with_colon_len(line, end - line); 620 end -= n; 621 622 n =short_time_len(line, end - line); 623if(!n) 624 n =fractional_time_len(line, end - line); 625 end -= n; 626 627 n =date_len(line, end - line); 628if(!n)/* No date. Too bad. */ 629return0; 630 end -= n; 631 632if(end == line)/* No space before date. */ 633return0; 634if(end[-1] =='\t') {/* Success! */ 635 end--; 636return line + len - end; 637} 638if(end[-1] !=' ')/* No space before date. */ 639return0; 640 641/* Whitespace damage. */ 642 end -=trailing_spaces_len(line, end - line); 643return line + len - end; 644} 645 646static char*null_strdup(const char*s) 647{ 648return s ?xstrdup(s) : NULL; 649} 650 651static char*find_name_common(const char*line,const char*def, 652int p_value,const char*end,int terminate) 653{ 654int len; 655const char*start = NULL; 656 657if(p_value ==0) 658 start = line; 659while(line != end) { 660char c = *line; 661 662if(!end &&isspace(c)) { 663if(c =='\n') 664break; 665if(name_terminate(start, line-start, c, terminate)) 666break; 667} 668 line++; 669if(c =='/'&& !--p_value) 670 start = line; 671} 672if(!start) 673returnsquash_slash(null_strdup(def)); 674 len = line - start; 675if(!len) 676returnsquash_slash(null_strdup(def)); 677 678/* 679 * Generally we prefer the shorter name, especially 680 * if the other one is just a variation of that with 681 * something else tacked on to the end (ie "file.orig" 682 * or "file~"). 683 */ 684if(def) { 685int deflen =strlen(def); 686if(deflen < len && !strncmp(start, def, deflen)) 687returnsquash_slash(xstrdup(def)); 688} 689 690if(root) { 691char*ret =xmalloc(root_len + len +1); 692strcpy(ret, root); 693memcpy(ret + root_len, start, len); 694 ret[root_len + len] ='\0'; 695returnsquash_slash(ret); 696} 697 698returnsquash_slash(xmemdupz(start, len)); 699} 700 701static char*find_name(const char*line,char*def,int p_value,int terminate) 702{ 703if(*line =='"') { 704char*name =find_name_gnu(line, def, p_value); 705if(name) 706return name; 707} 708 709returnfind_name_common(line, def, p_value, NULL, terminate); 710} 711 712static char*find_name_traditional(const char*line,char*def,int p_value) 713{ 714size_t len =strlen(line); 715size_t date_len; 716 717if(*line =='"') { 718char*name =find_name_gnu(line, def, p_value); 719if(name) 720return name; 721} 722 723 len =strchrnul(line,'\n') - line; 724 date_len =diff_timestamp_len(line, len); 725if(!date_len) 726returnfind_name_common(line, def, p_value, NULL, TERM_TAB); 727 len -= date_len; 728 729returnfind_name_common(line, def, p_value, line + len,0); 730} 731 732static intcount_slashes(const char*cp) 733{ 734int cnt =0; 735char ch; 736 737while((ch = *cp++)) 738if(ch =='/') 739 cnt++; 740return cnt; 741} 742 743/* 744 * Given the string after "--- " or "+++ ", guess the appropriate 745 * p_value for the given patch. 746 */ 747static intguess_p_value(const char*nameline) 748{ 749char*name, *cp; 750int val = -1; 751 752if(is_dev_null(nameline)) 753return-1; 754 name =find_name_traditional(nameline, NULL,0); 755if(!name) 756return-1; 757 cp =strchr(name,'/'); 758if(!cp) 759 val =0; 760else if(prefix) { 761/* 762 * Does it begin with "a/$our-prefix" and such? Then this is 763 * very likely to apply to our directory. 764 */ 765if(!strncmp(name, prefix, prefix_length)) 766 val =count_slashes(prefix); 767else{ 768 cp++; 769if(!strncmp(cp, prefix, prefix_length)) 770 val =count_slashes(prefix) +1; 771} 772} 773free(name); 774return val; 775} 776 777/* 778 * Does the ---/+++ line has the POSIX timestamp after the last HT? 779 * GNU diff puts epoch there to signal a creation/deletion event. Is 780 * this such a timestamp? 781 */ 782static inthas_epoch_timestamp(const char*nameline) 783{ 784/* 785 * We are only interested in epoch timestamp; any non-zero 786 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 787 * For the same reason, the date must be either 1969-12-31 or 788 * 1970-01-01, and the seconds part must be "00". 789 */ 790const char stamp_regexp[] = 791"^(1969-12-31|1970-01-01)" 792" " 793"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 794" " 795"([-+][0-2][0-9]:?[0-5][0-9])\n"; 796const char*timestamp = NULL, *cp, *colon; 797static regex_t *stamp; 798 regmatch_t m[10]; 799int zoneoffset; 800int hourminute; 801int status; 802 803for(cp = nameline; *cp !='\n'; cp++) { 804if(*cp =='\t') 805 timestamp = cp +1; 806} 807if(!timestamp) 808return0; 809if(!stamp) { 810 stamp =xmalloc(sizeof(*stamp)); 811if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 812warning("Cannot prepare timestamp regexp%s", 813 stamp_regexp); 814return0; 815} 816} 817 818 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 819if(status) { 820if(status != REG_NOMATCH) 821warning("regexec returned%dfor input:%s", 822 status, timestamp); 823return0; 824} 825 826 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 827if(*colon ==':') 828 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 829else 830 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 831if(timestamp[m[3].rm_so] =='-') 832 zoneoffset = -zoneoffset; 833 834/* 835 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 836 * (west of GMT) or 1970-01-01 (east of GMT) 837 */ 838if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 839(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 840return0; 841 842 hourminute = (strtol(timestamp +11, NULL,10) *60+ 843strtol(timestamp +14, NULL,10) - 844 zoneoffset); 845 846return((zoneoffset <0&& hourminute ==1440) || 847(0<= zoneoffset && !hourminute)); 848} 849 850/* 851 * Get the name etc info from the ---/+++ lines of a traditional patch header 852 * 853 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 854 * files, we can happily check the index for a match, but for creating a 855 * new file we should try to match whatever "patch" does. I have no idea. 856 */ 857static voidparse_traditional_patch(const char*first,const char*second,struct patch *patch) 858{ 859char*name; 860 861 first +=4;/* skip "--- " */ 862 second +=4;/* skip "+++ " */ 863if(!p_value_known) { 864int p, q; 865 p =guess_p_value(first); 866 q =guess_p_value(second); 867if(p <0) p = q; 868if(0<= p && p == q) { 869 p_value = p; 870 p_value_known =1; 871} 872} 873if(is_dev_null(first)) { 874 patch->is_new =1; 875 patch->is_delete =0; 876 name =find_name_traditional(second, NULL, p_value); 877 patch->new_name = name; 878}else if(is_dev_null(second)) { 879 patch->is_new =0; 880 patch->is_delete =1; 881 name =find_name_traditional(first, NULL, p_value); 882 patch->old_name = name; 883}else{ 884char*first_name; 885 first_name =find_name_traditional(first, NULL, p_value); 886 name =find_name_traditional(second, first_name, p_value); 887free(first_name); 888if(has_epoch_timestamp(first)) { 889 patch->is_new =1; 890 patch->is_delete =0; 891 patch->new_name = name; 892}else if(has_epoch_timestamp(second)) { 893 patch->is_new =0; 894 patch->is_delete =1; 895 patch->old_name = name; 896}else{ 897 patch->old_name = name; 898 patch->new_name =xstrdup(name); 899} 900} 901if(!name) 902die("unable to find filename in patch at line%d", linenr); 903} 904 905static intgitdiff_hdrend(const char*line,struct patch *patch) 906{ 907return-1; 908} 909 910/* 911 * We're anal about diff header consistency, to make 912 * sure that we don't end up having strange ambiguous 913 * patches floating around. 914 * 915 * As a result, gitdiff_{old|new}name() will check 916 * their names against any previous information, just 917 * to make sure.. 918 */ 919static char*gitdiff_verify_name(const char*line,int isnull,char*orig_name,const char*oldnew) 920{ 921if(!orig_name && !isnull) 922returnfind_name(line, NULL, p_value, TERM_TAB); 923 924if(orig_name) { 925int len; 926const char*name; 927char*another; 928 name = orig_name; 929 len =strlen(name); 930if(isnull) 931die("git apply: bad git-diff - expected /dev/null, got%son line%d", name, linenr); 932 another =find_name(line, NULL, p_value, TERM_TAB); 933if(!another ||memcmp(another, name, len +1)) 934die("git apply: bad git-diff - inconsistent%sfilename on line%d", oldnew, linenr); 935free(another); 936return orig_name; 937} 938else{ 939/* expect "/dev/null" */ 940if(memcmp("/dev/null", line,9) || line[9] !='\n') 941die("git apply: bad git-diff - expected /dev/null on line%d", linenr); 942return NULL; 943} 944} 945 946static intgitdiff_oldname(const char*line,struct patch *patch) 947{ 948char*orig = patch->old_name; 949 patch->old_name =gitdiff_verify_name(line, patch->is_new, patch->old_name,"old"); 950if(orig != patch->old_name) 951free(orig); 952return0; 953} 954 955static intgitdiff_newname(const char*line,struct patch *patch) 956{ 957char*orig = patch->new_name; 958 patch->new_name =gitdiff_verify_name(line, patch->is_delete, patch->new_name,"new"); 959if(orig != patch->new_name) 960free(orig); 961return0; 962} 963 964static intgitdiff_oldmode(const char*line,struct patch *patch) 965{ 966 patch->old_mode =strtoul(line, NULL,8); 967return0; 968} 969 970static intgitdiff_newmode(const char*line,struct patch *patch) 971{ 972 patch->new_mode =strtoul(line, NULL,8); 973return0; 974} 975 976static intgitdiff_delete(const char*line,struct patch *patch) 977{ 978 patch->is_delete =1; 979free(patch->old_name); 980 patch->old_name =null_strdup(patch->def_name); 981returngitdiff_oldmode(line, patch); 982} 983 984static intgitdiff_newfile(const char*line,struct patch *patch) 985{ 986 patch->is_new =1; 987free(patch->new_name); 988 patch->new_name =null_strdup(patch->def_name); 989returngitdiff_newmode(line, patch); 990} 991 992static intgitdiff_copysrc(const char*line,struct patch *patch) 993{ 994 patch->is_copy =1; 995free(patch->old_name); 996 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0); 997return0; 998} 9991000static intgitdiff_copydst(const char*line,struct patch *patch)1001{1002 patch->is_copy =1;1003free(patch->new_name);1004 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0);1005return0;1006}10071008static intgitdiff_renamesrc(const char*line,struct patch *patch)1009{1010 patch->is_rename =1;1011free(patch->old_name);1012 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0);1013return0;1014}10151016static intgitdiff_renamedst(const char*line,struct patch *patch)1017{1018 patch->is_rename =1;1019free(patch->new_name);1020 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0);1021return0;1022}10231024static intgitdiff_similarity(const char*line,struct patch *patch)1025{1026if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX)1027 patch->score =0;1028return0;1029}10301031static intgitdiff_dissimilarity(const char*line,struct patch *patch)1032{1033if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX)1034 patch->score =0;1035return0;1036}10371038static intgitdiff_index(const char*line,struct patch *patch)1039{1040/*1041 * index line is N hexadecimal, "..", N hexadecimal,1042 * and optional space with octal mode.1043 */1044const char*ptr, *eol;1045int len;10461047 ptr =strchr(line,'.');1048if(!ptr || ptr[1] !='.'||40< ptr - line)1049return0;1050 len = ptr - line;1051memcpy(patch->old_sha1_prefix, line, len);1052 patch->old_sha1_prefix[len] =0;10531054 line = ptr +2;1055 ptr =strchr(line,' ');1056 eol =strchr(line,'\n');10571058if(!ptr || eol < ptr)1059 ptr = eol;1060 len = ptr - line;10611062if(40< len)1063return0;1064memcpy(patch->new_sha1_prefix, line, len);1065 patch->new_sha1_prefix[len] =0;1066if(*ptr ==' ')1067 patch->old_mode =strtoul(ptr+1, NULL,8);1068return0;1069}10701071/*1072 * This is normal for a diff that doesn't change anything: we'll fall through1073 * into the next diff. Tell the parser to break out.1074 */1075static intgitdiff_unrecognized(const char*line,struct patch *patch)1076{1077return-1;1078}10791080static const char*stop_at_slash(const char*line,int llen)1081{1082int nslash = p_value;1083int i;10841085for(i =0; i < llen; i++) {1086int ch = line[i];1087if(ch =='/'&& --nslash <=0)1088return&line[i];1089}1090return NULL;1091}10921093/*1094 * This is to extract the same name that appears on "diff --git"1095 * line. We do not find and return anything if it is a rename1096 * patch, and it is OK because we will find the name elsewhere.1097 * We need to reliably find name only when it is mode-change only,1098 * creation or deletion of an empty file. In any of these cases,1099 * both sides are the same name under a/ and b/ respectively.1100 */1101static char*git_header_name(const char*line,int llen)1102{1103const char*name;1104const char*second = NULL;1105size_t len, line_len;11061107 line +=strlen("diff --git ");1108 llen -=strlen("diff --git ");11091110if(*line =='"') {1111const char*cp;1112struct strbuf first = STRBUF_INIT;1113struct strbuf sp = STRBUF_INIT;11141115if(unquote_c_style(&first, line, &second))1116goto free_and_fail1;11171118/* advance to the first slash */1119 cp =stop_at_slash(first.buf, first.len);1120/* we do not accept absolute paths */1121if(!cp || cp == first.buf)1122goto free_and_fail1;1123strbuf_remove(&first,0, cp +1- first.buf);11241125/*1126 * second points at one past closing dq of name.1127 * find the second name.1128 */1129while((second < line + llen) &&isspace(*second))1130 second++;11311132if(line + llen <= second)1133goto free_and_fail1;1134if(*second =='"') {1135if(unquote_c_style(&sp, second, NULL))1136goto free_and_fail1;1137 cp =stop_at_slash(sp.buf, sp.len);1138if(!cp || cp == sp.buf)1139goto free_and_fail1;1140/* They must match, otherwise ignore */1141if(strcmp(cp +1, first.buf))1142goto free_and_fail1;1143strbuf_release(&sp);1144returnstrbuf_detach(&first, NULL);1145}11461147/* unquoted second */1148 cp =stop_at_slash(second, line + llen - second);1149if(!cp || cp == second)1150goto free_and_fail1;1151 cp++;1152if(line + llen - cp != first.len +1||1153memcmp(first.buf, cp, first.len))1154goto free_and_fail1;1155returnstrbuf_detach(&first, NULL);11561157 free_and_fail1:1158strbuf_release(&first);1159strbuf_release(&sp);1160return NULL;1161}11621163/* unquoted first name */1164 name =stop_at_slash(line, llen);1165if(!name || name == line)1166return NULL;1167 name++;11681169/*1170 * since the first name is unquoted, a dq if exists must be1171 * the beginning of the second name.1172 */1173for(second = name; second < line + llen; second++) {1174if(*second =='"') {1175struct strbuf sp = STRBUF_INIT;1176const char*np;11771178if(unquote_c_style(&sp, second, NULL))1179goto free_and_fail2;11801181 np =stop_at_slash(sp.buf, sp.len);1182if(!np || np == sp.buf)1183goto free_and_fail2;1184 np++;11851186 len = sp.buf + sp.len - np;1187if(len < second - name &&1188!strncmp(np, name, len) &&1189isspace(name[len])) {1190/* Good */1191strbuf_remove(&sp,0, np - sp.buf);1192returnstrbuf_detach(&sp, NULL);1193}11941195 free_and_fail2:1196strbuf_release(&sp);1197return NULL;1198}1199}12001201/*1202 * Accept a name only if it shows up twice, exactly the same1203 * form.1204 */1205 second =strchr(name,'\n');1206if(!second)1207return NULL;1208 line_len = second - name;1209for(len =0; ; len++) {1210switch(name[len]) {1211default:1212continue;1213case'\n':1214return NULL;1215case'\t':case' ':1216 second =stop_at_slash(name + len, line_len - len);1217if(!second)1218return NULL;1219 second++;1220if(second[len] =='\n'&& !strncmp(name, second, len)) {1221returnxmemdupz(name, len);1222}1223}1224}1225}12261227/* Verify that we recognize the lines following a git header */1228static intparse_git_header(const char*line,int len,unsigned int size,struct patch *patch)1229{1230unsigned long offset;12311232/* A git diff has explicit new/delete information, so we don't guess */1233 patch->is_new =0;1234 patch->is_delete =0;12351236/*1237 * Some things may not have the old name in the1238 * rest of the headers anywhere (pure mode changes,1239 * or removing or adding empty files), so we get1240 * the default name from the header.1241 */1242 patch->def_name =git_header_name(line, len);1243if(patch->def_name && root) {1244char*s =xmalloc(root_len +strlen(patch->def_name) +1);1245strcpy(s, root);1246strcpy(s + root_len, patch->def_name);1247free(patch->def_name);1248 patch->def_name = s;1249}12501251 line += len;1252 size -= len;1253 linenr++;1254for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) {1255static const struct opentry {1256const char*str;1257int(*fn)(const char*,struct patch *);1258} optable[] = {1259{"@@ -", gitdiff_hdrend },1260{"--- ", gitdiff_oldname },1261{"+++ ", gitdiff_newname },1262{"old mode ", gitdiff_oldmode },1263{"new mode ", gitdiff_newmode },1264{"deleted file mode ", gitdiff_delete },1265{"new file mode ", gitdiff_newfile },1266{"copy from ", gitdiff_copysrc },1267{"copy to ", gitdiff_copydst },1268{"rename old ", gitdiff_renamesrc },1269{"rename new ", gitdiff_renamedst },1270{"rename from ", gitdiff_renamesrc },1271{"rename to ", gitdiff_renamedst },1272{"similarity index ", gitdiff_similarity },1273{"dissimilarity index ", gitdiff_dissimilarity },1274{"index ", gitdiff_index },1275{"", gitdiff_unrecognized },1276};1277int i;12781279 len =linelen(line, size);1280if(!len || line[len-1] !='\n')1281break;1282for(i =0; i <ARRAY_SIZE(optable); i++) {1283const struct opentry *p = optable + i;1284int oplen =strlen(p->str);1285if(len < oplen ||memcmp(p->str, line, oplen))1286continue;1287if(p->fn(line + oplen, patch) <0)1288return offset;1289break;1290}1291}12921293return offset;1294}12951296static intparse_num(const char*line,unsigned long*p)1297{1298char*ptr;12991300if(!isdigit(*line))1301return0;1302*p =strtoul(line, &ptr,10);1303return ptr - line;1304}13051306static intparse_range(const char*line,int len,int offset,const char*expect,1307unsigned long*p1,unsigned long*p2)1308{1309int digits, ex;13101311if(offset <0|| offset >= len)1312return-1;1313 line += offset;1314 len -= offset;13151316 digits =parse_num(line, p1);1317if(!digits)1318return-1;13191320 offset += digits;1321 line += digits;1322 len -= digits;13231324*p2 =1;1325if(*line ==',') {1326 digits =parse_num(line+1, p2);1327if(!digits)1328return-1;13291330 offset += digits+1;1331 line += digits+1;1332 len -= digits+1;1333}13341335 ex =strlen(expect);1336if(ex > len)1337return-1;1338if(memcmp(line, expect, ex))1339return-1;13401341return offset + ex;1342}13431344static voidrecount_diff(const char*line,int size,struct fragment *fragment)1345{1346int oldlines =0, newlines =0, ret =0;13471348if(size <1) {1349warning("recount: ignore empty hunk");1350return;1351}13521353for(;;) {1354int len =linelen(line, size);1355 size -= len;1356 line += len;13571358if(size <1)1359break;13601361switch(*line) {1362case' ':case'\n':1363 newlines++;1364/* fall through */1365case'-':1366 oldlines++;1367continue;1368case'+':1369 newlines++;1370continue;1371case'\\':1372continue;1373case'@':1374 ret = size <3||prefixcmp(line,"@@ ");1375break;1376case'd':1377 ret = size <5||prefixcmp(line,"diff ");1378break;1379default:1380 ret = -1;1381break;1382}1383if(ret) {1384warning("recount: unexpected line: %.*s",1385(int)linelen(line, size), line);1386return;1387}1388break;1389}1390 fragment->oldlines = oldlines;1391 fragment->newlines = newlines;1392}13931394/*1395 * Parse a unified diff fragment header of the1396 * form "@@ -a,b +c,d @@"1397 */1398static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1399{1400int offset;14011402if(!len || line[len-1] !='\n')1403return-1;14041405/* Figure out the number of lines in a fragment */1406 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1407 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14081409return offset;1410}14111412static intfind_header(const char*line,unsigned long size,int*hdrsize,struct patch *patch)1413{1414unsigned long offset, len;14151416 patch->is_toplevel_relative =0;1417 patch->is_rename = patch->is_copy =0;1418 patch->is_new = patch->is_delete = -1;1419 patch->old_mode = patch->new_mode =0;1420 patch->old_name = patch->new_name = NULL;1421for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) {1422unsigned long nextlen;14231424 len =linelen(line, size);1425if(!len)1426break;14271428/* Testing this early allows us to take a few shortcuts.. */1429if(len <6)1430continue;14311432/*1433 * Make sure we don't find any unconnected patch fragments.1434 * That's a sign that we didn't find a header, and that a1435 * patch has become corrupted/broken up.1436 */1437if(!memcmp("@@ -", line,4)) {1438struct fragment dummy;1439if(parse_fragment_header(line, len, &dummy) <0)1440continue;1441die("patch fragment without header at line%d: %.*s",1442 linenr, (int)len-1, line);1443}14441445if(size < len +6)1446break;14471448/*1449 * Git patch? It might not have a real patch, just a rename1450 * or mode change, so we handle that specially1451 */1452if(!memcmp("diff --git ", line,11)) {1453int git_hdr_len =parse_git_header(line, len, size, patch);1454if(git_hdr_len <= len)1455continue;1456if(!patch->old_name && !patch->new_name) {1457if(!patch->def_name)1458die("git diff header lacks filename information when removing "1459"%dleading pathname components (line%d)", p_value, linenr);1460 patch->old_name =xstrdup(patch->def_name);1461 patch->new_name =xstrdup(patch->def_name);1462}1463if(!patch->is_delete && !patch->new_name)1464die("git diff header lacks filename information "1465"(line%d)", linenr);1466 patch->is_toplevel_relative =1;1467*hdrsize = git_hdr_len;1468return offset;1469}14701471/* --- followed by +++ ? */1472if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1473continue;14741475/*1476 * We only accept unified patches, so we want it to1477 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1478 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1479 */1480 nextlen =linelen(line + len, size - len);1481if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1482continue;14831484/* Ok, we'll consider it a patch */1485parse_traditional_patch(line, line+len, patch);1486*hdrsize = len + nextlen;1487 linenr +=2;1488return offset;1489}1490return-1;1491}14921493static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1494{1495char*err;14961497if(!result)1498return;14991500 whitespace_error++;1501if(squelch_whitespace_errors &&1502 squelch_whitespace_errors < whitespace_error)1503return;15041505 err =whitespace_error_string(result);1506fprintf(stderr,"%s:%d:%s.\n%.*s\n",1507 patch_input_file, linenr, err, len, line);1508free(err);1509}15101511static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1512{1513unsigned result =ws_check(line +1, len -1, ws_rule);15141515record_ws_error(result, line +1, len -2, linenr);1516}15171518/*1519 * Parse a unified diff. Note that this really needs to parse each1520 * fragment separately, since the only way to know the difference1521 * between a "---" that is part of a patch, and a "---" that starts1522 * the next patch is to look at the line counts..1523 */1524static intparse_fragment(const char*line,unsigned long size,1525struct patch *patch,struct fragment *fragment)1526{1527int added, deleted;1528int len =linelen(line, size), offset;1529unsigned long oldlines, newlines;1530unsigned long leading, trailing;15311532 offset =parse_fragment_header(line, len, fragment);1533if(offset <0)1534return-1;1535if(offset >0&& patch->recount)1536recount_diff(line + offset, size - offset, fragment);1537 oldlines = fragment->oldlines;1538 newlines = fragment->newlines;1539 leading =0;1540 trailing =0;15411542/* Parse the thing.. */1543 line += len;1544 size -= len;1545 linenr++;1546 added = deleted =0;1547for(offset = len;15480< size;1549 offset += len, size -= len, line += len, linenr++) {1550if(!oldlines && !newlines)1551break;1552 len =linelen(line, size);1553if(!len || line[len-1] !='\n')1554return-1;1555switch(*line) {1556default:1557return-1;1558case'\n':/* newer GNU diff, an empty context line */1559case' ':1560 oldlines--;1561 newlines--;1562if(!deleted && !added)1563 leading++;1564 trailing++;1565break;1566case'-':1567if(apply_in_reverse &&1568 ws_error_action != nowarn_ws_error)1569check_whitespace(line, len, patch->ws_rule);1570 deleted++;1571 oldlines--;1572 trailing =0;1573break;1574case'+':1575if(!apply_in_reverse &&1576 ws_error_action != nowarn_ws_error)1577check_whitespace(line, len, patch->ws_rule);1578 added++;1579 newlines--;1580 trailing =0;1581break;15821583/*1584 * We allow "\ No newline at end of file". Depending1585 * on locale settings when the patch was produced we1586 * don't know what this line looks like. The only1587 * thing we do know is that it begins with "\ ".1588 * Checking for 12 is just for sanity check -- any1589 * l10n of "\ No newline..." is at least that long.1590 */1591case'\\':1592if(len <12||memcmp(line,"\\",2))1593return-1;1594break;1595}1596}1597if(oldlines || newlines)1598return-1;1599 fragment->leading = leading;1600 fragment->trailing = trailing;16011602/*1603 * If a fragment ends with an incomplete line, we failed to include1604 * it in the above loop because we hit oldlines == newlines == 01605 * before seeing it.1606 */1607if(12< size && !memcmp(line,"\\",2))1608 offset +=linelen(line, size);16091610 patch->lines_added += added;1611 patch->lines_deleted += deleted;16121613if(0< patch->is_new && oldlines)1614returnerror("new file depends on old contents");1615if(0< patch->is_delete && newlines)1616returnerror("deleted file still has contents");1617return offset;1618}16191620/*1621 * We have seen "diff --git a/... b/..." header (or a traditional patch1622 * header). Read hunks that belong to this patch into fragments and hang1623 * them to the given patch structure.1624 *1625 * The (fragment->patch, fragment->size) pair points into the memory given1626 * by the caller, not a copy, when we return.1627 */1628static intparse_single_patch(const char*line,unsigned long size,struct patch *patch)1629{1630unsigned long offset =0;1631unsigned long oldlines =0, newlines =0, context =0;1632struct fragment **fragp = &patch->fragments;16331634while(size >4&& !memcmp(line,"@@ -",4)) {1635struct fragment *fragment;1636int len;16371638 fragment =xcalloc(1,sizeof(*fragment));1639 fragment->linenr = linenr;1640 len =parse_fragment(line, size, patch, fragment);1641if(len <=0)1642die("corrupt patch at line%d", linenr);1643 fragment->patch = line;1644 fragment->size = len;1645 oldlines += fragment->oldlines;1646 newlines += fragment->newlines;1647 context += fragment->leading + fragment->trailing;16481649*fragp = fragment;1650 fragp = &fragment->next;16511652 offset += len;1653 line += len;1654 size -= len;1655}16561657/*1658 * If something was removed (i.e. we have old-lines) it cannot1659 * be creation, and if something was added it cannot be1660 * deletion. However, the reverse is not true; --unified=01661 * patches that only add are not necessarily creation even1662 * though they do not have any old lines, and ones that only1663 * delete are not necessarily deletion.1664 *1665 * Unfortunately, a real creation/deletion patch do _not_ have1666 * any context line by definition, so we cannot safely tell it1667 * apart with --unified=0 insanity. At least if the patch has1668 * more than one hunk it is not creation or deletion.1669 */1670if(patch->is_new <0&&1671(oldlines || (patch->fragments && patch->fragments->next)))1672 patch->is_new =0;1673if(patch->is_delete <0&&1674(newlines || (patch->fragments && patch->fragments->next)))1675 patch->is_delete =0;16761677if(0< patch->is_new && oldlines)1678die("new file%sdepends on old contents", patch->new_name);1679if(0< patch->is_delete && newlines)1680die("deleted file%sstill has contents", patch->old_name);1681if(!patch->is_delete && !newlines && context)1682fprintf(stderr,"** warning: file%sbecomes empty but "1683"is not deleted\n", patch->new_name);16841685return offset;1686}16871688staticinlineintmetadata_changes(struct patch *patch)1689{1690return patch->is_rename >0||1691 patch->is_copy >0||1692 patch->is_new >0||1693 patch->is_delete ||1694(patch->old_mode && patch->new_mode &&1695 patch->old_mode != patch->new_mode);1696}16971698static char*inflate_it(const void*data,unsigned long size,1699unsigned long inflated_size)1700{1701 git_zstream stream;1702void*out;1703int st;17041705memset(&stream,0,sizeof(stream));17061707 stream.next_in = (unsigned char*)data;1708 stream.avail_in = size;1709 stream.next_out = out =xmalloc(inflated_size);1710 stream.avail_out = inflated_size;1711git_inflate_init(&stream);1712 st =git_inflate(&stream, Z_FINISH);1713git_inflate_end(&stream);1714if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1715free(out);1716return NULL;1717}1718return out;1719}17201721/*1722 * Read a binary hunk and return a new fragment; fragment->patch1723 * points at an allocated memory that the caller must free, so1724 * it is marked as "->free_patch = 1".1725 */1726static struct fragment *parse_binary_hunk(char**buf_p,1727unsigned long*sz_p,1728int*status_p,1729int*used_p)1730{1731/*1732 * Expect a line that begins with binary patch method ("literal"1733 * or "delta"), followed by the length of data before deflating.1734 * a sequence of 'length-byte' followed by base-85 encoded data1735 * should follow, terminated by a newline.1736 *1737 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1738 * and we would limit the patch line to 66 characters,1739 * so one line can fit up to 13 groups that would decode1740 * to 52 bytes max. The length byte 'A'-'Z' corresponds1741 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1742 */1743int llen, used;1744unsigned long size = *sz_p;1745char*buffer = *buf_p;1746int patch_method;1747unsigned long origlen;1748char*data = NULL;1749int hunk_size =0;1750struct fragment *frag;17511752 llen =linelen(buffer, size);1753 used = llen;17541755*status_p =0;17561757if(!prefixcmp(buffer,"delta ")) {1758 patch_method = BINARY_DELTA_DEFLATED;1759 origlen =strtoul(buffer +6, NULL,10);1760}1761else if(!prefixcmp(buffer,"literal ")) {1762 patch_method = BINARY_LITERAL_DEFLATED;1763 origlen =strtoul(buffer +8, NULL,10);1764}1765else1766return NULL;17671768 linenr++;1769 buffer += llen;1770while(1) {1771int byte_length, max_byte_length, newsize;1772 llen =linelen(buffer, size);1773 used += llen;1774 linenr++;1775if(llen ==1) {1776/* consume the blank line */1777 buffer++;1778 size--;1779break;1780}1781/*1782 * Minimum line is "A00000\n" which is 7-byte long,1783 * and the line length must be multiple of 5 plus 2.1784 */1785if((llen <7) || (llen-2) %5)1786goto corrupt;1787 max_byte_length = (llen -2) /5*4;1788 byte_length = *buffer;1789if('A'<= byte_length && byte_length <='Z')1790 byte_length = byte_length -'A'+1;1791else if('a'<= byte_length && byte_length <='z')1792 byte_length = byte_length -'a'+27;1793else1794goto corrupt;1795/* if the input length was not multiple of 4, we would1796 * have filler at the end but the filler should never1797 * exceed 3 bytes1798 */1799if(max_byte_length < byte_length ||1800 byte_length <= max_byte_length -4)1801goto corrupt;1802 newsize = hunk_size + byte_length;1803 data =xrealloc(data, newsize);1804if(decode_85(data + hunk_size, buffer +1, byte_length))1805goto corrupt;1806 hunk_size = newsize;1807 buffer += llen;1808 size -= llen;1809}18101811 frag =xcalloc(1,sizeof(*frag));1812 frag->patch =inflate_it(data, hunk_size, origlen);1813 frag->free_patch =1;1814if(!frag->patch)1815goto corrupt;1816free(data);1817 frag->size = origlen;1818*buf_p = buffer;1819*sz_p = size;1820*used_p = used;1821 frag->binary_patch_method = patch_method;1822return frag;18231824 corrupt:1825free(data);1826*status_p = -1;1827error("corrupt binary patch at line%d: %.*s",1828 linenr-1, llen-1, buffer);1829return NULL;1830}18311832static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1833{1834/*1835 * We have read "GIT binary patch\n"; what follows is a line1836 * that says the patch method (currently, either "literal" or1837 * "delta") and the length of data before deflating; a1838 * sequence of 'length-byte' followed by base-85 encoded data1839 * follows.1840 *1841 * When a binary patch is reversible, there is another binary1842 * hunk in the same format, starting with patch method (either1843 * "literal" or "delta") with the length of data, and a sequence1844 * of length-byte + base-85 encoded data, terminated with another1845 * empty line. This data, when applied to the postimage, produces1846 * the preimage.1847 */1848struct fragment *forward;1849struct fragment *reverse;1850int status;1851int used, used_1;18521853 forward =parse_binary_hunk(&buffer, &size, &status, &used);1854if(!forward && !status)1855/* there has to be one hunk (forward hunk) */1856returnerror("unrecognized binary patch at line%d", linenr-1);1857if(status)1858/* otherwise we already gave an error message */1859return status;18601861 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1862if(reverse)1863 used += used_1;1864else if(status) {1865/*1866 * Not having reverse hunk is not an error, but having1867 * a corrupt reverse hunk is.1868 */1869free((void*) forward->patch);1870free(forward);1871return status;1872}1873 forward->next = reverse;1874 patch->fragments = forward;1875 patch->is_binary =1;1876return used;1877}18781879/*1880 * Read the patch text in "buffer" taht extends for "size" bytes; stop1881 * reading after seeing a single patch (i.e. changes to a single file).1882 * Create fragments (i.e. patch hunks) and hang them to the given patch.1883 * Return the number of bytes consumed, so that the caller can call us1884 * again for the next patch.1885 */1886static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1887{1888int hdrsize, patchsize;1889int offset =find_header(buffer, size, &hdrsize, patch);18901891if(offset <0)1892return offset;18931894 patch->ws_rule =whitespace_rule(patch->new_name1895? patch->new_name1896: patch->old_name);18971898 patchsize =parse_single_patch(buffer + offset + hdrsize,1899 size - offset - hdrsize, patch);19001901if(!patchsize) {1902static const char*binhdr[] = {1903"Binary files ",1904"Files ",1905 NULL,1906};1907static const char git_binary[] ="GIT binary patch\n";1908int i;1909int hd = hdrsize + offset;1910unsigned long llen =linelen(buffer + hd, size - hd);19111912if(llen ==sizeof(git_binary) -1&&1913!memcmp(git_binary, buffer + hd, llen)) {1914int used;1915 linenr++;1916 used =parse_binary(buffer + hd + llen,1917 size - hd - llen, patch);1918if(used)1919 patchsize = used + llen;1920else1921 patchsize =0;1922}1923else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1924for(i =0; binhdr[i]; i++) {1925int len =strlen(binhdr[i]);1926if(len < size - hd &&1927!memcmp(binhdr[i], buffer + hd, len)) {1928 linenr++;1929 patch->is_binary =1;1930 patchsize = llen;1931break;1932}1933}1934}19351936/* Empty patch cannot be applied if it is a text patch1937 * without metadata change. A binary patch appears1938 * empty to us here.1939 */1940if((apply || check) &&1941(!patch->is_binary && !metadata_changes(patch)))1942die("patch with only garbage at line%d", linenr);1943}19441945return offset + hdrsize + patchsize;1946}19471948#define swap(a,b) myswap((a),(b),sizeof(a))19491950#define myswap(a, b, size) do { \1951 unsigned char mytmp[size]; \1952 memcpy(mytmp, &a, size); \1953 memcpy(&a, &b, size); \1954 memcpy(&b, mytmp, size); \1955} while (0)19561957static voidreverse_patches(struct patch *p)1958{1959for(; p; p = p->next) {1960struct fragment *frag = p->fragments;19611962swap(p->new_name, p->old_name);1963swap(p->new_mode, p->old_mode);1964swap(p->is_new, p->is_delete);1965swap(p->lines_added, p->lines_deleted);1966swap(p->old_sha1_prefix, p->new_sha1_prefix);19671968for(; frag; frag = frag->next) {1969swap(frag->newpos, frag->oldpos);1970swap(frag->newlines, frag->oldlines);1971}1972}1973}19741975static const char pluses[] =1976"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";1977static const char minuses[]=1978"----------------------------------------------------------------------";19791980static voidshow_stats(struct patch *patch)1981{1982struct strbuf qname = STRBUF_INIT;1983char*cp = patch->new_name ? patch->new_name : patch->old_name;1984int max, add, del;19851986quote_c_style(cp, &qname, NULL,0);19871988/*1989 * "scale" the filename1990 */1991 max = max_len;1992if(max >50)1993 max =50;19941995if(qname.len > max) {1996 cp =strchr(qname.buf + qname.len +3- max,'/');1997if(!cp)1998 cp = qname.buf + qname.len +3- max;1999strbuf_splice(&qname,0, cp - qname.buf,"...",3);2000}20012002if(patch->is_binary) {2003printf(" %-*s | Bin\n", max, qname.buf);2004strbuf_release(&qname);2005return;2006}20072008printf(" %-*s |", max, qname.buf);2009strbuf_release(&qname);20102011/*2012 * scale the add/delete2013 */2014 max = max + max_change >70?70- max : max_change;2015 add = patch->lines_added;2016 del = patch->lines_deleted;20172018if(max_change >0) {2019int total = ((add + del) * max + max_change /2) / max_change;2020 add = (add * max + max_change /2) / max_change;2021 del = total - add;2022}2023printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2024 add, pluses, del, minuses);2025}20262027static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2028{2029switch(st->st_mode & S_IFMT) {2030case S_IFLNK:2031if(strbuf_readlink(buf, path, st->st_size) <0)2032returnerror("unable to read symlink%s", path);2033return0;2034case S_IFREG:2035if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2036returnerror("unable to open or read%s", path);2037convert_to_git(path, buf->buf, buf->len, buf,0);2038return0;2039default:2040return-1;2041}2042}20432044/*2045 * Update the preimage, and the common lines in postimage,2046 * from buffer buf of length len. If postlen is 0 the postimage2047 * is updated in place, otherwise it's updated on a new buffer2048 * of length postlen2049 */20502051static voidupdate_pre_post_images(struct image *preimage,2052struct image *postimage,2053char*buf,2054size_t len,size_t postlen)2055{2056int i, ctx;2057char*new, *old, *fixed;2058struct image fixed_preimage;20592060/*2061 * Update the preimage with whitespace fixes. Note that we2062 * are not losing preimage->buf -- apply_one_fragment() will2063 * free "oldlines".2064 */2065prepare_image(&fixed_preimage, buf, len,1);2066assert(fixed_preimage.nr == preimage->nr);2067for(i =0; i < preimage->nr; i++)2068 fixed_preimage.line[i].flag = preimage->line[i].flag;2069free(preimage->line_allocated);2070*preimage = fixed_preimage;20712072/*2073 * Adjust the common context lines in postimage. This can be2074 * done in-place when we are just doing whitespace fixing,2075 * which does not make the string grow, but needs a new buffer2076 * when ignoring whitespace causes the update, since in this case2077 * we could have e.g. tabs converted to multiple spaces.2078 * We trust the caller to tell us if the update can be done2079 * in place (postlen==0) or not.2080 */2081 old = postimage->buf;2082if(postlen)2083new= postimage->buf =xmalloc(postlen);2084else2085new= old;2086 fixed = preimage->buf;2087for(i = ctx =0; i < postimage->nr; i++) {2088size_t len = postimage->line[i].len;2089if(!(postimage->line[i].flag & LINE_COMMON)) {2090/* an added line -- no counterparts in preimage */2091memmove(new, old, len);2092 old += len;2093new+= len;2094continue;2095}20962097/* a common context -- skip it in the original postimage */2098 old += len;20992100/* and find the corresponding one in the fixed preimage */2101while(ctx < preimage->nr &&2102!(preimage->line[ctx].flag & LINE_COMMON)) {2103 fixed += preimage->line[ctx].len;2104 ctx++;2105}2106if(preimage->nr <= ctx)2107die("oops");21082109/* and copy it in, while fixing the line length */2110 len = preimage->line[ctx].len;2111memcpy(new, fixed, len);2112new+= len;2113 fixed += len;2114 postimage->line[i].len = len;2115 ctx++;2116}21172118/* Fix the length of the whole thing */2119 postimage->len =new- postimage->buf;2120}21212122static intmatch_fragment(struct image *img,2123struct image *preimage,2124struct image *postimage,2125unsigned longtry,2126int try_lno,2127unsigned ws_rule,2128int match_beginning,int match_end)2129{2130int i;2131char*fixed_buf, *buf, *orig, *target;2132struct strbuf fixed;2133size_t fixed_len;2134int preimage_limit;21352136if(preimage->nr + try_lno <= img->nr) {2137/*2138 * The hunk falls within the boundaries of img.2139 */2140 preimage_limit = preimage->nr;2141if(match_end && (preimage->nr + try_lno != img->nr))2142return0;2143}else if(ws_error_action == correct_ws_error &&2144(ws_rule & WS_BLANK_AT_EOF)) {2145/*2146 * This hunk extends beyond the end of img, and we are2147 * removing blank lines at the end of the file. This2148 * many lines from the beginning of the preimage must2149 * match with img, and the remainder of the preimage2150 * must be blank.2151 */2152 preimage_limit = img->nr - try_lno;2153}else{2154/*2155 * The hunk extends beyond the end of the img and2156 * we are not removing blanks at the end, so we2157 * should reject the hunk at this position.2158 */2159return0;2160}21612162if(match_beginning && try_lno)2163return0;21642165/* Quick hash check */2166for(i =0; i < preimage_limit; i++)2167if((img->line[try_lno + i].flag & LINE_PATCHED) ||2168(preimage->line[i].hash != img->line[try_lno + i].hash))2169return0;21702171if(preimage_limit == preimage->nr) {2172/*2173 * Do we have an exact match? If we were told to match2174 * at the end, size must be exactly at try+fragsize,2175 * otherwise try+fragsize must be still within the preimage,2176 * and either case, the old piece should match the preimage2177 * exactly.2178 */2179if((match_end2180? (try+ preimage->len == img->len)2181: (try+ preimage->len <= img->len)) &&2182!memcmp(img->buf +try, preimage->buf, preimage->len))2183return1;2184}else{2185/*2186 * The preimage extends beyond the end of img, so2187 * there cannot be an exact match.2188 *2189 * There must be one non-blank context line that match2190 * a line before the end of img.2191 */2192char*buf_end;21932194 buf = preimage->buf;2195 buf_end = buf;2196for(i =0; i < preimage_limit; i++)2197 buf_end += preimage->line[i].len;21982199for( ; buf < buf_end; buf++)2200if(!isspace(*buf))2201break;2202if(buf == buf_end)2203return0;2204}22052206/*2207 * No exact match. If we are ignoring whitespace, run a line-by-line2208 * fuzzy matching. We collect all the line length information because2209 * we need it to adjust whitespace if we match.2210 */2211if(ws_ignore_action == ignore_ws_change) {2212size_t imgoff =0;2213size_t preoff =0;2214size_t postlen = postimage->len;2215size_t extra_chars;2216char*preimage_eof;2217char*preimage_end;2218for(i =0; i < preimage_limit; i++) {2219size_t prelen = preimage->line[i].len;2220size_t imglen = img->line[try_lno+i].len;22212222if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2223 preimage->buf + preoff, prelen))2224return0;2225if(preimage->line[i].flag & LINE_COMMON)2226 postlen += imglen - prelen;2227 imgoff += imglen;2228 preoff += prelen;2229}22302231/*2232 * Ok, the preimage matches with whitespace fuzz.2233 *2234 * imgoff now holds the true length of the target that2235 * matches the preimage before the end of the file.2236 *2237 * Count the number of characters in the preimage that fall2238 * beyond the end of the file and make sure that all of them2239 * are whitespace characters. (This can only happen if2240 * we are removing blank lines at the end of the file.)2241 */2242 buf = preimage_eof = preimage->buf + preoff;2243for( ; i < preimage->nr; i++)2244 preoff += preimage->line[i].len;2245 preimage_end = preimage->buf + preoff;2246for( ; buf < preimage_end; buf++)2247if(!isspace(*buf))2248return0;22492250/*2251 * Update the preimage and the common postimage context2252 * lines to use the same whitespace as the target.2253 * If whitespace is missing in the target (i.e.2254 * if the preimage extends beyond the end of the file),2255 * use the whitespace from the preimage.2256 */2257 extra_chars = preimage_end - preimage_eof;2258strbuf_init(&fixed, imgoff + extra_chars);2259strbuf_add(&fixed, img->buf +try, imgoff);2260strbuf_add(&fixed, preimage_eof, extra_chars);2261 fixed_buf =strbuf_detach(&fixed, &fixed_len);2262update_pre_post_images(preimage, postimage,2263 fixed_buf, fixed_len, postlen);2264return1;2265}22662267if(ws_error_action != correct_ws_error)2268return0;22692270/*2271 * The hunk does not apply byte-by-byte, but the hash says2272 * it might with whitespace fuzz. We haven't been asked to2273 * ignore whitespace, we were asked to correct whitespace2274 * errors, so let's try matching after whitespace correction.2275 *2276 * The preimage may extend beyond the end of the file,2277 * but in this loop we will only handle the part of the2278 * preimage that falls within the file.2279 */2280strbuf_init(&fixed, preimage->len +1);2281 orig = preimage->buf;2282 target = img->buf +try;2283for(i =0; i < preimage_limit; i++) {2284size_t oldlen = preimage->line[i].len;2285size_t tgtlen = img->line[try_lno + i].len;2286size_t fixstart = fixed.len;2287struct strbuf tgtfix;2288int match;22892290/* Try fixing the line in the preimage */2291ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);22922293/* Try fixing the line in the target */2294strbuf_init(&tgtfix, tgtlen);2295ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);22962297/*2298 * If they match, either the preimage was based on2299 * a version before our tree fixed whitespace breakage,2300 * or we are lacking a whitespace-fix patch the tree2301 * the preimage was based on already had (i.e. target2302 * has whitespace breakage, the preimage doesn't).2303 * In either case, we are fixing the whitespace breakages2304 * so we might as well take the fix together with their2305 * real change.2306 */2307 match = (tgtfix.len == fixed.len - fixstart &&2308!memcmp(tgtfix.buf, fixed.buf + fixstart,2309 fixed.len - fixstart));23102311strbuf_release(&tgtfix);2312if(!match)2313goto unmatch_exit;23142315 orig += oldlen;2316 target += tgtlen;2317}231823192320/*2321 * Now handle the lines in the preimage that falls beyond the2322 * end of the file (if any). They will only match if they are2323 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2324 * false).2325 */2326for( ; i < preimage->nr; i++) {2327size_t fixstart = fixed.len;/* start of the fixed preimage */2328size_t oldlen = preimage->line[i].len;2329int j;23302331/* Try fixing the line in the preimage */2332ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);23332334for(j = fixstart; j < fixed.len; j++)2335if(!isspace(fixed.buf[j]))2336goto unmatch_exit;23372338 orig += oldlen;2339}23402341/*2342 * Yes, the preimage is based on an older version that still2343 * has whitespace breakages unfixed, and fixing them makes the2344 * hunk match. Update the context lines in the postimage.2345 */2346 fixed_buf =strbuf_detach(&fixed, &fixed_len);2347update_pre_post_images(preimage, postimage,2348 fixed_buf, fixed_len,0);2349return1;23502351 unmatch_exit:2352strbuf_release(&fixed);2353return0;2354}23552356static intfind_pos(struct image *img,2357struct image *preimage,2358struct image *postimage,2359int line,2360unsigned ws_rule,2361int match_beginning,int match_end)2362{2363int i;2364unsigned long backwards, forwards,try;2365int backwards_lno, forwards_lno, try_lno;23662367/*2368 * If match_beginning or match_end is specified, there is no2369 * point starting from a wrong line that will never match and2370 * wander around and wait for a match at the specified end.2371 */2372if(match_beginning)2373 line =0;2374else if(match_end)2375 line = img->nr - preimage->nr;23762377/*2378 * Because the comparison is unsigned, the following test2379 * will also take care of a negative line number that can2380 * result when match_end and preimage is larger than the target.2381 */2382if((size_t) line > img->nr)2383 line = img->nr;23842385try=0;2386for(i =0; i < line; i++)2387try+= img->line[i].len;23882389/*2390 * There's probably some smart way to do this, but I'll leave2391 * that to the smart and beautiful people. I'm simple and stupid.2392 */2393 backwards =try;2394 backwards_lno = line;2395 forwards =try;2396 forwards_lno = line;2397 try_lno = line;23982399for(i =0; ; i++) {2400if(match_fragment(img, preimage, postimage,2401try, try_lno, ws_rule,2402 match_beginning, match_end))2403return try_lno;24042405 again:2406if(backwards_lno ==0&& forwards_lno == img->nr)2407break;24082409if(i &1) {2410if(backwards_lno ==0) {2411 i++;2412goto again;2413}2414 backwards_lno--;2415 backwards -= img->line[backwards_lno].len;2416try= backwards;2417 try_lno = backwards_lno;2418}else{2419if(forwards_lno == img->nr) {2420 i++;2421goto again;2422}2423 forwards += img->line[forwards_lno].len;2424 forwards_lno++;2425try= forwards;2426 try_lno = forwards_lno;2427}24282429}2430return-1;2431}24322433static voidremove_first_line(struct image *img)2434{2435 img->buf += img->line[0].len;2436 img->len -= img->line[0].len;2437 img->line++;2438 img->nr--;2439}24402441static voidremove_last_line(struct image *img)2442{2443 img->len -= img->line[--img->nr].len;2444}24452446/*2447 * The change from "preimage" and "postimage" has been found to2448 * apply at applied_pos (counts in line numbers) in "img".2449 * Update "img" to remove "preimage" and replace it with "postimage".2450 */2451static voidupdate_image(struct image *img,2452int applied_pos,2453struct image *preimage,2454struct image *postimage)2455{2456/*2457 * remove the copy of preimage at offset in img2458 * and replace it with postimage2459 */2460int i, nr;2461size_t remove_count, insert_count, applied_at =0;2462char*result;2463int preimage_limit;24642465/*2466 * If we are removing blank lines at the end of img,2467 * the preimage may extend beyond the end.2468 * If that is the case, we must be careful only to2469 * remove the part of the preimage that falls within2470 * the boundaries of img. Initialize preimage_limit2471 * to the number of lines in the preimage that falls2472 * within the boundaries.2473 */2474 preimage_limit = preimage->nr;2475if(preimage_limit > img->nr - applied_pos)2476 preimage_limit = img->nr - applied_pos;24772478for(i =0; i < applied_pos; i++)2479 applied_at += img->line[i].len;24802481 remove_count =0;2482for(i =0; i < preimage_limit; i++)2483 remove_count += img->line[applied_pos + i].len;2484 insert_count = postimage->len;24852486/* Adjust the contents */2487 result =xmalloc(img->len + insert_count - remove_count +1);2488memcpy(result, img->buf, applied_at);2489memcpy(result + applied_at, postimage->buf, postimage->len);2490memcpy(result + applied_at + postimage->len,2491 img->buf + (applied_at + remove_count),2492 img->len - (applied_at + remove_count));2493free(img->buf);2494 img->buf = result;2495 img->len += insert_count - remove_count;2496 result[img->len] ='\0';24972498/* Adjust the line table */2499 nr = img->nr + postimage->nr - preimage_limit;2500if(preimage_limit < postimage->nr) {2501/*2502 * NOTE: this knows that we never call remove_first_line()2503 * on anything other than pre/post image.2504 */2505 img->line =xrealloc(img->line, nr *sizeof(*img->line));2506 img->line_allocated = img->line;2507}2508if(preimage_limit != postimage->nr)2509memmove(img->line + applied_pos + postimage->nr,2510 img->line + applied_pos + preimage_limit,2511(img->nr - (applied_pos + preimage_limit)) *2512sizeof(*img->line));2513memcpy(img->line + applied_pos,2514 postimage->line,2515 postimage->nr *sizeof(*img->line));2516if(!allow_overlap)2517for(i =0; i < postimage->nr; i++)2518 img->line[applied_pos + i].flag |= LINE_PATCHED;2519 img->nr = nr;2520}25212522/*2523 * Use the patch-hunk text in "frag" to prepare two images (preimage and2524 * postimage) for the hunk. Find lines that match "preimage" in "img" and2525 * replace the part of "img" with "postimage" text.2526 */2527static intapply_one_fragment(struct image *img,struct fragment *frag,2528int inaccurate_eof,unsigned ws_rule,2529int nth_fragment)2530{2531int match_beginning, match_end;2532const char*patch = frag->patch;2533int size = frag->size;2534char*old, *oldlines;2535struct strbuf newlines;2536int new_blank_lines_at_end =0;2537int found_new_blank_lines_at_end =0;2538int hunk_linenr = frag->linenr;2539unsigned long leading, trailing;2540int pos, applied_pos;2541struct image preimage;2542struct image postimage;25432544memset(&preimage,0,sizeof(preimage));2545memset(&postimage,0,sizeof(postimage));2546 oldlines =xmalloc(size);2547strbuf_init(&newlines, size);25482549 old = oldlines;2550while(size >0) {2551char first;2552int len =linelen(patch, size);2553int plen;2554int added_blank_line =0;2555int is_blank_context =0;2556size_t start;25572558if(!len)2559break;25602561/*2562 * "plen" is how much of the line we should use for2563 * the actual patch data. Normally we just remove the2564 * first character on the line, but if the line is2565 * followed by "\ No newline", then we also remove the2566 * last one (which is the newline, of course).2567 */2568 plen = len -1;2569if(len < size && patch[len] =='\\')2570 plen--;2571 first = *patch;2572if(apply_in_reverse) {2573if(first =='-')2574 first ='+';2575else if(first =='+')2576 first ='-';2577}25782579switch(first) {2580case'\n':2581/* Newer GNU diff, empty context line */2582if(plen <0)2583/* ... followed by '\No newline'; nothing */2584break;2585*old++ ='\n';2586strbuf_addch(&newlines,'\n');2587add_line_info(&preimage,"\n",1, LINE_COMMON);2588add_line_info(&postimage,"\n",1, LINE_COMMON);2589 is_blank_context =1;2590break;2591case' ':2592if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2593ws_blank_line(patch +1, plen, ws_rule))2594 is_blank_context =1;2595case'-':2596memcpy(old, patch +1, plen);2597add_line_info(&preimage, old, plen,2598(first ==' '? LINE_COMMON :0));2599 old += plen;2600if(first =='-')2601break;2602/* Fall-through for ' ' */2603case'+':2604/* --no-add does not add new lines */2605if(first =='+'&& no_add)2606break;26072608 start = newlines.len;2609if(first !='+'||2610!whitespace_error ||2611 ws_error_action != correct_ws_error) {2612strbuf_add(&newlines, patch +1, plen);2613}2614else{2615ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2616}2617add_line_info(&postimage, newlines.buf + start, newlines.len - start,2618(first =='+'?0: LINE_COMMON));2619if(first =='+'&&2620(ws_rule & WS_BLANK_AT_EOF) &&2621ws_blank_line(patch +1, plen, ws_rule))2622 added_blank_line =1;2623break;2624case'@':case'\\':2625/* Ignore it, we already handled it */2626break;2627default:2628if(apply_verbosely)2629error("invalid start of line: '%c'", first);2630return-1;2631}2632if(added_blank_line) {2633if(!new_blank_lines_at_end)2634 found_new_blank_lines_at_end = hunk_linenr;2635 new_blank_lines_at_end++;2636}2637else if(is_blank_context)2638;2639else2640 new_blank_lines_at_end =0;2641 patch += len;2642 size -= len;2643 hunk_linenr++;2644}2645if(inaccurate_eof &&2646 old > oldlines && old[-1] =='\n'&&2647 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2648 old--;2649strbuf_setlen(&newlines, newlines.len -1);2650}26512652 leading = frag->leading;2653 trailing = frag->trailing;26542655/*2656 * A hunk to change lines at the beginning would begin with2657 * @@ -1,L +N,M @@2658 * but we need to be careful. -U0 that inserts before the second2659 * line also has this pattern.2660 *2661 * And a hunk to add to an empty file would begin with2662 * @@ -0,0 +N,M @@2663 *2664 * In other words, a hunk that is (frag->oldpos <= 1) with or2665 * without leading context must match at the beginning.2666 */2667 match_beginning = (!frag->oldpos ||2668(frag->oldpos ==1&& !unidiff_zero));26692670/*2671 * A hunk without trailing lines must match at the end.2672 * However, we simply cannot tell if a hunk must match end2673 * from the lack of trailing lines if the patch was generated2674 * with unidiff without any context.2675 */2676 match_end = !unidiff_zero && !trailing;26772678 pos = frag->newpos ? (frag->newpos -1) :0;2679 preimage.buf = oldlines;2680 preimage.len = old - oldlines;2681 postimage.buf = newlines.buf;2682 postimage.len = newlines.len;2683 preimage.line = preimage.line_allocated;2684 postimage.line = postimage.line_allocated;26852686for(;;) {26872688 applied_pos =find_pos(img, &preimage, &postimage, pos,2689 ws_rule, match_beginning, match_end);26902691if(applied_pos >=0)2692break;26932694/* Am I at my context limits? */2695if((leading <= p_context) && (trailing <= p_context))2696break;2697if(match_beginning || match_end) {2698 match_beginning = match_end =0;2699continue;2700}27012702/*2703 * Reduce the number of context lines; reduce both2704 * leading and trailing if they are equal otherwise2705 * just reduce the larger context.2706 */2707if(leading >= trailing) {2708remove_first_line(&preimage);2709remove_first_line(&postimage);2710 pos--;2711 leading--;2712}2713if(trailing > leading) {2714remove_last_line(&preimage);2715remove_last_line(&postimage);2716 trailing--;2717}2718}27192720if(applied_pos >=0) {2721if(new_blank_lines_at_end &&2722 preimage.nr + applied_pos >= img->nr &&2723(ws_rule & WS_BLANK_AT_EOF) &&2724 ws_error_action != nowarn_ws_error) {2725record_ws_error(WS_BLANK_AT_EOF,"+",1,2726 found_new_blank_lines_at_end);2727if(ws_error_action == correct_ws_error) {2728while(new_blank_lines_at_end--)2729remove_last_line(&postimage);2730}2731/*2732 * We would want to prevent write_out_results()2733 * from taking place in apply_patch() that follows2734 * the callchain led us here, which is:2735 * apply_patch->check_patch_list->check_patch->2736 * apply_data->apply_fragments->apply_one_fragment2737 */2738if(ws_error_action == die_on_ws_error)2739 apply =0;2740}27412742if(apply_verbosely && applied_pos != pos) {2743int offset = applied_pos - pos;2744if(apply_in_reverse)2745 offset =0- offset;2746fprintf(stderr,2747"Hunk #%dsucceeded at%d(offset%dlines).\n",2748 nth_fragment, applied_pos +1, offset);2749}27502751/*2752 * Warn if it was necessary to reduce the number2753 * of context lines.2754 */2755if((leading != frag->leading) ||2756(trailing != frag->trailing))2757fprintf(stderr,"Context reduced to (%ld/%ld)"2758" to apply fragment at%d\n",2759 leading, trailing, applied_pos+1);2760update_image(img, applied_pos, &preimage, &postimage);2761}else{2762if(apply_verbosely)2763error("while searching for:\n%.*s",2764(int)(old - oldlines), oldlines);2765}27662767free(oldlines);2768strbuf_release(&newlines);2769free(preimage.line_allocated);2770free(postimage.line_allocated);27712772return(applied_pos <0);2773}27742775static intapply_binary_fragment(struct image *img,struct patch *patch)2776{2777struct fragment *fragment = patch->fragments;2778unsigned long len;2779void*dst;27802781if(!fragment)2782returnerror("missing binary patch data for '%s'",2783 patch->new_name ?2784 patch->new_name :2785 patch->old_name);27862787/* Binary patch is irreversible without the optional second hunk */2788if(apply_in_reverse) {2789if(!fragment->next)2790returnerror("cannot reverse-apply a binary patch "2791"without the reverse hunk to '%s'",2792 patch->new_name2793? patch->new_name : patch->old_name);2794 fragment = fragment->next;2795}2796switch(fragment->binary_patch_method) {2797case BINARY_DELTA_DEFLATED:2798 dst =patch_delta(img->buf, img->len, fragment->patch,2799 fragment->size, &len);2800if(!dst)2801return-1;2802clear_image(img);2803 img->buf = dst;2804 img->len = len;2805return0;2806case BINARY_LITERAL_DEFLATED:2807clear_image(img);2808 img->len = fragment->size;2809 img->buf =xmalloc(img->len+1);2810memcpy(img->buf, fragment->patch, img->len);2811 img->buf[img->len] ='\0';2812return0;2813}2814return-1;2815}28162817/*2818 * Replace "img" with the result of applying the binary patch.2819 * The binary patch data itself in patch->fragment is still kept2820 * but the preimage prepared by the caller in "img" is freed here2821 * or in the helper function apply_binary_fragment() this calls.2822 */2823static intapply_binary(struct image *img,struct patch *patch)2824{2825const char*name = patch->old_name ? patch->old_name : patch->new_name;2826unsigned char sha1[20];28272828/*2829 * For safety, we require patch index line to contain2830 * full 40-byte textual SHA1 for old and new, at least for now.2831 */2832if(strlen(patch->old_sha1_prefix) !=40||2833strlen(patch->new_sha1_prefix) !=40||2834get_sha1_hex(patch->old_sha1_prefix, sha1) ||2835get_sha1_hex(patch->new_sha1_prefix, sha1))2836returnerror("cannot apply binary patch to '%s' "2837"without full index line", name);28382839if(patch->old_name) {2840/*2841 * See if the old one matches what the patch2842 * applies to.2843 */2844hash_sha1_file(img->buf, img->len, blob_type, sha1);2845if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2846returnerror("the patch applies to '%s' (%s), "2847"which does not match the "2848"current contents.",2849 name,sha1_to_hex(sha1));2850}2851else{2852/* Otherwise, the old one must be empty. */2853if(img->len)2854returnerror("the patch applies to an empty "2855"'%s' but it is not empty", name);2856}28572858get_sha1_hex(patch->new_sha1_prefix, sha1);2859if(is_null_sha1(sha1)) {2860clear_image(img);2861return0;/* deletion patch */2862}28632864if(has_sha1_file(sha1)) {2865/* We already have the postimage */2866enum object_type type;2867unsigned long size;2868char*result;28692870 result =read_sha1_file(sha1, &type, &size);2871if(!result)2872returnerror("the necessary postimage%sfor "2873"'%s' cannot be read",2874 patch->new_sha1_prefix, name);2875clear_image(img);2876 img->buf = result;2877 img->len = size;2878}else{2879/*2880 * We have verified buf matches the preimage;2881 * apply the patch data to it, which is stored2882 * in the patch->fragments->{patch,size}.2883 */2884if(apply_binary_fragment(img, patch))2885returnerror("binary patch does not apply to '%s'",2886 name);28872888/* verify that the result matches */2889hash_sha1_file(img->buf, img->len, blob_type, sha1);2890if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2891returnerror("binary patch to '%s' creates incorrect result (expecting%s, got%s)",2892 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2893}28942895return0;2896}28972898static intapply_fragments(struct image *img,struct patch *patch)2899{2900struct fragment *frag = patch->fragments;2901const char*name = patch->old_name ? patch->old_name : patch->new_name;2902unsigned ws_rule = patch->ws_rule;2903unsigned inaccurate_eof = patch->inaccurate_eof;2904int nth =0;29052906if(patch->is_binary)2907returnapply_binary(img, patch);29082909while(frag) {2910 nth++;2911if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {2912error("patch failed:%s:%ld", name, frag->oldpos);2913if(!apply_with_reject)2914return-1;2915 frag->rejected =1;2916}2917 frag = frag->next;2918}2919return0;2920}29212922static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2923{2924if(!ce)2925return0;29262927if(S_ISGITLINK(ce->ce_mode)) {2928strbuf_grow(buf,100);2929strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2930}else{2931enum object_type type;2932unsigned long sz;2933char*result;29342935 result =read_sha1_file(ce->sha1, &type, &sz);2936if(!result)2937return-1;2938/* XXX read_sha1_file NUL-terminates */2939strbuf_attach(buf, result, sz, sz +1);2940}2941return0;2942}29432944static struct patch *in_fn_table(const char*name)2945{2946struct string_list_item *item;29472948if(name == NULL)2949return NULL;29502951 item =string_list_lookup(&fn_table, name);2952if(item != NULL)2953return(struct patch *)item->util;29542955return NULL;2956}29572958/*2959 * item->util in the filename table records the status of the path.2960 * Usually it points at a patch (whose result records the contents2961 * of it after applying it), but it could be PATH_WAS_DELETED for a2962 * path that a previously applied patch has already removed.2963 */2964#define PATH_TO_BE_DELETED ((struct patch *) -2)2965#define PATH_WAS_DELETED ((struct patch *) -1)29662967static intto_be_deleted(struct patch *patch)2968{2969return patch == PATH_TO_BE_DELETED;2970}29712972static intwas_deleted(struct patch *patch)2973{2974return patch == PATH_WAS_DELETED;2975}29762977static voidadd_to_fn_table(struct patch *patch)2978{2979struct string_list_item *item;29802981/*2982 * Always add new_name unless patch is a deletion2983 * This should cover the cases for normal diffs,2984 * file creations and copies2985 */2986if(patch->new_name != NULL) {2987 item =string_list_insert(&fn_table, patch->new_name);2988 item->util = patch;2989}29902991/*2992 * store a failure on rename/deletion cases because2993 * later chunks shouldn't patch old names2994 */2995if((patch->new_name == NULL) || (patch->is_rename)) {2996 item =string_list_insert(&fn_table, patch->old_name);2997 item->util = PATH_WAS_DELETED;2998}2999}30003001static voidprepare_fn_table(struct patch *patch)3002{3003/*3004 * store information about incoming file deletion3005 */3006while(patch) {3007if((patch->new_name == NULL) || (patch->is_rename)) {3008struct string_list_item *item;3009 item =string_list_insert(&fn_table, patch->old_name);3010 item->util = PATH_TO_BE_DELETED;3011}3012 patch = patch->next;3013}3014}30153016static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)3017{3018struct strbuf buf = STRBUF_INIT;3019struct image image;3020size_t len;3021char*img;3022struct patch *tpatch;30233024if(!(patch->is_copy || patch->is_rename) &&3025(tpatch =in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {3026if(was_deleted(tpatch)) {3027returnerror("patch%shas been renamed/deleted",3028 patch->old_name);3029}3030/* We have a patched copy in memory; use that. */3031strbuf_add(&buf, tpatch->result, tpatch->resultsize);3032}else if(cached) {3033if(read_file_or_gitlink(ce, &buf))3034returnerror("read of%sfailed", patch->old_name);3035}else if(patch->old_name) {3036if(S_ISGITLINK(patch->old_mode)) {3037if(ce) {3038read_file_or_gitlink(ce, &buf);3039}else{3040/*3041 * There is no way to apply subproject3042 * patch without looking at the index.3043 * NEEDSWORK: shouldn't this be flagged3044 * as an error???3045 */3046free_fragment_list(patch->fragments);3047 patch->fragments = NULL;3048}3049}else{3050if(read_old_data(st, patch->old_name, &buf))3051returnerror("read of%sfailed", patch->old_name);3052}3053}30543055 img =strbuf_detach(&buf, &len);3056prepare_image(&image, img, len, !patch->is_binary);30573058if(apply_fragments(&image, patch) <0)3059return-1;/* note with --reject this succeeds. */3060 patch->result = image.buf;3061 patch->resultsize = image.len;3062add_to_fn_table(patch);3063free(image.line_allocated);30643065if(0< patch->is_delete && patch->resultsize)3066returnerror("removal patch leaves file contents");30673068return0;3069}30703071static intcheck_to_create_blob(const char*new_name,int ok_if_exists)3072{3073struct stat nst;3074if(!lstat(new_name, &nst)) {3075if(S_ISDIR(nst.st_mode) || ok_if_exists)3076return0;3077/*3078 * A leading component of new_name might be a symlink3079 * that is going to be removed with this patch, but3080 * still pointing at somewhere that has the path.3081 * In such a case, path "new_name" does not exist as3082 * far as git is concerned.3083 */3084if(has_symlink_leading_path(new_name,strlen(new_name)))3085return0;30863087returnerror("%s: already exists in working directory", new_name);3088}3089else if((errno != ENOENT) && (errno != ENOTDIR))3090returnerror("%s:%s", new_name,strerror(errno));3091return0;3092}30933094static intverify_index_match(struct cache_entry *ce,struct stat *st)3095{3096if(S_ISGITLINK(ce->ce_mode)) {3097if(!S_ISDIR(st->st_mode))3098return-1;3099return0;3100}3101returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3102}31033104static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)3105{3106const char*old_name = patch->old_name;3107struct patch *tpatch = NULL;3108int stat_ret =0;3109unsigned st_mode =0;31103111/*3112 * Make sure that we do not have local modifications from the3113 * index when we are looking at the index. Also make sure3114 * we have the preimage file to be patched in the work tree,3115 * unless --cached, which tells git to apply only in the index.3116 */3117if(!old_name)3118return0;31193120assert(patch->is_new <=0);31213122if(!(patch->is_copy || patch->is_rename) &&3123(tpatch =in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {3124if(was_deleted(tpatch))3125returnerror("%s: has been deleted/renamed", old_name);3126 st_mode = tpatch->new_mode;3127}else if(!cached) {3128 stat_ret =lstat(old_name, st);3129if(stat_ret && errno != ENOENT)3130returnerror("%s:%s", old_name,strerror(errno));3131}31323133if(to_be_deleted(tpatch))3134 tpatch = NULL;31353136if(check_index && !tpatch) {3137int pos =cache_name_pos(old_name,strlen(old_name));3138if(pos <0) {3139if(patch->is_new <0)3140goto is_new;3141returnerror("%s: does not exist in index", old_name);3142}3143*ce = active_cache[pos];3144if(stat_ret <0) {3145struct checkout costate;3146/* checkout */3147memset(&costate,0,sizeof(costate));3148 costate.base_dir ="";3149 costate.refresh_cache =1;3150if(checkout_entry(*ce, &costate, NULL) ||3151lstat(old_name, st))3152return-1;3153}3154if(!cached &&verify_index_match(*ce, st))3155returnerror("%s: does not match index", old_name);3156if(cached)3157 st_mode = (*ce)->ce_mode;3158}else if(stat_ret <0) {3159if(patch->is_new <0)3160goto is_new;3161returnerror("%s:%s", old_name,strerror(errno));3162}31633164if(!cached && !tpatch)3165 st_mode =ce_mode_from_stat(*ce, st->st_mode);31663167if(patch->is_new <0)3168 patch->is_new =0;3169if(!patch->old_mode)3170 patch->old_mode = st_mode;3171if((st_mode ^ patch->old_mode) & S_IFMT)3172returnerror("%s: wrong type", old_name);3173if(st_mode != patch->old_mode)3174warning("%shas type%o, expected%o",3175 old_name, st_mode, patch->old_mode);3176if(!patch->new_mode && !patch->is_delete)3177 patch->new_mode = st_mode;3178return0;31793180 is_new:3181 patch->is_new =1;3182 patch->is_delete =0;3183free(patch->old_name);3184 patch->old_name = NULL;3185return0;3186}31873188/*3189 * Check and apply the patch in-core; leave the result in patch->result3190 * for the caller to write it out to the final destination.3191 */3192static intcheck_patch(struct patch *patch)3193{3194struct stat st;3195const char*old_name = patch->old_name;3196const char*new_name = patch->new_name;3197const char*name = old_name ? old_name : new_name;3198struct cache_entry *ce = NULL;3199struct patch *tpatch;3200int ok_if_exists;3201int status;32023203 patch->rejected =1;/* we will drop this after we succeed */32043205 status =check_preimage(patch, &ce, &st);3206if(status)3207return status;3208 old_name = patch->old_name;32093210if((tpatch =in_fn_table(new_name)) &&3211(was_deleted(tpatch) ||to_be_deleted(tpatch)))3212/*3213 * A type-change diff is always split into a patch to3214 * delete old, immediately followed by a patch to3215 * create new (see diff.c::run_diff()); in such a case3216 * it is Ok that the entry to be deleted by the3217 * previous patch is still in the working tree and in3218 * the index.3219 */3220 ok_if_exists =1;3221else3222 ok_if_exists =0;32233224if(new_name &&3225((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {3226if(check_index &&3227cache_name_pos(new_name,strlen(new_name)) >=0&&3228!ok_if_exists)3229returnerror("%s: already exists in index", new_name);3230if(!cached) {3231int err =check_to_create_blob(new_name, ok_if_exists);3232if(err)3233return err;3234}3235if(!patch->new_mode) {3236if(0< patch->is_new)3237 patch->new_mode = S_IFREG |0644;3238else3239 patch->new_mode = patch->old_mode;3240}3241}32423243if(new_name && old_name) {3244int same = !strcmp(old_name, new_name);3245if(!patch->new_mode)3246 patch->new_mode = patch->old_mode;3247if((patch->old_mode ^ patch->new_mode) & S_IFMT)3248returnerror("new mode (%o) of%sdoes not match old mode (%o)%s%s",3249 patch->new_mode, new_name, patch->old_mode,3250 same ?"":" of ", same ?"": old_name);3251}32523253if(apply_data(patch, &st, ce) <0)3254returnerror("%s: patch does not apply", name);3255 patch->rejected =0;3256return0;3257}32583259static intcheck_patch_list(struct patch *patch)3260{3261int err =0;32623263prepare_fn_table(patch);3264while(patch) {3265if(apply_verbosely)3266say_patch_name(stderr,3267"Checking patch ", patch,"...\n");3268 err |=check_patch(patch);3269 patch = patch->next;3270}3271return err;3272}32733274/* This function tries to read the sha1 from the current index */3275static intget_current_sha1(const char*path,unsigned char*sha1)3276{3277int pos;32783279if(read_cache() <0)3280return-1;3281 pos =cache_name_pos(path,strlen(path));3282if(pos <0)3283return-1;3284hashcpy(sha1, active_cache[pos]->sha1);3285return0;3286}32873288/* Build an index that contains the just the files needed for a 3way merge */3289static voidbuild_fake_ancestor(struct patch *list,const char*filename)3290{3291struct patch *patch;3292struct index_state result = { NULL };3293int fd;32943295/* Once we start supporting the reverse patch, it may be3296 * worth showing the new sha1 prefix, but until then...3297 */3298for(patch = list; patch; patch = patch->next) {3299const unsigned char*sha1_ptr;3300unsigned char sha1[20];3301struct cache_entry *ce;3302const char*name;33033304 name = patch->old_name ? patch->old_name : patch->new_name;3305if(0< patch->is_new)3306continue;3307else if(get_sha1(patch->old_sha1_prefix, sha1))3308/* git diff has no index line for mode/type changes */3309if(!patch->lines_added && !patch->lines_deleted) {3310if(get_current_sha1(patch->old_name, sha1))3311die("mode change for%s, which is not "3312"in current HEAD", name);3313 sha1_ptr = sha1;3314}else3315die("sha1 information is lacking or useless "3316"(%s).", name);3317else3318 sha1_ptr = sha1;33193320 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);3321if(!ce)3322die("make_cache_entry failed for path '%s'", name);3323if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3324die("Could not add%sto temporary index", name);3325}33263327 fd =open(filename, O_WRONLY | O_CREAT,0666);3328if(fd <0||write_index(&result, fd) ||close(fd))3329die("Could not write temporary index to%s", filename);33303331discard_index(&result);3332}33333334static voidstat_patch_list(struct patch *patch)3335{3336int files, adds, dels;33373338for(files = adds = dels =0; patch ; patch = patch->next) {3339 files++;3340 adds += patch->lines_added;3341 dels += patch->lines_deleted;3342show_stats(patch);3343}33443345print_stat_summary(stdout, files, adds, dels);3346}33473348static voidnumstat_patch_list(struct patch *patch)3349{3350for( ; patch; patch = patch->next) {3351const char*name;3352 name = patch->new_name ? patch->new_name : patch->old_name;3353if(patch->is_binary)3354printf("-\t-\t");3355else3356printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3357write_name_quoted(name, stdout, line_termination);3358}3359}33603361static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3362{3363if(mode)3364printf("%smode%06o%s\n", newdelete, mode, name);3365else3366printf("%s %s\n", newdelete, name);3367}33683369static voidshow_mode_change(struct patch *p,int show_name)3370{3371if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3372if(show_name)3373printf(" mode change%06o =>%06o%s\n",3374 p->old_mode, p->new_mode, p->new_name);3375else3376printf(" mode change%06o =>%06o\n",3377 p->old_mode, p->new_mode);3378}3379}33803381static voidshow_rename_copy(struct patch *p)3382{3383const char*renamecopy = p->is_rename ?"rename":"copy";3384const char*old, *new;33853386/* Find common prefix */3387 old = p->old_name;3388new= p->new_name;3389while(1) {3390const char*slash_old, *slash_new;3391 slash_old =strchr(old,'/');3392 slash_new =strchr(new,'/');3393if(!slash_old ||3394!slash_new ||3395 slash_old - old != slash_new -new||3396memcmp(old,new, slash_new -new))3397break;3398 old = slash_old +1;3399new= slash_new +1;3400}3401/* p->old_name thru old is the common prefix, and old and new3402 * through the end of names are renames3403 */3404if(old != p->old_name)3405printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,3406(int)(old - p->old_name), p->old_name,3407 old,new, p->score);3408else3409printf("%s %s=>%s(%d%%)\n", renamecopy,3410 p->old_name, p->new_name, p->score);3411show_mode_change(p,0);3412}34133414static voidsummary_patch_list(struct patch *patch)3415{3416struct patch *p;34173418for(p = patch; p; p = p->next) {3419if(p->is_new)3420show_file_mode_name("create", p->new_mode, p->new_name);3421else if(p->is_delete)3422show_file_mode_name("delete", p->old_mode, p->old_name);3423else{3424if(p->is_rename || p->is_copy)3425show_rename_copy(p);3426else{3427if(p->score) {3428printf(" rewrite%s(%d%%)\n",3429 p->new_name, p->score);3430show_mode_change(p,0);3431}3432else3433show_mode_change(p,1);3434}3435}3436}3437}34383439static voidpatch_stats(struct patch *patch)3440{3441int lines = patch->lines_added + patch->lines_deleted;34423443if(lines > max_change)3444 max_change = lines;3445if(patch->old_name) {3446int len =quote_c_style(patch->old_name, NULL, NULL,0);3447if(!len)3448 len =strlen(patch->old_name);3449if(len > max_len)3450 max_len = len;3451}3452if(patch->new_name) {3453int len =quote_c_style(patch->new_name, NULL, NULL,0);3454if(!len)3455 len =strlen(patch->new_name);3456if(len > max_len)3457 max_len = len;3458}3459}34603461static voidremove_file(struct patch *patch,int rmdir_empty)3462{3463if(update_index) {3464if(remove_file_from_cache(patch->old_name) <0)3465die("unable to remove%sfrom index", patch->old_name);3466}3467if(!cached) {3468if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {3469remove_path(patch->old_name);3470}3471}3472}34733474static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)3475{3476struct stat st;3477struct cache_entry *ce;3478int namelen =strlen(path);3479unsigned ce_size =cache_entry_size(namelen);34803481if(!update_index)3482return;34833484 ce =xcalloc(1, ce_size);3485memcpy(ce->name, path, namelen);3486 ce->ce_mode =create_ce_mode(mode);3487 ce->ce_flags = namelen;3488if(S_ISGITLINK(mode)) {3489const char*s = buf;34903491if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))3492die("corrupt patch for subproject%s", path);3493}else{3494if(!cached) {3495if(lstat(path, &st) <0)3496die_errno("unable to stat newly created file '%s'",3497 path);3498fill_stat_cache_info(ce, &st);3499}3500if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)3501die("unable to create backing store for newly created file%s", path);3502}3503if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3504die("unable to add cache entry for%s", path);3505}35063507static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)3508{3509int fd;3510struct strbuf nbuf = STRBUF_INIT;35113512if(S_ISGITLINK(mode)) {3513struct stat st;3514if(!lstat(path, &st) &&S_ISDIR(st.st_mode))3515return0;3516returnmkdir(path,0777);3517}35183519if(has_symlinks &&S_ISLNK(mode))3520/* Although buf:size is counted string, it also is NUL3521 * terminated.3522 */3523returnsymlink(buf, path);35243525 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);3526if(fd <0)3527return-1;35283529if(convert_to_working_tree(path, buf, size, &nbuf)) {3530 size = nbuf.len;3531 buf = nbuf.buf;3532}3533write_or_die(fd, buf, size);3534strbuf_release(&nbuf);35353536if(close(fd) <0)3537die_errno("closing file '%s'", path);3538return0;3539}35403541/*3542 * We optimistically assume that the directories exist,3543 * which is true 99% of the time anyway. If they don't,3544 * we create them and try again.3545 */3546static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)3547{3548if(cached)3549return;3550if(!try_create_file(path, mode, buf, size))3551return;35523553if(errno == ENOENT) {3554if(safe_create_leading_directories(path))3555return;3556if(!try_create_file(path, mode, buf, size))3557return;3558}35593560if(errno == EEXIST || errno == EACCES) {3561/* We may be trying to create a file where a directory3562 * used to be.3563 */3564struct stat st;3565if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))3566 errno = EEXIST;3567}35683569if(errno == EEXIST) {3570unsigned int nr =getpid();35713572for(;;) {3573char newpath[PATH_MAX];3574mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);3575if(!try_create_file(newpath, mode, buf, size)) {3576if(!rename(newpath, path))3577return;3578unlink_or_warn(newpath);3579break;3580}3581if(errno != EEXIST)3582break;3583++nr;3584}3585}3586die_errno("unable to write file '%s' mode%o", path, mode);3587}35883589static voidcreate_file(struct patch *patch)3590{3591char*path = patch->new_name;3592unsigned mode = patch->new_mode;3593unsigned long size = patch->resultsize;3594char*buf = patch->result;35953596if(!mode)3597 mode = S_IFREG |0644;3598create_one_file(path, mode, buf, size);3599add_index_file(path, mode, buf, size);3600}36013602/* phase zero is to remove, phase one is to create */3603static voidwrite_out_one_result(struct patch *patch,int phase)3604{3605if(patch->is_delete >0) {3606if(phase ==0)3607remove_file(patch,1);3608return;3609}3610if(patch->is_new >0|| patch->is_copy) {3611if(phase ==1)3612create_file(patch);3613return;3614}3615/*3616 * Rename or modification boils down to the same3617 * thing: remove the old, write the new3618 */3619if(phase ==0)3620remove_file(patch, patch->is_rename);3621if(phase ==1)3622create_file(patch);3623}36243625static intwrite_out_one_reject(struct patch *patch)3626{3627FILE*rej;3628char namebuf[PATH_MAX];3629struct fragment *frag;3630int cnt =0;36313632for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {3633if(!frag->rejected)3634continue;3635 cnt++;3636}36373638if(!cnt) {3639if(apply_verbosely)3640say_patch_name(stderr,3641"Applied patch ", patch," cleanly.\n");3642return0;3643}36443645/* This should not happen, because a removal patch that leaves3646 * contents are marked "rejected" at the patch level.3647 */3648if(!patch->new_name)3649die("internal error");36503651/* Say this even without --verbose */3652say_patch_name(stderr,"Applying patch ", patch," with");3653fprintf(stderr,"%drejects...\n", cnt);36543655 cnt =strlen(patch->new_name);3656if(ARRAY_SIZE(namebuf) <= cnt +5) {3657 cnt =ARRAY_SIZE(namebuf) -5;3658warning("truncating .rej filename to %.*s.rej",3659 cnt -1, patch->new_name);3660}3661memcpy(namebuf, patch->new_name, cnt);3662memcpy(namebuf + cnt,".rej",5);36633664 rej =fopen(namebuf,"w");3665if(!rej)3666returnerror("cannot open%s:%s", namebuf,strerror(errno));36673668/* Normal git tools never deal with .rej, so do not pretend3669 * this is a git patch by saying --git nor give extended3670 * headers. While at it, maybe please "kompare" that wants3671 * the trailing TAB and some garbage at the end of line ;-).3672 */3673fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",3674 patch->new_name, patch->new_name);3675for(cnt =1, frag = patch->fragments;3676 frag;3677 cnt++, frag = frag->next) {3678if(!frag->rejected) {3679fprintf(stderr,"Hunk #%dapplied cleanly.\n", cnt);3680continue;3681}3682fprintf(stderr,"Rejected hunk #%d.\n", cnt);3683fprintf(rej,"%.*s", frag->size, frag->patch);3684if(frag->patch[frag->size-1] !='\n')3685fputc('\n', rej);3686}3687fclose(rej);3688return-1;3689}36903691static intwrite_out_results(struct patch *list)3692{3693int phase;3694int errs =0;3695struct patch *l;36963697for(phase =0; phase <2; phase++) {3698 l = list;3699while(l) {3700if(l->rejected)3701 errs =1;3702else{3703write_out_one_result(l, phase);3704if(phase ==1&&write_out_one_reject(l))3705 errs =1;3706}3707 l = l->next;3708}3709}3710return errs;3711}37123713static struct lock_file lock_file;37143715static struct string_list limit_by_name;3716static int has_include;3717static voidadd_name_limit(const char*name,int exclude)3718{3719struct string_list_item *it;37203721 it =string_list_append(&limit_by_name, name);3722 it->util = exclude ? NULL : (void*)1;3723}37243725static intuse_patch(struct patch *p)3726{3727const char*pathname = p->new_name ? p->new_name : p->old_name;3728int i;37293730/* Paths outside are not touched regardless of "--include" */3731if(0< prefix_length) {3732int pathlen =strlen(pathname);3733if(pathlen <= prefix_length ||3734memcmp(prefix, pathname, prefix_length))3735return0;3736}37373738/* See if it matches any of exclude/include rule */3739for(i =0; i < limit_by_name.nr; i++) {3740struct string_list_item *it = &limit_by_name.items[i];3741if(!fnmatch(it->string, pathname,0))3742return(it->util != NULL);3743}37443745/*3746 * If we had any include, a path that does not match any rule is3747 * not used. Otherwise, we saw bunch of exclude rules (or none)3748 * and such a path is used.3749 */3750return!has_include;3751}375237533754static voidprefix_one(char**name)3755{3756char*old_name = *name;3757if(!old_name)3758return;3759*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3760free(old_name);3761}37623763static voidprefix_patches(struct patch *p)3764{3765if(!prefix || p->is_toplevel_relative)3766return;3767for( ; p; p = p->next) {3768prefix_one(&p->new_name);3769prefix_one(&p->old_name);3770}3771}37723773#define INACCURATE_EOF (1<<0)3774#define RECOUNT (1<<1)37753776static intapply_patch(int fd,const char*filename,int options)3777{3778size_t offset;3779struct strbuf buf = STRBUF_INIT;/* owns the patch text */3780struct patch *list = NULL, **listp = &list;3781int skipped_patch =0;37823783 patch_input_file = filename;3784read_patch_file(&buf, fd);3785 offset =0;3786while(offset < buf.len) {3787struct patch *patch;3788int nr;37893790 patch =xcalloc(1,sizeof(*patch));3791 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3792 patch->recount = !!(options & RECOUNT);3793 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3794if(nr <0)3795break;3796if(apply_in_reverse)3797reverse_patches(patch);3798if(prefix)3799prefix_patches(patch);3800if(use_patch(patch)) {3801patch_stats(patch);3802*listp = patch;3803 listp = &patch->next;3804}3805else{3806free_patch(patch);3807 skipped_patch++;3808}3809 offset += nr;3810}38113812if(!list && !skipped_patch)3813die("unrecognized input");38143815if(whitespace_error && (ws_error_action == die_on_ws_error))3816 apply =0;38173818 update_index = check_index && apply;3819if(update_index && newfd <0)3820 newfd =hold_locked_index(&lock_file,1);38213822if(check_index) {3823if(read_cache() <0)3824die("unable to read index file");3825}38263827if((check || apply) &&3828check_patch_list(list) <0&&3829!apply_with_reject)3830exit(1);38313832if(apply &&write_out_results(list))3833exit(1);38343835if(fake_ancestor)3836build_fake_ancestor(list, fake_ancestor);38373838if(diffstat)3839stat_patch_list(list);38403841if(numstat)3842numstat_patch_list(list);38433844if(summary)3845summary_patch_list(list);38463847free_patch_list(list);3848strbuf_release(&buf);3849string_list_clear(&fn_table,0);3850return0;3851}38523853static intgit_apply_config(const char*var,const char*value,void*cb)3854{3855if(!strcmp(var,"apply.whitespace"))3856returngit_config_string(&apply_default_whitespace, var, value);3857else if(!strcmp(var,"apply.ignorewhitespace"))3858returngit_config_string(&apply_default_ignorewhitespace, var, value);3859returngit_default_config(var, value, cb);3860}38613862static intoption_parse_exclude(const struct option *opt,3863const char*arg,int unset)3864{3865add_name_limit(arg,1);3866return0;3867}38683869static intoption_parse_include(const struct option *opt,3870const char*arg,int unset)3871{3872add_name_limit(arg,0);3873 has_include =1;3874return0;3875}38763877static intoption_parse_p(const struct option *opt,3878const char*arg,int unset)3879{3880 p_value =atoi(arg);3881 p_value_known =1;3882return0;3883}38843885static intoption_parse_z(const struct option *opt,3886const char*arg,int unset)3887{3888if(unset)3889 line_termination ='\n';3890else3891 line_termination =0;3892return0;3893}38943895static intoption_parse_space_change(const struct option *opt,3896const char*arg,int unset)3897{3898if(unset)3899 ws_ignore_action = ignore_ws_none;3900else3901 ws_ignore_action = ignore_ws_change;3902return0;3903}39043905static intoption_parse_whitespace(const struct option *opt,3906const char*arg,int unset)3907{3908const char**whitespace_option = opt->value;39093910*whitespace_option = arg;3911parse_whitespace_option(arg);3912return0;3913}39143915static intoption_parse_directory(const struct option *opt,3916const char*arg,int unset)3917{3918 root_len =strlen(arg);3919if(root_len && arg[root_len -1] !='/') {3920char*new_root;3921 root = new_root =xmalloc(root_len +2);3922strcpy(new_root, arg);3923strcpy(new_root + root_len++,"/");3924}else3925 root = arg;3926return0;3927}39283929intcmd_apply(int argc,const char**argv,const char*prefix_)3930{3931int i;3932int errs =0;3933int is_not_gitdir = !startup_info->have_repository;3934int force_apply =0;39353936const char*whitespace_option = NULL;39373938struct option builtin_apply_options[] = {3939{ OPTION_CALLBACK,0,"exclude", NULL,"path",3940"don't apply changes matching the given path",39410, option_parse_exclude },3942{ OPTION_CALLBACK,0,"include", NULL,"path",3943"apply changes matching the given path",39440, option_parse_include },3945{ OPTION_CALLBACK,'p', NULL, NULL,"num",3946"remove <num> leading slashes from traditional diff paths",39470, option_parse_p },3948OPT_BOOLEAN(0,"no-add", &no_add,3949"ignore additions made by the patch"),3950OPT_BOOLEAN(0,"stat", &diffstat,3951"instead of applying the patch, output diffstat for the input"),3952OPT_NOOP_NOARG(0,"allow-binary-replacement"),3953OPT_NOOP_NOARG(0,"binary"),3954OPT_BOOLEAN(0,"numstat", &numstat,3955"shows number of added and deleted lines in decimal notation"),3956OPT_BOOLEAN(0,"summary", &summary,3957"instead of applying the patch, output a summary for the input"),3958OPT_BOOLEAN(0,"check", &check,3959"instead of applying the patch, see if the patch is applicable"),3960OPT_BOOLEAN(0,"index", &check_index,3961"make sure the patch is applicable to the current index"),3962OPT_BOOLEAN(0,"cached", &cached,3963"apply a patch without touching the working tree"),3964OPT_BOOLEAN(0,"apply", &force_apply,3965"also apply the patch (use with --stat/--summary/--check)"),3966OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,3967"build a temporary index based on embedded index information"),3968{ OPTION_CALLBACK,'z', NULL, NULL, NULL,3969"paths are separated with NUL character",3970 PARSE_OPT_NOARG, option_parse_z },3971OPT_INTEGER('C', NULL, &p_context,3972"ensure at least <n> lines of context match"),3973{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,"action",3974"detect new or modified lines that have whitespace errors",39750, option_parse_whitespace },3976{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,3977"ignore changes in whitespace when finding context",3978 PARSE_OPT_NOARG, option_parse_space_change },3979{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,3980"ignore changes in whitespace when finding context",3981 PARSE_OPT_NOARG, option_parse_space_change },3982OPT_BOOLEAN('R',"reverse", &apply_in_reverse,3983"apply the patch in reverse"),3984OPT_BOOLEAN(0,"unidiff-zero", &unidiff_zero,3985"don't expect at least one line of context"),3986OPT_BOOLEAN(0,"reject", &apply_with_reject,3987"leave the rejected hunks in corresponding *.rej files"),3988OPT_BOOLEAN(0,"allow-overlap", &allow_overlap,3989"allow overlapping hunks"),3990OPT__VERBOSE(&apply_verbosely,"be verbose"),3991OPT_BIT(0,"inaccurate-eof", &options,3992"tolerate incorrectly detected missing new-line at the end of file",3993 INACCURATE_EOF),3994OPT_BIT(0,"recount", &options,3995"do not trust the line counts in the hunk headers",3996 RECOUNT),3997{ OPTION_CALLBACK,0,"directory", NULL,"root",3998"prepend <root> to all filenames",39990, option_parse_directory },4000OPT_END()4001};40024003 prefix = prefix_;4004 prefix_length = prefix ?strlen(prefix) :0;4005git_config(git_apply_config, NULL);4006if(apply_default_whitespace)4007parse_whitespace_option(apply_default_whitespace);4008if(apply_default_ignorewhitespace)4009parse_ignorewhitespace_option(apply_default_ignorewhitespace);40104011 argc =parse_options(argc, argv, prefix, builtin_apply_options,4012 apply_usage,0);40134014if(apply_with_reject)4015 apply = apply_verbosely =1;4016if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))4017 apply =0;4018if(check_index && is_not_gitdir)4019die("--index outside a repository");4020if(cached) {4021if(is_not_gitdir)4022die("--cached outside a repository");4023 check_index =1;4024}4025for(i =0; i < argc; i++) {4026const char*arg = argv[i];4027int fd;40284029if(!strcmp(arg,"-")) {4030 errs |=apply_patch(0,"<stdin>", options);4031 read_stdin =0;4032continue;4033}else if(0< prefix_length)4034 arg =prefix_filename(prefix, prefix_length, arg);40354036 fd =open(arg, O_RDONLY);4037if(fd <0)4038die_errno("can't open patch '%s'", arg);4039 read_stdin =0;4040set_default_whitespace_mode(whitespace_option);4041 errs |=apply_patch(fd, arg, options);4042close(fd);4043}4044set_default_whitespace_mode(whitespace_option);4045if(read_stdin)4046 errs |=apply_patch(0,"<stdin>", options);4047if(whitespace_error) {4048if(squelch_whitespace_errors &&4049 squelch_whitespace_errors < whitespace_error) {4050int squelched =4051 whitespace_error - squelch_whitespace_errors;4052warning("squelched%d"4053"whitespace error%s",4054 squelched,4055 squelched ==1?"":"s");4056}4057if(ws_error_action == die_on_ws_error)4058die("%dline%sadd%swhitespace errors.",4059 whitespace_error,4060 whitespace_error ==1?"":"s",4061 whitespace_error ==1?"s":"");4062if(applied_after_fixing_ws && apply)4063warning("%dline%sapplied after"4064" fixing whitespace errors.",4065 applied_after_fixing_ws,4066 applied_after_fixing_ws ==1?"":"s");4067else if(whitespace_error)4068warning("%dline%sadd%swhitespace errors.",4069 whitespace_error,4070 whitespace_error ==1?"":"s",4071 whitespace_error ==1?"s":"");4072}40734074if(update_index) {4075if(write_cache(newfd, active_cache, active_nr) ||4076commit_locked_index(&lock_file))4077die("Unable to write new index file");4078}40794080return!!errs;4081}