1/* 2 * apply.c 3 * 4 * Copyright (C) Linus Torvalds, 2005 5 * 6 * This applies patches on top of some (arbitrary) version of the SCM. 7 * 8 */ 9#include"cache.h" 10#include"cache-tree.h" 11#include"quote.h" 12#include"blob.h" 13#include"delta.h" 14#include"builtin.h" 15#include"string-list.h" 16#include"dir.h" 17#include"diff.h" 18#include"parse-options.h" 19 20/* 21 * --check turns on checking that the working tree matches the 22 * files that are being modified, but doesn't apply the patch 23 * --stat does just a diffstat, and doesn't actually apply 24 * --numstat does numeric diffstat, and doesn't actually apply 25 * --index-info shows the old and new index info for paths if available. 26 * --index updates the cache as well. 27 * --cached updates only the cache without ever touching the working tree. 28 */ 29static const char*prefix; 30static int prefix_length = -1; 31static int newfd = -1; 32 33static int unidiff_zero; 34static int p_value =1; 35static int p_value_known; 36static int check_index; 37static int update_index; 38static int cached; 39static int diffstat; 40static int numstat; 41static int summary; 42static int check; 43static int apply =1; 44static int apply_in_reverse; 45static int apply_with_reject; 46static int apply_verbosely; 47static int allow_overlap; 48static int no_add; 49static const char*fake_ancestor; 50static int line_termination ='\n'; 51static unsigned int p_context = UINT_MAX; 52static const char*const apply_usage[] = { 53"git apply [options] [<patch>...]", 54 NULL 55}; 56 57static enum ws_error_action { 58 nowarn_ws_error, 59 warn_on_ws_error, 60 die_on_ws_error, 61 correct_ws_error 62} ws_error_action = warn_on_ws_error; 63static int whitespace_error; 64static int squelch_whitespace_errors =5; 65static int applied_after_fixing_ws; 66 67static enum ws_ignore { 68 ignore_ws_none, 69 ignore_ws_change 70} ws_ignore_action = ignore_ws_none; 71 72 73static const char*patch_input_file; 74static const char*root; 75static int root_len; 76static int read_stdin =1; 77static int options; 78 79static voidparse_whitespace_option(const char*option) 80{ 81if(!option) { 82 ws_error_action = warn_on_ws_error; 83return; 84} 85if(!strcmp(option,"warn")) { 86 ws_error_action = warn_on_ws_error; 87return; 88} 89if(!strcmp(option,"nowarn")) { 90 ws_error_action = nowarn_ws_error; 91return; 92} 93if(!strcmp(option,"error")) { 94 ws_error_action = die_on_ws_error; 95return; 96} 97if(!strcmp(option,"error-all")) { 98 ws_error_action = die_on_ws_error; 99 squelch_whitespace_errors =0; 100return; 101} 102if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 103 ws_error_action = correct_ws_error; 104return; 105} 106die(_("unrecognized whitespace option '%s'"), option); 107} 108 109static voidparse_ignorewhitespace_option(const char*option) 110{ 111if(!option || !strcmp(option,"no") || 112!strcmp(option,"false") || !strcmp(option,"never") || 113!strcmp(option,"none")) { 114 ws_ignore_action = ignore_ws_none; 115return; 116} 117if(!strcmp(option,"change")) { 118 ws_ignore_action = ignore_ws_change; 119return; 120} 121die(_("unrecognized whitespace ignore option '%s'"), option); 122} 123 124static voidset_default_whitespace_mode(const char*whitespace_option) 125{ 126if(!whitespace_option && !apply_default_whitespace) 127 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 128} 129 130/* 131 * For "diff-stat" like behaviour, we keep track of the biggest change 132 * we've seen, and the longest filename. That allows us to do simple 133 * scaling. 134 */ 135static int max_change, max_len; 136 137/* 138 * Various "current state", notably line numbers and what 139 * file (and how) we're patching right now.. The "is_xxxx" 140 * things are flags, where -1 means "don't know yet". 141 */ 142static int linenr =1; 143 144/* 145 * This represents one "hunk" from a patch, starting with 146 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 147 * patch text is pointed at by patch, and its byte length 148 * is stored in size. leading and trailing are the number 149 * of context lines. 150 */ 151struct fragment { 152unsigned long leading, trailing; 153unsigned long oldpos, oldlines; 154unsigned long newpos, newlines; 155/* 156 * 'patch' is usually borrowed from buf in apply_patch(), 157 * but some codepaths store an allocated buffer. 158 */ 159const char*patch; 160unsigned free_patch:1, 161 rejected:1; 162int size; 163int linenr; 164struct fragment *next; 165}; 166 167/* 168 * When dealing with a binary patch, we reuse "leading" field 169 * to store the type of the binary hunk, either deflated "delta" 170 * or deflated "literal". 171 */ 172#define binary_patch_method leading 173#define BINARY_DELTA_DEFLATED 1 174#define BINARY_LITERAL_DEFLATED 2 175 176/* 177 * This represents a "patch" to a file, both metainfo changes 178 * such as creation/deletion, filemode and content changes represented 179 * as a series of fragments. 180 */ 181struct patch { 182char*new_name, *old_name, *def_name; 183unsigned int old_mode, new_mode; 184int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 185int rejected; 186unsigned ws_rule; 187unsigned long deflate_origlen; 188int lines_added, lines_deleted; 189int score; 190unsigned int is_toplevel_relative:1; 191unsigned int inaccurate_eof:1; 192unsigned int is_binary:1; 193unsigned int is_copy:1; 194unsigned int is_rename:1; 195unsigned int recount:1; 196struct fragment *fragments; 197char*result; 198size_t resultsize; 199char old_sha1_prefix[41]; 200char new_sha1_prefix[41]; 201struct patch *next; 202}; 203 204static voidfree_fragment_list(struct fragment *list) 205{ 206while(list) { 207struct fragment *next = list->next; 208if(list->free_patch) 209free((char*)list->patch); 210free(list); 211 list = next; 212} 213} 214 215static voidfree_patch(struct patch *patch) 216{ 217free_fragment_list(patch->fragments); 218free(patch->def_name); 219free(patch->old_name); 220free(patch->new_name); 221free(patch->result); 222free(patch); 223} 224 225static voidfree_patch_list(struct patch *list) 226{ 227while(list) { 228struct patch *next = list->next; 229free_patch(list); 230 list = next; 231} 232} 233 234/* 235 * A line in a file, len-bytes long (includes the terminating LF, 236 * except for an incomplete line at the end if the file ends with 237 * one), and its contents hashes to 'hash'. 238 */ 239struct line { 240size_t len; 241unsigned hash :24; 242unsigned flag :8; 243#define LINE_COMMON 1 244#define LINE_PATCHED 2 245}; 246 247/* 248 * This represents a "file", which is an array of "lines". 249 */ 250struct image { 251char*buf; 252size_t len; 253size_t nr; 254size_t alloc; 255struct line *line_allocated; 256struct line *line; 257}; 258 259/* 260 * Records filenames that have been touched, in order to handle 261 * the case where more than one patches touch the same file. 262 */ 263 264static struct string_list fn_table; 265 266static uint32_thash_line(const char*cp,size_t len) 267{ 268size_t i; 269uint32_t h; 270for(i =0, h =0; i < len; i++) { 271if(!isspace(cp[i])) { 272 h = h *3+ (cp[i] &0xff); 273} 274} 275return h; 276} 277 278/* 279 * Compare lines s1 of length n1 and s2 of length n2, ignoring 280 * whitespace difference. Returns 1 if they match, 0 otherwise 281 */ 282static intfuzzy_matchlines(const char*s1,size_t n1, 283const char*s2,size_t n2) 284{ 285const char*last1 = s1 + n1 -1; 286const char*last2 = s2 + n2 -1; 287int result =0; 288 289/* ignore line endings */ 290while((*last1 =='\r') || (*last1 =='\n')) 291 last1--; 292while((*last2 =='\r') || (*last2 =='\n')) 293 last2--; 294 295/* skip leading whitespace */ 296while(isspace(*s1) && (s1 <= last1)) 297 s1++; 298while(isspace(*s2) && (s2 <= last2)) 299 s2++; 300/* early return if both lines are empty */ 301if((s1 > last1) && (s2 > last2)) 302return1; 303while(!result) { 304 result = *s1++ - *s2++; 305/* 306 * Skip whitespace inside. We check for whitespace on 307 * both buffers because we don't want "a b" to match 308 * "ab" 309 */ 310if(isspace(*s1) &&isspace(*s2)) { 311while(isspace(*s1) && s1 <= last1) 312 s1++; 313while(isspace(*s2) && s2 <= last2) 314 s2++; 315} 316/* 317 * If we reached the end on one side only, 318 * lines don't match 319 */ 320if( 321((s2 > last2) && (s1 <= last1)) || 322((s1 > last1) && (s2 <= last2))) 323return0; 324if((s1 > last1) && (s2 > last2)) 325break; 326} 327 328return!result; 329} 330 331static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 332{ 333ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 334 img->line_allocated[img->nr].len = len; 335 img->line_allocated[img->nr].hash =hash_line(bol, len); 336 img->line_allocated[img->nr].flag = flag; 337 img->nr++; 338} 339 340/* 341 * "buf" has the file contents to be patched (read from various sources). 342 * attach it to "image" and add line-based index to it. 343 * "image" now owns the "buf". 344 */ 345static voidprepare_image(struct image *image,char*buf,size_t len, 346int prepare_linetable) 347{ 348const char*cp, *ep; 349 350memset(image,0,sizeof(*image)); 351 image->buf = buf; 352 image->len = len; 353 354if(!prepare_linetable) 355return; 356 357 ep = image->buf + image->len; 358 cp = image->buf; 359while(cp < ep) { 360const char*next; 361for(next = cp; next < ep && *next !='\n'; next++) 362; 363if(next < ep) 364 next++; 365add_line_info(image, cp, next - cp,0); 366 cp = next; 367} 368 image->line = image->line_allocated; 369} 370 371static voidclear_image(struct image *image) 372{ 373free(image->buf); 374 image->buf = NULL; 375 image->len =0; 376} 377 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 */ 922static char*gitdiff_verify_name(const char*line,int isnull,char*orig_name,const char*oldnew) 923{ 924if(!orig_name && !isnull) 925returnfind_name(line, NULL, p_value, TERM_TAB); 926 927if(orig_name) { 928int len; 929const char*name; 930char*another; 931 name = orig_name; 932 len =strlen(name); 933if(isnull) 934die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), name, linenr); 935 another =find_name(line, NULL, p_value, TERM_TAB); 936if(!another ||memcmp(another, name, len +1)) 937die(_("git apply: bad git-diff - inconsistent%sfilename on line%d"), oldnew, linenr); 938free(another); 939return orig_name; 940} 941else{ 942/* expect "/dev/null" */ 943if(memcmp("/dev/null", line,9) || line[9] !='\n') 944die(_("git apply: bad git-diff - expected /dev/null on line%d"), linenr); 945return NULL; 946} 947} 948 949static intgitdiff_oldname(const char*line,struct patch *patch) 950{ 951char*orig = patch->old_name; 952 patch->old_name =gitdiff_verify_name(line, patch->is_new, patch->old_name,"old"); 953if(orig != patch->old_name) 954free(orig); 955return0; 956} 957 958static intgitdiff_newname(const char*line,struct patch *patch) 959{ 960char*orig = patch->new_name; 961 patch->new_name =gitdiff_verify_name(line, patch->is_delete, patch->new_name,"new"); 962if(orig != patch->new_name) 963free(orig); 964return0; 965} 966 967static intgitdiff_oldmode(const char*line,struct patch *patch) 968{ 969 patch->old_mode =strtoul(line, NULL,8); 970return0; 971} 972 973static intgitdiff_newmode(const char*line,struct patch *patch) 974{ 975 patch->new_mode =strtoul(line, NULL,8); 976return0; 977} 978 979static intgitdiff_delete(const char*line,struct patch *patch) 980{ 981 patch->is_delete =1; 982free(patch->old_name); 983 patch->old_name =null_strdup(patch->def_name); 984returngitdiff_oldmode(line, patch); 985} 986 987static intgitdiff_newfile(const char*line,struct patch *patch) 988{ 989 patch->is_new =1; 990free(patch->new_name); 991 patch->new_name =null_strdup(patch->def_name); 992returngitdiff_newmode(line, patch); 993} 994 995static intgitdiff_copysrc(const char*line,struct patch *patch) 996{ 997 patch->is_copy =1; 998free(patch->old_name); 999 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0);1000return0;1001}10021003static intgitdiff_copydst(const char*line,struct patch *patch)1004{1005 patch->is_copy =1;1006free(patch->new_name);1007 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0);1008return0;1009}10101011static intgitdiff_renamesrc(const char*line,struct patch *patch)1012{1013 patch->is_rename =1;1014free(patch->old_name);1015 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0);1016return0;1017}10181019static intgitdiff_renamedst(const char*line,struct patch *patch)1020{1021 patch->is_rename =1;1022free(patch->new_name);1023 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0);1024return0;1025}10261027static intgitdiff_similarity(const char*line,struct patch *patch)1028{1029if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX)1030 patch->score =0;1031return0;1032}10331034static intgitdiff_dissimilarity(const char*line,struct patch *patch)1035{1036if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX)1037 patch->score =0;1038return0;1039}10401041static intgitdiff_index(const char*line,struct patch *patch)1042{1043/*1044 * index line is N hexadecimal, "..", N hexadecimal,1045 * and optional space with octal mode.1046 */1047const char*ptr, *eol;1048int len;10491050 ptr =strchr(line,'.');1051if(!ptr || ptr[1] !='.'||40< ptr - line)1052return0;1053 len = ptr - line;1054memcpy(patch->old_sha1_prefix, line, len);1055 patch->old_sha1_prefix[len] =0;10561057 line = ptr +2;1058 ptr =strchr(line,' ');1059 eol =strchr(line,'\n');10601061if(!ptr || eol < ptr)1062 ptr = eol;1063 len = ptr - line;10641065if(40< len)1066return0;1067memcpy(patch->new_sha1_prefix, line, len);1068 patch->new_sha1_prefix[len] =0;1069if(*ptr ==' ')1070 patch->old_mode =strtoul(ptr+1, NULL,8);1071return0;1072}10731074/*1075 * This is normal for a diff that doesn't change anything: we'll fall through1076 * into the next diff. Tell the parser to break out.1077 */1078static intgitdiff_unrecognized(const char*line,struct patch *patch)1079{1080return-1;1081}10821083static const char*stop_at_slash(const char*line,int llen)1084{1085int nslash = p_value;1086int i;10871088for(i =0; i < llen; i++) {1089int ch = line[i];1090if(ch =='/'&& --nslash <=0)1091return&line[i];1092}1093return NULL;1094}10951096/*1097 * This is to extract the same name that appears on "diff --git"1098 * line. We do not find and return anything if it is a rename1099 * patch, and it is OK because we will find the name elsewhere.1100 * We need to reliably find name only when it is mode-change only,1101 * creation or deletion of an empty file. In any of these cases,1102 * both sides are the same name under a/ and b/ respectively.1103 */1104static char*git_header_name(const char*line,int llen)1105{1106const char*name;1107const char*second = NULL;1108size_t len, line_len;11091110 line +=strlen("diff --git ");1111 llen -=strlen("diff --git ");11121113if(*line =='"') {1114const char*cp;1115struct strbuf first = STRBUF_INIT;1116struct strbuf sp = STRBUF_INIT;11171118if(unquote_c_style(&first, line, &second))1119goto free_and_fail1;11201121/* advance to the first slash */1122 cp =stop_at_slash(first.buf, first.len);1123/* we do not accept absolute paths */1124if(!cp || cp == first.buf)1125goto free_and_fail1;1126strbuf_remove(&first,0, cp +1- first.buf);11271128/*1129 * second points at one past closing dq of name.1130 * find the second name.1131 */1132while((second < line + llen) &&isspace(*second))1133 second++;11341135if(line + llen <= second)1136goto free_and_fail1;1137if(*second =='"') {1138if(unquote_c_style(&sp, second, NULL))1139goto free_and_fail1;1140 cp =stop_at_slash(sp.buf, sp.len);1141if(!cp || cp == sp.buf)1142goto free_and_fail1;1143/* They must match, otherwise ignore */1144if(strcmp(cp +1, first.buf))1145goto free_and_fail1;1146strbuf_release(&sp);1147returnstrbuf_detach(&first, NULL);1148}11491150/* unquoted second */1151 cp =stop_at_slash(second, line + llen - second);1152if(!cp || cp == second)1153goto free_and_fail1;1154 cp++;1155if(line + llen - cp != first.len +1||1156memcmp(first.buf, cp, first.len))1157goto free_and_fail1;1158returnstrbuf_detach(&first, NULL);11591160 free_and_fail1:1161strbuf_release(&first);1162strbuf_release(&sp);1163return NULL;1164}11651166/* unquoted first name */1167 name =stop_at_slash(line, llen);1168if(!name || name == line)1169return NULL;1170 name++;11711172/*1173 * since the first name is unquoted, a dq if exists must be1174 * the beginning of the second name.1175 */1176for(second = name; second < line + llen; second++) {1177if(*second =='"') {1178struct strbuf sp = STRBUF_INIT;1179const char*np;11801181if(unquote_c_style(&sp, second, NULL))1182goto free_and_fail2;11831184 np =stop_at_slash(sp.buf, sp.len);1185if(!np || np == sp.buf)1186goto free_and_fail2;1187 np++;11881189 len = sp.buf + sp.len - np;1190if(len < second - name &&1191!strncmp(np, name, len) &&1192isspace(name[len])) {1193/* Good */1194strbuf_remove(&sp,0, np - sp.buf);1195returnstrbuf_detach(&sp, NULL);1196}11971198 free_and_fail2:1199strbuf_release(&sp);1200return NULL;1201}1202}12031204/*1205 * Accept a name only if it shows up twice, exactly the same1206 * form.1207 */1208 second =strchr(name,'\n');1209if(!second)1210return NULL;1211 line_len = second - name;1212for(len =0; ; len++) {1213switch(name[len]) {1214default:1215continue;1216case'\n':1217return NULL;1218case'\t':case' ':1219 second =stop_at_slash(name + len, line_len - len);1220if(!second)1221return NULL;1222 second++;1223if(second[len] =='\n'&& !strncmp(name, second, len)) {1224returnxmemdupz(name, len);1225}1226}1227}1228}12291230/* Verify that we recognize the lines following a git header */1231static intparse_git_header(const char*line,int len,unsigned int size,struct patch *patch)1232{1233unsigned long offset;12341235/* A git diff has explicit new/delete information, so we don't guess */1236 patch->is_new =0;1237 patch->is_delete =0;12381239/*1240 * Some things may not have the old name in the1241 * rest of the headers anywhere (pure mode changes,1242 * or removing or adding empty files), so we get1243 * the default name from the header.1244 */1245 patch->def_name =git_header_name(line, len);1246if(patch->def_name && root) {1247char*s =xmalloc(root_len +strlen(patch->def_name) +1);1248strcpy(s, root);1249strcpy(s + root_len, patch->def_name);1250free(patch->def_name);1251 patch->def_name = s;1252}12531254 line += len;1255 size -= len;1256 linenr++;1257for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) {1258static const struct opentry {1259const char*str;1260int(*fn)(const char*,struct patch *);1261} optable[] = {1262{"@@ -", gitdiff_hdrend },1263{"--- ", gitdiff_oldname },1264{"+++ ", gitdiff_newname },1265{"old mode ", gitdiff_oldmode },1266{"new mode ", gitdiff_newmode },1267{"deleted file mode ", gitdiff_delete },1268{"new file mode ", gitdiff_newfile },1269{"copy from ", gitdiff_copysrc },1270{"copy to ", gitdiff_copydst },1271{"rename old ", gitdiff_renamesrc },1272{"rename new ", gitdiff_renamedst },1273{"rename from ", gitdiff_renamesrc },1274{"rename to ", gitdiff_renamedst },1275{"similarity index ", gitdiff_similarity },1276{"dissimilarity index ", gitdiff_dissimilarity },1277{"index ", gitdiff_index },1278{"", gitdiff_unrecognized },1279};1280int i;12811282 len =linelen(line, size);1283if(!len || line[len-1] !='\n')1284break;1285for(i =0; i <ARRAY_SIZE(optable); i++) {1286const struct opentry *p = optable + i;1287int oplen =strlen(p->str);1288if(len < oplen ||memcmp(p->str, line, oplen))1289continue;1290if(p->fn(line + oplen, patch) <0)1291return offset;1292break;1293}1294}12951296return offset;1297}12981299static intparse_num(const char*line,unsigned long*p)1300{1301char*ptr;13021303if(!isdigit(*line))1304return0;1305*p =strtoul(line, &ptr,10);1306return ptr - line;1307}13081309static intparse_range(const char*line,int len,int offset,const char*expect,1310unsigned long*p1,unsigned long*p2)1311{1312int digits, ex;13131314if(offset <0|| offset >= len)1315return-1;1316 line += offset;1317 len -= offset;13181319 digits =parse_num(line, p1);1320if(!digits)1321return-1;13221323 offset += digits;1324 line += digits;1325 len -= digits;13261327*p2 =1;1328if(*line ==',') {1329 digits =parse_num(line+1, p2);1330if(!digits)1331return-1;13321333 offset += digits+1;1334 line += digits+1;1335 len -= digits+1;1336}13371338 ex =strlen(expect);1339if(ex > len)1340return-1;1341if(memcmp(line, expect, ex))1342return-1;13431344return offset + ex;1345}13461347static voidrecount_diff(const char*line,int size,struct fragment *fragment)1348{1349int oldlines =0, newlines =0, ret =0;13501351if(size <1) {1352warning("recount: ignore empty hunk");1353return;1354}13551356for(;;) {1357int len =linelen(line, size);1358 size -= len;1359 line += len;13601361if(size <1)1362break;13631364switch(*line) {1365case' ':case'\n':1366 newlines++;1367/* fall through */1368case'-':1369 oldlines++;1370continue;1371case'+':1372 newlines++;1373continue;1374case'\\':1375continue;1376case'@':1377 ret = size <3||prefixcmp(line,"@@ ");1378break;1379case'd':1380 ret = size <5||prefixcmp(line,"diff ");1381break;1382default:1383 ret = -1;1384break;1385}1386if(ret) {1387warning(_("recount: unexpected line: %.*s"),1388(int)linelen(line, size), line);1389return;1390}1391break;1392}1393 fragment->oldlines = oldlines;1394 fragment->newlines = newlines;1395}13961397/*1398 * Parse a unified diff fragment header of the1399 * form "@@ -a,b +c,d @@"1400 */1401static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1402{1403int offset;14041405if(!len || line[len-1] !='\n')1406return-1;14071408/* Figure out the number of lines in a fragment */1409 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1410 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14111412return offset;1413}14141415static intfind_header(const char*line,unsigned long size,int*hdrsize,struct patch *patch)1416{1417unsigned long offset, len;14181419 patch->is_toplevel_relative =0;1420 patch->is_rename = patch->is_copy =0;1421 patch->is_new = patch->is_delete = -1;1422 patch->old_mode = patch->new_mode =0;1423 patch->old_name = patch->new_name = NULL;1424for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) {1425unsigned long nextlen;14261427 len =linelen(line, size);1428if(!len)1429break;14301431/* Testing this early allows us to take a few shortcuts.. */1432if(len <6)1433continue;14341435/*1436 * Make sure we don't find any unconnected patch fragments.1437 * That's a sign that we didn't find a header, and that a1438 * patch has become corrupted/broken up.1439 */1440if(!memcmp("@@ -", line,4)) {1441struct fragment dummy;1442if(parse_fragment_header(line, len, &dummy) <0)1443continue;1444die(_("patch fragment without header at line%d: %.*s"),1445 linenr, (int)len-1, line);1446}14471448if(size < len +6)1449break;14501451/*1452 * Git patch? It might not have a real patch, just a rename1453 * or mode change, so we handle that specially1454 */1455if(!memcmp("diff --git ", line,11)) {1456int git_hdr_len =parse_git_header(line, len, size, patch);1457if(git_hdr_len <= len)1458continue;1459if(!patch->old_name && !patch->new_name) {1460if(!patch->def_name)1461die(Q_("git diff header lacks filename information when removing "1462"%dleading pathname component (line%d)",1463"git diff header lacks filename information when removing "1464"%dleading pathname components (line%d)",1465 p_value),1466 p_value, linenr);1467 patch->old_name =xstrdup(patch->def_name);1468 patch->new_name =xstrdup(patch->def_name);1469}1470if(!patch->is_delete && !patch->new_name)1471die("git diff header lacks filename information "1472"(line%d)", linenr);1473 patch->is_toplevel_relative =1;1474*hdrsize = git_hdr_len;1475return offset;1476}14771478/* --- followed by +++ ? */1479if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1480continue;14811482/*1483 * We only accept unified patches, so we want it to1484 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1485 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1486 */1487 nextlen =linelen(line + len, size - len);1488if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1489continue;14901491/* Ok, we'll consider it a patch */1492parse_traditional_patch(line, line+len, patch);1493*hdrsize = len + nextlen;1494 linenr +=2;1495return offset;1496}1497return-1;1498}14991500static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1501{1502char*err;15031504if(!result)1505return;15061507 whitespace_error++;1508if(squelch_whitespace_errors &&1509 squelch_whitespace_errors < whitespace_error)1510return;15111512 err =whitespace_error_string(result);1513fprintf(stderr,"%s:%d:%s.\n%.*s\n",1514 patch_input_file, linenr, err, len, line);1515free(err);1516}15171518static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1519{1520unsigned result =ws_check(line +1, len -1, ws_rule);15211522record_ws_error(result, line +1, len -2, linenr);1523}15241525/*1526 * Parse a unified diff. Note that this really needs to parse each1527 * fragment separately, since the only way to know the difference1528 * between a "---" that is part of a patch, and a "---" that starts1529 * the next patch is to look at the line counts..1530 */1531static intparse_fragment(const char*line,unsigned long size,1532struct patch *patch,struct fragment *fragment)1533{1534int added, deleted;1535int len =linelen(line, size), offset;1536unsigned long oldlines, newlines;1537unsigned long leading, trailing;15381539 offset =parse_fragment_header(line, len, fragment);1540if(offset <0)1541return-1;1542if(offset >0&& patch->recount)1543recount_diff(line + offset, size - offset, fragment);1544 oldlines = fragment->oldlines;1545 newlines = fragment->newlines;1546 leading =0;1547 trailing =0;15481549/* Parse the thing.. */1550 line += len;1551 size -= len;1552 linenr++;1553 added = deleted =0;1554for(offset = len;15550< size;1556 offset += len, size -= len, line += len, linenr++) {1557if(!oldlines && !newlines)1558break;1559 len =linelen(line, size);1560if(!len || line[len-1] !='\n')1561return-1;1562switch(*line) {1563default:1564return-1;1565case'\n':/* newer GNU diff, an empty context line */1566case' ':1567 oldlines--;1568 newlines--;1569if(!deleted && !added)1570 leading++;1571 trailing++;1572break;1573case'-':1574if(apply_in_reverse &&1575 ws_error_action != nowarn_ws_error)1576check_whitespace(line, len, patch->ws_rule);1577 deleted++;1578 oldlines--;1579 trailing =0;1580break;1581case'+':1582if(!apply_in_reverse &&1583 ws_error_action != nowarn_ws_error)1584check_whitespace(line, len, patch->ws_rule);1585 added++;1586 newlines--;1587 trailing =0;1588break;15891590/*1591 * We allow "\ No newline at end of file". Depending1592 * on locale settings when the patch was produced we1593 * don't know what this line looks like. The only1594 * thing we do know is that it begins with "\ ".1595 * Checking for 12 is just for sanity check -- any1596 * l10n of "\ No newline..." is at least that long.1597 */1598case'\\':1599if(len <12||memcmp(line,"\\",2))1600return-1;1601break;1602}1603}1604if(oldlines || newlines)1605return-1;1606 fragment->leading = leading;1607 fragment->trailing = trailing;16081609/*1610 * If a fragment ends with an incomplete line, we failed to include1611 * it in the above loop because we hit oldlines == newlines == 01612 * before seeing it.1613 */1614if(12< size && !memcmp(line,"\\",2))1615 offset +=linelen(line, size);16161617 patch->lines_added += added;1618 patch->lines_deleted += deleted;16191620if(0< patch->is_new && oldlines)1621returnerror(_("new file depends on old contents"));1622if(0< patch->is_delete && newlines)1623returnerror(_("deleted file still has contents"));1624return offset;1625}16261627/*1628 * We have seen "diff --git a/... b/..." header (or a traditional patch1629 * header). Read hunks that belong to this patch into fragments and hang1630 * them to the given patch structure.1631 *1632 * The (fragment->patch, fragment->size) pair points into the memory given1633 * by the caller, not a copy, when we return.1634 */1635static intparse_single_patch(const char*line,unsigned long size,struct patch *patch)1636{1637unsigned long offset =0;1638unsigned long oldlines =0, newlines =0, context =0;1639struct fragment **fragp = &patch->fragments;16401641while(size >4&& !memcmp(line,"@@ -",4)) {1642struct fragment *fragment;1643int len;16441645 fragment =xcalloc(1,sizeof(*fragment));1646 fragment->linenr = linenr;1647 len =parse_fragment(line, size, patch, fragment);1648if(len <=0)1649die(_("corrupt patch at line%d"), linenr);1650 fragment->patch = line;1651 fragment->size = len;1652 oldlines += fragment->oldlines;1653 newlines += fragment->newlines;1654 context += fragment->leading + fragment->trailing;16551656*fragp = fragment;1657 fragp = &fragment->next;16581659 offset += len;1660 line += len;1661 size -= len;1662}16631664/*1665 * If something was removed (i.e. we have old-lines) it cannot1666 * be creation, and if something was added it cannot be1667 * deletion. However, the reverse is not true; --unified=01668 * patches that only add are not necessarily creation even1669 * though they do not have any old lines, and ones that only1670 * delete are not necessarily deletion.1671 *1672 * Unfortunately, a real creation/deletion patch do _not_ have1673 * any context line by definition, so we cannot safely tell it1674 * apart with --unified=0 insanity. At least if the patch has1675 * more than one hunk it is not creation or deletion.1676 */1677if(patch->is_new <0&&1678(oldlines || (patch->fragments && patch->fragments->next)))1679 patch->is_new =0;1680if(patch->is_delete <0&&1681(newlines || (patch->fragments && patch->fragments->next)))1682 patch->is_delete =0;16831684if(0< patch->is_new && oldlines)1685die(_("new file%sdepends on old contents"), patch->new_name);1686if(0< patch->is_delete && newlines)1687die(_("deleted file%sstill has contents"), patch->old_name);1688if(!patch->is_delete && !newlines && context)1689fprintf_ln(stderr,1690_("** warning: "1691"file%sbecomes empty but is not deleted"),1692 patch->new_name);16931694return offset;1695}16961697staticinlineintmetadata_changes(struct patch *patch)1698{1699return patch->is_rename >0||1700 patch->is_copy >0||1701 patch->is_new >0||1702 patch->is_delete ||1703(patch->old_mode && patch->new_mode &&1704 patch->old_mode != patch->new_mode);1705}17061707static char*inflate_it(const void*data,unsigned long size,1708unsigned long inflated_size)1709{1710 git_zstream stream;1711void*out;1712int st;17131714memset(&stream,0,sizeof(stream));17151716 stream.next_in = (unsigned char*)data;1717 stream.avail_in = size;1718 stream.next_out = out =xmalloc(inflated_size);1719 stream.avail_out = inflated_size;1720git_inflate_init(&stream);1721 st =git_inflate(&stream, Z_FINISH);1722git_inflate_end(&stream);1723if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1724free(out);1725return NULL;1726}1727return out;1728}17291730/*1731 * Read a binary hunk and return a new fragment; fragment->patch1732 * points at an allocated memory that the caller must free, so1733 * it is marked as "->free_patch = 1".1734 */1735static struct fragment *parse_binary_hunk(char**buf_p,1736unsigned long*sz_p,1737int*status_p,1738int*used_p)1739{1740/*1741 * Expect a line that begins with binary patch method ("literal"1742 * or "delta"), followed by the length of data before deflating.1743 * a sequence of 'length-byte' followed by base-85 encoded data1744 * should follow, terminated by a newline.1745 *1746 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1747 * and we would limit the patch line to 66 characters,1748 * so one line can fit up to 13 groups that would decode1749 * to 52 bytes max. The length byte 'A'-'Z' corresponds1750 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1751 */1752int llen, used;1753unsigned long size = *sz_p;1754char*buffer = *buf_p;1755int patch_method;1756unsigned long origlen;1757char*data = NULL;1758int hunk_size =0;1759struct fragment *frag;17601761 llen =linelen(buffer, size);1762 used = llen;17631764*status_p =0;17651766if(!prefixcmp(buffer,"delta ")) {1767 patch_method = BINARY_DELTA_DEFLATED;1768 origlen =strtoul(buffer +6, NULL,10);1769}1770else if(!prefixcmp(buffer,"literal ")) {1771 patch_method = BINARY_LITERAL_DEFLATED;1772 origlen =strtoul(buffer +8, NULL,10);1773}1774else1775return NULL;17761777 linenr++;1778 buffer += llen;1779while(1) {1780int byte_length, max_byte_length, newsize;1781 llen =linelen(buffer, size);1782 used += llen;1783 linenr++;1784if(llen ==1) {1785/* consume the blank line */1786 buffer++;1787 size--;1788break;1789}1790/*1791 * Minimum line is "A00000\n" which is 7-byte long,1792 * and the line length must be multiple of 5 plus 2.1793 */1794if((llen <7) || (llen-2) %5)1795goto corrupt;1796 max_byte_length = (llen -2) /5*4;1797 byte_length = *buffer;1798if('A'<= byte_length && byte_length <='Z')1799 byte_length = byte_length -'A'+1;1800else if('a'<= byte_length && byte_length <='z')1801 byte_length = byte_length -'a'+27;1802else1803goto corrupt;1804/* if the input length was not multiple of 4, we would1805 * have filler at the end but the filler should never1806 * exceed 3 bytes1807 */1808if(max_byte_length < byte_length ||1809 byte_length <= max_byte_length -4)1810goto corrupt;1811 newsize = hunk_size + byte_length;1812 data =xrealloc(data, newsize);1813if(decode_85(data + hunk_size, buffer +1, byte_length))1814goto corrupt;1815 hunk_size = newsize;1816 buffer += llen;1817 size -= llen;1818}18191820 frag =xcalloc(1,sizeof(*frag));1821 frag->patch =inflate_it(data, hunk_size, origlen);1822 frag->free_patch =1;1823if(!frag->patch)1824goto corrupt;1825free(data);1826 frag->size = origlen;1827*buf_p = buffer;1828*sz_p = size;1829*used_p = used;1830 frag->binary_patch_method = patch_method;1831return frag;18321833 corrupt:1834free(data);1835*status_p = -1;1836error(_("corrupt binary patch at line%d: %.*s"),1837 linenr-1, llen-1, buffer);1838return NULL;1839}18401841static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1842{1843/*1844 * We have read "GIT binary patch\n"; what follows is a line1845 * that says the patch method (currently, either "literal" or1846 * "delta") and the length of data before deflating; a1847 * sequence of 'length-byte' followed by base-85 encoded data1848 * follows.1849 *1850 * When a binary patch is reversible, there is another binary1851 * hunk in the same format, starting with patch method (either1852 * "literal" or "delta") with the length of data, and a sequence1853 * of length-byte + base-85 encoded data, terminated with another1854 * empty line. This data, when applied to the postimage, produces1855 * the preimage.1856 */1857struct fragment *forward;1858struct fragment *reverse;1859int status;1860int used, used_1;18611862 forward =parse_binary_hunk(&buffer, &size, &status, &used);1863if(!forward && !status)1864/* there has to be one hunk (forward hunk) */1865returnerror(_("unrecognized binary patch at line%d"), linenr-1);1866if(status)1867/* otherwise we already gave an error message */1868return status;18691870 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1871if(reverse)1872 used += used_1;1873else if(status) {1874/*1875 * Not having reverse hunk is not an error, but having1876 * a corrupt reverse hunk is.1877 */1878free((void*) forward->patch);1879free(forward);1880return status;1881}1882 forward->next = reverse;1883 patch->fragments = forward;1884 patch->is_binary =1;1885return used;1886}18871888/*1889 * Read the patch text in "buffer" taht extends for "size" bytes; stop1890 * reading after seeing a single patch (i.e. changes to a single file).1891 * Create fragments (i.e. patch hunks) and hang them to the given patch.1892 * Return the number of bytes consumed, so that the caller can call us1893 * again for the next patch.1894 */1895static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1896{1897int hdrsize, patchsize;1898int offset =find_header(buffer, size, &hdrsize, patch);18991900if(offset <0)1901return offset;19021903 patch->ws_rule =whitespace_rule(patch->new_name1904? patch->new_name1905: patch->old_name);19061907 patchsize =parse_single_patch(buffer + offset + hdrsize,1908 size - offset - hdrsize, patch);19091910if(!patchsize) {1911static const char*binhdr[] = {1912"Binary files ",1913"Files ",1914 NULL,1915};1916static const char git_binary[] ="GIT binary patch\n";1917int i;1918int hd = hdrsize + offset;1919unsigned long llen =linelen(buffer + hd, size - hd);19201921if(llen ==sizeof(git_binary) -1&&1922!memcmp(git_binary, buffer + hd, llen)) {1923int used;1924 linenr++;1925 used =parse_binary(buffer + hd + llen,1926 size - hd - llen, patch);1927if(used)1928 patchsize = used + llen;1929else1930 patchsize =0;1931}1932else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1933for(i =0; binhdr[i]; i++) {1934int len =strlen(binhdr[i]);1935if(len < size - hd &&1936!memcmp(binhdr[i], buffer + hd, len)) {1937 linenr++;1938 patch->is_binary =1;1939 patchsize = llen;1940break;1941}1942}1943}19441945/* Empty patch cannot be applied if it is a text patch1946 * without metadata change. A binary patch appears1947 * empty to us here.1948 */1949if((apply || check) &&1950(!patch->is_binary && !metadata_changes(patch)))1951die(_("patch with only garbage at line%d"), linenr);1952}19531954return offset + hdrsize + patchsize;1955}19561957#define swap(a,b) myswap((a),(b),sizeof(a))19581959#define myswap(a, b, size) do { \1960 unsigned char mytmp[size]; \1961 memcpy(mytmp, &a, size); \1962 memcpy(&a, &b, size); \1963 memcpy(&b, mytmp, size); \1964} while (0)19651966static voidreverse_patches(struct patch *p)1967{1968for(; p; p = p->next) {1969struct fragment *frag = p->fragments;19701971swap(p->new_name, p->old_name);1972swap(p->new_mode, p->old_mode);1973swap(p->is_new, p->is_delete);1974swap(p->lines_added, p->lines_deleted);1975swap(p->old_sha1_prefix, p->new_sha1_prefix);19761977for(; frag; frag = frag->next) {1978swap(frag->newpos, frag->oldpos);1979swap(frag->newlines, frag->oldlines);1980}1981}1982}19831984static const char pluses[] =1985"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";1986static const char minuses[]=1987"----------------------------------------------------------------------";19881989static voidshow_stats(struct patch *patch)1990{1991struct strbuf qname = STRBUF_INIT;1992char*cp = patch->new_name ? patch->new_name : patch->old_name;1993int max, add, del;19941995quote_c_style(cp, &qname, NULL,0);19961997/*1998 * "scale" the filename1999 */2000 max = max_len;2001if(max >50)2002 max =50;20032004if(qname.len > max) {2005 cp =strchr(qname.buf + qname.len +3- max,'/');2006if(!cp)2007 cp = qname.buf + qname.len +3- max;2008strbuf_splice(&qname,0, cp - qname.buf,"...",3);2009}20102011if(patch->is_binary) {2012printf(" %-*s | Bin\n", max, qname.buf);2013strbuf_release(&qname);2014return;2015}20162017printf(" %-*s |", max, qname.buf);2018strbuf_release(&qname);20192020/*2021 * scale the add/delete2022 */2023 max = max + max_change >70?70- max : max_change;2024 add = patch->lines_added;2025 del = patch->lines_deleted;20262027if(max_change >0) {2028int total = ((add + del) * max + max_change /2) / max_change;2029 add = (add * max + max_change /2) / max_change;2030 del = total - add;2031}2032printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2033 add, pluses, del, minuses);2034}20352036static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2037{2038switch(st->st_mode & S_IFMT) {2039case S_IFLNK:2040if(strbuf_readlink(buf, path, st->st_size) <0)2041returnerror(_("unable to read symlink%s"), path);2042return0;2043case S_IFREG:2044if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2045returnerror(_("unable to open or read%s"), path);2046convert_to_git(path, buf->buf, buf->len, buf,0);2047return0;2048default:2049return-1;2050}2051}20522053/*2054 * Update the preimage, and the common lines in postimage,2055 * from buffer buf of length len. If postlen is 0 the postimage2056 * is updated in place, otherwise it's updated on a new buffer2057 * of length postlen2058 */20592060static voidupdate_pre_post_images(struct image *preimage,2061struct image *postimage,2062char*buf,2063size_t len,size_t postlen)2064{2065int i, ctx;2066char*new, *old, *fixed;2067struct image fixed_preimage;20682069/*2070 * Update the preimage with whitespace fixes. Note that we2071 * are not losing preimage->buf -- apply_one_fragment() will2072 * free "oldlines".2073 */2074prepare_image(&fixed_preimage, buf, len,1);2075assert(fixed_preimage.nr == preimage->nr);2076for(i =0; i < preimage->nr; i++)2077 fixed_preimage.line[i].flag = preimage->line[i].flag;2078free(preimage->line_allocated);2079*preimage = fixed_preimage;20802081/*2082 * Adjust the common context lines in postimage. This can be2083 * done in-place when we are just doing whitespace fixing,2084 * which does not make the string grow, but needs a new buffer2085 * when ignoring whitespace causes the update, since in this case2086 * we could have e.g. tabs converted to multiple spaces.2087 * We trust the caller to tell us if the update can be done2088 * in place (postlen==0) or not.2089 */2090 old = postimage->buf;2091if(postlen)2092new= postimage->buf =xmalloc(postlen);2093else2094new= old;2095 fixed = preimage->buf;2096for(i = ctx =0; i < postimage->nr; i++) {2097size_t len = postimage->line[i].len;2098if(!(postimage->line[i].flag & LINE_COMMON)) {2099/* an added line -- no counterparts in preimage */2100memmove(new, old, len);2101 old += len;2102new+= len;2103continue;2104}21052106/* a common context -- skip it in the original postimage */2107 old += len;21082109/* and find the corresponding one in the fixed preimage */2110while(ctx < preimage->nr &&2111!(preimage->line[ctx].flag & LINE_COMMON)) {2112 fixed += preimage->line[ctx].len;2113 ctx++;2114}2115if(preimage->nr <= ctx)2116die(_("oops"));21172118/* and copy it in, while fixing the line length */2119 len = preimage->line[ctx].len;2120memcpy(new, fixed, len);2121new+= len;2122 fixed += len;2123 postimage->line[i].len = len;2124 ctx++;2125}21262127/* Fix the length of the whole thing */2128 postimage->len =new- postimage->buf;2129}21302131static intmatch_fragment(struct image *img,2132struct image *preimage,2133struct image *postimage,2134unsigned longtry,2135int try_lno,2136unsigned ws_rule,2137int match_beginning,int match_end)2138{2139int i;2140char*fixed_buf, *buf, *orig, *target;2141struct strbuf fixed;2142size_t fixed_len;2143int preimage_limit;21442145if(preimage->nr + try_lno <= img->nr) {2146/*2147 * The hunk falls within the boundaries of img.2148 */2149 preimage_limit = preimage->nr;2150if(match_end && (preimage->nr + try_lno != img->nr))2151return0;2152}else if(ws_error_action == correct_ws_error &&2153(ws_rule & WS_BLANK_AT_EOF)) {2154/*2155 * This hunk extends beyond the end of img, and we are2156 * removing blank lines at the end of the file. This2157 * many lines from the beginning of the preimage must2158 * match with img, and the remainder of the preimage2159 * must be blank.2160 */2161 preimage_limit = img->nr - try_lno;2162}else{2163/*2164 * The hunk extends beyond the end of the img and2165 * we are not removing blanks at the end, so we2166 * should reject the hunk at this position.2167 */2168return0;2169}21702171if(match_beginning && try_lno)2172return0;21732174/* Quick hash check */2175for(i =0; i < preimage_limit; i++)2176if((img->line[try_lno + i].flag & LINE_PATCHED) ||2177(preimage->line[i].hash != img->line[try_lno + i].hash))2178return0;21792180if(preimage_limit == preimage->nr) {2181/*2182 * Do we have an exact match? If we were told to match2183 * at the end, size must be exactly at try+fragsize,2184 * otherwise try+fragsize must be still within the preimage,2185 * and either case, the old piece should match the preimage2186 * exactly.2187 */2188if((match_end2189? (try+ preimage->len == img->len)2190: (try+ preimage->len <= img->len)) &&2191!memcmp(img->buf +try, preimage->buf, preimage->len))2192return1;2193}else{2194/*2195 * The preimage extends beyond the end of img, so2196 * there cannot be an exact match.2197 *2198 * There must be one non-blank context line that match2199 * a line before the end of img.2200 */2201char*buf_end;22022203 buf = preimage->buf;2204 buf_end = buf;2205for(i =0; i < preimage_limit; i++)2206 buf_end += preimage->line[i].len;22072208for( ; buf < buf_end; buf++)2209if(!isspace(*buf))2210break;2211if(buf == buf_end)2212return0;2213}22142215/*2216 * No exact match. If we are ignoring whitespace, run a line-by-line2217 * fuzzy matching. We collect all the line length information because2218 * we need it to adjust whitespace if we match.2219 */2220if(ws_ignore_action == ignore_ws_change) {2221size_t imgoff =0;2222size_t preoff =0;2223size_t postlen = postimage->len;2224size_t extra_chars;2225char*preimage_eof;2226char*preimage_end;2227for(i =0; i < preimage_limit; i++) {2228size_t prelen = preimage->line[i].len;2229size_t imglen = img->line[try_lno+i].len;22302231if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2232 preimage->buf + preoff, prelen))2233return0;2234if(preimage->line[i].flag & LINE_COMMON)2235 postlen += imglen - prelen;2236 imgoff += imglen;2237 preoff += prelen;2238}22392240/*2241 * Ok, the preimage matches with whitespace fuzz.2242 *2243 * imgoff now holds the true length of the target that2244 * matches the preimage before the end of the file.2245 *2246 * Count the number of characters in the preimage that fall2247 * beyond the end of the file and make sure that all of them2248 * are whitespace characters. (This can only happen if2249 * we are removing blank lines at the end of the file.)2250 */2251 buf = preimage_eof = preimage->buf + preoff;2252for( ; i < preimage->nr; i++)2253 preoff += preimage->line[i].len;2254 preimage_end = preimage->buf + preoff;2255for( ; buf < preimage_end; buf++)2256if(!isspace(*buf))2257return0;22582259/*2260 * Update the preimage and the common postimage context2261 * lines to use the same whitespace as the target.2262 * If whitespace is missing in the target (i.e.2263 * if the preimage extends beyond the end of the file),2264 * use the whitespace from the preimage.2265 */2266 extra_chars = preimage_end - preimage_eof;2267strbuf_init(&fixed, imgoff + extra_chars);2268strbuf_add(&fixed, img->buf +try, imgoff);2269strbuf_add(&fixed, preimage_eof, extra_chars);2270 fixed_buf =strbuf_detach(&fixed, &fixed_len);2271update_pre_post_images(preimage, postimage,2272 fixed_buf, fixed_len, postlen);2273return1;2274}22752276if(ws_error_action != correct_ws_error)2277return0;22782279/*2280 * The hunk does not apply byte-by-byte, but the hash says2281 * it might with whitespace fuzz. We haven't been asked to2282 * ignore whitespace, we were asked to correct whitespace2283 * errors, so let's try matching after whitespace correction.2284 *2285 * The preimage may extend beyond the end of the file,2286 * but in this loop we will only handle the part of the2287 * preimage that falls within the file.2288 */2289strbuf_init(&fixed, preimage->len +1);2290 orig = preimage->buf;2291 target = img->buf +try;2292for(i =0; i < preimage_limit; i++) {2293size_t oldlen = preimage->line[i].len;2294size_t tgtlen = img->line[try_lno + i].len;2295size_t fixstart = fixed.len;2296struct strbuf tgtfix;2297int match;22982299/* Try fixing the line in the preimage */2300ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);23012302/* Try fixing the line in the target */2303strbuf_init(&tgtfix, tgtlen);2304ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);23052306/*2307 * If they match, either the preimage was based on2308 * a version before our tree fixed whitespace breakage,2309 * or we are lacking a whitespace-fix patch the tree2310 * the preimage was based on already had (i.e. target2311 * has whitespace breakage, the preimage doesn't).2312 * In either case, we are fixing the whitespace breakages2313 * so we might as well take the fix together with their2314 * real change.2315 */2316 match = (tgtfix.len == fixed.len - fixstart &&2317!memcmp(tgtfix.buf, fixed.buf + fixstart,2318 fixed.len - fixstart));23192320strbuf_release(&tgtfix);2321if(!match)2322goto unmatch_exit;23232324 orig += oldlen;2325 target += tgtlen;2326}232723282329/*2330 * Now handle the lines in the preimage that falls beyond the2331 * end of the file (if any). They will only match if they are2332 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2333 * false).2334 */2335for( ; i < preimage->nr; i++) {2336size_t fixstart = fixed.len;/* start of the fixed preimage */2337size_t oldlen = preimage->line[i].len;2338int j;23392340/* Try fixing the line in the preimage */2341ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);23422343for(j = fixstart; j < fixed.len; j++)2344if(!isspace(fixed.buf[j]))2345goto unmatch_exit;23462347 orig += oldlen;2348}23492350/*2351 * Yes, the preimage is based on an older version that still2352 * has whitespace breakages unfixed, and fixing them makes the2353 * hunk match. Update the context lines in the postimage.2354 */2355 fixed_buf =strbuf_detach(&fixed, &fixed_len);2356update_pre_post_images(preimage, postimage,2357 fixed_buf, fixed_len,0);2358return1;23592360 unmatch_exit:2361strbuf_release(&fixed);2362return0;2363}23642365static intfind_pos(struct image *img,2366struct image *preimage,2367struct image *postimage,2368int line,2369unsigned ws_rule,2370int match_beginning,int match_end)2371{2372int i;2373unsigned long backwards, forwards,try;2374int backwards_lno, forwards_lno, try_lno;23752376/*2377 * If match_beginning or match_end is specified, there is no2378 * point starting from a wrong line that will never match and2379 * wander around and wait for a match at the specified end.2380 */2381if(match_beginning)2382 line =0;2383else if(match_end)2384 line = img->nr - preimage->nr;23852386/*2387 * Because the comparison is unsigned, the following test2388 * will also take care of a negative line number that can2389 * result when match_end and preimage is larger than the target.2390 */2391if((size_t) line > img->nr)2392 line = img->nr;23932394try=0;2395for(i =0; i < line; i++)2396try+= img->line[i].len;23972398/*2399 * There's probably some smart way to do this, but I'll leave2400 * that to the smart and beautiful people. I'm simple and stupid.2401 */2402 backwards =try;2403 backwards_lno = line;2404 forwards =try;2405 forwards_lno = line;2406 try_lno = line;24072408for(i =0; ; i++) {2409if(match_fragment(img, preimage, postimage,2410try, try_lno, ws_rule,2411 match_beginning, match_end))2412return try_lno;24132414 again:2415if(backwards_lno ==0&& forwards_lno == img->nr)2416break;24172418if(i &1) {2419if(backwards_lno ==0) {2420 i++;2421goto again;2422}2423 backwards_lno--;2424 backwards -= img->line[backwards_lno].len;2425try= backwards;2426 try_lno = backwards_lno;2427}else{2428if(forwards_lno == img->nr) {2429 i++;2430goto again;2431}2432 forwards += img->line[forwards_lno].len;2433 forwards_lno++;2434try= forwards;2435 try_lno = forwards_lno;2436}24372438}2439return-1;2440}24412442static voidremove_first_line(struct image *img)2443{2444 img->buf += img->line[0].len;2445 img->len -= img->line[0].len;2446 img->line++;2447 img->nr--;2448}24492450static voidremove_last_line(struct image *img)2451{2452 img->len -= img->line[--img->nr].len;2453}24542455/*2456 * The change from "preimage" and "postimage" has been found to2457 * apply at applied_pos (counts in line numbers) in "img".2458 * Update "img" to remove "preimage" and replace it with "postimage".2459 */2460static voidupdate_image(struct image *img,2461int applied_pos,2462struct image *preimage,2463struct image *postimage)2464{2465/*2466 * remove the copy of preimage at offset in img2467 * and replace it with postimage2468 */2469int i, nr;2470size_t remove_count, insert_count, applied_at =0;2471char*result;2472int preimage_limit;24732474/*2475 * If we are removing blank lines at the end of img,2476 * the preimage may extend beyond the end.2477 * If that is the case, we must be careful only to2478 * remove the part of the preimage that falls within2479 * the boundaries of img. Initialize preimage_limit2480 * to the number of lines in the preimage that falls2481 * within the boundaries.2482 */2483 preimage_limit = preimage->nr;2484if(preimage_limit > img->nr - applied_pos)2485 preimage_limit = img->nr - applied_pos;24862487for(i =0; i < applied_pos; i++)2488 applied_at += img->line[i].len;24892490 remove_count =0;2491for(i =0; i < preimage_limit; i++)2492 remove_count += img->line[applied_pos + i].len;2493 insert_count = postimage->len;24942495/* Adjust the contents */2496 result =xmalloc(img->len + insert_count - remove_count +1);2497memcpy(result, img->buf, applied_at);2498memcpy(result + applied_at, postimage->buf, postimage->len);2499memcpy(result + applied_at + postimage->len,2500 img->buf + (applied_at + remove_count),2501 img->len - (applied_at + remove_count));2502free(img->buf);2503 img->buf = result;2504 img->len += insert_count - remove_count;2505 result[img->len] ='\0';25062507/* Adjust the line table */2508 nr = img->nr + postimage->nr - preimage_limit;2509if(preimage_limit < postimage->nr) {2510/*2511 * NOTE: this knows that we never call remove_first_line()2512 * on anything other than pre/post image.2513 */2514 img->line =xrealloc(img->line, nr *sizeof(*img->line));2515 img->line_allocated = img->line;2516}2517if(preimage_limit != postimage->nr)2518memmove(img->line + applied_pos + postimage->nr,2519 img->line + applied_pos + preimage_limit,2520(img->nr - (applied_pos + preimage_limit)) *2521sizeof(*img->line));2522memcpy(img->line + applied_pos,2523 postimage->line,2524 postimage->nr *sizeof(*img->line));2525if(!allow_overlap)2526for(i =0; i < postimage->nr; i++)2527 img->line[applied_pos + i].flag |= LINE_PATCHED;2528 img->nr = nr;2529}25302531/*2532 * Use the patch-hunk text in "frag" to prepare two images (preimage and2533 * postimage) for the hunk. Find lines that match "preimage" in "img" and2534 * replace the part of "img" with "postimage" text.2535 */2536static intapply_one_fragment(struct image *img,struct fragment *frag,2537int inaccurate_eof,unsigned ws_rule,2538int nth_fragment)2539{2540int match_beginning, match_end;2541const char*patch = frag->patch;2542int size = frag->size;2543char*old, *oldlines;2544struct strbuf newlines;2545int new_blank_lines_at_end =0;2546int found_new_blank_lines_at_end =0;2547int hunk_linenr = frag->linenr;2548unsigned long leading, trailing;2549int pos, applied_pos;2550struct image preimage;2551struct image postimage;25522553memset(&preimage,0,sizeof(preimage));2554memset(&postimage,0,sizeof(postimage));2555 oldlines =xmalloc(size);2556strbuf_init(&newlines, size);25572558 old = oldlines;2559while(size >0) {2560char first;2561int len =linelen(patch, size);2562int plen;2563int added_blank_line =0;2564int is_blank_context =0;2565size_t start;25662567if(!len)2568break;25692570/*2571 * "plen" is how much of the line we should use for2572 * the actual patch data. Normally we just remove the2573 * first character on the line, but if the line is2574 * followed by "\ No newline", then we also remove the2575 * last one (which is the newline, of course).2576 */2577 plen = len -1;2578if(len < size && patch[len] =='\\')2579 plen--;2580 first = *patch;2581if(apply_in_reverse) {2582if(first =='-')2583 first ='+';2584else if(first =='+')2585 first ='-';2586}25872588switch(first) {2589case'\n':2590/* Newer GNU diff, empty context line */2591if(plen <0)2592/* ... followed by '\No newline'; nothing */2593break;2594*old++ ='\n';2595strbuf_addch(&newlines,'\n');2596add_line_info(&preimage,"\n",1, LINE_COMMON);2597add_line_info(&postimage,"\n",1, LINE_COMMON);2598 is_blank_context =1;2599break;2600case' ':2601if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2602ws_blank_line(patch +1, plen, ws_rule))2603 is_blank_context =1;2604case'-':2605memcpy(old, patch +1, plen);2606add_line_info(&preimage, old, plen,2607(first ==' '? LINE_COMMON :0));2608 old += plen;2609if(first =='-')2610break;2611/* Fall-through for ' ' */2612case'+':2613/* --no-add does not add new lines */2614if(first =='+'&& no_add)2615break;26162617 start = newlines.len;2618if(first !='+'||2619!whitespace_error ||2620 ws_error_action != correct_ws_error) {2621strbuf_add(&newlines, patch +1, plen);2622}2623else{2624ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2625}2626add_line_info(&postimage, newlines.buf + start, newlines.len - start,2627(first =='+'?0: LINE_COMMON));2628if(first =='+'&&2629(ws_rule & WS_BLANK_AT_EOF) &&2630ws_blank_line(patch +1, plen, ws_rule))2631 added_blank_line =1;2632break;2633case'@':case'\\':2634/* Ignore it, we already handled it */2635break;2636default:2637if(apply_verbosely)2638error(_("invalid start of line: '%c'"), first);2639return-1;2640}2641if(added_blank_line) {2642if(!new_blank_lines_at_end)2643 found_new_blank_lines_at_end = hunk_linenr;2644 new_blank_lines_at_end++;2645}2646else if(is_blank_context)2647;2648else2649 new_blank_lines_at_end =0;2650 patch += len;2651 size -= len;2652 hunk_linenr++;2653}2654if(inaccurate_eof &&2655 old > oldlines && old[-1] =='\n'&&2656 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2657 old--;2658strbuf_setlen(&newlines, newlines.len -1);2659}26602661 leading = frag->leading;2662 trailing = frag->trailing;26632664/*2665 * A hunk to change lines at the beginning would begin with2666 * @@ -1,L +N,M @@2667 * but we need to be careful. -U0 that inserts before the second2668 * line also has this pattern.2669 *2670 * And a hunk to add to an empty file would begin with2671 * @@ -0,0 +N,M @@2672 *2673 * In other words, a hunk that is (frag->oldpos <= 1) with or2674 * without leading context must match at the beginning.2675 */2676 match_beginning = (!frag->oldpos ||2677(frag->oldpos ==1&& !unidiff_zero));26782679/*2680 * A hunk without trailing lines must match at the end.2681 * However, we simply cannot tell if a hunk must match end2682 * from the lack of trailing lines if the patch was generated2683 * with unidiff without any context.2684 */2685 match_end = !unidiff_zero && !trailing;26862687 pos = frag->newpos ? (frag->newpos -1) :0;2688 preimage.buf = oldlines;2689 preimage.len = old - oldlines;2690 postimage.buf = newlines.buf;2691 postimage.len = newlines.len;2692 preimage.line = preimage.line_allocated;2693 postimage.line = postimage.line_allocated;26942695for(;;) {26962697 applied_pos =find_pos(img, &preimage, &postimage, pos,2698 ws_rule, match_beginning, match_end);26992700if(applied_pos >=0)2701break;27022703/* Am I at my context limits? */2704if((leading <= p_context) && (trailing <= p_context))2705break;2706if(match_beginning || match_end) {2707 match_beginning = match_end =0;2708continue;2709}27102711/*2712 * Reduce the number of context lines; reduce both2713 * leading and trailing if they are equal otherwise2714 * just reduce the larger context.2715 */2716if(leading >= trailing) {2717remove_first_line(&preimage);2718remove_first_line(&postimage);2719 pos--;2720 leading--;2721}2722if(trailing > leading) {2723remove_last_line(&preimage);2724remove_last_line(&postimage);2725 trailing--;2726}2727}27282729if(applied_pos >=0) {2730if(new_blank_lines_at_end &&2731 preimage.nr + applied_pos >= img->nr &&2732(ws_rule & WS_BLANK_AT_EOF) &&2733 ws_error_action != nowarn_ws_error) {2734record_ws_error(WS_BLANK_AT_EOF,"+",1,2735 found_new_blank_lines_at_end);2736if(ws_error_action == correct_ws_error) {2737while(new_blank_lines_at_end--)2738remove_last_line(&postimage);2739}2740/*2741 * We would want to prevent write_out_results()2742 * from taking place in apply_patch() that follows2743 * the callchain led us here, which is:2744 * apply_patch->check_patch_list->check_patch->2745 * apply_data->apply_fragments->apply_one_fragment2746 */2747if(ws_error_action == die_on_ws_error)2748 apply =0;2749}27502751if(apply_verbosely && applied_pos != pos) {2752int offset = applied_pos - pos;2753if(apply_in_reverse)2754 offset =0- offset;2755fprintf_ln(stderr,2756Q_("Hunk #%dsucceeded at%d(offset%dline).",2757"Hunk #%dsucceeded at%d(offset%dlines).",2758 offset),2759 nth_fragment, applied_pos +1, offset);2760}27612762/*2763 * Warn if it was necessary to reduce the number2764 * of context lines.2765 */2766if((leading != frag->leading) ||2767(trailing != frag->trailing))2768fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2769" to apply fragment at%d"),2770 leading, trailing, applied_pos+1);2771update_image(img, applied_pos, &preimage, &postimage);2772}else{2773if(apply_verbosely)2774error(_("while searching for:\n%.*s"),2775(int)(old - oldlines), oldlines);2776}27772778free(oldlines);2779strbuf_release(&newlines);2780free(preimage.line_allocated);2781free(postimage.line_allocated);27822783return(applied_pos <0);2784}27852786static intapply_binary_fragment(struct image *img,struct patch *patch)2787{2788struct fragment *fragment = patch->fragments;2789unsigned long len;2790void*dst;27912792if(!fragment)2793returnerror(_("missing binary patch data for '%s'"),2794 patch->new_name ?2795 patch->new_name :2796 patch->old_name);27972798/* Binary patch is irreversible without the optional second hunk */2799if(apply_in_reverse) {2800if(!fragment->next)2801returnerror("cannot reverse-apply a binary patch "2802"without the reverse hunk to '%s'",2803 patch->new_name2804? patch->new_name : patch->old_name);2805 fragment = fragment->next;2806}2807switch(fragment->binary_patch_method) {2808case BINARY_DELTA_DEFLATED:2809 dst =patch_delta(img->buf, img->len, fragment->patch,2810 fragment->size, &len);2811if(!dst)2812return-1;2813clear_image(img);2814 img->buf = dst;2815 img->len = len;2816return0;2817case BINARY_LITERAL_DEFLATED:2818clear_image(img);2819 img->len = fragment->size;2820 img->buf =xmalloc(img->len+1);2821memcpy(img->buf, fragment->patch, img->len);2822 img->buf[img->len] ='\0';2823return0;2824}2825return-1;2826}28272828/*2829 * Replace "img" with the result of applying the binary patch.2830 * The binary patch data itself in patch->fragment is still kept2831 * but the preimage prepared by the caller in "img" is freed here2832 * or in the helper function apply_binary_fragment() this calls.2833 */2834static intapply_binary(struct image *img,struct patch *patch)2835{2836const char*name = patch->old_name ? patch->old_name : patch->new_name;2837unsigned char sha1[20];28382839/*2840 * For safety, we require patch index line to contain2841 * full 40-byte textual SHA1 for old and new, at least for now.2842 */2843if(strlen(patch->old_sha1_prefix) !=40||2844strlen(patch->new_sha1_prefix) !=40||2845get_sha1_hex(patch->old_sha1_prefix, sha1) ||2846get_sha1_hex(patch->new_sha1_prefix, sha1))2847returnerror("cannot apply binary patch to '%s' "2848"without full index line", name);28492850if(patch->old_name) {2851/*2852 * See if the old one matches what the patch2853 * applies to.2854 */2855hash_sha1_file(img->buf, img->len, blob_type, sha1);2856if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2857returnerror("the patch applies to '%s' (%s), "2858"which does not match the "2859"current contents.",2860 name,sha1_to_hex(sha1));2861}2862else{2863/* Otherwise, the old one must be empty. */2864if(img->len)2865returnerror("the patch applies to an empty "2866"'%s' but it is not empty", name);2867}28682869get_sha1_hex(patch->new_sha1_prefix, sha1);2870if(is_null_sha1(sha1)) {2871clear_image(img);2872return0;/* deletion patch */2873}28742875if(has_sha1_file(sha1)) {2876/* We already have the postimage */2877enum object_type type;2878unsigned long size;2879char*result;28802881 result =read_sha1_file(sha1, &type, &size);2882if(!result)2883returnerror("the necessary postimage%sfor "2884"'%s' cannot be read",2885 patch->new_sha1_prefix, name);2886clear_image(img);2887 img->buf = result;2888 img->len = size;2889}else{2890/*2891 * We have verified buf matches the preimage;2892 * apply the patch data to it, which is stored2893 * in the patch->fragments->{patch,size}.2894 */2895if(apply_binary_fragment(img, patch))2896returnerror(_("binary patch does not apply to '%s'"),2897 name);28982899/* verify that the result matches */2900hash_sha1_file(img->buf, img->len, blob_type, sha1);2901if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2902returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),2903 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2904}29052906return0;2907}29082909static intapply_fragments(struct image *img,struct patch *patch)2910{2911struct fragment *frag = patch->fragments;2912const char*name = patch->old_name ? patch->old_name : patch->new_name;2913unsigned ws_rule = patch->ws_rule;2914unsigned inaccurate_eof = patch->inaccurate_eof;2915int nth =0;29162917if(patch->is_binary)2918returnapply_binary(img, patch);29192920while(frag) {2921 nth++;2922if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {2923error(_("patch failed:%s:%ld"), name, frag->oldpos);2924if(!apply_with_reject)2925return-1;2926 frag->rejected =1;2927}2928 frag = frag->next;2929}2930return0;2931}29322933static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2934{2935if(!ce)2936return0;29372938if(S_ISGITLINK(ce->ce_mode)) {2939strbuf_grow(buf,100);2940strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2941}else{2942enum object_type type;2943unsigned long sz;2944char*result;29452946 result =read_sha1_file(ce->sha1, &type, &sz);2947if(!result)2948return-1;2949/* XXX read_sha1_file NUL-terminates */2950strbuf_attach(buf, result, sz, sz +1);2951}2952return0;2953}29542955static struct patch *in_fn_table(const char*name)2956{2957struct string_list_item *item;29582959if(name == NULL)2960return NULL;29612962 item =string_list_lookup(&fn_table, name);2963if(item != NULL)2964return(struct patch *)item->util;29652966return NULL;2967}29682969/*2970 * item->util in the filename table records the status of the path.2971 * Usually it points at a patch (whose result records the contents2972 * of it after applying it), but it could be PATH_WAS_DELETED for a2973 * path that a previously applied patch has already removed, or2974 * PATH_TO_BE_DELETED for a path that a later patch would remove.2975 *2976 * The latter is needed to deal with a case where two paths A and B2977 * are swapped by first renaming A to B and then renaming B to A;2978 * moving A to B should not be prevented due to presense of B as we2979 * will remove it in a later patch.2980 */2981#define PATH_TO_BE_DELETED ((struct patch *) -2)2982#define PATH_WAS_DELETED ((struct patch *) -1)29832984static intto_be_deleted(struct patch *patch)2985{2986return patch == PATH_TO_BE_DELETED;2987}29882989static intwas_deleted(struct patch *patch)2990{2991return patch == PATH_WAS_DELETED;2992}29932994static voidadd_to_fn_table(struct patch *patch)2995{2996struct string_list_item *item;29972998/*2999 * Always add new_name unless patch is a deletion3000 * This should cover the cases for normal diffs,3001 * file creations and copies3002 */3003if(patch->new_name != NULL) {3004 item =string_list_insert(&fn_table, patch->new_name);3005 item->util = patch;3006}30073008/*3009 * store a failure on rename/deletion cases because3010 * later chunks shouldn't patch old names3011 */3012if((patch->new_name == NULL) || (patch->is_rename)) {3013 item =string_list_insert(&fn_table, patch->old_name);3014 item->util = PATH_WAS_DELETED;3015}3016}30173018static voidprepare_fn_table(struct patch *patch)3019{3020/*3021 * store information about incoming file deletion3022 */3023while(patch) {3024if((patch->new_name == NULL) || (patch->is_rename)) {3025struct string_list_item *item;3026 item =string_list_insert(&fn_table, patch->old_name);3027 item->util = PATH_TO_BE_DELETED;3028}3029 patch = patch->next;3030}3031}30323033static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)3034{3035struct strbuf buf = STRBUF_INIT;3036struct image image;3037size_t len;3038char*img;3039struct patch *tpatch;30403041if(!(patch->is_copy || patch->is_rename) &&3042(tpatch =in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {3043if(was_deleted(tpatch)) {3044returnerror(_("patch%shas been renamed/deleted"),3045 patch->old_name);3046}3047/* We have a patched copy in memory; use that. */3048strbuf_add(&buf, tpatch->result, tpatch->resultsize);3049}else if(cached) {3050if(read_file_or_gitlink(ce, &buf))3051returnerror(_("read of%sfailed"), patch->old_name);3052}else if(patch->old_name) {3053if(S_ISGITLINK(patch->old_mode)) {3054if(ce) {3055read_file_or_gitlink(ce, &buf);3056}else{3057/*3058 * There is no way to apply subproject3059 * patch without looking at the index.3060 * NEEDSWORK: shouldn't this be flagged3061 * as an error???3062 */3063free_fragment_list(patch->fragments);3064 patch->fragments = NULL;3065}3066}else{3067if(read_old_data(st, patch->old_name, &buf))3068returnerror(_("read of%sfailed"), patch->old_name);3069}3070}30713072 img =strbuf_detach(&buf, &len);3073prepare_image(&image, img, len, !patch->is_binary);30743075if(apply_fragments(&image, patch) <0)3076return-1;/* note with --reject this succeeds. */3077 patch->result = image.buf;3078 patch->resultsize = image.len;3079add_to_fn_table(patch);3080free(image.line_allocated);30813082if(0< patch->is_delete && patch->resultsize)3083returnerror(_("removal patch leaves file contents"));30843085return0;3086}30873088static intcheck_to_create_blob(const char*new_name,int ok_if_exists)3089{3090struct stat nst;3091if(!lstat(new_name, &nst)) {3092if(S_ISDIR(nst.st_mode) || ok_if_exists)3093return0;3094/*3095 * A leading component of new_name might be a symlink3096 * that is going to be removed with this patch, but3097 * still pointing at somewhere that has the path.3098 * In such a case, path "new_name" does not exist as3099 * far as git is concerned.3100 */3101if(has_symlink_leading_path(new_name,strlen(new_name)))3102return0;31033104returnerror(_("%s: already exists in working directory"), new_name);3105}3106else if((errno != ENOENT) && (errno != ENOTDIR))3107returnerror("%s:%s", new_name,strerror(errno));3108return0;3109}31103111static intverify_index_match(struct cache_entry *ce,struct stat *st)3112{3113if(S_ISGITLINK(ce->ce_mode)) {3114if(!S_ISDIR(st->st_mode))3115return-1;3116return0;3117}3118returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3119}31203121static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)3122{3123const char*old_name = patch->old_name;3124struct patch *tpatch = NULL;3125int stat_ret =0;3126unsigned st_mode =0;31273128/*3129 * Make sure that we do not have local modifications from the3130 * index when we are looking at the index. Also make sure3131 * we have the preimage file to be patched in the work tree,3132 * unless --cached, which tells git to apply only in the index.3133 */3134if(!old_name)3135return0;31363137assert(patch->is_new <=0);31383139if(!(patch->is_copy || patch->is_rename) &&3140(tpatch =in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {3141if(was_deleted(tpatch))3142returnerror(_("%s: has been deleted/renamed"), old_name);3143 st_mode = tpatch->new_mode;3144}else if(!cached) {3145 stat_ret =lstat(old_name, st);3146if(stat_ret && errno != ENOENT)3147returnerror(_("%s:%s"), old_name,strerror(errno));3148}31493150if(to_be_deleted(tpatch))3151 tpatch = NULL;31523153if(check_index && !tpatch) {3154int pos =cache_name_pos(old_name,strlen(old_name));3155if(pos <0) {3156if(patch->is_new <0)3157goto is_new;3158returnerror(_("%s: does not exist in index"), old_name);3159}3160*ce = active_cache[pos];3161if(stat_ret <0) {3162struct checkout costate;3163/* checkout */3164memset(&costate,0,sizeof(costate));3165 costate.base_dir ="";3166 costate.refresh_cache =1;3167if(checkout_entry(*ce, &costate, NULL) ||3168lstat(old_name, st))3169return-1;3170}3171if(!cached &&verify_index_match(*ce, st))3172returnerror(_("%s: does not match index"), old_name);3173if(cached)3174 st_mode = (*ce)->ce_mode;3175}else if(stat_ret <0) {3176if(patch->is_new <0)3177goto is_new;3178returnerror(_("%s:%s"), old_name,strerror(errno));3179}31803181if(!cached && !tpatch)3182 st_mode =ce_mode_from_stat(*ce, st->st_mode);31833184if(patch->is_new <0)3185 patch->is_new =0;3186if(!patch->old_mode)3187 patch->old_mode = st_mode;3188if((st_mode ^ patch->old_mode) & S_IFMT)3189returnerror(_("%s: wrong type"), old_name);3190if(st_mode != patch->old_mode)3191warning(_("%shas type%o, expected%o"),3192 old_name, st_mode, patch->old_mode);3193if(!patch->new_mode && !patch->is_delete)3194 patch->new_mode = st_mode;3195return0;31963197 is_new:3198 patch->is_new =1;3199 patch->is_delete =0;3200free(patch->old_name);3201 patch->old_name = NULL;3202return0;3203}32043205/*3206 * Check and apply the patch in-core; leave the result in patch->result3207 * for the caller to write it out to the final destination.3208 */3209static intcheck_patch(struct patch *patch)3210{3211struct stat st;3212const char*old_name = patch->old_name;3213const char*new_name = patch->new_name;3214const char*name = old_name ? old_name : new_name;3215struct cache_entry *ce = NULL;3216struct patch *tpatch;3217int ok_if_exists;3218int status;32193220 patch->rejected =1;/* we will drop this after we succeed */32213222 status =check_preimage(patch, &ce, &st);3223if(status)3224return status;3225 old_name = patch->old_name;32263227/*3228 * A type-change diff is always split into a patch to delete3229 * old, immediately followed by a patch to create new (see3230 * diff.c::run_diff()); in such a case it is Ok that the entry3231 * to be deleted by the previous patch is still in the working3232 * tree and in the index.3233 *3234 * A patch to swap-rename between A and B would first rename A3235 * to B and then rename B to A. While applying the first one,3236 * the presense of B should not stop A from getting renamed to3237 * B; ask to_be_deleted() about the later rename. Removal of3238 * B and rename from A to B is handled the same way by asking3239 * was_deleted().3240 */3241if((tpatch =in_fn_table(new_name)) &&3242(was_deleted(tpatch) ||to_be_deleted(tpatch)))3243 ok_if_exists =1;3244else3245 ok_if_exists =0;32463247if(new_name &&3248((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {3249if(check_index &&3250cache_name_pos(new_name,strlen(new_name)) >=0&&3251!ok_if_exists)3252returnerror(_("%s: already exists in index"), new_name);3253if(!cached) {3254int err =check_to_create_blob(new_name, ok_if_exists);3255if(err)3256return err;3257}3258if(!patch->new_mode) {3259if(0< patch->is_new)3260 patch->new_mode = S_IFREG |0644;3261else3262 patch->new_mode = patch->old_mode;3263}3264}32653266if(new_name && old_name) {3267int same = !strcmp(old_name, new_name);3268if(!patch->new_mode)3269 patch->new_mode = patch->old_mode;3270if((patch->old_mode ^ patch->new_mode) & S_IFMT)3271returnerror(_("new mode (%o) of%sdoes not match old mode (%o)%s%s"),3272 patch->new_mode, new_name, patch->old_mode,3273 same ?"":" of ", same ?"": old_name);3274}32753276if(apply_data(patch, &st, ce) <0)3277returnerror(_("%s: patch does not apply"), name);3278 patch->rejected =0;3279return0;3280}32813282static intcheck_patch_list(struct patch *patch)3283{3284int err =0;32853286prepare_fn_table(patch);3287while(patch) {3288if(apply_verbosely)3289say_patch_name(stderr,3290_("Checking patch%s..."), patch);3291 err |=check_patch(patch);3292 patch = patch->next;3293}3294return err;3295}32963297/* This function tries to read the sha1 from the current index */3298static intget_current_sha1(const char*path,unsigned char*sha1)3299{3300int pos;33013302if(read_cache() <0)3303return-1;3304 pos =cache_name_pos(path,strlen(path));3305if(pos <0)3306return-1;3307hashcpy(sha1, active_cache[pos]->sha1);3308return0;3309}33103311/* Build an index that contains the just the files needed for a 3way merge */3312static voidbuild_fake_ancestor(struct patch *list,const char*filename)3313{3314struct patch *patch;3315struct index_state result = { NULL };3316int fd;33173318/* Once we start supporting the reverse patch, it may be3319 * worth showing the new sha1 prefix, but until then...3320 */3321for(patch = list; patch; patch = patch->next) {3322const unsigned char*sha1_ptr;3323unsigned char sha1[20];3324struct cache_entry *ce;3325const char*name;33263327 name = patch->old_name ? patch->old_name : patch->new_name;3328if(0< patch->is_new)3329continue;3330else if(get_sha1(patch->old_sha1_prefix, sha1))3331/* git diff has no index line for mode/type changes */3332if(!patch->lines_added && !patch->lines_deleted) {3333if(get_current_sha1(patch->old_name, sha1))3334die("mode change for%s, which is not "3335"in current HEAD", name);3336 sha1_ptr = sha1;3337}else3338die("sha1 information is lacking or useless "3339"(%s).", name);3340else3341 sha1_ptr = sha1;33423343 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);3344if(!ce)3345die(_("make_cache_entry failed for path '%s'"), name);3346if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3347die("Could not add%sto temporary index", name);3348}33493350 fd =open(filename, O_WRONLY | O_CREAT,0666);3351if(fd <0||write_index(&result, fd) ||close(fd))3352die("Could not write temporary index to%s", filename);33533354discard_index(&result);3355}33563357static voidstat_patch_list(struct patch *patch)3358{3359int files, adds, dels;33603361for(files = adds = dels =0; patch ; patch = patch->next) {3362 files++;3363 adds += patch->lines_added;3364 dels += patch->lines_deleted;3365show_stats(patch);3366}33673368print_stat_summary(stdout, files, adds, dels);3369}33703371static voidnumstat_patch_list(struct patch *patch)3372{3373for( ; patch; patch = patch->next) {3374const char*name;3375 name = patch->new_name ? patch->new_name : patch->old_name;3376if(patch->is_binary)3377printf("-\t-\t");3378else3379printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3380write_name_quoted(name, stdout, line_termination);3381}3382}33833384static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3385{3386if(mode)3387printf("%smode%06o%s\n", newdelete, mode, name);3388else3389printf("%s %s\n", newdelete, name);3390}33913392static voidshow_mode_change(struct patch *p,int show_name)3393{3394if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3395if(show_name)3396printf(" mode change%06o =>%06o%s\n",3397 p->old_mode, p->new_mode, p->new_name);3398else3399printf(" mode change%06o =>%06o\n",3400 p->old_mode, p->new_mode);3401}3402}34033404static voidshow_rename_copy(struct patch *p)3405{3406const char*renamecopy = p->is_rename ?"rename":"copy";3407const char*old, *new;34083409/* Find common prefix */3410 old = p->old_name;3411new= p->new_name;3412while(1) {3413const char*slash_old, *slash_new;3414 slash_old =strchr(old,'/');3415 slash_new =strchr(new,'/');3416if(!slash_old ||3417!slash_new ||3418 slash_old - old != slash_new -new||3419memcmp(old,new, slash_new -new))3420break;3421 old = slash_old +1;3422new= slash_new +1;3423}3424/* p->old_name thru old is the common prefix, and old and new3425 * through the end of names are renames3426 */3427if(old != p->old_name)3428printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,3429(int)(old - p->old_name), p->old_name,3430 old,new, p->score);3431else3432printf("%s %s=>%s(%d%%)\n", renamecopy,3433 p->old_name, p->new_name, p->score);3434show_mode_change(p,0);3435}34363437static voidsummary_patch_list(struct patch *patch)3438{3439struct patch *p;34403441for(p = patch; p; p = p->next) {3442if(p->is_new)3443show_file_mode_name("create", p->new_mode, p->new_name);3444else if(p->is_delete)3445show_file_mode_name("delete", p->old_mode, p->old_name);3446else{3447if(p->is_rename || p->is_copy)3448show_rename_copy(p);3449else{3450if(p->score) {3451printf(" rewrite%s(%d%%)\n",3452 p->new_name, p->score);3453show_mode_change(p,0);3454}3455else3456show_mode_change(p,1);3457}3458}3459}3460}34613462static voidpatch_stats(struct patch *patch)3463{3464int lines = patch->lines_added + patch->lines_deleted;34653466if(lines > max_change)3467 max_change = lines;3468if(patch->old_name) {3469int len =quote_c_style(patch->old_name, NULL, NULL,0);3470if(!len)3471 len =strlen(patch->old_name);3472if(len > max_len)3473 max_len = len;3474}3475if(patch->new_name) {3476int len =quote_c_style(patch->new_name, NULL, NULL,0);3477if(!len)3478 len =strlen(patch->new_name);3479if(len > max_len)3480 max_len = len;3481}3482}34833484static voidremove_file(struct patch *patch,int rmdir_empty)3485{3486if(update_index) {3487if(remove_file_from_cache(patch->old_name) <0)3488die(_("unable to remove%sfrom index"), patch->old_name);3489}3490if(!cached) {3491if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {3492remove_path(patch->old_name);3493}3494}3495}34963497static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)3498{3499struct stat st;3500struct cache_entry *ce;3501int namelen =strlen(path);3502unsigned ce_size =cache_entry_size(namelen);35033504if(!update_index)3505return;35063507 ce =xcalloc(1, ce_size);3508memcpy(ce->name, path, namelen);3509 ce->ce_mode =create_ce_mode(mode);3510 ce->ce_flags = namelen;3511if(S_ISGITLINK(mode)) {3512const char*s = buf;35133514if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))3515die(_("corrupt patch for subproject%s"), path);3516}else{3517if(!cached) {3518if(lstat(path, &st) <0)3519die_errno(_("unable to stat newly created file '%s'"),3520 path);3521fill_stat_cache_info(ce, &st);3522}3523if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)3524die(_("unable to create backing store for newly created file%s"), path);3525}3526if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3527die(_("unable to add cache entry for%s"), path);3528}35293530static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)3531{3532int fd;3533struct strbuf nbuf = STRBUF_INIT;35343535if(S_ISGITLINK(mode)) {3536struct stat st;3537if(!lstat(path, &st) &&S_ISDIR(st.st_mode))3538return0;3539returnmkdir(path,0777);3540}35413542if(has_symlinks &&S_ISLNK(mode))3543/* Although buf:size is counted string, it also is NUL3544 * terminated.3545 */3546returnsymlink(buf, path);35473548 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);3549if(fd <0)3550return-1;35513552if(convert_to_working_tree(path, buf, size, &nbuf)) {3553 size = nbuf.len;3554 buf = nbuf.buf;3555}3556write_or_die(fd, buf, size);3557strbuf_release(&nbuf);35583559if(close(fd) <0)3560die_errno(_("closing file '%s'"), path);3561return0;3562}35633564/*3565 * We optimistically assume that the directories exist,3566 * which is true 99% of the time anyway. If they don't,3567 * we create them and try again.3568 */3569static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)3570{3571if(cached)3572return;3573if(!try_create_file(path, mode, buf, size))3574return;35753576if(errno == ENOENT) {3577if(safe_create_leading_directories(path))3578return;3579if(!try_create_file(path, mode, buf, size))3580return;3581}35823583if(errno == EEXIST || errno == EACCES) {3584/* We may be trying to create a file where a directory3585 * used to be.3586 */3587struct stat st;3588if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))3589 errno = EEXIST;3590}35913592if(errno == EEXIST) {3593unsigned int nr =getpid();35943595for(;;) {3596char newpath[PATH_MAX];3597mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);3598if(!try_create_file(newpath, mode, buf, size)) {3599if(!rename(newpath, path))3600return;3601unlink_or_warn(newpath);3602break;3603}3604if(errno != EEXIST)3605break;3606++nr;3607}3608}3609die_errno(_("unable to write file '%s' mode%o"), path, mode);3610}36113612static voidcreate_file(struct patch *patch)3613{3614char*path = patch->new_name;3615unsigned mode = patch->new_mode;3616unsigned long size = patch->resultsize;3617char*buf = patch->result;36183619if(!mode)3620 mode = S_IFREG |0644;3621create_one_file(path, mode, buf, size);3622add_index_file(path, mode, buf, size);3623}36243625/* phase zero is to remove, phase one is to create */3626static voidwrite_out_one_result(struct patch *patch,int phase)3627{3628if(patch->is_delete >0) {3629if(phase ==0)3630remove_file(patch,1);3631return;3632}3633if(patch->is_new >0|| patch->is_copy) {3634if(phase ==1)3635create_file(patch);3636return;3637}3638/*3639 * Rename or modification boils down to the same3640 * thing: remove the old, write the new3641 */3642if(phase ==0)3643remove_file(patch, patch->is_rename);3644if(phase ==1)3645create_file(patch);3646}36473648static intwrite_out_one_reject(struct patch *patch)3649{3650FILE*rej;3651char namebuf[PATH_MAX];3652struct fragment *frag;3653int cnt =0;3654struct strbuf sb = STRBUF_INIT;36553656for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {3657if(!frag->rejected)3658continue;3659 cnt++;3660}36613662if(!cnt) {3663if(apply_verbosely)3664say_patch_name(stderr,3665_("Applied patch%scleanly."), patch);3666return0;3667}36683669/* This should not happen, because a removal patch that leaves3670 * contents are marked "rejected" at the patch level.3671 */3672if(!patch->new_name)3673die(_("internal error"));36743675/* Say this even without --verbose */3676strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",3677"Applying patch %%swith%drejects...",3678 cnt),3679 cnt);3680say_patch_name(stderr, sb.buf, patch);3681strbuf_release(&sb);36823683 cnt =strlen(patch->new_name);3684if(ARRAY_SIZE(namebuf) <= cnt +5) {3685 cnt =ARRAY_SIZE(namebuf) -5;3686warning(_("truncating .rej filename to %.*s.rej"),3687 cnt -1, patch->new_name);3688}3689memcpy(namebuf, patch->new_name, cnt);3690memcpy(namebuf + cnt,".rej",5);36913692 rej =fopen(namebuf,"w");3693if(!rej)3694returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));36953696/* Normal git tools never deal with .rej, so do not pretend3697 * this is a git patch by saying --git nor give extended3698 * headers. While at it, maybe please "kompare" that wants3699 * the trailing TAB and some garbage at the end of line ;-).3700 */3701fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",3702 patch->new_name, patch->new_name);3703for(cnt =1, frag = patch->fragments;3704 frag;3705 cnt++, frag = frag->next) {3706if(!frag->rejected) {3707fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);3708continue;3709}3710fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);3711fprintf(rej,"%.*s", frag->size, frag->patch);3712if(frag->patch[frag->size-1] !='\n')3713fputc('\n', rej);3714}3715fclose(rej);3716return-1;3717}37183719static intwrite_out_results(struct patch *list)3720{3721int phase;3722int errs =0;3723struct patch *l;37243725for(phase =0; phase <2; phase++) {3726 l = list;3727while(l) {3728if(l->rejected)3729 errs =1;3730else{3731write_out_one_result(l, phase);3732if(phase ==1&&write_out_one_reject(l))3733 errs =1;3734}3735 l = l->next;3736}3737}3738return errs;3739}37403741static struct lock_file lock_file;37423743static struct string_list limit_by_name;3744static int has_include;3745static voidadd_name_limit(const char*name,int exclude)3746{3747struct string_list_item *it;37483749 it =string_list_append(&limit_by_name, name);3750 it->util = exclude ? NULL : (void*)1;3751}37523753static intuse_patch(struct patch *p)3754{3755const char*pathname = p->new_name ? p->new_name : p->old_name;3756int i;37573758/* Paths outside are not touched regardless of "--include" */3759if(0< prefix_length) {3760int pathlen =strlen(pathname);3761if(pathlen <= prefix_length ||3762memcmp(prefix, pathname, prefix_length))3763return0;3764}37653766/* See if it matches any of exclude/include rule */3767for(i =0; i < limit_by_name.nr; i++) {3768struct string_list_item *it = &limit_by_name.items[i];3769if(!fnmatch(it->string, pathname,0))3770return(it->util != NULL);3771}37723773/*3774 * If we had any include, a path that does not match any rule is3775 * not used. Otherwise, we saw bunch of exclude rules (or none)3776 * and such a path is used.3777 */3778return!has_include;3779}378037813782static voidprefix_one(char**name)3783{3784char*old_name = *name;3785if(!old_name)3786return;3787*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3788free(old_name);3789}37903791static voidprefix_patches(struct patch *p)3792{3793if(!prefix || p->is_toplevel_relative)3794return;3795for( ; p; p = p->next) {3796prefix_one(&p->new_name);3797prefix_one(&p->old_name);3798}3799}38003801#define INACCURATE_EOF (1<<0)3802#define RECOUNT (1<<1)38033804static intapply_patch(int fd,const char*filename,int options)3805{3806size_t offset;3807struct strbuf buf = STRBUF_INIT;/* owns the patch text */3808struct patch *list = NULL, **listp = &list;3809int skipped_patch =0;38103811 patch_input_file = filename;3812read_patch_file(&buf, fd);3813 offset =0;3814while(offset < buf.len) {3815struct patch *patch;3816int nr;38173818 patch =xcalloc(1,sizeof(*patch));3819 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3820 patch->recount = !!(options & RECOUNT);3821 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3822if(nr <0)3823break;3824if(apply_in_reverse)3825reverse_patches(patch);3826if(prefix)3827prefix_patches(patch);3828if(use_patch(patch)) {3829patch_stats(patch);3830*listp = patch;3831 listp = &patch->next;3832}3833else{3834free_patch(patch);3835 skipped_patch++;3836}3837 offset += nr;3838}38393840if(!list && !skipped_patch)3841die(_("unrecognized input"));38423843if(whitespace_error && (ws_error_action == die_on_ws_error))3844 apply =0;38453846 update_index = check_index && apply;3847if(update_index && newfd <0)3848 newfd =hold_locked_index(&lock_file,1);38493850if(check_index) {3851if(read_cache() <0)3852die(_("unable to read index file"));3853}38543855if((check || apply) &&3856check_patch_list(list) <0&&3857!apply_with_reject)3858exit(1);38593860if(apply &&write_out_results(list))3861exit(1);38623863if(fake_ancestor)3864build_fake_ancestor(list, fake_ancestor);38653866if(diffstat)3867stat_patch_list(list);38683869if(numstat)3870numstat_patch_list(list);38713872if(summary)3873summary_patch_list(list);38743875free_patch_list(list);3876strbuf_release(&buf);3877string_list_clear(&fn_table,0);3878return0;3879}38803881static intgit_apply_config(const char*var,const char*value,void*cb)3882{3883if(!strcmp(var,"apply.whitespace"))3884returngit_config_string(&apply_default_whitespace, var, value);3885else if(!strcmp(var,"apply.ignorewhitespace"))3886returngit_config_string(&apply_default_ignorewhitespace, var, value);3887returngit_default_config(var, value, cb);3888}38893890static intoption_parse_exclude(const struct option *opt,3891const char*arg,int unset)3892{3893add_name_limit(arg,1);3894return0;3895}38963897static intoption_parse_include(const struct option *opt,3898const char*arg,int unset)3899{3900add_name_limit(arg,0);3901 has_include =1;3902return0;3903}39043905static intoption_parse_p(const struct option *opt,3906const char*arg,int unset)3907{3908 p_value =atoi(arg);3909 p_value_known =1;3910return0;3911}39123913static intoption_parse_z(const struct option *opt,3914const char*arg,int unset)3915{3916if(unset)3917 line_termination ='\n';3918else3919 line_termination =0;3920return0;3921}39223923static intoption_parse_space_change(const struct option *opt,3924const char*arg,int unset)3925{3926if(unset)3927 ws_ignore_action = ignore_ws_none;3928else3929 ws_ignore_action = ignore_ws_change;3930return0;3931}39323933static intoption_parse_whitespace(const struct option *opt,3934const char*arg,int unset)3935{3936const char**whitespace_option = opt->value;39373938*whitespace_option = arg;3939parse_whitespace_option(arg);3940return0;3941}39423943static intoption_parse_directory(const struct option *opt,3944const char*arg,int unset)3945{3946 root_len =strlen(arg);3947if(root_len && arg[root_len -1] !='/') {3948char*new_root;3949 root = new_root =xmalloc(root_len +2);3950strcpy(new_root, arg);3951strcpy(new_root + root_len++,"/");3952}else3953 root = arg;3954return0;3955}39563957intcmd_apply(int argc,const char**argv,const char*prefix_)3958{3959int i;3960int errs =0;3961int is_not_gitdir = !startup_info->have_repository;3962int force_apply =0;39633964const char*whitespace_option = NULL;39653966struct option builtin_apply_options[] = {3967{ OPTION_CALLBACK,0,"exclude", NULL,"path",3968"don't apply changes matching the given path",39690, option_parse_exclude },3970{ OPTION_CALLBACK,0,"include", NULL,"path",3971"apply changes matching the given path",39720, option_parse_include },3973{ OPTION_CALLBACK,'p', NULL, NULL,"num",3974"remove <num> leading slashes from traditional diff paths",39750, option_parse_p },3976OPT_BOOLEAN(0,"no-add", &no_add,3977"ignore additions made by the patch"),3978OPT_BOOLEAN(0,"stat", &diffstat,3979"instead of applying the patch, output diffstat for the input"),3980OPT_NOOP_NOARG(0,"allow-binary-replacement"),3981OPT_NOOP_NOARG(0,"binary"),3982OPT_BOOLEAN(0,"numstat", &numstat,3983"shows number of added and deleted lines in decimal notation"),3984OPT_BOOLEAN(0,"summary", &summary,3985"instead of applying the patch, output a summary for the input"),3986OPT_BOOLEAN(0,"check", &check,3987"instead of applying the patch, see if the patch is applicable"),3988OPT_BOOLEAN(0,"index", &check_index,3989"make sure the patch is applicable to the current index"),3990OPT_BOOLEAN(0,"cached", &cached,3991"apply a patch without touching the working tree"),3992OPT_BOOLEAN(0,"apply", &force_apply,3993"also apply the patch (use with --stat/--summary/--check)"),3994OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,3995"build a temporary index based on embedded index information"),3996{ OPTION_CALLBACK,'z', NULL, NULL, NULL,3997"paths are separated with NUL character",3998 PARSE_OPT_NOARG, option_parse_z },3999OPT_INTEGER('C', NULL, &p_context,4000"ensure at least <n> lines of context match"),4001{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,"action",4002"detect new or modified lines that have whitespace errors",40030, option_parse_whitespace },4004{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,4005"ignore changes in whitespace when finding context",4006 PARSE_OPT_NOARG, option_parse_space_change },4007{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,4008"ignore changes in whitespace when finding context",4009 PARSE_OPT_NOARG, option_parse_space_change },4010OPT_BOOLEAN('R',"reverse", &apply_in_reverse,4011"apply the patch in reverse"),4012OPT_BOOLEAN(0,"unidiff-zero", &unidiff_zero,4013"don't expect at least one line of context"),4014OPT_BOOLEAN(0,"reject", &apply_with_reject,4015"leave the rejected hunks in corresponding *.rej files"),4016OPT_BOOLEAN(0,"allow-overlap", &allow_overlap,4017"allow overlapping hunks"),4018OPT__VERBOSE(&apply_verbosely,"be verbose"),4019OPT_BIT(0,"inaccurate-eof", &options,4020"tolerate incorrectly detected missing new-line at the end of file",4021 INACCURATE_EOF),4022OPT_BIT(0,"recount", &options,4023"do not trust the line counts in the hunk headers",4024 RECOUNT),4025{ OPTION_CALLBACK,0,"directory", NULL,"root",4026"prepend <root> to all filenames",40270, option_parse_directory },4028OPT_END()4029};40304031 prefix = prefix_;4032 prefix_length = prefix ?strlen(prefix) :0;4033git_config(git_apply_config, NULL);4034if(apply_default_whitespace)4035parse_whitespace_option(apply_default_whitespace);4036if(apply_default_ignorewhitespace)4037parse_ignorewhitespace_option(apply_default_ignorewhitespace);40384039 argc =parse_options(argc, argv, prefix, builtin_apply_options,4040 apply_usage,0);40414042if(apply_with_reject)4043 apply = apply_verbosely =1;4044if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))4045 apply =0;4046if(check_index && is_not_gitdir)4047die(_("--index outside a repository"));4048if(cached) {4049if(is_not_gitdir)4050die(_("--cached outside a repository"));4051 check_index =1;4052}4053for(i =0; i < argc; i++) {4054const char*arg = argv[i];4055int fd;40564057if(!strcmp(arg,"-")) {4058 errs |=apply_patch(0,"<stdin>", options);4059 read_stdin =0;4060continue;4061}else if(0< prefix_length)4062 arg =prefix_filename(prefix, prefix_length, arg);40634064 fd =open(arg, O_RDONLY);4065if(fd <0)4066die_errno(_("can't open patch '%s'"), arg);4067 read_stdin =0;4068set_default_whitespace_mode(whitespace_option);4069 errs |=apply_patch(fd, arg, options);4070close(fd);4071}4072set_default_whitespace_mode(whitespace_option);4073if(read_stdin)4074 errs |=apply_patch(0,"<stdin>", options);4075if(whitespace_error) {4076if(squelch_whitespace_errors &&4077 squelch_whitespace_errors < whitespace_error) {4078int squelched =4079 whitespace_error - squelch_whitespace_errors;4080warning(Q_("squelched%dwhitespace error",4081"squelched%dwhitespace errors",4082 squelched),4083 squelched);4084}4085if(ws_error_action == die_on_ws_error)4086die(Q_("%dline adds whitespace errors.",4087"%dlines add whitespace errors.",4088 whitespace_error),4089 whitespace_error);4090if(applied_after_fixing_ws && apply)4091warning("%dline%sapplied after"4092" fixing whitespace errors.",4093 applied_after_fixing_ws,4094 applied_after_fixing_ws ==1?"":"s");4095else if(whitespace_error)4096warning(Q_("%dline adds whitespace errors.",4097"%dlines add whitespace errors.",4098 whitespace_error),4099 whitespace_error);4100}41014102if(update_index) {4103if(write_cache(newfd, active_cache, active_nr) ||4104commit_locked_index(&lock_file))4105die(_("Unable to write new index file"));4106}41074108return!!errs;4109}