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[] = { 53N_("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 378/* fmt must contain _one_ %s and no other substitution */ 379static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 380{ 381struct strbuf sb = STRBUF_INIT; 382 383if(patch->old_name && patch->new_name && 384strcmp(patch->old_name, patch->new_name)) { 385quote_c_style(patch->old_name, &sb, NULL,0); 386strbuf_addstr(&sb," => "); 387quote_c_style(patch->new_name, &sb, NULL,0); 388}else{ 389const char*n = patch->new_name; 390if(!n) 391 n = patch->old_name; 392quote_c_style(n, &sb, NULL,0); 393} 394fprintf(output, fmt, sb.buf); 395fputc('\n', output); 396strbuf_release(&sb); 397} 398 399#define SLOP (16) 400 401static voidread_patch_file(struct strbuf *sb,int fd) 402{ 403if(strbuf_read(sb, fd,0) <0) 404die_errno("git apply: failed to read"); 405 406/* 407 * Make sure that we have some slop in the buffer 408 * so that we can do speculative "memcmp" etc, and 409 * see to it that it is NUL-filled. 410 */ 411strbuf_grow(sb, SLOP); 412memset(sb->buf + sb->len,0, SLOP); 413} 414 415static unsigned longlinelen(const char*buffer,unsigned long size) 416{ 417unsigned long len =0; 418while(size--) { 419 len++; 420if(*buffer++ =='\n') 421break; 422} 423return len; 424} 425 426static intis_dev_null(const char*str) 427{ 428return!memcmp("/dev/null", str,9) &&isspace(str[9]); 429} 430 431#define TERM_SPACE 1 432#define TERM_TAB 2 433 434static intname_terminate(const char*name,int namelen,int c,int terminate) 435{ 436if(c ==' '&& !(terminate & TERM_SPACE)) 437return0; 438if(c =='\t'&& !(terminate & TERM_TAB)) 439return0; 440 441return1; 442} 443 444/* remove double slashes to make --index work with such filenames */ 445static char*squash_slash(char*name) 446{ 447int i =0, j =0; 448 449if(!name) 450return NULL; 451 452while(name[i]) { 453if((name[j++] = name[i++]) =='/') 454while(name[i] =='/') 455 i++; 456} 457 name[j] ='\0'; 458return name; 459} 460 461static char*find_name_gnu(const char*line,const char*def,int p_value) 462{ 463struct strbuf name = STRBUF_INIT; 464char*cp; 465 466/* 467 * Proposed "new-style" GNU patch/diff format; see 468 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2 469 */ 470if(unquote_c_style(&name, line, NULL)) { 471strbuf_release(&name); 472return NULL; 473} 474 475for(cp = name.buf; p_value; p_value--) { 476 cp =strchr(cp,'/'); 477if(!cp) { 478strbuf_release(&name); 479return NULL; 480} 481 cp++; 482} 483 484strbuf_remove(&name,0, cp - name.buf); 485if(root) 486strbuf_insert(&name,0, root, root_len); 487returnsquash_slash(strbuf_detach(&name, NULL)); 488} 489 490static size_tsane_tz_len(const char*line,size_t len) 491{ 492const char*tz, *p; 493 494if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 495return0; 496 tz = line + len -strlen(" +0500"); 497 498if(tz[1] !='+'&& tz[1] !='-') 499return0; 500 501for(p = tz +2; p != line + len; p++) 502if(!isdigit(*p)) 503return0; 504 505return line + len - tz; 506} 507 508static size_ttz_with_colon_len(const char*line,size_t len) 509{ 510const char*tz, *p; 511 512if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 513return0; 514 tz = line + len -strlen(" +08:00"); 515 516if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 517return0; 518 p = tz +2; 519if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 520!isdigit(*p++) || !isdigit(*p++)) 521return0; 522 523return line + len - tz; 524} 525 526static size_tdate_len(const char*line,size_t len) 527{ 528const char*date, *p; 529 530if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 531return0; 532 p = date = line + len -strlen("72-02-05"); 533 534if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 535!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 536!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 537return0; 538 539if(date - line >=strlen("19") && 540isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 541 date -=strlen("19"); 542 543return line + len - date; 544} 545 546static size_tshort_time_len(const char*line,size_t len) 547{ 548const char*time, *p; 549 550if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 551return0; 552 p = time = line + len -strlen(" 07:01:32"); 553 554/* Permit 1-digit hours? */ 555if(*p++ !=' '|| 556!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 557!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 558!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 559return0; 560 561return line + len - time; 562} 563 564static size_tfractional_time_len(const char*line,size_t len) 565{ 566const char*p; 567size_t n; 568 569/* Expected format: 19:41:17.620000023 */ 570if(!len || !isdigit(line[len -1])) 571return0; 572 p = line + len -1; 573 574/* Fractional seconds. */ 575while(p > line &&isdigit(*p)) 576 p--; 577if(*p !='.') 578return0; 579 580/* Hours, minutes, and whole seconds. */ 581 n =short_time_len(line, p - line); 582if(!n) 583return0; 584 585return line + len - p + n; 586} 587 588static size_ttrailing_spaces_len(const char*line,size_t len) 589{ 590const char*p; 591 592/* Expected format: ' ' x (1 or more) */ 593if(!len || line[len -1] !=' ') 594return0; 595 596 p = line + len; 597while(p != line) { 598 p--; 599if(*p !=' ') 600return line + len - (p +1); 601} 602 603/* All spaces! */ 604return len; 605} 606 607static size_tdiff_timestamp_len(const char*line,size_t len) 608{ 609const char*end = line + len; 610size_t n; 611 612/* 613 * Posix: 2010-07-05 19:41:17 614 * GNU: 2010-07-05 19:41:17.620000023 -0500 615 */ 616 617if(!isdigit(end[-1])) 618return0; 619 620 n =sane_tz_len(line, end - line); 621if(!n) 622 n =tz_with_colon_len(line, end - line); 623 end -= n; 624 625 n =short_time_len(line, end - line); 626if(!n) 627 n =fractional_time_len(line, end - line); 628 end -= n; 629 630 n =date_len(line, end - line); 631if(!n)/* No date. Too bad. */ 632return0; 633 end -= n; 634 635if(end == line)/* No space before date. */ 636return0; 637if(end[-1] =='\t') {/* Success! */ 638 end--; 639return line + len - end; 640} 641if(end[-1] !=' ')/* No space before date. */ 642return0; 643 644/* Whitespace damage. */ 645 end -=trailing_spaces_len(line, end - line); 646return line + len - end; 647} 648 649static char*null_strdup(const char*s) 650{ 651return s ?xstrdup(s) : NULL; 652} 653 654static char*find_name_common(const char*line,const char*def, 655int p_value,const char*end,int terminate) 656{ 657int len; 658const char*start = NULL; 659 660if(p_value ==0) 661 start = line; 662while(line != end) { 663char c = *line; 664 665if(!end &&isspace(c)) { 666if(c =='\n') 667break; 668if(name_terminate(start, line-start, c, terminate)) 669break; 670} 671 line++; 672if(c =='/'&& !--p_value) 673 start = line; 674} 675if(!start) 676returnsquash_slash(null_strdup(def)); 677 len = line - start; 678if(!len) 679returnsquash_slash(null_strdup(def)); 680 681/* 682 * Generally we prefer the shorter name, especially 683 * if the other one is just a variation of that with 684 * something else tacked on to the end (ie "file.orig" 685 * or "file~"). 686 */ 687if(def) { 688int deflen =strlen(def); 689if(deflen < len && !strncmp(start, def, deflen)) 690returnsquash_slash(xstrdup(def)); 691} 692 693if(root) { 694char*ret =xmalloc(root_len + len +1); 695strcpy(ret, root); 696memcpy(ret + root_len, start, len); 697 ret[root_len + len] ='\0'; 698returnsquash_slash(ret); 699} 700 701returnsquash_slash(xmemdupz(start, len)); 702} 703 704static char*find_name(const char*line,char*def,int p_value,int terminate) 705{ 706if(*line =='"') { 707char*name =find_name_gnu(line, def, p_value); 708if(name) 709return name; 710} 711 712returnfind_name_common(line, def, p_value, NULL, terminate); 713} 714 715static char*find_name_traditional(const char*line,char*def,int p_value) 716{ 717size_t len =strlen(line); 718size_t date_len; 719 720if(*line =='"') { 721char*name =find_name_gnu(line, def, p_value); 722if(name) 723return name; 724} 725 726 len =strchrnul(line,'\n') - line; 727 date_len =diff_timestamp_len(line, len); 728if(!date_len) 729returnfind_name_common(line, def, p_value, NULL, TERM_TAB); 730 len -= date_len; 731 732returnfind_name_common(line, def, p_value, line + len,0); 733} 734 735static intcount_slashes(const char*cp) 736{ 737int cnt =0; 738char ch; 739 740while((ch = *cp++)) 741if(ch =='/') 742 cnt++; 743return cnt; 744} 745 746/* 747 * Given the string after "--- " or "+++ ", guess the appropriate 748 * p_value for the given patch. 749 */ 750static intguess_p_value(const char*nameline) 751{ 752char*name, *cp; 753int val = -1; 754 755if(is_dev_null(nameline)) 756return-1; 757 name =find_name_traditional(nameline, NULL,0); 758if(!name) 759return-1; 760 cp =strchr(name,'/'); 761if(!cp) 762 val =0; 763else if(prefix) { 764/* 765 * Does it begin with "a/$our-prefix" and such? Then this is 766 * very likely to apply to our directory. 767 */ 768if(!strncmp(name, prefix, prefix_length)) 769 val =count_slashes(prefix); 770else{ 771 cp++; 772if(!strncmp(cp, prefix, prefix_length)) 773 val =count_slashes(prefix) +1; 774} 775} 776free(name); 777return val; 778} 779 780/* 781 * Does the ---/+++ line has the POSIX timestamp after the last HT? 782 * GNU diff puts epoch there to signal a creation/deletion event. Is 783 * this such a timestamp? 784 */ 785static inthas_epoch_timestamp(const char*nameline) 786{ 787/* 788 * We are only interested in epoch timestamp; any non-zero 789 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 790 * For the same reason, the date must be either 1969-12-31 or 791 * 1970-01-01, and the seconds part must be "00". 792 */ 793const char stamp_regexp[] = 794"^(1969-12-31|1970-01-01)" 795" " 796"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 797" " 798"([-+][0-2][0-9]:?[0-5][0-9])\n"; 799const char*timestamp = NULL, *cp, *colon; 800static regex_t *stamp; 801 regmatch_t m[10]; 802int zoneoffset; 803int hourminute; 804int status; 805 806for(cp = nameline; *cp !='\n'; cp++) { 807if(*cp =='\t') 808 timestamp = cp +1; 809} 810if(!timestamp) 811return0; 812if(!stamp) { 813 stamp =xmalloc(sizeof(*stamp)); 814if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 815warning(_("Cannot prepare timestamp regexp%s"), 816 stamp_regexp); 817return0; 818} 819} 820 821 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 822if(status) { 823if(status != REG_NOMATCH) 824warning(_("regexec returned%dfor input:%s"), 825 status, timestamp); 826return0; 827} 828 829 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 830if(*colon ==':') 831 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 832else 833 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 834if(timestamp[m[3].rm_so] =='-') 835 zoneoffset = -zoneoffset; 836 837/* 838 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 839 * (west of GMT) or 1970-01-01 (east of GMT) 840 */ 841if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 842(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 843return0; 844 845 hourminute = (strtol(timestamp +11, NULL,10) *60+ 846strtol(timestamp +14, NULL,10) - 847 zoneoffset); 848 849return((zoneoffset <0&& hourminute ==1440) || 850(0<= zoneoffset && !hourminute)); 851} 852 853/* 854 * Get the name etc info from the ---/+++ lines of a traditional patch header 855 * 856 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 857 * files, we can happily check the index for a match, but for creating a 858 * new file we should try to match whatever "patch" does. I have no idea. 859 */ 860static voidparse_traditional_patch(const char*first,const char*second,struct patch *patch) 861{ 862char*name; 863 864 first +=4;/* skip "--- " */ 865 second +=4;/* skip "+++ " */ 866if(!p_value_known) { 867int p, q; 868 p =guess_p_value(first); 869 q =guess_p_value(second); 870if(p <0) p = q; 871if(0<= p && p == q) { 872 p_value = p; 873 p_value_known =1; 874} 875} 876if(is_dev_null(first)) { 877 patch->is_new =1; 878 patch->is_delete =0; 879 name =find_name_traditional(second, NULL, p_value); 880 patch->new_name = name; 881}else if(is_dev_null(second)) { 882 patch->is_new =0; 883 patch->is_delete =1; 884 name =find_name_traditional(first, NULL, p_value); 885 patch->old_name = name; 886}else{ 887char*first_name; 888 first_name =find_name_traditional(first, NULL, p_value); 889 name =find_name_traditional(second, first_name, p_value); 890free(first_name); 891if(has_epoch_timestamp(first)) { 892 patch->is_new =1; 893 patch->is_delete =0; 894 patch->new_name = name; 895}else if(has_epoch_timestamp(second)) { 896 patch->is_new =0; 897 patch->is_delete =1; 898 patch->old_name = name; 899}else{ 900 patch->old_name = name; 901 patch->new_name =xstrdup(name); 902} 903} 904if(!name) 905die(_("unable to find filename in patch at line%d"), linenr); 906} 907 908static intgitdiff_hdrend(const char*line,struct patch *patch) 909{ 910return-1; 911} 912 913/* 914 * We're anal about diff header consistency, to make 915 * sure that we don't end up having strange ambiguous 916 * patches floating around. 917 * 918 * As a result, gitdiff_{old|new}name() will check 919 * their names against any previous information, just 920 * to make sure.. 921 */ 922#define DIFF_OLD_NAME 0 923#define DIFF_NEW_NAME 1 924 925static char*gitdiff_verify_name(const char*line,int isnull,char*orig_name,int side) 926{ 927if(!orig_name && !isnull) 928returnfind_name(line, NULL, p_value, TERM_TAB); 929 930if(orig_name) { 931int len; 932const char*name; 933char*another; 934 name = orig_name; 935 len =strlen(name); 936if(isnull) 937die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), name, linenr); 938 another =find_name(line, NULL, p_value, TERM_TAB); 939if(!another ||memcmp(another, name, len +1)) 940die((side == DIFF_NEW_NAME) ? 941_("git apply: bad git-diff - inconsistent new filename on line%d") : 942_("git apply: bad git-diff - inconsistent old filename on line%d"), linenr); 943free(another); 944return orig_name; 945} 946else{ 947/* expect "/dev/null" */ 948if(memcmp("/dev/null", line,9) || line[9] !='\n') 949die(_("git apply: bad git-diff - expected /dev/null on line%d"), linenr); 950return NULL; 951} 952} 953 954static intgitdiff_oldname(const char*line,struct patch *patch) 955{ 956char*orig = patch->old_name; 957 patch->old_name =gitdiff_verify_name(line, patch->is_new, patch->old_name, 958 DIFF_OLD_NAME); 959if(orig != patch->old_name) 960free(orig); 961return0; 962} 963 964static intgitdiff_newname(const char*line,struct patch *patch) 965{ 966char*orig = patch->new_name; 967 patch->new_name =gitdiff_verify_name(line, patch->is_delete, patch->new_name, 968 DIFF_NEW_NAME); 969if(orig != patch->new_name) 970free(orig); 971return0; 972} 973 974static intgitdiff_oldmode(const char*line,struct patch *patch) 975{ 976 patch->old_mode =strtoul(line, NULL,8); 977return0; 978} 979 980static intgitdiff_newmode(const char*line,struct patch *patch) 981{ 982 patch->new_mode =strtoul(line, NULL,8); 983return0; 984} 985 986static intgitdiff_delete(const char*line,struct patch *patch) 987{ 988 patch->is_delete =1; 989free(patch->old_name); 990 patch->old_name =null_strdup(patch->def_name); 991returngitdiff_oldmode(line, patch); 992} 993 994static intgitdiff_newfile(const char*line,struct patch *patch) 995{ 996 patch->is_new =1; 997free(patch->new_name); 998 patch->new_name =null_strdup(patch->def_name); 999returngitdiff_newmode(line, patch);1000}10011002static intgitdiff_copysrc(const char*line,struct patch *patch)1003{1004 patch->is_copy =1;1005free(patch->old_name);1006 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0);1007return0;1008}10091010static intgitdiff_copydst(const char*line,struct patch *patch)1011{1012 patch->is_copy =1;1013free(patch->new_name);1014 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0);1015return0;1016}10171018static intgitdiff_renamesrc(const char*line,struct patch *patch)1019{1020 patch->is_rename =1;1021free(patch->old_name);1022 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0);1023return0;1024}10251026static intgitdiff_renamedst(const char*line,struct patch *patch)1027{1028 patch->is_rename =1;1029free(patch->new_name);1030 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0);1031return0;1032}10331034static intgitdiff_similarity(const char*line,struct patch *patch)1035{1036if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX)1037 patch->score =0;1038return0;1039}10401041static intgitdiff_dissimilarity(const char*line,struct patch *patch)1042{1043if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX)1044 patch->score =0;1045return0;1046}10471048static intgitdiff_index(const char*line,struct patch *patch)1049{1050/*1051 * index line is N hexadecimal, "..", N hexadecimal,1052 * and optional space with octal mode.1053 */1054const char*ptr, *eol;1055int len;10561057 ptr =strchr(line,'.');1058if(!ptr || ptr[1] !='.'||40< ptr - line)1059return0;1060 len = ptr - line;1061memcpy(patch->old_sha1_prefix, line, len);1062 patch->old_sha1_prefix[len] =0;10631064 line = ptr +2;1065 ptr =strchr(line,' ');1066 eol =strchr(line,'\n');10671068if(!ptr || eol < ptr)1069 ptr = eol;1070 len = ptr - line;10711072if(40< len)1073return0;1074memcpy(patch->new_sha1_prefix, line, len);1075 patch->new_sha1_prefix[len] =0;1076if(*ptr ==' ')1077 patch->old_mode =strtoul(ptr+1, NULL,8);1078return0;1079}10801081/*1082 * This is normal for a diff that doesn't change anything: we'll fall through1083 * into the next diff. Tell the parser to break out.1084 */1085static intgitdiff_unrecognized(const char*line,struct patch *patch)1086{1087return-1;1088}10891090static const char*stop_at_slash(const char*line,int llen)1091{1092int nslash = p_value;1093int i;10941095for(i =0; i < llen; i++) {1096int ch = line[i];1097if(ch =='/'&& --nslash <=0)1098return&line[i];1099}1100return NULL;1101}11021103/*1104 * This is to extract the same name that appears on "diff --git"1105 * line. We do not find and return anything if it is a rename1106 * patch, and it is OK because we will find the name elsewhere.1107 * We need to reliably find name only when it is mode-change only,1108 * creation or deletion of an empty file. In any of these cases,1109 * both sides are the same name under a/ and b/ respectively.1110 */1111static char*git_header_name(const char*line,int llen)1112{1113const char*name;1114const char*second = NULL;1115size_t len, line_len;11161117 line +=strlen("diff --git ");1118 llen -=strlen("diff --git ");11191120if(*line =='"') {1121const char*cp;1122struct strbuf first = STRBUF_INIT;1123struct strbuf sp = STRBUF_INIT;11241125if(unquote_c_style(&first, line, &second))1126goto free_and_fail1;11271128/* advance to the first slash */1129 cp =stop_at_slash(first.buf, first.len);1130/* we do not accept absolute paths */1131if(!cp || cp == first.buf)1132goto free_and_fail1;1133strbuf_remove(&first,0, cp +1- first.buf);11341135/*1136 * second points at one past closing dq of name.1137 * find the second name.1138 */1139while((second < line + llen) &&isspace(*second))1140 second++;11411142if(line + llen <= second)1143goto free_and_fail1;1144if(*second =='"') {1145if(unquote_c_style(&sp, second, NULL))1146goto free_and_fail1;1147 cp =stop_at_slash(sp.buf, sp.len);1148if(!cp || cp == sp.buf)1149goto free_and_fail1;1150/* They must match, otherwise ignore */1151if(strcmp(cp +1, first.buf))1152goto free_and_fail1;1153strbuf_release(&sp);1154returnstrbuf_detach(&first, NULL);1155}11561157/* unquoted second */1158 cp =stop_at_slash(second, line + llen - second);1159if(!cp || cp == second)1160goto free_and_fail1;1161 cp++;1162if(line + llen - cp != first.len +1||1163memcmp(first.buf, cp, first.len))1164goto free_and_fail1;1165returnstrbuf_detach(&first, NULL);11661167 free_and_fail1:1168strbuf_release(&first);1169strbuf_release(&sp);1170return NULL;1171}11721173/* unquoted first name */1174 name =stop_at_slash(line, llen);1175if(!name || name == line)1176return NULL;1177 name++;11781179/*1180 * since the first name is unquoted, a dq if exists must be1181 * the beginning of the second name.1182 */1183for(second = name; second < line + llen; second++) {1184if(*second =='"') {1185struct strbuf sp = STRBUF_INIT;1186const char*np;11871188if(unquote_c_style(&sp, second, NULL))1189goto free_and_fail2;11901191 np =stop_at_slash(sp.buf, sp.len);1192if(!np || np == sp.buf)1193goto free_and_fail2;1194 np++;11951196 len = sp.buf + sp.len - np;1197if(len < second - name &&1198!strncmp(np, name, len) &&1199isspace(name[len])) {1200/* Good */1201strbuf_remove(&sp,0, np - sp.buf);1202returnstrbuf_detach(&sp, NULL);1203}12041205 free_and_fail2:1206strbuf_release(&sp);1207return NULL;1208}1209}12101211/*1212 * Accept a name only if it shows up twice, exactly the same1213 * form.1214 */1215 second =strchr(name,'\n');1216if(!second)1217return NULL;1218 line_len = second - name;1219for(len =0; ; len++) {1220switch(name[len]) {1221default:1222continue;1223case'\n':1224return NULL;1225case'\t':case' ':1226 second =stop_at_slash(name + len, line_len - len);1227if(!second)1228return NULL;1229 second++;1230if(second[len] =='\n'&& !strncmp(name, second, len)) {1231returnxmemdupz(name, len);1232}1233}1234}1235}12361237/* Verify that we recognize the lines following a git header */1238static intparse_git_header(const char*line,int len,unsigned int size,struct patch *patch)1239{1240unsigned long offset;12411242/* A git diff has explicit new/delete information, so we don't guess */1243 patch->is_new =0;1244 patch->is_delete =0;12451246/*1247 * Some things may not have the old name in the1248 * rest of the headers anywhere (pure mode changes,1249 * or removing or adding empty files), so we get1250 * the default name from the header.1251 */1252 patch->def_name =git_header_name(line, len);1253if(patch->def_name && root) {1254char*s =xmalloc(root_len +strlen(patch->def_name) +1);1255strcpy(s, root);1256strcpy(s + root_len, patch->def_name);1257free(patch->def_name);1258 patch->def_name = s;1259}12601261 line += len;1262 size -= len;1263 linenr++;1264for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) {1265static const struct opentry {1266const char*str;1267int(*fn)(const char*,struct patch *);1268} optable[] = {1269{"@@ -", gitdiff_hdrend },1270{"--- ", gitdiff_oldname },1271{"+++ ", gitdiff_newname },1272{"old mode ", gitdiff_oldmode },1273{"new mode ", gitdiff_newmode },1274{"deleted file mode ", gitdiff_delete },1275{"new file mode ", gitdiff_newfile },1276{"copy from ", gitdiff_copysrc },1277{"copy to ", gitdiff_copydst },1278{"rename old ", gitdiff_renamesrc },1279{"rename new ", gitdiff_renamedst },1280{"rename from ", gitdiff_renamesrc },1281{"rename to ", gitdiff_renamedst },1282{"similarity index ", gitdiff_similarity },1283{"dissimilarity index ", gitdiff_dissimilarity },1284{"index ", gitdiff_index },1285{"", gitdiff_unrecognized },1286};1287int i;12881289 len =linelen(line, size);1290if(!len || line[len-1] !='\n')1291break;1292for(i =0; i <ARRAY_SIZE(optable); i++) {1293const struct opentry *p = optable + i;1294int oplen =strlen(p->str);1295if(len < oplen ||memcmp(p->str, line, oplen))1296continue;1297if(p->fn(line + oplen, patch) <0)1298return offset;1299break;1300}1301}13021303return offset;1304}13051306static intparse_num(const char*line,unsigned long*p)1307{1308char*ptr;13091310if(!isdigit(*line))1311return0;1312*p =strtoul(line, &ptr,10);1313return ptr - line;1314}13151316static intparse_range(const char*line,int len,int offset,const char*expect,1317unsigned long*p1,unsigned long*p2)1318{1319int digits, ex;13201321if(offset <0|| offset >= len)1322return-1;1323 line += offset;1324 len -= offset;13251326 digits =parse_num(line, p1);1327if(!digits)1328return-1;13291330 offset += digits;1331 line += digits;1332 len -= digits;13331334*p2 =1;1335if(*line ==',') {1336 digits =parse_num(line+1, p2);1337if(!digits)1338return-1;13391340 offset += digits+1;1341 line += digits+1;1342 len -= digits+1;1343}13441345 ex =strlen(expect);1346if(ex > len)1347return-1;1348if(memcmp(line, expect, ex))1349return-1;13501351return offset + ex;1352}13531354static voidrecount_diff(const char*line,int size,struct fragment *fragment)1355{1356int oldlines =0, newlines =0, ret =0;13571358if(size <1) {1359warning("recount: ignore empty hunk");1360return;1361}13621363for(;;) {1364int len =linelen(line, size);1365 size -= len;1366 line += len;13671368if(size <1)1369break;13701371switch(*line) {1372case' ':case'\n':1373 newlines++;1374/* fall through */1375case'-':1376 oldlines++;1377continue;1378case'+':1379 newlines++;1380continue;1381case'\\':1382continue;1383case'@':1384 ret = size <3||prefixcmp(line,"@@ ");1385break;1386case'd':1387 ret = size <5||prefixcmp(line,"diff ");1388break;1389default:1390 ret = -1;1391break;1392}1393if(ret) {1394warning(_("recount: unexpected line: %.*s"),1395(int)linelen(line, size), line);1396return;1397}1398break;1399}1400 fragment->oldlines = oldlines;1401 fragment->newlines = newlines;1402}14031404/*1405 * Parse a unified diff fragment header of the1406 * form "@@ -a,b +c,d @@"1407 */1408static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1409{1410int offset;14111412if(!len || line[len-1] !='\n')1413return-1;14141415/* Figure out the number of lines in a fragment */1416 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1417 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14181419return offset;1420}14211422static intfind_header(const char*line,unsigned long size,int*hdrsize,struct patch *patch)1423{1424unsigned long offset, len;14251426 patch->is_toplevel_relative =0;1427 patch->is_rename = patch->is_copy =0;1428 patch->is_new = patch->is_delete = -1;1429 patch->old_mode = patch->new_mode =0;1430 patch->old_name = patch->new_name = NULL;1431for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) {1432unsigned long nextlen;14331434 len =linelen(line, size);1435if(!len)1436break;14371438/* Testing this early allows us to take a few shortcuts.. */1439if(len <6)1440continue;14411442/*1443 * Make sure we don't find any unconnected patch fragments.1444 * That's a sign that we didn't find a header, and that a1445 * patch has become corrupted/broken up.1446 */1447if(!memcmp("@@ -", line,4)) {1448struct fragment dummy;1449if(parse_fragment_header(line, len, &dummy) <0)1450continue;1451die(_("patch fragment without header at line%d: %.*s"),1452 linenr, (int)len-1, line);1453}14541455if(size < len +6)1456break;14571458/*1459 * Git patch? It might not have a real patch, just a rename1460 * or mode change, so we handle that specially1461 */1462if(!memcmp("diff --git ", line,11)) {1463int git_hdr_len =parse_git_header(line, len, size, patch);1464if(git_hdr_len <= len)1465continue;1466if(!patch->old_name && !patch->new_name) {1467if(!patch->def_name)1468die(Q_("git diff header lacks filename information when removing "1469"%dleading pathname component (line%d)",1470"git diff header lacks filename information when removing "1471"%dleading pathname components (line%d)",1472 p_value),1473 p_value, linenr);1474 patch->old_name =xstrdup(patch->def_name);1475 patch->new_name =xstrdup(patch->def_name);1476}1477if(!patch->is_delete && !patch->new_name)1478die("git diff header lacks filename information "1479"(line%d)", linenr);1480 patch->is_toplevel_relative =1;1481*hdrsize = git_hdr_len;1482return offset;1483}14841485/* --- followed by +++ ? */1486if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1487continue;14881489/*1490 * We only accept unified patches, so we want it to1491 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1492 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1493 */1494 nextlen =linelen(line + len, size - len);1495if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1496continue;14971498/* Ok, we'll consider it a patch */1499parse_traditional_patch(line, line+len, patch);1500*hdrsize = len + nextlen;1501 linenr +=2;1502return offset;1503}1504return-1;1505}15061507static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1508{1509char*err;15101511if(!result)1512return;15131514 whitespace_error++;1515if(squelch_whitespace_errors &&1516 squelch_whitespace_errors < whitespace_error)1517return;15181519 err =whitespace_error_string(result);1520fprintf(stderr,"%s:%d:%s.\n%.*s\n",1521 patch_input_file, linenr, err, len, line);1522free(err);1523}15241525static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1526{1527unsigned result =ws_check(line +1, len -1, ws_rule);15281529record_ws_error(result, line +1, len -2, linenr);1530}15311532/*1533 * Parse a unified diff. Note that this really needs to parse each1534 * fragment separately, since the only way to know the difference1535 * between a "---" that is part of a patch, and a "---" that starts1536 * the next patch is to look at the line counts..1537 */1538static intparse_fragment(const char*line,unsigned long size,1539struct patch *patch,struct fragment *fragment)1540{1541int added, deleted;1542int len =linelen(line, size), offset;1543unsigned long oldlines, newlines;1544unsigned long leading, trailing;15451546 offset =parse_fragment_header(line, len, fragment);1547if(offset <0)1548return-1;1549if(offset >0&& patch->recount)1550recount_diff(line + offset, size - offset, fragment);1551 oldlines = fragment->oldlines;1552 newlines = fragment->newlines;1553 leading =0;1554 trailing =0;15551556/* Parse the thing.. */1557 line += len;1558 size -= len;1559 linenr++;1560 added = deleted =0;1561for(offset = len;15620< size;1563 offset += len, size -= len, line += len, linenr++) {1564if(!oldlines && !newlines)1565break;1566 len =linelen(line, size);1567if(!len || line[len-1] !='\n')1568return-1;1569switch(*line) {1570default:1571return-1;1572case'\n':/* newer GNU diff, an empty context line */1573case' ':1574 oldlines--;1575 newlines--;1576if(!deleted && !added)1577 leading++;1578 trailing++;1579break;1580case'-':1581if(apply_in_reverse &&1582 ws_error_action != nowarn_ws_error)1583check_whitespace(line, len, patch->ws_rule);1584 deleted++;1585 oldlines--;1586 trailing =0;1587break;1588case'+':1589if(!apply_in_reverse &&1590 ws_error_action != nowarn_ws_error)1591check_whitespace(line, len, patch->ws_rule);1592 added++;1593 newlines--;1594 trailing =0;1595break;15961597/*1598 * We allow "\ No newline at end of file". Depending1599 * on locale settings when the patch was produced we1600 * don't know what this line looks like. The only1601 * thing we do know is that it begins with "\ ".1602 * Checking for 12 is just for sanity check -- any1603 * l10n of "\ No newline..." is at least that long.1604 */1605case'\\':1606if(len <12||memcmp(line,"\\",2))1607return-1;1608break;1609}1610}1611if(oldlines || newlines)1612return-1;1613 fragment->leading = leading;1614 fragment->trailing = trailing;16151616/*1617 * If a fragment ends with an incomplete line, we failed to include1618 * it in the above loop because we hit oldlines == newlines == 01619 * before seeing it.1620 */1621if(12< size && !memcmp(line,"\\",2))1622 offset +=linelen(line, size);16231624 patch->lines_added += added;1625 patch->lines_deleted += deleted;16261627if(0< patch->is_new && oldlines)1628returnerror(_("new file depends on old contents"));1629if(0< patch->is_delete && newlines)1630returnerror(_("deleted file still has contents"));1631return offset;1632}16331634/*1635 * We have seen "diff --git a/... b/..." header (or a traditional patch1636 * header). Read hunks that belong to this patch into fragments and hang1637 * them to the given patch structure.1638 *1639 * The (fragment->patch, fragment->size) pair points into the memory given1640 * by the caller, not a copy, when we return.1641 */1642static intparse_single_patch(const char*line,unsigned long size,struct patch *patch)1643{1644unsigned long offset =0;1645unsigned long oldlines =0, newlines =0, context =0;1646struct fragment **fragp = &patch->fragments;16471648while(size >4&& !memcmp(line,"@@ -",4)) {1649struct fragment *fragment;1650int len;16511652 fragment =xcalloc(1,sizeof(*fragment));1653 fragment->linenr = linenr;1654 len =parse_fragment(line, size, patch, fragment);1655if(len <=0)1656die(_("corrupt patch at line%d"), linenr);1657 fragment->patch = line;1658 fragment->size = len;1659 oldlines += fragment->oldlines;1660 newlines += fragment->newlines;1661 context += fragment->leading + fragment->trailing;16621663*fragp = fragment;1664 fragp = &fragment->next;16651666 offset += len;1667 line += len;1668 size -= len;1669}16701671/*1672 * If something was removed (i.e. we have old-lines) it cannot1673 * be creation, and if something was added it cannot be1674 * deletion. However, the reverse is not true; --unified=01675 * patches that only add are not necessarily creation even1676 * though they do not have any old lines, and ones that only1677 * delete are not necessarily deletion.1678 *1679 * Unfortunately, a real creation/deletion patch do _not_ have1680 * any context line by definition, so we cannot safely tell it1681 * apart with --unified=0 insanity. At least if the patch has1682 * more than one hunk it is not creation or deletion.1683 */1684if(patch->is_new <0&&1685(oldlines || (patch->fragments && patch->fragments->next)))1686 patch->is_new =0;1687if(patch->is_delete <0&&1688(newlines || (patch->fragments && patch->fragments->next)))1689 patch->is_delete =0;16901691if(0< patch->is_new && oldlines)1692die(_("new file%sdepends on old contents"), patch->new_name);1693if(0< patch->is_delete && newlines)1694die(_("deleted file%sstill has contents"), patch->old_name);1695if(!patch->is_delete && !newlines && context)1696fprintf_ln(stderr,1697_("** warning: "1698"file%sbecomes empty but is not deleted"),1699 patch->new_name);17001701return offset;1702}17031704staticinlineintmetadata_changes(struct patch *patch)1705{1706return patch->is_rename >0||1707 patch->is_copy >0||1708 patch->is_new >0||1709 patch->is_delete ||1710(patch->old_mode && patch->new_mode &&1711 patch->old_mode != patch->new_mode);1712}17131714static char*inflate_it(const void*data,unsigned long size,1715unsigned long inflated_size)1716{1717 git_zstream stream;1718void*out;1719int st;17201721memset(&stream,0,sizeof(stream));17221723 stream.next_in = (unsigned char*)data;1724 stream.avail_in = size;1725 stream.next_out = out =xmalloc(inflated_size);1726 stream.avail_out = inflated_size;1727git_inflate_init(&stream);1728 st =git_inflate(&stream, Z_FINISH);1729git_inflate_end(&stream);1730if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1731free(out);1732return NULL;1733}1734return out;1735}17361737/*1738 * Read a binary hunk and return a new fragment; fragment->patch1739 * points at an allocated memory that the caller must free, so1740 * it is marked as "->free_patch = 1".1741 */1742static struct fragment *parse_binary_hunk(char**buf_p,1743unsigned long*sz_p,1744int*status_p,1745int*used_p)1746{1747/*1748 * Expect a line that begins with binary patch method ("literal"1749 * or "delta"), followed by the length of data before deflating.1750 * a sequence of 'length-byte' followed by base-85 encoded data1751 * should follow, terminated by a newline.1752 *1753 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1754 * and we would limit the patch line to 66 characters,1755 * so one line can fit up to 13 groups that would decode1756 * to 52 bytes max. The length byte 'A'-'Z' corresponds1757 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1758 */1759int llen, used;1760unsigned long size = *sz_p;1761char*buffer = *buf_p;1762int patch_method;1763unsigned long origlen;1764char*data = NULL;1765int hunk_size =0;1766struct fragment *frag;17671768 llen =linelen(buffer, size);1769 used = llen;17701771*status_p =0;17721773if(!prefixcmp(buffer,"delta ")) {1774 patch_method = BINARY_DELTA_DEFLATED;1775 origlen =strtoul(buffer +6, NULL,10);1776}1777else if(!prefixcmp(buffer,"literal ")) {1778 patch_method = BINARY_LITERAL_DEFLATED;1779 origlen =strtoul(buffer +8, NULL,10);1780}1781else1782return NULL;17831784 linenr++;1785 buffer += llen;1786while(1) {1787int byte_length, max_byte_length, newsize;1788 llen =linelen(buffer, size);1789 used += llen;1790 linenr++;1791if(llen ==1) {1792/* consume the blank line */1793 buffer++;1794 size--;1795break;1796}1797/*1798 * Minimum line is "A00000\n" which is 7-byte long,1799 * and the line length must be multiple of 5 plus 2.1800 */1801if((llen <7) || (llen-2) %5)1802goto corrupt;1803 max_byte_length = (llen -2) /5*4;1804 byte_length = *buffer;1805if('A'<= byte_length && byte_length <='Z')1806 byte_length = byte_length -'A'+1;1807else if('a'<= byte_length && byte_length <='z')1808 byte_length = byte_length -'a'+27;1809else1810goto corrupt;1811/* if the input length was not multiple of 4, we would1812 * have filler at the end but the filler should never1813 * exceed 3 bytes1814 */1815if(max_byte_length < byte_length ||1816 byte_length <= max_byte_length -4)1817goto corrupt;1818 newsize = hunk_size + byte_length;1819 data =xrealloc(data, newsize);1820if(decode_85(data + hunk_size, buffer +1, byte_length))1821goto corrupt;1822 hunk_size = newsize;1823 buffer += llen;1824 size -= llen;1825}18261827 frag =xcalloc(1,sizeof(*frag));1828 frag->patch =inflate_it(data, hunk_size, origlen);1829 frag->free_patch =1;1830if(!frag->patch)1831goto corrupt;1832free(data);1833 frag->size = origlen;1834*buf_p = buffer;1835*sz_p = size;1836*used_p = used;1837 frag->binary_patch_method = patch_method;1838return frag;18391840 corrupt:1841free(data);1842*status_p = -1;1843error(_("corrupt binary patch at line%d: %.*s"),1844 linenr-1, llen-1, buffer);1845return NULL;1846}18471848static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1849{1850/*1851 * We have read "GIT binary patch\n"; what follows is a line1852 * that says the patch method (currently, either "literal" or1853 * "delta") and the length of data before deflating; a1854 * sequence of 'length-byte' followed by base-85 encoded data1855 * follows.1856 *1857 * When a binary patch is reversible, there is another binary1858 * hunk in the same format, starting with patch method (either1859 * "literal" or "delta") with the length of data, and a sequence1860 * of length-byte + base-85 encoded data, terminated with another1861 * empty line. This data, when applied to the postimage, produces1862 * the preimage.1863 */1864struct fragment *forward;1865struct fragment *reverse;1866int status;1867int used, used_1;18681869 forward =parse_binary_hunk(&buffer, &size, &status, &used);1870if(!forward && !status)1871/* there has to be one hunk (forward hunk) */1872returnerror(_("unrecognized binary patch at line%d"), linenr-1);1873if(status)1874/* otherwise we already gave an error message */1875return status;18761877 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1878if(reverse)1879 used += used_1;1880else if(status) {1881/*1882 * Not having reverse hunk is not an error, but having1883 * a corrupt reverse hunk is.1884 */1885free((void*) forward->patch);1886free(forward);1887return status;1888}1889 forward->next = reverse;1890 patch->fragments = forward;1891 patch->is_binary =1;1892return used;1893}18941895/*1896 * Read the patch text in "buffer" taht extends for "size" bytes; stop1897 * reading after seeing a single patch (i.e. changes to a single file).1898 * Create fragments (i.e. patch hunks) and hang them to the given patch.1899 * Return the number of bytes consumed, so that the caller can call us1900 * again for the next patch.1901 */1902static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1903{1904int hdrsize, patchsize;1905int offset =find_header(buffer, size, &hdrsize, patch);19061907if(offset <0)1908return offset;19091910 patch->ws_rule =whitespace_rule(patch->new_name1911? patch->new_name1912: patch->old_name);19131914 patchsize =parse_single_patch(buffer + offset + hdrsize,1915 size - offset - hdrsize, patch);19161917if(!patchsize) {1918static const char*binhdr[] = {1919"Binary files ",1920"Files ",1921 NULL,1922};1923static const char git_binary[] ="GIT binary patch\n";1924int i;1925int hd = hdrsize + offset;1926unsigned long llen =linelen(buffer + hd, size - hd);19271928if(llen ==sizeof(git_binary) -1&&1929!memcmp(git_binary, buffer + hd, llen)) {1930int used;1931 linenr++;1932 used =parse_binary(buffer + hd + llen,1933 size - hd - llen, patch);1934if(used)1935 patchsize = used + llen;1936else1937 patchsize =0;1938}1939else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1940for(i =0; binhdr[i]; i++) {1941int len =strlen(binhdr[i]);1942if(len < size - hd &&1943!memcmp(binhdr[i], buffer + hd, len)) {1944 linenr++;1945 patch->is_binary =1;1946 patchsize = llen;1947break;1948}1949}1950}19511952/* Empty patch cannot be applied if it is a text patch1953 * without metadata change. A binary patch appears1954 * empty to us here.1955 */1956if((apply || check) &&1957(!patch->is_binary && !metadata_changes(patch)))1958die(_("patch with only garbage at line%d"), linenr);1959}19601961return offset + hdrsize + patchsize;1962}19631964#define swap(a,b) myswap((a),(b),sizeof(a))19651966#define myswap(a, b, size) do { \1967 unsigned char mytmp[size]; \1968 memcpy(mytmp, &a, size); \1969 memcpy(&a, &b, size); \1970 memcpy(&b, mytmp, size); \1971} while (0)19721973static voidreverse_patches(struct patch *p)1974{1975for(; p; p = p->next) {1976struct fragment *frag = p->fragments;19771978swap(p->new_name, p->old_name);1979swap(p->new_mode, p->old_mode);1980swap(p->is_new, p->is_delete);1981swap(p->lines_added, p->lines_deleted);1982swap(p->old_sha1_prefix, p->new_sha1_prefix);19831984for(; frag; frag = frag->next) {1985swap(frag->newpos, frag->oldpos);1986swap(frag->newlines, frag->oldlines);1987}1988}1989}19901991static const char pluses[] =1992"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";1993static const char minuses[]=1994"----------------------------------------------------------------------";19951996static voidshow_stats(struct patch *patch)1997{1998struct strbuf qname = STRBUF_INIT;1999char*cp = patch->new_name ? patch->new_name : patch->old_name;2000int max, add, del;20012002quote_c_style(cp, &qname, NULL,0);20032004/*2005 * "scale" the filename2006 */2007 max = max_len;2008if(max >50)2009 max =50;20102011if(qname.len > max) {2012 cp =strchr(qname.buf + qname.len +3- max,'/');2013if(!cp)2014 cp = qname.buf + qname.len +3- max;2015strbuf_splice(&qname,0, cp - qname.buf,"...",3);2016}20172018if(patch->is_binary) {2019printf(" %-*s | Bin\n", max, qname.buf);2020strbuf_release(&qname);2021return;2022}20232024printf(" %-*s |", max, qname.buf);2025strbuf_release(&qname);20262027/*2028 * scale the add/delete2029 */2030 max = max + max_change >70?70- max : max_change;2031 add = patch->lines_added;2032 del = patch->lines_deleted;20332034if(max_change >0) {2035int total = ((add + del) * max + max_change /2) / max_change;2036 add = (add * max + max_change /2) / max_change;2037 del = total - add;2038}2039printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2040 add, pluses, del, minuses);2041}20422043static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2044{2045switch(st->st_mode & S_IFMT) {2046case S_IFLNK:2047if(strbuf_readlink(buf, path, st->st_size) <0)2048returnerror(_("unable to read symlink%s"), path);2049return0;2050case S_IFREG:2051if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2052returnerror(_("unable to open or read%s"), path);2053convert_to_git(path, buf->buf, buf->len, buf,0);2054return0;2055default:2056return-1;2057}2058}20592060/*2061 * Update the preimage, and the common lines in postimage,2062 * from buffer buf of length len. If postlen is 0 the postimage2063 * is updated in place, otherwise it's updated on a new buffer2064 * of length postlen2065 */20662067static voidupdate_pre_post_images(struct image *preimage,2068struct image *postimage,2069char*buf,2070size_t len,size_t postlen)2071{2072int i, ctx;2073char*new, *old, *fixed;2074struct image fixed_preimage;20752076/*2077 * Update the preimage with whitespace fixes. Note that we2078 * are not losing preimage->buf -- apply_one_fragment() will2079 * free "oldlines".2080 */2081prepare_image(&fixed_preimage, buf, len,1);2082assert(fixed_preimage.nr == preimage->nr);2083for(i =0; i < preimage->nr; i++)2084 fixed_preimage.line[i].flag = preimage->line[i].flag;2085free(preimage->line_allocated);2086*preimage = fixed_preimage;20872088/*2089 * Adjust the common context lines in postimage. This can be2090 * done in-place when we are just doing whitespace fixing,2091 * which does not make the string grow, but needs a new buffer2092 * when ignoring whitespace causes the update, since in this case2093 * we could have e.g. tabs converted to multiple spaces.2094 * We trust the caller to tell us if the update can be done2095 * in place (postlen==0) or not.2096 */2097 old = postimage->buf;2098if(postlen)2099new= postimage->buf =xmalloc(postlen);2100else2101new= old;2102 fixed = preimage->buf;2103for(i = ctx =0; i < postimage->nr; i++) {2104size_t len = postimage->line[i].len;2105if(!(postimage->line[i].flag & LINE_COMMON)) {2106/* an added line -- no counterparts in preimage */2107memmove(new, old, len);2108 old += len;2109new+= len;2110continue;2111}21122113/* a common context -- skip it in the original postimage */2114 old += len;21152116/* and find the corresponding one in the fixed preimage */2117while(ctx < preimage->nr &&2118!(preimage->line[ctx].flag & LINE_COMMON)) {2119 fixed += preimage->line[ctx].len;2120 ctx++;2121}2122if(preimage->nr <= ctx)2123die(_("oops"));21242125/* and copy it in, while fixing the line length */2126 len = preimage->line[ctx].len;2127memcpy(new, fixed, len);2128new+= len;2129 fixed += len;2130 postimage->line[i].len = len;2131 ctx++;2132}21332134/* Fix the length of the whole thing */2135 postimage->len =new- postimage->buf;2136}21372138static intmatch_fragment(struct image *img,2139struct image *preimage,2140struct image *postimage,2141unsigned longtry,2142int try_lno,2143unsigned ws_rule,2144int match_beginning,int match_end)2145{2146int i;2147char*fixed_buf, *buf, *orig, *target;2148struct strbuf fixed;2149size_t fixed_len;2150int preimage_limit;21512152if(preimage->nr + try_lno <= img->nr) {2153/*2154 * The hunk falls within the boundaries of img.2155 */2156 preimage_limit = preimage->nr;2157if(match_end && (preimage->nr + try_lno != img->nr))2158return0;2159}else if(ws_error_action == correct_ws_error &&2160(ws_rule & WS_BLANK_AT_EOF)) {2161/*2162 * This hunk extends beyond the end of img, and we are2163 * removing blank lines at the end of the file. This2164 * many lines from the beginning of the preimage must2165 * match with img, and the remainder of the preimage2166 * must be blank.2167 */2168 preimage_limit = img->nr - try_lno;2169}else{2170/*2171 * The hunk extends beyond the end of the img and2172 * we are not removing blanks at the end, so we2173 * should reject the hunk at this position.2174 */2175return0;2176}21772178if(match_beginning && try_lno)2179return0;21802181/* Quick hash check */2182for(i =0; i < preimage_limit; i++)2183if((img->line[try_lno + i].flag & LINE_PATCHED) ||2184(preimage->line[i].hash != img->line[try_lno + i].hash))2185return0;21862187if(preimage_limit == preimage->nr) {2188/*2189 * Do we have an exact match? If we were told to match2190 * at the end, size must be exactly at try+fragsize,2191 * otherwise try+fragsize must be still within the preimage,2192 * and either case, the old piece should match the preimage2193 * exactly.2194 */2195if((match_end2196? (try+ preimage->len == img->len)2197: (try+ preimage->len <= img->len)) &&2198!memcmp(img->buf +try, preimage->buf, preimage->len))2199return1;2200}else{2201/*2202 * The preimage extends beyond the end of img, so2203 * there cannot be an exact match.2204 *2205 * There must be one non-blank context line that match2206 * a line before the end of img.2207 */2208char*buf_end;22092210 buf = preimage->buf;2211 buf_end = buf;2212for(i =0; i < preimage_limit; i++)2213 buf_end += preimage->line[i].len;22142215for( ; buf < buf_end; buf++)2216if(!isspace(*buf))2217break;2218if(buf == buf_end)2219return0;2220}22212222/*2223 * No exact match. If we are ignoring whitespace, run a line-by-line2224 * fuzzy matching. We collect all the line length information because2225 * we need it to adjust whitespace if we match.2226 */2227if(ws_ignore_action == ignore_ws_change) {2228size_t imgoff =0;2229size_t preoff =0;2230size_t postlen = postimage->len;2231size_t extra_chars;2232char*preimage_eof;2233char*preimage_end;2234for(i =0; i < preimage_limit; i++) {2235size_t prelen = preimage->line[i].len;2236size_t imglen = img->line[try_lno+i].len;22372238if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2239 preimage->buf + preoff, prelen))2240return0;2241if(preimage->line[i].flag & LINE_COMMON)2242 postlen += imglen - prelen;2243 imgoff += imglen;2244 preoff += prelen;2245}22462247/*2248 * Ok, the preimage matches with whitespace fuzz.2249 *2250 * imgoff now holds the true length of the target that2251 * matches the preimage before the end of the file.2252 *2253 * Count the number of characters in the preimage that fall2254 * beyond the end of the file and make sure that all of them2255 * are whitespace characters. (This can only happen if2256 * we are removing blank lines at the end of the file.)2257 */2258 buf = preimage_eof = preimage->buf + preoff;2259for( ; i < preimage->nr; i++)2260 preoff += preimage->line[i].len;2261 preimage_end = preimage->buf + preoff;2262for( ; buf < preimage_end; buf++)2263if(!isspace(*buf))2264return0;22652266/*2267 * Update the preimage and the common postimage context2268 * lines to use the same whitespace as the target.2269 * If whitespace is missing in the target (i.e.2270 * if the preimage extends beyond the end of the file),2271 * use the whitespace from the preimage.2272 */2273 extra_chars = preimage_end - preimage_eof;2274strbuf_init(&fixed, imgoff + extra_chars);2275strbuf_add(&fixed, img->buf +try, imgoff);2276strbuf_add(&fixed, preimage_eof, extra_chars);2277 fixed_buf =strbuf_detach(&fixed, &fixed_len);2278update_pre_post_images(preimage, postimage,2279 fixed_buf, fixed_len, postlen);2280return1;2281}22822283if(ws_error_action != correct_ws_error)2284return0;22852286/*2287 * The hunk does not apply byte-by-byte, but the hash says2288 * it might with whitespace fuzz. We haven't been asked to2289 * ignore whitespace, we were asked to correct whitespace2290 * errors, so let's try matching after whitespace correction.2291 *2292 * The preimage may extend beyond the end of the file,2293 * but in this loop we will only handle the part of the2294 * preimage that falls within the file.2295 */2296strbuf_init(&fixed, preimage->len +1);2297 orig = preimage->buf;2298 target = img->buf +try;2299for(i =0; i < preimage_limit; i++) {2300size_t oldlen = preimage->line[i].len;2301size_t tgtlen = img->line[try_lno + i].len;2302size_t fixstart = fixed.len;2303struct strbuf tgtfix;2304int match;23052306/* Try fixing the line in the preimage */2307ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);23082309/* Try fixing the line in the target */2310strbuf_init(&tgtfix, tgtlen);2311ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);23122313/*2314 * If they match, either the preimage was based on2315 * a version before our tree fixed whitespace breakage,2316 * or we are lacking a whitespace-fix patch the tree2317 * the preimage was based on already had (i.e. target2318 * has whitespace breakage, the preimage doesn't).2319 * In either case, we are fixing the whitespace breakages2320 * so we might as well take the fix together with their2321 * real change.2322 */2323 match = (tgtfix.len == fixed.len - fixstart &&2324!memcmp(tgtfix.buf, fixed.buf + fixstart,2325 fixed.len - fixstart));23262327strbuf_release(&tgtfix);2328if(!match)2329goto unmatch_exit;23302331 orig += oldlen;2332 target += tgtlen;2333}233423352336/*2337 * Now handle the lines in the preimage that falls beyond the2338 * end of the file (if any). They will only match if they are2339 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2340 * false).2341 */2342for( ; i < preimage->nr; i++) {2343size_t fixstart = fixed.len;/* start of the fixed preimage */2344size_t oldlen = preimage->line[i].len;2345int j;23462347/* Try fixing the line in the preimage */2348ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);23492350for(j = fixstart; j < fixed.len; j++)2351if(!isspace(fixed.buf[j]))2352goto unmatch_exit;23532354 orig += oldlen;2355}23562357/*2358 * Yes, the preimage is based on an older version that still2359 * has whitespace breakages unfixed, and fixing them makes the2360 * hunk match. Update the context lines in the postimage.2361 */2362 fixed_buf =strbuf_detach(&fixed, &fixed_len);2363update_pre_post_images(preimage, postimage,2364 fixed_buf, fixed_len,0);2365return1;23662367 unmatch_exit:2368strbuf_release(&fixed);2369return0;2370}23712372static intfind_pos(struct image *img,2373struct image *preimage,2374struct image *postimage,2375int line,2376unsigned ws_rule,2377int match_beginning,int match_end)2378{2379int i;2380unsigned long backwards, forwards,try;2381int backwards_lno, forwards_lno, try_lno;23822383/*2384 * If match_beginning or match_end is specified, there is no2385 * point starting from a wrong line that will never match and2386 * wander around and wait for a match at the specified end.2387 */2388if(match_beginning)2389 line =0;2390else if(match_end)2391 line = img->nr - preimage->nr;23922393/*2394 * Because the comparison is unsigned, the following test2395 * will also take care of a negative line number that can2396 * result when match_end and preimage is larger than the target.2397 */2398if((size_t) line > img->nr)2399 line = img->nr;24002401try=0;2402for(i =0; i < line; i++)2403try+= img->line[i].len;24042405/*2406 * There's probably some smart way to do this, but I'll leave2407 * that to the smart and beautiful people. I'm simple and stupid.2408 */2409 backwards =try;2410 backwards_lno = line;2411 forwards =try;2412 forwards_lno = line;2413 try_lno = line;24142415for(i =0; ; i++) {2416if(match_fragment(img, preimage, postimage,2417try, try_lno, ws_rule,2418 match_beginning, match_end))2419return try_lno;24202421 again:2422if(backwards_lno ==0&& forwards_lno == img->nr)2423break;24242425if(i &1) {2426if(backwards_lno ==0) {2427 i++;2428goto again;2429}2430 backwards_lno--;2431 backwards -= img->line[backwards_lno].len;2432try= backwards;2433 try_lno = backwards_lno;2434}else{2435if(forwards_lno == img->nr) {2436 i++;2437goto again;2438}2439 forwards += img->line[forwards_lno].len;2440 forwards_lno++;2441try= forwards;2442 try_lno = forwards_lno;2443}24442445}2446return-1;2447}24482449static voidremove_first_line(struct image *img)2450{2451 img->buf += img->line[0].len;2452 img->len -= img->line[0].len;2453 img->line++;2454 img->nr--;2455}24562457static voidremove_last_line(struct image *img)2458{2459 img->len -= img->line[--img->nr].len;2460}24612462/*2463 * The change from "preimage" and "postimage" has been found to2464 * apply at applied_pos (counts in line numbers) in "img".2465 * Update "img" to remove "preimage" and replace it with "postimage".2466 */2467static voidupdate_image(struct image *img,2468int applied_pos,2469struct image *preimage,2470struct image *postimage)2471{2472/*2473 * remove the copy of preimage at offset in img2474 * and replace it with postimage2475 */2476int i, nr;2477size_t remove_count, insert_count, applied_at =0;2478char*result;2479int preimage_limit;24802481/*2482 * If we are removing blank lines at the end of img,2483 * the preimage may extend beyond the end.2484 * If that is the case, we must be careful only to2485 * remove the part of the preimage that falls within2486 * the boundaries of img. Initialize preimage_limit2487 * to the number of lines in the preimage that falls2488 * within the boundaries.2489 */2490 preimage_limit = preimage->nr;2491if(preimage_limit > img->nr - applied_pos)2492 preimage_limit = img->nr - applied_pos;24932494for(i =0; i < applied_pos; i++)2495 applied_at += img->line[i].len;24962497 remove_count =0;2498for(i =0; i < preimage_limit; i++)2499 remove_count += img->line[applied_pos + i].len;2500 insert_count = postimage->len;25012502/* Adjust the contents */2503 result =xmalloc(img->len + insert_count - remove_count +1);2504memcpy(result, img->buf, applied_at);2505memcpy(result + applied_at, postimage->buf, postimage->len);2506memcpy(result + applied_at + postimage->len,2507 img->buf + (applied_at + remove_count),2508 img->len - (applied_at + remove_count));2509free(img->buf);2510 img->buf = result;2511 img->len += insert_count - remove_count;2512 result[img->len] ='\0';25132514/* Adjust the line table */2515 nr = img->nr + postimage->nr - preimage_limit;2516if(preimage_limit < postimage->nr) {2517/*2518 * NOTE: this knows that we never call remove_first_line()2519 * on anything other than pre/post image.2520 */2521 img->line =xrealloc(img->line, nr *sizeof(*img->line));2522 img->line_allocated = img->line;2523}2524if(preimage_limit != postimage->nr)2525memmove(img->line + applied_pos + postimage->nr,2526 img->line + applied_pos + preimage_limit,2527(img->nr - (applied_pos + preimage_limit)) *2528sizeof(*img->line));2529memcpy(img->line + applied_pos,2530 postimage->line,2531 postimage->nr *sizeof(*img->line));2532if(!allow_overlap)2533for(i =0; i < postimage->nr; i++)2534 img->line[applied_pos + i].flag |= LINE_PATCHED;2535 img->nr = nr;2536}25372538/*2539 * Use the patch-hunk text in "frag" to prepare two images (preimage and2540 * postimage) for the hunk. Find lines that match "preimage" in "img" and2541 * replace the part of "img" with "postimage" text.2542 */2543static intapply_one_fragment(struct image *img,struct fragment *frag,2544int inaccurate_eof,unsigned ws_rule,2545int nth_fragment)2546{2547int match_beginning, match_end;2548const char*patch = frag->patch;2549int size = frag->size;2550char*old, *oldlines;2551struct strbuf newlines;2552int new_blank_lines_at_end =0;2553int found_new_blank_lines_at_end =0;2554int hunk_linenr = frag->linenr;2555unsigned long leading, trailing;2556int pos, applied_pos;2557struct image preimage;2558struct image postimage;25592560memset(&preimage,0,sizeof(preimage));2561memset(&postimage,0,sizeof(postimage));2562 oldlines =xmalloc(size);2563strbuf_init(&newlines, size);25642565 old = oldlines;2566while(size >0) {2567char first;2568int len =linelen(patch, size);2569int plen;2570int added_blank_line =0;2571int is_blank_context =0;2572size_t start;25732574if(!len)2575break;25762577/*2578 * "plen" is how much of the line we should use for2579 * the actual patch data. Normally we just remove the2580 * first character on the line, but if the line is2581 * followed by "\ No newline", then we also remove the2582 * last one (which is the newline, of course).2583 */2584 plen = len -1;2585if(len < size && patch[len] =='\\')2586 plen--;2587 first = *patch;2588if(apply_in_reverse) {2589if(first =='-')2590 first ='+';2591else if(first =='+')2592 first ='-';2593}25942595switch(first) {2596case'\n':2597/* Newer GNU diff, empty context line */2598if(plen <0)2599/* ... followed by '\No newline'; nothing */2600break;2601*old++ ='\n';2602strbuf_addch(&newlines,'\n');2603add_line_info(&preimage,"\n",1, LINE_COMMON);2604add_line_info(&postimage,"\n",1, LINE_COMMON);2605 is_blank_context =1;2606break;2607case' ':2608if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2609ws_blank_line(patch +1, plen, ws_rule))2610 is_blank_context =1;2611case'-':2612memcpy(old, patch +1, plen);2613add_line_info(&preimage, old, plen,2614(first ==' '? LINE_COMMON :0));2615 old += plen;2616if(first =='-')2617break;2618/* Fall-through for ' ' */2619case'+':2620/* --no-add does not add new lines */2621if(first =='+'&& no_add)2622break;26232624 start = newlines.len;2625if(first !='+'||2626!whitespace_error ||2627 ws_error_action != correct_ws_error) {2628strbuf_add(&newlines, patch +1, plen);2629}2630else{2631ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2632}2633add_line_info(&postimage, newlines.buf + start, newlines.len - start,2634(first =='+'?0: LINE_COMMON));2635if(first =='+'&&2636(ws_rule & WS_BLANK_AT_EOF) &&2637ws_blank_line(patch +1, plen, ws_rule))2638 added_blank_line =1;2639break;2640case'@':case'\\':2641/* Ignore it, we already handled it */2642break;2643default:2644if(apply_verbosely)2645error(_("invalid start of line: '%c'"), first);2646return-1;2647}2648if(added_blank_line) {2649if(!new_blank_lines_at_end)2650 found_new_blank_lines_at_end = hunk_linenr;2651 new_blank_lines_at_end++;2652}2653else if(is_blank_context)2654;2655else2656 new_blank_lines_at_end =0;2657 patch += len;2658 size -= len;2659 hunk_linenr++;2660}2661if(inaccurate_eof &&2662 old > oldlines && old[-1] =='\n'&&2663 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2664 old--;2665strbuf_setlen(&newlines, newlines.len -1);2666}26672668 leading = frag->leading;2669 trailing = frag->trailing;26702671/*2672 * A hunk to change lines at the beginning would begin with2673 * @@ -1,L +N,M @@2674 * but we need to be careful. -U0 that inserts before the second2675 * line also has this pattern.2676 *2677 * And a hunk to add to an empty file would begin with2678 * @@ -0,0 +N,M @@2679 *2680 * In other words, a hunk that is (frag->oldpos <= 1) with or2681 * without leading context must match at the beginning.2682 */2683 match_beginning = (!frag->oldpos ||2684(frag->oldpos ==1&& !unidiff_zero));26852686/*2687 * A hunk without trailing lines must match at the end.2688 * However, we simply cannot tell if a hunk must match end2689 * from the lack of trailing lines if the patch was generated2690 * with unidiff without any context.2691 */2692 match_end = !unidiff_zero && !trailing;26932694 pos = frag->newpos ? (frag->newpos -1) :0;2695 preimage.buf = oldlines;2696 preimage.len = old - oldlines;2697 postimage.buf = newlines.buf;2698 postimage.len = newlines.len;2699 preimage.line = preimage.line_allocated;2700 postimage.line = postimage.line_allocated;27012702for(;;) {27032704 applied_pos =find_pos(img, &preimage, &postimage, pos,2705 ws_rule, match_beginning, match_end);27062707if(applied_pos >=0)2708break;27092710/* Am I at my context limits? */2711if((leading <= p_context) && (trailing <= p_context))2712break;2713if(match_beginning || match_end) {2714 match_beginning = match_end =0;2715continue;2716}27172718/*2719 * Reduce the number of context lines; reduce both2720 * leading and trailing if they are equal otherwise2721 * just reduce the larger context.2722 */2723if(leading >= trailing) {2724remove_first_line(&preimage);2725remove_first_line(&postimage);2726 pos--;2727 leading--;2728}2729if(trailing > leading) {2730remove_last_line(&preimage);2731remove_last_line(&postimage);2732 trailing--;2733}2734}27352736if(applied_pos >=0) {2737if(new_blank_lines_at_end &&2738 preimage.nr + applied_pos >= img->nr &&2739(ws_rule & WS_BLANK_AT_EOF) &&2740 ws_error_action != nowarn_ws_error) {2741record_ws_error(WS_BLANK_AT_EOF,"+",1,2742 found_new_blank_lines_at_end);2743if(ws_error_action == correct_ws_error) {2744while(new_blank_lines_at_end--)2745remove_last_line(&postimage);2746}2747/*2748 * We would want to prevent write_out_results()2749 * from taking place in apply_patch() that follows2750 * the callchain led us here, which is:2751 * apply_patch->check_patch_list->check_patch->2752 * apply_data->apply_fragments->apply_one_fragment2753 */2754if(ws_error_action == die_on_ws_error)2755 apply =0;2756}27572758if(apply_verbosely && applied_pos != pos) {2759int offset = applied_pos - pos;2760if(apply_in_reverse)2761 offset =0- offset;2762fprintf_ln(stderr,2763Q_("Hunk #%dsucceeded at%d(offset%dline).",2764"Hunk #%dsucceeded at%d(offset%dlines).",2765 offset),2766 nth_fragment, applied_pos +1, offset);2767}27682769/*2770 * Warn if it was necessary to reduce the number2771 * of context lines.2772 */2773if((leading != frag->leading) ||2774(trailing != frag->trailing))2775fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2776" to apply fragment at%d"),2777 leading, trailing, applied_pos+1);2778update_image(img, applied_pos, &preimage, &postimage);2779}else{2780if(apply_verbosely)2781error(_("while searching for:\n%.*s"),2782(int)(old - oldlines), oldlines);2783}27842785free(oldlines);2786strbuf_release(&newlines);2787free(preimage.line_allocated);2788free(postimage.line_allocated);27892790return(applied_pos <0);2791}27922793static intapply_binary_fragment(struct image *img,struct patch *patch)2794{2795struct fragment *fragment = patch->fragments;2796unsigned long len;2797void*dst;27982799if(!fragment)2800returnerror(_("missing binary patch data for '%s'"),2801 patch->new_name ?2802 patch->new_name :2803 patch->old_name);28042805/* Binary patch is irreversible without the optional second hunk */2806if(apply_in_reverse) {2807if(!fragment->next)2808returnerror("cannot reverse-apply a binary patch "2809"without the reverse hunk to '%s'",2810 patch->new_name2811? patch->new_name : patch->old_name);2812 fragment = fragment->next;2813}2814switch(fragment->binary_patch_method) {2815case BINARY_DELTA_DEFLATED:2816 dst =patch_delta(img->buf, img->len, fragment->patch,2817 fragment->size, &len);2818if(!dst)2819return-1;2820clear_image(img);2821 img->buf = dst;2822 img->len = len;2823return0;2824case BINARY_LITERAL_DEFLATED:2825clear_image(img);2826 img->len = fragment->size;2827 img->buf =xmalloc(img->len+1);2828memcpy(img->buf, fragment->patch, img->len);2829 img->buf[img->len] ='\0';2830return0;2831}2832return-1;2833}28342835/*2836 * Replace "img" with the result of applying the binary patch.2837 * The binary patch data itself in patch->fragment is still kept2838 * but the preimage prepared by the caller in "img" is freed here2839 * or in the helper function apply_binary_fragment() this calls.2840 */2841static intapply_binary(struct image *img,struct patch *patch)2842{2843const char*name = patch->old_name ? patch->old_name : patch->new_name;2844unsigned char sha1[20];28452846/*2847 * For safety, we require patch index line to contain2848 * full 40-byte textual SHA1 for old and new, at least for now.2849 */2850if(strlen(patch->old_sha1_prefix) !=40||2851strlen(patch->new_sha1_prefix) !=40||2852get_sha1_hex(patch->old_sha1_prefix, sha1) ||2853get_sha1_hex(patch->new_sha1_prefix, sha1))2854returnerror("cannot apply binary patch to '%s' "2855"without full index line", name);28562857if(patch->old_name) {2858/*2859 * See if the old one matches what the patch2860 * applies to.2861 */2862hash_sha1_file(img->buf, img->len, blob_type, sha1);2863if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2864returnerror("the patch applies to '%s' (%s), "2865"which does not match the "2866"current contents.",2867 name,sha1_to_hex(sha1));2868}2869else{2870/* Otherwise, the old one must be empty. */2871if(img->len)2872returnerror("the patch applies to an empty "2873"'%s' but it is not empty", name);2874}28752876get_sha1_hex(patch->new_sha1_prefix, sha1);2877if(is_null_sha1(sha1)) {2878clear_image(img);2879return0;/* deletion patch */2880}28812882if(has_sha1_file(sha1)) {2883/* We already have the postimage */2884enum object_type type;2885unsigned long size;2886char*result;28872888 result =read_sha1_file(sha1, &type, &size);2889if(!result)2890returnerror("the necessary postimage%sfor "2891"'%s' cannot be read",2892 patch->new_sha1_prefix, name);2893clear_image(img);2894 img->buf = result;2895 img->len = size;2896}else{2897/*2898 * We have verified buf matches the preimage;2899 * apply the patch data to it, which is stored2900 * in the patch->fragments->{patch,size}.2901 */2902if(apply_binary_fragment(img, patch))2903returnerror(_("binary patch does not apply to '%s'"),2904 name);29052906/* verify that the result matches */2907hash_sha1_file(img->buf, img->len, blob_type, sha1);2908if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2909returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),2910 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2911}29122913return0;2914}29152916static intapply_fragments(struct image *img,struct patch *patch)2917{2918struct fragment *frag = patch->fragments;2919const char*name = patch->old_name ? patch->old_name : patch->new_name;2920unsigned ws_rule = patch->ws_rule;2921unsigned inaccurate_eof = patch->inaccurate_eof;2922int nth =0;29232924if(patch->is_binary)2925returnapply_binary(img, patch);29262927while(frag) {2928 nth++;2929if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {2930error(_("patch failed:%s:%ld"), name, frag->oldpos);2931if(!apply_with_reject)2932return-1;2933 frag->rejected =1;2934}2935 frag = frag->next;2936}2937return0;2938}29392940static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2941{2942if(!ce)2943return0;29442945if(S_ISGITLINK(ce->ce_mode)) {2946strbuf_grow(buf,100);2947strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2948}else{2949enum object_type type;2950unsigned long sz;2951char*result;29522953 result =read_sha1_file(ce->sha1, &type, &sz);2954if(!result)2955return-1;2956/* XXX read_sha1_file NUL-terminates */2957strbuf_attach(buf, result, sz, sz +1);2958}2959return0;2960}29612962static struct patch *in_fn_table(const char*name)2963{2964struct string_list_item *item;29652966if(name == NULL)2967return NULL;29682969 item =string_list_lookup(&fn_table, name);2970if(item != NULL)2971return(struct patch *)item->util;29722973return NULL;2974}29752976/*2977 * item->util in the filename table records the status of the path.2978 * Usually it points at a patch (whose result records the contents2979 * of it after applying it), but it could be PATH_WAS_DELETED for a2980 * path that a previously applied patch has already removed.2981 */2982#define PATH_TO_BE_DELETED ((struct patch *) -2)2983#define PATH_WAS_DELETED ((struct patch *) -1)29842985static intto_be_deleted(struct patch *patch)2986{2987return patch == PATH_TO_BE_DELETED;2988}29892990static intwas_deleted(struct patch *patch)2991{2992return patch == PATH_WAS_DELETED;2993}29942995static voidadd_to_fn_table(struct patch *patch)2996{2997struct string_list_item *item;29982999/*3000 * Always add new_name unless patch is a deletion3001 * This should cover the cases for normal diffs,3002 * file creations and copies3003 */3004if(patch->new_name != NULL) {3005 item =string_list_insert(&fn_table, patch->new_name);3006 item->util = patch;3007}30083009/*3010 * store a failure on rename/deletion cases because3011 * later chunks shouldn't patch old names3012 */3013if((patch->new_name == NULL) || (patch->is_rename)) {3014 item =string_list_insert(&fn_table, patch->old_name);3015 item->util = PATH_WAS_DELETED;3016}3017}30183019static voidprepare_fn_table(struct patch *patch)3020{3021/*3022 * store information about incoming file deletion3023 */3024while(patch) {3025if((patch->new_name == NULL) || (patch->is_rename)) {3026struct string_list_item *item;3027 item =string_list_insert(&fn_table, patch->old_name);3028 item->util = PATH_TO_BE_DELETED;3029}3030 patch = patch->next;3031}3032}30333034static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)3035{3036struct strbuf buf = STRBUF_INIT;3037struct image image;3038size_t len;3039char*img;3040struct patch *tpatch;30413042if(!(patch->is_copy || patch->is_rename) &&3043(tpatch =in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {3044if(was_deleted(tpatch)) {3045returnerror(_("patch%shas been renamed/deleted"),3046 patch->old_name);3047}3048/* We have a patched copy in memory; use that. */3049strbuf_add(&buf, tpatch->result, tpatch->resultsize);3050}else if(cached) {3051if(read_file_or_gitlink(ce, &buf))3052returnerror(_("read of%sfailed"), patch->old_name);3053}else if(patch->old_name) {3054if(S_ISGITLINK(patch->old_mode)) {3055if(ce) {3056read_file_or_gitlink(ce, &buf);3057}else{3058/*3059 * There is no way to apply subproject3060 * patch without looking at the index.3061 * NEEDSWORK: shouldn't this be flagged3062 * as an error???3063 */3064free_fragment_list(patch->fragments);3065 patch->fragments = NULL;3066}3067}else{3068if(read_old_data(st, patch->old_name, &buf))3069returnerror(_("read of%sfailed"), patch->old_name);3070}3071}30723073 img =strbuf_detach(&buf, &len);3074prepare_image(&image, img, len, !patch->is_binary);30753076if(apply_fragments(&image, patch) <0)3077return-1;/* note with --reject this succeeds. */3078 patch->result = image.buf;3079 patch->resultsize = image.len;3080add_to_fn_table(patch);3081free(image.line_allocated);30823083if(0< patch->is_delete && patch->resultsize)3084returnerror(_("removal patch leaves file contents"));30853086return0;3087}30883089static intcheck_to_create_blob(const char*new_name,int ok_if_exists)3090{3091struct stat nst;3092if(!lstat(new_name, &nst)) {3093if(S_ISDIR(nst.st_mode) || ok_if_exists)3094return0;3095/*3096 * A leading component of new_name might be a symlink3097 * that is going to be removed with this patch, but3098 * still pointing at somewhere that has the path.3099 * In such a case, path "new_name" does not exist as3100 * far as git is concerned.3101 */3102if(has_symlink_leading_path(new_name,strlen(new_name)))3103return0;31043105returnerror(_("%s: already exists in working directory"), new_name);3106}3107else if((errno != ENOENT) && (errno != ENOTDIR))3108returnerror("%s:%s", new_name,strerror(errno));3109return0;3110}31113112static intverify_index_match(struct cache_entry *ce,struct stat *st)3113{3114if(S_ISGITLINK(ce->ce_mode)) {3115if(!S_ISDIR(st->st_mode))3116return-1;3117return0;3118}3119returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3120}31213122static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)3123{3124const char*old_name = patch->old_name;3125struct patch *tpatch = NULL;3126int stat_ret =0;3127unsigned st_mode =0;31283129/*3130 * Make sure that we do not have local modifications from the3131 * index when we are looking at the index. Also make sure3132 * we have the preimage file to be patched in the work tree,3133 * unless --cached, which tells git to apply only in the index.3134 */3135if(!old_name)3136return0;31373138assert(patch->is_new <=0);31393140if(!(patch->is_copy || patch->is_rename) &&3141(tpatch =in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {3142if(was_deleted(tpatch))3143returnerror(_("%s: has been deleted/renamed"), old_name);3144 st_mode = tpatch->new_mode;3145}else if(!cached) {3146 stat_ret =lstat(old_name, st);3147if(stat_ret && errno != ENOENT)3148returnerror(_("%s:%s"), old_name,strerror(errno));3149}31503151if(to_be_deleted(tpatch))3152 tpatch = NULL;31533154if(check_index && !tpatch) {3155int pos =cache_name_pos(old_name,strlen(old_name));3156if(pos <0) {3157if(patch->is_new <0)3158goto is_new;3159returnerror(_("%s: does not exist in index"), old_name);3160}3161*ce = active_cache[pos];3162if(stat_ret <0) {3163struct checkout costate;3164/* checkout */3165memset(&costate,0,sizeof(costate));3166 costate.base_dir ="";3167 costate.refresh_cache =1;3168if(checkout_entry(*ce, &costate, NULL) ||3169lstat(old_name, st))3170return-1;3171}3172if(!cached &&verify_index_match(*ce, st))3173returnerror(_("%s: does not match index"), old_name);3174if(cached)3175 st_mode = (*ce)->ce_mode;3176}else if(stat_ret <0) {3177if(patch->is_new <0)3178goto is_new;3179returnerror(_("%s:%s"), old_name,strerror(errno));3180}31813182if(!cached && !tpatch)3183 st_mode =ce_mode_from_stat(*ce, st->st_mode);31843185if(patch->is_new <0)3186 patch->is_new =0;3187if(!patch->old_mode)3188 patch->old_mode = st_mode;3189if((st_mode ^ patch->old_mode) & S_IFMT)3190returnerror(_("%s: wrong type"), old_name);3191if(st_mode != patch->old_mode)3192warning(_("%shas type%o, expected%o"),3193 old_name, st_mode, patch->old_mode);3194if(!patch->new_mode && !patch->is_delete)3195 patch->new_mode = st_mode;3196return0;31973198 is_new:3199 patch->is_new =1;3200 patch->is_delete =0;3201free(patch->old_name);3202 patch->old_name = NULL;3203return0;3204}32053206/*3207 * Check and apply the patch in-core; leave the result in patch->result3208 * for the caller to write it out to the final destination.3209 */3210static intcheck_patch(struct patch *patch)3211{3212struct stat st;3213const char*old_name = patch->old_name;3214const char*new_name = patch->new_name;3215const char*name = old_name ? old_name : new_name;3216struct cache_entry *ce = NULL;3217struct patch *tpatch;3218int ok_if_exists;3219int status;32203221 patch->rejected =1;/* we will drop this after we succeed */32223223 status =check_preimage(patch, &ce, &st);3224if(status)3225return status;3226 old_name = patch->old_name;32273228if((tpatch =in_fn_table(new_name)) &&3229(was_deleted(tpatch) ||to_be_deleted(tpatch)))3230/*3231 * A type-change diff is always split into a patch to3232 * delete old, immediately followed by a patch to3233 * create new (see diff.c::run_diff()); in such a case3234 * it is Ok that the entry to be deleted by the3235 * previous patch is still in the working tree and in3236 * the index.3237 */3238 ok_if_exists =1;3239else3240 ok_if_exists =0;32413242if(new_name &&3243((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {3244if(check_index &&3245cache_name_pos(new_name,strlen(new_name)) >=0&&3246!ok_if_exists)3247returnerror(_("%s: already exists in index"), new_name);3248if(!cached) {3249int err =check_to_create_blob(new_name, ok_if_exists);3250if(err)3251return err;3252}3253if(!patch->new_mode) {3254if(0< patch->is_new)3255 patch->new_mode = S_IFREG |0644;3256else3257 patch->new_mode = patch->old_mode;3258}3259}32603261if(new_name && old_name) {3262int same = !strcmp(old_name, new_name);3263if(!patch->new_mode)3264 patch->new_mode = patch->old_mode;3265if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3266if(same)3267returnerror(_("new mode (%o) of%sdoes not "3268"match old mode (%o)"),3269 patch->new_mode, new_name,3270 patch->old_mode);3271else3272returnerror(_("new mode (%o) of%sdoes not "3273"match old mode (%o) of%s"),3274 patch->new_mode, new_name,3275 patch->old_mode, old_name);3276}3277}32783279if(apply_data(patch, &st, ce) <0)3280returnerror(_("%s: patch does not apply"), name);3281 patch->rejected =0;3282return0;3283}32843285static intcheck_patch_list(struct patch *patch)3286{3287int err =0;32883289prepare_fn_table(patch);3290while(patch) {3291if(apply_verbosely)3292say_patch_name(stderr,3293_("Checking patch%s..."), patch);3294 err |=check_patch(patch);3295 patch = patch->next;3296}3297return err;3298}32993300/* This function tries to read the sha1 from the current index */3301static intget_current_sha1(const char*path,unsigned char*sha1)3302{3303int pos;33043305if(read_cache() <0)3306return-1;3307 pos =cache_name_pos(path,strlen(path));3308if(pos <0)3309return-1;3310hashcpy(sha1, active_cache[pos]->sha1);3311return0;3312}33133314/* Build an index that contains the just the files needed for a 3way merge */3315static voidbuild_fake_ancestor(struct patch *list,const char*filename)3316{3317struct patch *patch;3318struct index_state result = { NULL };3319int fd;33203321/* Once we start supporting the reverse patch, it may be3322 * worth showing the new sha1 prefix, but until then...3323 */3324for(patch = list; patch; patch = patch->next) {3325const unsigned char*sha1_ptr;3326unsigned char sha1[20];3327struct cache_entry *ce;3328const char*name;33293330 name = patch->old_name ? patch->old_name : patch->new_name;3331if(0< patch->is_new)3332continue;3333else if(get_sha1(patch->old_sha1_prefix, sha1))3334/* git diff has no index line for mode/type changes */3335if(!patch->lines_added && !patch->lines_deleted) {3336if(get_current_sha1(patch->old_name, sha1))3337die("mode change for%s, which is not "3338"in current HEAD", name);3339 sha1_ptr = sha1;3340}else3341die("sha1 information is lacking or useless "3342"(%s).", name);3343else3344 sha1_ptr = sha1;33453346 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);3347if(!ce)3348die(_("make_cache_entry failed for path '%s'"), name);3349if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3350die("Could not add%sto temporary index", name);3351}33523353 fd =open(filename, O_WRONLY | O_CREAT,0666);3354if(fd <0||write_index(&result, fd) ||close(fd))3355die("Could not write temporary index to%s", filename);33563357discard_index(&result);3358}33593360static voidstat_patch_list(struct patch *patch)3361{3362int files, adds, dels;33633364for(files = adds = dels =0; patch ; patch = patch->next) {3365 files++;3366 adds += patch->lines_added;3367 dels += patch->lines_deleted;3368show_stats(patch);3369}33703371print_stat_summary(stdout, files, adds, dels);3372}33733374static voidnumstat_patch_list(struct patch *patch)3375{3376for( ; patch; patch = patch->next) {3377const char*name;3378 name = patch->new_name ? patch->new_name : patch->old_name;3379if(patch->is_binary)3380printf("-\t-\t");3381else3382printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3383write_name_quoted(name, stdout, line_termination);3384}3385}33863387static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3388{3389if(mode)3390printf("%smode%06o%s\n", newdelete, mode, name);3391else3392printf("%s %s\n", newdelete, name);3393}33943395static voidshow_mode_change(struct patch *p,int show_name)3396{3397if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3398if(show_name)3399printf(" mode change%06o =>%06o%s\n",3400 p->old_mode, p->new_mode, p->new_name);3401else3402printf(" mode change%06o =>%06o\n",3403 p->old_mode, p->new_mode);3404}3405}34063407static voidshow_rename_copy(struct patch *p)3408{3409const char*renamecopy = p->is_rename ?"rename":"copy";3410const char*old, *new;34113412/* Find common prefix */3413 old = p->old_name;3414new= p->new_name;3415while(1) {3416const char*slash_old, *slash_new;3417 slash_old =strchr(old,'/');3418 slash_new =strchr(new,'/');3419if(!slash_old ||3420!slash_new ||3421 slash_old - old != slash_new -new||3422memcmp(old,new, slash_new -new))3423break;3424 old = slash_old +1;3425new= slash_new +1;3426}3427/* p->old_name thru old is the common prefix, and old and new3428 * through the end of names are renames3429 */3430if(old != p->old_name)3431printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,3432(int)(old - p->old_name), p->old_name,3433 old,new, p->score);3434else3435printf("%s %s=>%s(%d%%)\n", renamecopy,3436 p->old_name, p->new_name, p->score);3437show_mode_change(p,0);3438}34393440static voidsummary_patch_list(struct patch *patch)3441{3442struct patch *p;34433444for(p = patch; p; p = p->next) {3445if(p->is_new)3446show_file_mode_name("create", p->new_mode, p->new_name);3447else if(p->is_delete)3448show_file_mode_name("delete", p->old_mode, p->old_name);3449else{3450if(p->is_rename || p->is_copy)3451show_rename_copy(p);3452else{3453if(p->score) {3454printf(" rewrite%s(%d%%)\n",3455 p->new_name, p->score);3456show_mode_change(p,0);3457}3458else3459show_mode_change(p,1);3460}3461}3462}3463}34643465static voidpatch_stats(struct patch *patch)3466{3467int lines = patch->lines_added + patch->lines_deleted;34683469if(lines > max_change)3470 max_change = lines;3471if(patch->old_name) {3472int len =quote_c_style(patch->old_name, NULL, NULL,0);3473if(!len)3474 len =strlen(patch->old_name);3475if(len > max_len)3476 max_len = len;3477}3478if(patch->new_name) {3479int len =quote_c_style(patch->new_name, NULL, NULL,0);3480if(!len)3481 len =strlen(patch->new_name);3482if(len > max_len)3483 max_len = len;3484}3485}34863487static voidremove_file(struct patch *patch,int rmdir_empty)3488{3489if(update_index) {3490if(remove_file_from_cache(patch->old_name) <0)3491die(_("unable to remove%sfrom index"), patch->old_name);3492}3493if(!cached) {3494if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {3495remove_path(patch->old_name);3496}3497}3498}34993500static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)3501{3502struct stat st;3503struct cache_entry *ce;3504int namelen =strlen(path);3505unsigned ce_size =cache_entry_size(namelen);35063507if(!update_index)3508return;35093510 ce =xcalloc(1, ce_size);3511memcpy(ce->name, path, namelen);3512 ce->ce_mode =create_ce_mode(mode);3513 ce->ce_flags = namelen;3514if(S_ISGITLINK(mode)) {3515const char*s = buf;35163517if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))3518die(_("corrupt patch for subproject%s"), path);3519}else{3520if(!cached) {3521if(lstat(path, &st) <0)3522die_errno(_("unable to stat newly created file '%s'"),3523 path);3524fill_stat_cache_info(ce, &st);3525}3526if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)3527die(_("unable to create backing store for newly created file%s"), path);3528}3529if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3530die(_("unable to add cache entry for%s"), path);3531}35323533static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)3534{3535int fd;3536struct strbuf nbuf = STRBUF_INIT;35373538if(S_ISGITLINK(mode)) {3539struct stat st;3540if(!lstat(path, &st) &&S_ISDIR(st.st_mode))3541return0;3542returnmkdir(path,0777);3543}35443545if(has_symlinks &&S_ISLNK(mode))3546/* Although buf:size is counted string, it also is NUL3547 * terminated.3548 */3549returnsymlink(buf, path);35503551 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);3552if(fd <0)3553return-1;35543555if(convert_to_working_tree(path, buf, size, &nbuf)) {3556 size = nbuf.len;3557 buf = nbuf.buf;3558}3559write_or_die(fd, buf, size);3560strbuf_release(&nbuf);35613562if(close(fd) <0)3563die_errno(_("closing file '%s'"), path);3564return0;3565}35663567/*3568 * We optimistically assume that the directories exist,3569 * which is true 99% of the time anyway. If they don't,3570 * we create them and try again.3571 */3572static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)3573{3574if(cached)3575return;3576if(!try_create_file(path, mode, buf, size))3577return;35783579if(errno == ENOENT) {3580if(safe_create_leading_directories(path))3581return;3582if(!try_create_file(path, mode, buf, size))3583return;3584}35853586if(errno == EEXIST || errno == EACCES) {3587/* We may be trying to create a file where a directory3588 * used to be.3589 */3590struct stat st;3591if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))3592 errno = EEXIST;3593}35943595if(errno == EEXIST) {3596unsigned int nr =getpid();35973598for(;;) {3599char newpath[PATH_MAX];3600mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);3601if(!try_create_file(newpath, mode, buf, size)) {3602if(!rename(newpath, path))3603return;3604unlink_or_warn(newpath);3605break;3606}3607if(errno != EEXIST)3608break;3609++nr;3610}3611}3612die_errno(_("unable to write file '%s' mode%o"), path, mode);3613}36143615static voidcreate_file(struct patch *patch)3616{3617char*path = patch->new_name;3618unsigned mode = patch->new_mode;3619unsigned long size = patch->resultsize;3620char*buf = patch->result;36213622if(!mode)3623 mode = S_IFREG |0644;3624create_one_file(path, mode, buf, size);3625add_index_file(path, mode, buf, size);3626}36273628/* phase zero is to remove, phase one is to create */3629static voidwrite_out_one_result(struct patch *patch,int phase)3630{3631if(patch->is_delete >0) {3632if(phase ==0)3633remove_file(patch,1);3634return;3635}3636if(patch->is_new >0|| patch->is_copy) {3637if(phase ==1)3638create_file(patch);3639return;3640}3641/*3642 * Rename or modification boils down to the same3643 * thing: remove the old, write the new3644 */3645if(phase ==0)3646remove_file(patch, patch->is_rename);3647if(phase ==1)3648create_file(patch);3649}36503651static intwrite_out_one_reject(struct patch *patch)3652{3653FILE*rej;3654char namebuf[PATH_MAX];3655struct fragment *frag;3656int cnt =0;3657struct strbuf sb = STRBUF_INIT;36583659for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {3660if(!frag->rejected)3661continue;3662 cnt++;3663}36643665if(!cnt) {3666if(apply_verbosely)3667say_patch_name(stderr,3668_("Applied patch%scleanly."), patch);3669return0;3670}36713672/* This should not happen, because a removal patch that leaves3673 * contents are marked "rejected" at the patch level.3674 */3675if(!patch->new_name)3676die(_("internal error"));36773678/* Say this even without --verbose */3679strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",3680"Applying patch %%swith%drejects...",3681 cnt),3682 cnt);3683say_patch_name(stderr, sb.buf, patch);3684strbuf_release(&sb);36853686 cnt =strlen(patch->new_name);3687if(ARRAY_SIZE(namebuf) <= cnt +5) {3688 cnt =ARRAY_SIZE(namebuf) -5;3689warning(_("truncating .rej filename to %.*s.rej"),3690 cnt -1, patch->new_name);3691}3692memcpy(namebuf, patch->new_name, cnt);3693memcpy(namebuf + cnt,".rej",5);36943695 rej =fopen(namebuf,"w");3696if(!rej)3697returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));36983699/* Normal git tools never deal with .rej, so do not pretend3700 * this is a git patch by saying --git nor give extended3701 * headers. While at it, maybe please "kompare" that wants3702 * the trailing TAB and some garbage at the end of line ;-).3703 */3704fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",3705 patch->new_name, patch->new_name);3706for(cnt =1, frag = patch->fragments;3707 frag;3708 cnt++, frag = frag->next) {3709if(!frag->rejected) {3710fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);3711continue;3712}3713fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);3714fprintf(rej,"%.*s", frag->size, frag->patch);3715if(frag->patch[frag->size-1] !='\n')3716fputc('\n', rej);3717}3718fclose(rej);3719return-1;3720}37213722static intwrite_out_results(struct patch *list)3723{3724int phase;3725int errs =0;3726struct patch *l;37273728for(phase =0; phase <2; phase++) {3729 l = list;3730while(l) {3731if(l->rejected)3732 errs =1;3733else{3734write_out_one_result(l, phase);3735if(phase ==1&&write_out_one_reject(l))3736 errs =1;3737}3738 l = l->next;3739}3740}3741return errs;3742}37433744static struct lock_file lock_file;37453746static struct string_list limit_by_name;3747static int has_include;3748static voidadd_name_limit(const char*name,int exclude)3749{3750struct string_list_item *it;37513752 it =string_list_append(&limit_by_name, name);3753 it->util = exclude ? NULL : (void*)1;3754}37553756static intuse_patch(struct patch *p)3757{3758const char*pathname = p->new_name ? p->new_name : p->old_name;3759int i;37603761/* Paths outside are not touched regardless of "--include" */3762if(0< prefix_length) {3763int pathlen =strlen(pathname);3764if(pathlen <= prefix_length ||3765memcmp(prefix, pathname, prefix_length))3766return0;3767}37683769/* See if it matches any of exclude/include rule */3770for(i =0; i < limit_by_name.nr; i++) {3771struct string_list_item *it = &limit_by_name.items[i];3772if(!fnmatch(it->string, pathname,0))3773return(it->util != NULL);3774}37753776/*3777 * If we had any include, a path that does not match any rule is3778 * not used. Otherwise, we saw bunch of exclude rules (or none)3779 * and such a path is used.3780 */3781return!has_include;3782}378337843785static voidprefix_one(char**name)3786{3787char*old_name = *name;3788if(!old_name)3789return;3790*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3791free(old_name);3792}37933794static voidprefix_patches(struct patch *p)3795{3796if(!prefix || p->is_toplevel_relative)3797return;3798for( ; p; p = p->next) {3799prefix_one(&p->new_name);3800prefix_one(&p->old_name);3801}3802}38033804#define INACCURATE_EOF (1<<0)3805#define RECOUNT (1<<1)38063807static intapply_patch(int fd,const char*filename,int options)3808{3809size_t offset;3810struct strbuf buf = STRBUF_INIT;/* owns the patch text */3811struct patch *list = NULL, **listp = &list;3812int skipped_patch =0;38133814 patch_input_file = filename;3815read_patch_file(&buf, fd);3816 offset =0;3817while(offset < buf.len) {3818struct patch *patch;3819int nr;38203821 patch =xcalloc(1,sizeof(*patch));3822 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3823 patch->recount = !!(options & RECOUNT);3824 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3825if(nr <0)3826break;3827if(apply_in_reverse)3828reverse_patches(patch);3829if(prefix)3830prefix_patches(patch);3831if(use_patch(patch)) {3832patch_stats(patch);3833*listp = patch;3834 listp = &patch->next;3835}3836else{3837free_patch(patch);3838 skipped_patch++;3839}3840 offset += nr;3841}38423843if(!list && !skipped_patch)3844die(_("unrecognized input"));38453846if(whitespace_error && (ws_error_action == die_on_ws_error))3847 apply =0;38483849 update_index = check_index && apply;3850if(update_index && newfd <0)3851 newfd =hold_locked_index(&lock_file,1);38523853if(check_index) {3854if(read_cache() <0)3855die(_("unable to read index file"));3856}38573858if((check || apply) &&3859check_patch_list(list) <0&&3860!apply_with_reject)3861exit(1);38623863if(apply &&write_out_results(list))3864exit(1);38653866if(fake_ancestor)3867build_fake_ancestor(list, fake_ancestor);38683869if(diffstat)3870stat_patch_list(list);38713872if(numstat)3873numstat_patch_list(list);38743875if(summary)3876summary_patch_list(list);38773878free_patch_list(list);3879strbuf_release(&buf);3880string_list_clear(&fn_table,0);3881return0;3882}38833884static intgit_apply_config(const char*var,const char*value,void*cb)3885{3886if(!strcmp(var,"apply.whitespace"))3887returngit_config_string(&apply_default_whitespace, var, value);3888else if(!strcmp(var,"apply.ignorewhitespace"))3889returngit_config_string(&apply_default_ignorewhitespace, var, value);3890returngit_default_config(var, value, cb);3891}38923893static intoption_parse_exclude(const struct option *opt,3894const char*arg,int unset)3895{3896add_name_limit(arg,1);3897return0;3898}38993900static intoption_parse_include(const struct option *opt,3901const char*arg,int unset)3902{3903add_name_limit(arg,0);3904 has_include =1;3905return0;3906}39073908static intoption_parse_p(const struct option *opt,3909const char*arg,int unset)3910{3911 p_value =atoi(arg);3912 p_value_known =1;3913return0;3914}39153916static intoption_parse_z(const struct option *opt,3917const char*arg,int unset)3918{3919if(unset)3920 line_termination ='\n';3921else3922 line_termination =0;3923return0;3924}39253926static intoption_parse_space_change(const struct option *opt,3927const char*arg,int unset)3928{3929if(unset)3930 ws_ignore_action = ignore_ws_none;3931else3932 ws_ignore_action = ignore_ws_change;3933return0;3934}39353936static intoption_parse_whitespace(const struct option *opt,3937const char*arg,int unset)3938{3939const char**whitespace_option = opt->value;39403941*whitespace_option = arg;3942parse_whitespace_option(arg);3943return0;3944}39453946static intoption_parse_directory(const struct option *opt,3947const char*arg,int unset)3948{3949 root_len =strlen(arg);3950if(root_len && arg[root_len -1] !='/') {3951char*new_root;3952 root = new_root =xmalloc(root_len +2);3953strcpy(new_root, arg);3954strcpy(new_root + root_len++,"/");3955}else3956 root = arg;3957return0;3958}39593960intcmd_apply(int argc,const char**argv,const char*prefix_)3961{3962int i;3963int errs =0;3964int is_not_gitdir = !startup_info->have_repository;3965int force_apply =0;39663967const char*whitespace_option = NULL;39683969struct option builtin_apply_options[] = {3970{ OPTION_CALLBACK,0,"exclude", NULL,N_("path"),3971N_("don't apply changes matching the given path"),39720, option_parse_exclude },3973{ OPTION_CALLBACK,0,"include", NULL,N_("path"),3974N_("apply changes matching the given path"),39750, option_parse_include },3976{ OPTION_CALLBACK,'p', NULL, NULL,N_("num"),3977N_("remove <num> leading slashes from traditional diff paths"),39780, option_parse_p },3979OPT_BOOLEAN(0,"no-add", &no_add,3980N_("ignore additions made by the patch")),3981OPT_BOOLEAN(0,"stat", &diffstat,3982N_("instead of applying the patch, output diffstat for the input")),3983OPT_NOOP_NOARG(0,"allow-binary-replacement"),3984OPT_NOOP_NOARG(0,"binary"),3985OPT_BOOLEAN(0,"numstat", &numstat,3986N_("shows number of added and deleted lines in decimal notation")),3987OPT_BOOLEAN(0,"summary", &summary,3988N_("instead of applying the patch, output a summary for the input")),3989OPT_BOOLEAN(0,"check", &check,3990N_("instead of applying the patch, see if the patch is applicable")),3991OPT_BOOLEAN(0,"index", &check_index,3992N_("make sure the patch is applicable to the current index")),3993OPT_BOOLEAN(0,"cached", &cached,3994N_("apply a patch without touching the working tree")),3995OPT_BOOLEAN(0,"apply", &force_apply,3996N_("also apply the patch (use with --stat/--summary/--check)")),3997OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,3998N_("build a temporary index based on embedded index information")),3999{ OPTION_CALLBACK,'z', NULL, NULL, NULL,4000N_("paths are separated with NUL character"),4001 PARSE_OPT_NOARG, option_parse_z },4002OPT_INTEGER('C', NULL, &p_context,4003N_("ensure at least <n> lines of context match")),4004{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,N_("action"),4005N_("detect new or modified lines that have whitespace errors"),40060, option_parse_whitespace },4007{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,4008N_("ignore changes in whitespace when finding context"),4009 PARSE_OPT_NOARG, option_parse_space_change },4010{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,4011N_("ignore changes in whitespace when finding context"),4012 PARSE_OPT_NOARG, option_parse_space_change },4013OPT_BOOLEAN('R',"reverse", &apply_in_reverse,4014N_("apply the patch in reverse")),4015OPT_BOOLEAN(0,"unidiff-zero", &unidiff_zero,4016N_("don't expect at least one line of context")),4017OPT_BOOLEAN(0,"reject", &apply_with_reject,4018N_("leave the rejected hunks in corresponding *.rej files")),4019OPT_BOOLEAN(0,"allow-overlap", &allow_overlap,4020N_("allow overlapping hunks")),4021OPT__VERBOSE(&apply_verbosely,N_("be verbose")),4022OPT_BIT(0,"inaccurate-eof", &options,4023N_("tolerate incorrectly detected missing new-line at the end of file"),4024 INACCURATE_EOF),4025OPT_BIT(0,"recount", &options,4026N_("do not trust the line counts in the hunk headers"),4027 RECOUNT),4028{ OPTION_CALLBACK,0,"directory", NULL,N_("root"),4029N_("prepend <root> to all filenames"),40300, option_parse_directory },4031OPT_END()4032};40334034 prefix = prefix_;4035 prefix_length = prefix ?strlen(prefix) :0;4036git_config(git_apply_config, NULL);4037if(apply_default_whitespace)4038parse_whitespace_option(apply_default_whitespace);4039if(apply_default_ignorewhitespace)4040parse_ignorewhitespace_option(apply_default_ignorewhitespace);40414042 argc =parse_options(argc, argv, prefix, builtin_apply_options,4043 apply_usage,0);40444045if(apply_with_reject)4046 apply = apply_verbosely =1;4047if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))4048 apply =0;4049if(check_index && is_not_gitdir)4050die(_("--index outside a repository"));4051if(cached) {4052if(is_not_gitdir)4053die(_("--cached outside a repository"));4054 check_index =1;4055}4056for(i =0; i < argc; i++) {4057const char*arg = argv[i];4058int fd;40594060if(!strcmp(arg,"-")) {4061 errs |=apply_patch(0,"<stdin>", options);4062 read_stdin =0;4063continue;4064}else if(0< prefix_length)4065 arg =prefix_filename(prefix, prefix_length, arg);40664067 fd =open(arg, O_RDONLY);4068if(fd <0)4069die_errno(_("can't open patch '%s'"), arg);4070 read_stdin =0;4071set_default_whitespace_mode(whitespace_option);4072 errs |=apply_patch(fd, arg, options);4073close(fd);4074}4075set_default_whitespace_mode(whitespace_option);4076if(read_stdin)4077 errs |=apply_patch(0,"<stdin>", options);4078if(whitespace_error) {4079if(squelch_whitespace_errors &&4080 squelch_whitespace_errors < whitespace_error) {4081int squelched =4082 whitespace_error - squelch_whitespace_errors;4083warning(Q_("squelched%dwhitespace error",4084"squelched%dwhitespace errors",4085 squelched),4086 squelched);4087}4088if(ws_error_action == die_on_ws_error)4089die(Q_("%dline adds whitespace errors.",4090"%dlines add whitespace errors.",4091 whitespace_error),4092 whitespace_error);4093if(applied_after_fixing_ws && apply)4094warning("%dline%sapplied after"4095" fixing whitespace errors.",4096 applied_after_fixing_ws,4097 applied_after_fixing_ws ==1?"":"s");4098else if(whitespace_error)4099warning(Q_("%dline adds whitespace errors.",4100"%dlines add whitespace errors.",4101 whitespace_error),4102 whitespace_error);4103}41044105if(update_index) {4106if(write_cache(newfd, active_cache, active_nr) ||4107commit_locked_index(&lock_file))4108die(_("Unable to write new index file"));4109}41104111return!!errs;4112}